Skip to main content


Showing posts from October, 2012

ASP.Net: Unable to make session state request to the session state server

While working with web application, sometime you get the following error message: “Unable to make the session state request to the session state server. Please ensure that the ASP.NET State service is started and that the client and server ports are the same.”

To solve this problem follow the bellow steps: 1)  Open the Service window by either click on Start–> Control Panel -> Administrative Tools –> Services or open run and type “services.msc” and press enter.
2) Service window is opened now -> now select ASP.NET State service, you can check it is not started, right click on service and click on start.
Now just refresh the page again and you are done.  Note: If service is set to manual startup and you want to start it with system starts, simply right click on service and select “Properties” and set startup type as “Automatic”.

ASP.Net: Export from Gridview to Excel in C#

In another example I had written about how to export from list of records to excel file. But one of my friends asked me to write a sample to export from Gridview to excel file.
Here is that function which will export from Gridview to excel file: ///<summary> /// Export Gridview to excel. ///</summary> privatevoid ExportGridviewToExcel() {     Response.Clear();     Response.AddHeader("content-disposition", 
                        "attachment;filename= Test_Data.xls");     Response.Charset = "";     Response.ContentType = "application/vnd.xls";
var stringWriter = new System.IO.StringWriter(); var htmlWriter = newHtmlTextWriter(stringWriter);
// Added gridview to HtmlForm to handle the exception:     // Control 'TestGrid' of type 'GridView' must be placed     // inside a form tag with runat=server. var form = new System.Web.UI.HtmlControls.HtmlForm();     Controls.Add(form);     form.Controls.Add(TestGrid); // TestGrid i…

ASP.Net: Export to text/csv file and save with save file dialog in C#.

In my last example I had demonstrated the export to excel in C#, and keeping up my promise now I’ll show you how to export data to text or csv file. For this example I’ll use same “GetData” method which we had used in Export to Excel example.
///<summary> /// Export to text/csv ///</summary> privatevoid ExportTextFile() { var records = GetData(); var sb = newStringBuilder();     sb.AppendLine("First Name\tLast Name\tEmail Address\tCity"); foreach (var record in records)     {         sb.AppendFormat("{0}\t{1}\t{2}\t{3}"             , record.FirstName             , record.LastName             , record.Email             , record.City);         sb.AppendLine();     }
//Get current response var response = HttpContext.Current.Response;     response.BufferOutput = true;
//clear response     response.Clear();     response.ClearHeaders();     response.ContentEncoding = Encoding.Unicode;
//For csv export give file name as "Test_Data.csv"     response.AddHeader(&…

SQL Server: Insert specific value in identity column explicitly

SQL Server by default not allows inserting in column having Identity on, and if you try to insert it will throw error as:
Cannot insert explicit value foridentitycolumnintable'table'whenIDENTITY_INSERTissettoOFF. But sometime we need to enter a specific value in the column having identity on, for example if we delete specific row identity is not reset.
There is workaround to insert specific value in identity column. We can set IDENTITY_INSERT to ON and after value is inserted we can set this to OFF.
So here we go: First of all Create a table and insert some values in it as: CREATETABLE tb_TestIdentity (         Id intIDENTITYPRIMARYKEY,         Name Nvarchar(100) ) GO
-- Insert two names: INSERTINTO tb_TestIdentity(Name)VALUES ('Sandeep') INSERTINTO tb_TestIdentity(Name)VALUES ('Sachin') GO

Hosting application with Uhuru AppCloud

While hosting your application, you can found numerous hosting options, some provide great features while other provides flexibility in money and in feature you want to use.
I have gone through and found Uhuru AppCloud is a very nice option you can try for hosting your application and it provide flexibility to host application written on different platforms (i.e. .Net, Java, PHP, Ruby etc) . Here I am writing some steps for naive users to start with Uruhucloud.
Steps to use Uruhucloud:-
1.Create Account        a.Open the site  and click on “Sign Up” button (If you have promo code then enter, no issue if you have none).       b.Select any one OpenID Authentication ex. Google, Microsoft or Facebook.       c.Your account will be created and redirected to Dashboard. 2.Download and Install Uhuru Cloud Admin and Visual Studio Plugin from (link is given in the footer of your dashboard) 3.Manage (host, upload, download) your applic…

ASP.Net: Export to excel file and save with save file dialog in C#

While working in software industry almost every developer at some place must have worked with export application data to any document. In a series of export articles I’ll provide the example of exporting the data to excel, text HTML and pdf file. And in the end of all articles I’ll also provide the source code of exporting to all above formats.
In this article I’ll explain how you can export the data in excel sheet.
First of all I have created one proxy class, I’ll use this class to store the data and then export that data to excel file. (Note: I am using this class and method for sample only, if you have your own list or data table you can skip first two steps.) So first of all I have declared on proxy class as:  //Proxy class. publicsealedclassDataProxy { publicString FirstName { get; set; } publicString LastName { get; set; } publicString Email { get; set; } publicString City { get; set; } }
Now let’s create one method which will put some data in this class, later on we’ll export that d…

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

While using EF 4.1 code-first to insert data into a SQL Server database. If there is a validation error, EF throws aDbEntityValidationException whoseEntityValidationsErrorscontains the details of the issue.
For example you have set one field as required while creating model, but while saving data in that entity user have supplied Null value to that required field, EF throws aDbEntityValidationException. There can be many other validation errors as well, and to see what exactly error EF is throwing, you can write you SaveChanges method in try..catch block as:
try {     dbContext.SaveChanges(); } catch (DbEntityValidationException e) { foreach (var error in e.EntityValidationErrors)     { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",          error.Entry.Entity.GetType().Name, error.Entry.State); foreach (var ve in error.ValidationErrors)          { Console.WriteLine("-Property: \"{0}\", Error: \&qu…

C#: If Else Shortcut with Ternary Operator (? :)

We can simplify if..then..else statement(or can write shorthand expression) with the help of Ternary Operators. The ternary operator tests a condition. It compares two values. It produces a third value that depends on the result of the comparison. This can be accomplished with if-statements or other constructs. But the ternary operator provides an elegant and equivalent syntax form.

For example here is function which used to take one object as parameter and return object’s value as String if it’s not null, else it’ll return empty string. privateString GetValueFromObject(object value)         { if (value != null)             { return value.ToString();             } else             { returnString.Empty;             }         }
We can write whole if else condition in line as:
privateString GetValueFromObject(object value)         { return value != null ? value.ToString() : String.Empty;         }