Search Results

Search found 2153 results on 87 pages for 'adam west'.

Page 18/87 | < Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >

  • Python many-to-one mapping (creating equivalence classes)

    - by Adam Matan
    Hi, I have a project of converting one database to another. One of the original database columns defines the row's category. This coulmn should be mapepd to a new category in the new databse. For example, let's assume the original categories are:parrot, spam, cheese_shop, Cleese, Gilliam, Palin Now that's a little verbose for me, And I want to have these rows categorized as sketch, actor - That is, define all the sketches and all the actors as two equivalence classes. >>> monty={'parrot':'sketch', 'spam':'sketch', 'cheese_shop':'sketch', 'Cleese':'actor', 'Gilliam':'actor', 'Palin':'actor'} >>> monty {'Gilliam': 'actor', 'Cleese': 'actor', 'parrot': 'sketch', 'spam': 'sketch', 'Palin': 'actor', 'cheese_shop': 'sketch'} That's quite awkward- I would prefer having something like: monty={ ('parrot','spam','cheese_shop'): 'sketch', ('Cleese', 'Gilliam', 'Palin') : 'actors'} But this, of course, sets the entire tuple as a key: >>> monty['parrot'] Traceback (most recent call last): File "<pyshell#29>", line 1, in <module> monty['parrot'] KeyError: 'parrot' Any ideas how to create an elegant many-to-one dictionary in Python? Thanks, Adam

    Read the article

  • How to load JPG file into NSBitmapImageRep?

    - by Adam
    Objective-C / Cocoa: I need to load the image from a JPG file into a two dimensional array so that I can access each pixel. I am trying (unsuccessfully) to load the image into a NSBitmapImageRep. I have tried several variations on the following two lines of code: NSString *filePath = [NSString stringWithFormat: @"%@%@",@"/Users/adam/Documents/phoneimages/", [outLabel stringValue]]; //this coming from a window control NSImageRep *controlBitmap = [[NSImageRep alloc] imageRepWithContentsOfFile:filePath]; With the code shown, I get a runtime error: -[NSImageRep imageRepWithContentsOfFile:]: unrecognized selector sent to instance 0x100147070. I have tried replacing the second line of code with: NSImage *controlImage = [[NSImage alloc] initWithContentsOfFile:filePath]; NSBitmapImageRep *controlBitmap = [[NSBitmapImageRep alloc] initWithData:controlImage]; But this yields a compiler error 'incompatible type' saying that initWithData wants a NSData variable not an NSImage. I have also tried various other ways to get this done, but all are unsuccessful either due to compiler or runtime error. Can someone help me with this? I will eventually need to load some PNG files in the same way (so it would be nice to have a consistent technique for both). And if you know of an easier / simpler way to accomplish what I am trying to do (i.e., get the images into a two-dimensional array), rather than using NSBitmapImageRep, then please let me know! And by the way, I know the path is valid (confirmed with fileExistsAtPath) -- and the filename in outLabel is a file with .jpg extension. Thanks for any help!

    Read the article

  • SEO redirects for removed pages

    - by adam
    Hi, Apologies if SO is not the right place for this, but there are 700+ other SEO questions on here. I'm a senior developer for a travel site with 12k+ pages. We completely redeveloped the site and relaunched in January, and with the volatile nature of travel, there are many pages which are no longer on the site. Examples: /destinations/africa/senegal.aspx /destinations/africa/features.aspx Of course, we have a 404 page in place (and it's a hard 404 page rather than a 30x redirect to a 404). Our SEO advisor has asked us to 30x redirect all our 404 pages (as found in Webmaster Tools), his argument being that 404's are damaging to our pagerank. He'd want us to redirect our Senegal and features pages above to the Africa page (which doesn't contain the content previously found on Senegal.aspx or features.aspx). An equivalent for SO would be taking a url for a removed question and redirecting it to /questions rather than showing a 404 'Question/Page not found'. My argument is that, as these pages are no longer on the site, 404 is the correct status to return. I'd also argue that redirecting these to less relevant pages could damage our SEO (due to duplicate content perhaps)? It's also very time consuming redirecting all 404's when our site takes some content from our in-house system, which adds/removes content at will. Thanks for any advice, Adam

    Read the article

  • ExtJs Grid in TabPanel auto Fit issue.

    - by Jinah Adam
    Hi, I am having problems redering an grid in a a tab panel (Its made with Ext Designer.). the hierarchy is as follows , Viewport. - tabPanel - Panel - Container - Grid. This is how its displayed now Here is the code for viewport mainWindowUi = Ext.extend(Ext.Viewport, { layout: 'border', id: 'mainWindow', initComponent: function() { this.items = [ { xtype: 'panel', title: 'Navigation', region: 'west', width: 200, frame: true, split: true, titleCollapse: true, collapsible: true, id: 'navigation', items: [ { flex: 1, xtype: 'mytreepanel' } ] }, { xtype: 'tabpanel', layoutOnTabChange: true, resizeTabs: true, defaults: { layout: 'fit', autoScroll: true }, region: 'center', tpl: '', id: 'mainTabPanel', layoutConfig: { deferredRender: true } } ]; mainWindowUi.superclass.initComponent.call(this); } }); here is the code to create the tab.. (created from a nav panel programmatically) var currentTab = tabPanel.findById(node.id); // If not yet created, create the tab if (!currentTab){ currentTab = tabPanel.add({ title:node.id, id:node.id, closable:true, items:[{ xtype: 'phasePanel', layout: 'fit', autoscroll: true, }], autoScroll:true, }); } // Activate tab tabPanel.setActiveTab(currentTab); here is the code for the panel/container/grid PhasePanelUi = Ext.extend(Ext.Panel, { frame: true, layout: 'anchor', autoScroll: true, autoWidth: true, defaults: '', initComponent: function() { this.items = [ { xtype: 'container', autoScroll: true, layout: 'fit', defaults: { layout: 'fit', autoScroll: true }, id: 'gridHolder', items: [ { xtype: 'grid', title: 'Current Phases', store: 'PhaseStore', autoDestroy: false, viewConfig: '', deferRowRender: false, autoLoad: '', ref: '../phaseGrid', id: 'phaseGrid', columns: [ { xtype: 'gridcolumn', header: 'Name', dataIndex: 'name', sortable: true, width: 200 }, { xtype: 'gridcolumn', header: 'Estate', dataIndex: 'estate_name', sortable: true, width: 500 } ] } ] } ]; PhasePanelUi.superclass.initComponent.call(this); } }); i have tried all sorts of combinations. but just cant get the grid to render correctly any sort of assistance will be appreciated.

    Read the article

  • strange run time error message from CIImage initWithContentsOfURL

    - by Adam
    When executing the following code I receive a run time error when the code executes the second line of code. The error (which shows up in the debugger) says: [NSButton initWithContentsOfURL:]: unrecognized selector sent to instance 0x100418e10. I don't understand this message, because it looks to me (based on my source code) like the initWithContentsOfURL message is being sent to the myImage instance (of the CIImage class) ... not NSButton. Any idea what is going on? If it matters ... this code is in the Application Controller class module of an Xcode project (a Cocoa application) -- within a method that is called when I click on a button on the application window. There is only the one button on the window ... // Step1: Load the JPG file into CIImage NSURL *myURL = [NSURL fileURLWithPath:@"/Users/Adam/Documents/Images/image7.jpg"]; CIImage *myImage = [myImage initWithContentsOfURL: myURL]; if (myImage = Nil) { NSLog(@"Creating myImage failed"); return; } else { NSLog(@"Created myImage successfully"); }

    Read the article

  • Maven Java Source Code Generation for Hibernate

    - by Adam
    Hi, I´m busy converting an existing project from an Ant build to one using Maven. Part of this build includes using the hibernate hbm2java tool to convert a collection of .hbm.xml files into Java. Here's a snippet of the Ant script used to do this: <target name="dbcodegen" depends="cleangen" description="Generate Java source from Hibernate XML"> <hibernatetool destdir="${src.generated}"> <configuration> <fileset dir="${src.config}"> <include name="**/*.hbm.xml"/> </fileset> </configuration> <hbm2java jdk5="true"/> </hibernatetool> </target> I've had a look around on the internet and some people seem to do this (I think) using Ant within Maven and others with the Maven plugin. I'd prefer to avoid mixing Ant and Maven. Can anyone suggest a way to do this so that all of the .hbm.xml files are picked up and the code generation takes place as part of the Maven code generation build phase? Thanks! Adam.

    Read the article

  • Dynamic Type to do away with Reflection

    - by Rick Strahl
    The dynamic type in C# 4.0 is a welcome addition to the language. One thing I’ve been doing a lot with it is to remove explicit Reflection code that’s often necessary when you ‘dynamically’ need to walk and object hierarchy. In the past I’ve had a number of ReflectionUtils that used string based expressions to walk an object hierarchy. With the introduction of dynamic much of the ReflectionUtils code can be removed for cleaner code that runs considerably faster to boot. The old Way - Reflection Here’s a really contrived example, but assume for a second, you’d want to dynamically retrieve a Page.Request.Url.AbsoluteUrl based on a Page instance in an ASP.NET Web Page request. The strongly typed version looks like this: string path = Page.Request.Url.AbsolutePath; Now assume for a second that Page wasn’t available as a strongly typed instance and all you had was an object reference to start with and you couldn’t cast it (right I said this was contrived :-)) If you’re using raw Reflection code to retrieve this you’d end up writing 3 sets of Reflection calls using GetValue(). Here’s some internal code I use to retrieve Property values as part of ReflectionUtils: /// <summary> /// Retrieve a property value from an object dynamically. This is a simple version /// that uses Reflection calls directly. It doesn't support indexers. /// </summary> /// <param name="instance">Object to make the call on</param> /// <param name="property">Property to retrieve</param> /// <returns>Object - cast to proper type</returns> public static object GetProperty(object instance, string property) { return instance.GetType().GetProperty(property, ReflectionUtils.MemberAccess).GetValue(instance, null); } If you want more control over properties and support both fields and properties as well as array indexers a little more work is required: /// <summary> /// Parses Properties and Fields including Array and Collection references. /// Used internally for the 'Ex' Reflection methods. /// </summary> /// <param name="Parent"></param> /// <param name="Property"></param> /// <returns></returns> private static object GetPropertyInternal(object Parent, string Property) { if (Property == "this" || Property == "me") return Parent; object result = null; string pureProperty = Property; string indexes = null; bool isArrayOrCollection = false; // Deal with Array Property if (Property.IndexOf("[") > -1) { pureProperty = Property.Substring(0, Property.IndexOf("[")); indexes = Property.Substring(Property.IndexOf("[")); isArrayOrCollection = true; } // Get the member MemberInfo member = Parent.GetType().GetMember(pureProperty, ReflectionUtils.MemberAccess)[0]; if (member.MemberType == MemberTypes.Property) result = ((PropertyInfo)member).GetValue(Parent, null); else result = ((FieldInfo)member).GetValue(Parent); if (isArrayOrCollection) { indexes = indexes.Replace("[", string.Empty).Replace("]", string.Empty); if (result is Array) { int Index = -1; int.TryParse(indexes, out Index); result = CallMethod(result, "GetValue", Index); } else if (result is ICollection) { if (indexes.StartsWith("\"")) { // String Index indexes = indexes.Trim('\"'); result = CallMethod(result, "get_Item", indexes); } else { // assume numeric index int index = -1; int.TryParse(indexes, out index); result = CallMethod(result, "get_Item", index); } } } return result; } /// <summary> /// Returns a property or field value using a base object and sub members including . syntax. /// For example, you can access: oCustomer.oData.Company with (this,"oCustomer.oData.Company") /// This method also supports indexers in the Property value such as: /// Customer.DataSet.Tables["Customers"].Rows[0] /// </summary> /// <param name="Parent">Parent object to 'start' parsing from. Typically this will be the Page.</param> /// <param name="Property">The property to retrieve. Example: 'Customer.Entity.Company'</param> /// <returns></returns> public static object GetPropertyEx(object Parent, string Property) { Type type = Parent.GetType(); int at = Property.IndexOf("."); if (at < 0) { // Complex parse of the property return GetPropertyInternal(Parent, Property); } // Walk the . syntax - split into current object (Main) and further parsed objects (Subs) string main = Property.Substring(0, at); string subs = Property.Substring(at + 1); // Retrieve the next . section of the property object sub = GetPropertyInternal(Parent, main); // Now go parse the left over sections return GetPropertyEx(sub, subs); } As you can see there’s a fair bit of code involved into retrieving a property or field value reliably especially if you want to support array indexer syntax. This method is then used by a variety of routines to retrieve individual properties including one called GetPropertyEx() which can walk the dot syntax hierarchy easily. Anyway with ReflectionUtils I can  retrieve Page.Request.Url.AbsolutePath using code like this: string url = ReflectionUtils.GetPropertyEx(Page, "Request.Url.AbsolutePath") as string; This works fine, but is bulky to write and of course requires that I use my custom routines. It’s also quite slow as the code in GetPropertyEx does all sorts of string parsing to figure out which members to walk in the hierarchy. Enter dynamic – way easier! .NET 4.0’s dynamic type makes the above really easy. The following code is all that it takes: object objPage = Page; // force to object for contrivance :) dynamic page = objPage; // convert to dynamic from untyped object string scriptUrl = page.Request.Url.AbsolutePath; The dynamic type assignment in the first two lines turns the strongly typed Page object into a dynamic. The first assignment is just part of the contrived example to force the strongly typed Page reference into an untyped value to demonstrate the dynamic member access. The next line then just creates the dynamic type from the Page reference which allows you to access any public properties and methods easily. It also lets you access any child properties as dynamic types so when you look at Intellisense you’ll see something like this when typing Request.: In other words any dynamic value access on an object returns another dynamic object which is what allows the walking of the hierarchy chain. Note also that the result value doesn’t have to be explicitly cast as string in the code above – the compiler is perfectly happy without the cast in this case inferring the target type based on the type being assigned to. The dynamic conversion automatically handles the cast when making the final assignment which is nice making for natural syntnax that looks *exactly* like the fully typed syntax, but is completely dynamic. Note that you can also use indexers in the same natural syntax so the following also works on the dynamic page instance: string scriptUrl = page.Request.ServerVariables["SCRIPT_NAME"]; The dynamic type is going to make a lot of Reflection code go away as it’s simply so much nicer to be able to use natural syntax to write out code that previously required nasty Reflection syntax. Another interesting thing about the dynamic type is that it actually works considerably faster than Reflection. Check out the following methods that check performance: void Reflection() { Stopwatch stop = new Stopwatch(); stop.Start(); for (int i = 0; i < reps; i++) { // string url = ReflectionUtils.GetProperty(Page,"Title") as string;// "Request.Url.AbsolutePath") as string; string url = Page.GetType().GetProperty("Title", ReflectionUtils.MemberAccess).GetValue(Page, null) as string; } stop.Stop(); Response.Write("Reflection: " + stop.ElapsedMilliseconds.ToString()); } void Dynamic() { Stopwatch stop = new Stopwatch(); stop.Start(); dynamic page = Page; for (int i = 0; i < reps; i++) { string url = page.Title; //Request.Url.AbsolutePath; } stop.Stop(); Response.Write("Dynamic: " + stop.ElapsedMilliseconds.ToString()); } The dynamic code runs in 4-5 milliseconds while the Reflection code runs around 200+ milliseconds! There’s a bit of overhead in the first dynamic object call but subsequent calls are blazing fast and performance is actually much better than manual Reflection. Dynamic is definitely a huge win-win situation when you need dynamic access to objects at runtime.© Rick Strahl, West Wind Technologies, 2005-2010Posted in .NET  CSharp  

    Read the article

  • Mapping UrlEncoded POST Values in ASP.NET Web API

    - by Rick Strahl
    If there's one thing that's a bit unexpected in ASP.NET Web API, it's the limited support for mapping url encoded POST data values to simple parameters of ApiController methods. When I first looked at this I thought I was doing something wrong, because it seems mighty odd that you can bind query string values to parameters by name, but can't bind POST values to parameters in the same way. To demonstrate here's a simple example. If you have a Web API method like this:[HttpGet] public HttpResponseMessage Authenticate(string username, string password) { …} and then hit with a URL like this: http://localhost:88/samples/authenticate?Username=ricks&Password=sekrit it works just fine. The query string values are mapped to the username and password parameters of our API method. But if you now change the method to work with [HttpPost] instead like this:[HttpPost] public HttpResponseMessage Authenticate(string username, string password) { …} and hit it with a POST HTTP Request like this: POST http://localhost:88/samples/authenticate HTTP/1.1 Host: localhost:88 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Content-type: application/x-www-form-urlencoded Content-Length: 30 Username=ricks&Password=sekrit you'll find that while the request works, it doesn't actually receive the two string parameters. The username and password parameters are null and so the method is definitely going to fail. When I mentioned this over Twitter a few days ago I got a lot of responses back of why I'd want to do this in the first place - after all HTML Form submissions are the domain of MVC and not WebAPI which is a valid point. However, the more common use case is using POST Variables with AJAX calls. The following is quite common for passing simple values:$.post(url,{ Username: "Rick", Password: "sekrit" },function(result) {…}); but alas that doesn't work. How ASP.NET Web API handles Content Bodies Web API supports parsing content data in a variety of ways, but it does not deal with multiple posted content values. In effect you can only post a single content value to a Web API Action method. That one parameter can be very complex and you can bind it in a variety of ways, but ultimately you're tied to a single POST content value in your parameter definition. While it's possible to support multiple parameters on a POST/PUT operation, only one parameter can be mapped to the actual content - the rest have to be mapped to route values or the query string. Web API treats the whole request body as one big chunk of data that is sent to a Media Type Formatter that's responsible for de-serializing the content into whatever value the method requires. The restriction comes from async nature of Web API where the request data is read only once inside of the formatter that retrieves and deserializes it. Because it's read once, checking for content (like individual POST variables) first is not possible. However, Web API does provide a couple of ways to access the form POST data: Model Binding - object property mapping to bind POST values FormDataCollection - collection of POST keys/values ModelBinding POST Values - Binding POST data to Object Properties The recommended way to handle POST values in Web API is to use Model Binding, which maps individual urlencoded POST values to properties of a model object provided as the parameter. Model binding requires a single object as input to be bound to the POST data, with each POST key that matches a property name (including nested properties like Address.Street) being mapped and updated including automatic type conversion of simple types. This is a very nice feature - and a familiar one from MVC - that makes it very easy to have model objects mapped directly from inbound data. The obvious drawback with Model Binding is that you need a model for it to work: You have to provide a strongly typed object that can receive the data and this object has to map the inbound data. To rewrite the example above to use ModelBinding I have to create a class maps the properties that I need as parameters:public class LoginData { public string Username { get; set; } public string Password { get; set; } } and then accept the data like this in the API method:[HttpPost] public HttpResponseMessage Authenticate(LoginData login) { string username = login.Username; string password = login.Password; … } This works fine mapping the POST values to the properties of the login object. As a side benefit of this method definition, the method now also allows posting of JSON or XML to the same endpoint. If I change my request to send JSON like this: POST http://localhost:88/samples/authenticate HTTP/1.1 Host: localhost:88 Accept: application/jsonContent-type: application/json Content-Length: 40 {"Username":"ricks","Password":"sekrit"} it works as well and transparently, courtesy of the nice Content Negotiation features of Web API. There's nothing wrong with using Model binding and in fact it's a common practice to use (view) model object for inputs coming back from the client and mapping them into these models. But it can be  kind of a hassle if you have AJAX applications with a ton of backend hits, especially if many methods are very atomic and focused and don't effectively require a model or view. Not always do you have to pass structured data, but sometimes there are just a couple of simple response values that need to be sent back. If all you need is to pass a couple operational parameters, creating a view model object just for parameter purposes seems like overkill. Maybe you can use the query string instead (if that makes sense), but if you can't then you can often end up with a plethora of 'message objects' that serve no further  purpose than to make Model Binding work. Note that you can accept multiple parameters with ModelBinding so the following would still work:[HttpPost] public HttpResponseMessage Authenticate(LoginData login, string loginDomain) but only the object will be bound to POST data. As long as loginDomain comes from the querystring or route data this will work. Collecting POST values with FormDataCollection Another more dynamic approach to handle POST values is to collect POST data into a FormDataCollection. FormDataCollection is a very basic key/value collection (like FormCollection in MVC and Request.Form in ASP.NET in general) and then read the values out individually by querying each. [HttpPost] public HttpResponseMessage Authenticate(FormDataCollection form) { var username = form.Get("Username"); var password = form.Get("Password"); …} The downside to this approach is that it's not strongly typed, you have to handle type conversions on non-string parameters, and it gets a bit more complicated to test such as setup as you have to seed a FormDataCollection with data. On the other hand it's flexible and easy to use and especially with string parameters is easy to deal with. It's also dynamic, so if the client sends you a variety of combinations of values on which you make operating decisions, this is much easier to work with than a strongly typed object that would have to account for all possible values up front. The downside is that the code looks old school and isn't as self-documenting as a parameter list or object parameter would be. Nevertheless it's totally functionality and a viable choice for collecting POST values. What about [FromBody]? Web API also has a [FromBody] attribute that can be assigned to parameters. If you have multiple parameters on a Web API method signature you can use [FromBody] to specify which one will be parsed from the POST content. Unfortunately it's not terribly useful as it only returns content in raw format and requires a totally non-standard format ("=content") to specify your content. For more info in how FromBody works and several related issues to how POST data is mapped, you can check out Mike Stalls post: How WebAPI does Parameter Binding Not really sure where the Web API team thought [FromBody] would really be a good fit other than a down and dirty way to send a full string buffer. Extending Web API to make multiple POST Vars work? Don't think so Clearly there's no native support for multiple POST variables being mapped to parameters, which is a bit of a bummer. I know in my own work on one project my customer actually found this to be a real sticking point in their AJAX backend work, and we ended up not using Web API and using MVC JSON features instead. That's kind of sad because Web API is supposed to be the proper solution for AJAX backends. With all of ASP.NET Web API's extensibility you'd think there would be some way to build this functionality on our own, but after spending a bit of time digging and asking some of the experts from the team and Web API community I didn't hear anything that even suggests that this is possible. From what I could find I'd say it's not possible primarily because Web API's Routing engine does not account for the POST variable mapping. This means [HttpPost] methods with url encoded POST buffers are not mapped to the parameters of the endpoint, and so the routes would never even trigger a request that could be intercepted. Once the routing doesn't work there's not much that can be done. If somebody has an idea how this could be accomplished I would love to hear about it. Do we really need multi-value POST mapping? I think that that POST value mapping is a feature that one would expect of any API tool to have. If you look at common APIs out there like Flicker and Google Maps etc. they all work with POST data. POST data is very prominent much more so than JSON inputs and so supporting as many options that enable would seem to be crucial. All that aside, Web API does provide very nice features with Model Binding that allows you to capture many POST variables easily enough, and logistically this will let you build whatever you need with POST data of all shapes as long as you map objects. But having to have an object for every operation that receives a data input is going to take its toll in heavy AJAX applications, with a lot of types created that do nothing more than act as parameter containers. I also think that POST variable mapping is an expected behavior and Web APIs non-support will likely result in many, many questions like this one: How do I bind a simple POST value in ASP.NET WebAPI RC? with no clear answer to this question. I hope for V.next of WebAPI Microsoft will consider this a feature that's worth adding. Related Articles Passing multiple POST parameters to Web API Controller Methods Mike Stall's post: How Web API does Parameter Binding Where does ASP.NET Web API Fit?© Rick Strahl, West Wind Technologies, 2005-2012Posted in Web Api   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Are high powered 3D game engines better at 2D games than engines made for 2D

    - by Adam
    I'm a software engineer that's new to game programming so forgive me if this is a dumb question as I don't know that much about game engines. If I was building a 2D game am I better off going with an engine like Torque that looks like it's built for 2D, or would higher powered engines like Unreal, Source and Unity work better? I'm mainly asking if 2D vs 3D is a large factor in choosing an engine. For the purpose of comparison, let's eliminate variables by saying price isn't a factor (even though it probably is). EDIT: I should probably also mention that the game we're developing has a lot of RTS and RPG elements regarding leveling up

    Read the article

  • ASP.NET MVC Postbacks and HtmlHelper Controls ignoring Model Changes

    - by Rick Strahl
    So here's a binding behavior in ASP.NET MVC that I didn't really get until today: HtmlHelpers controls (like .TextBoxFor() etc.) don't bind to model values on Postback, but rather get their value directly out of the POST buffer from ModelState. Effectively it looks like you can't change the display value of a control via model value updates on a Postback operation. To demonstrate here's an example. I have a small section in a document where I display an editable email address: This is what the form displays on a GET operation and as expected I get the email value displayed in both the textbox and plain value display below, which reflects the value in the mode. I added a plain text value to demonstrate the model value compared to what's rendered in the textbox. The relevant markup is the email address which needs to be manipulated via the model in the Controller code. Here's the Razor markup: <div class="fieldcontainer"> <label> Email: &nbsp; <small>(username and <a href="http://gravatar.com">Gravatar</a> image)</small> </label> <div> @Html.TextBoxFor( mod=> mod.User.Email, new {type="email",@class="inputfield"}) @Model.User.Email </div> </div>   So, I have this form and the user can change their email address. On postback the Post controller code then asks the business layer whether the change is allowed. If it's not I want to reset the email address back to the old value which exists in the database and was previously store. The obvious thing to do would be to modify the model. Here's the Controller logic block that deals with that:// did user change email? if (!string.IsNullOrEmpty(oldEmail) && user.Email != oldEmail) { if (userBus.DoesEmailExist(user.Email)) { userBus.ValidationErrors.Add("New email address exists already. Please…"); user.Email = oldEmail; } else // allow email change but require verification by forcing a login user.IsVerified = false; }… model.user = user; return View(model); The logic is straight forward - if the new email address is not valid because it already exists I don't want to display the new email address the user entered, but rather the old one. To do this I change the value on the model which effectively does this:model.user.Email = oldEmail; return View(model); So when I press the Save button after entering in my new email address ([email protected]) here's what comes back in the rendered view: Notice that the textbox value and the raw displayed model value are different. The TextBox displays the POST value, the raw value displays the actual model value which are different. This means that MVC renders the textbox value from the POST data rather than from the view data when an Http POST is active. Now I don't know about you but this is not the behavior I expected - initially. This behavior effectively means that I cannot modify the contents of the textbox from the Controller code if using HtmlHelpers for binding. Updating the model for display purposes in a POST has in effect - no effect. (Apr. 25, 2012 - edited the post heavily based on comments and more experimentation) What should the behavior be? After getting quite a few comments on this post I quickly realized that the behavior I described above is actually the behavior you'd want in 99% of the binding scenarios. You do want to get the POST values back into your input controls at all times, so that the data displayed on a form for the user matches what they typed. So if an error occurs, the error doesn't mysteriously disappear getting replaced either with a default value or some value that you changed on the model on your own. Makes sense. Still it is a little non-obvious because the way you create the UI elements with MVC, it certainly looks like your are binding to the model value:@Html.TextBoxFor( mod=> mod.User.Email, new {type="email",@class="inputfield",required="required" }) and so unless one understands a little bit about how the model binder works this is easy to trip up. At least it was for me. Even though I'm telling the control which model value to bind to, that model value is only used initially on GET operations. After that ModelState/POST values provide the display value. Workarounds The default behavior should be fine for 99% of binding scenarios. But if you do need fix up values based on your model rather than the default POST values, there are a number of ways that you can work around this. Initially when I ran into this, I couldn't figure out how to set the value using code and so the simplest solution to me was simply to not use the MVC Html Helper for the specific control and explicitly bind the model via HTML markup and @Razor expression: <input type="text" name="User.Email" id="User_Email" value="@Model.User.Email" /> And this produces the right result. This is easy enough to create, but feels a little out of place when using the @Html helpers for everything else. As you can see by the difference in the name and id values, you also are forced to remember the naming conventions that MVC imposes in order for ModelBinding to work properly which is a pain to remember and set manually (name is the same as the property with . syntax, id replaces dots with underlines). Use the ModelState Some of my original confusion came because I didn't understand how the model binder works. The model binder basically maintains ModelState on a postback, which holds a value and binding errors for each of the Post back value submitted on the page that can be mapped to the model. In other words there's one ModelState entry for each bound property of the model. Each ModelState entry contains a value property that holds AttemptedValue and RawValue properties. The AttemptedValue is essentially the POST value retrieved from the form. The RawValue is the value that the model holds. When MVC binds controls like @Html.TextBoxFor() or @Html.TextBox(), it always binds values on a GET operation. On a POST operation however, it'll always used the AttemptedValue to display the control. MVC binds using the ModelState on a POST operation, not the model's value. So, if you want the behavior that I was expecting originally you can actually get it by clearing the ModelState in the controller code:ModelState.Clear(); This clears out all the captured ModelState values, and effectively binds to the model. Note this will produce very similar results - in fact if there are no binding errors you see exactly the same behavior as if binding from ModelState, because the model has been updated from the ModelState already and binding to the updated values most likely produces the same values you would get with POST back values. The big difference though is that any values that couldn't bind - like say putting a string into a numeric field - will now not display back the value the user typed, but the default field value or whatever you changed the model value to. This is the behavior I was actually expecting previously. But - clearing out all values might be a bit heavy handed. You might want to fix up one or two values in a model but rarely would you want the entire model to update from the model. So, you can also clear out individual values on an as needed basis:if (userBus.DoesEmailExist(user.Email)) { userBus.ValidationErrors.Add("New email address exists already. Please…"); user.Email = oldEmail; ModelState.Remove("User.Email"); } This allows you to remove a single value from the ModelState and effectively allows you to replace that value for display from the model. Why? While researching this I came across a post from Microsoft's Brad Wilson who describes the default binding behavior best in a forum post: The reason we use the posted value for editors rather than the model value is that the model may not be able to contain the value that the user typed. Imagine in your "int" editor the user had typed "dog". You want to display an error message which says "dog is not valid", and leave "dog" in the editor field. However, your model is an int: there's no way it can store "dog". So we keep the old value. If you don't want the old values in the editor, clear out the Model State. That's where the old value is stored and pulled from the HTML helpers. There you have it. It's not the most intuitive behavior, but in hindsight this behavior does make some sense even if at first glance it looks like you should be able to update values from the model. The solution of clearing ModelState works and is a reasonable one but you have to know about some of the innards of ModelState and how it actually works to figure that out.© Rick Strahl, West Wind Technologies, 2005-2012Posted in ASP.NET  MVC   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • top tweets WebLogic Partner Community – June 2012

    - by JuergenKress
    Send your tweets @wlscommunity #WebLogicCommunity and follow us at http://twitter.com/wlscommunity OTNArchBeat? Free Virtual Developer Day: Oracle ADF and Oracle Fusion Middleware Development http://bit.ly/MxuNAg AMIS, Oracle & Java? Checklist veearts nu ook op iPad. @amis_services Mobile integratie met Oracle Fusion Middleware http://dld.bz/buwsM #OSB #SOA WhitehorsesWhiteblog: Troubleshoot JVM crashes of Weblogic: CompilerThread (http://bit.ly/KcGzZK) Jon petter hjulstad E-vita is now Apps Grid Specialized! ODTUG Fusion Middleware Sessions RT @OTNArchBeat: ODTUG Kscope12 - June 24-28 - San Antonio, TX http://bit.ly/LlWkNV OTNArchBeat? Free Event: Modern #Java Development, in/outside the Enterprise - May 30 - Redwood Shores, CA http://bit.ly/LfB79a ADF Community DE? Oracle Advanced ADF 11g Partner Workshop Düsseldorf /Germany (english) June 26-29, click here to see Nicolas Lorain? Best Practices for #JavaFX 2 Enterprise Applications (Part Two) http://buff.ly/Lk1DBn by Jim Weaver shay shmeltzer? #Oracle Developers in #Israel - don't miss the free #ADF workshop July 2nd - get hands-on with Oracle ADF -here OTNArchBeat? Java at JAXconf | Tori Wieldt http://bit.ly/LdoLS2 Anand Akela? #Oracle Customers and Partners – Get your free pass to @CloudExpo in New York, June 11 to 14, http://goo.gl/RpYFT <- Stop by booth #511 OracleSupport_WLS? Did you know that since 3/15/12 #WebLogic Server 12.1.1.0 is certified for production with JDK 7? http://bit.ly/IYJE0L Sharat? Highly useful #JavaFX best practices blog by @JavaFXpert More details here ADF EMG How to set up a productive ADF Dev Env - discussion started by @baigsorcl. Click here to Read and comment. OracleSupport_WLS Upcoming #webcast: Diagnosing #weblogic performance issues through #java thread dumps http://bit.ly/M4O9qF My Oracle Support? New to Oracle Support? - Webcast on Support Basics webcast May 22 10:30 Central Europe. Register @ http://bit.ly/J8o0WG Mohamad Afshar? Cloud Expo – Oracle Customers and Partners – get your free pass to Cloud Expo in New York, June 11 to 14, http://goo.gl/RpYFT OTNArchBeat Oracle VM 3.1 is here | @Ronenkofman http://bit.ly/JriWTq Oracle Exalogic? RT @D0uglasPhillips: ExalogicTV New Video Introducing Oracle Secure Global Desktop for #Exalogic!! http://bit.ly/nwkrCu OracleBlogs? Java EE6 and WebLogic YouTube video channels http://ow.ly/1jVcYJ Oracle WebLogic RT @aleftik: Excited to spend some time today playing around with the WebSockets SDK http://bit.ly/NoTtri WebLogic Community Java EE6 and WebLogic YouTube video channels http://wp.me/p1LMIb-h0 OracleSupport_WLS New tutorial! How to use the #JMS #API to create a message producer with #GlassFish and #NetBeans http://bit.ly/Juqjn JDeveloper & ADF? Tip when installing JDeveloper 11.1.2.2.0 version http://dlvr.it/1b48s1 WebLogic Community Middleware Oracle Excellence Awards 2012 – HAPPY NEW YEAR! Click here to read WebLogicCommunity #opn #oracle#Specialization #opnaward Steven Davelaar? Improve performance of your ADF app using lazy, on-demand querying of detail view objects: Click here OracleBlogs? Middleware Oracle Excellence Awards 2012 & HAPPY NEW YEAR! http://ow.ly/1kahzZ OracleSupport_WLS Upgrading from #weblogic 9.2.x to 10.3.x? http://bit.ly/Kqzl9N AMIS, Oracle & Java “@JDeveloper: Logout from an ADF application http://dlvr.it/1fQBnm” WebLogic Community UK OUG call for papers–your middleware success! Click here #UKOUG #soacommunity #OPN Whitehorses Whiteblog: Enterprise Manager: Manage your Fusion Middleware logfiles (http://bit.ly/KQlZkR) WebLogic Community? @Jphjulstad HI Jon, should we send Pizza when you go in production with your WebLogic 12c project? Whish you success! #WebLogicCommunity Sabine Leitner ADF Einsteigerworkshops je 2 Tage im Juni in HAM, BLN, HANN #Oracle #WLS http://bit.ly/LcOIzB @OracleWebLogic @OracleAppGrid@soacommunity Andreas Koop new post Java Heap Monitor in JDeveloper http://bit.ly/LgSk85 Sabine Leitner? #Oracle Kundentag mit Vorträgen von Sparkasse, Schufa, LBBW, Allianz über FMW & Exa Lösungen! 21.06. FRA http://bit.ly/JtwE3v @wlscommunity NetBeans Team RT @chadlung: Installing and configuring #NetBeans 7.1.2 and the #Java JDK 1.7 on OS X: http://www.giantflyingsaucer.com/blog/p=3760 #osx WebLogic Community Happy New Year #WeblogicCommunity thanks for the business! Time for a drink http://pic.twitter.com/K34KFbvH WebLogic Community UK OUG call for papers&ndash;your middleware success! http://wp.me/p1LMIb-gU WebLogic Community? Middleware Oracle Excellence Awards 2012 - HAPPY NEW YEAR! http://wp.me/p1LMIb-h6 Oracle WebLogic? RT @wlscommunity: WebLogic World Record Two Processor Result with SPECjEnterprise2010 Benchmark Click here to read #weblogic #sunfire #li Marc? Relocate wlst script for all the logfiles in your domain @wlscommunity, http://tinyurl.com/btbjcco WebLogic Community WebLogic World Record Two Processor Result with SPECjEnterprise2010 Benchmark Click here #WebLogicCommunity #weblogic #sunfire Oracle WebLogic MIss a WebLogic Devcast webinar? Catch any of the replays in the series on-demand! #WebLogic #JavaEE #coherence http://bit.ly/LNGa4p JDeveloper & ADF? Bean DataControl - Edit table records http://dlvr.it/1ZWqCx Justin Kestelyn? Contents of "Virtual Developer Day: Java SE 7 and JavaFX 2.0" are now avail on demand; no reg http://tinyurl.com/78nxnyo Frank Nimphius? Preparing 12c new features for DOAG 2012 Development - June 14th in Bonn (http://development.doag.org) WebLogic Community? Middleware Oracle Excellence Awards 2012&ndash;HAPPY NEW YEAR! http://wp.me/p1LMIb-he JDeveloper & ADF Placeholder Watermarks with ADF 11.1.2 http://dlvr.it/1ZWDc9 Oracle ACE Program? May edition #ACE newsletter now available online. http://bit.ly/LKA2de chriscmuir New blog post: Which JDeveloper is right for me? http://bit.ly/J8sj9e GlassFish? Transactional Interceptors in Java EE 7 - Request for feedback: Linda described how EJB's container-managed tr http://bit.ly/KKuGNJ OracleEnterpriseMgr Oracle Application Testing Suite 12.1 Debuts at StarEast 2012 http://ow.ly/aXcv8 #em12c JAX London First set of speaker session announced for #JAXLondon see: http://bit.ly/L0HSME OTNArchBeat? Oracle Cloud Conference: dates and locations worldwide http://bit.ly/JgNeID NetBeans Team? Video: Create and debug a TestNG test class in #NetBeans IDE: http://ow.ly/b7NEW NetBeans Team #NetBeans tip: Code Template for #Kohana #PHP Framework: http://ow.ly/aWIvY Robin? Started to use the #Oracle #WebLogic Server #Maven Plugin. Really awesome to install a complete #WLS with "mvn wls:install" !@wlscommunity OTNArchBeat? Free Event: Modern #Java Development, in/outside the Enterprise - May 30 - Redwood Shores, CA http://bit.ly/JIN9tf OracleBlogs WebLogic Partner Community Newsletter May 2012 http://ow.ly/1k5TeG Java Certification? Java SE 7 Fundamentals course now available On Demand. Watch a preview now: http://ow.ly/aWYgD Whitehorses Whiteblog: Native IO in WebLogic on Solaris 11 X64 (http://bit.ly/KGM4mp) NetBeans Team? Quick video of FindBugs Integration in #NetBeans IDE 7.2: http://ow.ly/aNece NetBeans Team #JavaFX Scene Builder Docs Updated for 2.2 and #NetBeans 7.2 dev builds: http://ow.ly/b7Nie Duncan Mills? New blog posting on implementing input field watermarks with ADF Faces 11.1.2 Click here #adf WebLogic Community? WebLogic Partner Community Newsletter May 2012 http://wp.me/p1LMIb-h4 OracleBlogs? UK OUG call for papersyour middleware success! http://ow.ly/1jNs49 Nicolas Lorain? Java tip: Deploying #JavaFX apps to multiple environments - JavaWorld http://buff.ly/KDADvu Adam Bien? Java EE and How to Specify The Unconventional With Convention Over Configuration [Free Article]: The free http://bit.ly/JEUkUf Owen Hughes and team?#Oracle #Exalogic #Performance: What? How? Why? Click here GlassFish? SecuritEE in the Cloud: Java EE 7 and the Cloud theme continue to move full steam ahead. In a PaaS environment http://bit.ly/K2RPte JDeveloper & ADF? How to Align Managed Bean Scope and Bean Data Control in Oracle ADF http://dlvr.it/1dngxQ Andrejus Baranovskis Missing New Feature in JDev (11.1.2.2.0) - ADF Methods Security http://fb.me/1jQM1enls OracleSupport_WLS? Tutorial on managing #HTTP Sessions in a #Weblogic #Cluster http://bit.ly/JshESe Oracle WebLogic? ZeroTurnaround developer report: #Spring keeps getting heavier, and #Java EE keeps getting lighter http://bit.ly/JDmKy2 JDeveloper & ADF? How to Search in Views - Part 4 || Oracle ADF http://dlvr.it/1dpDjZ WebLogic Community Java Message Service with Java and Spring Framework on Oracle WebLogic; Webcast May 15th 2012 http://wp.me/p1LMIb-gS Andreas Koop? new post ADF Bug or Feature? Non-Breaking Space outside required icon style http://bit.ly/KDZnUo Oracle WebLogic? Don't miss this month's WebLogic DevCast: WebLogic JMS and Spring JMS http://bit.ly/J6g2ST Tuesday May 15th 10:00am PT JDeveloper & ADF How To Disable SELECT COUNT Execution for ADF Table Rendering http://dlvr.it/1dqKH6 OracleSupport_WLS? #SSL and security has its own Information Center, http://bit.ly/LP8Vil for troubleshooting, install, config and more NetBeans Team? Featured #NetBeans plugin is @Codename_One for creating native apps for major mobile platforms: http://plugins.netbeans.org/ JDeveloper & ADF? Using JDeveloper HTTP Analyser to intercept/forward requests http://dlvr.it/1Yzl4J Nicolas Lorain? Create native looks for JavaFX applications: JavaFX-CSS-Themes · http://buff.ly/M0jel0 by Gregg Setzer Devoxx? Want to make the world a better place? Then get involved in Random Hacks of Kindness on June 2 - 3 in Belgium @ http://www.rhok.be #RHoK WebLogic Community top tweets WebLogic Partner Community – May 2012 Click here #WebLogicCommunity Michel Schildmeijer Oracle Traffic Director 11g http://lnkd.in/-mm3Vy Andrejus Baranovskis? Proactively Monitoring JDeveloper 11g IDE Heap Memory http://fb.me/16YZErPrx Arun Gupta? 80+ attendees building a #javaee6 application using NetBeans/WebLogic at Java Day, Istanbul fun times! http://pic.twitter.com/odY19daW A. Chatziantoniou? Just registered for the Oracle FMW Summer Camp in Lisbon. Looking forward to learn, meet friends and try to buy ice cream on the beach OTNArchBeat Another Myth Debunked: 200 Continuous Redeployments with WebLogic|@munz http://bit.ly/JiPyM7 Oracle WebLogic? Need to learn more on #WebLogic Server #JVM performance tuning? http://bit.ly/MN UxHx GlassFish? Dukes Choice Awards 2012 Nominations Are Open: 2012 Duke's Choice Award are open for nominations. These awards http://bit.ly/Ksk4U3 Justin Kestelyn? Major cloud-related announcements from Larry Ellison and Mark Hurd on June 6 http://bit.ly/KTJiII Nicolas Lorain Transparent Windows (Stage) with #JavaFX 2 : Adam Bien's Weblog http://j.mp/INgq8K WebLogic Community Web Services with JAX and Spring on WebLogic–Webcast May 30th 2012 #WebLogicCommunity #weblogic #opn JDeveloper & ADF Oracle ADF - How to work with Dates http://dlvr.it/1Y70zw OracleBlogs Web Services with JAX and Spring on WebLogicWebcast May 30th 2012 http://ow.ly/1k2WtO Adam Bien? Summer Java EE Workshops: 23.05, Amsterdam Airport Java EE Hacking, Without Airport. The dutch version of Airport http://bit.ly/JeP6hV JDeveloper & ADF ADF 11g: BC4J or EJB3. http://bit.ly/JVVFZF ADF EMG? Great discussion with JSF guru Andy Schwartz on the forum - 38 posts! Check it out: here Devoxx? Oracle (http://www.oracle.com ) joins Devoxx 2012 as the first Premium partner, welcome aboard! Nicolas Lorain Developing a Simple Todo Application using #JavaFX, #Java and #MongoDB- Part-1JavaBeat http://j.mp/IDGxLA Nicolas Lorain Preview of JavaFX 2.2 canvas feature > Harmonic Code: Death bitmaps could be beautiful... Part I http://buff.ly/KyAXg5 #JavaFX OTNArchBeat?? New York Coherence Special Interest Group (NYCSIG) - May 24 - NYC http://bit.ly/JzJcbT WebLogic Community iAS upgrade to WebLogic watch #C2B2 online seminar http://youtu.be/5m2CNUjBIGQ #WebLogicCommunity Ruth Collett? Join Oracle in #Joburg on May 21 for OTN Developer Day - sessions on #Java #JavaEE 6/7 and much more! http://bit.ly/IENwnD WebLogic Community? Sending out invitations to our advanced Fusion Middleware Summer Camps! Want to learn more register for the community Ruth Collett? Join @ArunGupta in Istanbul this Monday to hear the latest on #JavaEE 6/7 http://bit.ly/Je63cc GlassFish? NetBeans 7.2 Beta - Built for Speed, Deploy Apps to Oracle Cloud: NetBeans 7.2 Beta is now available. The http://bit.ly/LxMMTK Lucas Jellema My latest SlideShare upload : Java ain't scary - introducing Java to PL/SQ. here via @slideshare JDeveloper & ADF? #Developer #free#ADF training in #Scotland - June 13. More information: http://bit.ly/LbPLlf AMIS, Oracle & Java? AMIS behaalt als eerste in Nedeland de Oracle ADF specialisatie - Channelworld nieuwsChannelconnect: http://bit.ly/JzAcB4 WebLogic Community Web Services with JAX and Spring on WebLogic&ndash;Webcast May 30th 2012 http://wp.me/p1LMIb-gX Nicolas Lorain?@ JavaFX-based SimpleDateFormat Demonstrator http://j.mp/KFCVOi #JavaFX via Dustin Marx Oracle Exalogic? Are you an Oracle partner? There's news on the Oracle Partner Network about #Exalogic specializations - http://bit.ly/Mt3ANY JDeveloper & ADF Shorter URL for your ADF application http://dlvr.it/1XqNLY OTNArchBeat? Bay Area Coherence Special Interest Group (BACSIG) Meeting June 7 http://bit.ly/JAa0Lx OTNArchBeat? Java EE 6 Sample Application on WebLogic 12c: Conference Planner | @arungupta http://bit.ly/LPvof4 JDeveloper & ADF? Excellent example of Oracle ADF - Google Maps/Earth integration http://dlvr.it/1cbc80 JDeveloper & ADF Setting Up JDeveloper's Embedded WLS for MySQL http://dlvr.it/1c4b8P JDeveloper & ADF? Solution for Sharing Global User Data in ADF BC http://dlvr.it/1cc7SJ Java? Java Magazine May/June #javaee #javafx #javame #openJDK #hotspot #wicket #lotsmore http://ow.ly/aX07v Oracle WebLogic? http://bit.ly/JxQsnS if you have trouble finding the right #patchset when doing an upgrade to your #weblogic server OracleEnterpriseMgr 15 minutes to go before we start our Application Testing Suite 12.1 webcast. http://bit.ly/JHyTEe Learn from the lead PM what's new. #em12c Sten Vesterli Eating your own dog food - Oracle support site finally in ADF: http://lnkd.in/s6hg_p Adam Bien Project: "Jenever" (=poison) checked-in with GIT:here CU at http://workshops.adam-bien.com. Thanks for attending! OTNArchBeat Web Service Development with NetBeans and Testing with WebLogic Admin Console | @munz http://bit.ly/JcWk34 Please feel free to send us your news! And add your blog to our SOA blog wiki

    Read the article

  • Back to Basics: When does a .NET Assembly Dependency get loaded

    - by Rick Strahl
    When we work on typical day to day applications, it's easy to forget some of the core features of the .NET framework. For me personally it's been a long time since I've learned about some of the underlying CLR system level services even though I rely on them on a daily basis. I often think only about high level application constructs and/or high level framework functionality, but the low level stuff is often just taken for granted. Over the last week at DevConnections I had all sorts of low level discussions with other developers about the inner workings of this or that technology (especially in light of my Low Level ASP.NET Architecture talk and the Razor Hosting talk). One topic that came up a couple of times and ended up a point of confusion even amongst some seasoned developers (including some folks from Microsoft <snicker>) is when assemblies actually load into a .NET process. There are a number of different ways that assemblies are loaded in .NET. When you create a typical project assemblies usually come from: The Assembly reference list of the top level 'executable' project The Assembly references of referenced projects Dynamically loaded at runtime via AppDomain/Reflection loading In addition .NET automatically loads mscorlib (most of the System namespace) the boot process that hosts the .NET runtime in EXE apps, or some other kind of runtime hosting environment (runtime hosting in servers like IIS, SQL Server or COM Interop). In hosting environments the runtime host may also pre-load a bunch of assemblies on its own (for example the ASP.NET host requires all sorts of assemblies just to run itself, before ever routing into your user specific code). Assembly Loading The most obvious source of loaded assemblies is the top level application's assembly reference list. You can add assembly references to a top level application and those assembly references are then available to the application. In a nutshell, referenced assemblies are not immediately loaded - they are loaded on the fly as needed. So regardless of whether you have an assembly reference in a top level project, or a dependent assembly assemblies typically load on an as needed basis, unless explicitly loaded by user code. The same is true of dependent assemblies. To check this out I ran a simple test: I have a utility assembly Westwind.Utilities which is a general purpose library that can work in any type of project. Due to a couple of small requirements for encoding and a logging piece that allows logging Web content (dependency on HttpContext.Current) this utility library has a dependency on System.Web. Now System.Web is a pretty large assembly and generally you'd want to avoid adding it to a non-Web project if it can be helped. So I created a Console Application that loads my utility library: You can see that the top level Console app a reference to Westwind.Utilities and System.Data (beyond the core .NET libs). The Westwind.Utilities project on the other hand has quite a few dependencies including System.Web. I then add a main program that accesses only a simple utillity method in the Westwind.Utilities library that doesn't require any of the classes that access System.Web: static void Main(string[] args) { Console.WriteLine(StringUtils.NewStringId()); Console.ReadLine(); } StringUtils.NewStringId() calls into Westwind.Utilities, but it doesn't rely on System.Web. Any guesses what the assembly list looks like when I stop the code on the ReadLine() command? I'll wait here while you think about it… … … So, when I stop on ReadLine() and then fire up Process Explorer and check the assembly list I get: We can see here that .NET has not actually loaded any of the dependencies of the Westwind.Utilities assembly. Also not loaded is the top level System.Data reference even though it's in the dependent assembly list of the top level project. Since this particular function I called only uses core System functionality (contained in mscorlib) there's in fact nothing else loaded beyond the main application and my Westwind.Utilities assembly that contains the method accessed. None of the dependencies of Westwind.Utilities loaded. If you were to open the assembly in a disassembler like Reflector or ILSpy, you would however see all the compiled in dependencies. The referenced assemblies are in the dependency list and they are loadable, but they are not immediately loaded by the application. In other words the C# compiler and .NET linker are smart enough to figure out the dependencies based on the code that actually is referenced from your application and any dependencies cascading down into the dependencies from your top level application into the referenced assemblies. In the example above the usage requirement is pretty obvious since I'm only calling a single static method and then exiting the app, but in more complex applications these dependency relationships become very complicated - however it's all taken care of by the compiler and linker figuring out what types and members are actually referenced and including only those assemblies that are in fact referenced in your code or required by any of your dependencies. The good news here is: That if you are referencing an assembly that has a dependency on something like System.Web in a few places that are not actually accessed by any of your code or any dependent assembly code that you are calling, that assembly is never loaded into memory! Some Hosting Environments pre-load Assemblies The load behavior can vary however. In Console and desktop applications we have full control over assembly loading so we see the core CLR behavior. However other environments like ASP.NET for example will preload referenced assemblies explicitly as part of the startup process - primarily to minimize load conflicts. Specifically ASP.NET pre-loads all assemblies referenced in the assembly list and the /bin folder. So in Web applications it definitely pays to minimize your top level assemblies if they are not used. Understanding when Assemblies Load To clarify and see it actually happen what I described in the first example , let's look at a couple of other scenarios. To see assemblies loading at runtime in real time lets create a utility function to print out loaded assemblies to the console: public static void PrintAssemblies() { var assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (var assembly in assemblies) { Console.WriteLine(assembly.GetName()); } } Now let's look at the first scenario where I have class method that references internally uses System.Web. In the first scenario lets add a method to my main program like this: static void Main(string[] args) { Console.WriteLine(StringUtils.NewStringId()); Console.ReadLine(); PrintAssemblies(); } public static void WebLogEntry() { var entry = new WebLogEntry(); entry.UpdateFromRequest(); Console.WriteLine(entry.QueryString); } UpdateFromWebRequest() internally accesses HttpContext.Current to read some information of the ASP.NET Request object so it clearly needs a reference System.Web to work. In this first example, the method that holds the calling code is never called, but exists as a static method that can potentially be called externally at some point. What do you think will happen here with the assembly loading? Will System.Web load in this example? No - it doesn't. Because the WebLogEntry() method is never called by the mainline application (or anywhere else) System.Web is not loaded. .NET dynamically loads assemblies as code that needs it is called. No code references the WebLogEntry() method and so System.Web is never loaded. Next, let's add the call to this method, which should trigger System.Web to be loaded because a dependency exists. Let's change the code to: static void Main(string[] args) { Console.WriteLine(StringUtils.NewStringId()); Console.WriteLine("--- Before:"); PrintAssemblies(); WebLogEntry(); Console.WriteLine("--- After:"); PrintAssemblies(); Console.ReadLine(); } public static void WebLogEntry() { var entry = new WebLogEntry(); entry.UpdateFromRequest(); Console.WriteLine(entry.QueryString); } Looking at the code now, when do you think System.Web will be loaded? Will the before list include it? Yup System.Web gets loaded, but only after it's actually referenced. In fact, just until before the call to UpdateFromRequest() System.Web is not loaded - it only loads when the method is actually called and requires the reference in the executing code. Moral of the Story So what have we learned - or maybe remembered again? Dependent Assembly References are not pre-loaded when an application starts (by default) Dependent Assemblies that are not referenced by executing code are never loaded Dependent Assemblies are just in time loaded when first referenced in code All of this is nothing new - .NET has always worked like this. But it's good to have a refresher now and then and go through the exercise of seeing it work in action. It's not one of those things we think about everyday, and as I found out last week, I couldn't remember exactly how it worked since it's been so long since I've learned about this. And apparently I'm not the only one as several other people I had discussions with in relation to loaded assemblies also didn't recall exactly what should happen or assumed incorrectly that just having a reference automatically loads the assembly. The moral of the story for me is: Trying at all costs to eliminate an assembly reference from a component is not quite as important as it's often made out to be. For example, the Westwind.Utilities module described above has a logging component, including a Web specific logging entry that supports pulling information from the active HTTP Context. Adding that feature requires a reference to System.Web. Should I worry about this in the scope of this library? Probably not, because if I don't use that one class of nearly a hundred, System.Web never gets pulled into the parent process. IOW, System.Web only loads when I use that specific feature and if I am, well I clearly have to be running in a Web environment anyway to use it realistically. The alternative would be considerably uglier: Pulling out the WebLogEntry class and sticking it into another assembly and breaking up the logging code. In this case - definitely not worth it. So, .NET definitely goes through some pretty nifty optimizations to ensure that it loads only what it needs and in most cases you can just rely on .NET to do the right thing. Sometimes though assembly loading can go wrong (especially when signed and versioned local assemblies are involved), but that's subject for a whole other post…© Rick Strahl, West Wind Technologies, 2005-2012Posted in .NET  CSharp   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Passing multiple simple POST Values to ASP.NET Web API

    - by Rick Strahl
    A few weeks backs I posted a blog post  about what does and doesn't work with ASP.NET Web API when it comes to POSTing data to a Web API controller. One of the features that doesn't work out of the box - somewhat unexpectedly -  is the ability to map POST form variables to simple parameters of a Web API method. For example imagine you have this form and you want to post this data to a Web API end point like this via AJAX: <form> Name: <input type="name" name="name" value="Rick" /> Value: <input type="value" name="value" value="12" /> Entered: <input type="entered" name="entered" value="12/01/2011" /> <input type="button" id="btnSend" value="Send" /> </form> <script type="text/javascript"> $("#btnSend").click( function() { $.post("samples/PostMultipleSimpleValues?action=kazam", $("form").serialize(), function (result) { alert(result); }); }); </script> or you might do this more explicitly by creating a simple client map and specifying the POST values directly by hand:$.post("samples/PostMultipleSimpleValues?action=kazam", { name: "Rick", value: 1, entered: "12/01/2012" }, $("form").serialize(), function (result) { alert(result); }); On the wire this generates a simple POST request with Url Encoded values in the content:POST /AspNetWebApi/samples/PostMultipleSimpleValues?action=kazam HTTP/1.1 Host: localhost User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: application/json Connection: keep-alive Content-Type: application/x-www-form-urlencoded; charset=UTF-8 X-Requested-With: XMLHttpRequest Referer: http://localhost/AspNetWebApi/FormPostTest.html Content-Length: 41 Pragma: no-cache Cache-Control: no-cachename=Rick&value=12&entered=12%2F10%2F2011 Seems simple enough, right? We are basically posting 3 form variables and 1 query string value to the server. Unfortunately Web API can't handle request out of the box. If I create a method like this:[HttpPost] public string PostMultipleSimpleValues(string name, int value, DateTime entered, string action = null) { return string.Format("Name: {0}, Value: {1}, Date: {2}, Action: {3}", name, value, entered, action); }You'll find that you get an HTTP 404 error and { "Message": "No HTTP resource was found that matches the request URI…"} Yes, it's possible to pass multiple POST parameters of course, but Web API expects you to use Model Binding for this - mapping the post parameters to a strongly typed .NET object, not to single parameters. Alternately you can also accept a FormDataCollection parameter on your API method to get a name value collection of all POSTed values. If you're using JSON only, using the dynamic JObject/JValue objects might also work. ModelBinding is fine in many use cases, but can quickly become overkill if you only need to pass a couple of simple parameters to many methods. Especially in applications with many, many AJAX callbacks the 'parameter mapping type' per method signature can lead to serious class pollution in a project very quickly. Simple POST variables are also commonly used in AJAX applications to pass data to the server, even in many complex public APIs. So this is not an uncommon use case, and - maybe more so a behavior that I would have expected Web API to support natively. The question "Why aren't my POST parameters mapping to Web API method parameters" is already a frequent one… So this is something that I think is fairly important, but unfortunately missing in the base Web API installation. Creating a Custom Parameter Binder Luckily Web API is greatly extensible and there's a way to create a custom Parameter Binding to provide this functionality! Although this solution took me a long while to find and then only with the help of some folks Microsoft (thanks Hong Mei!!!), it's not difficult to hook up in your own projects. It requires one small class and a GlobalConfiguration hookup. Web API parameter bindings allow you to intercept processing of individual parameters - they deal with mapping parameters to the signature as well as converting the parameters to the actual values that are returned. Here's the implementation of the SimplePostVariableParameterBinding class:public class SimplePostVariableParameterBinding : HttpParameterBinding { private const string MultipleBodyParameters = "MultipleBodyParameters"; public SimplePostVariableParameterBinding(HttpParameterDescriptor descriptor) : base(descriptor) { } /// <summary> /// Check for simple binding parameters in POST data. Bind POST /// data as well as query string data /// </summary> public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { // Body can only be read once, so read and cache it NameValueCollection col = TryReadBody(actionContext.Request); string stringValue = null; if (col != null) stringValue = col[Descriptor.ParameterName]; // try reading query string if we have no POST/PUT match if (stringValue == null) { var query = actionContext.Request.GetQueryNameValuePairs(); if (query != null) { var matches = query.Where(kv => kv.Key.ToLower() == Descriptor.ParameterName.ToLower()); if (matches.Count() > 0) stringValue = matches.First().Value; } } object value = StringToType(stringValue); // Set the binding result here SetValue(actionContext, value); // now, we can return a completed task with no result TaskCompletionSource<AsyncVoid> tcs = new TaskCompletionSource<AsyncVoid>(); tcs.SetResult(default(AsyncVoid)); return tcs.Task; } private object StringToType(string stringValue) { object value = null; if (stringValue == null) value = null; else if (Descriptor.ParameterType == typeof(string)) value = stringValue; else if (Descriptor.ParameterType == typeof(int)) value = int.Parse(stringValue, CultureInfo.CurrentCulture); else if (Descriptor.ParameterType == typeof(Int32)) value = Int32.Parse(stringValue, CultureInfo.CurrentCulture); else if (Descriptor.ParameterType == typeof(Int64)) value = Int64.Parse(stringValue, CultureInfo.CurrentCulture); else if (Descriptor.ParameterType == typeof(decimal)) value = decimal.Parse(stringValue, CultureInfo.CurrentCulture); else if (Descriptor.ParameterType == typeof(double)) value = double.Parse(stringValue, CultureInfo.CurrentCulture); else if (Descriptor.ParameterType == typeof(DateTime)) value = DateTime.Parse(stringValue, CultureInfo.CurrentCulture); else if (Descriptor.ParameterType == typeof(bool)) { value = false; if (stringValue == "true" || stringValue == "on" || stringValue == "1") value = true; } else value = stringValue; return value; } /// <summary> /// Read and cache the request body /// </summary> /// <param name="request"></param> /// <returns></returns> private NameValueCollection TryReadBody(HttpRequestMessage request) { object result = null; // try to read out of cache first if (!request.Properties.TryGetValue(MultipleBodyParameters, out result)) { // parsing the string like firstname=Hongmei&lastname=Ge result = request.Content.ReadAsFormDataAsync().Result; request.Properties.Add(MultipleBodyParameters, result); } return result as NameValueCollection; } private struct AsyncVoid { } }   The ExecuteBindingAsync method is fired for each parameter that is mapped and sent for conversion. This custom binding is fired only if the incoming parameter is a simple type (that gets defined later when I hook up the binding), so this binding never fires on complex types or if the first type is not a simple type. For the first parameter of a request the Binding first reads the request body into a NameValueCollection and caches that in the request.Properties collection. The request body can only be read once, so the first parameter request reads it and then caches it. Subsequent parameters then use the cached POST value collection. Once the form collection is available the value of the parameter is read, and the value is translated into the target type requested by the Descriptor. SetValue writes out the value to be mapped. Once you have the ParameterBinding in place, the binding has to be assigned. This is done along with all other Web API configuration tasks at application startup in global.asax's Application_Start:GlobalConfiguration.Configuration.ParameterBindingRules .Insert(0, (HttpParameterDescriptor descriptor) => { var supportedMethods = descriptor.ActionDescriptor.SupportedHttpMethods; // Only apply this binder on POST and PUT operations if (supportedMethods.Contains(HttpMethod.Post) || supportedMethods.Contains(HttpMethod.Put)) { var supportedTypes = new Type[] { typeof(string), typeof(int), typeof(decimal), typeof(double), typeof(bool), typeof(DateTime) }; if (supportedTypes.Where(typ => typ == descriptor.ParameterType).Count() > 0) return new SimplePostVariableParameterBinding(descriptor); } // let the default bindings do their work return null; });   The ParameterBindingRules.Insert method takes a delegate that checks which type of requests it should handle. The logic here checks whether the request is POST or PUT and whether the parameter type is a simple type that is supported. Web API calls this delegate once for each method signature it tries to map and the delegate returns null to indicate it's not handling this parameter, or it returns a new parameter binding instance - in this case the SimplePostVariableParameterBinding. Once the parameter binding and this hook up code is in place, you can now pass simple POST values to methods with simple parameters. The examples I showed above should now work in addition to the standard bindings. Summary Clearly this is not easy to discover. I spent quite a bit of time digging through the Web API source trying to figure this out on my own without much luck. It took Hong Mei at Micrsoft to provide a base example as I asked around so I can't take credit for this solution :-). But once you know where to look, Web API is brilliantly extensible to make it relatively easy to customize the parameter behavior. I'm very stoked that this got resolved  - in the last two months I've had two customers with projects that decided not to use Web API in AJAX heavy SPA applications because this POST variable mapping wasn't available. This might actually change their mind to still switch back and take advantage of the many great features in Web API. I too frequently use plain POST variables for communicating with server AJAX handlers and while I could have worked around this (with untyped JObject or the Form collection mostly), having proper POST to parameter mapping makes things much easier. I said this in my last post on POST data and say it again here: I think POST to method parameter mapping should have been shipped in the box with Web API, because without knowing about this limitation the expectation is that simple POST variables map to parameters just like query string values do. I hope Microsoft considers including this type of functionality natively in the next version of Web API natively or at least as a built-in HttpParameterBinding that can be just added. This is especially true, since this binding doesn't affect existing bindings. Resources SimplePostVariableParameterBinding Source on GitHub Global.asax hookup source Mapping URL Encoded Post Values in  ASP.NET Web API© Rick Strahl, West Wind Technologies, 2005-2012Posted in Web Api  AJAX   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Creating a Dynamic DataRow for easier DataRow Syntax

    - by Rick Strahl
    I've been thrown back into an older project that uses DataSets and DataRows as their entity storage model. I have several applications internally that I still maintain that run just fine (and I sometimes wonder if this wasn't easier than all this ORM crap we deal with with 'newer' improved technology today - but I disgress) but use this older code. For the most part DataSets/DataTables/DataRows are abstracted away in a pseudo entity model, but in some situations like queries DataTables and DataRows are still surfaced to the business layer. Here's an example. Here's a business object method that runs dynamic query and the code ends up looping over the result set using the ugly DataRow Array syntax:public int UpdateAllSafeTitles() { int result = this.Execute("select pk, title, safetitle from " + Tablename + " where EntryType=1", "TPks"); if (result < 0) return result; result = 0; foreach (DataRow row in this.DataSet.Tables["TPks"].Rows) { string title = row["title"] as string; string safeTitle = row["safeTitle"] as string; int pk = (int)row["pk"]; string newSafeTitle = this.GetSafeTitle(title); if (newSafeTitle != safeTitle) { this.ExecuteNonQuery("update " + this.Tablename + " set safeTitle=@safeTitle where pk=@pk", this.CreateParameter("@safeTitle",newSafeTitle), this.CreateParameter("@pk",pk) ); result++; } } return result; } The problem with looping over DataRow objecs is two fold: The array syntax is tedious to type and not real clear to look at, and explicit casting is required in order to do anything useful with the values. I've highlighted the place where this matters. Using the DynamicDataRow class I'll show in a minute this code can be changed to look like this:public int UpdateAllSafeTitles() { int result = this.Execute("select pk, title, safetitle from " + Tablename + " where EntryType=1", "TPks"); if (result < 0) return result; result = 0; foreach (DataRow row in this.DataSet.Tables["TPks"].Rows) { dynamic entry = new DynamicDataRow(row); string newSafeTitle = this.GetSafeTitle(entry.title); if (newSafeTitle != entry.safeTitle) { this.ExecuteNonQuery("update " + this.Tablename + " set safeTitle=@safeTitle where pk=@pk", this.CreateParameter("@safeTitle",newSafeTitle), this.CreateParameter("@pk",entry.pk) ); result++; } } return result; } The code looks much a bit more natural and describes what's happening a little nicer as well. Well, using the new dynamic features in .NET it's actually quite easy to implement the DynamicDataRow class. Creating your own custom Dynamic Objects .NET 4.0 introduced the Dynamic Language Runtime (DLR) and opened up a whole bunch of new capabilities for .NET applications. The dynamic type is an easy way to avoid Reflection and directly access members of 'dynamic' or 'late bound' objects at runtime. There's a lot of very subtle but extremely useful stuff that dynamic does (especially for COM Interop scenearios) but in its simplest form it often allows you to do away with manual Reflection at runtime. In addition you can create DynamicObject implementations that can perform  custom interception of member accesses and so allow you to provide more natural access to more complex or awkward data structures like the DataRow that I use as an example here. Bascially you can subclass DynamicObject and then implement a few methods (TryGetMember, TrySetMember, TryInvokeMember) to provide the ability to return dynamic results from just about any data structure using simple property/method access. In the code above, I created a custom DynamicDataRow class which inherits from DynamicObject and implements only TryGetMember and TrySetMember. Here's what simple class looks like:/// <summary> /// This class provides an easy way to turn a DataRow /// into a Dynamic object that supports direct property /// access to the DataRow fields. /// /// The class also automatically fixes up DbNull values /// (null into .NET and DbNUll to DataRow) /// </summary> public class DynamicDataRow : DynamicObject { /// <summary> /// Instance of object passed in /// </summary> DataRow DataRow; /// <summary> /// Pass in a DataRow to work off /// </summary> /// <param name="instance"></param> public DynamicDataRow(DataRow dataRow) { DataRow = dataRow; } /// <summary> /// Returns a value from a DataRow items array. /// If the field doesn't exist null is returned. /// DbNull values are turned into .NET nulls. /// /// </summary> /// <param name="binder"></param> /// <param name="result"></param> /// <returns></returns> public override bool TryGetMember(GetMemberBinder binder, out object result) { result = null; try { result = DataRow[binder.Name]; if (result == DBNull.Value) result = null; return true; } catch { } result = null; return false; } /// <summary> /// Property setter implementation tries to retrieve value from instance /// first then into this object /// </summary> /// <param name="binder"></param> /// <param name="value"></param> /// <returns></returns> public override bool TrySetMember(SetMemberBinder binder, object value) { try { if (value == null) value = DBNull.Value; DataRow[binder.Name] = value; return true; } catch {} return false; } } To demonstrate the basic features here's a short test: [TestMethod] [ExpectedException(typeof(RuntimeBinderException))] public void BasicDataRowTests() { DataTable table = new DataTable("table"); table.Columns.Add( new DataColumn() { ColumnName = "Name", DataType=typeof(string) }); table.Columns.Add( new DataColumn() { ColumnName = "Entered", DataType=typeof(DateTime) }); table.Columns.Add(new DataColumn() { ColumnName = "NullValue", DataType = typeof(string) }); DataRow row = table.NewRow(); DateTime now = DateTime.Now; row["Name"] = "Rick"; row["Entered"] = now; row["NullValue"] = null; // converted in DbNull dynamic drow = new DynamicDataRow(row); string name = drow.Name; DateTime entered = drow.Entered; string nulled = drow.NullValue; Assert.AreEqual(name, "Rick"); Assert.AreEqual(entered,now); Assert.IsNull(nulled); // this should throw a RuntimeBinderException Assert.AreEqual(entered,drow.enteredd); } The DynamicDataRow requires a custom constructor that accepts a single parameter that sets the DataRow. Once that's done you can access property values that match the field names. Note that types are automatically converted - no type casting is needed in the code you write. The class also automatically converts DbNulls to regular nulls and vice versa which is something that makes it much easier to deal with data returned from a database. What's cool here isn't so much the functionality - even if I'd prefer to leave DataRow behind ASAP -  but the fact that we can create a dynamic type that uses a DataRow as it's 'DataSource' to serve member values. It's pretty useful feature if you think about it, especially given how little code it takes to implement. By implementing these two simple methods we get to provide two features I was complaining about at the beginning that are missing from the DataRow: Direct Property Syntax Automatic Type Casting so no explicit casts are required Caveats As cool and easy as this functionality is, it's important to understand that it doesn't come for free. The dynamic features in .NET are - well - dynamic. Which means they are essentially evaluated at runtime (late bound). Rather than static typing where everything is compiled and linked by the compiler/linker, member invokations are looked up at runtime and essentially call into your custom code. There's some overhead in this. Direct invocations - the original code I showed - is going to be faster than the equivalent dynamic code. However, in the above code the difference of running the dynamic code and the original data access code was very minor. The loop running over 1500 result records took on average 13ms with the original code and 14ms with the dynamic code. Not exactly a serious performance bottleneck. One thing to remember is that Microsoft optimized the DLR code significantly so that repeated calls to the same operations are routed very efficiently which actually makes for very fast evaluation. The bottom line for performance with dynamic code is: Make sure you test and profile your code if you think that there might be a performance issue. However, in my experience with dynamic types so far performance is pretty good for repeated operations (ie. in loops). While usually a little slower the perf hit is a lot less typically than equivalent Reflection work. Although the code in the second example looks like standard object syntax, dynamic is not static code. It's evaluated at runtime and so there's no type recognition until runtime. This means no Intellisense at development time, and any invalid references that call into 'properties' (ie. fields in the DataRow) that don't exist still cause runtime errors. So in the case of the data row you still get a runtime error if you mistype a column name:// this should throw a RuntimeBinderException Assert.AreEqual(entered,drow.enteredd); Dynamic - Lots of uses The arrival of Dynamic types in .NET has been met with mixed emotions. Die hard .NET developers decry dynamic types as an abomination to the language. After all what dynamic accomplishes goes against all that a static language is supposed to provide. On the other hand there are clearly scenarios when dynamic can make life much easier (COM Interop being one place). Think of the possibilities. What other data structures would you like to expose to a simple property interface rather than some sort of collection or dictionary? And beyond what I showed here you can also implement 'Method missing' behavior on objects with InvokeMember which essentially allows you to create dynamic methods. It's all very flexible and maybe just as important: It's easy to do. There's a lot of power hidden in this seemingly simple interface. Your move…© Rick Strahl, West Wind Technologies, 2005-2011Posted in CSharp  .NET   Tweet (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Visual Studio 2010 and SQLCLR: Some Good, Some Bad

    - by Adam Machanic
    This past week I've been trying out Visual Studio 2010 for SQLCLR development. Verdict: A couple of nice things, a couple not so nice. In the interest of keeping things somewhat positive around here, we'll start with the good stuff : Pre-deployment and post-deployment scripts are built in. This is great, especially if you're working with features such as ordered TVFs, which Visual Studio 2008 never properly supported. In 2010 you can stick the ALTER FUNCTION in a post-deployment script and you'll...(read more)

    Read the article

  • Creating a JSONP Formatter for ASP.NET Web API

    - by Rick Strahl
    Out of the box ASP.NET WebAPI does not include a JSONP formatter, but it's actually very easy to create a custom formatter that implements this functionality. JSONP is one way to allow Browser based JavaScript client applications to bypass cross-site scripting limitations and serve data from the non-current Web server. AJAX in Web Applications uses the XmlHttp object which by default doesn't allow access to remote domains. There are number of ways around this limitation <script> tag loading and JSONP is one of the easiest and semi-official ways that you can do this. JSONP works by combining JSON data and wrapping it into a function call that is executed when the JSONP data is returned. If you use a tool like jQUery it's extremely easy to access JSONP content. Imagine that you have a URL like this: http://RemoteDomain/aspnetWebApi/albums which on an HTTP GET serves some data - in this case an array of record albums. This URL is always directly accessible from an AJAX request if the URL is on the same domain as the parent request. However, if that URL lives on a separate server it won't be easily accessible to an AJAX request. Now, if  the server can serve up JSONP this data can be accessed cross domain from a browser client. Using jQuery it's really easy to retrieve the same data with JSONP:function getAlbums() { $.getJSON("http://remotedomain/aspnetWebApi/albums?callback=?",null, function (albums) { alert(albums.length); }); } The resulting callback the same as if the call was to a local server when the data is returned. jQuery deserializes the data and feeds it into the method. Here the array is received and I simply echo back the number of items returned. From here your app is ready to use the data as needed. This all works fine - as long as the server can serve the data with JSONP. What does JSONP look like? JSONP is a pretty simple 'protocol'. All it does is wrap a JSON response with a JavaScript function call. The above result from the JSONP call looks like this:Query17103401925975181569_1333408916499( [{"Id":"34043957","AlbumName":"Dirty Deeds Done Dirt Cheap",…},{…}] ) The way JSONP works is that the client (jQuery in this case) sends of the request, receives the response and evals it. The eval basically executes the function and deserializes the JSON inside of the function. It's actually a little more complex for the framework that does this, but that's the gist of what happens. JSONP works by executing the code that gets returned from the JSONP call. JSONP and ASP.NET Web API As mentioned previously, JSONP support is not natively in the box with ASP.NET Web API. But it's pretty easy to create and plug-in a custom formatter that provides this functionality. The following code is based on Christian Weyers example but has been updated to the latest Web API CodePlex bits, which changes the implementation a bit due to the way dependent objects are exposed differently in the latest builds. Here's the code:  using System; using System.IO; using System.Net; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Threading.Tasks; using System.Web; using System.Net.Http; namespace Westwind.Web.WebApi { /// <summary> /// Handles JsonP requests when requests are fired with /// text/javascript or application/json and contain /// a callback= (configurable) query string parameter /// /// Based on Christian Weyers implementation /// https://github.com/thinktecture/Thinktecture.Web.Http/blob/master/Thinktecture.Web.Http/Formatters/JsonpFormatter.cs /// </summary> public class JsonpFormatter : JsonMediaTypeFormatter { public JsonpFormatter() { SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json")); SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/javascript")); //MediaTypeMappings.Add(new UriPathExtensionMapping("jsonp", "application/json")); JsonpParameterName = "callback"; } /// <summary> /// Name of the query string parameter to look for /// the jsonp function name /// </summary> public string JsonpParameterName {get; set; } /// <summary> /// Captured name of the Jsonp function that the JSON call /// is wrapped in. Set in GetPerRequestFormatter Instance /// </summary> private string JsonpCallbackFunction; public override bool CanWriteType(Type type) { return true; } /// <summary> /// Override this method to capture the Request object /// and look for the query string parameter and /// create a new instance of this formatter. /// /// This is the only place in a formatter where the /// Request object is available. /// </summary> /// <param name="type"></param> /// <param name="request"></param> /// <param name="mediaType"></param> /// <returns></returns> public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType) { var formatter = new JsonpFormatter() { JsonpCallbackFunction = GetJsonCallbackFunction(request) }; return formatter; } /// <summary> /// Override to wrap existing JSON result with the /// JSONP function call /// </summary> /// <param name="type"></param> /// <param name="value"></param> /// <param name="stream"></param> /// <param name="contentHeaders"></param> /// <param name="transportContext"></param> /// <returns></returns> public override Task WriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, TransportContext transportContext) { if (!string.IsNullOrEmpty(JsonpCallbackFunction)) { return Task.Factory.StartNew(() => { var writer = new StreamWriter(stream); writer.Write( JsonpCallbackFunction + "("); writer.Flush(); base.WriteToStreamAsync(type, value, stream, contentHeaders, transportContext).Wait(); writer.Write(")"); writer.Flush(); }); } else { return base.WriteToStreamAsync(type, value, stream, contentHeaders, transportContext); } } /// <summary> /// Retrieves the Jsonp Callback function /// from the query string /// </summary> /// <returns></returns> private string GetJsonCallbackFunction(HttpRequestMessage request) { if (request.Method != HttpMethod.Get) return null; var query = HttpUtility.ParseQueryString(request.RequestUri.Query); var queryVal = query[this.JsonpParameterName]; if (string.IsNullOrEmpty(queryVal)) return null; return queryVal; } } } Note again that this code will not work with the Beta bits of Web API - it works only with post beta bits from CodePlex and hopefully this will continue to work until RTM :-) This code is a bit different from Christians original code as the API has changed. The biggest change is that the Read/Write functions no longer receive a global context object that gives access to the Request and Response objects as the older bits did. Instead you now have to override the GetPerRequestFormatterInstance() method, which receives the Request as a parameter. You can capture the Request there, or use the request to pick up the values you need and store them on the formatter. Note that I also have to create a new instance of the formatter since I'm storing request specific state on the instance (information whether the callback= querystring is present) so I return a new instance of this formatter. Other than that the code should be straight forward: The code basically writes out the function pre- and post-amble and the defers to the base stream to retrieve the JSON to wrap the function call into. The code uses the Async APIs to write this data out (this will take some getting used to seeing all over the place for me). Hooking up the JsonpFormatter Once you've created a formatter, it has to be added to the request processing sequence by adding it to the formatter collection. Web API is configured via the static GlobalConfiguration object.  protected void Application_Start(object sender, EventArgs e) { // Verb Routing RouteTable.Routes.MapHttpRoute( name: "AlbumsVerbs", routeTemplate: "albums/{title}", defaults: new { title = RouteParameter.Optional, controller = "AlbumApi" } ); GlobalConfiguration .Configuration .Formatters .Insert(0, new Westwind.Web.WebApi.JsonpFormatter()); }   That's all it takes. Note that I added the formatter at the top of the list of formatters, rather than adding it to the end which is required. The JSONP formatter needs to fire before any other JSON formatter since it relies on the JSON formatter to encode the actual JSON data. If you reverse the order the JSONP output never shows up. So, in general when adding new formatters also try to be aware of the order of the formatters as they are added. Resources JsonpFormatter Code on GitHub© Rick Strahl, West Wind Technologies, 2005-2012Posted in Web Api   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Project Navigation and File Nesting in ASP.NET MVC Projects

    - by Rick Strahl
    More and more I’m finding myself getting lost in the files in some of my larger Web projects. There’s so much freaking content to deal with – HTML Views, several derived CSS pages, page level CSS, script libraries, application wide scripts and page specific script files etc. etc. Thankfully I use Resharper and the Ctrl-T Go to Anything which autocompletes you to any file, type, member rapidly. Awesome except when I forget – or when I’m not quite sure of the name of what I’m looking for. Project navigation is still important. Sometimes while working on a project I seem to have 30 or more files open and trying to locate another new file to open in the solution often ends up being a mental exercise – “where did I put that thing?” It’s those little hesitations that tend to get in the way of workflow frequently. To make things worse most NuGet packages for client side frameworks and scripts, dump stuff into folders that I generally don’t use. I’ve never been a fan of the ‘Content’ folder in MVC which is just an empty layer that doesn’t serve much of a purpose. It’s usually the first thing I nuke in every MVC project. To me the project root is where the actual content for a site goes – is there really a need to add another folder to force another path into every resource you use? It’s ugly and also inefficient as it adds additional bytes to every resource link you embed into a page. Alternatives I’ve been playing around with different folder layouts recently and found that moving my cheese around has actually made project navigation much easier. In this post I show a couple of things I’ve found useful and maybe you find some of these useful as well or at least get some ideas what can be changed to provide better project flow. The first thing I’ve been doing is add a root Code folder and putting all server code into that. I’m a big fan of treating the Web project root folder as my Web root folder so all content comes from the root without unneeded nesting like the Content folder. By moving all server code out of the root tree (except for Code) the root tree becomes a lot cleaner immediately as you remove Controllers, App_Start, Models etc. and move them underneath Code. Yes this adds another folder level for server code, but it leaves only code related things in one place that’s easier to jump back and forth in. Additionally I find myself doing a lot less with server side code these days, more with client side code so I want the server code separated from that. The root folder itself then serves as the root content folder. Specifically I have the Views folder below it, as well as the Css and Scripts folders which serve to hold only common libraries and global CSS and Scripts code. These days of building SPA style application, I also tend to have an App folder there where I keep my application specific JavaScript files, as well as HTML View templates for client SPA apps like Angular. Here’s an example of what this looks like in a relatively small project: The goal is to keep things that are related together, so I don’t end up jumping around so much in the solution to get to specific project items. The Code folder may irk some of you and hark back to the days of the App_Code folder in non Web-Application projects, but these days I find myself messing with a lot less server side code and much more with client side files – HTML, CSS and JavaScript. Generally I work on a single controller at a time – once that’s open it’s open that’s typically the only server code I work with regularily. Business logic lives in another project altogether, so other than the controller and maybe ViewModels there’s not a lot of code being accessed in the Code folder. So throwing that off the root and isolating seems like an easy win. Nesting Page specific content In a lot of my existing applications that are pure server side MVC application perhaps with some JavaScript associated with them , I tend to have page level javascript and css files. For these types of pages I actually prefer the local files stored in the same folder as the parent view. So typically I have a .css and .js files with the same name as the view in the same folder. This looks something like this: In order for this to work you have to also make a configuration change inside of the /Views/web.config file, as the Views folder is blocked with the BlockViewHandler that prohibits access to content from that folder. It’s easy to fix by changing the path from * to *.cshtml or *.vbhtml so that view retrieval is blocked:<system.webServer> <handlers> <remove name="BlockViewHandler"/> <add name="BlockViewHandler" path="*.cshtml" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" /> </handlers> </system.webServer> With this in place, from inside of your Views you can then reference those same resources like this:<link href="~/Views/Admin/QuizPrognosisItems.css" rel="stylesheet" /> and<script src="~/Views/Admin/QuizPrognosisItems.js"></script> which works fine. JavaScript and CSS files in the Views folder deploy just like the .cshtml files do and can be referenced from this folder as well. Making this happen is not really as straightforward as it should be with just Visual Studio unfortunately, as there’s no easy way to get the file nesting from the VS IDE directly (you have to modify the .csproj file). However, Mads Kristensen has a nice Visual Studio Add-in that provides file nesting via a short cut menu option. Using this you can select each of the ‘child’ files and then nest them under a parent file. In the case above I select the .js and .css files and nest them underneath the .cshtml view. I was even toying with the idea of throwing the controller.cs files into the Views folder, but that’s maybe going a little too far :-) It would work however as Visual Studio doesn’t publish .cs files and the compiler doesn’t care where the files live. There are lots of options and if you think that would make life easier it’s another option to help group related things together. Are there any downside to this? Possibly – if you’re using automated minification/packaging tools like ASP.NET Bundling or Grunt/Gulp with Uglify, it becomes a little harder to group script and css files for minification as you may end up looking in multiple folders instead of a single folder. But – again that’s a one time configuration step that’s easily handled and much less intrusive then constantly having to search for files in your project. Client Side Folders The particular project shown above in the screen shots above is a traditional server side ASP.NET MVC application with most content rendered into server side Razor pages. There’s a fair amount of client side stuff happening on these pages as well – specifically several of these pages are self contained single page Angular applications that deal with 1 or maybe 2 separate views and the layout I’ve shown above really focuses on the server side aspect where there are Razor views with related script and css resources. For applications that are more client centric and have a lot more script and HTML template based content I tend to use the same layout for the server components, but the client side code can often be broken out differently. In SPA type applications I tend to follow the App folder approach where all the application pieces that make the SPA applications end up below the App folder. Here’s what that looks like for me – here this is an AngularJs project: In this case the App folder holds both the application specific js files, and the partial HTML views that get loaded into this single SPA page application. In this particular Angular SPA application that has controllers linked to particular partial views, I prefer to keep the script files that are associated with the views – Angular Js Controllers in this case – with the actual partials. Again I like the proximity of the view with the main code associated with the view, because 90% of the UI application code that gets written is handled between these two files. This approach works well, but only if controllers are fairly closely aligned with the partials. If you have many smaller sub-controllers or lots of directives where the alignment between views and code is more segmented this approach starts falling apart and you’ll probably be better off with separate folders in js folder. Following Angular conventions you’d have controllers/directives/services etc. folders. Please note that I’m not saying any of these ways are right or wrong  – this is just what has worked for me and why! Skipping Project Navigation altogether with Resharper I’ve talked a bit about project navigation in the project tree, which is a common way to navigate and which we all use at least some of the time, but if you use a tool like Resharper – which has Ctrl-T to jump to anything, you can quickly navigate with a shortcut key and autocomplete search. Here’s what Resharper’s jump to anything looks like: Resharper’s Goto Anything box lets you type and quick search over files, classes and members of the entire solution which is a very fast and powerful way to find what you’re looking for in your project, by passing the solution explorer altogether. As long as you remember to use (which I sometimes don’t) and you know what you’re looking for it’s by far the quickest way to find things in a project. It’s a shame that this sort of a simple search interface isn’t part of the native Visual Studio IDE. Work how you like to work Ultimately it all comes down to workflow and how you like to work, and what makes *you* more productive. Following pre-defined patterns is great for consistency, as long as they don’t get in the way you work. A lot of the default folder structures in Visual Studio for ASP.NET MVC were defined when things were done differently. These days we’re dealing with a lot more diverse project content than when ASP.NET MVC was originally introduced and project organization definitely is something that can get in the way if it doesn’t fit your workflow. So take a look and see what works well and what might benefit from organizing files differently. As so many things with ASP.NET, as things evolve and tend to get more complex I’ve found that I end up fighting some of the conventions. The good news is that you don’t have to follow the conventions and you have the freedom to do just about anything that works for you. Even though what I’ve shown here diverges from conventions, I don’t think anybody would stumble over these relatively minor changes and not immediately figure out where things live, even in larger projects. But nevertheless think long and hard before breaking those conventions – if there isn’t a good reason to break them or the changes don’t provide improved workflow then it’s not worth it. Break the rules, but only if there’s a quantifiable benefit. You may not agree with how I’ve chosen to divert from the standard project structures in this article, but maybe it gives you some ideas of how you can mix things up to make your existing project flow a little nicer and make it easier to navigate for your environment. © Rick Strahl, West Wind Technologies, 2005-2014Posted in ASP.NET  MVC   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Rejuvenated: Script Creates and Drops for Candidate Keys and Referencing Foreign Keys

    - by Adam Machanic
    Once upon a time it was 2004, and I wrote what I have to say was a pretty cool little script . (Yes, I know the post is dated 2006, but that's because I dropped the ball and failed to back-date the posts when I moved them over here from my prior blog space.) The impetus for creating this script was (and is) simple: Changing keys can be a painful experience. Sometimes you want to make a clustered key nonclustered, or a nonclustered key clustered. Or maybe you want to add a column to the key. Or remove...(read more)

    Read the article

  • T-SQL Tuesday #005: Reporting

    - by Adam Machanic
    This month's T-SQL Tuesday is hosted by Aaron Nelson of SQLVariations . Aaron has picked a really fantastic topic: Reporting . Reporting is a lot more than just SSRS. Whether or not you realize it, you deal with all sorts of reports every day. Server up-time reports. Application activity reports. And even DMVs, which as Aaron points out are simply reports about what's going on inside of SQL Server. This month's topic can be twisted any number of ways, so have fun and be creative! I'm really looking...(read more)

    Read the article

  • Five Things To Which SQL Server Should Say "Goodbye and Good Riddance"

    - by Adam Machanic
    I was tagged by master blogger Aaron Bertrand and asked to identify five things that should be removed from SQL Server. Easy enough, or so I thought... 1) Tempdb . But I should qualify that a bit. Tempdb is absolutely necessary for SQL Server to properly function, but in its current state is easily the number one bottleneck in the majority of SQL Server instances. Many other DBMS vendors abandoned the "monolithic, instance-scoped temporary data space" years ago, yet SQL Server soldiers on, putting...(read more)

    Read the article

  • Delete directory by referencing symbolic link

    - by Adam
    To set up the question, imagine this scenario: mkdir ~/temp cd ~/ ln -s temp temporary rm -rf temporary, rm -f temporary, and rm temporary each will remove the symbolic link but leave the directory ~/temp/. I have a script where the name of the symbolic link is easily derived but the name of the linked directory is not. Is there a way to remove the directory by referencing the symbolic link, short of parsing the name of the directory from ls -od ~/temporary?

    Read the article

  • SQL University: Parallelism Week - Part 2, Query Processing

    - by Adam Machanic
    Welcome back for the second part of Parallelism Week here at SQL University . Get your pencils ready, and make sure to raise your hand if you have a question. Last time we covered the necessary background material to help you understand how the SQL Server Operating System schedules its many active threads, and the differences between its behavior and that of the Windows operating system's scheduler. We also discussed some of the variations on the theme of parallel processing. Today we'll take a look...(read more)

    Read the article

  • Routing to a Controller with no View in Angular

    - by Rick Strahl
    I've finally had some time to put Angular to use this week in a small project I'm working on for fun. Angular's routing is great and makes it real easy to map URL routes to controllers and model data into views. But what if you don't actually need a view, if you effectively need a headless controller that just runs code, but doesn't render a view?Preserve the ViewWhen Angular navigates a route and and presents a new view, it loads the controller and then renders the view from scratch. Views are not cached or stored, but displayed and then removed. So if you have routes configured like this:'use strict'; // Declare app level module which depends on filters, and services window.myApp = angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'myApp.controllers']). config(['$routeProvider', function($routeProvider) { $routeProvider.when('/map', { template: "partials/map.html ", controller: 'mapController', reloadOnSearch: false, animation: 'slide' }); … $routeProvider.otherwise({redirectTo: '/map'}); }]); Angular routes to the mapController and then re-renders the map.html template with the new data from the $scope filled in.But, but… I don't want a new View!Now in most cases this works just fine. If I'm rendering plain DOM content, or textboxes in a form interface that is all fine and dandy - it's perfectly fine to completely re-render the UI.But in some cases, the UI that's being managed has state and shouldn't be redrawn. In this case the main page in question has a Google Map on it. The map is  going to be manipulated throughout the lifetime of the application and the rest of the pages. In my application I have a toolbar on the bottom and the rest of the content is replaced/switched out by the Angular Views:The problem is that the map shouldn't be redrawn each time the Location view is activated. It should maintain its state, such as the current position selected (which can move), and shouldn't redraw due to the overhead of re-rendering the initial map.Originally I set up the map, exactly like all my other views - as a partial, that is rendered with a separate file, but that didn't work.The Workaround - Controller Only RoutesThe workaround for this goes decidedly against Angular's way of doing things:Setting up a Template-less RouteIn-lining the map view directly into the main pageHiding and showing the map view manuallyLet's see how this works.Controller Only RouteThe template-less route is basically a route that doesn't have any template to render. This is not directly supported by Angular, but thankfully easy to fake. The end goal here is that I want to simply have the Controller fire and then have the controller manage the display of the already active view by hiding and showing the map and any other view content, in effect bypassing Angular's view display management.In short - I want a controller action, but no view rendering.The controller-only or template-less route looks like this: $routeProvider.when('/map', { template: " ", // just fire controller controller: 'mapController', animation: 'slide' });Notice I'm using the template property rather than templateUrl (used in the first example above), which allows specifying a string template, and leaving it blank. The template property basically allows you to provide a templated string using Angular's HandleBar like binding syntax which can be useful at times. You can use plain strings or strings with template code in the template, or as I'm doing here a blank string to essentially fake 'just clear the view'. In-lined ViewSo if there's no view where does the HTML go? Because I don't want Angular to manage the view the map markup is in-lined directly into the page. So instead of rendering the map into the Angular view container, the content is simply set up as inline HTML to display as a sibling to the view container.<div id="MapContent" data-icon="LocationIcon" ng-controller="mapController" style="display:none"> <div class="headerbar"> <div class="right-header" style="float:right"> <a id="btnShowSaveLocationDialog" class="iconbutton btn btn-sm" href="#/saveLocation" style="margin-right: 2px;"> <i class="icon-ok icon-2x" style="color: lightgreen; "></i> Save Location </a> </div> <div class="left-header">GeoCrumbs</div> </div> <div class="clearfix"></div> <div id="Message"> <i id="MessageIcon"></i> <span id="MessageText"></span> </div> <div id="Map" class="content-area"> </div> </div> <div id="ViewPlaceholder" ng-view></div>Note that there's the #MapContent element and the #ViewPlaceHolder. The #MapContent is my static map view that is always 'live' and is initially hidden. It is initially hidden and doesn't get made visible until the MapController controller activates it which does the initial rendering of the map. After that the element is persisted with the map data already loaded and any future access only updates the map with new locations/pins etc.Note that default route is assigned to the mapController, which means that the mapController is fired right as the page loads, which is actually a good thing in this case, as the map is the cornerstone of this app that is manipulated by some of the other controllers/views.The Controller handles some UISince there's effectively no view activation with the template-less route, the controller unfortunately has to take over some UI interaction directly. Specifically it has to swap the hidden state between the map and any of the other views.Here's what the controller looks like:myApp.controller('mapController', ["$scope", "$routeParams", "locationData", function($scope, $routeParams, locationData) { $scope.locationData = locationData.location; $scope.locationHistory = locationData.locationHistory; if ($routeParams.mode == "currentLocation") { bc.getCurrentLocation(false); } bc.showMap(false,"#LocationIcon"); }]);bc.showMap is responsible for a couple of display tasks that hide/show the views/map and for activating/deactivating icons. The code looks like this:this.showMap = function (hide,selActiveIcon) { if (!hide) $("#MapContent").show(); else { $("#MapContent").hide(); } self.fitContent(); if (selActiveIcon) { $(".iconbutton").removeClass("active"); $(selActiveIcon).addClass("active"); } };Each of the other controllers in the app also call this function when they are activated to basically hide the map and make the View Content area visible. The map controller makes the map.This is UI code and calling this sort of thing from controllers is generally not recommended, but I couldn't figure out a way using directives to make this work any more easily than this. It'd be easy to hide and show the map and view container using a flag an ng-show, but it gets tricky because of scoping of the $scope. I would have to resort to storing this setting on the $rootscope which I try to avoid. The same issues exists with the icons.It sure would be nice if Angular had a way to explicitly specify that a View shouldn't be destroyed when another view is activated, so currently this workaround is required. Searching around, I saw a number of whacky hacks to get around this, but this solution I'm using here seems much easier than any of that I could dig up even if it doesn't quite fit the 'Angular way'.Angular nice, until it's notOverall I really like Angular and the way it works although it took me a bit of time to get my head around how all the pieces fit together. Once I got the idea how the app/routes, the controllers and views snap together, putting together Angular pages becomes fairly straightforward. You can get quite a bit done never going beyond those basics. For most common things Angular's default routing and view presentation works very well.But, when you do something a bit more complex, where there are multiple dependencies or as in this case where Angular doesn't appear to support a feature that's absolutely necessary, you're on your own. Finding information on more advanced topics is not trivial especially since versions are changing so rapidly and the low level behaviors are changing frequently so finding something that works is often an exercise in trial and error. Not that this is surprising. Angular is a complex piece of kit as are all the frameworks that try to hack JavaScript into submission to do something that it was really never designed to. After all everything about a framework like Angular is an elaborate hack. A lot of shit has to happen to make this all work together and at that Angular (and Ember, Durandel etc.) are pretty amazing pieces of JavaScript code. So no harm, no foul, but I just can't help feeling like working in toy sandbox at times :-)© Rick Strahl, West Wind Technologies, 2005-2013Posted in Angular  JavaScript   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Internet doesn't work by default

    - by Adam Martinez
    After upgrading to Precise, I am required to run 'sudo dhclient eth0' in a terminal in order to get the internet to work. Everything worked perfectly fine on Oneiric, so It's really puzzling me. I'm thinking it could possibly be something with the kernel, but who knows. Output of dmesg: [ 0.247891] system 00:01: [io 0x0290-0x030f] has been reserved [ 0.247896] system 00:01: [io 0x0290-0x0297] has been reserved [ 0.247901] system 00:01: [io 0x0880-0x088f] has been reserved [ 0.247908] system 00:01: Plug and Play ACPI device, IDs PNP0c02 (active) [ 0.247931] pnp 00:02: [dma 4] [ 0.247935] pnp 00:02: [io 0x0000-0x000f] [ 0.247939] pnp 00:02: [io 0x0080-0x0090] [ 0.247943] pnp 00:02: [io 0x0094-0x009f] [ 0.247947] pnp 00:02: [io 0x00c0-0x00df] [ 0.248033] pnp 00:02: Plug and Play ACPI device, IDs PNP0200 (active) [ 0.248125] pnp 00:03: [io 0x0070-0x0073] [ 0.248187] pnp 00:03: Plug and Play ACPI device, IDs PNP0b00 (active) [ 0.248205] pnp 00:04: [io 0x0061] [ 0.248260] pnp 00:04: Plug and Play ACPI device, IDs PNP0800 (active) [ 0.248277] pnp 00:05: [io 0x00f0-0x00ff] [ 0.248292] pnp 00:05: [irq 13] [ 0.248348] pnp 00:05: Plug and Play ACPI device, IDs PNP0c04 (active) [ 0.248583] pnp 00:06: [io 0x03f0-0x03f5] [ 0.248588] pnp 00:06: [io 0x03f7] [ 0.248597] pnp 00:06: [irq 6] [ 0.248601] pnp 00:06: [dma 2] [ 0.248690] pnp 00:06: Plug and Play ACPI device, IDs PNP0700 (active) [ 0.248998] pnp 00:07: [io 0x03f8-0x03ff] [ 0.249008] pnp 00:07: [irq 4] [ 0.249122] pnp 00:07: Plug and Play ACPI device, IDs PNP0501 (active) [ 0.249479] pnp 00:08: [io 0x0400-0x04bf] [ 0.249584] system 00:08: [io 0x0400-0x04bf] has been reserved [ 0.249591] system 00:08: Plug and Play ACPI device, IDs PNP0c02 (active) [ 0.249628] pnp 00:09: [mem 0xffb80000-0xffbfffff] [ 0.249690] pnp 00:09: Plug and Play ACPI device, IDs INT0800 (active) [ 0.250049] pnp 00:0a: [mem 0xe0000000-0xefffffff] [ 0.250167] system 00:0a: [mem 0xe0000000-0xefffffff] has been reserved [ 0.250173] system 00:0a: Plug and Play ACPI device, IDs PNP0c02 (active) [ 0.250302] pnp 00:0b: [mem 0x000f0000-0x000fffff] [ 0.250307] pnp 00:0b: [mem 0x7ff00000-0x7fffffff] [ 0.250311] pnp 00:0b: [mem 0xfed00000-0xfed000ff] [ 0.250316] pnp 00:0b: [mem 0x0000046e-0x0000056d] [ 0.250320] pnp 00:0b: [mem 0x7fee0000-0x7fefffff] [ 0.250324] pnp 00:0b: [mem 0x00000000-0x0009ffff] [ 0.250328] pnp 00:0b: [mem 0x00100000-0x7fedffff] [ 0.250332] pnp 00:0b: [mem 0xfec00000-0xfec00fff] [ 0.250336] pnp 00:0b: [mem 0xfed14000-0xfed1dfff] [ 0.250341] pnp 00:0b: [mem 0xfed20000-0xfed9ffff] [ 0.250345] pnp 00:0b: [mem 0xfee00000-0xfee00fff] [ 0.250349] pnp 00:0b: [mem 0xffb00000-0xffb7ffff] [ 0.250353] pnp 00:0b: [mem 0xfff00000-0xffffffff] [ 0.250357] pnp 00:0b: [mem 0x000e0000-0x000effff] [ 0.250409] pnp 00:0b: disabling [mem 0x0000046e-0x0000056d] because it overlaps 0000:01:00.0 BAR 6 [mem 0x00000000-0x0007ffff pref] [ 0.250419] pnp 00:0b: disabling [mem 0x0000046e-0x0000056d disabled] because it overlaps 0000:03:00.0 BAR 6 [mem 0x00000000-0x0000ffff pref] [ 0.250430] pnp 00:0b: disabling [mem 0x0000046e-0x0000056d disabled] because it overlaps 0000:04:00.0 BAR 6 [mem 0x00000000-0x0001ffff pref] [ 0.250524] system 00:0b: [mem 0x000f0000-0x000fffff] could not be reserved [ 0.250530] system 00:0b: [mem 0x7ff00000-0x7fffffff] has been reserved [ 0.250536] system 00:0b: [mem 0xfed00000-0xfed000ff] has been reserved [ 0.250541] system 00:0b: [mem 0x7fee0000-0x7fefffff] could not be reserved [ 0.250547] system 00:0b: [mem 0x00000000-0x0009ffff] could not be reserved [ 0.250552] system 00:0b: [mem 0x00100000-0x7fedffff] could not be reserved [ 0.250558] system 00:0b: [mem 0xfec00000-0xfec00fff] could not be reserved [ 0.250563] system 00:0b: [mem 0xfed14000-0xfed1dfff] has been reserved [ 0.250568] system 00:0b: [mem 0xfed20000-0xfed9ffff] has been reserved [ 0.250574] system 00:0b: [mem 0xfee00000-0xfee00fff] has been reserved [ 0.250579] system 00:0b: [mem 0xffb00000-0xffb7ffff] has been reserved [ 0.250585] system 00:0b: [mem 0xfff00000-0xffffffff] has been reserved [ 0.250590] system 00:0b: [mem 0x000e0000-0x000effff] has been reserved [ 0.250596] system 00:0b: Plug and Play ACPI device, IDs PNP0c01 (active) [ 0.250614] pnp: PnP ACPI: found 12 devices [ 0.250617] ACPI: ACPI bus type pnp unregistered [ 0.250624] PnPBIOS: Disabled by ACPI PNP [ 0.288725] PCI: max bus depth: 1 pci_try_num: 2 [ 0.288786] pci 0000:01:00.0: BAR 6: assigned [mem 0xfb000000-0xfb07ffff pref] [ 0.288792] pci 0000:00:01.0: PCI bridge to [bus 01-01] [ 0.288797] pci 0000:00:01.0: bridge window [io 0xa000-0xafff] [ 0.288804] pci 0000:00:01.0: bridge window [mem 0xf8000000-0xfbffffff] [ 0.288811] pci 0000:00:01.0: bridge window [mem 0xd0000000-0xdfffffff 64bit pref] [ 0.288820] pci 0000:00:1c.0: PCI bridge to [bus 02-02] [ 0.288825] pci 0000:00:1c.0: bridge window [io 0x9000-0x9fff] [ 0.288833] pci 0000:00:1c.0: bridge window [mem 0xfdb00000-0xfdbfffff] [ 0.288840] pci 0000:00:1c.0: bridge window [mem 0xfd800000-0xfd8fffff 64bit pref] [ 0.288851] pci 0000:03:00.0: BAR 6: assigned [mem 0xfde00000-0xfde0ffff pref] [ 0.288856] pci 0000:00:1c.4: PCI bridge to [bus 03-03] [ 0.288861] pci 0000:00:1c.4: bridge window [io 0xd000-0xdfff] [ 0.288869] pci 0000:00:1c.4: bridge window [mem 0xfd700000-0xfd7fffff] [ 0.288876] pci 0000:00:1c.4: bridge window [mem 0xfde00000-0xfdefffff 64bit pref] [ 0.288887] pci 0000:04:00.0: BAR 6: assigned [mem 0xfdc00000-0xfdc1ffff pref] [ 0.288891] pci 0000:00:1c.5: PCI bridge to [bus 04-04] [ 0.288897] pci 0000:00:1c.5: bridge window [io 0xb000-0xbfff] [ 0.288904] pci 0000:00:1c.5: bridge window [mem 0xfdd00000-0xfddfffff] [ 0.288911] pci 0000:00:1c.5: bridge window [mem 0xfdc00000-0xfdcfffff 64bit pref] [ 0.288920] pci 0000:00:1e.0: PCI bridge to [bus 05-05] [ 0.288926] pci 0000:00:1e.0: bridge window [io 0xc000-0xcfff] [ 0.288933] pci 0000:00:1e.0: bridge window [mem 0xfda00000-0xfdafffff] [ 0.288940] pci 0000:00:1e.0: bridge window [mem 0xfd900000-0xfd9fffff 64bit pref] [ 0.288971] pci 0000:00:01.0: PCI INT A -> GSI 16 (level, low) -> IRQ 16 [ 0.288979] pci 0000:00:01.0: setting latency timer to 64 [ 0.288991] pci 0000:00:1c.0: PCI INT A -> GSI 16 (level, low) -> IRQ 16 [ 0.288998] pci 0000:00:1c.0: setting latency timer to 64 [ 0.289008] pci 0000:00:1c.4: PCI INT A -> GSI 16 (level, low) -> IRQ 16 [ 0.289014] pci 0000:00:1c.4: setting latency timer to 64 [ 0.289030] pci 0000:00:1c.5: PCI INT B -> GSI 17 (level, low) -> IRQ 17 [ 0.289037] pci 0000:00:1c.5: setting latency timer to 64 [ 0.289047] pci 0000:00:1e.0: setting latency timer to 64 [ 0.289054] pci_bus 0000:00: resource 4 [io 0x0000-0x0cf7] [ 0.289058] pci_bus 0000:00: resource 5 [io 0x0d00-0xffff] [ 0.289063] pci_bus 0000:00: resource 6 [mem 0x000a0000-0x000bffff] [ 0.289067] pci_bus 0000:00: resource 7 [mem 0x000c0000-0x000dffff] [ 0.289072] pci_bus 0000:00: resource 8 [mem 0x7ff00000-0xfebfffff] [ 0.289077] pci_bus 0000:01: resource 0 [io 0xa000-0xafff] [ 0.289081] pci_bus 0000:01: resource 1 [mem 0xf8000000-0xfbffffff] [ 0.289086] pci_bus 0000:01: resource 2 [mem 0xd0000000-0xdfffffff 64bit pref] [ 0.289092] pci_bus 0000:02: resource 0 [io 0x9000-0x9fff] [ 0.289096] pci_bus 0000:02: resource 1 [mem 0xfdb00000-0xfdbfffff] [ 0.289101] pci_bus 0000:02: resource 2 [mem 0xfd800000-0xfd8fffff 64bit pref] [ 0.289106] pci_bus 0000:03: resource 0 [io 0xd000-0xdfff] [ 0.289110] pci_bus 0000:03: resource 1 [mem 0xfd700000-0xfd7fffff] [ 0.289115] pci_bus 0000:03: resource 2 [mem 0xfde00000-0xfdefffff 64bit pref] [ 0.289120] pci_bus 0000:04: resource 0 [io 0xb000-0xbfff] [ 0.289124] pci_bus 0000:04: resource 1 [mem 0xfdd00000-0xfddfffff] [ 0.289129] pci_bus 0000:04: resource 2 [mem 0xfdc00000-0xfdcfffff 64bit pref] [ 0.289134] pci_bus 0000:05: resource 0 [io 0xc000-0xcfff] [ 0.289138] pci_bus 0000:05: resource 1 [mem 0xfda00000-0xfdafffff] [ 0.289143] pci_bus 0000:05: resource 2 [mem 0xfd900000-0xfd9fffff 64bit pref] [ 0.289148] pci_bus 0000:05: resource 4 [io 0x0000-0x0cf7] [ 0.289152] pci_bus 0000:05: resource 5 [io 0x0d00-0xffff] [ 0.289157] pci_bus 0000:05: resource 6 [mem 0x000a0000-0x000bffff] [ 0.289161] pci_bus 0000:05: resource 7 [mem 0x000c0000-0x000dffff] [ 0.289166] pci_bus 0000:05: resource 8 [mem 0x7ff00000-0xfebfffff] [ 0.289233] NET: Registered protocol family 2 [ 0.289360] IP route cache hash table entries: 32768 (order: 5, 131072 bytes) [ 0.289754] TCP established hash table entries: 131072 (order: 8, 1048576 bytes) [ 0.290351] TCP bind hash table entries: 65536 (order: 7, 524288 bytes) [ 0.290670] TCP: Hash tables configured (established 131072 bind 65536) [ 0.290674] TCP reno registered [ 0.290680] UDP hash table entries: 512 (order: 2, 16384 bytes) [ 0.290703] UDP-Lite hash table entries: 512 (order: 2, 16384 bytes) [ 0.290868] NET: Registered protocol family 1 [ 0.290911] pci 0000:00:1a.0: PCI INT A -> GSI 16 (level, low) -> IRQ 16 [ 0.290932] pci 0000:00:1a.0: PCI INT A disabled [ 0.290956] pci 0000:00:1a.1: PCI INT B -> GSI 21 (level, low) -> IRQ 21 [ 0.290975] pci 0000:00:1a.1: PCI INT B disabled [ 0.290992] pci 0000:00:1a.2: PCI INT D -> GSI 19 (level, low) -> IRQ 19 [ 0.291012] pci 0000:00:1a.2: PCI INT D disabled [ 0.291031] pci 0000:00:1a.7: PCI INT C -> GSI 18 (level, low) -> IRQ 18 [ 0.291068] pci 0000:00:1a.7: PCI INT C disabled [ 0.291104] pci 0000:00:1d.0: PCI INT A -> GSI 23 (level, low) -> IRQ 23 [ 0.291123] pci 0000:00:1d.0: PCI INT A disabled [ 0.291135] pci 0000:00:1d.1: PCI INT B -> GSI 19 (level, low) -> IRQ 19 [ 0.291155] pci 0000:00:1d.1: PCI INT B disabled [ 0.291166] pci 0000:00:1d.2: PCI INT C -> GSI 18 (level, low) -> IRQ 18 [ 0.291185] pci 0000:00:1d.2: PCI INT C disabled [ 0.291198] pci 0000:00:1d.7: PCI INT A -> GSI 23 (level, low) -> IRQ 23 [ 0.291219] pci 0000:00:1d.7: PCI INT A disabled [ 0.291258] pci 0000:01:00.0: Boot video device [ 0.291273] PCI: CLS 4 bytes, default 64 [ 0.291857] audit: initializing netlink socket (disabled) [ 0.291876] type=2000 audit(1336753420.284:1): initialized [ 0.337724] highmem bounce pool size: 64 pages [ 0.337734] HugeTLB registered 2 MB page size, pre-allocated 0 pages [ 0.349241] VFS: Disk quotas dquot_6.5.2 [ 0.349365] Dquot-cache hash table entries: 1024 (order 0, 4096 bytes) [ 0.350418] fuse init (API version 7.17) [ 0.350611] msgmni has been set to 1685 [ 0.351179] Block layer SCSI generic (bsg) driver version 0.4 loaded (major 253) [ 0.351229] io scheduler noop registered [ 0.351233] io scheduler deadline registered [ 0.351247] io scheduler cfq registered (default) [ 0.351450] pcieport 0000:00:01.0: setting latency timer to 64 [ 0.351502] pcieport 0000:00:01.0: irq 40 for MSI/MSI-X [ 0.351585] pcieport 0000:00:1c.0: setting latency timer to 64 [ 0.351639] pcieport 0000:00:1c.0: irq 41 for MSI/MSI-X [ 0.351728] pcieport 0000:00:1c.4: setting latency timer to 64 [ 0.351779] pcieport 0000:00:1c.4: irq 42 for MSI/MSI-X [ 0.351875] pcieport 0000:00:1c.5: setting latency timer to 64 [ 0.351927] pcieport 0000:00:1c.5: irq 43 for MSI/MSI-X [ 0.352094] pci_hotplug: PCI Hot Plug PCI Core version: 0.5 [ 0.352143] pciehp: PCI Express Hot Plug Controller Driver version: 0.4 [ 0.352311] intel_idle: MWAIT substates: 0x22220 [ 0.352315] intel_idle: does not run on family 6 model 23 [ 0.352446] input: Power Button as /devices/LNXSYSTM:00/device:00/PNP0C0C:00/input/input0 [ 0.352455] ACPI: Power Button [PWRB] [ 0.352556] input: Power Button as /devices/LNXSYSTM:00/LNXPWRBN:00/input/input1 [ 0.352562] ACPI: Power Button [PWRF] [ 0.352650] ACPI: Fan [FAN] (on) [ 0.355667] thermal LNXTHERM:00: registered as thermal_zone0 [ 0.355673] ACPI: Thermal Zone [THRM] (26 C) [ 0.355750] ERST: Table is not found! [ 0.355753] GHES: HEST is not enabled! [ 0.355898] Serial: 8250/16550 driver, 32 ports, IRQ sharing enabled [ 0.376332] serial8250: ttyS0 at I/O 0x3f8 (irq = 4) is a 16550A [ 0.376582] isapnp: Scanning for PnP cards... [ 0.709133] Freeing initrd memory: 13792k freed [ 0.729743] isapnp: No Plug & Play device found [ 0.816786] 00:07: ttyS0 at I/O 0x3f8 (irq = 4) is a 16550A [ 0.832385] Linux agpgart interface v0.103 [ 0.835605] brd: module loaded [ 0.837138] loop: module loaded [ 0.837452] ata_piix 0000:00:1f.2: version 2.13 [ 0.837473] ata_piix 0000:00:1f.2: PCI INT A -> GSI 19 (level, low) -> IRQ 19 [ 0.837480] ata_piix 0000:00:1f.2: MAP [ P0 P2 P1 P3 ] [ 0.837546] ata_piix 0000:00:1f.2: setting latency timer to 64 [ 0.838099] scsi0 : ata_piix [ 0.838253] scsi1 : ata_piix [ 0.839183] ata1: SATA max UDMA/133 cmd 0xf900 ctl 0xf800 bmdma 0xf500 irq 19 [ 0.839192] ata2: SATA max UDMA/133 cmd 0xf700 ctl 0xf600 bmdma 0xf508 irq 19 [ 0.839239] ata_piix 0000:00:1f.5: PCI INT A -> GSI 19 (level, low) -> IRQ 19 [ 0.839246] ata_piix 0000:00:1f.5: MAP [ P0 -- P1 -- ] [ 0.839300] ata_piix 0000:00:1f.5: setting latency timer to 64 [ 0.839708] scsi2 : ata_piix [ 0.839841] scsi3 : ata_piix [ 0.840301] ata3: SATA max UDMA/133 cmd 0xf200 ctl 0xf100 bmdma 0xee00 irq 19 [ 0.840308] ata4: SATA max UDMA/133 cmd 0xf000 ctl 0xef00 bmdma 0xee08 irq 19 [ 0.840429] pata_acpi 0000:03:00.0: PCI INT A -> GSI 16 (level, low) -> IRQ 16 [ 0.840467] pata_acpi 0000:03:00.0: setting latency timer to 64 [ 0.840488] pata_acpi 0000:03:00.0: PCI INT A disabled [ 0.841159] Fixed MDIO Bus: probed [ 0.841205] tun: Universal TUN/TAP device driver, 1.6 [ 0.841210] tun: (C) 1999-2004 Max Krasnyansky <[email protected]> [ 0.841322] PPP generic driver version 2.4.2 [ 0.841515] ehci_hcd: USB 2.0 'Enhanced' Host Controller (EHCI) Driver [ 0.841542] ehci_hcd 0000:00:1a.7: PCI INT C -> GSI 18 (level, low) -> IRQ 18 [ 0.841567] ehci_hcd 0000:00:1a.7: setting latency timer to 64 [ 0.841573] ehci_hcd 0000:00:1a.7: EHCI Host Controller [ 0.841658] ehci_hcd 0000:00:1a.7: new USB bus registered, assigned bus number 1 [ 0.845582] ehci_hcd 0000:00:1a.7: cache line size of 4 is not supported [ 0.845610] ehci_hcd 0000:00:1a.7: irq 18, io mem 0xfdfff000 [ 0.860022] ehci_hcd 0000:00:1a.7: USB 2.0 started, EHCI 1.00 [ 0.860264] hub 1-0:1.0: USB hub found [ 0.860272] hub 1-0:1.0: 6 ports detected [ 0.860404] ehci_hcd 0000:00:1d.7: PCI INT A -> GSI 23 (level, low) -> IRQ 23 [ 0.860424] ehci_hcd 0000:00:1d.7: setting latency timer to 64 [ 0.860430] ehci_hcd 0000:00:1d.7: EHCI Host Controller [ 0.860512] ehci_hcd 0000:00:1d.7: new USB bus registered, assigned bus number 2 [ 0.864413] ehci_hcd 0000:00:1d.7: cache line size of 4 is not supported [ 0.864438] ehci_hcd 0000:00:1d.7: irq 23, io mem 0xfdffe000 [ 0.880021] ehci_hcd 0000:00:1d.7: USB 2.0 started, EHCI 1.00 [ 0.880227] hub 2-0:1.0: USB hub found [ 0.880234] hub 2-0:1.0: 6 ports detected [ 0.880369] ohci_hcd: USB 1.1 'Open' Host Controller (OHCI) Driver [ 0.880396] uhci_hcd: USB Universal Host Controller Interface driver [ 0.880431] uhci_hcd 0000:00:1a.0: PCI INT A -> GSI 16 (level, low) -> IRQ 16 [ 0.880443] uhci_hcd 0000:00:1a.0: setting latency timer to 64 [ 0.880449] uhci_hcd 0000:00:1a.0: UHCI Host Controller [ 0.880529] uhci_hcd 0000:00:1a.0: new USB bus registered, assigned bus number 3 [ 0.880574] uhci_hcd 0000:00:1a.0: irq 16, io base 0x0000ff00 [ 0.880803] hub 3-0:1.0: USB hub found [ 0.880811] hub 3-0:1.0: 2 ports detected [ 0.880929] uhci_hcd 0000:00:1a.1: PCI INT B -> GSI 21 (level, low) -> IRQ 21 [ 0.880940] uhci_hcd 0000:00:1a.1: setting latency timer to 64 [ 0.880946] uhci_hcd 0000:00:1a.1: UHCI Host Controller [ 0.881039] uhci_hcd 0000:00:1a.1: new USB bus registered, assigned bus number 4 [ 0.881081] uhci_hcd 0000:00:1a.1: irq 21, io base 0x0000fe00 [ 0.881302] hub 4-0:1.0: USB hub found [ 0.881310] hub 4-0:1.0: 2 ports detected [ 0.881427] uhci_hcd 0000:00:1a.2: PCI INT D -> GSI 19 (level, low) -> IRQ 19 [ 0.881438] uhci_hcd 0000:00:1a.2: setting latency timer to 64 [ 0.881443] uhci_hcd 0000:00:1a.2: UHCI Host Controller [ 0.881523] uhci_hcd 0000:00:1a.2: new USB bus registered, assigned bus number 5 [ 0.881551] uhci_hcd 0000:00:1a.2: irq 19, io base 0x0000fd00 [ 0.881774] hub 5-0:1.0: USB hub found [ 0.881781] hub 5-0:1.0: 2 ports detected [ 0.881899] uhci_hcd 0000:00:1d.0: PCI INT A -> GSI 23 (level, low) -> IRQ 23 [ 0.881910] uhci_hcd 0000:00:1d.0: setting latency timer to 64 [ 0.881915] uhci_hcd 0000:00:1d.0: UHCI Host Controller [ 0.881993] uhci_hcd 0000:00:1d.0: new USB bus registered, assigned bus number 6 [ 0.882021] uhci_hcd 0000:00:1d.0: irq 23, io base 0x0000fc00 [ 0.882244] hub 6-0:1.0: USB hub found [ 0.882252] hub 6-0:1.0: 2 ports detected [ 0.882370] uhci_hcd 0000:00:1d.1: PCI INT B -> GSI 19 (level, low) -> IRQ 19 [ 0.882381] uhci_hcd 0000:00:1d.1: setting latency timer to 64 [ 0.882386] uhci_hcd 0000:00:1d.1: UHCI Host Controller [ 0.882467] uhci_hcd 0000:00:1d.1: new USB bus registered, assigned bus number 7 [ 0.882495] uhci_hcd 0000:00:1d.1: irq 19, io base 0x0000fb00 [ 0.882735] hub 7-0:1.0: USB hub found [ 0.882742] hub 7-0:1.0: 2 ports detected [ 0.882858] uhci_hcd 0000:00:1d.2: PCI INT C -> GSI 18 (level, low) -> IRQ 18 [ 0.882869] uhci_hcd 0000:00:1d.2: setting latency timer to 64 [ 0.882875] uhci_hcd 0000:00:1d.2: UHCI Host Controller [ 0.882954] uhci_hcd 0000:00:1d.2: new USB bus registered, assigned bus number 8 [ 0.882982] uhci_hcd 0000:00:1d.2: irq 18, io base 0x0000fa00 [ 0.883205] hub 8-0:1.0: USB hub found [ 0.883213] hub 8-0:1.0: 2 ports detected [ 0.883435] usbcore: registered new interface driver libusual [ 0.883535] i8042: PNP: No PS/2 controller found. Probing ports directly. [ 0.883926] serio: i8042 KBD port at 0x60,0x64 irq 1 [ 0.883936] serio: i8042 AUX port at 0x60,0x64 irq 12 [ 0.884187] mousedev: PS/2 mouse device common for all mice [ 0.884433] rtc_cmos 00:03: RTC can wake from S4 [ 0.884582] rtc_cmos 00:03: rtc core: registered rtc_cmos as rtc0 [ 0.884612] rtc0: alarms up to one month, 242 bytes nvram, hpet irqs [ 0.884719] device-mapper: uevent: version 1.0.3 [ 0.884854] device-mapper: ioctl: 4.22.0-ioctl (2011-10-19) initialised: [email protected] [ 0.884917] EISA: Probing bus 0 at eisa.0 [ 0.884921] EISA: Cannot allocate resource for mainboard [ 0.884925] Cannot allocate resource for EISA slot 1 [ 0.884929] Cannot allocate resource for EISA slot 2 [ 0.884932] Cannot allocate resource for EISA slot 3 [ 0.884936] Cannot allocate resource for EISA slot 4 [ 0.884940] Cannot allocate resource for EISA slot 5 [ 0.884943] Cannot allocate resource for EISA slot 6 [ 0.884947] Cannot allocate resource for EISA slot 7 [ 0.884950] Cannot allocate resource for EISA slot 8 [ 0.884954] EISA: Detected 0 cards. [ 0.884969] cpufreq-nforce2: No nForce2 chipset. [ 0.884973] cpuidle: using governor ladder [ 0.884976] cpuidle: using governor menu [ 0.884980] EFI Variables Facility v0.08 2004-May-17 [ 0.885476] TCP cubic registered [ 0.885708] NET: Registered protocol family 10 [ 0.886771] NET: Registered protocol family 17 [ 0.886799] Registering the dns_resolver key type [ 0.886837] Using IPI No-Shortcut mode [ 0.887028] PM: Hibernation image not present or could not be loaded. [ 0.887047] registered taskstats version 1 [ 0.902579] Magic number: 12:339:388 [ 0.902592] usb usb6: hash matches [ 0.902687] rtc_cmos 00:03: setting system clock to 2012-05-11 16:23:41 UTC (1336753421) [ 0.903185] BIOS EDD facility v0.16 2004-Jun-25, 0 devices found [ 0.903189] EDD information not available. [ 1.170710] ata3: SATA link down (SStatus 0 SControl 300) [ 1.181439] ata4: SATA link down (SStatus 0 SControl 300) [ 1.288020] Refined TSC clocksource calibration: 2499.999 MHz. [ 1.288028] Switching to clocksource tsc [ 1.292016] usb 1-5: new high-speed USB device number 3 using ehci_hcd [ 1.486745] ata2.00: SATA link down (SStatus 0 SControl 300) [ 1.486762] ata2.01: SATA link down (SStatus 0 SControl 300) [ 1.640115] ata1.00: SATA link up 1.5 Gbps (SStatus 113 SControl 300) [ 1.640130] ata1.01: SATA link down (SStatus 0 SControl 300) [ 1.648342] ata1.00: ATA-7: Maxtor 7Y250M0, YAR511W0, max UDMA/133 [ 1.648348] ata1.00: 490234752 sectors, multi 0: LBA48 [ 1.664325] ata1.00: configured for UDMA/133 [ 1.664531] scsi 0:0:0:0: Direct-Access ATA Maxtor 7Y250M0 YAR5 PQ: 0 ANSI: 5 [ 1.664745] sd 0:0:0:0: [sda] 490234752 512-byte logical blocks: (251 GB/233 GiB) [ 1.664809] sd 0:0:0:0: Attached scsi generic sg0 type 0 [ 1.664838] sd 0:0:0:0: [sda] Write Protect is off [ 1.664843] sd 0:0:0:0: [sda] Mode Sense: 00 3a 00 00 [ 1.664884] sd 0:0:0:0: [sda] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA [ 1.691699] sda: sda1 sda2 sda3 sda4 [ 1.692348] sd 0:0:0:0: [sda] Attached SCSI disk [ 1.692461] Freeing unused kernel memory: 740k freed [ 1.692820] Write protecting the kernel text: 5828k [ 1.692851] Write protecting the kernel read-only data: 2376k [ 1.692854] NX-protecting the kernel data: 4412k [ 1.723980] udevd[92]: starting version 175 [ 1.865339] Floppy drive(s): fd0 is 1.44M [ 1.865429] pata_jmicron 0000:03:00.0: PCI INT A -> GSI 16 (level, low) -> IRQ 16 [ 1.865478] pata_jmicron 0000:03:00.0: setting latency timer to 64 [ 1.867875] sky2: driver version 1.30 [ 1.867926] sky2 0000:04:00.0: PCI INT A -> GSI 17 (level, low) -> IRQ 17 [ 1.867942] sky2 0000:04:00.0: setting latency timer to 64 [ 1.867979] sky2 0000:04:00.0: Yukon-2 EC chip revision 2 [ 1.868111] sky2 0000:04:00.0: irq 44 for MSI/MSI-X [ 1.868174] scsi4 : pata_jmicron [ 1.869802] sky2 0000:04:00.0: eth0: addr 00:01:29:a4:16:0a [ 1.869828] scsi5 : pata_jmicron [ 1.869943] ata5: PATA max UDMA/100 cmd 0xdf00 ctl 0xde00 bmdma 0xdb00 irq 16 [ 1.869949] ata6: PATA max UDMA/100 cmd 0xdd00 ctl 0xdc00 bmdma 0xdb08 irq 16 [ 1.880053] usb 4-1: new full-speed USB device number 2 using uhci_hcd [ 1.884052] FDC 0 is a post-1991 82077 [ 2.032611] ata5.00: ATAPI: _NEC DVD+/-RW ND-3450A, 103C, max UDMA/33 [ 2.048585] ata5.00: configured for UDMA/33 [ 2.049777] scsi 4:0:0:0: CD-ROM _NEC DVD+-RW ND-3450A 103C PQ: 0 ANSI: 5 [ 2.051048] sr0: scsi3-mmc drive: 48x/48x writer cd/rw xa/form2 cdda tray [ 2.051054] cdrom: Uniform CD-ROM driver Revision: 3.20 [ 2.051283] sr 4:0:0:0: Attached scsi CD-ROM sr0 [ 2.051483] sr 4:0:0:0: Attached scsi generic sg1 type 5 [ 2.079838] usbcore: registered new interface driver usbhid [ 2.079844] usbhid: USB HID core driver [ 2.236660] EXT4-fs (sda1): mounted filesystem with ordered data mode. Opts: (null) [ 12.150230] ADDRCONF(NETDEV_UP): eth0: link is not ready [ 12.177342] udevd[333]: starting version 175 [ 12.195524] Adding 417684k swap on /dev/sda2. Priority:-1 extents:1 across:417684k [ 12.278032] lp: driver loaded but no devices found [ 12.516456] logitech-djreceiver 0003:046D:C52B.0003: hiddev0,hidraw0: USB HID v1.11 Device [Logitech USB Receiver] on usb-0000:00:1a.1-1/input2 [ 12.520297] input: Logitech Unifying Device. Wireless PID:1024 as /devices/pci0000:00/0000:00:1a.1/usb4/4-1/4-1:1.2/0003:046D:C52B.0003/input/input2 [ 12.520753] logitech-djdevice 0003:046D:C52B.0004: input,hidraw1: USB HID v1.11 Mouse [Logitech Unifying Device. Wireless PID:1024] on usb-0000:00:1a.1-1:1 [ 12.523286] input: Logitech Unifying Device. Wireless PID:2011 as /devices/pci0000:00/0000:00:1a.1/usb4/4-1/4-1:1.2/0003:046D:C52B.0003/input/input3 [ 12.524439] logitech-djdevice 0003:046D:C52B.0005: input,hidraw2: USB HID v1.11 Keyboard [Logitech Unifying Device. Wireless PID:2011] on usb-0000:00:1a.1-1:2 [ 12.545746] type=1400 audit(1336771433.137:2): apparmor="STATUS" operation="profile_load" name="/sbin/dhclient" pid=502 comm="apparmor_parser" [ 12.546574] type=1400 audit(1336771433.137:3): apparmor="STATUS" operation="profile_load" name="/usr/lib/NetworkManager/nm-dhcp-client.action" pid=502 comm="apparmor_parser" [ 12.547034] type=1400 audit(1336771433.137:4): apparmor="STATUS" operation="profile_load" name="/usr/lib/connman/scripts/dhclient-script" pid=502 comm="apparmor_parser" [ 12.626869] Linux video capture interface: v2.00 [ 12.649104] uvcvideo: Found UVC 1.00 device <unnamed> (046d:081a) [ 12.668665] input: UVC Camera (046d:081a) as /devices/pci0000:00/0000:00:1a.7/usb1/1-5/1-5:1.0/input/input4 [ 12.668909] usbcore: registered new interface driver uvcvideo [ 12.668914] USB Video Class driver (1.1.1) [ 12.697645] snd_hda_intel 0000:00:1b.0: PCI INT A -> GSI 22 (level, low) -> IRQ 22 [ 12.697721] snd_hda_intel 0000:00:1b.0: irq 45 for MSI/MSI-X [ 12.697760] snd_hda_intel 0000:00:1b.0: setting latency timer to 64 [ 12.706772] nvidia: module license 'NVIDIA' taints kernel. [ 12.706778] Disabling lock debugging due to kernel taint [ 12.735428] EXT4-fs (sda1): re-mounted. Opts: errors=remount-ro [ 13.350252] nvidia 0000:01:00.0: PCI INT A -> GSI 16 (level, low) -> IRQ 16 [ 13.350267] nvidia 0000:01:00.0: setting latency timer to 64 [ 13.350275] vgaarb: device changed decodes: PCI:0000:01:00.0,olddecodes=io+mem,decodes=none:owns=io+mem [ 13.351464] NVRM: loading NVIDIA UNIX x86 Kernel Module 295.40 Thu Apr 5 21:28:09 PDT 2012 [ 13.356785] hda_codec: ALC889A: BIOS auto-probing. [ 13.357267] init: failsafe main process (658) killed by TERM signal [ 13.372756] input: HDA Intel Line as /devices/pci0000:00/0000:00:1b.0/sound/card0/input5 [ 13.373173] input: HDA Intel Front Mic as /devices/pci0000:00/0000:00:1b.0/sound/card0/input6 [ 13.373568] input: HDA Intel Rear Mic as /devices/pci0000:00/0000:00:1b.0/sound/card0/input7 [ 13.373954] input: HDA Intel Front Headphone as /devices/pci0000:00/0000:00:1b.0/sound/card0/input8 [ 13.374339] input: HDA Intel Line-Out Side as /devices/pci0000:00/0000:00:1b.0/sound/card0/input9 [ 13.374715] input: HDA Intel Line-Out CLFE as /devices/pci0000:00/0000:00:1b.0/sound/card0/input10 [ 13.375109] input: HDA Intel Line-Out Surround as /devices/pci0000:00/0000:00:1b.0/sound/card0/input11 [ 13.375724] input: HDA Intel Line-Out Front as /devices/pci0000:00/0000:00:1b.0/sound/card0/input12 [ 13.475252] type=1400 audit(1336771434.065:5): apparmor="STATUS" operation="profile_replace" name="/sbin/dhclient" pid=735 comm="apparmor_parser" [ 13.477026] type=1400 audit(1336771434.069:6): apparmor="STATUS" operation="profile_replace" name="/usr/lib/NetworkManager/nm-dhcp-client.action" pid=735 comm="apparmor_parser" [ 13.477695] type=1400 audit(1336771434.069:7): apparmor="STATUS" operation="profile_replace" name="/usr/lib/connman/scripts/dhclient-script" pid=735 comm="apparmor_parser" [ 13.479048] type=1400 audit(1336771434.069:8): apparmor="STATUS" operation="profile_load" name="/usr/lib/lightdm/lightdm/lightdm-guest-session-wrapper" pid=734 comm="apparmor_parser" [ 13.488994] type=1400 audit(1336771434.081:9): apparmor="STATUS" operation="profile_load" name="/usr/lib/telepathy/mission-control-5" pid=738 comm="apparmor_parser" [ 13.489972] type=1400 audit(1336771434.081:10): apparmor="STATUS" operation="profile_load" name="/usr/lib/telepathy/telepathy-*" pid=738 comm="apparmor_parser" [ 13.

    Read the article

  • TechEd 2010 Thanks and Demos

    - by Adam Machanic
    Thank you to everyone who attended my three sessions at this year's TechEd show in New Orleans. I had a great time presenting and answering the really great questions posed by attendees. My sessions were: DAT317 T-SQL Power! The OVER Clause: Your Key to No-Sweat Problem Solving Have you ever stared at a convoluted requirement, unsure of where to begin and how to get there with T-SQL? Have you ever spent three days working on a long and complex query, wondering if there might be a better way? Good...(read more)

    Read the article

< Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >