Showing posts with label C#.NET. Show all posts
Showing posts with label C#.NET. Show all posts
Friday, August 24, 2012

What is Inversion of control and why we need it?

Most of programmer need inversion of control pattern in today’s complex real time application world. So I have decided to write a blog post about it. This blog post will explain what is Inversion of control and why we need it. We are going to take a real world example so it would be better to understand.

The problem- Why we need inversion of control?


Before giving definition of Inversion of control let’s take a simple real word example to see why we need inversion of control. Please have look on the following code.

public class class1
{
    private class2 _class2;

    public class1()
    {
       _class2=new class2();
    }

}
public class class2
{
     //Some implementation of class2
}

I have two classes “Class1” and “Class2”.  If you see the code in that I have created a instance of class2 class in the class1 class constructor. So the “class1” class is dependent on “class2”. I think that is the biggest issue in real world scenario as if we change the “class2” class then we might need to change the “class1” class also. Here there is one type of dependency between this two classes that is called Tight Coupling. Tight coupling will have lots of problem in real world applications as things are tends to be change in future so we have to change all the tight couple classes that are dependent of each other. To avoid this kind of issue we need Inversion of control.
Share:
Friday, June 22, 2012

Why C# does not support multiple inheritance?

Yesterday, One of my friends, Dharmendra ask me why C# does not support multiple inheritance. This is the question most of the people ask every time. So I thought it will be good to write a blog post about it. So why it does not support multiple inheritance?

I tried to dig into the problem and I have found the some of good links from C# team from Microsoft for why it’s not supported in it. Following is a link for it.

http://blogs.msdn.com/b/csharpfaq/archive/2004/03/07/85562.aspx


Also, I was giving some of the example to my friend Dharmendra where multiple inheritance can be a problem.The problem is called the diamond problem. Let me explain a bit. If you have class that is inherited from the more then one classes and If two classes have same signature function then for child class object, It is impossible to call specific parent class method.
Share:
Thursday, May 3, 2012

Review of 70-562exam preparation kit from uCertify

Before some time I got an offer from uCertify to review their examination kit. I was lot busy this days so was able to do early but now I have completed review of it. So the first things to do is to download preparation  kit from their website. Here is the link from where I have downloaded this.

http://www.ucertify.com/exams/Microsoft/70-562-CSHARP.html
Share:
Tuesday, April 17, 2012

Difference between SkipWhile and Where in linq

Before some time I have written a blog post about the SkipWhile operator and a reader of my blog asked me that we can do the same thing with Where also but there is a difference between this two. So In this post I am going to explain you difference between those two.

Where operator filters a list of collection based on condition. It will filter whole collection while SkipWhile will only skip those elements in list until condition is true and after that it will stop filtering of skipping.Now let’s take an example where we can see the difference between Where and SkipWhile. Following is a code for that.
Share:
Monday, April 16, 2012

Tuple in C# 4.0

C# 4.0 language includes a new feature called Tuple. Tuple provides us a way of grouping elements of different data type. That enables us to use it a lots places at practical world like we can store a coordinates of graphs etc.

In C# 4.0 we can create Tuple with Create method. This Create method offer 8 overload like following. So you can group maximum 8 data types with a Tuple. Followings are overloads of a data type.
  • Create(T1)- Which represents a tuple of size 1
  • Create(T1,T2)- Which represents a tuple of size 2
  • Create(T1,T2,T3) – Which represents a tuple of size 3
  • Create(T1,T2,T3,T4) – Which represents a tuple of size 4
  • Create(T1,T2,T3,T4,T5) – Which represents a tuple of size 5
  • Create(T1,T2,T3,T4,T5,T6) – Which represents a tuple of size 6
  • Create(T1,T2,T3,T4,T5,T6,T7) – Which represents a tuple of size 7
  • Create(T1,T2,T3,T4,T5,T6,T7,T8) – Which represents a tuple of size 8
Share:
Saturday, April 14, 2012

TakeWhile operator in linq

In this post I am going to explain TakeWhile Operator in details. TakeWhile is one of partitioning operator available in Linq. It will take sequence until condition becomes false.

Here is the example for that.

using System;
using System.Collections.Generic;
using System.Linq;
namespace Linq
{
class Program
{
  static void Main(string[] args)
  {
      int[] numbers ={10,9,8,7,6,5,4,3,2,1};

      foreach(var number in numbers.TakeWhile(n=>n>5))
      {
          Console.WriteLine(number);
      }
  }
}
}


Share:

SkipWhile Method in Linq

I have been playing around linq and I have found great method call SkipWhile method. SkipWhile methods skips particular element which matches condition in predicate this can be use full in condition where we need to skip elements on particular condition.

So let’s take some example. I have written following console application code.

using System;
using System.Collections.Generic;
using System.Linq;
namespace Linq
{
  class Program
  {
      static void Main(string[] args)
      {
          string[] names = { "Jalpesh", "Jayesh", "Tushar", "Tejas", "Sanjay", "Nijesh" };
          foreach(var name in names.SkipWhile(s=>s.ToLower().StartsWith("j")))
          {
              Console.WriteLine(name);
          }
      }
  }
}

Share:
Friday, April 13, 2012

Multicast delegates in c#

In yesterday’s post We learn about Delegates and how we can use delegates in C#. In today’s blog post we are going to learn about Multicast delegates.

What is Multicast Delegates?

As we all know we can assign methods as object to delegate and later on we can call that method with the help delegates. We can also assign more then methods to delegates that is called Multicast delegates. It’s provide functionality to execute more then method at a time. It’s maintain delegates as invocation list (linked list).
Share:
Thursday, April 12, 2012

Delegates in c#

I have used delegates in my programming since C# 2.0. But I have seen there are lots of confusion going on with delegates so I have decided to blog about it. In this blog I will explain about delegate basics and use of delegates in C#.

What is delegate?

We can say a delegate is a type safe function pointer which holds methods reference in object. As per MSDN it's a type that references to a method. So you can assign more than one methods to delegates with same parameter and same return type.
Share:
Wednesday, April 4, 2012

Ternary operator in VB.NET

We all know about Ternary operator in C#.NET. I am a big fan of ternary operator and I like to use it instead of using IF..Else. Those who don’t know about ternary operator please go through below link.

http://msdn.microsoft.com/en-us/library/ty67wk28(v=vs.80).aspx

Here you can see ternary operator returns one of the two values based on the condition. See following example.
Share:

How to pad number with leading zero with C#

Recently I was working with a project where I was in need to format a number in such a way which can apply leading zero for particular format. So after doing such R and D I have found a great way to apply this leading zero format.

I was having need that I need to pad number in 5 digit format. So following is a table in which format I need my leading zero format.

1-> 00001
20->00020
300->00300
4000->04000
50000->5000

So in the above example you can see that 1 will become 00001 and 20 will become 00200 format so on. So to display an integer value in decimal format I have applied interger.Tostring(String) method where I have passed “Dn” as the value of the format parameter, where n represents the minimum length of the string. So if we pass 5 it will have padding up to 5 digits.
Share:
Sunday, January 8, 2012

string.format escape sequence in c#

Recently I was working on something and I need to put a curly bracket on the string with a string.format function but I was not aware how to to do it. So I did some search on internet and found how to give escape sequence in string.format. Suppose You need to put curly bracket then you have write two ‘{{‘ instead of { to put ‘{‘ and same way ‘}}’ to put ‘}’

Let’s take simple example. Following is a code where I am printing simple string with string.format and Response.Write.

using System;
using System.Web.UI;

namespace CallBack
{
    public partial class Index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write( string.Format(@"{{ escape sequence for string format from {0}}}", "DotNetJalps"));
        }

    }
}


Now let’s run that example in browser and let’s see how it goes.


C#,Escape Sequence,String.format

That’s it. It’s very easy to use.Hope you liked it. Stay tuned for more..Happy Programming.

Shout it

kick it on DotNetKicks.com
Share:
Saturday, December 24, 2011

Page methods in asp.net

Now days people are looking for richer and fluid user experience and to create that kind of application Ajax is required. There are several options available to call server-side function from JavaScript with ASP.NET Ajax and if you are using asp.net 2.0 or higher version of Microsoft.NET Framework then page methods are one of best options available to you.

Page methods are available there from asp.net 2.0. If works just like a normal web service. You can direct call that page methods directly from the JavaScript.

Let’s take a real world example. I will call java script on button client click event and then from that we call server-side function from the page methods. So let’s create a project called Pagemethods via File->New Project like following

Page methods in ASP.NET

After that I have created a page called test.aspx and now I am creating page method called GetCurrentDate like following.

using System;
using System.Web.Services;

namespace PageMethods
{
   public partial class Test : System.Web.UI.Page
   {
      [WebMethod]
      public static string GetCurrentDate()
      {
          return DateTime.Now.ToShortDateString();
      }
   }
}

As you can see in above there is  a web method called GetCurrentDate which is just returning short date in string format. Here you will notice that I have putted WebMehod attribute for that method this is a perquisite for page methods to make available in client side.

Now let’s write code for HTML and JavaScript and following is a HTML code for that.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="PageMethods.Test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Page Method demo</title>
</head>
<body>
   <form id="form1" runat="server">
   <div>
       <asp:ScriptManager runat="server" EnablePageMethods="true" EnablePartialRendering="true">
       </asp:ScriptManager>

       <asp:button ID="btnGetDate" runat="server" Text="Get date from server" OnClientClick="return GetDateFromServer();"/>
   </div>
   </form>
</body>
</html>

As you can see in above code I have taken an ASP.NET button which call client side function GetDateFromServer which call page methods and get server date. Following is a javascript code for that.

<script type="text/javascript">
   function GetDateFromServer() {
       PageMethods.GetCurrentDate(OnSuccess, OnError);
       return false;
   }
   function OnSuccess(response) {
       alert(response);
   }
   function OnError(error) {
       alert(error);
   }
</script>

As you can see in GetdateFromServer methods I have called our page method Get Current date and you can see PageMethods object in JavaScript has all the methods which are available from server-side. I have passed two event handler for success and error. If any error occurred then it will alert that error and on successful response from server it will alert a current date.

So it’s now time to run that in browser.So once you pass F5 then once you click ‘Get date from server’ the output is like following as expected.

PageMethodOutput

That’s it as you see it’s very easy.Hope you like it. Stay tuned for more.Till then happy programming..

Shout it

kick it on DotNetKicks.com
Share:
Saturday, October 8, 2011

NuGet with multiple projects part-2

Before some days I have posted one post about how we can add NuGet package other than start project. In this post I am going to explain another way of doing that.

Earlier we have use ‘Manage NuGet Package’. Today I am going to use Package Manager Console for that. So let’s take same example which we have used in the earlier post. I have a sample application which have three projects.

MyApplication- Nuget with multiple projects. www.dotnetjalps.com

As you can see in above post there are three projects.
  1. MyApplication-Main Web application project
  2. MyApplication.Business- This project has business logic classes for application
  3. MyApplication.Data- This project has database access layer classes for application
Now I want to add Entity Framework MyApplication.Data Project. As we have to use Package Manager Console. We need to open package manager console you have click Tools->Library Package Manager –>Package Manager Console. Once you click that it will open a console in visual studio like following

.
PackageManagerConsole

Now as I have to type following command in NuGet Package Manager Console to install EntityFramework Package to MyApplication.Data project

Get-Project MyApplication.Data | Install-Package EntityFramework

Here in above command Get-Project will get the project where we have to install the project and Install-Package will install the required package. As you can see entityframework reference added in MyApplication.Data Project in below image.

EntityFrameworkReference

That’s it. Hope you like it. Stay tuned for more.. Till then Happy programming

Namaste!!
Share:
Wednesday, September 14, 2011

BigInteger in C# 4.0

In C# 4.0 Microsoft has added so many features and I love all most all the features. In today’s post we are going to discuss BigInteger Class. During programming some complex systems often we need a very big numbers. For example if we use some of asymmetrical cryptographic feature which require to use large numbers or we can give simple example of factorial where we sometime reached to limit of data type provided by C# compiler. At that time this BigInteger data type can be very handy. You can store 232 to 264 number in this data type. So its very big and you can copy very very big number in that data type.

So let’s take a simple example to write a factorial program. BigInteger data type comes under System.Numerics namespace. So first we have to add reference to our program to System.Numerics assembly like following.

Big Integer In C# 4.0 - Add Reference to System. Numeric

Now we have added the reference to System.Numeric so we are ready for code. Here in code I have just taken a very large number in big integer which is out of range of integer to test out. So I have assigned ‘39242937852522522’ to big integer object and printed that. Following is a code for that.

using System;
using System.Numerics;

namespace ExperimentConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            BigInteger n = 39242937852522522;
            Console.WriteLine(n);
        }
    }
}
Let’s run code and see output like following as expected its printing value.

Output

If you are run same program with integer it will not compile. It will give ‘Can not covert type long to integer error’. That’s it. Hope you liked it. Stay tuned for more.. Till then happy programming. Namaste!!

Shout it
Share:
Sunday, August 28, 2011

Visual Studio 2010 Features post list on my blog

Share:
Tuesday, August 16, 2011

Setting default value for @Html.EditorFor in asp.net mvc

Yesterday one of my friend asked me to set default value for @HTML.EditorFor in ASP.NET MVC. So I decided to write this blog post. In this blog post I am going to Explain How we create Default values for model Entities. So Let’s start this via taking a simple example Model class called User. In User Model class I have created two properties UserName and UserJoinedDate. Following is a code for that.
using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;



namespace CodeSimplified.Models

{

public class User

{

    private DateTime _userJoinDate = DateTime.Now;



    public DateTime UserJoinDate

    {

        get

        {

            return _userJoinDate;

        }

        set

        {

            _userJoinDate = value;

        }

    }



    public string UserName

    { get; set; }

}

}
As you can see in above class username is default property while for UserJoinedDate I have used old method of declaring properties. Where I have assigned a private variable with System DateTime.
Now let’s Create a Action Result User in Home Controller like following where I am returning a new User View like following.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

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 User()

    { return View(new CodeSimplified.Models.User()); }

}

}

Now Let’s Create User View from the action right click Add view like following. Here I have created Strongly Typed view like following.


User

Once you click Add It will add a new View like following.

@model CodeSimplified.Models.User



@{

ViewBag.Title = "User";

}



<h2>User</h2>



<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>

<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>



@using (Html.BeginForm()) {

@Html.ValidationSummary(true)

<fieldset>

    <legend>User</legend>



    <div class="editor-label">

        @Html.LabelFor(model => model.UserJoinDate)

    </div>

    <div class="editor-field">

        @Html.EditorFor(model => model.UserJoinDate)

        @Html.ValidationMessageFor(model => model.UserJoinDate)

    </div>



    <div class="editor-label">

        @Html.LabelFor(model => model.UserName)

    </div>

    <div class="editor-field">

        @Html.te

        @Html.EditorFor(model => model.UserName)

        @Html.ValidationMessageFor(model => model.UserName)

    </div>



    <p>

        <input type="submit" value="Create" />

    </p>

</fieldset>

}



<div>

@Html.ActionLink("Back to List", "Index")

</div>


Now everything is ready so Let's run that in browser. Following is the output as expected.

Browser

So that’s it. It’s very easy. Hope you liked it. Stay tuned for more.. Till then happy programming.

Shout itkick it on DotNetKicks.com
Share:
Saturday, August 13, 2011

Visual Studio 2010 Color Theme Editor- Customize look of visual studio

We have all love Visual Studio 2010 and I am sure you all want to change color for menus, toolbars and title etc. Today I have found one of the most interesting Extension for Visual studio 2010 from which you can manage all this things. Don’t believe me I’m sure you won’t believe but this reality and You can change the look of your favorite visual studio look and feel. There is a new extension called “Visual Studio Color Theme Editor” from which you can do all this stuff. Here is the link for that.

http://visualstudiogallery.msdn.microsoft.com/20cd93a2-c435-4d00-a797-499f16402378

Once you download and install this link a Theme Menu will be added to Visual Studio like following.

ThemeMenu

There are 8 themes provided by the Default. You can choose any one of them. Lets choose Emerald theme for visual studio and It will look like following.

EmerlandThemeForVisualStudio

Isn’t that great?. Even you can also design your own theme also. Click on Theme->Customize colors and then It will popup a dialog like following. where you can will get lots of things for which you can customize the color.


CustomisedColorDialogForVisualStudio

Isn’t that Great. Hoped You liked it. Stay tuned for more..Till then happy programming..


Shout itkick it on DotNetKicks.com
Share:
Tuesday, August 2, 2011

Surround with feature in Visual Studio 2010

Everyday I am discovering something new with Visual Studio 2010 and today Once again I have discovered a new feature called “Surround with” feature. This feature is quite useful when you have very big HTML element and You want to surround it some HTML or ASP.NET element i.e. Suppose there is one very big div there and you want to add update panel for Ajax . So let’s take a Simple Example over there. I am having a div which contain very big HTML in it. Like following.

<div>

 Very big HTML here.

</div>

Now let's put that div into update panel with Surround with feature. You can right click and click Surround With or You can directly have shortcut Ctrl+k, Ctrl +S like following.

SurroundMenu

Now once you click it It will popup three things. 1) ASP.NET 2) ASP.NET MVC 2 and 3) HTML. You can select element of any of that like following.

SurroundPopup

I am going select ASP.NET as we want to put Update panel over there. Once you click ASP.NET It will popup elements of asp.net. Here I have selected update panel as I want to put update panel covering this div like following.

UpdatePanel

Now once you click update panel it will put Update panel and div will be in content template of Update panel. Now our code will like following.

<asp:UpdatePanel runat="server">

 <ContentTemplate>

     <div>

         Very big HTML here.

     </div>

 </ContentTemplate>

</asp:UpdatePanel>

That's it. Isn't that cool?.Isn't visual studio 2010 is a great IDE? Hope you like it. Stay tuned for more.. Till then Happy Programming..

Shout itkick it on DotNetKicks.com
Share:
Sunday, July 31, 2011

SQL Management Studio in Visual Studio 2010

Microsoft Visual Studio 2010 is a great IDE and everyday I am discovering something new about it. Today I am also going to explain new feature of Visual Studio 2010. In this post I am going to Transact SQL Editor feature in Visual Studio 2010.

Visual Studio 2010 Ultimate Edition provides this great feature. You can run you SQL Queries in visual studio 2010 itself with all intellisense and all the stuff that SQL Server provides. Let’s explore in details.
To connect the database of your SQL Server in Visual studio Go to Data->Transact SQL Editor –>New Query connection like following.

SSMS 

Now once you click it will open the dialog box for connection SQL server like it. If you don’t have install anything it will install SQL Server 2008 express edition with Visual Studio 2010 Ultimate Edition. The dialog appear like following.


SQLServer

Once you are done with the connection it will open full fledge Query editor windows with intellisesnse like following.

Intellisense

Also it can connect to any databases including your SQL Azure databases also. Isn’t that great. You don’t need SQL management studio at all for the basic database operations. That’s it. Hope you like it. Stay tuned for more.. Till then happy programming.


Shout itkick it on DotNetKicks.com
Share:

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews