Code refactoring with Visual Studio 2010 Part-4

I have been writing few post with code refactoring features in Visual Studio 2010. This post also will be part of series and this post will be last of the series. In this post I am going explain two features 1) Encapsulate Field and 2) Extract Interface. Let’s explore both features in details.

Encapsulate Field:


This is a nice code refactoring feature provides by Visual Studio 2010. With help of this feature we can create properties from the existing private field of the class. Let’s take a simple example of Customer Class. In that I there are two private field called firstName and lastName. Below is the code for the class.

public class Customer
{
 private string firstName;
 private string lastName;
 public string Address { get; set; }
 public string City { get; set; }

}

Now lets encapsulate first field firstName with Encapsulate feature. So first select that field and goto refactor menu in Visual Studio 2010 and click on Encapsulate Field. Once you click that a dialog box will appear like following.

EncapsulateField

Now once you click OK a preview dialog box will open as we have selected preview reference changes. I think its a good options to check that option to preview code that is being changed by IDE itself. Dialog will look like following.

PreviewEncapsulateField

Once you click apply it create a new property called FirstName. Same way I have done for the lastName and now my customer class code look like following.

public class Customer
{
 private string firstName;

 public string FirstName
 {
     get { return firstName; }
     set { firstName = value; }
 }
 private string lastName;

 public string LastName
 {
     get { return lastName; }
     set { lastName = value; }
 }
 public string Address { get; set; }
 public string City { get; set; }

}

So you can see that its very easy to create properties with existing fields and you don’t have to change anything there in code it will change all the stuff itself.

Extract Interface:


When you are writing software prototype and You don’t know the future implementation of that then its a good practice to use interface there. I am going to explain here that How we can extract interface from the existing code without writing a single line of code with the help of code refactoring feature of Visual Studio 2010. For that I have create a Simple Repository class called CustomerRepository with three methods like following.

public class CustomerRespository
{
public void Add()
{
    // Some code to add customer
}

public void Update()
{
    //some code to update customer
}

public void Delete()
{
    //some code delete customer
}
}

In above class there are three method Add,Update and Delete where we are going to implement some code for each one. Now I want to create a interface which I can use for my other entities in project. So let’s create a interface from the above class with the help of Visual Studio 2010. So first select class and goto refactor menu and click Extract Interface. It will open up dialog box like following.

ExtactInterface

Here I have selected all the method for interface and Once I click OK then it will create a new file called ICustomerRespository where it has created a interface. Just like following.

SolutionExplorer

Here is a code for that interface.

using System;
namespace CodeRefractoring
{
 interface ICustomerRespository
 {
     void Add();
     void Delete();
     void Update();
 }
}

Now let's see the code for the our class. It will also changed like following to implement the interface.

public class CustomerRespository : ICustomerRespository
{
public void Add()
{
    // Some code to add customer
}

public void Update()
{
    //some code to update customer
}

public void Delete()
{
    //some code delete customer
}
}

Isn't that great we have created a interface and implemented it without writing a single line of code. Hope you liked it. Stay tuned for more.. Till that Happy Programming.

Shout it

kick it on DotNetKicks.com

Code refactoring with Visual Studio 2010-Part 3

I have been writing few post about Code refactoring features of visual studio 2010 and This blog post is also one of them. In this post I am going to show you reorder parameters features in visual studio 2010. As a developer you might need to reorder parameter of a method or procedure in code for better readability of the the code and if you do this task manually then it is tedious job to do. But Visual Studio Reorder Parameter code refactoring feature can do this stuff within a minute. So let’s see how its works. For this I have created a simple console application which I have used earlier posts . Following is a code for that.

using System;

namespace CodeRefractoring
{
  class Program
  {
      static void Main(string[] args)
      {
          string firstName = "Jalpesh";
          string lastName = "Vadgama";

          PrintMyName(firstName, lastName);
      }

      private static void PrintMyName(string firstName, string lastName)
      {
          Console.WriteLine(string.Format("FirstName:{0}", firstName));
          Console.WriteLine(string.Format("LastName:{0}", lastName));
          Console.ReadLine();
      }
  }
}

Above code is very simple. It just print a firstname and lastname via PrintMyName method. Now I want to reorder the firstname and lastname parameter of PrintMyName. So for that first I have to select method and then click Refactor Menu-> Reorder parameters like following.

ReOrderParameters

Once you click a dialog box appears like following where it will give options to move parameter with arrow navigation like following.

ReorderParameterDialog

Now I am moving lastname parameter as first parameter like following.

ReOrderParameterAfterReordering

Once you click OK it will show a preview option where I can see the effects of changes like following.

PreviewOption

Once I clicked Apply my code will be changed like following.

using System;

namespace CodeRefractoring
{
  class Program
  {
      static void Main(string[] args)
      {
          string firstName = "Jalpesh";
          string lastName = "Vadgama";

          PrintMyName(lastName, firstName);
      }

      private static void PrintMyName(string lastName, string firstName)
      {
          Console.WriteLine(string.Format("FirstName:{0}", firstName));
          Console.WriteLine(string.Format("LastName:{0}", lastName));
          Console.ReadLine();
      }
  }
}

As you can see its very easy to use this feature. Hoped you liked it.. Stay tuned for more.. Till that happy programming.

Shout it

kick it on DotNetKicks.com

Code refactoring with Visual Studio 2010 Part-2

In previous post I have written about Extract Method Code refactoring option. In this post I am going to some other code refactoring features of Visual Studio 2010. Renaming variables and methods is one of the most difficult task for a developer. Normally we do like this. First we will rename method or variable and then we will find all the references then do remaining over that stuff. This will be become difficult if your variable or method are referenced at so many files and so many place. But once you use refactor menu rename it will be bit Easy. I am going to use same code which I have created in my previous post. I am just once again putting that code here for your reference.

using System;

namespace CodeRefractoring
{
  class Program
  {
      static void Main(string[] args)
      {
          string firstName = "Jalpesh";
          string lastName = "Vadgama";

          Print(firstName, lastName);
      }

      private static void Print(string firstName, string lastName)
      {
          Console.WriteLine(string.Format("FirstName:{0}", firstName));
          Console.WriteLine(string.Format("LastName:{0}", lastName));
          Console.ReadLine();
      }
  }
}

Now I want to rename print method in this code. To rename the method you can select method name and then select Refactor-> Rename . Once I selected Print method and then click on rename a dialog box will appear like following.

Print

Now I am renaming this Print method to PrintMyName like following.

PrintMyName

Now once you click OK a dialog will appear with preview of code like following. It will show preview of code.

PreviewCode

Now once you click apply. You code will be changed like following.

using System;

namespace CodeRefractoring
{
  class Program
  {
      static void Main(string[] args)
      {
          string firstName = "Jalpesh";
          string lastName = "Vadgama";

          PrintMyName(firstName, lastName);
      }

      private static void PrintMyName(string firstName, string lastName)
      {
          Console.WriteLine(string.Format("FirstName:{0}", firstName));
          Console.WriteLine(string.Format("LastName:{0}", lastName));
          Console.ReadLine();
      }
  }
}
So that’s it. This will work in multiple files also. Hope you liked it.. Stay tuned for more.. Till that Happy Programming.

Shout it

kick it on DotNetKicks.com

My blog post appearing on Channel9.msdn.com

Recently I was searching something and I found that one of the post about New Features of the SQL Server Denali was being discussed on Channel9 on MSDN. It’s a great pleasure and honour to have this kind of appreciation. I would like to thanks again Microsoft for giving opportunity and serve community. I would also like to thanks my readers who are giving me all the support and love.

Once again I am appealing good developers to start blogging. I have seen many great developers are who are doing great stuff but not blogging. I would like to say please please do the blogging and share your stuff with community and you will also get this kind of great appreciation.

Here is the link where they discussed that video.

https://channel9.msdn.com/Shows/This+Week+On+Channel+9/TWC9-Skype-HTML-5-Canvas-Python-tools--more

Following is video where Dan and Clint from Microsoft discussed my blog post on channel 9.



Here are the stuff they have discussed during the video.
Once again thank you for great appreciation. Stay tuned for more.. Happy programming.

Shout it

Code refactoring with Visual Studio 2010 Part-1

Visual studio 2010 is a Great IDE(Integrated Development Environment) and we all are using it in day by day for our coding purpose. There are many great features provided by Visual Studio 2010 and Today I am going to show one of great feature called for code refactoring. This feature is one of the most unappreciated features of Visual Studio 2010 as lots of people still not using that and doing stuff manfully. So to explain feature let’s create a simple console application which will print first name and last name like following.

ConsoleApplication

And following is code for that.

using System;

namespace CodeRefractoring
{
class Program
{
  static void Main(string[] args)
  {
      string firstName = "Jalpesh";
      string lastName = "Vadgama";

      Console.WriteLine(string.Format("FirstName:{0}",firstName));
      Console.WriteLine(string.Format("LastName:{0}", lastName));
      Console.ReadLine();
  }
}
}

So as you can see this is a very basic console application and let’s run it to see output.

Output

So now lets explore our first feature called extract method in visual studio you can also do that via refractor menu like following. Just select the code for which you want to extract method and then click refractor menu and then click extract method. Now I am selecting three lines of code and clicking on refactor –> Extract Method just like following.

ExtractMethod

Once you click menu a dialog box will appear like following.

ExtractMethodDialog

As you can I have highlighted two thing first is Method Name where I put Print as Method Name and another one Preview method signature where its smart enough to extract parameter also as We have just selected three lines with console.writeline. One you click ok it will extract the method and you code will be like this.

using System;

namespace CodeRefractoring
{
class Program
{
  static void Main(string[] args)
  {
      string firstName = "Jalpesh";
      string lastName = "Vadgama";

      Print(firstName, lastName);
  }

  private static void Print(string firstName, string lastName)
  {
      Console.WriteLine(string.Format("FirstName:{0}", firstName));
      Console.WriteLine(string.Format("LastName:{0}", lastName));
      Console.ReadLine();
  }
}
}
So as you can see in above code its has created a static method called Print and also passed parameter for as firstname and lastname. Isn’t that great!!!. It has also created static print method as I am calling it from static void main. Hope you liked it.. Stay tuned for more..Till that Happy programming.

Shout it

kick it on DotNetKicks.com

PetaPoco with parameterised stored procedure and Asp.Net MVC

I have been playing with Micro ORMs as this is very interesting things that are happening in developer communities and I already liked the concept of it. It’s tiny easy to use and can do performance tweaks. PetaPoco is also one of them I have written few blog post about this. In this blog post I have explained How we can use the PetaPoco with stored procedure which are having parameters. I am going to use same Customer table which I have used in my previous posts. For those who have not read my previous post following is the link for that.

Get started with ASP.NET MVC and PetaPoco
PetaPoco with stored procedures

Now our customer table is ready. So let’s Create a simple process which will fetch a single customer via CustomerId. Following is a code for that.

CREATE PROCEDURE mysp_GetCustomer
 @CustomerId as INT
AS
SELECT * FROM [dbo].Customer where  CustomerId=@CustomerId

Now we are ready with our stored procedures. Now lets create code in CustomerDB class to retrieve single customer like following.

using System.Collections.Generic;

namespace CodeSimplified.Models
{
  public class CustomerDB
  {
      public IEnumerable<Customer> GetCustomers()
      {
          var databaseContext = new PetaPoco.Database("MyConnectionString");
          databaseContext.EnableAutoSelect = false;
          return databaseContext.Query<Customer>("exec mysp_GetCustomers");

      }
      public Customer GetCustomer(int customerId)
      {
          var databaseContext = new PetaPoco.Database("MyConnectionString");
          databaseContext.EnableAutoSelect = false;
          var customer= databaseContext.SingleOrDefault<Customer>("exec mysp_GetCustomer @customerId",new {customerId});
          return customer;
      }
  }
}

Here in above code you can see that I have created a new method call GetCustomer which is having customerId as parameter and then I have written to code to use stored procedure which we have created to fetch customer Information. Here I have set EnableAutoSelect=false because I don’t want to create Select statement automatically I want to use my stored procedure for that. Now Our Customer DB class is ready and now lets create a ActionResult Detail in our controller like following

using System.Web.Mvc;

namespace CodeSimplified.Controllers
{
  public class HomeController : Controller
  {
      public ActionResult Index()
      {
          ViewBag.Message = "Welcome to ASP.NET MVC!";

          return View();
      }

      public ActionResult About()
      {
          return View();
      }

      public ActionResult Customer()
      {
          var customerDb = new Models.CustomerDB();
          return View(customerDb.GetCustomers());
      }
      public ActionResult Details(int id)
      {
          var customerDb = new Models.CustomerDB();
          return View(customerDb.GetCustomer(id));
      }
  }
}

Now Let’s create view based on that ActionResult Details method like following.

AddView

Now everything is ready let’s test it in browser. So lets first goto customer list like following.

CustomerList

Now I am clicking on details for first customer and Let’s see how we can use the stored procedure with parameter to fetch the customer details and below is the output.

CustomerDetails

So that’s it. It’s very easy. Hope you liked it. Stay tuned for more..Happy Programming.

Shout it

kick it on DotNetKicks.com

PetaPoco with stored procedures

In previous post I have written that How we can use PetaPoco with the asp.net MVC. One of my dear friend Kirti asked me that How we can use it with Stored procedure. So decided to write a small post for that. So let’s first create a simple stored procedure for customer table which I have used in my previous post. I have written simple code a single query that will return customers. Following is a code for that.

CREATE PROCEDURE mysp_GetCustomers
AS
SELECT * FROM [dbo].Customer
Now our stored procedure is ready so I just need to change my CustomDB file from the my previous post example like following.
using System.Collections.Generic;

namespace CodeSimplified.Models
{
  public class CustomerDB
  {
      public IEnumerable<Customer> GetCustomers()
      {
          var databaseContext = new PetaPoco.Database("MyConnectionString");
          return databaseContext.Query<Customer>("exec mysp_GetCustomers");

      }
  }
}

That's It. Now It's time to run this in browser and Here is the output.

Output

In future post I will explain How we can use PetaPoco with parameterised stored procedure. Hope you liked it.. Stay tuned for more.. Happy programming.

Shout it

kick it on DotNetKicks.com

Get started with ASP.NET MVC and PetaPoco

Micro ORM are having their pro and cons and right now its a buzz in the Microsoft.NET developers buzz. I personally like a Micro ORM Concept and I already posted some blog posts with asp.net mvc and dapper Micro ORM. Today I am going to explain how we can use PetaPoco in asp.net mvc application. First lets get little bit introduction about PetaPoco.

PetaPoco is developed by Top Ten software and It’s Micro ORM inspired by Masive and Dapper. Following is link where you can get more information about that.
http://www.toptensoftware.com/petapoco/.

To install PetaPoco in our application first we need to add a library reference as Its already available there. so Let’s add library reference like following.

AddlibraryReference

Once click on add library reference a dialog box appears to find the the library package like following. I have written PetaPoco in search box and it will be appear in list like following.

PetaPocoNugetPackage

Select first one then click Install and It will install the PetaPoco in your application. Once installation done you will have one t4 teamplte and one PetaPoco.cs file in your model section of ASP.NET application like following.

SolutionExplorer

Now we are ready use the PetaPoco in our application. Now let’s use same DB which we have use for dapper demonstration let’s take same customer table like following.Following is a script to create table.

/****** Object:  Table [dbo].[Customer]    Script Date: 06/17/2011 02:27:34 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Customer](
   [CustomerId] [int] IDENTITY(1,1) NOT NULL,
   [FirstName] [nvarchar](50) NULL,
   [LastName] [nvarchar](50) NULL,
   [Address] [nvarchar](256) NULL,
   [City] [nvarchar](50) NULL,
CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED
(
   [CustomerId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

Now I have inserted some sample data in the table and now its ready to use. Now I have added a Model Entity class which contains same properties as Table columns. Just like following.
namespace CodeSimplified.Models
{
   public class Customer
   {
       public int CustomerId { get; set; }
       public string FirstName { get; set; }
       public string LastName { get; set; }
       public string Address { get; set; }
       public string City { get; set; }
   }
}

Now we are ready with our class I have create a new class called CustomerDB to fetch customer from the database. In that class I have created method called GetCustomers which will fetch all the customer from database. Here I have created a database object of PetaPoco and then I have using Its query method to query database. Following is a code for that.
using System.Collections.Generic;

namespace CodeSimplified.Models
{
   public class CustomerDB
   {
       public IEnumerable<Customer> GetCustomers()
       {
           var databaseContext = new PetaPoco.Database("MyConnectionString");
           return databaseContext.Query<Customer>("Select * from Customer");
       }
   }
}

Now as this is for demo purpose only lets create a method in Home Controller class to get customers like following.
using System.Web.Mvc;

namespace CodeSimplified.Controllers
{
   public class HomeController : Controller
   {
       public ActionResult Index()
       {
           ViewBag.Message = "Welcome to ASP.NET MVC!";

           return View();
       }

       public ActionResult About()
       {
           return View();
       }

       public ActionResult Customer()
       {
           var customerDb = new Models.CustomerDB();
           return View(customerDb.GetCustomers());
       }
   }
}

Now once done we with Customer Method in Home Controller let’s create view for that. Here I have created a strongly typed view like following for customers.

View

Now we are done with our view also So let’s run the project and let’s see output in browser. You can see output in browser as expected like following.

Output

So it’s very easy to use PetaPoco with ASP.NET MVC. Hope you liked it. Stay tuned for more..

Shout it

kick it on DotNetKicks.com

Tech-Ed on Road 2011- Ahmedabad–A great event

Last Saturday on June 11,2011 Ahmedabad was having Microsoft Tech-Ed on Road event. I was fortunate to being part of it. I have attended many community events in Ahmedabad but this time we get overwhelming response and approx. 300 to 400 persons where there in person and organizers were having hard time to arrange seats for them.

DSCN0369

As always first event was started by welcome note where Pinal Dave has delivered a very short and sweet welcome note and then we have got our first speaker Mahesh Dhola on Lightswitch on cloud. In his session he has shown us some excellent features of the Visual Studio Lightswitch . He has created a CRUD Silverlight application without writing zero lines of code and with all the business validation and all the basic stuff that required for a application. The session contained lots practical demos.

DSCN0373

After that session we had very own Technology Evangelist Pinal Dave. He has taken session on SQL Server Waits and Queues – Your gateway to performance troubleshooting. In his session he has explained what is the use of waits and queues and How we can increase the performance of our database with solving problems related waits and queues. Hi has made us fill that there is simple solutions to big problems and He also showed demo of some of the waits types. As our another speaker Harish Vaidyanathan said Pinal’s session was full of drama and emotions.

DSCN0389

After that we have got another great speaker Harish Vaidyanathan. Who has taken session on HTML5- Future of web. He has got some excellent demos of HTML5 and CSS3 and also he has explained some of the features of Internet Explorer 9 and also explained How IE9 utilized resources on machine to serve web content faster then other browsers. We have learned a lots from him and we have proud to have him at Ahmedabad.

DSCN0403

After session of HTML5 we had lunch and its a great way to meet people and exchange your knowledge with them. I have met many great people over there who are already serving community to a lot. After the lunch we had a small session and demo from Microsoft MVP Dhananjay Kumar. In his session he has delivered and showed demo of some of cool features of Microsoft new windows phone operating system called Windows Phone 7 Mango. It was to great to see multitasking third party applications.

DSCN0421

After that We have one of the great session of the event. Our own proud of Ahmedabad the SQL and XML Guru Jacob Sebastian. He has delivered excellent session on TSQL Worst practices. In his sessions we have gone through some of the excellent scenarios where SQL Queries looks fine and work in some scenarios but it can be dangerous in some of the scenario. Usually we don’t care of that but he made us feel that we should not use this kind of queries.

DSCN0430

After that we have got another good session about from our local Guys Tejas Shah who has delivered session on ASP.NET Tips and Tricks. In that he has explained some of basic features of asp.net with best practice to use them.

DSCN0433

After that We has small demos of from the Kaushal Bhavsar about Silverlight 5 features.

DSCN0434

After that we have some quiz and also announced some of winners for quiz one of my friend Kirti Darji also got pen drive a part of quiz winner.

DSCN0416

It was a great event and I would to take this opportunity to thanks Microsoft and Ahmedabad User .NET groups and other organizers to have such kind of events. I am also looking for some of forthcoming events. Following are some of links from where you can find presentations and scripts that are used in demos.

HTML5 Beauty of Web -By Harish Vaidyanathan
TSQL Worst Practices- By Jacob Sebastian
SQL SERVER Performance troubleshooting using Waits and Queues -By Pinal Dave
ASP.NET Tips and Tracks -By Tejas Shah
LightSwitch on cloud- By Mahesh Dhola

Shout it

Important milestone achieved!!- I got 300000 visitors for my blog

I have been writing this blog since last four years and I am working on hard on this to server community which I love most as much as I can. Here I got great news from www.sitemeter.com that my blog has achieved 300000 mark.  I would like to take this opportunity to thanks all my readers who has supported me all time whenever I write blogs. I got some nice appreciations from people and that’s encourage me to write more blogs.

Followings are my statistics from the sitemeter.com. Till I was writing this blog post I got 304412 visits to my blog and 368759 page views from my blog. Following are screenshots of my statistics.

Vistors

Pageviews

Pageviews

Here is another one from blogger itself that is saying that I am getting 22500 page views last moth.

GooglePageview

When I get appreciation from you guys like this then its feels great. Once this occasion I would like to tell you that if you are having passion for any technologies then please do write blogs. Because you are not going to share it you are not going to gain more knowledge.

Shout it