Saturday, February 20, 2010

How to use javascript inside updatePanel, asp.net

Use Javascirpt in code behind like this 

string Scriptup = "javascript: alert('Munesh Sunda');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Scriptup", Scriptup, true);

This works fine.

How to Remove duplicate records - Sql-server 2005

Query to remove duplicate records, in this query please add all the columns in GROUP BY clause that are duplicate, it is based on primary key


DELETE from TableName
WHERE CoumnName1 + CoumnName2 + CoumnName3
IN (select CoumnName1 + CoumnName2 + CoumnName3
        FROM TableName
        group by CoumnName1 , CoumnName2 ,CoumnName3
        having Count(ID)>1)
AND ID NOT IN (select MAX(ID) from TableName
        WHERE CoumnName1 + CoumnName2 + CoumnName3
        IN (select CoumnName1 + CoumnName2 + CoumnName3
                FROM TableName
                group by CoumnName1 , CoumnName2 ,CoumnName3
                having Count(ID)>1)
        GROUP BY CoumnName1 ,CoumnName2 ,CoumnName3)

How to DownLoad a File in ASP.NET ?

To DownLoad a file:-

1. Add a link to page, Like this:-
               <a href="Download.ashx?FileName=file.pdf&FilePath=DownLoad/">Download Standing Order Mandate</a >

          Where file.pdf = file to download
                     DownLoad = Folder name where the file placed at server.

2. Then  Add a Generic Handler to the website/project with the name Download.ashx and add the following code:
   public void ProcessRequest(HttpContext context)
    {
        if (context.Request.QueryString["FileName"] != null && context.Request.QueryString["FilePath"] != null)
        {
            string strFileName = context.Request.QueryString["FileName"];
            string strOnPath = @"~/" + context.Request.QueryString["FilePath"].ToString() + strFileName;
            string strpath = context.Server.MapPath(strOnPath);
            FileInfo myFile = new FileInfo(strpath);
            context.Response.Clear();
            context.Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName);
            context.Response.AddHeader("Content-Length", myFile.Length.ToString());
            context.Response.ContentType = "application/octet-stream";
            context.Response.WriteFile(myFile.FullName);
            context.Response.End();
        }

  

Monday, February 15, 2010

Date Format, C#

Date FromatOutput
dd-MMM-yyyy15-Feb-2010
dd-MM-yyyy15-02-2010
dd-MMM-yyyy hh:mm:ss15-Feb-2010 11:25:56
dd-MMM-yyyy hh:mm tt15-Feb-2010 11:25 AM
dd-MMM-yy15-Feb-10
MMM dd, yyyyFeb 15, 2010
MMMM dd, yyyyApril 15, 2010


Example:
DateTime objDt = DateTime.Now;
objDt.ToString("dd-MMM-YYYY") = 15-Feb-2010

Trim a string to a specified length, C#

Trim a string to a length, Here

        public  string TrimString(string strValue,int Count)
        {           
            if (strValue.Length > Count)
            {
                strValue = strValue.Substring(0, Count - 1) + "..";
            }
            return strValue;
        }

Generate an alphanumeric Random Code, C#

        To generate an alphanumeric Random code

         ///

        /// Public static function Generate Random Code
        /// generate the random code
        /// Created By:   Munesh
        /// Created Date: Feb 10, 2010
        ///

        /// string
        public static string GenerateRandomCode()
        {
            int _minLength = 6, _maxLength = 6;

            string _charsLCase = "abcdefgijkmnopqrstwxyz";
            string _charsUCase = "ABCDEFGHJKLMNPQRSTWXYZ";
            string _charsNumeric = "23456789";

            // Create a local array containing supported Verification Code characters
            char[][] _charGroups = new char[][]
            {
                _charsLCase.ToCharArray(),
                _charsUCase.ToCharArray(),
                _charsNumeric.ToCharArray(),
                //PASSWORD_CHARS_SPECIAL.ToCharArray()
            };

            // Use this array to track the number of unused characters in each
            // character group.
            int[] _charsLeftInGroup = new int[_charGroups.Length];

            // Initially, all characters in each group are not used.
            for (int i = 0; i < _charsLeftInGroup.Length; i++)
                _charsLeftInGroup[i] = _charGroups[i].Length;

            // Use this array to track (iterate through) unused character groups.
            int[] _leftGroupsOrder = new int[_charGroups.Length];

            // Initially, all character groups are not used.
            for (int i = 0; i < _leftGroupsOrder.Length; i++)
                _leftGroupsOrder[i] = i;

            // Because we cannot use the default randomizer, which is based on the
            // current time (it will produce the same "random" number within a
            // second), we will use a random number generator to seed the
            // randomizer.

            // Use a 4-byte array to fill it with random bytes and convert it then
            // to an integer value.
            byte[] _randomBytes = new byte[4];

            // Generate 4 random bytes.
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            rng.GetBytes(_randomBytes);

            // Convert 4 bytes into a 32-bit integer value.
            int _seed = (_randomBytes[0] & 0x7f) << 24 |
                        _randomBytes[1] << 16 |
                        _randomBytes[2] << 8 |
                        _randomBytes[3];

            // Now, this is real randomization.
            Random random = new Random(_seed);

            // This array will hold password characters.
            char[] _verificationCode = null;

            // Allocate appropriate memory for the password.
            if (_minLength < _maxLength)
                _verificationCode = new char[random.Next(_minLength, _maxLength + 1)];
            else
                _verificationCode = new char[_minLength];

            // Index of the next character to be added to password.
            int _nextCharIdx;

            // Index of the next character group to be processed.
            int _nextGroupIdx;

            // Index which will be used to track not processed character groups.
            int _nextLeftGroupsOrderIdx;

            // Index of the last non-processed character in a group.
            int _lastCharIdx;

            // Index of the last non-processed group.
            int _lastLeftGroupsOrderIdx = _leftGroupsOrder.Length - 1;

            // Generate password characters one at a time.
            for (int i = 0; i < _verificationCode.Length; i++)
            {
                // If only one character group remained unprocessed, process it;
                // otherwise, pick a random character group from the unprocessed
                // group list. To allow a special character to appear in the
                // first position, increment the second parameter of the Next
                // function call by one, i.e. lastLeftGroupsOrderIdx + 1.
                if (_lastLeftGroupsOrderIdx == 0)
                    _nextLeftGroupsOrderIdx = 0;
                else
                    _nextLeftGroupsOrderIdx = random.Next(0,
                                                         _lastLeftGroupsOrderIdx);

                // Get the actual index of the character group, from which we will
                // pick the next character.
                _nextGroupIdx = _leftGroupsOrder[_nextLeftGroupsOrderIdx];

                // Get the index of the last unprocessed characters in this group.
                _lastCharIdx = _charsLeftInGroup[_nextGroupIdx] - 1;

                // If only one unprocessed character is left, pick it; otherwise,
                // get a random character from the unused character list.
                if (_lastCharIdx == 0)
                    _nextCharIdx = 0;
                else
                    _nextCharIdx = random.Next(0, _lastCharIdx + 1);

                // Add this character to the password.
                _verificationCode[i] = _charGroups[_nextGroupIdx][_nextCharIdx];

                // If we processed the last character in this group, start over.
                if (_lastCharIdx == 0)
                    _charsLeftInGroup[_nextGroupIdx] =
                                              _charGroups[_nextGroupIdx].Length;
                // There are more unprocessed characters left.
                else
                {
                    // Swap processed character with the last unprocessed character
                    // so that we don't pick it until we process all characters in
                    // this group.
                    if (_lastCharIdx != _nextCharIdx)
                    {
                        char _temp = _charGroups[_nextGroupIdx][_lastCharIdx];
                        _charGroups[_nextGroupIdx][_lastCharIdx] =
                                    _charGroups[_nextGroupIdx][_nextCharIdx];
                        _charGroups[_nextGroupIdx][_nextCharIdx] = _temp;
                    }
                    // Decrement the number of unprocessed characters in
                    // this group.
                    _charsLeftInGroup[_nextGroupIdx]--;
                }

                // If we processed the last group, start all over.
                if (_lastLeftGroupsOrderIdx == 0)
                    _lastLeftGroupsOrderIdx = _leftGroupsOrder.Length - 1;
                // There are more unprocessed groups left.
                else
                {
                    // Swap processed group with the last unprocessed group
                    // so that we don't pick it until we process all groups.
                    if (_lastLeftGroupsOrderIdx != _nextLeftGroupsOrderIdx)
                    {
                        int _temp = _leftGroupsOrder[_lastLeftGroupsOrderIdx];
                        _leftGroupsOrder[_lastLeftGroupsOrderIdx] =
                                    _leftGroupsOrder[_nextLeftGroupsOrderIdx];
                        _leftGroupsOrder[_nextLeftGroupsOrderIdx] = _temp;
                    }
                    // Decrement the number of unprocessed groups.
                    _lastLeftGroupsOrderIdx--;
                }
            }

            // Convert password characters into a string and return the result.
            return new string(_verificationCode);
        }

Saturday, February 13, 2010

Resize image and save without saving it to temporary file, C#

Upload an image after resizing to specific size without saving it to temporary file.      


ResizeImageAndSave(fileImage.PostedFile.InputStream, Width, Height, FileName);

        ///
        /// Resize image of Weight X Height and save
        ///

        public static void ResizeImageAndSave(Stream fs, int intW, int intH, string FileName)
        {
            System.Drawing.Image objImg = Bitmap.FromStream(fs);
            int intImgH = objImg.Height;
            int intImgW = objImg.Width;
            double R = ((double)intImgW / (double)intImgH);
            //if image is greater than 800*800
            if (intImgH > intImgW)
            {
                if (intImgH > intH)
                {
                    intImgH = intH;
                    intImgW = (int)(intH * R);
                }
            }
            else
            {
                if (intImgW > intW)
                {
                    intImgW = intW;
                    intImgH = (int)(intW / R);
                }
            }

          
            Bitmap outputImage = new Bitmap(intImgW, intImgH,PixelFormat.Format24bppRgb);
            outputImage.SetResolution(objImg.HorizontalResolution, objImg.VerticalResolution);
            Graphics graphics = Graphics.FromImage(outputImage);
            graphics.Clear(Color.White);
            graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            graphics.DrawImage(objImg, new Rectangle(0, 0, intImgW, intImgH), new Rectangle(4, 4, objImg.Width - 4, objImg.Height - 4), GraphicsUnit.Pixel);
            graphics.Dispose();
            outputImage.Save(FileName);
            outputImage.Dispose();
            outputImage = null;
        }

Stored procedure for paging with sorting


CREATE PROCEDURE DataWithPagingAndSorting
--Add the parameters for the stored procedure here
    @insPageNo SMALLINT = 1,
    @insPageSize SMALLINT = 10,
    @SortType varchar(128) = 'DT',
AS
BEGIN
    DECLARE @intTotalCount INT,
            @intPageCount INT
      SET NOCOUNT ON

   SELECT @intTotalCount = COUNT(Id) from TableName
                   
        SET @intPageCount = @intTotalCount/@insPageSize;       
        IF (@intTotalCount%@insPageSize<>0)
            SET @intPageCount= @intPageCount+1
        IF (@insPageNo>@intPageCount)
            SET @insPageNo=@intPageCount       

        SELECT TOP (@insPageSize) *
            FROM (
                    SELECT ROW_NUMBER() OVER ( ORDER BY 
                                                    CASE WHEN @SortType  = 'NM' THEN Name END
                                                    ,CASE WHEN @SortType  = 'EM' THEN [Email] END
                                                    ,CASE WHEN @SortType  = 'MN' THEN ContactNo END
                                                    ,CASE WHEN @SortType  = 'CC' THEN Country END
                                                    ,CASE WHEN @SortType  = 'DT' THEN CreDate END DESC
                                                ) AS RowNum,
                            M.Id [ID], [Name],M.Add1, M.Add2,
                            M.Town, M.PostCode, M.ContactNo, M.CreDate, M.ActDate , Country, M.Email
                    from TableName M                
                ) A
                   
            WHERE A.RowNum > (@insPageSize * (@insPageNo - 1))
               
           
            SELECT @intTotalCount as TotalCount;
END

Friday, February 12, 2010

Code to Read Files from Directory - C#, ASP.NET

public void ReadFile(strFileName)
{
      System.IO.DirectoryInfo obj = new DirectoryInfo(Server.MapPath("FolderName/" + strFileName);
      FileInfo[] Files = obj.GetFiles();

      for (int i = 0; i < Files.Length; i++)
     {
          string FileName = Files[i].Name;
          string FileExtension = FileName.Substring(0, FileName.LastIndexOf("."));
          InsertToDB(FileName, FileExtension ); --Function to save in database
     }
}

Thursday, February 11, 2010

Get value of radiobuttonlist, javascript

Call the javascript function at page_load()

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
rbtnList.Attributes.Add("onclick", "javascript:checkOthersOption('" + rbtnList.ClientID + "');");
}
}

And Add javascript to the aspx page


function checkOthersOption(id)
{
var radioList = document.getElementById(id);
var radio = radioList.getElementsByTagName('input');
alert(radio.length);
for (var i = 0; i < radio.length; i++)
{
if(radio[i].type =="radio")
{
if (radio[i].checked)
alert(radio[i].value);
}
}

}