Welcome to my blog.

Post on this blog are my experience which I like to share. This blog is completely about sharing my experience and solving others query. So my humble request would be share you queries to me, who knows... maybe I can come up with a solution...
It is good know :-)

Use my contact details below to get directly in touch with me.
Gmail: nadarmuthukumar1987@gmail.com
Yahoo: nadarmuthukumar@yahoo.co.in

Apart from above people can share their queries on programming related stuff also. As me myself a programmer ;-)
Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Session Value lost on every request

Recently I was facing an issue where my website is working fine with other browsers but it fails on internet explorer. Getting deeper into that issue I found like session values are lost on every request on pages on internet explorer, this is because session id actually getting changes on every request on internet explorer.

Getting into deeper, why it wasn't working is, because my website's url contained an underscore character (ie http://my_website). I have changed the name and now it all works fine.

Reference: Muthukumar Nadar (http://nadarmuthukumar.blogspot.in) 
http://forums.iis.net/post/1873244.aspx

Hope you liked this post, also let me know your thoughts on the post through your valuable comment. Thank you.

Insert text at the cursor position in CKEditor

function InsertHTML() {
      CKEDITOR.instances['<%= CKEditor1.ClientID %>'].insertText('Your Text');
      return false;
}

Reference: Muthukumar (http://nadarmuthukumar.blogspot.in) 
Hope you liked this post, also let me know your thoughts on the post through your valuable comment. Thank you.

Unable to set Minimum and Maximum value of MultiHandleSliderExtender

Anyone who have this problem the solution is to reset or clear MultiHandleSliderExtender's ClientState using below code.
MultiHandleSliderExtender_Price.ClientState = "0";
OR
MultiHandleSliderExtender_Price.ClientState = "45,55";
Reference: Muthukumar (http://nadarmuthukumar.blogspot.in) Hope you liked this post, also let me know your thoughts on the post through your valuable comment. Thank you.

Convert List to DataTable in C#

public DataTable ConvertToDataTable<T>(IList<T> data)
    {
        PropertyDescriptorCollection properties =
           TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        foreach (PropertyDescriptor prop in properties)
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        foreach (T item in data)
        {
            DataRow row = table.NewRow();
            foreach (PropertyDescriptor prop in properties)
                row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
            table.Rows.Add(row);
        }
        return table;

    }
Reference: Muthukumar (http://nadarmuthukumar.blogspot.in) 
Hope you liked this post, also let me know your thoughts on the post through your valuable comment. 
Thank you.

Find median of an array in c#

public static int GetMedian(int[] Value)
    {
        decimal Median = 0;
        int size = Value.Length;
        int mid = size / 2;
        Median = (size % 2 != 0) ? (decimal)Value[mid] : ((decimal)Value[mid] + (decimal)Value[mid + 1]) / 2;
        return Convert.ToInt32(Math.Round(Median));
    }

Reference: Muthukumar (http://nadarmuthukumar.blogspot.in) 
Hope you liked this and let me know your thoughts on post through your valuable comment.

Thank you

Get last thursday of a month in C#

int Monthly = 1;
DateTime StartDate = new DateTime(2012, 01, 01);
DateTime EndDate = new DateTime(2012, 10, 01);
for (DateTime i = StartDate; i < EndDate; i = i.AddMonths(Monthly))
{
    const int Thursday = 4;
    const int DayDiff = 7 - Thursday;
    //This will give me last day of month
    int Day = DateTime.DaysInMonth(i.Year, i.Month);
    //This will return any value from "0-7" where 0 is sunday.
    int DayOfWeek = (int)new DateTime(i.Year, i.Month, Day).DayOfWeek;
    DateTime _dtNew = new DateTime(i.Year, i.Month, Day).AddDays(-((DayOfWeek < Thursday) ? (DayOfWeek + DayDiff) : (DayOfWeek - Thursday)));
    Response.Write(_dtNew.ToString("dd-MMM-yyyy") + "
"); }
Reference: Muthukumar (http://nadarmuthukumar.blogspot.in)
Hope you liked this and let me know your thoughts on post through your comments :)

This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms

Actually, this issue is not caused by IIS, the problem occurs when the following conditions are true:
  • The HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\fipsalgorithmpolicy registry subkey is set to 1.
  • ASP.NET 2.0 uses the RijndaelManaged implementation of the AES algorithm when it processes view state data. The ReindaelManaged implementation has not been certified by the National Institute of Standards and Technology (NIST) as compliant with the Federal Information Processing Standard (FIPS). Therefore, the AES algorithm is not part of the Windows Platform FIPS validated cryptographic algorithms.
To work around this problem, change the configuration in the application-level Web.config file. Specify that ASP.NET use the Triple Data Encryption Standard (3DES) algorithm to process view state data. To do this, follow these steps:
  1. In a text editor such as Notepad, open the application-level Web.config file.
  2. In the Web.config file, locate the <system.web> section.
  3. Add the following <machineKey> section to in the <system.web> section: <machineKey validationKey="AutoGenerate,IsolateApps" decryptionKey="AutoGenerate,IsolateApps" validation="3DES" decryption="3DES"/>
  4. Save the Web.config file.
  5. Restart the Microsoft Internet Information Services (IIS) service. To do this, run the following command at a command prompt: iisreset
After doing this also if it is not working then set the subkey HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\fipsalgorithmpolicy value to 0



Reference: Muthukumar (http://nadarmuthukumar.blogspot.in), ref
Hope you liked this and let me know your thoughts on post through your comments :)

Upload file to webserver using c#

  1. Place one Label, FileUpload and Button control to your page.
  2. Name Label control as “lblMessage”, FileUpload control as “fuUpload” and Button control as “btnSubmit”
  3. Create a Method as shown below,
    private bool UploadFile()
    {
        bool _Result = false;
        try
        {
          if (fuUpload.HasFile)
          {
              string strFileName = DateTime.Now.ToString("ddMMyyyy_HHmmss");
              string strFileType = System.IO.Path.GetExtension(fuUpload.FileName).ToString().ToLower();
              strFileName += fuUpload.FileName;
              ViewState["FileName"] = strFileName;
              if (strFileType.ToLower() == ".pdf")
              {
                   fuUpload.SaveAs(Server.MapPath("~/Pdf/" + strFileName));
                   _Result = true;
              }
              else
              {
                   lblMessage.Text = "Only pdf files allowed.";
                   _Result = false;
              }
          }
          else
          {
              _Result = false;
              lblMessage.Text = "Please select valid pdf file";
          }
        }
        catch (Exception ex)
        {
             _Result = false;
             lblMessage.Text = ex.Message;
        }
        return _Result;
    }
    
  4. Now under btnSubmit_click event call the created method as shown below
    if (UploadFile())
    {
         // You can get the uploaded file name from below viewstate
         string FileName = Convert.ToString(ViewState["FileName"]);
    }
    
Reference: Muthukumar (http://nadarmuthukumar.blogspot.in)
Hope you liked this and let me know your thoughts on post through your comments :)

Increment for loop by step n

Normally i++ increments i by 1, in order to increment i by nth count you can use i += n where n is any number.
e.g.
for (int i = 0; i < 11; i += 2)
{
Console.WriteLine(i);
}
Reference: Muthukumar (http://nadarmuthukumar.blogspot.in) Hope you liked this and let me know your thoughts on post through your comments :)

Generate Random Code

Import below into your Namespace
using System.Security.Cryptography;
Declare Below Variables
public const string Alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public const string AlphaNumeric = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
public const string Numeric = "1234567890";
Create a Enum as below
public enum StringType { Alpha, AplhaNumeric, Numeric }
Create a Method as below
public static string GenerateRandomCode(int CodeSize, StringType objStringType)
        {
            string RandomCode = string.Empty;
            try
            {
                char[] chars = new char[62];
                if (objStringType == StringType.AplhaNumeric)
                    chars = AlphaNumeric.ToCharArray();
                else if (objStringType == StringType.Numeric)
                    chars = Numeric.ToCharArray();

                byte[] data = new byte[1];
                RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
                crypto.GetNonZeroBytes(data);
                data = new byte[CodeSize];
                crypto.GetNonZeroBytes(data);
                StringBuilder result = new StringBuilder(CodeSize);
                foreach (byte b in data)
                    result.Append(chars[b % (chars.Length - 1)]);
                RandomCode = result.ToString();
            }
            catch (Exception ex)
            {
                //throw ex;
            }
            return RandomCode;
        }

You can call the method using below code
Response.Write(GenerateRandomCode(4, StringType.Numeric));

Reference: Muthukumar (http://nadarmuthukumar.blogspot.in)
Hope you liked this and let me know your thoughts on post through your comments :)

80070005 Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

Recently I was having a task to work with Word Automation. I have created word file and everything sucessfully. When I deployed the same to Server it failed and thown me below error,

Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80070005 Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)).


After going into lots of research below solution worked for me.

<system.web>
<identity impersonate="true"
userName="Server User Name"
password="Server Password" />
</system.web>


Add Above to your webconfig file.

Reference: Muthukumar (
http://nadarmuthukumar.blogspot.in)
Hope you liked this and let me know your thoughts on post through your comments :)

Create Connection Strings easily

The connection string may include attributes such as the name of the driver, server and database, as well as security information such as user name and password.

UDL file can be used to generate connection strings easily.

To create UDL file first create new text file and rename it from "filename.txt" to "filename.udl" that's it.

Now run filename.udl by double clicking it.

Data Link Properties window will open, select Provider Tab and select the provider you need and click next.

Now provide the details as required and click on test connection.

If you get success message, you are done.

Now open udl file as text file, connection string will be there in the last line.

Reference: Muthukumar (http://nadarmuthukumar.blogspot.in/), CodeProject
 

Convert dd mm yyyy string to datetime

Create a function as shown below.
Your can use any one of the method give below inside the function, rest you can comment it out.
private DateTime FormatDate(string _Date)
{
        DateTime Dt;
            
        //Method 1
        System.Globalization.DateTimeFormatInfo dateInfo = new System.Globalization.DateTimeFormatInfo();
        dateInfo.ShortDatePattern = "dd/MM/yyyy";
        Dt = Convert.ToDateTime(_Date, dateInfo);
        //Method 2
        IFormatProvider mFomatter = new System.Globalization.CultureInfo("en-US");
        Dt = DateTime.ParseExact(_Date, "dd/MM/yyyy", mFomatter);
        //Method 3
        Dt = DateTime.ParseExact(_Date, "dd/MM/yyyy", null);
            
        return Dt;
}
To call the function use below code
string UrDate = "27/08/2008";
DateTime _obj = FormatDate(UrDate);

Reference: Muthukumar (http://nadarmuthukumar.blogspot.in)

Build Succeeded but Publish Failed

Recently I faced an issue where my website is getting build successfully, means NO error NO warning NO MESSAGE, but if I try to publish it fails.

To find solution for this you need to see your output window.
You can open the output window by pressing Ctl + w, O.

In the output window you can check at which stage does the publish website operation fail.

Reference: Muthukumar (http://nadarmuthukumar.blogspot.in)

Pan Card Validation in C#

Add below code to your head section of page under script tag.
function chkPANLen(sender, args)
        {
            var PANno = document.getElementById("").value;
            var pan = /^([A-Z a-z]{5})+([0-9]{4})+([A-Z a-z]{1})$/;
            if (!(PANno.match(pan)))
            {
                args.IsValid = false ;
                return;
            }
            args.IsValid = true ;
        }
Below is the code to validate your control
Pan No. :
                   








Reference: Muthukumar (http://nadarmuthukumar.blogspot.in)

serial number column in gridview


   
      
         
            <%# Container.DataItemIndex + 1 %>                                    
         
      
   

Reference: Muthukumar (http://nadarmuthukumar.blogspot.in)

Clear all controls in Asp.net

public static void ClearAllControls(Control PageObject)
        {
            foreach (Control ctrControl in PageObject.Controls)
            {
                if (object.ReferenceEquals(ctrControl.GetType(), typeof(TextBox)))
                    ((TextBox)ctrControl).Text = string.Empty;

                if (object.ReferenceEquals(ctrControl.GetType(), typeof(DropDownList)))
                    ((DropDownList)ctrControl).SelectedIndex = -1;

                ClearAllControls(ctrControl);
            }
        }
Call Controlprocedure using below code
ClearAllControls(this);
Note in the above code I have only involved TextBox and DropDownList Controls, likewise you can use your own.
Reference: Muthukumar (http://nadarmuthukumar.blogspot.in)

no implicit conversion between null to int

I faced this issue twice now.

When I tried to use below code
DateTime? foo;
foo = string.IsNullOrEmpty(txtDate.Text) ? null : Convert.ToDateTime(txtDate.Text);
I get error as,
Type of conditional expression cannot be determined because there is no implicit conversion between '' and 'System.DateTime'

Solution for the problem is below
DateTime? foo;
foo = string.IsNullOrEmpty(txtDate.Text) ? (DateTime?)null : Convert.ToDateTime(txtDate.Text);



Reference: Muthukumar (http://nadarmuthukumar.blogspot.in)

MonthPicker

At the end of this article you will be capable of creating your own month year picker.

While creating reports we normally give from and to date filter, for which we use our normal DateTimePicker. But recently I got a requirement where I want to give "From Month Year" to "To Month Year" filter for a report. This can be achieved using DateTimePicker with some modification on its Javascript. But on some case I failed and decided to create my own usercontrol.

Technology used
Dot Net 3.5 Framework, Ajax.

Month Picker
 Follow below steps to create your Month Year Picker.
Step 1. Create a User Control
  1. Right Click on the project and click on "Add New Item"
  2. Select Web User Control and name it as "MonthYearPicker.ascx" and click Add.
  3. Now place below code into designer part of your user control.

    
        
        
        
        
            
                loading...
            
        
        
            
            
            
            
            
        
    
 

4.    And Place the below code to Code Behind of User Control 
private string _TextBoxCss;
    public string TextBoxCss
    {
        get { return _TextBoxCss; }
        set { _TextBoxCss = value; }
    }

    private string _SelectButtonCss;
    public string SelectButtonCss
    {
        get { return _SelectButtonCss; }
        set { _SelectButtonCss = value; }
    }

    private string _SetButtonCss;
    public string SetButtonCss
    {
        get { return _SetButtonCss; }
        set { _SetButtonCss = value; }
    }

    private string _PanelCss;
    public string PanelCss
    {
        get { return _PanelCss; }
        set { _PanelCss = value; }
    }

    private int _MinYear;
    public int MinYear
    {
        get { return _MinYear; }
        set { _MinYear = value; }
    }

    private int _MaxYear;
    public int MaxYear
    {
        get { return _MaxYear; }
        set { _MaxYear = value; }
    }

    private int _MinMonth;
    public int MinMonth
    {
        get { return _MinMonth; }
        set { _MinMonth = value; }
    }

    private int _MaxMonth;
    public int MaxMonth
    {
        get { return _MaxMonth; }
        set { _MaxMonth = value; }
    }

    private string _Value;
    public string Value
    {
        get
        {
            _Value = GetSelectMonthYear();
            return _Value;
        }
        set { _Value = value; }
    }

    protected void Page_Init(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            txtValue.CssClass = _TextBoxCss;
            btnSelect.CssClass = _SelectButtonCss;
            btnSet.CssClass = _SetButtonCss;
            pnlDate.CssClass = _PanelCss;

            ddlYear.Items.Clear();
            _MinYear = _MinYear == 0 ? DateTime.MinValue.Year : _MinYear;
            _MaxYear = _MaxYear == 0 ? DateTime.MaxValue.Year : _MaxYear;
            for (int i = _MinYear; i <= _MaxYear; i++)
                ddlYear.Items.Add(new ListItem(i.ToString(), i.ToString()));

            ddlMonth.Items.Clear();
            _MinMonth = _MinMonth == 0 ? DateTime.MinValue.Month : _MinMonth;
            _MaxMonth = _MaxMonth == 0 ? DateTime.MaxValue.Month : _MaxMonth;
            for (int i = _MinMonth; i <= _MaxMonth; i++)
                ddlMonth.Items.Add(new ListItem(GetMonth(i), i.ToString()));


        }
    }

    private string GetSelectMonthYear()
    {
        string _ReturnValue = string.Empty;
        string _Month = string.Empty;

        if (!string.IsNullOrEmpty(txtValue.Text))
        {
            string[] _strValue = txtValue.Text.Split(' ');

            switch (Convert.ToString(_strValue[0]).ToLower())
            {
                case "jan":
                    _Month = "01";
                    break;
                case "feb":
                    _Month = "02";
                    break;
                case "mar":
                    _Month = "03";
                    break;
                case "apr":
                    _Month = "04";
                    break;
                case "may":
                    _Month = "05";
                    break;
                case "jun":
                    _Month = "06";
                    break;
                case "jul":
                    _Month = "07";
                    break;
                case "aug":
                    _Month = "08";
                    break;
                case "sep":
                    _Month = "09";
                    break;
                case "oct":
                    _Month = "10";
                    break;
                case "nov":
                    _Month = "11";
                    break;
                case "dec":
                    _Month = "12";
                    break;
                default:
                    break;
            }
            if (!(string.IsNullOrEmpty(_Month) & string.IsNullOrEmpty(Convert.ToString(_strValue[1]))))
            {
                _ReturnValue = _Month + "," + Convert.ToString(_strValue[1]);
            }

        }
        return _ReturnValue;
    }

    private string GetMonth(int Month)
    {
        string _ReturnValue = string.Empty;
        switch (Month)
        {
            case 1:
                _ReturnValue = "Jan";
                break;
            case 2:
                _ReturnValue = "Feb";
                break;
            case 3:
                _ReturnValue = "Mar";
                break;
            case 4:
                _ReturnValue = "Apr";
                break;
            case 5:
                _ReturnValue = "May";
                break;
            case 6:
                _ReturnValue = "Jun";
                break;
            case 7:
                _ReturnValue = "Jul";
                break;
            case 8:
                _ReturnValue = "Aug";
                break;
            case 9:
                _ReturnValue = "Sep";
                break;
            case 10:
                _ReturnValue = "Oct";
                break;
            case 11:
                _ReturnValue = "Nov";
                break;
            case 12:
                _ReturnValue = "Dec";
                break;
            default:
                break;
        }
        return _ReturnValue;
    }

    protected void btnSelect_Click(object sender, EventArgs e)
    {
        pnlDate.Visible = !pnlDate.Visible;
        if (pnlDate.Visible)
        {
            ddlMonth.SelectedValue = DateTime.Now.Month.ToString();
            ddlYear.SelectedValue = DateTime.Now.Year.ToString();
        }
    }

    protected void btnSet_Click(object sender, EventArgs e)
    {
        txtValue.Text = ddlMonth.SelectedItem.Text + " " + ddlYear.SelectedValue;
        pnlDate.Visible = false;
    } 
Step 2. Create a Page where you want to place this control
  1. Right Click on the project and click on "Add New Item"
  2. Select Web Form and name it as "Default1.aspx" and click Add.
  3. Register you created User Control using below code above.
<%@ Register Src="~/UserControl/MonthYearPicker.ascx" TagName="MonthYearPicker" TagPrefix="myp" %>
4.    Now place below code into designer part of your Page.


    
    


    

Month Year


Show Value
5.    And Place the below code to Code Behind of Page.
protected void btnShow_Click(object sender, EventArgs e) 
    {
        Response.Write(mypMonthYear.Value);
    } 
That's it you are don't with your own Month Year Picker.

Reference: Muthukumar (http://nadarmuthukumar.blogspot.in)

Remove special characters from String

public static string RemoveSpecialCharacters(string str)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        for (int i = 0; i < str.Length; i++)
            if ((str[i] >= '0' && str[i] <= '9') || (str[i] >= 'A' && str[i] <= 'z' || (str[i] == '.' || str[i] == '_')))
                sb.Append(str[i]);
        return sb.ToString();
    }
Reference: Muthukumar (http://nadarmuthukumar.blogspot.in)

Twitter Delicious Facebook Digg Stumbleupon Favorites More