Thursday, December 20, 2012

SQL SERVER – Select and Delete Duplicate Records

Developers often face situations when they find their column have duplicate records and they want to delete it. A good developer will never delete any data without observing it and making sure that what is being deleted is the absolutely fine to delete. Before deleting duplicate data, one should select it and see if the data is really duplicate.

A very nice post & video. Read more here.

Saturday, December 15, 2012

Using Code Map in Visual Studio 2012 Ultimate

This post explains how to analyze and navigate complex code using Code Map in Visual Studio 2012. The new Code Map feature in Visual Studio 2012 ultimate allows you to create visualizations in your source code. This helps you to identify and quickly fix the bugs in your code. You need to install Visual Studio update to get this feature from here.

For more read here.

Testing features added in Visual Studio 2012 Update1

This post explains the enhanced testing features that were introduced with Visual Studio 2012 update 1. Visual Studio 2012 now supports code coverage analysis during the manual testing. This functionality can be enabled by configuring test settings in Microsoft Test manager. This feature is currently supported for ASP.NET applications that running on IIS.

For more read here.

Web Publishing Features in Visual Studio 2012

There is no formal build and publishing process for Websites in Visual Studio 2010, it is really a set of files and folders. If you use the web site templates while creating a project in Visual Studio 2010 then publishing experience is vastly different from what available on web application projects. New updates have been released for improving publishing experience in Visual Studio 2010 and Visual Studio 2012 as part of the Windows Azure SDK release. The new publishing features are available for both website and web application projects. This post walk-through the new publishing features available in Visual Studio 2012 by creating and publishing a new website.

more read here.

Entity Framework 6: Alpha2 Now Available

Entity Framework 6: Alpha2 Now Available:
The Entity Framework team recently announced the 2nd alpha release of EF6.   The alpha 2 package is available for download from NuGet. Since this is a pre-release package make sure to select “Include Prereleases” in the NuGet package manager, or execute the following from the package manager console to install it:
PM> Install-Package EntityFramework -Pre
This week’s alpha release includes a bunch of great improvements in the following areas:
  • Async language support is now available for queries and updates when running on .NET 4.5.
  • Custom conventions now provide the ability to override the default conventions that Code First uses for mapping types, properties, etc. to your database.
  • Multi-tenant migrations allow the same database to be used by multiple contexts with full Code First Migrations support for independently evolving the model backing each context.
  • Using Enumerable.Contains in a LINQ query is now handled much more efficiently by EF and the SQL Server provider resulting greatly improved performance.
  • All features of EF6 (except async) are available on both .NET 4 and .NET 4.5. This includes support for enums and spatial types and the performance improvements that were previously only available when using .NET 4.5.
  • Start-up time for many large models has been dramatically improved thanks to improved view generation performance.
Below are some additional details about a few of the improvements above:

Async Support

.NET 4.5 introduced the Task-Based Asynchronous Pattern that uses the async and await keywords to help make writing asynchronous code easier. EF 6 now supports this pattern. This is great for ASP.NET applications as database calls made through EF can now be processed asynchronously – avoiding any blocking of worker threads. This can increase scalability on the server by allowing more requests to be processed while waiting for the database to respond.
The following code shows an MVC controller that is querying a database for a list of location entities:
    public class HomeController : Controller
    {
        LocationContext db = new LocationContext();

        public async Task<ActionResult> Index()
        {
            var locations = await db.Locations.ToListAsync();

            return View(locations);
        }
    }
Notice above the call to the new ToListAsync method with the await keyword. When the web server reaches this code it initiates the database request, but rather than blocking while waiting for the results to come back, the thread that is processing the request returns to the thread pool, allowing ASP.NET to process another incoming request with the same thread. In other words, a thread is only consumed when there is actual processing work to do, allowing the web server to handle more concurrent requests with the same resources.
A more detailed walkthrough covering async in EF is available with additional information and examples. Also a walkthrough is available showing how to use async in an ASP.NET MVC application.

Custom Conventions

When working with EF Code First, the default behavior is to map .NET classes to tables using a set of conventions baked into EF. For example, Code First will detect properties that end with “ID” and configure them automatically as primary keys.
However, sometimes you cannot or do not want to follow those conventions and would rather provide your own. For example, maybe your primary key properties all end in “Key” instead of “Id”. Custom conventions allow the default conventions to be overridden or new conventions to be added so that Code First can map by convention using whatever rules make sense for your project.
The following code demonstrates using custom conventions to set the precision of all decimals to 5. As with other Code First configuration, this code is placed in the OnModelCreating method which is overridden on your derived DbContext class:
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Properties<decimal>()
                .Configure(x => x.HasPrecision(5));

        }
But what if there are a couple of places where a decimal property should have a different precision? Just as with all the existing Code First conventions, this new convention can be overridden for a particular property simply by explicitly configuring that property using either the fluent API or a data annotation.
A more detailed description of custom code first conventions is available here.

Community Involvement

I blogged a while ago about EF being released under an open source license.  Since then a number of community members have made contributions and these are included in EF6 alpha 2.
Two examples of community contributions are:
  • AlirezaHaghshenas contributed a change that increases the startup performance of EF for larger models by improving the performance of view generation. The change means that it is less often necessary to use of pre-generated views.
  • UnaiZorrilla contributed the first community feature to EF: the ability to load all Code First configuration classes in an assembly with a single method call like the following:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
       modelBuilder.Configurations
           .AddFromAssembly(
typeof(LocationContext).Assembly);

}
This code will find and load all the classes that inherit from EntityTypeConfiguration<T> or ComplexTypeConfiguration<T> in the assembly where LocationContext is defined. This reduces the amount of coupling between the context and Code First configuration classes, and is also a very convenient shortcut for large models.

Other upcoming features coming in EF 6

Lots of information about the development of EF6 can be found on the EF CodePlex site, including a roadmap showing the other features that are planned for EF6.
One of of the nice upcoming features is connection resiliency, which will automate the process of retying database operations on transient failures common in cloud environments and with databases such as the Windows Azure SQL Database.
Another often requested feature that will be included in EF6 is the ability to map stored procedures to query and update operations on entities when using Code First.

Summary

EF6 is the first open source release of Entity Framework being developed in CodePlex. The alpha 2 preview release of EF6 is now available on NuGet, and contains some really great features for you to try.
The EF team are always looking for feedback from developers - especially on the new features such as custom Code First conventions and async support. To provide feedback you can post a comment on the EF6 alpha 2 announcement post, start a discussion or file a bug on the CodePlex site.
Hope this helps,
Vihang

Sunday, December 9, 2012

Conventions for Code First


The latest preview of Code First allows you to describe a model using C# or VB.Net classes. The basic shape of the model is detected by convention and then a fluent API can be used to further refine your model.
We recently posted about our plans to support Data Annotations as another way to further describe your model. We are now looking at extending and improving the conventions that initially infer the shape of the model. This post describes the conventions we are planning to include.
Conventions are designed to provide a starting point for a model. Data Annotations or the fluent API can then be used to further describe the model or change what was detected by convention. Precedence is given to configuration via the fluent API followed by Data Annotations then convention.

For more read here.

The Repository Pattern with EF Code First & Dependency Injection in ASP.NET MVC3


Introduction

These days, I started using EF code first and thought about how could I take advantage from it for my recent project. My project is based on MVC3 and there are some challenges to continue updating this project. At that time, I must finish my job in a very short deadline so fast so good I just define some data access interfaces and implemented them with EF4.
There are some things in my project troubling me:
  • I have used the EF entities in my controllers anywhere that there is a connection translation error throwing infrequently.
  • Modules coupling degree becoming closed.
  • Manage services and contexts life cycle are difficult.
Obviously, it needs to refactor my project with a new architecture designing.

More to read here.

Code First with Entity Framework 5 using MVC4 and MVC Scaffold


Introduction

In this article, I will walk you through a simple application using MVC4 and Entity Framework 5 and will demonstrate how one can make use of code first technology. I will be using MvsScaffold for quick creation of controllers and views. We will be creating a TODO application.

More to read here.

Finally! Entity Framework working in fully disconnected N-tier web app


Introduction 

Entity Framework was supposed to solve the problem of Linq to SQL, which requires endless hacks to make it work in n-tier world. Not only did Entity Framework solve none of the L2S problems, but also it made it even more difficult to use and hack it for n-tier scenarios. It’s somehow half way between a fully disconnected ORM and a fully connected ORM like Linq to SQL. Some useful features of Linq to SQL are gone – like automatic deferred loading. If you try to do simple select with join, insert, update, delete in a disconnected architecture, you will realize not only you need to make fundamental changes from the top layer to the very bottom layer, but also endless hacks in basic CRUD operations. I will show you in this article how I have  added custom CRUD functions on top of EF’s ObjectContext to make it finally work well in a fully disconnected N-tier web application (my open source Web 2.0 AJAX portal – Dropthings) and how I have produced a 100% unit testable fully n-tier compliant data access layer following the repository pattern.
In .NET 4.0, most of the problems are solved, but not all. So, you should read this article even if you are coding in .NET 4.0. Moreover, there’s enough insight here to help you troubleshoot EF related problems.
You might think “Why bother using EF when Linq to SQL is doing good enough for me.” Linq to SQL is not going to get any innovation from Microsoft anymore. Entity Framework is the future of persistence layer in .NET framework. All the innovations are happening in EF world only, which is frustrating. There’s a big jump on EF 4.0. So, you should plan to migrate your L2S projects to EF soon.

For More read here.

Hope you like this article friendz... :)

Thursday, November 22, 2012

A potentially dangerous request.querystring value was detected from the client asp.net


Last Week, while working on an ASP.NET Web project, I got an issue. The issue was, when I am trying to pass unencoded HTML content into a querystring I got an error something like ”A potentially dangerous Request. Form value was detected from the client”. After that I surf through the net and then got a solution. Here are possible solution which may help you. Put this below script in existing “page” directive in that .aspx file.

<%@ Page validateRequest="false" %>

If you are having more pages in your project means its very difficult to put this code in each page.so add this below tag in Web.Config file to access it globally

<configuration>
<system.web>
<pages validateRequest="false" />
</system.web>
</configuration>

If you are using .Net 4.0 than you have to make one more change in Web.Config file. Add this tag in section.
<httpRuntime  requestValidationMode="2.0" />

If You are facing the same problem in ASP.NET MVC 3.
Add this below code in Application_Start() method.

GlobalFilters.Filters.Add(new ValidateInputAttribute(false));

Note: When disabling the request validation on the application make sure to validate the entire application

Tuesday, November 20, 2012

Collapse Selection in Solution Explorer extension

After much feedback asking for a feature that would recursively collapse nodes in the solution explorer. Visual Studio Project Team are happy to announce the Collapse Selection in Solution Explorer extension!


What is the Collapse Selection in Solution Explorer extension?
Many Visual Studio users have a solution tree structure with multiple projects and solution folders that are organized as a deep hierarchy. To avoid visual pollution, users want only those projects expanded that are being actively developed (often with many of the project’s child nodes recursively collapsed). To accomplish this task, they have to manually collapse each node recursively – an onerous chore if one has a deeply nested solution tree. The Collapse Selection in Solution Explorer extension addresses this particular issue by enabling the user to recursively collapse multiple nodes with a single click.
How do I install the extension?
1. You can download the extension from the VS Gallery. Double-click the downloaded VSIX file and the extension will be installed.
2. You can navigate to Tools –> Extension Manager, and search for “Collapse Selection in Solution Explorer” in the Online Gallery. Simply download and click Install.
How does the extension work?
Once the extension is installed, you will see a button appear in the Solution Explorer bar. Choose any collapsible node (any node with children nodes; i.e. parent node) in the Solution Explorer and click the Collapse Selection button. All the children nodes will be recursively collapsed to show only the parent node. When you click the expand/collapse icon next to the just collapsed parent node, the parent node will expand to list all the children nodes which will appear collapsed if they have their own children nodes (see figure below). You can select the solution node and click the Collapse Selection button to recursively collapse all nodes in the solution tree. You can also select multiple collapsible nodes and click the Collapse Selection button to recursively collapse each of them.

I prefer using my keyboard. Is it possible to use this extension through keyboard shortcuts?
Definitely. Ensure that the focus is on the Solution Explorer and press Alt + Num(-) to collapse selected nodes. You can also use the Command Window by entering the following command: View.CollapseSelectionInSolutionExplorer.
Is this extension limited to certain project types?
No. This extension should work with all project types.

Source: From Here



Monday, September 24, 2012

What is new in C# and Visual Basic in Visual Studio 2012



This post discusses the new language features that is introduced in Visual Studio 2012. One of the main things that language team introduced is the idea of producing windows 8 App. These APPs are talking to new API called windows runtime. Small new feature Caller Info Attributes is also added in this release. More about this feature can be read here.
image
This release also brings iterators to Visual Basic. The main discussion in this post is around Asynchronous programming in C# language.
image 
If you want to give importance on responsiveness of client and scalability in server App then you probably call Asynchronous API’s. These API’s take Callbacks as parameters and uses that Callback to notify you about result of available. When you start write these call backs then it is harder maintain the code but with new Async language support that introduced in  Visual Basic and C# and it is easy consume these API’s.
Below is the synchronous code in C#
image
The code basically Searches the movie index in Netflix using OData by taking Year as parameter. While it is downloading the movies using above code , you can notice you can not interact with your user interface. You can scroll along UI and explore the movies only after the search operation is complete. Users expects more responsive apps.
Why the above code is Unresponsive? 
The call to DownloadString is of webclient type and it asks you to wait till it returns string. During this process your UI is going to hang-up and holds the thread until it returns the result back you.
Two different options here, you can put this code on background Thread and it is bit complicated. You may have to marshal and unmarshal the code. The second option is to interact with Asynchronous API there you have an overloaded function DownloadStringAsync, But when you use this method you are no longer take back data as result. You need to sign-up a call-back when a result is available. If you have multiple Async calls then you have to write multiple call-backs. In this case your code is getting more difficult to understand.
Solution
The new overload method is DownloadStringTaskAsync, This method now returns string of type Task, Task of string is object that notify you when result is available. Now you can change the signature of the method QueryMovies and mark this as async. This tells the compiler that this method is pausable and resumeable , they can wait without locking to the UI thread. Now change the return type of method from Movie array to Task<Movie[]> array. Write a word await to get the string from Task of objects from DownloadStringTaskAsync call.
image
Now you can call the above even from while loop
image
The compiler is now able to figure out how to handle the await inside the while loop and resume it when it gets the result. Now you should be able to interact with your UI without any hang-ups.
Reference: Alex Turner talk in Visual Studio launch

Caller Info Attributes in C# 5.0


Caller Info Attributes is a new feature in C# 5.0, Caller Info Attributes instructs the compiler to obtain and feed information into the parameter’s default value. You can tag optional parameters using Caller Info Attributes.
image
Three Caller Info Attributes are
  • [CallerMemberName]  – It applies the caller’s member name
  • [CallerFilePath] -  It applies the path to the caller’s source code file
  • [CallerLineNumber]-  It applies the line number in the caller’s source code file
The below piece of code demonstrates all three attributes
   1: using System;

   2: using System.Runtime.CompilerServices;

   3: class Program

   4: {

   5: static void Main()

   6: {

   7:   Demo();

   8: }

   9: static void Demo (

  10: [CallerMemberName] string memberName = null,

  11: [CallerFilePath] string filePath = null,

  12: [CallerLineNumber] int lineNumber = 0)

  13: {

  14:    Console.WriteLine (memberName);

  15:    Console.WriteLine (filePath);

  16:    Console.WriteLine (lineNumber);

  17: }

  18: }
The output of the code as below
Main
C:\Projects\Program.cs (Assuming your project is located in this path)
16
Caller Info attributes are useful for writing logging functions and for implementing change notification patterns. The following method can be called from property’s set accessor
   1: void RaisePropertyChanged( [CallMemberName] string propertyName = null)

   2: {

   3:  

   4: }
More can be read here

Software Testing with Visual Studio 2012



Microsoft Test Manager is a tool which comes with Visual Studio 2012 , which was built from the scratch to support the needs of Manual testers.  Using this tool you can manage and track test cases that helps both developer and tester.This post gives you an overview on Microsoft Software Testing tools.
image
Back ground
Prior to the release of Visual Studio 2010 launch the testing land scape and testing life cycle was shown as below
image
When you look at the Software Testing land scape, you can see the Manual testers in left , they look at the new test cases and new builds that are coming along and run through their test runs and report bugs back to the developers.
image
Far right end of the picture, You can see developers who are specialists in writing the code. You all know the 70% of the testing on software happens in manual testing team. Manual testers can adapt and respond to the changes in underlining applications. The typical tools that manual testers use are Excel and Word. So we need a tool for Manual testers !!!
We all know when testers do find a bug and fires to developer then developer says it works on my machine, this is the problem that happens all the time
image
There is some time waste in going back and forth between testers and developers to try to understand how the developer recreate the issue, we want to make this happen in automated fashion!
The tools are building up and automatically capturing lot of rich details bugs can give the developer everything they need at their finger tips to understand what happen and importantly fix for it.
Microsoft Test Professional is part of Visual Studio 2012 family
image
Microsoft Test Professional can be purchased as a standalone tool or it includes Visual Studio 2012 premium and ultimate editions.
Build – Deploy – Test
image
Lab Management in VS 2012 can allow you to take code changes that developers modeling in source control and press a single button which will compile those changes and deploy them into one or more environments and run all of your automated tests against those environments.
As a manual tester if you want to test different varieties of environments like legacy operating systems, may in different browsers or may be different database projects. So Lab Management makes manual tester life more easier for creating new environments.
image
By tying all those processes and tools together , you can track the software quality all the way from requirements through their test cases. You can now say how the software quality is doing either up or down over time. You can also on what rate we are automating the test cases.
Reference: Brian Keller talk on Visual Studio launch

Visual Studio 2012 Testing Features for Developers


Developer Testing in Visual Studio 2012 has been improved a lot and it is allowing them to concentrate more on the code they are writing in the application. In addition to the testing framework that comes with Visual Studio 2012, you can easily add third-party testing frameworks in the IDE. This post discusses the new unit and integration testing features for developer in Visual Studio 2012. image
To open the new Test Explorer window, Select the Test Menu then choose windows and click Test Explorer
image
The look and fell of Test Explorer in VS 2012 is different in number of ways. You do not have too many different windows to say same information in new IDE, instead you have one widow that focus on unit and integration testing results.
image
When you select a test case in Test Explorer then you can see the detailed information about the test in below pane. The green bar in test explorer gives you quick view on the out-come.
Integrating Third Party Testing Frameworks
One of the important feature for developers for testing in this release is, it enables you to quickly integrate third-party testing frame-works in VS 2012. So If your team uses N-Unit or XUnit.net or some other testing framework then you can simply install Visual Studio extension.
To open the Extension tools manager, Go to Tools and click Extensions and Updates
image
You can search the framework that you need and download as shown below
image
In Visual Studio 2012 Regard less of which Testing Framework you use, it is fast and scales  up to thousands of test cases.
Developer testing is also very easy to use, If you want to Run or Debug the test that is in your editor then you can right-click on the code and select either run tests or debug tests.
image
You can also Filter the test cases by entering the search term in Test Explorer. You can also group tests with different properties, You can group the tests either by Test Outcome or Duration.
image
If you often require to run unit and integration tests in your solution then with single click in Visual Studio 2012 you can accomplish with Run test after build feature.
image
Now your test will run as part of every build you do.
With a single-click you can analyze and understand various code-metrics about your solution.
image
The Code Metrics Results window will appear as below information like number of line of code , Class Cohesion and Depth of inheritance
image
As it in previous visual studio versions, you can use Code Analysis Tool to quickly find common coding and design mistakes in your code
image
Another new feature in Visual Studio 2012 is Code Clone Analysis, using this feature you can scan your entire solution for duplicate code
image
Code Clone Analysis is smart enough to identify the duplicate code and groups the results with Exact match and medium match.
You can also use code clone feature that matches selected code in editor as shown below
image
Code Coverage Analysis
Code Coverage Analysis tool helps you to know how well your tests exercise your code? Code Coverage Analysis has significantly improved in Visual Studio 2012. To Analyze the code coverage of all the tests in your solution simply click Run drop down in Test Explorer
image
You can browse and explore the Code Coverage Results after completing the run
image
Unit test cases can also run in isolated mode with fakes framework, more information on this can be read here 
Reference: Peter Provost’s talk on Visual Studio launch

Wednesday, September 19, 2012

ASP.NET Web Forms 4.5 new features in Visual Studio 2012


This post discusses about ASP.NET Web Forms 4.5 features, Web Forms in 4.5 allows you to build dynamic web sites quickly and easily. Web Forms generates much cleaner code on client-side with Unobtrusive Validation in this version. You can also build data-centric applications easily with data-binding features. image
Typical Web Form which contains more fields and validation controls can generate more code on client-side. When you run this typical form in browser then you can see the page size as below
image
The reason for this size is because client-side validation is enabled. If you change Unobtrusive validation mode in page load to web forms then you can see the difference.
image
Now re-compile your application and run the page the result is as shown below, Now page size is much smaller than before
image
Strongly typed Data Controls
Take a typical Search Form which shows the results in list view. Inside list view you have item template which is having multiple calls to the EVAL expression as shown below
image
The above method is the standard way of doing data-binding in web forms. You optimize the above using strongly typed data controls.
You can set the Item Type property of List View to the type that you actually data-binding to as shown below
image
Now you can member variables in place of Eval expressions, member variables are now typed and you will get an Intel license on item class.
image 
Model Binding
You may be familiar with Model Binding in ASP.NET MVC, The typical code which you might write in web forms to bind the results in web forms as below
image
The above code talking to the data base by building a query which does a case insensitive search then it coverts into list binds the results to list view. Let us re-write the above code using Model-Binding
image
Now there is no page load and click-handler, The above code is not directly interacting with the page. You can populate the formTerm and qsTerm variables using attributes Control and QueryString in model-binding.
The return result of GetResults method is IQueryable. Because the result is of type IQueryable the control has the ability to modify this before it is rendering it to the page. You can use this in sorting and paging. You can specify the same in markup.
Advantage of using Model Binding As the code is not directly interacting with the page, you can fairly easily unit test the method or even move it to the completely different class.
Support for OpenID in OAuth Logins
image
The AuthConfig.cs file is standard in all new projects that created in ASP.NET 4.5 in Visual Studio 2012. You can see there are number of external services code is commented out and it is ready to use by putting your custom application credentials.
Now you can use external services to login to the application.
image
These are the features which you can try out in Visual Studio 2012.
Reference: Damian Edwards talk in Visual Studio launch.

Agile Development with Visual Studio 2012



Developers want to be more agile and want to cope up with interruptions. This post helps the developers to collaborate with teams using Visual Studio 2012 and focus on what they do as developers.
image
Assume you are in the middle of implementing some requirement or fixing the bug, something else is come may be it is high priority bug or requirement which your manager want you to work on first, I am sure this is common for the developers!
Suspend and Resume work with Visual Studio 2012 
There is a new area of Team Explorer in Visual Studio 2012 called My Work
image
one of the options under My Work  is Suspend & Shelve. When you click Suspend & Shelve it backup all your changes into Team Foundation Server and it also save entire visual studio environment.
image
When you click Resume button then it un-shelve the changes from Team-Foundation server and open up all the windows exactly if where they were before, if you look at the option View Changes in Team Explorer it shows you all pending check in files
image
You can get these pending files in solution explorer using filter option as shown below
image
When you click the Pending Changes Filter then it shows only the files that needs to be checked-in in solution explorer.
Even if you are not sure a particular feature existed in visual studio or not  then you can type the word in Quick Launch bar in Visual Studio IDE then it launches the options windows if it exists in the product.
image
Searching Work Items within Visual Studio
image
Now you can quickly search work items within Visual Studio from Team Explorer window.
As an Agile Developer you may want to improve your code and maintainability , You can then use Analyze menu in Visual Studio and click Analyze Solution for Code Clones
image
What it does is it look-up your entire solution for any blocks of code which look to be similar
image
You can open those files from result window compare and re-factor the code. If you want to know where exactly these files or piece of code in visual studio solution hierarchy then open the file and click sync button in solution explorer then it high-lights the file.
image
You can also do this more granular level by selecting a piece of code in a file and say find the clone. Select the code and right-click on it and then say Find Matching clones in solution
image
what it does is , it looks at your entire solution for anything that similar to the selected lines-of code
image
The results under Medium March category are not necessarily be identical but they may be similar in type of object or operation that you are performing.
I hope the features will definitely helps developers to be more agile in day-to-day coding. More about Visual Studio 2012 IDE features can be read here
Reference: from Brian Keller Visual Studio launch talk

Find a cool free stuff everyday

Giveaway of the Day

Hiren Bharadwa's Posts

DotNetJalps