Saturday, December 31, 2011

Happy New Year

Tuesday, December 6, 2011

How to click a button from javascrip in C#?

 Some times the __doPostBack event not working in javascript  but we need to fire an event from javascript. We all knows that its not possible to call server site event easily from javascrit so i decided to  click a button with the help of javascript function so can the related server side event will fire automatically, so we can say that from javascript we can able to call a server site event :) 

 <script type="text/javascript" language="javascript">
function ClickTheButton()
 var a = document.getElementById("hdIp");
            a.value ="Bishnu Tewary";



  <asp:HiddenField ID="hdIp" runat="server"  Value="0" />
        <asp:Button ID="myImageButton" runat="server" OnClick="myImageButton_Click" Text="Click Me"/> 

// C# Code
 protected void myImageButton_Click(object sender, EventArgs e)
            string IpAddress = Convert.ToString(hdIp.Value);

                HttpCookie ck = Request.Cookies["clientIPAdd"];
                if (ck.Value == "undefined" || string.IsNullOrEmpty(ck.Value))
                    ck.Value = IpAddress;
            catch (Exception ex) { }
            Session["IPAddress"] = IpAddress;

How to update a cookie in C#?

In my previous post we learn how to retrieve cookie in silverlight, now i am showing how to update cookies value in C# :) why C# ? hahaha because i love this :)

Here is the code for update cookie
string IpAddress="";
 HttpCookie ck = Request.Cookies["clientIPAdd"];
                if (ck.Value == "undefined" || string.IsNullOrEmpty(ck.Value))
                    ck.Value = IpAddress;

I think you remember about my post Cookie , in this post the cookie created by javascript so may be sometims its returns undefined. So when ever it returns undefined or empty value the above code will update the related (clientIPAdd) cookie value to ""

Cheers :)

How to retrieve value from a cookie in silverlight?

In my previous post I shows how to create cookie in javascript, now i am going to tell you how to retrieve value from a cookie in Silverlight. The code i'm using here is C# because i love this :)

I create a methode which returns the value from a cookie
string IPAddress = GetCookieValueByKey("clientIPAdd");
 This is the methode
 private string GetCookieValueByKey(string keyName)
            string[] cookies = HtmlPage.Document.Cookies.Split(';');
            foreach (string cookie in cookies)
                string[] keyValue = cookie.Split('=');
                if (keyValue.Length == 2)
                    if (keyValue[0].ToString() == key)
                        return keyValue[1];
            return string.empty;

Hope this helps :)

Monday, December 5, 2011

How to create cookie in javascript?

Today I am showing how to create cookie in java script. Here i am giving you an example for how to get the client IP address and save that into the cookie.

Here's the script for this
Put this script within the head tag
 <script type="text/javascript">
        var ipadd;
        function getip(data) {
            ipadd = data.ip;

//This function helping us to create the cookie
 function setvisibility() {
            var a = document.getElementById("hdIp");
            a.value = ipadd;
            var c_name = "clientIPAdd";
            var exdays = 1;
            var exdate = new Date();
            exdate.setDate(exdate.getDate() + exdays);
            var c_value = escape(ipadd) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
            document.cookie = c_name + "=" + c_value;
          //Where c_name(clientIPAdd) is the  name of the and   //c_value is its value and the cookie will expire next day of creation

    <script type="text/javascript" src="">

Here is the page 

<body onload="setvisibility();">
    <form id="form1" runat="server">

        <asp:HiddenField ID="hdIp" runat="server" OnValueChanged="hdIp_ValueChanged" Value="0" />
        <asp:Button ID="myImageButton" runat="server" OnClick="myImageButton_Click" Height="1"
            Width="1" />


Friday, November 25, 2011

How to solve Siverlight application's attempting to access a service in a cross-domain way without a proper cross-domain policy in place, or a policy that is unsuitable for SOAP services. You may need to contact the owner of the service to publish a cross-domain policy file and to ensure it allows SOAP-related HTTP headers to be sent?

An error occurred while trying to make a request to URI ‘http://localhost:<portnumber>/<ServiceAppName>/<serviceclassname>’. This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place, or a policy that is unsuitable for SOAP services. You may need to contact the owner of the service to publish a cross-domain policy file and to ensure it allows SOAP-related HTTP headers to be sent.

 When you call WCF Service using Silverlight you might receive the above error message.

 Here i am showing you how to solve this problem , which i have got so many times thanks to Chanmingman's blog from where i able to solve this.

The Steps to follow

1. Create an xml file using notepad and save as clientaccesspolicy.xml with the following content.

<?xml version="1.0" encoding="utf-8"?>
      <allow-from http-request-headers="SOAPAction">
        <domain uri="*"/>
        <resource path="/" include-subpaths="true"/>

2. Create an xml file using notepad and save as crossdomain.xml with the following content.

<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "">
  <allow-http-request-headers-from domain="*" headers="SOAPAction,Content-Type"/>

3. Copy these 2 files into web site root folder for example, c:\inetpub\wwwroot. for your IIS 

Cheers :)


Sunday, November 20, 2011

Why we use web.config transformation?

As I promised on my last post that i will describe what is web.config transformation is, but i did not get any reply for that. So this time I will describe why we use this we.config transformation.
As we  know in Microsoft Visual Studio we have two default Solution Configurations (Debug and Release) but do you realize we  have two different configuration for these two Solution Configurations, if you keep look on the web.config file you can see there are two config files for Debug and Release each
as Web.Debug.config and Web.Release.config.
Some times we add many connectionstring key  for different purpose i.e one for development purpose one for test one for live etc . But we are not using these two configuration files , why these are created? what the meaning of these?

Ok keep eye on my blog I will describe this on next week

Good Luck

Saturday, November 12, 2011

Do you know what is web.config transformation?

Do you know what is web.config transformation?
OK , let see how many answers i got. I will describe this next week ....:)

Tuesday, October 18, 2011

How to pass " within a string variable in C#?

 Some times we need to assign string like "<table id="tableStudent"> " or "Hello "Bishnu!" but we know that we cannot set " within a string because string are know as within a " (quotation)  mark. so for assign string like above we have to these to literals
1. Regular string literals
2. Verbatim string literals
 Here I describe both with example
Regular String Literals:
For this we must embed escape characters provided by C#

string strStringToFind = "<table id=\"tableStudent\"";
Output: <table id="tableStudent";

Verbatim String Literals:


string strString= @"Hello ""Bishnu!""";

Output: Hello "Bishnu!"
Hope this help you..

Thursday, September 22, 2011

How to get all stored procedures in database ?

 some times we need to know which stored procedure we are using for a single database and for that we need to note down all stored procedure name. Its takes lot of time and passions i am also faced this time of problem so many times . So i decided to looking for a better option so can we get the stored procedures name very easily
 And finally i found this query which returns stored procedure  name from the database.

 Here is the query to get all stored procedures in the database

Select As ProcedureName
   sys.procedures Pro
Inner Join
   sys.schemas Shma
   Pro.schema_id = Shma.schema_id

Friday, September 9, 2011

How to redirect to the login page automatically when session timeout in C#

 On my last project my client ask me to do some thing so can after certain of time if the website page is in idle mode for a specified time(session timeout) then the current user should automatically redirect to the login page! very interesting. i took this a a challenge and thanks god i able to do this.

Here i am showing  how to redirect to the login page automatically when session timeout in C#

Write this code in to the masterpage's cs file

 protected override void OnPreRender(EventArgs e)
            this.HeadContent.Controls.Add(new LiteralControl(
                String.Format("<meta http-equiv='refresh' content='{0};url={1}'>",
                SessionTimeOutWithin * 60, PageToSentAfterSessionTimeOut)));
This will add a metatag into the page header which will refresh the CheckSessionTimeOut.aspx page after SessionTimeOutWithin* 60 seconds when the session timeout occurs.

//This the page to be refresh after sessioin timeout
public string PageToSentAfterSessionTimeOut
            get { return "CheckSessionTimeOut.aspx"; }

//This takes the Session.Timeout from the webconfig or from where the Session.Timeout is being set
 public int SessionTimeOutWithin
            get { return Session.Timeout; }

// Add this within the <system.web> tag in web.config file . Here i am set 1 min as Session timeout

    <sessionState mode="InProc" cookieless="true" timeout="1"></sessionState>

 This will set the session timeout as 1 minute

Mode: means what happens if page is in active mode , InProc means session timeout will increase 1 minute more after the page activity time but if the page is in idle for 1 minute then session timeout will occurs.

How to split values in sql server?

 Here i am showing how to split values in Sql server as Split function did  in c#

Why should we take some string value from a table and split that on our C# programming why not in the SQL programming? so many times we prefer to save a One to Many relation type with a single field in a SQL db table by concatenating the selected item with a separator like"1,4,8,7". But as we know SQL don't have a function like C# has Split(). So many programmer takes that value from db and split it in the C# code. But i am not happy with that as always going for better option and i implement this Function for that and thanks god its works..

Create function [dbo].[fnSplit](
    @sInputList VARCHAR(8000) -- List of delimited items
  , @sDelimiter VARCHAR(8000) = ',' -- delimiter that separates items
) RETURNS @List TABLE (item VARCHAR(8000))

WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0

 IF LEN(@sItem) > 0

IF LEN(@sInputList) > 0
 INSERT INTO @List SELECT @sInputList -- Put the last item in
--select * from dbo.fnSplit('1,2,34,5', ',') where item=34
--select * from dbo.fnSplit('1,2,34,5', ',')

Hope this will helps you tooooo :)

Monday, August 29, 2011

How to Reseed Indentyty In SQL Server 2008

When we delete a table in sql server db all values are deleted but the Seed set to the last identity.Means if there was 50 fields in that table and and the last identity was 50 with identity increment with 1 and here we delete the table but if we insert again in this table the identity will be 51 instead on 1. If you wants the identity to be one then you need to reseed the identity to 0 so the next identity will be 1.
 Note : This is the main difference between the TRUNCATE table and DELETE table. TRUNCATE reset the table definition after deleting all fields where DELETE only remove table values

Here is the example to reseed the tbl_SubModel seed to 0

DBCC CHECKIDENT ("dbo.tbl_SubModel", RESEED, 0);

Saturday, March 26, 2011

How to Load CSV file to datatable and insert into the database in C#?

Here I'm showing how to load CSV file to DataTable and insert into the databse in C#.
For this you have to choose the csv file formate same as your sql db Destination Table
with the header name and header name aslo need to match with the sql table too. One thing
if you have bit coulmn in sql db table then chnage that data as 0 or 1 in the source csv file

Here GetDataTableFromCSV function convert the CSV file to a datatable and WriteDataTableToTheDatabase
function is for saving the datatable to the server as it's name suggest :)

How to call?
string strNewFilename = Server.MapPath("~/Temp/") + file.FileName;
DataTable dtReaderDescription = GetDataTableFromCSV(strNewFilename);
WriteDataTableToTheDatabase(dtReaderDescription, strNewFilename);

public DataTable GetDataTableFromCSV(string strFileName)
                System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"");
                string strQuery = "Select * from [" + System.IO.Path.GetFileName(strFileName) + "]";
                System.Data.OleDb.OleDbDataAdapter da = new System.Data.OleDb.OleDbDataAdapter(strQuery, conn);
                System.Data.DataSet ds = new System.Data.DataSet();
                return ds.Tables[0];
            catch (Exception ex) { }
            return new DataTable();

private void WriteDataTableToTheDatabase(DataTable dtTosave,string fileToDelete)
                string strConn = ConfigurationManager.ConnectionStrings["dbBulkCopy"].ConnectionString;
                using (SqlConnection sqlConnection =
                        new SqlConnection(strConn ))
                       SqlBulkCopy bulkCopy =
                        new SqlBulkCopy
                        sqlConnection ,
                        SqlBulkCopyOptions.TableLock |
                        SqlBulkCopyOptions.FireTriggers |
                    bulkCopy.DestinationTableName = "ReaderDescription";

                        FileSystemProxy FileSystem = new Microsoft.VisualBasic.Devices.Computer().FileSystem;
                        FileSystem = null;
                    catch (Exception ex) { }
            catch (Exception ex) { }


Thursday, March 3, 2011

How to export gridview content to csv in C#?

Here I'm showing you how to export a GridView content to csv (Comma separated values) in using C#.

So here I have a GridView gvResult and a button btnExportToCsv . On btnExportToCsv click we want to export gvResults data to export in csv file. So here is the code bellow hope this helps you.

protected void btnExportToCsv_Click(object sender, EventArgs e)
Response.Buffer = true;
Response.Charset = string.Empty;
Response.ContentType = "application/text";
gvResult.AllowPaging = false;
StringBuilder sb = new StringBuilder();
string coloumns = string.Empty;
for (int k = 1; k < gvResult.Columns.Count - 1; k++)
//add ',' separator

coloumns += gvResult.Columns[k].HeaderText + ',';
sb.Append(gvResult.Columns[k].HeaderText + ',');


//This portion is to replace the header text of the gvResult to the binding data source data table's columns //name so can we get the correct data from the datasource ,because we formated the gvResult header as per //our reqirement and the header text doesn't match with the datasource table
coloumns = coloumns.Replace("Coupon ID", "ID_Coupon");
coloumns = coloumns.Replace("Employee ID", "Customer_ID");
coloumns = coloumns.Replace("Created On", "CreatedDate");
coloumns = coloumns.Replace("Valid Until", "ValidUntil");
coloumns = coloumns.Replace("Activated", "ActivatedDate");
coloumns = coloumns.Replace("Cashed", "CashedDate");
coloumns = coloumns.Replace("Euro", "EuroValue");
//here we remove the last ',' from the string 'coloumns'

coloumns = string.IsNullOrEmpty(coloumns) ? string.Empty : coloumns.Substring(0, coloumns.LastIndexOf(","));
string[] clmnList = coloumns.Split(',');
DataTable dt = new DataTable();

//Here takes the required fields from the gridview(gvResult's datasource)
dt = gvResult.DefaultView.ToTable(false, clmnList.ToArray());
//append new line

//Here put the data to the particular column
for (int i = 0; i < dt.Rows.Count; i++)
for (int k = 0; k < dt.Columns.Count; k++)
//add separator
sb.Append(Convert.ToString(dt.Rows[i][k]) + ',');
//append new line
catch (Exception ex) { }

Hope this will help!

Wednesday, February 16, 2011

How to select multiple value of a checkboxlist in C#?

Here I am showing how to select multiple value of a checkboxlist.
The SetValueCheckBoxList methode doing this where the StringToArrayList methode return the arrylist for the sValues parameter of SetValueCheckBoxList
    public void SetValueCheckBoxList(CheckBoxList cbl, string sValues)
        if (!string.IsNullOrEmpty(sValues))
            ArrayList values = StringToArrayList(sValues);
            foreach (ListItem li in cbl.Items)
                if (values.Contains(li.Value))
                    li.Selected = true;
                    li.Selected = false;

    private ArrayList StringToArrayList(string value)
        ArrayList _al = new ArrayList();
        string[] _s = value.Split(new char[] { ',' });
        foreach (string item in _s)
        return _al;
Call like this bellow
SetValueCheckBoxList(chkTypeHome, Convert.ToString(dtProperty.Rows[0]["TypeOfhome"]));
here chkTypeHome= checkboxlist
and Convert.ToString(dtProperty.Rows[0]["TypeOfhome"]) has data with comma separated sting like "1,2,4,5"