A day with .Net

My day to day experince in .net

Archive for the ‘Asp.net’ Category

Decoding hex values using c#.net

Posted by vivekcek on August 24, 2009

The following method can be used for the above purpose.

private string Decode(string input)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        int len = input.Length;
        int i = 0;
        int sIx = 0;
        while (true)
        {
            if (input[i] == '%')
            {
                sb.Append(input.Substring(sIx, i - sIx));
                string hc = input.Substring(i + 1, 2);
                int hi = int.Parse(hc, System.Globalization.NumberStyles.HexNumber);
                char c = (char)hi;
                sb.Append(c);

                sIx = i + 3;
                i = i + 2;
            }
            i++;

            if (i >= len)
            {
                sb.Append(input.Substring(sIx));
                break;
            }
        }
Advertisements

Posted in Asp.net, c#.net | 1 Comment »

SSL in ASP.NET

Posted by vivekcek on July 23, 2009

SSL is the standard protocol to secure communications of web sites and applications. If you are developing your application using ASP.NET on a windows server, making the necessary configurations for SSL is not very difficult.

Unfortunately, while trying to accomplish this task at work, I discovered there isn’t one good source of information to get the whole job done.

In this series of (about) three posts I will try to get you up to speed on everything you need to do and how it’s done.

So, on to part one: “What is SSL and How Do We Create a Certificate?”. Let’s go.

A Short Intro on SSL

(Ugly oversimplification coming at you)

SSL is the standard protocol for (1)authenticating one or both parties and (2)encrypting communication between the parties.

Authentication is accomplished by a party presenting a valid certificate.

Encryption is accomplished in two steps:

Negotiating encryption key(s).
Encrypting communication using the negotiated key.

Setting up SSL for an ASP.NET App

The basic steps to do this are:

Obtaining a certificate for use by the server.
Configuring IIS.
(Optional) Enforcing the use of SSL by creating a redirection mechanism in IIS and ASP.NET.

Usually, it’s desired to create the setup at the development stage so you will be able to develop, debug and test your application in the same structure it will exist come production-time. So, in this post I will explain the whole setup for you developer station (referred to as localhost).

Obtaining a Server Certificate

What’s a certificate? A certificate is simply a character string that contains the public key of some entitiy (like your server) signed by a third party. Presenting a valid certificate guarantees to the person who wants to communicate with you that you are who you claim you are (think drivers license).

To have SSL working in the real world you need to buy a certificate from an Authorized Certification Authority (CA) like Verisign, for example. An authorized CA is an organization that is recognized (“trusted”) by client software (the web browser you’re using, for example). Continuing with the driver’s license metaphor, the CA in that case is the state government that issues the license.

A verified certificate costs money and is only valid for the specific machine it was issued to, so for development and testing purposes you can create your own “self-signed” certificate.

On a side note, the fellows over at Verisign are basically charging people 1,500 USD for a short string in a file. Talk about a sweet and sustainable business model – no advertising revenue required, thank you very much.

Introducing makecert.exe

Luckily, on a Windows mcahine you can use the makecert command-line utility to create a self-signed certificate.

It has a s**t-load of arguments, so here is the minimal command you need to run on the machine that hosts the application:

makecert -pe -n “CN=localhost” -ss my -sr localMachine -sky exchange

The interesting bits are:

-n “CN=localhost” : creates the certificate suitable for use by server “localhost”. Remember that every certificate is server-specific.
-ss my : places the certificate in the “personal” certificates folder.

Last argument deserves a word: to view all certificates installed on your machine – use the Certificates MMC snap-in. Choose “local computer” and you are presented with various “stores” which are basically folders of certificates. To consume a certificate in IIS you need it to reside in the “personal” store of local computer.

There are additional useful arguments to the makecert utility, but the basic ones I presented will get you up an running. If you can see a certificate named “localhost” in your personal certificates store you are doing fine so far.

Stay tuned for the next part, where I will cover configuring IIS for SSL support using the certifcate we created.

This is the second part in an article series about setting up SSL in an ASP.NET application.

You can read the first part here. Go ahead, read it now.

Okay.

Now, that we’ve created an SSL certificate for testing and development purposes, we are ready to make the required configuration in IIS.

Setting Up IIS to Work with SSL

First thing we have to do is configure the web site to use the certificate we created:

From the IIS MMC snap-in, select your web site, right-click “properties” and under “directory security” click “Server Certificate…”.
Click “Assign an existing certificate”. You should be able to see the self-signed certificate you created. Select it and finish the wizard.

At this state IIS is able to respond to SSL HTTP requests with this certificate.

To test that everything is okay, try to navigate to an existing URL in your application, with https in the beginning of the URL.

Forcing SSL for an application

If your application requires SSL encryption for all traffic you want to force the application to only handle SSL requests.

You can do this on the application level (so that other applications on the same web site in IIS will not require SSL) or on the web site level.

Here’s how:

In IIS MMC, right click the application virtual directory or the web site.
Select “Directory Security” tab and click “Edit…”.
Check “Require secure channel” and “Require 128-bit encryption”.

Now, any request to a URL that starts with http and not https – will receive a 403.4 error from the web server.

Supporting Debugging in Visual Studio

Now that you’ve setup the web server on your machine to require SSL traffic, you need to update the application URL in Visual Studio in order to be able to run the application from Visual Studio:

Right click the project in Solution Explorer and select “Properties”.
Under the “Web” tab change the value of “Project Url” to start with https.

Auto-Redirecting non-SSL Traffic

Perhaps some of your users will try to navigate to your application via a non SSL URL (most users assume a web page URL starts with http).

You can silently redirect your users to the correct SSL address using the following technique:

Users trying to reach a non-SSL URL will be automatically redirected by IIS to the standard 403.4 error page. First step is to change that page to your own page:

In your project, create a new web form called “NonSslRedirect.aspx”.
In IIS MMC, right click your application virtual directory, click the “Custom Errors” tab and select the 403;4 error.
Click “Edit Properties…”, select “URL” in “Message Type” and type the address of the page you added in step 1 (for example: /MyApp/NonSslRedirect.aspx).

Try again to navigate to a URL starting with http. You should be redirected by IIS to NonSslRedirect.aspx.

Now, in the code-behind file of NonSslRedirect.aspx, add code similar to the following to automatically redirect the users to the matching SSL URL:

protected void Page_Load(object sender, EventArgs e)

{

string originalUrl = Request.Url.ToString().Split(new char[1] { ';' })[1];

string urlWithHttps = "https" + originalUrl.Substring(4);

Response.Redirect(urlWithHttps);

}

This code will replace the http prefix in the requested URL with an https prefix and redirect the user to new URL.

Posted in Asp.net | 1 Comment »

Opening a page in a pop up’s parent window or in it’s grand parent window

Posted by vivekcek on July 22, 2009

Today i faced a problem,The problem was that open a link in a pop up windows parent window
this can be done the following javascript functions

In parent


window.opener.parent.location ='../../folder/folder/somepage.aspx?tId='+TrId;

In grand parent

window.opener.opener.parent.location ='../../folder/folder/somepage.aspx?tId='+TrId;

Posted in Asp.net | Leave a Comment »

Binding formated data to gridview by Bind()

Posted by vivekcek on July 22, 2009

<asp:GridView ID="ccGvAdv" runat="server" AutoGenerateColumns="False" CellPadding="4"
                            CssClass="grid" DataKeyNames="ccr_CurrencyExchangeRateID" GridLines="None" Width="100%"
                            AllowPaging="True" OnPageIndexChanging="ccGvAdv_PageIndexChanging" OnRowDataBound="ccGvAdv_RowDataBound">
                            <PagerSettings NextPageText="NextPage" PreviousPageText="PreviousPage" />
                            <Columns>
                                <asp:BoundField DataField="cur_Name" HeaderText="Currency" />
                                <asp:TemplateField HeaderText="Updated Date&amp;Time">
                                    <ItemTemplate>
                                        <asp:Label ID="Label2" runat="server" Text='<%# Bind("ccr_DateTime","{0:dd MMM-yyy HH:mm:ss}") %>'></asp:Label>
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="Original Rate">
                                    <ItemTemplate>
                                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("ccr_OriginalRate","{0:#.##}")  %>'></asp:Label>
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="ISV Charges">
                                    <ItemTemplate>
                                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("InterserveCharge")  %>'></asp:Label>
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="Summed Rate">
                                    <ItemTemplate>
                                        <asp:Label ID="Label2" runat="server" Text='<%# Bind("ccr_Rate","{0:#.##}")  %>'></asp:Label>
                                    </ItemTemplate>
                                </asp:TemplateField>
                            </Columns>
                            <AlternatingRowStyle CssClass="grid_row_alternate" />
                            <HeaderStyle CssClass="grid_row_header" />
                            <FooterStyle CssClass="grid_row_footer" />
                            <RowStyle CssClass="grid_row_normal" />
                            <PagerStyle CssClass="grid_row_pager" />
                        </asp:GridView>

Posted in Asp.net | Leave a Comment »

Using skin in asp.net

Posted by vivekcek on July 22, 2009

A skin is a definition of styles applied to the server controls in your ASP.NET page.
Skins can work in conjunction with CSS files or images.
The skin file can have any name, but it must have a .skin file extension.
The Summer.skin file.

<asp:Label Runat="server" 
           ForeColor="#004000" 
           Font-Names="Verdana"
           Font-Size="X-Small" />

<asp:Textbox Runat="server" 
             ForeColor="#004000" 
             Font-Names="Verdana"
             Font-Size="X-Small" 
             BorderStyle="Solid" 
             BorderWidth="1px"
             BorderColor="#004000" 
             Font-Bold="True" />

<asp:Button Runat="server" 
            ForeColor="#004000" 
            Font-Names="Verdana"
            Font-Size="X-Small" 
            BorderStyle="Solid" 
            BorderWidth="1px"
            BorderColor="#004000" 
            Font-Bold="True" 
            BackColor="#FFE0C0" />

Control definitions must contain the Runat=”server” attribute.
No ID attribute is specified in the skinned version of the control.
Using the Summer theme in an ASP.NET page.

skin

Posted in Asp.net | Leave a Comment »

How to use the find method associated with the datatable

Posted by vivekcek on July 21, 2009

Find method in datatable is used to find a particaular row in datatable.For that we have to

set one coulmn of the datatable as promary key.The below code do this things

adt.Fill(dt_Supplier);
DataColumn[] dlc = new DataColumn[1];
dlc[0] = dt_Supplier.Columns[0];
dt_Supplier.PrimaryKey = dlc;

In the above datatable if we supply the 0th coulmns value in find() method we can identyfy a

unique row

For deleting a particular row we can use the following method in the case of above table

 public void DeleteItem(string Sup_Code)
        {

            DataRow DelRow = dt_Supplier.Rows.Find(Sup_Code);
            DelRow.Delete();
            adt.Update(dt_Supplier);

        }

Posted in Asp.net | Leave a Comment »

To make the pop up window in the centre of the screen

Posted by vivekcek on July 21, 2009

The script for the same


window.history.forward(1);
function OpenTransaction()
{
    var LeftPosition=(screen.width)?(screen.width-820)/2:100;
	var TopPosition=(screen.height)?(screen.height-550)/2:100;
    var formProperties = 'width=820,height=550,toolbar=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no,top='+TopPosition+',left='+LeftPosition;
    window.open('../BBRetrieveTransaction.aspx?v=0','RetrTrans',formProperties);
}

Posted in Asp.net | Leave a Comment »

Pop up window in asp.net

Posted by vivekcek on July 21, 2009

To open a page as pop up we can use the following code

string url = Program.GetAppUrlBase(Request) + "/folder/folder1/mypage.aspx?tid=" + e.CommandArgument.ToString();
            string script = "window.open('" + url + 

"','Trans','toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');";
            ClientScript.RegisterClientScriptBlock(this.GetType(), "Transaction", script, true);

where GetAppUrlBase(Request) is a function written on Program.cs file in App_Code folder to get the base Url of application

public static string GetAppUrlBase(HttpRequest request)
    {
        string nUrl = request.ApplicationPath;

        if (nUrl == null || nUrl.Trim('/') == string.Empty)
            nUrl = request.Url.GetLeftPart(UriPartial.Authority).TrimEnd('/');
        else
            nUrl = request.Url.GetLeftPart(UriPartial.Authority).TrimEnd('/') + "/" + nUrl.Trim('/');

        return nUrl;
    }

Posted in Asp.net | Leave a Comment »

javascript code to check only one radio button and highlighting its table row

Posted by vivekcek on July 21, 2009

Another day i was stucked with a problem in this case my web page contains 10 radio buttons,in which only one should be

checked at a time also when a radio button is checked the table row in which it reside should by highlighted this process

also should done using client side javascript,To make the problem worse my tester told for enabling the auto post back of the

radio buttons for some input clearing purposes,if we set nything in client side by javascipt that will be losted after a

server post back but i solved this problem by some script and small CSS

For that add small style tag under title tag in HTML section as

.highlight { background-color: yellow; }

Below it add two javascript functions


function rowHighlight(obj) {
			if (obj.checked) {
				obj.parentNode.parentNode.className = 'highlight';
				
				
			}
			else {
				obj.parentNode.parentNode.className = '';
			}
			
			for(i = 0; i &lt; document.forms[0].elements.length; i++)
                {
                    elm = document.forms[0].elements[i]
                        if (elm.type == &#39;radio&#39;)
                            {
                            if(!elm.checked)
                            {
                            elm.parentNode.parentNode.className = &#39;&#39;;
                            }
                              
                            }
                }
		}
		


function show()
		{
		    var obj=document.getElementById(&#39;RdbFirst&#39;);
		    if(obj!=null)
		    {
		        if(obj.checked)
		        {
		         rowHighlight(obj);
		        }
		    }	
		    obj=document.getElementById(&#39;RdbSecond&#39;);
		    if(obj!=null)
		    {
		        if(obj.checked)
		        {
		         rowHighlight(obj);
		        }
		    }
		    
		    obj=document.getElementById(&#39;RdbThird&#39;);
		    if(obj!=null)
		    {
		        if(obj.checked)
		        {
		         rowHighlight(obj);
		        }
		    }

the function rowHighlight(obj) is called when we check a radio button for taht we have to add the following code in Page load

event


protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
RdbFirst.Attributes.Add(“onclick”, “rowHighlight(this);”);
RdbSecond.Attributes.Add(“onclick”, “rowHighlight(this);”);
RdbThird.Attributes.Add(“onclick”, “rowHighlight(this);”);
}
}

rowHighlight(obj) function check one radio button and highlight is residing row and then it unselect all other radio buttons

and remove the highlight of unselcted radio buttons parent row

The function show() is used to maintain the state at client side after post back

this function is called by

adding an on load event in body tag

one button

Posted in Asp.net | Leave a Comment »

Call XML webservice through c#.net

Posted by vivekcek on July 21, 2009

I am working in a project for online reesrvation of airlines,Hotels etc in asp.net.Online reservation is by XML webservices

beacause XML is the language independent information exchange language.So i developed a common application to send XML

request to webservice and getting response from them and populte the result in a grid view.
The application includes two text boxes one for inputing XML one to show out put XML from webservice.
The UI and code for the same is given below
XML tester

In the coding section first line shows the declration of web service URL as

static Uri Url = new Uri(“https://example.com/exampleapi/RequestListenerServlet&#8221;);

In the submit button click event

we format the xml string entered in the input test box and convert it int an XML document


XmlElement _xmlResponse =ResponseListElement(doc);

In the above code we call the function for sending our formated xml document to webservice and return an xml result

ResponseListElement()

Then we load the result XML into a dataset and shows in gridview

using GTAApp;
using System.IO;
using System.Net;
//using System.Web.Services.Protocols;
using System.Diagnostics;
using System.IO.Compression;

using System.Data.SqlClient;
using System.Xml;

namespace MyApp
{
    public partial class XMLtesterGta : Form
    {
        static Uri Url = new Uri("https://example.com/exampleapi/RequestListenerServlet");
        
        public XMLtesterGta()
        {
            InitializeComponent();
        }
        
        DataSet ds;
        private void ccBtnSubmit_Click(object sender, EventArgs e)
        {
            string unformattedXml = ccTxtInput.Text;
            string formattedXML = IndentXMLString(unformattedXml);
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(formattedXML);
            
            XmlElement _xmlResponse =ResponseListElement(doc);
            if (_xmlResponse != null)
            {
                string formattedXML1 = IndentXMLString(_xmlResponse.OuterXml);
                ccTxtOutput.Text = formattedXML1;
                ds = new DataSet();

                byte[] reqData = Encoding.ASCII.GetBytes(_xmlResponse.OuterXml);
                System.IO.MemoryStream m = new System.IO.MemoryStream(reqData);
                ds.ReadXml(m);
                foreach (DataTable dt in ds.Tables)
                {
                    ccDdlTables.Items.Add(dt.TableName.ToString());

                }
            }

        }
        private static string IndentXMLString(string xml)
      {
         string outXml = string.Empty;
         MemoryStream ms = new MemoryStream();
         // Create a XMLTextWriter that will send its output to a memory stream (file)
         XmlTextWriter xtw = new XmlTextWriter(ms, Encoding.Unicode);
         XmlDocument doc = new XmlDocument();

         try
         {
            // Load the unformatted XML text string into an instance 
            // of the XML Document Object Model (DOM)
            doc.LoadXml(xml);

            // Set the formatting property of the XML Text Writer to indented
            // the text writer is where the indenting will be performed
            xtw.Formatting = Formatting.Indented;

            // write dom xml to the xmltextwriter
            doc.WriteContentTo(xtw);
            // Flush the contents of the text writer
            // to the memory stream, which is simply a memory file
            xtw.Flush();

            // set to start of the memory stream (file)
            ms.Seek(0, SeekOrigin.Begin);
            // create a reader to read the contents of 
            // the memory stream (file)
            StreamReader sr = new StreamReader(ms);
            // return the formatted string to caller
            return sr.ReadToEnd();
         }
         catch (Exception ex)
         {
            MessageBox.Show(ex.ToString());
            return string.Empty;
         }
      }

        private void ccDdlTables_SelectedIndexChanged(object sender, EventArgs e)
        {
            ccGdTables.DataSource=ds.Tables[ccDdlTables.SelectedItem.ToString()];
        }
        public XmlElement ResponseListElement(XmlDocument xDocs)
        {
            try
            {
                byte[] reqData = Encoding.ASCII.GetBytes(xDocs.OuterXml);
                System.IO.Stream st = null;

                // Send Request
                HttpWebRequest httpWR = (HttpWebRequest)HttpWebRequest.Create(Url);
                //httpWR.Timeout = 6000;
                //httpWR.ReadWriteTimeout = 8000;
                httpWR.Method = "POST";
                httpWR.ContentType = "text/xml";
                httpWR.ContentLength = reqData.Length;
                httpWR.GetRequestStream().Write(reqData, 0, reqData.Length);

                //Receive Response
                st = httpWR.GetResponse().GetResponseStream();

                StringBuilder sbResponse = new StringBuilder();
                int numBytesToRead = 1024;
                byte[] resData = new byte[numBytesToRead];

                while (true)
                {
                    int n = st.Read(resData, 0, numBytesToRead);
                    if (n == 0) break;

                    sbResponse.Append(Encoding.ASCII.GetString(resData, 0, n));
                }

                XmlDocument ret = new XmlDocument();
                ret.LoadXml(sbResponse.ToString());
                return ret.DocumentElement;
            }
            catch (WebException wEx)
            {
                MessageBox.Show(wEx.Message.ToString());
                //long len = wEx.Response.GetResponseStream().Length;
                //byte[] exMsg = new byte[len];
                //wEx.Response.GetResponseStream().Read(exMsg, 0, (int)len);

                //Debug.Assert(false, Encoding.ASCII.GetString(exMsg));
            }
            return null;
        }

        private void ccBtnClear_Click(object sender, EventArgs e)
        {
            ccTxtInput.Clear();
            ccTxtOutput.Clear();
            ccDdlTables.Items.Clear();
            ds.Clear();
            ccDdlTables.SelectedText = "";
        }
   }
}

Posted in Asp.net | Leave a Comment »