Monthly Archives: September 2012

ObjectContext’s SavingChanges Event

ObjectContext’s SavingChanges event lets you validate or change data before Entity Framework sends it to the database. Entity Framework raises this event immediately before it creates the SQL INSERT, UPDATE, and DELETE statements that will persist the changes to the database.

One of the issues with using Entity Framework with SQL Server is that the range of DateTime values in .NET is different than those of the DateTime type in SQL Server. So in the case where you have a non-nullable DateTime field in a table, you have to assign a value to the corresponding property in an entity. This is exactly the case with the Modified property, associated with the ModifiedDate field in all of the tables of the AdventureWorksLT database. If you create a new instance of any entity and don’t explicitly set a valid value for the Modified property, .NET sets its minimum value, which doesn’t work for a SQL Server DateTime type. (It would, however, work with SQL Server 2008 and later’s DateTime2 type, but AdventureWorksLT doesn’t use this type for its date/time fields.) So you either need to explicitly set the Modified property to DateTime.Now when you create or update any entity, you’ll get a rather cryptic exception about some unnamed DateTime type being out of range.

NOTE: It is interesting that while the ModifiedDate fields in the database have a default value of GETDATE()—the T-SQL equivalent of DateTime. Now—there is nothing that updates the value when a record is changed. So you’ll need to supply a value for the Modified property when creating a new instance of an entity to avoid the datetime overflow problem, and when modifying an entity so that the field reflects the last time any data in the record changed.

This is a perfect use of the SavingChanges event. The one trick is that the view entities—CategoryList, ProductAndDescription, and ProductModelCatalogDescription—don’t have a Modified property. So the code has to be selective about which entities it applies to. But SavingChanges makes this easy through how it requires you to get access to the set of inserted, updated, or deleted entities. You have to access the entities with the ObjectContext’s GetObjectStateEntries method. The method takes one or more EntityState enumerations OR’d together, and returns a collection of entities with the selected state. You can select for Added, Deleted, Modified, and Unchanged states, but in this case you’re only interested in the Added and Modified states. There is no reason to update Modified for an entity you are deleting or that remains unchanged.

modify entities method

TIP: There is one other EntityState enumeration value, Detached. This state means that ObjectContext isn’t managing state for that entity. This value is not relevant in the SavingChanges event because there won’t be any work to do for detached entities.

The AWLT project in AWLT.sln has a Context.cs code file with a partial AWLTEntities class to customize the context object. The class implements the following AWLTEntities_SavingChanges method. The code uses the ObjectStateManager property of ObjectContext to get a reference to the ObjectStateManager for the context. It then uses the GetObjectStateEntries method, with the Added and Modified EntityState enumeration values, to populate the entities object with a collection of modified entities. Then the code loops through the collection, and uses reflection to update the value of the Modified property of each entity. The update code is wrapped in a try block and a do-nothing catch just in case an entity slips through that doesn’t have a Modified property.

You also have to wire up the SavingChanges event handler, and the OnContextCreated partial method is the perfect place to do that. The following code in the partial AWLTEntities class takes care of this task in the code.

The ModifyEntries method in Program.cs puts the SavingChanges event handler to use. It executes a query to retrieve all customers named Ann, and updates each one with a Jr. suffix. Then it saves the changes to the database, and turns around and resets the suffixes to null (which is what they all were originally). It then refreshes the collection of customers, just to make sure nothing was cached in memory, and writes out each customer, including the new value of the Modified property. Figure 1 shows the result of running the application.

 

Figure 1. The result of running the ModifyEntities method.

 

Go Ahead and Be Geeky

computer-nerds-are-sexy

 

There was a time when computer programming was considered something that only “geeks” did. Anyone who spent all of his or her time in front of a computer clearly had no social life. That belief system has changed a great deal over the years, as computers have become more and more important to our ability to communicate and carry out business transactions of many different types. Having computer knowledge, such as how to use Sharepoint 2010, or how to effectively utilize C#, is now almost a requirement for job advancement.

For those people who were slow to jump onto the computer bandwagon, the learning curve can feel very steep. However, a C# video course, an online HTML5 tutorial, or a web-based course on Sharepoint 2010, can help you feel less like you are floundering at the deep end of the pool. With a better understanding of how to program web-based applications, and how to develop and work with network systems, you can increase your value at work, and your overall effectiveness with computers. So go ahead and be “geeky”, because “geeky” is savvy, too.


 

(function(){
var s=’hubspotutk’,r,c=((r=new RegExp(‘(^|; )’+s+’=([^;]*)’).exec(document.cookie))?r[2]:(function(){var c=’0123456789abcdef’,s=[],i=0;for(i=0;i<32;i++)s[i]=c[Math.floor(Math.random()*0x10)];return s.join(”);})()),w=window;w[s]=w[s]||c,
hsjs=document.createElement(“script”),el=document.getElementById(“hs-cta-c6aa8857-3e7e-4761-a672-02016ac3851d”);
hsjs.type = “text/javascript”;hsjs.async = true;
hsjs.src = “//cta-service-cms2.hubspot.com/cs/loader.js?pg=c6aa8857-3e7e-4761-a672-02016ac3851d&pid=153597&hsutk=” + encodeURIComponent(c);
(document.getElementsByTagName(“head”)[0]||document.getElementsByTagName(“body”)[0]).appendChild(hsjs);
try{el.style.visibility=”hidden”;}catch(err){}
setTimeout(function() {try{el.style.visibility=”visible”;}catch(err){}}, 2500);
})();

When is your PC not your PC?

Windows-Vista-Start-Button

 

Since growing up in Seattle I have always been a big proponent of Microsoft. One of the key characteristics of Microsoft’s software that kept me loyal was that they always gave me enough rope to hang myself with. With any operating system or software, I was allowed to get in and tweak the system to be however I wanted it to be. And over time, I could solve most any technical issue because I knew how the guts were put together as a direct result of constant experimentation.

So what’s got me on edge? The Windows Start Button. I am struggling to understand Microsoft’s obsession with removing it. Microsoft released a Developer Preview of Windows 8 and a Consumer Preview. In both releases, bloggers like Jake Durasamy quickly posted how to get the Start button back and life seemed normal again. But with RTM, to quote Paul Thurrott, ” Microsoft has been furiously ripping out legacy code in Windows 8 that would have enabled third parties to bring back the Start button.” Really?

Mary Jo Foley agrees and pointed out that clearly Microsoft has made deliberate attempts to prevent developers from circumventing the bringing back of the Start Button as well as being able to boot straight into the Windows 8 desktop. Microsoft did not comment on her observations.

Don’t get me wrong, I understand Microsoft’s desire to move its users into the next generation of operating systems and I’m certainly familiar with the term, “sink or swim,” but is that the right move? TechRepublic has an infographic regarding pros and cons of Windows 8 and listed “No Start menu” and “Need for Massive Training” as two key negatives. Businesses are already struggling for compelling reasons to upgrade their employee’s computers. Is Microsoft’s being bullish on removing all training wheels really helping their cause?

I don’t deny the future and it is clear that the Start Button is not meant to be in it. The new Windows 8 style environment is here to stay and will be the new standard just like the Start Button was back in 1995. But is asking for little conveniences of the past asking too much before we go cold-turkey? Is going overboard in preventing its return better than simply making it optional? As I see it, it’s hard to go wrong by giving customers the freedom to do what they want.

win8-start-screen-1

Martin Schaeferle – Marty has taught IT professionals nationwide to develop applications using Visual Basic, Microsoft® SQL Server, ASP, and XML. He has been a featured speaker at Microsoft® Tech-Ed and the Microsoft® NCD Channel Summit, and he specializes in developing Visual Basic database applications, COM-based components, and ASP-based Web sites. In addition to writing and presenting technical training content, Martin is also LearnNowOnline’s Vice President of technology.

It’s Cleanup Time, Entity Data Model Style

As good and useful as a model generated using database-first design can be—it is highly dependent on the quality of the underlying database design—you’ll almost always need to do at least small tweaks to the resulting Entity Data Model. There are some things that Entity Framework just can’t handle intelligently, such as naming conflicts, vagaries in English pluralization, and various other issues that make the model usable but less than ideal for development work. Similarly, there are tweaks you can make that make the data entities easier to use, such as setting intelligent default values for properties when that makes sense. And many of these techniques apply to creating a model from scratch using model-first design, so you’re likely to put them to use no matter how the model comes into existence.

This article focuses on cleaning up an Entity Data Model once it’s created.

One of the very first things you should do after creating a model is to clean up the names of objects and properties in the model, making sure that they make sense for applications that use the model. Just because a name made sense to the database designer doesn’t mean that it will make sense to application developers. Make sure that the terminology is correct, consistent, and valid. Good names can make a huge difference to the productivity of application developers, particularly when they don’t constantly have to stop and think about which inconsistent name is used in the part of the database they are working with at the time.

One big reason you’ll have to rename things in the model is if the person who designed the database used outdated or misguided naming standards. For example, the figure below shows just one table from a very large database that we’ve encountered in our consulting work. In fairness, the original database was created back in the days of SQL Server 2000 before schemas were available as a kind of namespace container. So all the tables have a “tbl” prefix on the name, followed by the name of the functional area (“Subscript” here for the subscription area), and the table name (“Member”). Complicating things further, some of the tables have a three-character subscript on the name (“smi” in the figure), none of which any current employees of the company has any idea the meaning of.

Naming standards implemented in a production database.

The fields in all the tables follow a similar pattern, with a data type prefix, a functional area name (no one knows why the table in the above figure uses both “Member” and “Subscript” in various field names), and finally the field name. Unfortunately, the data type prefixes are unreliable because over the years it has been necessary to change data types here and there—which isn’t necessarily a breaking change—without changing the field name—which is a breaking change.

The nightmare of this database design has persisted for years because the company has a large, complex Web site built on it, as well as various support applications and tools. Making all the required changes to the applications and stored procedures would be a nightmare if any field names changed. As you can imagine, we had to spend a ton of time cleaning up the names in the Entity Data Model we created for the database. It was time well spent, however, because we were able to simplify the names, clean up inconsistencies, and change names that made no sense at all. All without changing the underlying database design.

Fortunately, all of the AdventureWorks databases use a much saner naming convention, so there isn’t nearly as much work to do. But there are still things to refine that will make the model much easier to use in an application. And with Entity Framework version 4 and later, the Entity Data Model Wizard has already made entity and entity set names singular and plural by default, which saves a lot of the work required in earlier versions. It isn’t perfect, but it is good enough by far and away most of the time.

You can fix database object misspellings in the model as well. Sometimes you can’t change the misspellings because of application dependencies, but you don’t have to perpetuate the problem in your new model and applications.

1e723e30-168f-450f-9f8d-9445c49dd3ed

Learning A New Programming Language

VisualStudio2010

 

Microsoft’s .NET interpreted languages are some of the easiest to learn and some of the easiest to use to develop fully functional software applications. Visual Basic has long been used as a training language – it’s easy to learn, but not particularly robust. C++ on the other hand is the granddaddy of the modern programming language. Object-oriented with sophisticated memory management, it’s the professional language of choice for software development. But, it’s very difficult to learn.

A popular choice is Visual C#. It combines the object-oriented power of C++ with the simplicity of Visual Basic. It’s very easy to learn.

There are several ways to learn a new programming language. Programming books come loaded with samples and often include actual code on a CD or as downloads. Don’t have enough time for a book? Just choose a visual studio 2010 tutorial video and start building some software.


Leave Well Enough Alone: The iOS6 Maps App

ios6-maps-turnbyturn

 

Personally, I love many of the new desktop features in Windows 8, but I’m not loving the new start screen UI. It just seems to get in my way. But that’s just my opinion.

On the other hand, one has to consider why software companies hoist changes like this on unsuspecting users. We could go on for hours about the Windows 8 start screen, but one “change for change’s sake” popped up this morning: I installed iOS 6 on my iPad and iPhone, and tried out the new Maps app. Apple created their own app to replace the Google Maps app that has been in iOS since the first version. Ugh. Seriously ugh. Yes, you gain the verbal turn-by-turn directions (which Android users have had from the beginning, withheld on purpose from iOS), but it’s ugly, it’s inaccurate, and you lose the street view that Google perfected. I have to ask: Apple, what do WE gain for this change? Sure, you can remove one more Google app from the device, and sure, you can stop paying Google licensing fees, but what do WE get? If the data isn’t accurate (I looked up local rural streets to check for through streets, and found a few errors, which Google has, over the years, corrected), how can you use the app?

Like the Windows 8 Start screen, I’m sure there’s some reason that was good for Apple, but I remain unconvinced of what it gains the average user.

ldn-expertkgetzKen Getz is a Visual Studio expert with over 25 years of experience as a successful developer and consultant. He is a nationally recognized author and speaker, as well as a featured instructor for LearnNowOnline.

Updating Existing Entities

 

Querying data is a useful benefit of using Entity Framework, but you’ll often need to create, modify, and delete entity data as well. As with most of its features, Entity Framework provides rich support for changing data and has lots of options. This article discusses updating existing entities.

When you query the model and retrieve one or more entities then modify them, you can simply call SaveChanges to persist the changes. The following code retrieves all customers with the first name Ann and selects the first one, then writes the entity’s current state to the console window. Then the code changes a couple of property values, and again writes the state. Then it calls SaveChanges and writes the state yet again, then confirms that it updated the entity.

Figure 1 shows the results in the console window. Notice that immediately after materializing the Customer object, its state is Unchanged. This is as you’d expect, since no entity data has changed. After making changes but before saving them, the state is Modified. And after saving the changes, the state is once again Unchanged, because the context updated the entity’s original values to the new values to reflect the values now stored in the database.

results-of-changing-a-single-entity

Figure 1. The results of changing a single entity.

If you run SQL Profiler and examine the UPDATE statement that Entity Framework generated to persist the changes, you’ll find the following statement. Notice that Entity Framework is passing only the two updated fields, not the entire set of entity data. The context keeps track of which
properties changed, so is able to create more efficient SQL for the operation.

An interesting experiment is to update the FirstName property to Ann instead of Anne; in other words to set the value of the property to its current value. Change the code for that statement to the following and comment out the line that updates the ModifiedDate property. Then run the application again. And again. And once more. Notice that each time you get the same Unchanged/Modified/Unchanged states that you saw in Figure 1. Entity Framework sees that you assign a value to the property and changes the state to Modified without comparing the new value to the old one.

If you use SQL Profiler to look at the SQL statement generated with this new version of the code, you’ll find that it is the following statement every time. The UPDATE statement sets the FirstName field to ‘Ann’ even though that is already its value.

You can also update related data using the navigation properties of each entity, as long as those related objects are materialized in the query. Usually the easiest way to do that is to use the Include method for the related entities to make sure their data is available in memory for modification.

XAML vs. HTML ain’t like VB vs. C#

windows-8-logo0817

 

Before Windows 8 apps came along, I spent a lot of time writing courseware for both VB and C#, and converting between the two was relatively easy–I got it down to a science. At worst, it involved some minor changes, once you got past the language differences. And those minor changes got smaller and smaller with each version of the languages.

So, wow, was I surprised to find that it’s nothing like that when comparing C# and JavaScript apps for Windows 8.

Basically, they have little, if anything, in common. Because C# (and VB) use the .NET Framework, more or less, and JavaScript apps use WinJS, the tools, classes, and even concepts are different. I was totally surprised how different the environments are, down to big differences in the available controls–things you find in JavaScript simply aren’t available to C#/VB developers. Want a date picker control? Better look outside Visual Studio to find that control (and several others that JavaScript supplies but C#/VB do not).

Anyway, my point is that if you’re a writer (or a developer) thinking that you can create apps in C# and then later convert them to JavaScript (or vice versa) think again. That ain’t happening.

Ken Getz is a Visual Studio expert with over 25 years of experience as a successful developer and consultant. He is a nationally recognized author and speaker, as well as a featured instructor for LearnNowOnline.

The Fabulous Free Utility, LINQPad

Selecting the Entity Framework data context

When writing and testing LINQ expressions and queries using LINQ for Entities—or other LINQ variants—you can write a custom application, reference the class library containing your Entity Data Model, and write code that executes the expression and displays the results somehow, perhaps in a console window. All that setup can be a bit tedious when you are working with throwaway LINQ expressions that you tweak, explore, and then delete.

A better option is the fabulous free utility, LINQPad, written by Joseph Albahari. This tool lets you interactively query databases using LINQ expressions you build in its own development environment.

The one thing that LINQPad can’t easily do is let you explore the Entity Framework and .NET Framework objects used to return data to the application. It does display the direct object type returned with the results, but doesn’t let you explore its properties. For more extensive exploration of these objects, the debugging tools in Visual Studio, particularly the object tooltips and Locals window, are invaluable.

Setting Up LINQPad to Use an Entity Data Model Assembly

Before you can write LINQ expressions against an Entity Framework model, you’ll have to configure the utility so that it knows which assembly to use and some other basic information to find the correct objects in your Entity Data Model. Follow these instructions for setting up LINQPad to use a pre-built AWLTModel that uses the AdventureWorksLT database.

1. Launch LINQPad from the Windows Start menu.

2. Click the Add Connection link in the upper left portion of the LINQPad window, to open the Choose Data Context dialog box.

3. Select the lower radio button, Use a typed data context from your own assembly, and select the Entity Framework item in the list, as shown in Figure 2. This tells LINQPad that you want to use an Entity Framework model rather than a direct connection to a data store. Click Next to move to the next step.

Selecting-the-Entity-Framework-data-context

Figure 2. Selecting the Entity Framework data context.

4. In the Entity Framework Custom Assembly Connection dialog box, click the Browse link in the upper right to open an Open File dialog box. Navigate to the AWLT.dll file in this chapter’s files, and click the Open button. This causes LINQPad to look inside the assembly for the context and model name, and opens the Choose Custom Type dialog box as shown in Figure 3. Accept the default AWLT.AWLTEntities and AWLTModel selections, and click OK.

Choosing-the-custom-types-from-the-AWLT.dll-assembly

Figure 3. Choosing the custom types from the AWLT.dll assembly.

5. This populates several of the selections in the Entity Framework Custom Assembly Connection dialog box, which is now named the LINQPad Connection dialog box, as shown in Figure 4. Review the selections; you shouldn’t have to make any changes here because it reflects the connection information in the assembly, but you can if necessary. Click OK to create the connection.

the-fully-populated-LINQPad-connection-dialog-box

Figure 4. The fully populated LINQPad Connection dialog box.

6. LINQPad will gather metadata information from the model assembly and populate the treeview in the upper left portion of the LINQPad window with a list of entities in the assembly. You can expand an entity to view its properties.

You’re now ready to write LINQ expressions and queries against the AWLT model!

Download LINQPad now!

Learn and Do with Video Tutorials

The reason taking a class is so useful when you are learning something new, is that you can see someone interacting with the material first hand, in real time. Reading a textbook or attempting to complete a workbook on your own is not always as useful. This is especially true with learning new computer-related skills. There are many, many books available, but until you can actually see someone working with the material and experience it yourself, it is difficult to understand.

This is why aC# video courseor other video tutorials for developersare so useful. Instead of attempting to grasp the material via pages and pages of text and the occasional screen grab, a video tutorial can literally walk you through each step of the C# programming process. This allows you to learn and do at the same time. Additionally, a video tutorial allows you to go back and look at portions of the lesson you may not have fully understood or which you need to practice repeatedly. If you are struggling with C#, don’t give up. Look forC# .NET coursesonline, and learn everything you need to know at your own pace.

Getting Started with Windows 8 Metro Style Applications Using C# and XAML