Search Results

Search found 25779 results on 1032 pages for 'custom model binder'.

Page 8/1032 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • List of models in Model in MVC

    - by arri
    I have two models: class ModelIn{ public string FirstName { get; set; } public string LastName { get; set; } public string Address { get; set; } } class ModelOut{ public ModelOut(){ People = new List<ModelIn>();} public List<ModelIn> People { get; private set;} public string Country { get; set; } } And I have Controller editing ModelOut: public ActionResult People() { ... return View(SomeModelOutInstanceWith3People); } [HttpPost] public ActionResult(ModelOut m) { ... } In view I have sth like: <% using (Html.BeginForm()) { %> <%: Html.EditorFor(m => Model.Country) %> <% for(int i = 0; i < Model.People.Count; ++i){ %> <%: Html.EditorFor(m => Model.People[i].FirstName) %> <%: Html.EditorFor(m => Model.People[i].LastName) %> <%: Html.EditorFor(m => Model.People[i].Address) %> <% } %> <input type="submit" /> <% } %> It works all OK, but in post action I have empty ModelOut m. I can see in logs that data is sent correctly. I have tried everything, nothing works.

    Read the article

  • Django model help

    - by dotty
    Does anyone have any clue why this doesn't work as expected. If i use the python shell and do team.game_set or team.games It returns an error AttributeError: 'Team' object has no attribute 'game' If i create a Game object and call game.home_team it returns the correct team object Heres my model class Team(models.Model): name = models.CharField(blank=True, max_length=100) class Game(models.Model): home_team = models.ForeignKey(Team, related_name="home_team")

    Read the article

  • Implementing a Cakephp Model using an Array

    - by Zubin
    The CakePHP Cookbook states that a Model can use a file (csv for example) instead of an actual database table but I couldn't find any implementation for it. I was wondering if it is possible to use an Array of data as a model in CakePHP since I have a fairly static set of data which is important to me in a relationship with another table but it doesn't make a whole lot of sense to create a complete table for it. Is it possible to implement a CakePHP Model using an Array?

    Read the article

  • Codeigniter: Check where model is loaded from?

    - by qwerty
    I'm having the strangest thing ever right now. I "disabled" a model because i don't need to access it ever again. I did so by echoing out an error string in the __construct() and right after that die(). That way i would notice if i ever loaded the model, even by mistake, which should never happen. Alright? The problem is, the model is not loaded ANYWHERE in the entire project, but it still gets loaded for some reason. It's not auto loaded, that's for sure. Is it possible to track down where a model is loaded? Like which line it happens etc?

    Read the article

  • Error Handling in Model (MVC)

    - by Andre
    I was wondering what the excepted standard is for handling errors in the Model. Currently I have 'setError' and 'getError' methods that's in use by all my Models. This means I'm only concerned with whether a call to a method in my Model is true or false. If it's false then I would use $this-model-getError() in my Controller. Additionally I'm contemplating setting up a separate file that contains all my errors. One file per model, also wanted to have thoughts on this.

    Read the article

  • Formating a date field in the Model (Codeigniter)

    - by Landitus
    Hi, I', trying to re-format a date from a table in Codeigniter. The Controller is for a blog. I was succesfull when the date conversion happens in the View. I was hoping to convert the date in the Model to have things in order. This is the Model: class Novedades_model extends Model { function getAll() { $this->db->order_by('date','desc'); $query = $this->db->get('novedades'); if($query->num_rows() > 0) { foreach ($query->result() as $row) { $data[] = $row; } } return $data; } } This is part of the controller $this->load->model('novedades_model'); $data['records'] = $this->novedades_model->getAll(); Here's the date conversion as it happens in the View. This is inside the posts loop: <?php foreach($records as $row) : ?> <?php $fdate = "%d <abbr>%M</abbr> %Y"; $dateConv = mdate($fdate, mysql_to_unix($row->date)); ?> <div class="article section"> <span class="date"><?php echo $dateConv ;?></span> ... Keeps going ... How can I convert the date in the Model? Can I access the date key and refactor it?

    Read the article

  • What is the difference (if any) between Html.Partial(view, model) and Html.RenderPartial(view,model)

    - by Stephane
    Other than the type it returns and the fact that you call it differently of course <% Html.RenderPartial(...); %> <%= Html.Partial(...) %> If they are different, why would you call one rather than the other one? The definitions: // Type: System.Web.Mvc.Html.RenderPartialExtensions // Assembly: System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 // Assembly location: C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 2\Assemblies\System.Web.Mvc.dll using System.Web.Mvc; namespace System.Web.Mvc.Html { public static class RenderPartialExtensions { public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName); public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName, ViewDataDictionary viewData); public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName, object model); public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName, object model, ViewDataDictionary viewData); } } // Type: System.Web.Mvc.Html.PartialExtensions // Assembly: System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 // Assembly location: C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 2\Assemblies\System.Web.Mvc.dll using System.Web.Mvc; namespace System.Web.Mvc.Html { public static class PartialExtensions { public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName); public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName, ViewDataDictionary viewData); public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName, object model); public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName, object model, ViewDataDictionary viewData); } }

    Read the article

  • (Quaternion based) Trouble moving foward based on model rotation

    - by ChocoMan
    Using quaternions, I'm having trouble moving my model in its facing direction. Currently the model moves can move in all cardinal directions with no problems. The problem comes when I rotate the move as it still travelling in the direction of world space. Meaning, if I'm moving forward, backward or any other direction while rotating the model, the model acts like its a figure skater spinning while traveling in the same direction. How do I update the direction of travel proper with the facing direction of the model? Rotates model on Y-axis: Yaw = pController.ThumbSticks.Right.X * MathHelper.ToRadians(speedAngleMAX); AddRotation = Quaternion.CreateFromYawPitchRoll(yaw, 0, 0); ModelLoad.MRotation *= AddRotation; MOrientation = Matrix.CreateFromQuaternion(ModelLoad.MRotation); Moves model forward: // Move Forward if (pController.IsButtonDown(Buttons.LeftThumbstickUp)) { SpeedX = (float)(Math.Sin(ModelLoad.ModelRotation)) * FWDSpeedMax * pController.ThumbSticks.Left.Y * (float)gameTime.ElapsedGameTime.TotalSeconds; SpeedZ = (float)(Math.Cos(ModelLoad.ModelRotation)) * FWDSpeedMax * pController.ThumbSticks.Left.Y * (float)gameTime.ElapsedGameTime.TotalSeconds; // Update model position ModelLoad._modelPos += Vector3.Forward * SpeedZ; ModelLoad._modelPos += Vector3.Left * SpeedX; }

    Read the article

  • Model value not being set on return from View to Controller

    - by sagesky36
    I have a boolean model variable who's value is supposed to be set to TRUE in order to perform a process on return back into the Controller. It works absolutely fine on my local machine, but not on the remote web server. Can somebody PLEASE inform me what I am missing? Below is the "proof of the pudding": The boolean value in quesion is "ShouldGeneratePdf"; MODEL: namespace PDFConverterModel.ViewModels { public partial class ViewModelTemplate_Guarantors { public ViewModelTemplate_Guarantors() { Templates = new List<PDFTemplate>(); Guarantors = new List<tGuarantor>(); } public int SelectedTemplateId { get; set; } public List<PDFTemplate> Templates { get; set; } public int SelectedGuarantorId { get; set; } public List<tGuarantor> Guarantors { get; set; } public string LoanId { get; set; } public string DepartmentId { get; set; } public bool isRepeat { get; set; } public string ddlDept { get; set; } public string SelectedDeptText { get; set; } public string LoanTypeId { get; set; } public string LoanType { get; set; } public string Error { get; set; } public string ErrorT { get; set; } public string ErrorG { get; set; } public bool ShowGeneratePDFBtn { get; set; } public bool ShouldGeneratePdf { get; set; } } } MasterPage: <!DOCTYPE html> <html> <head> <title>@ViewBag.Title</title> <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" /> <link href="@Url.Content("~/Content/kendo/2012.2.913/kendo.common.min.css")" rel="stylesheet" type="text/css" /> <link href="@Url.Content("~/Content/kendo/2012.2.913/kendo.dataviz.min.css")" rel="stylesheet" type="text/css" /> <link href="@Url.Content("~/Content/kendo/2012.2.913/kendo.blueopal.min.css")" rel="stylesheet" type="text/css" /> <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/modernizr-2.5.3.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/kendo/2012.2.913/kendo.all.min.js")"></script> <script src="@Url.Content("~/Scripts/kendo/2012.2.913/kendo.aspnetmvc.min.js")"></script> </head> <body> <div class="page"> <header> <div id="title"> <h1>BHG :: PDF Service Generator</h1> </div> </header> <section id="main"> @RenderBody() </section> <footer> </footer> </div> </body> </html> View: @model PDFConverterModel.ViewModels.ViewModelTemplate_Guarantors @using (Html.BeginForm("ProcessForm", "Home", new AjaxOptions { HttpMethod = "POST" })) { <table style="width: 1000px"> @Html.HiddenFor(x => x.ShouldGeneratePdf) <tr> <td> <img alt="BHG Logo" src="~/Images/logo.gif" /> </td> </tr> <tr> <td> @(Html.Kendo().IntegerTextBox() .Placeholder("Enter Loan Id") .Name("LoanId") .Format("{0:#######}") .Value(Convert.ToInt32(Model.LoanId)) ) </td> </tr> <tr> <td>@Html.Label("Loan Type: ") @Html.DisplayFor(model => Model.LoanType) </td> <td> <label for="ddlDept">Department:</label> @(Html.Kendo().DropDownListFor(model => Model.ddlDept) .Name("ddlDept") .DataTextField("DepartmentName") .DataValueField("DepartmentID") .Events(e => e.Change("Refresh")) .DataSource(source => { source.Read(read => { read.Action("GetDepartments", "Home"); }); }) .Value(Model.ddlDept.ToString()) ) </td> </tr> @if (Model.ShowGeneratePDFBtn == true) { if (Model.ErrorT == string.Empty) { <tr> <td> <u><b>@Html.Label("Templates:")</b></u> </td> </tr> <tr> @for (int i = 0; i < Model.Templates.Count; i++) { <td> @Html.CheckBoxFor(model => Model.Templates[i].IsChecked) @Html.DisplayFor(model => Model.Templates[i].TemplateId) </td> } </tr> } else { <tr> <td> <b>@Html.DisplayFor(model => Model.ErrorT)</b> </td> </tr> } if (Model.ErrorG == string.Empty) { <tr> <td> <u><b>@Html.Label("Guarantors:")</b></u> </td> </tr> <tr> @for (int i = 0; i < Model.Guarantors.Count; i++) { <td> @Html.CheckBoxFor(model => Model.Guarantors[i].isChecked) @Html.DisplayFor(model => Model.Guarantors[i].GuarantorFirstName)&nbsp;@Html.DisplayFor(model => Model.Guarantors[i].GuarantorLastName) </td> } </tr> } else { <tr> <td> <b>@Html.DisplayFor(model => Model.ErrorG)</b> </td> </tr> } } <tr> <td> <input type="submit" name="submitbutton" id="btnRefresh" value='Refresh' /> </td> @if (Model.ShowGeneratePDFBtn == true) { <td> <input type="submit" name="submitbutton" id="btnGeneratePDF" value='Generate PDF' /> </td> } </tr> <tr> <td style="color: red; font: bold"> @Model.Error </td> </tr> </table> } <script type="text/javascript"> $('#btnRefresh').click(function () { Refresh(); }); function Refresh() { var LoanID = $("#LoanID").val(); if (parseInt(LoanID) != 0) { $('#ShouldGeneratePdf').val(false) document.forms[0].submit(); } else { alert("Please enter a LoanId"); } } //$(function () { // //DOM loaded // $('#btnGeneratePDF').click(function () { // DisableGeneratePDF(); // $('#ShouldGeneratePdf').val(true) // }); //}); //function DisableGeneratePDF() { // $('#btnGeneratePDF').attr("disabled", true); // $('#btnRefresh').attr("disabled", true); //} $('#btnGeneratePDF').click(function () { alert("inside click function"); DisableGeneratePDF(); $('#ShouldGeneratePdf').val(true) tof = $('#ShouldGeneratePdf').val(); alert("ShouldGeneratePdf set to " + tof); }); function DisableGeneratePDF() { alert("begin DisableGeneratePDF function"); $('#btnGeneratePDF').attr("disabled", true); $('#btnRefresh').attr("disabled", true); alert("end DisableGeneratePDF function"); } </script> Controller: [HttpPost] public ActionResult ProcessForm(string submitbutton, ViewModelTemplate_Guarantors model, FormCollection collection) if ((submitbutton == "Refresh") || (submitbutton == null) && (model.ShouldGeneratePdf == false)) { } else if ((submitbutton == "Generate PDF") || (model.ShouldGeneratePdf == true)) { } The "Alerts" in the script above come out to exactly what they should be on the remote server. The last alert shows that the value of the bool variable is "true". However, when I do page source views of the hidden variable, below is the result. The values of the hidden variable when the page loads and when the last alert button finishes are as follows: My local machine: The remote machine: As you can see, the value on my machine is set to true when the process executes. However, on the remote machine, it is set to false where it then doesn't excute. Why isn't the value in the model being returned as TRUE on the remote machine?

    Read the article

  • How to deal with data on the model specific to the technology being used?

    - by user1620696
    There are some cases where some of the data on a class of the domain model of an application seems to be dependent on the technology being used. One example of this is the following: suppose we are building one application in .NET such that there's the need of an Employee class. Suppose further that we are going to implement relational database, then the Employee has a primary key right? So that the classe would be something like public class Employee { public int EmployeeID { get; set; } public string Name { get; set; } ... } Now, that EmployeeID is dependent on the technology right? That's something that has to do with the way we've choose to persist our data. Should we write down a class independent of such things? If we do it this way, how should we work? I think I would need to map all the time between domain model and persistence specific types, but I'm not sure.

    Read the article

  • Developing a Cost Model for Cloud Applications

    - by BuckWoody
    Note - please pay attention to the date of this post. As much as I attempt to make the information below accurate, the nature of distributed computing means that components, units and pricing will change over time. The definitive costs for Microsoft Windows Azure and SQL Azure are located here, and are more accurate than anything you will see in this post: http://www.microsoft.com/windowsazure/offers/  When writing software that is run on a Platform-as-a-Service (PaaS) offering like Windows Azure / SQL Azure, one of the questions you must answer is how much the system will cost. I will not discuss the comparisons between on-premise costs (which are nigh impossible to calculate accurately) versus cloud costs, but instead focus on creating a general model for estimating costs for a given application. You should be aware that there are (at this writing) two billing mechanisms for Windows and SQL Azure: “Pay-as-you-go” or consumption, and “Subscription” or commitment. Conceptually, you can consider the former a pay-as-you-go cell phone plan, where you pay by the unit used (at a slightly higher rate) and the latter as a standard cell phone plan where you commit to a contract and thus pay lower rates. In this post I’ll stick with the pay-as-you-go mechanism for simplicity, which should be the maximum cost you would pay. From there you may be able to get a lower cost if you use the other mechanism. In any case, the model you create should hold. Developing a good cost model is essential. As a developer or architect, you’ll most certainly be asked how much something will cost, and you need to have a reliable way to estimate that. Businesses and Organizations have been used to paying for servers, software licenses, and other infrastructure as an up-front cost, and power, people to the systems and so on as an ongoing (and sometimes not factored) cost. When presented with a new paradigm like distributed computing, they may not understand the true cost/value proposition, and that’s where the architect and developer can guide the conversation to make a choice based on features of the application versus the true costs. The two big buckets of use-types for these applications are customer-based and steady-state. In the customer-based use type, each successful use of the program results in a sale or income for your organization. Perhaps you’ve written an application that provides the spot-price of foo, and your customer pays for the use of that application. In that case, once you’ve estimated your cost for a successful traversal of the application, you can build that into the price you charge the user. It’s a standard restaurant model, where the price of the meal is determined by the cost of making it, plus any profit you can make. In the second use-type, the application will be used by a more-or-less constant number of processes or users and no direct revenue is attached to the system. A typical example is a customer-tracking system used by the employees within your company. In this case, the cost model is often created “in reverse” - meaning that you pilot the application, monitor the use (and costs) and that cost is held steady. This is where the comparison with an on-premise system becomes necessary, even though it is more difficult to estimate those on-premise true costs. For instance, do you know exactly how much cost the air conditioning is because you have a team of system administrators? This may sound trivial, but that, along with the insurance for the building, the wiring, and every other part of the system is in fact a cost to the business. There are three primary methods that I’ve been successful with in estimating the cost. None are perfect, all are demand-driven. The general process is to lay out a matrix of: components units cost per unit and then multiply that times the usage of the system, based on which components you use in the program. That sounds a bit simplistic, but using those metrics in a calculation becomes more detailed. In all of the methods that follow, you need to know your application. The components for a PaaS include computing instances, storage, transactions, bandwidth and in the case of SQL Azure, database size. In most cases, architects start with the first model and progress through the other methods to gain accuracy. Simple Estimation The simplest way to calculate costs is to architect the application (even UML or on-paper, no coding involved) and then estimate which of the components you’ll use, and how much of each will be used. Microsoft provides two tools to do this - one is a simple slider-application located here: http://www.microsoft.com/windowsazure/pricing-calculator/  The other is a tool you download to create an “Return on Investment” (ROI) spreadsheet, which has the advantage of leading you through various questions to estimate what you plan to use, located here: https://roianalyst.alinean.com/msft/AutoLogin.do?d=176318219048082115  You can also just create a spreadsheet yourself with a structure like this: Program Element Azure Component Unit of Measure Cost Per Unit Estimated Use of Component Total Cost Per Component Cumulative Cost               Of course, the consideration with this model is that it is difficult to predict a system that is not running or hasn’t even been developed. Which brings us to the next model type. Measure and Project A more accurate model is to actually write the code for the application, using the Software Development Kit (SDK) which can run entirely disconnected from Azure. The code should be instrumented to estimate the use of the application components, logging to a local file on the development system. A series of unit and integration tests should be run, which will create load on the test system. You can use standard development concepts to track this usage, and even use Windows Performance Monitor counters. The best place to start with this method is to use the Windows Azure Diagnostics subsystem in your code, which you can read more about here: http://blogs.msdn.com/b/sumitm/archive/2009/11/18/introducing-windows-azure-diagnostics.aspx This set of API’s greatly simplifies tracking the application, and in fact you can use this information for more than just a cost model. After you have the tracking logs, you can plug the numbers into ay of the tools above, which should give a representative cost or in some cases a unit cost. The consideration with this model is that the SDK fabric is not a one-to-one comparison with performance on the actual Windows Azure fabric. Those differences are usually smaller, but they do need to be considered. Also, you may not be able to accurately predict the load on the system, which might lead to an architectural change, which changes the model. This leads us to the next, most accurate method for a cost model. Sample and Estimate Using standard statistical and other predictive math, once the application is deployed you will get a bill each month from Microsoft for your Azure usage. The bill is quite detailed, and you can export the data from it to do analysis, and using methods like regression and so on project out into the future what the costs will be. I normally advise that the architect also extrapolate a unit cost from those metrics as well. This is the information that should be reported back to the executives that pay the bills: the past cost, future projected costs, and unit cost “per click” or “per transaction”, as your case warrants. The challenge here is in the model itself - statistical methods are not foolproof, and the larger the sample (in this case I recommend the entire population, not a smaller sample) is key. References and Tools Articles: http://blogs.msdn.com/b/patrick_butler_monterde/archive/2010/02/10/windows-azure-billing-overview.aspx http://technet.microsoft.com/en-us/magazine/gg213848.aspx http://blog.codingoutloud.com/2011/06/05/azure-faq-how-much-will-it-cost-me-to-run-my-application-on-windows-azure/ http://blogs.msdn.com/b/johnalioto/archive/2010/08/25/10054193.aspx http://geekswithblogs.net/iupdateable/archive/2010/02/08/qampa-how-can-i-calculate-the-tco-and-roi-when.aspx   Other Tools: http://cloud-assessment.com/ http://communities.quest.com/community/cloud_tools

    Read the article

  • Ruby on rails model and controllers inside of different namespaces

    - by Nelson LaQuet
    OK. This is insane. I'm new to RoR and I really want to get into it as everything about it that I have seen so far makes it more appealing to the type of work that I do. However, I can't seem to accomplish a very simple thing with RoR. I want these controlers: /admin/blog/entries (index/show/edit/delete) /admin/blog/categories (index/show/edit/delete) /admin/blog/comments (index/show/edit/delete) ... and so on And these models: Blog::Entry (table: blog_entries) Blog::Category (table: blog_categories) Blog::Comments (table: blog_comments) ... and so on Now, I have already gone though quite a bit of misery to make this work. My first attempt was with generating scaffolding (I'm using 2.2.2). I generated my scaffolding, but had to move my model, then fix the references to the model in my controller (see http://stackoverflow.com/questions/903258/ruby-on-rails-model-inside-namespace-cant-be-found-in-controller). That is already a big of a pain, but hey, I got it to work. Now though form_for won't work and I cannot figure out how to use the url helpers (I have no idea what these are called... they are the automatically generated methods that return URLs to controllers associated with a model). I cannot figure out what their name is. My model is Blog::Entries. I have tried to mess with the route.rb's map's resource method, but no luck. When I attempt to use form_for with my model, I get this error undefined method `blog_entries_path' for #<ActionView::Base:0xb6848080> Now. This is really quite frustrating. I am not going to completely destroy my code's organization in order to use this framework, and if I cannot figure out how to accomplish this simple task (I have been researching this for at least 5 hours) then I simply cannot continue. Are there any ideas on how to accomplish this? Thanks EDIT Here are my routes: admin_blog_entries GET /admin_blog_entries {:controller=>"admin_blog_entries", :action=>"index"} formatted_admin_blog_entries GET /admin_blog_entries.:format {:controller=>"admin_blog_entries", :action=>"index"} POST /admin_blog_entries {:controller=>"admin_blog_entries", :action=>"create"} POST /admin_blog_entries.:format {:controller=>"admin_blog_entries", :action=>"create"} new_admin_blog_entry GET /admin_blog_entries/new {:controller=>"admin_blog_entries", :action=>"new"} formatted_new_admin_blog_entry GET /admin_blog_entries/new.:format {:controller=>"admin_blog_entries", :action=>"new"} edit_admin_blog_entry GET /admin_blog_entries/:id/edit {:controller=>"admin_blog_entries", :action=>"edit"} formatted_edit_admin_blog_entry GET /admin_blog_entries/:id/edit.:format {:controller=>"admin_blog_entries", :action=>"edit"} admin_blog_entry GET /admin_blog_entries/:id {:controller=>"admin_blog_entries", :action=>"show"} formatted_admin_blog_entry GET /admin_blog_entries/:id.:format {:controller=>"admin_blog_entries", :action=>"show"} PUT /admin_blog_entries/:id {:controller=>"admin_blog_entries", :action=>"update"} PUT /admin_blog_entries/:id.:format {:controller=>"admin_blog_entries", :action=>"update"} DELETE /admin_blog_entries/:id {:controller=>"admin_blog_entries", :action=>"destroy"} DELE

    Read the article

  • Custom PCI bracket with support, for custom PCB?

    - by newbiez
    I am considering to put a custom PCB card that I made, into my computer. It won't go on any PCI connector, it plugs in on a USB connector on the motherboard, via a ribbon cable. I need thou to plug a device to it; which means that either I leave the PCB outside the case, hanging by the ribbon (bad idea), or I could put it in a PCI slot, using a bracket. The issue is that the brackets that I have, do not have tabs, so I have no way to screw the PCB on them. I was hoping to find something that would allow me to put the PCB on it, and then just fit it in the PCI bracket opening, like this: http://www.idotpc.com/TheStore/pc/viewPrd.asp?idproduct=1203&idcategory=0 This one won't fit the bill since the holes are too close apart, compared to the one that I have already on the PCB (and can't make more holes). Do you know if there is a place where they make universal PCI bracket mounting systems for custom PCB? I just need one, so can't even order a custom one (they ask me 120 dollars for one). Thanks in advance!

    Read the article

  • GWT, MVP, and UIBinding - How to get the best of all worlds

    - by Stephane Grenier
    With MVP, you normally bind the View (UI) with the Presenter in the Presenter. However with the latest version of GWT, especially with UIBinding, you can do the following in the View: @UiHandler("loginButton") void onAboutClicked(ClickEvent event) { // my login code } Which basically exchanges a lot of anonymous inner class code for some quick annotation code. Very nice!! The problem is that this code is in the view and not the presenter... So I thought maybe: @UiHandler("loginButton") void onAboutClicked(ClickEvent event) { myPresenter.onAboutClicked(...); } But there are several problems with this approach. The most important, you blur the lines between View and Presenter. Who does which binding, in some cases it's the View, in others it's the presenter (binding to events not in your current view but that need to be attached - for example a system wide update event). You still get the benefit of being able to unit test your presenter, but at what cost. The responsibilities are messy now. For example the binding is sometimes in the View and others times in the Presenter level. I can see the code falling into all kinds of chaos with time. I also thought of extending the Presenter to the View, so that you could do this in the View. The problem here is that you lose the Presenter's ability to run standard unit tests! That's a major issue. That and the lines again become blurred. So my question, does anyone have a good method of taking advantage of the annotation from UIBinding within the MVP pattern without blurring the lines and losing the advantages of the MVP pattern?

    Read the article

  • What's faster Model.get(keys) or Model.get_by_id(ids, parent=None)

    - by WooYek
    I'm wondering is there a difference in terms of computing cost for the Model.get(keys) and Model.get_by_id(ids, parent=None) methods? Is there a server side computing advantage of using numeric id's over encoded string keys, or other way around? How big is the difference? PS. Sorry, if it's a dupe. I'm sure I read an article about it, but I cannot find it now.

    Read the article

  • Why is the W3C box model considered better?

    - by Mel
    Why do most developers consider the W3C box-model to be better than the box-model used by Internet Explorer? I know it's very frustrating developing pages that look the way you want them on Internet Explorer, but I find the W3C box-model to be counter-intuitive. For example, if margins, padding, and border were factored into the width, I could assign fixed width values for all my columns without having to worry about how many columns I have and what changes I make to my padding and margins. Under W3C box model I have to worry about how many columns I have, and develop something akin to a mathematical formula to calculate my values. Changing them would nightmarish, especially for complex layouts. My novice opinion is that it's more restrictive. Consider this small frame-work I wrote: #content { margin:0 auto 30px auto; padding:0 30px 30px 30px; width:900px; } #content .column { float:left; margin:0 20px 20px 20px; } #content .first { margin-left:0; } #content .last { margin-right:0; } .width_1-4 { width:195px; } .width_1-3 { width:273px; } .width_1-2 { width:430px; } .width_3-4 { width:645px; } .width_1-1 { width:900px; } These values I have assigned here will falter unless there are three columns, and thus the margins at 0(first)+20+20+20+20+0(last). It would be a disaster if I wanted to add padding to my columns too, as my entire setup would have to be re calibrated. Now imagine if column width incorporated all the other elements, all I would need to do is change one associated value, and I have my layout. I'm less criticizing it and more hoping to understand why it's better, or why I'm finding it more difficult. Am I doing this whole thing wrong? I don't know very much about this topic, but it seems counter intuitive to use W3C's box-model. Some advice would be really appreciated. Thanks

    Read the article

  • Instantiate a model when the kind of model needed is represented as a string argument

    - by indiehacker
    My input data is a string representing the kind of datastore model I want to make. In python, I am using the eval() function to instantiate the model (below code), but this seems overly complex so I was wondering if there is a simpler way people normally do this? >>>model_kind="TextPixels" >>>key_name_eval="key_name" >>>key_name="key_name" >>>kwargs {'lat': [0, 1, 2, 3], 'stringText': 'boris,ted', 'lon': [0, 1, 2, 8], 'zooms': [0, 10]} >>>obj=eval( model_type + '(key_name='+tester+ ',**kwargs )' ) >>>obj <datamodel.TextPixels object at 0xed8808c>

    Read the article

  • Edit the Windows Live Writer Custom Dictionary

    - by Matthew Guay
    Windows Live Writer is a great tool for writing and publishing posts to your blog, but its spell check unfortunately doesn’t include many common tech words.  Here’s how you can easily edit your custom dictionary and add your favorite words. Customize Live Writer’s Dictionary Adding an individual word to the Windows Live Writer dictionary works as you would expect.  Right-click on a word and select Add to dictionary. And changing the default spell check settings is easy too.  In the menu, click Tools, then Options, and select the Spelling tab in this dialog.  Here you can choose your dictionary language and turn on/off real-time spell checking and other settings. But there’s no obvious way to edit your custom dictionary.  Editing the custom dictionary directly is nice if you accidently add a misspelled word to your dictionary and want to remove it, or if you want to add a lot of words to the dictionary at once. Live Writer actually stores your custom dictionary entries in a plain text file located in your appdata folder.  It is saved as User.dic in the C:\Users\user_name\AppData\Roaming\Windows Live Writer\Dictionaries folder.  The easiest way to open the custom dictionary is to enter the following in the Run box or the address bar of an Explorer window: %appdata%\Windows Live Writer\Dictionaries\User.dic   This will open the User.dic file in your default text editor.  Add any new words to the custom dictionary on separate lines, and delete any misspelled words you accidently added to the dictionary.   Microsoft Office Word also stores its custom dictionary in a plain text file.  If you already have lots of custom words in it and want to import them into Live Writer, enter the following in the Run command or Explorer’s address bar to open Word’s custom dictionary.  Then copy the words, and past them into your Live Writer custom dictionary file. %AppData%\Microsoft\UProof\Custom.dic Don’t forget to save the changes when you’re done.  Note that the changes to the dictionary may not show up in Live Writer’s spell check until you restart the program.  If it’s currently running, save any posts you’re working on, exit, and then reopen, and all of your new words should be in the dictionary. Conclusion Whether you use Live Writer daily in your job or occasionally post an update to a personal blog, adding your own custom words to the dictionary can save you a lot of time and frustration in editing.  Plus, if you’ve accidently added a misspelled word to the dictionary, this is a great way to undo your mistake and make sure your spelling is up to par! Similar Articles Productive Geek Tips Backup Your Windows Live Writer SettingsTransfer or Move Your Microsoft Office Custom DictionaryFuture Date a Post in Windows Live WriterTools to Help Post Content On Your WordPress BlogInstall Windows Live Essentials In Windows 7 TouchFreeze Alternative in AutoHotkey The Icy Undertow Desktop Windows Home Server – Backup to LAN The Clear & Clean Desktop Use This Bookmarklet to Easily Get Albums Use AutoHotkey to Assign a Hotkey to a Specific Window Latest Software Reviews Tinyhacker Random Tips Acronis Online Backup DVDFab 6 Revo Uninstaller Pro Registry Mechanic 9 for Windows Video Toolbox is a Superb Online Video Editor Fun with 47 charts and graphs Tomorrow is Mother’s Day Check the Average Speed of YouTube Videos You’ve Watched OutlookStatView Scans and Displays General Usage Statistics How to Add Exceptions to the Windows Firewall

    Read the article

  • Accessing global variables of custom controls in ASP.NET

    - by CL4NCY
    Hi, I have built lots of custom asp.net controls which work really well separately but I want to somehow allow global access to all their variables from anywhere on the page. I have a central control called the ContentManager which I can use to store these variables. The problem I have is that all the controls are bound at different times so I only want the variables available after they're bound. For example I have many custom repeaters on the page which when bound I want to add a reference in the content manager so all their variables are then available to use. <Custom:ContentManager ID="cm" runat="server"/> <Custom:Repeater ID="r1" runat="server"/> <Custom:Repeater ID="r2" runat="server"/> <Custom:Repeater ID="r3" runat="server"/> Then I want a tag which can access all variables from any of these controls. <%= cm.controls["r1"].Items[0]["name"] %> The problem with this is that the variable isn't available until the repeater is bound so I might need to use events to push out the value to tags on the page like so: <Custom:Var ID="v1" control="r1" value="Items[0]["name"]" runat="server"/> Is this possible or can you recommend a better approach?

    Read the article

  • Custom ASP.NET Routing to an HttpHandler

    - by Rick Strahl
    As of version 4.0 ASP.NET natively supports routing via the now built-in System.Web.Routing namespace. Routing features are automatically integrated into the HtttpRuntime via a few custom interfaces. New Web Forms Routing Support In ASP.NET 4.0 there are a host of improvements including routing support baked into Web Forms via a RouteData property available on the Page class and RouteCollection.MapPageRoute() route handler that makes it easy to route to Web forms. To map ASP.NET Page routes is as simple as setting up the routes with MapPageRoute:protected void Application_Start(object sender, EventArgs e) { RegisterRoutes(RouteTable.Routes); } void RegisterRoutes(RouteCollection routes) { routes.MapPageRoute("StockQuote", "StockQuote/{symbol}", "StockQuote.aspx"); routes.MapPageRoute("StockQuotes", "StockQuotes/{symbolList}", "StockQuotes.aspx"); } and then accessing the route data in the page you can then use the new Page class RouteData property to retrieve the dynamic route data information:public partial class StockQuote1 : System.Web.UI.Page { protected StockQuote Quote = null; protected void Page_Load(object sender, EventArgs e) { string symbol = RouteData.Values["symbol"] as string; StockServer server = new StockServer(); Quote = server.GetStockQuote(symbol); // display stock data in Page View } } Simple, quick and doesn’t require much explanation. If you’re using WebForms most of your routing needs should be served just fine by this simple mechanism. Kudos to the ASP.NET team for putting this in the box and making it easy! How Routing Works To handle Routing in ASP.NET involves these steps: Registering Routes Creating a custom RouteHandler to retrieve an HttpHandler Attaching RouteData to your HttpHandler Picking up Route Information in your Request code Registering routes makes ASP.NET aware of the Routes you want to handle via the static RouteTable.Routes collection. You basically add routes to this collection to let ASP.NET know which URL patterns it should watch for. You typically hook up routes off a RegisterRoutes method that fires in Application_Start as I did in the example above to ensure routes are added only once when the application first starts up. When you create a route, you pass in a RouteHandler instance which ASP.NET caches and reuses as routes are matched. Once registered ASP.NET monitors the routes and if a match is found just prior to the HttpHandler instantiation, ASP.NET uses the RouteHandler registered for the route and calls GetHandler() on it to retrieve an HttpHandler instance. The RouteHandler.GetHandler() method is responsible for creating an instance of an HttpHandler that is to handle the request and – if necessary – to assign any additional custom data to the handler. At minimum you probably want to pass the RouteData to the handler so the handler can identify the request based on the route data available. To do this you typically add  a RouteData property to your handler and then assign the property from the RouteHandlers request context. This is essentially how Page.RouteData comes into being and this approach should work well for any custom handler implementation that requires RouteData. It’s a shame that ASP.NET doesn’t have a top level intrinsic object that’s accessible off the HttpContext object to provide route data more generically, but since RouteData is directly tied to HttpHandlers and not all handlers support it it might cause some confusion of when it’s actually available. Bottom line is that if you want to hold on to RouteData you have to assign it to a custom property of the handler or else pass it to the handler via Context.Items[] object that can be retrieved on an as needed basis. It’s important to understand that routing is hooked up via RouteHandlers that are responsible for loading HttpHandler instances. RouteHandlers are invoked for every request that matches a route and through this RouteHandler instance the Handler gains access to the current RouteData. Because of this logic it’s important to understand that Routing is really tied to HttpHandlers and not available prior to handler instantiation, which is pretty late in the HttpRuntime’s request pipeline. IOW, Routing works with Handlers but not with earlier in the pipeline within Modules. Specifically ASP.NET calls RouteHandler.GetHandler() from the PostResolveRequestCache HttpRuntime pipeline event. Here’s the call stack at the beginning of the GetHandler() call: which fires just before handler resolution. Non-Page Routing – You need to build custom RouteHandlers If you need to route to a custom Http Handler or other non-Page (and non-MVC) endpoint in the HttpRuntime, there is no generic mapping support available. You need to create a custom RouteHandler that can manage creating an instance of an HttpHandler that is fired in response to a routed request. Depending on what you are doing this process can be simple or fairly involved as your code is responsible based on the route data provided which handler to instantiate, and more importantly how to pass the route data on to the Handler. Luckily creating a RouteHandler is easy by implementing the IRouteHandler interface which has only a single GetHttpHandler(RequestContext context) method. In this method you can pick up the requestContext.RouteData, instantiate the HttpHandler of choice, and assign the RouteData to it. Then pass back the handler and you’re done.Here’s a simple example of GetHttpHandler() method that dynamically creates a handler based on a passed in Handler type./// <summary> /// Retrieves an Http Handler based on the type specified in the constructor /// </summary> /// <param name="requestContext"></param> /// <returns></returns> IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext) { IHttpHandler handler = Activator.CreateInstance(CallbackHandlerType) as IHttpHandler; // If we're dealing with a Callback Handler // pass the RouteData for this route to the Handler if (handler is CallbackHandler) ((CallbackHandler)handler).RouteData = requestContext.RouteData; return handler; } Note that this code checks for a specific type of handler and if it matches assigns the RouteData to this handler. This is optional but quite a common scenario if you want to work with RouteData. If the handler you need to instantiate isn’t under your control but you still need to pass RouteData to Handler code, an alternative is to pass the RouteData via the HttpContext.Items collection:IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext) { IHttpHandler handler = Activator.CreateInstance(CallbackHandlerType) as IHttpHandler; requestContext.HttpContext.Items["RouteData"] = requestContext.RouteData; return handler; } The code in the handler implementation can then pick up the RouteData from the context collection as needed:RouteData routeData = HttpContext.Current.Items["RouteData"] as RouteData This isn’t as clean as having an explicit RouteData property, but it does have the advantage that the route data is visible anywhere in the Handler’s code chain. It’s definitely preferable to create a custom property on your handler, but the Context work-around works in a pinch when you don’t’ own the handler code and have dynamic code executing as part of the handler execution. An Example of a Custom RouteHandler: Attribute Based Route Implementation In this post I’m going to discuss a custom routine implementation I built for my CallbackHandler class in the West Wind Web & Ajax Toolkit. CallbackHandler can be very easily used for creating AJAX, REST and POX requests following RPC style method mapping. You can pass parameters via URL query string, POST data or raw data structures, and you can retrieve results as JSON, XML or raw string/binary data. It’s a quick and easy way to build service interfaces with no fuss. As a quick review here’s how CallbackHandler works: You create an Http Handler that derives from CallbackHandler You implement methods that have a [CallbackMethod] Attribute and that’s it. Here’s an example of an CallbackHandler implementation in an ashx.cs based handler:// RestService.ashx.cs public class RestService : CallbackHandler { [CallbackMethod] public StockQuote GetStockQuote(string symbol) { StockServer server = new StockServer(); return server.GetStockQuote(symbol); } [CallbackMethod] public StockQuote[] GetStockQuotes(string symbolList) { StockServer server = new StockServer(); string[] symbols = symbolList.Split(new char[2] { ',',';' },StringSplitOptions.RemoveEmptyEntries); return server.GetStockQuotes(symbols); } } CallbackHandler makes it super easy to create a method on the server, pass data to it via POST, QueryString or raw JSON/XML data, and then retrieve the results easily back in various formats. This works wonderful and I’ve used these tools in many projects for myself and with clients. But one thing missing has been the ability to create clean URLs. Typical URLs looked like this: http://www.west-wind.com/WestwindWebToolkit/samples/Rest/StockService.ashx?Method=GetStockQuote&symbol=msfthttp://www.west-wind.com/WestwindWebToolkit/samples/Rest/StockService.ashx?Method=GetStockQuotes&symbolList=msft,intc,gld,slw,mwe&format=xml which works and is clear enough, but also clearly very ugly. It would be much nicer if URLs could look like this: http://www.west-wind.com//WestwindWebtoolkit/Samples/StockQuote/msfthttp://www.west-wind.com/WestwindWebtoolkit/Samples/StockQuotes/msft,intc,gld,slw?format=xml (the Virtual Root in this sample is WestWindWebToolkit/Samples and StockQuote/{symbol} is the route)(If you use FireFox try using the JSONView plug-in make it easier to view JSON content) So, taking a clue from the WCF REST tools that use RouteUrls I set out to create a way to specify RouteUrls for each of the endpoints. The change made basically allows changing the above to: [CallbackMethod(RouteUrl="RestService/StockQuote/{symbol}")] public StockQuote GetStockQuote(string symbol) { StockServer server = new StockServer(); return server.GetStockQuote(symbol); } [CallbackMethod(RouteUrl = "RestService/StockQuotes/{symbolList}")] public StockQuote[] GetStockQuotes(string symbolList) { StockServer server = new StockServer(); string[] symbols = symbolList.Split(new char[2] { ',',';' },StringSplitOptions.RemoveEmptyEntries); return server.GetStockQuotes(symbols); } where a RouteUrl is specified as part of the Callback attribute. And with the changes made with RouteUrls I can now get URLs like the second set shown earlier. So how does that work? Let’s find out… How to Create Custom Routes As mentioned earlier Routing is made up of several steps: Creating a custom RouteHandler to create HttpHandler instances Mapping the actual Routes to the RouteHandler Retrieving the RouteData and actually doing something useful with it in the HttpHandler In the CallbackHandler routing example above this works out to something like this: Create a custom RouteHandler that includes a property to track the method to call Set up the routes using Reflection against the class Looking for any RouteUrls in the CallbackMethod attribute Add a RouteData property to the CallbackHandler so we can access the RouteData in the code of the handler Creating a Custom Route Handler To make the above work I created a custom RouteHandler class that includes the actual IRouteHandler implementation as well as a generic and static method to automatically register all routes marked with the [CallbackMethod(RouteUrl="…")] attribute. Here’s the code:/// <summary> /// Route handler that can create instances of CallbackHandler derived /// callback classes. The route handler tracks the method name and /// creates an instance of the service in a predictable manner /// </summary> /// <typeparam name="TCallbackHandler">CallbackHandler type</typeparam> public class CallbackHandlerRouteHandler : IRouteHandler { /// <summary> /// Method name that is to be called on this route. /// Set by the automatically generated RegisterRoutes /// invokation. /// </summary> public string MethodName { get; set; } /// <summary> /// The type of the handler we're going to instantiate. /// Needed so we can semi-generically instantiate the /// handler and call the method on it. /// </summary> public Type CallbackHandlerType { get; set; } /// <summary> /// Constructor to pass in the two required components we /// need to create an instance of our handler. /// </summary> /// <param name="methodName"></param> /// <param name="callbackHandlerType"></param> public CallbackHandlerRouteHandler(string methodName, Type callbackHandlerType) { MethodName = methodName; CallbackHandlerType = callbackHandlerType; } /// <summary> /// Retrieves an Http Handler based on the type specified in the constructor /// </summary> /// <param name="requestContext"></param> /// <returns></returns> IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext) { IHttpHandler handler = Activator.CreateInstance(CallbackHandlerType) as IHttpHandler; // If we're dealing with a Callback Handler // pass the RouteData for this route to the Handler if (handler is CallbackHandler) ((CallbackHandler)handler).RouteData = requestContext.RouteData; return handler; } /// <summary> /// Generic method to register all routes from a CallbackHandler /// that have RouteUrls defined on the [CallbackMethod] attribute /// </summary> /// <typeparam name="TCallbackHandler">CallbackHandler Type</typeparam> /// <param name="routes"></param> public static void RegisterRoutes<TCallbackHandler>(RouteCollection routes) { // find all methods var methods = typeof(TCallbackHandler).GetMethods(BindingFlags.Instance | BindingFlags.Public); foreach (var method in methods) { var attrs = method.GetCustomAttributes(typeof(CallbackMethodAttribute), false); if (attrs.Length < 1) continue; CallbackMethodAttribute attr = attrs[0] as CallbackMethodAttribute; if (string.IsNullOrEmpty(attr.RouteUrl)) continue; // Add the route routes.Add(method.Name, new Route(attr.RouteUrl, new CallbackHandlerRouteHandler(method.Name, typeof(TCallbackHandler)))); } } } The RouteHandler implements IRouteHandler, and its responsibility via the GetHandler method is to create an HttpHandler based on the route data. When ASP.NET calls GetHandler it passes a requestContext parameter which includes a requestContext.RouteData property. This parameter holds the current request’s route data as well as an instance of the current RouteHandler. If you look at GetHttpHandler() you can see that the code creates an instance of the handler we are interested in and then sets the RouteData property on the handler. This is how you can pass the current request’s RouteData to the handler. The RouteData object also has a  RouteData.RouteHandler property that is also available to the Handler later, which is useful in order to get additional information about the current route. In our case here the RouteHandler includes a MethodName property that identifies the method to execute in the handler since that value no longer comes from the URL so we need to figure out the method name some other way. The method name is mapped explicitly when the RouteHandler is created and here the static method that auto-registers all CallbackMethods with RouteUrls sets the method name when it creates the routes while reflecting over the methods (more on this in a minute). The important point here is that you can attach additional properties to the RouteHandler and you can then later access the RouteHandler and its properties later in the Handler to pick up these custom values. This is a crucial feature in that the RouteHandler serves in passing additional context to the handler so it knows what actions to perform. The automatic route registration is handled by the static RegisterRoutes<TCallbackHandler> method. This method is generic and totally reusable for any CallbackHandler type handler. To register a CallbackHandler and any RouteUrls it has defined you simple use code like this in Application_Start (or other application startup code):protected void Application_Start(object sender, EventArgs e) { // Register Routes for RestService CallbackHandlerRouteHandler.RegisterRoutes<RestService>(RouteTable.Routes); } If you have multiple CallbackHandler style services you can make multiple calls to RegisterRoutes for each of the service types. RegisterRoutes internally uses reflection to run through all the methods of the Handler, looking for CallbackMethod attributes and whether a RouteUrl is specified. If it is a new instance of a CallbackHandlerRouteHandler is created and the name of the method and the type are set. routes.Add(method.Name,           new Route(attr.RouteUrl, new CallbackHandlerRouteHandler(method.Name, typeof(TCallbackHandler) )) ); While the routing with CallbackHandlerRouteHandler is set up automatically for all methods that use the RouteUrl attribute, you can also use code to hook up those routes manually and skip using the attribute. The code for this is straightforward and just requires that you manually map each individual route to each method you want a routed: protected void Application_Start(objectsender, EventArgs e){    RegisterRoutes(RouteTable.Routes);}void RegisterRoutes(RouteCollection routes) { routes.Add("StockQuote Route",new Route("StockQuote/{symbol}",                     new CallbackHandlerRouteHandler("GetStockQuote",typeof(RestService) ) ) );     routes.Add("StockQuotes Route",new Route("StockQuotes/{symbolList}",                     new CallbackHandlerRouteHandler("GetStockQuotes",typeof(RestService) ) ) );}I think it’s clearly easier to have CallbackHandlerRouteHandler.RegisterRoutes() do this automatically for you based on RouteUrl attributes, but some people have a real aversion to attaching logic via attributes. Just realize that the option to manually create your routes is available as well. Using the RouteData in the Handler A RouteHandler’s responsibility is to create an HttpHandler and as mentioned earlier, natively IHttpHandler doesn’t have any support for RouteData. In order to utilize RouteData in your handler code you have to pass the RouteData to the handler. In my CallbackHandlerRouteHandler when it creates the HttpHandler instance it creates the instance and then assigns the custom RouteData property on the handler:IHttpHandler handler = Activator.CreateInstance(CallbackHandlerType) as IHttpHandler; if (handler is CallbackHandler) ((CallbackHandler)handler).RouteData = requestContext.RouteData; return handler; Again this only works if you actually add a RouteData property to your handler explicitly as I did in my CallbackHandler implementation:/// <summary> /// Optionally store RouteData on this handler /// so we can access it internally /// </summary> public RouteData RouteData {get; set; } and the RouteHandler needs to set it when it creates the handler instance. Once you have the route data in your handler you can access Route Keys and Values and also the RouteHandler. Since my RouteHandler has a custom property for the MethodName to retrieve it from within the handler I can do something like this now to retrieve the MethodName (this example is actually not in the handler but target is an instance pass to the processor): // check for Route Data method name if (target is CallbackHandler) { var routeData = ((CallbackHandler)target).RouteData; if (routeData != null) methodToCall = ((CallbackHandlerRouteHandler)routeData.RouteHandler).MethodName; } When I need to access the dynamic values in the route ( symbol in StockQuote/{symbol}) I can retrieve it easily with the Values collection (RouteData.Values["symbol"]). In my CallbackHandler processing logic I’m basically looking for matching parameter names to Route parameters: // look for parameters in the routeif(routeData != null){    string parmString = routeData.Values[parameter.Name] as string;    adjustedParms[parmCounter] = ReflectionUtils.StringToTypedValue(parmString, parameter.ParameterType);} And with that we’ve come full circle. We’ve created a custom RouteHandler() that passes the RouteData to the handler it creates. We’ve registered our routes to use the RouteHandler, and we’ve utilized the route data in our handler. For completeness sake here’s the routine that executes a method call based on the parameters passed in and one of the options is to retrieve the inbound parameters off RouteData (as well as from POST data or QueryString parameters):internal object ExecuteMethod(string method, object target, string[] parameters, CallbackMethodParameterType paramType, ref CallbackMethodAttribute callbackMethodAttribute) { HttpRequest Request = HttpContext.Current.Request; object Result = null; // Stores parsed parameters (from string JSON or QUeryString Values) object[] adjustedParms = null; Type PageType = target.GetType(); MethodInfo MI = PageType.GetMethod(method, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (MI == null) throw new InvalidOperationException("Invalid Server Method."); object[] methods = MI.GetCustomAttributes(typeof(CallbackMethodAttribute), false); if (methods.Length < 1) throw new InvalidOperationException("Server method is not accessible due to missing CallbackMethod attribute"); if (callbackMethodAttribute != null) callbackMethodAttribute = methods[0] as CallbackMethodAttribute; ParameterInfo[] parms = MI.GetParameters(); JSONSerializer serializer = new JSONSerializer(); RouteData routeData = null; if (target is CallbackHandler) routeData = ((CallbackHandler)target).RouteData; int parmCounter = 0; adjustedParms = new object[parms.Length]; foreach (ParameterInfo parameter in parms) { // Retrieve parameters out of QueryString or POST buffer if (parameters == null) { // look for parameters in the route if (routeData != null) { string parmString = routeData.Values[parameter.Name] as string; adjustedParms[parmCounter] = ReflectionUtils.StringToTypedValue(parmString, parameter.ParameterType); } // GET parameter are parsed as plain string values - no JSON encoding else if (HttpContext.Current.Request.HttpMethod == "GET") { // Look up the parameter by name string parmString = Request.QueryString[parameter.Name]; adjustedParms[parmCounter] = ReflectionUtils.StringToTypedValue(parmString, parameter.ParameterType); } // POST parameters are treated as methodParameters that are JSON encoded else if (paramType == CallbackMethodParameterType.Json) //string newVariable = methodParameters.GetValue(parmCounter) as string; adjustedParms[parmCounter] = serializer.Deserialize(Request.Params["parm" + (parmCounter + 1).ToString()], parameter.ParameterType); else adjustedParms[parmCounter] = SerializationUtils.DeSerializeObject( Request.Params["parm" + (parmCounter + 1).ToString()], parameter.ParameterType); } else if (paramType == CallbackMethodParameterType.Json) adjustedParms[parmCounter] = serializer.Deserialize(parameters[parmCounter], parameter.ParameterType); else adjustedParms[parmCounter] = SerializationUtils.DeSerializeObject(parameters[parmCounter], parameter.ParameterType); parmCounter++; } Result = MI.Invoke(target, adjustedParms); return Result; } The code basically uses Reflection to loop through all the parameters available on the method and tries to assign the parameters from RouteData, QueryString or POST variables. The parameters are converted into their appropriate types and then used to eventually make a Reflection based method call. What’s sweet is that the RouteData retrieval is just another option for dealing with the inbound data in this scenario and it adds exactly two lines of code plus the code to retrieve the MethodName I showed previously – a seriously low impact addition that adds a lot of extra value to this endpoint callback processing implementation. Debugging your Routes If you create a lot of routes it’s easy to run into Route conflicts where multiple routes have the same path and overlap with each other. This can be difficult to debug especially if you are using automatically generated routes like the routes created by CallbackHandlerRouteHandler.RegisterRoutes. Luckily there’s a tool that can help you out with this nicely. Phill Haack created a RouteDebugging tool you can download and add to your project. The easiest way to do this is to grab and add this to your project is to use NuGet (Add Library Package from your Project’s Reference Nodes):   which adds a RouteDebug assembly to your project. Once installed you can easily debug your routes with this simple line of code which needs to be installed at application startup:protected void Application_Start(object sender, EventArgs e) { CallbackHandlerRouteHandler.RegisterRoutes<StockService>(RouteTable.Routes); // Debug your routes RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes); } Any routed URL then displays something like this: The screen shows you your current route data and all the routes that are mapped along with a flag that displays which route was actually matched. This is useful – if you have any overlap of routes you will be able to see which routes are triggered – the first one in the sequence wins. This tool has saved my ass on a few occasions – and with NuGet now it’s easy to add it to your project in a few seconds and then remove it when you’re done. Routing Around Custom routing seems slightly complicated on first blush due to its disconnected components of RouteHandler, route registration and mapping of custom handlers. But once you understand the relationship between a RouteHandler, the RouteData and how to pass it to a handler, utilizing of Routing becomes a lot easier as you can easily pass context from the registration to the RouteHandler and through to the HttpHandler. The most important thing to understand when building custom routing solutions is to figure out how to map URLs in such a way that the handler can figure out all the pieces it needs to process the request. This can be via URL routing parameters and as I did in my example by passing additional context information as part of the RouteHandler instance that provides the proper execution context. In my case this ‘context’ was the method name, but it could be an actual static value like an enum identifying an operation or category in an application. Basically user supplied data comes in through the url and static application internal data can be passed via RouteHandler property values. Routing can make your application URLs easier to read by non-techie types regardless of whether you’re building Service type or REST applications, or full on Web interfaces. Routing in ASP.NET 4.0 makes it possible to create just about any extensionless URLs you can dream up and custom RouteHanmdler References Sample ProjectIncludes the sample CallbackHandler service discussed here along with compiled versionsof the Westwind.Web and Westwind.Utilities assemblies.  (requires .NET 4.0/VS 2010) West Wind Web Toolkit includes full implementation of CallbackHandler and the Routing Handler West Wind Web Toolkit Source CodeContains the full source code to the Westwind.Web and Westwind.Utilities assemblies usedin these samples. Includes the source described in the post.(Latest build in the Subversion Repository) CallbackHandler Source(Relevant code to this article tree in Westwind.Web assembly) JSONView FireFoxPluginA simple FireFox Plugin to easily view JSON data natively in FireFox.For IE you can use a registry hack to display JSON as raw text.© Rick Strahl, West Wind Technologies, 2005-2011Posted in ASP.NET  AJAX  HTTP  

    Read the article

  • Report Model; problem regarding many-to-many relations

    - by Koen
    I'm having trouble setting up a report model to create reports with report builder. I guess I'm doing something wrong when configuring the report model, but it might also due to change of primary entity in report builder. I have 3 tables: Client, Address and Product. The Client has PK ClientNumber. The Address and Product both have a FK relation on ClientNumber. The relation between Client and Address is 1-to-many and also between Client and Product: Product-(many:1)-Client-(1:many)-Address. I've created a report model (mostly auto generate) with these 3 tables, for each table I've made an Entity. Now on the Client Entity , I've got 2 roles, Address and Product. They both have a cardinality of 'OptionalMany', because Client can have multiple Addresses or Products. On both Address and Product I have a Client Role with cardinality 'One', because for each Address or Product, there has to be a Client (tried OptionalOne as well...). Now I'm trying to create a report in Report Builder (2.0) where I select fields from these three entities. I'd like an overview of Clients with their main address and their products, but I don't seem to be able to create a report with fields from both Address and Products in it. I start by selecting attributes from Client, and as soon as I add Product for example the Primary entity changes as if I'm selecting Products (instead of Clients). This is a basic example of a problem I'm facing in a much more complex model. I've tried lots of different things for 2 days, but I can't get it to work. Does anyone have an idea how to cope with this? (Using SSRS 2008)

    Read the article

  • How to use bll, dal and model?

    - by bruno
    Dear all, In my company I must use a Bll, Dal and model layer for creating applications with a database. I've learned at school that every databasetable should be an object in my model. so I create the whole model of my database. Also I've learned that for every table (or model object) there should be a DAO created into the DAL. So I do this to. Now i'm stuck with the BLL classes. I can write a BLLclass for each DAO/ModelObject or I can write a BLLclass that combine some (logic) DAO's... Or i can write just one Bllclass that will manage everything. (this last one I'm sure it aint the best way..) What is the best practice to handle this Bll 'problem'? And a second question. If a bll is in need of tablecontent from an other table where it aint responsible for, whats the best way to get the content? Go ask on the responsible BLL or go directly to the DAO? I'm struggling with these questions the last 2 months, and i don't know what is the best way to handle it.

    Read the article

  • OO Design / Patterns - Fat Model Vs Transaction Script?

    - by ben
    Ok, 'Fat' Model and Transaction Script both solve design problems associated with where to keep business logic. I've done some research and popular thought says having all business logic encapsulated within the model is the way to go (mainly since Transaction Script can become really complex and often results in code duplication). However, how does this work if I want to use the TDG of a second Model in my business logic? Surely Transaction Script presents a neater, less coupled solution than using one Model inside the business logic of another? A practical example... I have two classes: User & Alert. When pushing User instances to the database (eg, creating new user accounts), there is a business rule that requires inserting some default Alerts records too (eg, a default 'welcome to the system' message etc). I see two options here: 1) Add this rule as a User method, and in the process create a dependency between User and Alert (or, at least, Alert's Table Data Gateway). 2) Use a Transaction Script, which avoids the dependency between models. (Also, means the business logic is kept in a 'neutral' class & easily accessible by Alert. That probably isn't too important here, though). User takes responsibility for it's own validation etc, however, but because we're talking about a business rule involving two Models, Transaction Script seems like a better choice to me. Anyone spot flaws with this approach?

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >