Nice website for C# developer

Do check out this very very useful web-site for c# developer for understanding
multi threading and it has got some wonderful tools like

QueryExpression – which has an user interface similar to query analyzer using which we can query oracle, sql server and other databases. It is also very light weight.

LinqPad for practicing the Linq syntax.

Creating custom application exception C#


There are times when we are creating a custom class and the class needs to have it’s own application specific exception which can be thrown so that calling program can be aware of the error condition.

Say we have a class named BillingUpdate which has a condition that the billing amount should never be less than 10,000.

Say it has a function which accepts billing amount in one of it’s methods as a parameter and we need to make the user of this function aware of the condition that it can’t take billing amount less than 10000.

In this case what we can do is

create a custom class BillingException which inherits SystemException class

// creating a custom class that inherits from SystemException.
class BillingException :SystemException
// overloading the constructor for passing the message associated with the exception
public BillingException(string message)
: base(message)

Now to use this exception class we can do the following

public void GetBillingAmount(decimal billingAmount)
if(billingAmount < 10000M)
throw new BillingException(“Billing amount can’t be less than 10000”);

And the calling code can do something like this

BillingUpdate billingUpdate = new BillingUpdate();
BillingException ex)


Using Transaction In ADO.NET


In most of the cases we need to execute a number of statements together.

Best example would be a bank transaction in which we are debiting certain amount from one of the user’s account and crediting the same in someone else’s account. So in this case the entire thing should run or nothing should run.

We have in our .NET framework various transaction class one for each .NET-managed provider i.e.

OracleTransaction, OleDbTransaction, SqlTransaction etc.

The most basic way we can use the transaction class is the following way

SqlTransaction myTransaction;
SqlCommand myCommand1 = new SqlCommand();
myCommand1.CommandText = “some command”;
SqlCommand myCommand2 = new SqlCommand();
myCommand2.CommandText = “some command”;
using(SqlConnection myConn = new SqlConnection(connectionString))

myTransaction = myConn.BeginTransaction();

myCommand1.Connection = myConn;
myCommand1.Transaction = myTransaction;

myCommand2.Connection = myConn;
myCommand2.Transaction = myTransaction;




Using Forms Authentication in Asp.NET

Hi All,

To use form authentication in application

1- Create a new website

2- Change the name of the default.aspx to login.aspx

3- Add 2 labels one for username and password and two textboxes name txtUserName and txtPassword

and a button named btnLogin with label Login.

4 -Put the following in the web.config page

<authentication mode=”Forms”>
<forms loginUrl=”login.aspx”>
<credentials passwordFormat=”Clear”>
<user name=”Mickey” password=”Mouse”/>
<deny users=”?”/>

5-Put this code in the btnLogin click’s event handler.

protected void btnLogin_Click(object sender, EventArgs e)
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, false);
lblInfo.Text = “you are not authorized to view the page”; // add one more label lblInfo }

6- That’s it your page should work now

We can add more users within the credential section of web.config

We can even encrypt the password we are saving in the web.config

We can even make use of cookie for the same.

Looking forward to include the code for the same


JavaScript and Microsoft Dynamics CRM

I was thinking that it would have been nice if some expert would have written some article or post about how to use JavaScript within CRM.

And today only i came to know about such an article , it is written by none other than MichaelHohne, the CRM guru, the creator of stunnware site( the most helpful site for Microsoft CRM Developer)

For different things we can do by making use of JavaScript in Microsoft Dynamics CRM,

Plzzzz check and bookmark this url


Operation failed due to a SQL integrity violation


Today i was suppose to write a callout which would be sending email to owner’s manager for our opportunity entity.

I thought before trying out with an callout(which is really hard to debug) i should try it first in a windows application. Finally after some time i was able to get it working.

So than i decided to put the same code in the callout as well. But to my surprise i found that the same code was not working in the callout.

This was the error i was getting as

ex.detail.innerxml // for (SoapException ex)

<description>Operation failed due to a SQL integrity violation.</description>

After searching on the internet for the same i was able to find the cause for the error in my code

For my windows application this piece of code was sufficient

CrmService service=new CrmService();

But when it came to callout it had to be

CrmService service=new CrmService();
service.CallerIdValue = new CallerId();
service.CallerIdValue.CallerGuid =userContext.UserId;

This helped me to solve the error.

Check this link as well


Creating a simple Hello World ASP.NET AJAX web page.


Here we will create a simple ASP.Net Ajax webpage having a button and textbox control in it.
On the click of button we will fill the textbox with “Hello world” string returned from the server without refreshing our webpage.

1) Create a new ASP.NET Ajax web site(Visual Studio 2005)or ASP.NET web site (version 3.5) if we are using Orcas(Visual studio 2008)

2) Add a ScriptManager control in the page( if it isn’t there)

3) Add button and textbox server side control.

<asp:TextBox ID=”TextBox1″ runat=”server” />

<asp:Button ID=”Button1″ runat=”server” Text=”Button” />

4) Add this event Handler for button click event

protected void Button1_Click(object sender, EventArgs e)
TextBox1.Text=”Hello World”;

4) Now to make our page AJAX enabled the only thing we need to add is

<asp:UpdatePanel id=up1 runat=server>

<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>
<asp:Button ID=”Button1″ runat=”server” onclick=”Button1_Click” Text=”Button” />


Just wrap our server side controls inside update panel control’s content template.

5) That’s it. Now run the application and click on the button the textbox should get filled with Hello World string without any refresh of the page.

Right now what we saw was a server-centric approach using updatePanel control.

We can do the same thing using client-centric approach using ASP.NET AJAX client library. Check this post



Creating and Calling ASP.NET AJAX Web Service


First we will create a new ASP.NET Ajax web site(Visual Studio 2005)
or ASP.NET web site (version 3.5) if we are using Orcas(Visual studio 2008)

Through Add New Item, add a new web service WebService.asmx in the website.

1) Add this in webservice.cs

using System.Web.Script.Services;

2) Add a ScriptService attribute to our webservice class

[WebService(Namespace = “;)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

3) We’ll use the default Hello World web service. So just save the web service and view it in browser to test it.

Now change the url of the webservice in browser and append “/js” to it

Press enter it will ask you to save the file,
just save and open it in notepad

We will see something like this

var WebService=function() {
this._timeout = 0;
this._userContext = null;
this._succeeded = null;
this._failed = null;
_get_path:function() {

This is a javascript proxy class which the our client side ajax library will use to make call to our web service.

4) Add a script manager control to our default.aspx page ( if not already there), and add the reference to our web service

<asp:ScriptManager ID=”ScriptManager1″ runat=”server”>
<asp:ServiceReference Path=”WebService.asmx” />

5) Now add a simple html text control on the default.aspx page. We will be calling our web service and fill the text box value returned from the webservce (“Hello World”).

<input id=”Text1″ type=”text” />

6) Put this script on your default.aspx page

<script type=”text/javascript”>

function pageLoad()

function onSuccess(result)


7) Now just view the page in browser we should see the textbox filled with “Hello World” string returned from our web service.

8) Or if we want to call it in the click of the button. add a html button control.

<input id=”Button1″ type=”button” value=”button” />

9) Replace the above script with this one

<script type=”text/javascript”>
var myButton=null;
function pageLoad(sender,e)

function btn_click(sender,e)

function onSuccess(result)

In the above example we saw a client centric approach, the same thing can be done very easily by making use  of server centric approach in ASP.NET AJAX framework.



Creating Word document using C#

Create a new windows application project and add a button to it.

On click of that button, we will create a new document(word) and write a simple Hello World text in it.

To create a word document using C# we need to first reference the following DLL(com)


After adding reference, add this directive

using Microsoft.Office.Interop.Word;

Put this code on button click

    private void button1_Click(object sender, EventArgs e)


            object missing = System.Reflection.Missing.Value;

            object Visible=true;

            object start1 = 0;

            object end1 = 0;


            ApplicationClass WordApp = new ApplicationClass();

            Document adoc = WordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);

            Range rng = adoc.Range(ref start1, ref missing);




                rng.Font.Name = “Georgia”;

                rng.InsertAfter(“Hello World!”);

                object filename = @”D:\MyWord.doc”;

                adoc.SaveAs(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing,

                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);

                WordApp.Visible = true;


            catch (Exception ex)





The easiest way to write code for office interoperability is to make use of VBA code.

Say you want to insert a picture in a word document what you can do is

open the word document – Go to Tools ->Macro-> Record New Macro

Now click on insert menu and insert the picture. Stop the recording, again go to Macro -Macros-> Select your Macro and click on edit

You will find the vba code over there

Sub Macro1()

Selection.InlineShapes.AddPicture FileName:= _
“C:\Documents and Settings\nishantr1\My Documents\My Pictures\untitled.bmp” _
, LinkToFile:=False, SaveWithDocument:=True
End Sub

Now to write the same code in c# you will do something like this

Range rngPic = adoc.Tables[1].Range;

rngPic.InlineShapes.AddPicture(@”C:\anne_hathaway.jpg”, ref missing, ref missing, ref missing);


Saving and Retrieving richtextbox control’s content (.rtf file) in database

Let’s start with a very simple application.


Drop OpenFileDialog control in the application.

When user click on Pick File button using OpenFileDialog he will select a rtf file to display in richtextbox control.

The content of richtextbox control will be saved in the sql server table.

This is how our table looks like.


File content is the image data type column where we will store our rtf content.

<!–[if gte vml 1]> <![endif]–>

Put the following code in Pick file button click.

if(openFileDialog1.ShowDialog() == DialogResult.OK)






catch(Exception ex)





Put the following code in Save Button Click

SqlConnection conn=new SqlConnection(“Data Source=D-0824;Initial Catalog=WordInterOp; uid=sa;pwd=sa;”);

SqlCommand cmd=new SqlCommand();

cmd.CommandText = “Insert into RtfStore (fileName,fileContent) values ( @fname,@fcontent)”;


SqlParameter fileName=new SqlParameter(“@fname”,openFileDialog1.SafeFileName);

rtfContent.SaveFile(@”c:\temp.rtf”, RichTextBoxStreamType.RichText);

FileStream stream = new FileStream(@”c:\temp.rtf”, FileMode.Open, FileAccess.Read);

int size = Convert.ToInt32(stream.Length);

Byte[] rtf = new Byte[size];

stream.Read(rtf, 0, size);

SqlParameter fileContent=new SqlParameter();








int success=cmd.ExecuteNonQuery();



MessageBox.Show(“Entered data successfully”);


openFileDialog1.SafeFileName- To get the name of file instead of the complete path.

rtfContent.SaveFile- Saving the content of the control in a rtf file.

RichTextBoxStreamType.RichText– This tells that we are saving richtext having some formatting and not just plain text.

Finally through filestream we are reading that file and saving it’s content in our sqlserver table.

Similary to read the rtf content from the database and display it in Richtextbox control, this is what we need to do

// cmd.commandText=”select fileContent from RtfStore where filename=’xyz’ “;

SqlDataReader dr =  cmd.ExecuteReader();

if (dr.Read())


Byte[] rtf = new Byte[Convert.ToInt32((dr.GetBytes(0, 0,

null, 0, Int32.MaxValue)))];

long bytesReceived = dr.GetBytes(0, 0, rtf, 0, rtf.Length);

ASCIIEncoding encoding = new ASCIIEncoding();

rtfContent.Rtf = encoding.GetString(rtf, 0, Convert.ToInt32(bytesReceived));