Tuesday, May 29, 2012

Dispalying maintanence or construction page to the user when the application is upgrading.

To show a maintanence page to the request just you need to create a html page with your desired description and name that file as "app_offline.htm". Once you pace this file in your virtual directory the IIS serves App_Offline.htm page for all requests.



Basically, if you place a file with this name in the root of a web application directory, ASP.NET 2.0 will shut-down the application, unload the application domain from the server, and stop processing any new incoming requests for that application.  ASP.NET will also then respond to all requests for dynamic pages in the application by sending back the content of the app_offline.htm file (for example: you might want to have a “site under construction” or “down for maintenance” message).

This provides a convenient way to take down your application while you are making big changes or copying in lots of new page functionality (and you want to avoid the annoying problem of people hitting and activating your site in the middle of a content update).  It can also be a useful way to immediately unlock and unload a SQL Express or Access database whose .mdf or .mdb data files are residing in the /app_data directory.

Once you remove the app_offline.htm file, the next request into the application will cause ASP.NET to load the application and app-domain again, and life will continue along as normal.
 

Friday, May 25, 2012

Configuring a client to request wcf service using Http and https protocols.

At a time we can request one WCF service using one protocol only. If you want to use both the protocols at a time there should be a difference in your service address. Below code I commented the HTTPS protocol accessing. Once you comment the http and uncomment the https it will start using https protocol for your requests.


<system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <!-- Https(SSL) Binding -->
        <!--<binding name="BasicHttpBinding_Service"
          messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true">         
          <security mode="Transport">
            <transport clientCredentialType="None"/>          
          </security>
        </binding>-->
        <!-- Http binding-->
        <!-- please comment below lines if client want to use HTTPS protocol-->
        <binding name="BasicHttpBinding_Service"
          messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true">         
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <!-- Https(SSL) End point-->
      <!--<endpoint address="your service url"
       binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_Service"
       contract="ServiceReference.IService" name="BasicHttpBinding_Service" />-->

      <!--Http end point-->
      <!-- please comment below lines if user want to use Https as communication protocol-->
      <endpoint address="your service url"
      binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_Service"
      contract="ServiceReference.IService" name="BasicHttpBinding_Service" />
    </client>
  </system.serviceModel>

Thursday, May 24, 2012

Configure a WCF service for https and http protocols

Configuring a service to serve http and https is become a common requirement for all  the services. I have spent googling on this. After spending about 6 hours I fincdout below one would configure your service for both http and https.


<system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="httpsConfiguration" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">         
          <security mode="Transport">
            <transport clientCredentialType ="None"/>
          </security>
        </binding>
        <binding name="httpConfiguration" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">         
        </binding>
      </basicHttpBinding>

    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpsGetEnabled="true" httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service behaviorConfiguration="ServiceBehavior" name="YourServiceName">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="httpsConfiguration" contract="YourServiceContract">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="httpConfiguration" contract="YourServiceContract">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
  </system.serviceModel>

Tuesday, May 15, 2012

Get the Querystring variables using javascript


This JS block helps you to get the query string values of a url at the client side.


function getUrlVars() {
            var vars = [], hash;
            var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
            for (var i = 0; i < hashes.length; i++) {
                hash = hashes[i].split('=');
                vars.push(hash[0]);
                vars[hash[0]] = hash[1];
            }
            return vars;
        }

If you want to get the query string value of “RecordId” simply you can say
var recordIdValue = getUrlVars()["RecordId"];

The record id will contain the RecordId value

Creating and reading MultiValued cookie in .net using C#


Creating a multi valued cookie using c#.
The below code will create a multi valued cookie for you.

Int cookieTimeLimit = 20;
HttpCookie userCookie = new HttpCookie(“MultiValuedCookie”);
                    userCookie.Values["userId"] = “userId”;
                    userCookie.Values["FirstName"] = “Anji”;
                    userCookie.Values["TimeStamp"] = DateTime.Now.ToString();
                    userCookie.Expires = DateTime.Now.AddMinutes(cookieTimeLimit);
                    Response.Cookies.Add(userCookie);

Reading the Values from the Multi Valued cookie.
if (Request.Cookies[“MultiValuedCookie”] != null)
{
string userId = Request.Cookies[cookieName]["userId"].ToString();
string firstName = Request.Cookies[cookieName]["FirstName"].ToString();
string lastAccessedTime = Request.Cookies[cookieName]["TimeStamp"].ToString();
}
 

XML serialization and deserialization in C#.net



Here my idea to avoid the serialization for the basic types. So the  demo purpose I am skipping serialization for the strings.

private string SerializeAnObject(object obj)
        {
            if (obj.GetType() == string.Empty.GetType())
            {
                return (string)obj;
            }
            System.Xml.XmlDocument doc = new XmlDocument();
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            try
            {
                serializer.Serialize(stream, obj);
                stream.Position = 0;
                doc.Load(stream);
                return doc.InnerXml;
            }
            catch
            {
                throw;
            }
            finally
            {
                stream.Close();
                stream.Dispose();
            }

        }

In the below code I am explicitly passing the xRoot object i.e. root object of your xml data which is serialized previously. Here xRoot is mandatory otherwise the decryption is not possible.

This method Internally calls deserialize method to deserilaize the data

public UsersInfo FillProdcutsOrderSessionData(string xmlData)
        {
            ProductOrderModel productsOrderModel = new ProductOrderModel();
            XmlRootAttribute xRoot = new XmlRootAttribute();
            xRoot.ElementName = "UserInforModel";
            xRoot.IsNullable = true;
            object deserializedData = DeSerializeAnObject(xmlData, xRoot, productsOrderModel.GetType());
            UsersInfo usersInfo = (UsersInfo)deserializedData;
return usersInfo;

        }




/// <summary>
        /// Deserialze the data
        /// </summary>
        /// <param name="xmlOfAnObject">Xml data which is got stored when serialization happens</param>
        /// <param name="xRoot">xRppt Object</param>
        /// <returns></returns>
        private object DeSerializeAnObject(string xmlOfAnObject, XmlRootAttribute xRoot)
        {

            UsersInfo myObject = new UsersInfo ();
            System.IO.StringReader read = new StringReader(xmlOfAnObject);
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(myObject.GetType(), xRoot);
            System.Xml.XmlReader reader = new XmlTextReader(read);
            try
            {
                myObject = (UsersInfo)serializer.Deserialize(reader);
                return myObject;
            }
            catch (Exception ex)
            {
                throw;
            }

            finally
            {
                reader.Close();
                read.Close();
                read.Dispose();
            }

        }