Monday, 10 December 2012

IIS 7.5 error: Handler “PageHandlerFactory-Integrated” has a bad module “ManagedPipelineHandler” in its module list


IIS 7.5 error: Handler “PageHandlerFactory-Integrated” has a bad module “ManagedPipelineHandler” in its module list
Posted on August 12, 2010 by Maris
Today I installed Clean Windows Web Server 2008 R2 64-bit with IIS 7.5. To my surprise opening .NET 4.0 application I received the following error:
IIS 7.5 Detailed Error - 500.21 - Internal Server Error






As it turns out, some glitch caused this problem, and somehow .NET was not registered with IIS.
Running the following commands solved this issue:
%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i

Unique visitor counter in asp.net


In global.asax file 


<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="HitCounterControl.ascx.cs" Inherits="Rr.HitCounterControl" %>


<div style="padding-top: 15px; text-align: center">
    <span style="font-size:small">Visitor Count </span>
    <asp:Literal ID="ltlCounter" runat="server"></asp:Literal>
</div>





 void Session_Start(object sender, EventArgs e)
        {                    
         

//Get & increment visitor count
            int count = 0;
            DataSet tmpDs = new DataSet();
            HttpContext currentContext = HttpContext.Current;
            if (currentContext != null)
            {              
                try
                {
                    tmpDs.ReadXml(Server.MapPath("~/HitCounter.xml"));
                    int i = 0;
                    String ipAddress = currentContext.Request.UserHostAddress;
                    Session["ipAddress"] = ipAddress;
                    while (tmpDs.Tables[0].Rows[i]["ipAddress"].ToString() != null)
                    {
                        if (ipAddress == tmpDs.Tables[0].Rows[i]["ipAddress"].ToString())
                        {
                            count++;
                        }
                        i++;
                    }
                }
                catch (System.IO.FileNotFoundException)
                {
                    throw;
                }
                catch
                {
                    //no need to throw exception for this
                }
            }
            if (currentContext != null && count==0)
            {
                try
                {
                    Session["Start"] = DateTime.Now;
                    //UserVisitCount();
                    // DataSet tmpDs = new DataSet();
                    //read hit count
                    tmpDs.ReadXml(Server.MapPath("~/HitCounter.xml"));
                    tmpDs.Tables[0].Rows.Add(tmpDs.Tables[0].Rows.Count + 1, currentContext.Request.UserHostAddress, DateTime.Now.ToString(), currentContext.Session.SessionID);
                    tmpDs.WriteXml(Server.MapPath("~/HitCounter.xml"));
                    //set in Session                  
                }
                catch { }
            }


            Session["HitCount"] = tmpDs.Tables[0].Rows.Count;


}




In user control






using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;


namespace RR
{
    public partial class HitCounterControl : System.Web.UI.UserControl
    {
         int totalDigits = 6;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ltlCounter.Text = FormatHTMLCounter(Session["HitCount"].ToString());
            }
        }

       /// <summary>
       /// Calculates and formats the vistor count number
       /// </summary>
       /// <param name="visitCount"></param>
       /// <returns></returns>
        private string FormatHTMLCounter(string visitCount)
        {
            int noOfDigits = visitCount.Length;
            int zeroesToPrefix = totalDigits - noOfDigits;
            StringBuilder strCounterHtml = new StringBuilder();
         
            strCounterHtml.Append(@"<table align=""center"" style=""width: 120px; background-color: Black; color: White; text-align: center; font-weight: bold;""><tr>");

            for (int i = 0; i < zeroesToPrefix; i++)
            {
                strCounterHtml.Append(@"<td style=""border:1px solid white; padding:2px"">");
                strCounterHtml.Append("0");
                strCounterHtml.Append("</td>");
            }

            char[] visitCountChar = visitCount.ToCharArray();
            for (int i = 0; i < visitCountChar.Length; i++)
            {
                strCounterHtml.Append(@"<td style=""border:1px solid white; padding:2px"">");
                strCounterHtml.Append(visitCountChar[i]);
                strCounterHtml.Append("</td>");
            }

            strCounterHtml.Append("</tr></table>");
            return strCounterHtml.ToString();
        }
    }
}

//Drag and drop this user control to required web page


Sunday, 9 December 2012

Display time in ASP.NET Application


    <script type="text/javascript" language="javascript">
                function updateTime() {
                    var label = document.getElementById('currentTime');
                    if (label) {
                        var time = (new Date()).localeFormat("T");
                        label.innerHTML = time;
                    }
                }
                updateTime();
                window.setInterval(updateTime, 1000);
        </script>
            <Ajax:ToolkitScriptManager runat="server" EnablePartialRendering="true" ID="ScriptManager1" />
            <asp:UpdatePanel runat="server" ID="UpdatePanel1">
                <ContentTemplate>
                    <div style="width: 180px; height: 100px;">
                        <asp:Panel ID="timer" runat="server" Width="200px" ForeColor="DarkBlue" Style="z-index: 500; border-radius: 15px;">
                            <div style="width: 100%; height: 100%; vertical-align: middle; text-align: center;">
                                <span id="currentTime" clientidmode="Static" runat="server" style="font-size: large;font-weight: bold; line-height: 40px; color: Black;" />
                            </div>
                        </asp:Panel>
                        <Ajax:AlwaysVisibleControlExtender ID="avce" runat="server" TargetControlID="timer"
                            VerticalSide="Top" VerticalOffset="10" HorizontalSide="Right" HorizontalOffset="10"
                            ScrollEffectDuration=".1" />
                    </div>
                </ContentTemplate>
            </asp:UpdatePanel>

Saturday, 8 December 2012

VB.net Encryption and Decyption pssword



Encrypt Process:

Public Function Encrypt(ByVal plainText As String) As String

        Dim passPhrase As String = "Pas5pr@se"
        Dim saltValue As String = "zKqffFs392WuxGMhFkfhYj/HtDDIjSiXnYqMlMMzrNc="

        Dim hashAlgorithm As String = "SHA1"

        Dim passwordIterations As Integer = 2
        Dim initVector As String = "@1B2c3D4e5F6g7H8"
        Dim keySize As Integer = 256

        Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
        Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)

        Dim plainTextBytes As Byte() = Encoding.UTF8.GetBytes(plainText)


        Dim password As New PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations)

        Dim keyBytes As Byte() = password.GetBytes(keySize \ 8)
        Dim symmetricKey As New RijndaelManaged()

        symmetricKey.Mode = CipherMode.CBC

        Dim encryptor As ICryptoTransform = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes)

        Dim memoryStream As New IO.MemoryStream()
        Dim cryptoStream As New CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)

        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length)
        cryptoStream.FlushFinalBlock()
        Dim cipherTextBytes As Byte() = memoryStream.ToArray()
        memoryStream.Close()
        cryptoStream.Close()
        Dim cipherText As String = Convert.ToBase64String(cipherTextBytes)
        Return cipherText
    End Function


Decrypt Process


Public Function Decrypt(ByVal cipherText As String, ByVal salt As String) As String

        Dim passPhrase As String = "Pas5pr@se"
        Dim saltValue As String = "zKqffFs392WuxGMhFkfhYj/HtDDIjSiXnYqMlMMzrNc="
        Dim hashAlgorithm As String = "SHA1"
        Dim passwordIterations As Integer = 2
        Dim initVector As String = "@1B2c3D4e5F6g7H8"
        Dim keySize As Integer = 256
        ' Convert strings defining encryption key characteristics into byte
        ' arrays. Let us assume that strings only contain ASCII codes.
        ' If strings include Unicode characters, use Unicode, UTF7, or UTF8
        ' encoding.
        Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
        Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)

        ' Convert our ciphertext into a byte array.
        Dim cipherTextBytes As Byte() = Convert.FromBase64String(cipherText)

        ' First, we must create a password, from which the key will be
        ' derived. This password will be generated from the specified
        ' passphrase and salt value. The password will be created using
        ' the specified hash algorithm. Password creation can be done in
        ' several iterations.
        Dim password As New PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations)

        ' Use the password to generate pseudo-random bytes for the encryption
        ' key. Specify the size of the key in bytes (instead of bits).
        Dim keyBytes As Byte() = password.GetBytes(keySize \ 8)

        ' Create uninitialized Rijndael encryption object.
        Dim symmetricKey As New RijndaelManaged()

        ' It is reasonable to set encryption mode to Cipher Block Chaining
        ' (CBC). Use default options for other symmetric key parameters.
        symmetricKey.Mode = CipherMode.CBC

        ' Generate decryptor from the existing key bytes and initialization
        ' vector. Key size will be defined based on the number of the key
        ' bytes.
        Dim decryptor As ICryptoTransform = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes)

        ' Define memory stream which will be used to hold encrypted data.
        Dim memoryStream As New IO.MemoryStream(cipherTextBytes)

        ' Define cryptographic stream (always use Read mode for encryption).
        Dim cryptoStream As New CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)

        ' Since at this point we don't know what the size of decrypted data
        ' will be, allocate the buffer long enough to hold ciphertext;
        ' plaintext is never longer than ciphertext.
        Dim plainTextBytes As Byte() = New Byte(cipherTextBytes.Length - 1) {}

        ' Start decrypting.
        Dim decryptedByteCount As Integer = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length)

        ' Close both streams.
        memoryStream.Close()
        cryptoStream.Close()
        ' Convert decrypted data into a string.
        ' Let us assume that the original plaintext string was UTF8-encoded.
        Dim plainText As String = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount)

        ' Return decrypted string.
        Return plainText
    End Function

C# decryption password




Decryption

    public string Decrypt(string cipherText,string salt)
    {
        string passPhrase = "Pas5pr@se";        // can be any string
        string saltValue = salt;        // can be any string
        string hashAlgorithm = "SHA1";             // can be "MD5"
        int passwordIterations = 2;                  // can be any number
        string initVector = "@1B2c3D4e5F6g7H8"; // must be 16 bytes
        int keySize = 256;                // can be 192 or 128
        cipherText = cipherText.Replace(" ", "+");

        // Convert strings defining encryption key characteristics into byte
        // arrays. Let us assume that strings only contain ASCII codes.
        // If strings include Unicode characters, use Unicode, UTF7, or UTF8
        // encoding.
        byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
        byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);

        // Convert our ciphertext into a byte array.
        byte[] cipherTextBytes = Convert.FromBase64String(cipherText);

        // First, we must create a password, from which the key will be
        // derived. This password will be generated from the specified
        // passphrase and salt value. The password will be created using
        // the specified hash algorithm. Password creation can be done in
        // several iterations.
        PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase,
                                                        saltValueBytes,
                                                        hashAlgorithm,
                                                        passwordIterations);

        // Use the password to generate pseudo-random bytes for the encryption
        // key. Specify the size of the key in bytes (instead of bits).
        byte[] keyBytes = password.GetBytes(keySize / 8);

        // Create uninitialized Rijndael encryption object.
        RijndaelManaged symmetricKey = new RijndaelManaged();

        // It is reasonable to set encryption mode to Cipher Block Chaining
        // (CBC). Use default options for other symmetric key parameters.
        symmetricKey.Mode = CipherMode.CBC;

        // Generate decryptor from the existing key bytes and initialization
        // vector. Key size will be defined based on the number of the key
        // bytes.
        ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
                                                         keyBytes,
                                                         initVectorBytes);

        // Define memory stream which will be used to hold encrypted data.
        MemoryStream memoryStream = new MemoryStream(cipherTextBytes);

        // Define cryptographic stream (always use Read mode for encryption).
        CryptoStream cryptoStream = new CryptoStream(memoryStream,
                                                      decryptor,
                                                      CryptoStreamMode.Read);

        // Since at this point we don't know what the size of decrypted data
        // will be, allocate the buffer long enough to hold ciphertext;
        // plaintext is never longer than ciphertext.
        byte[] plainTextBytes = new byte[cipherTextBytes.Length];
        // Start decrypting.
        int decryptedByteCount = cryptoStream.Read(plainTextBytes,0,plainTextBytes.Length);

        // Close both streams.
        memoryStream.Close();
        cryptoStream.Close();

        // Convert decrypted data into a string.
        // Let us assume that the original plaintext string was UTF8-encoded.
        string plainText = Encoding.UTF8.GetString(plainTextBytes,0,decryptedByteCount);

        // Return decrypted string.  
        return plainText;
    }

Thursday, 29 November 2012

read and write data into xml using gridview


//creation of gridview

<table width="900px">
                <tr>
                    <td style="background-color: Silver; width: 900">
                        <asp:GridView ID="gvClientTestimonials" runat="server" AutoGenerateColumns="false"
                            OnRowDataBound="gvClientTestimonials_RowDataBound">
                            <Columns>
                                <asp:TemplateField>
                                    <ItemTemplate>
                                        <p>
                                            <img src="images/open-quotes.gif" width="19" height="12" hspace="5" vspace="5" align="bottom"><asp:Label
                                                ID="lblTestimonial" runat="server">
                                            </asp:Label>
                                            <img src="images/close-quotes1.gif" width="19" height="12" hspace="5" vspace="5"
                                                align="middle"></p>
                                        <div align="right">
                                            <strong>--<asp:Label ID="lblClientName" runat="server"></asp:Label></strong></div>
                                        <br />
                                    </ItemTemplate>
                                </asp:TemplateField>
                            </Columns>
                        </asp:GridView>
                    </td>
                </tr>
            </table>

//in.cs file


protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                DataSet ds = new DataSet("Testimonials");
                //finding xml file is exist or not

                if (File.Exists(Server.MapPath("Testimonials.xml")) == false)
                {                  
                    ds.Tables.Add("Testimonials");
                    ds.Tables[0].Columns.Add("Id");
                    ds.Tables[0].Columns.Add("Testimonial");
                    ds.Tables[0].Columns.Add("Client");
                    ds.Tables[0].Columns.Add("DateTime");
                   // ds.Tables[0].Rows.Add(txtClientTestimonials.Text, txtClientName.Text, DateTime.Now.ToString());
                    ds.Tables[0].Rows.Add(0, "Working with the some is a great pleasure!", "ram", DateTime.Now.ToString());
                    ds.WriteXml(Server.MapPath("ClientTestimonials/Testimonials.xml"));
                    ds.Clear();
                    ds.ReadXml(Server.MapPath("ClientTestimonials/Testimonials.xml"));
                    gvClientTestimonials.DataSource = ds;
                    gvClientTestimonials.DataBind();
                }
                else
                {
                    ds.ReadXml(Server.MapPath("ClientTestimonials/Testimonials.xml"));
                    gvClientTestimonials.DataSource = ds;
                    gvClientTestimonials.DataBind();
                }
               
            }
           
        }
        protected void gvClientTestimonials_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Label lblTestimonial = (Label)e.Row.FindControl("lblTestimonial");
                Label lblClientName = (Label)e.Row.FindControl("lblClientName");
                DataRowView drv = (DataRowView)e.Row.DataItem;
                lblTestimonial.Text = drv["Testimonial"].ToString();
                lblClientName.Text = drv["Client"].ToString();
            }
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            DataSet ds = new DataSet("Testimonials");
            if (File.Exists(Server.MapPath("ClientTestimonials/Testimonials.xml")) == false)
            {
                ds.Tables.Add("Testimonials");
                ds.Tables[0].Columns.Add("Id");
                ds.Tables[0].Columns.Add("Testimonial");
                ds.Tables[0].Columns.Add("Client");
                ds.Tables[0].Columns.Add("DateTime");              
                ds.Tables[0].Rows.Add(0,"Working with the Roopasoft is a great pleasure!","James",DateTime.Now.ToString());
                ds.WriteXml(Server.MapPath("ClientTestimonials/Testimonials.xml"));
            }
            else
            {
                ds.ReadXml(Server.MapPath("ClientTestimonials/Testimonials.xml"));
                ds.Tables[0].Rows.Add(ds.Tables[0].Rows.Count+1,txtClientTestimonials.Text, txtClientName.Text, DateTime.Now.ToString());
                ds.WriteXml(Server.MapPath("ClientTestimonials/Testimonials.xml"));
            }
            gvClientTestimonials.DataSource = ds;
            gvClientTestimonials.DataBind();
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            txtClientName.Text = "";
            txtClientTestimonials.Text = "";

        }

Sunday, 18 November 2012

create binary image converstion and stores in database


//on button click(browse button)

private void btnProductVariantBrowse_Click(object sender, EventArgs e)
        {
  //it stores the file name in textbox
            txtProductImage.Text = BrowseFile();
         
        }

//it open window and return the file name

public string BrowseFile()
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.RestoreDirectory = true;
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                return ofd.FileName;
            }
            return "";
        }
//picture details


 if (File.Exists(txtProductImage.Text))
            {
                FileInfo fi = new FileInfo(txtProductImage.Text);
                pvDetails.picture = new Picture();
                pvDetails.picture.PictureBinary = DbHelper.FileToByteArray(txtProductImage.Text);
                pvDetails .picture .MimeType="Image/" + fi.Extension.Substring(1, fi.Extension.Length - 1);
                pvDetails .picture.IsNew =true;       
               

            }
           

//file to byte array class


 public static byte[] FileToByteArray(string _FileName)
        {
            byte[] bytArrData = null;
            try
            {
                // Open file for reading
                System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                // attach filestream to binary reader
                System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);
                // get total byte length of the file
                long _TotalBytes = new System.IO.FileInfo(_FileName).Length;
                // read entire file into buffer
                bytArrData = _BinaryReader.ReadBytes((Int32)_TotalBytes);

                // close file reader
                _FileStream.Close();
                _FileStream.Dispose();
                _BinaryReader.Close();
            }
            catch (Exception ex)
            {
                // Error
                //Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
            }
            return bytArrData;
        }