Monday 13 October 2014

Downloading files from server folder in C# on link button clicked Event which is inside GridView

     


              
 protected void lnk_attach4_Click(object sender, EventArgs e)
    {
        try
        {
            LinkButton _lnk = (LinkButton)sender;
            GridViewRow _row = (GridViewRow)_lnk.NamingContainer;
            int _i = Convert.ToInt32(_row.RowIndex);
            int _reqID = Convert.ToInt32(gv_hrmrequest.DataKeys[_i][0].ToString());

            string _LogPath = ConfigurationManager.AppSettings["Docs"].ToString();
            string _filename1 = _LogPath + _reqID + "_4_" + _lnk.Text;

            if (_lnk.Text != string.Empty)
            {
                if (_lnk.Text.EndsWith(".txt"))
                {
                    Response.ContentType = "application/txt";
                }
                else if (_lnk.Text.EndsWith(".pdf"))
                {
                    Response.ContentType = "application/pdf";
                }
                else if (_lnk.Text.EndsWith(".docx"))
                {
                    Response.ContentType = "application/docx";
                }
                else
                {
                    Response.ContentType = "image/jpg";
                }

                string filePath = _lnk.Text;

                Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filePath + "\"");
                Response.TransmitFile(_filename1);
                Response.End();
            }
        }
        catch (Exception ex)
        {

        }
        finally
        {

        }
    }

Monday 4 August 2014

Select / Dis select all the check boxes inside the Grid view using java script.


// javascript block



function SelectAll() {
            var gv = document.getElementById('<%=gv_orderdetails.ClientID%>');

            if (gv.rows[0].cells[5].getElementsByTagName("INPUT")[0].checked == true) {
                for (var i = 1 ; i < gv.rows.length; i++) {
                    gv.rows[i].cells[5].getElementsByTagName("INPUT")[0].checked = true;
                }
            }
            else {
                for (var i = 1 ; i < gv.rows.length; i++) {
                    gv.rows[i].cells[5].getElementsByTagName("INPUT")[0].checked = false;
                }
            }

        }

        function disselect()
        {
            var gv = document.getElementById('<%=gv_orderdetails.ClientID%>');

            var x = false;

            for (var i = 1 ; i < gv.rows.length-1; i++)
            {
                if (gv.rows[i].cells[5].getElementsByTagName("INPUT")[0].checked == true)
                {
                    x = true;
                }
                if (gv.rows[i].cells[5].getElementsByTagName("INPUT")[0].checked == false)
                {
                    x = false;
                    break;
                }

            }

            if (!x)
            {
                gv.rows[0].cells[5].getElementsByTagName("INPUT")[0].checked = false;
            }
            else
            {
                gv.rows[0].cells[5].getElementsByTagName("INPUT")[0].checked = true;
            }
        }




------------------------------------------------------------------

// In Design


             <asp:TemplateField HeaderStyle-Width="30px">
                    <HeaderTemplate>
                        <asp:CheckBox ID="chk_Headerselect" runat="server"                              onclick="Javascript:SelectAll();" />
                    </HeaderTemplate>
                    <ItemTemplate>
                        <asp:CheckBox ID="chk_select" runat="server"
  onclick="Javascript:disselect();"/>
                    </ItemTemplate>
                    <ItemStyle HorizontalAlign="Center" />
                    <HeaderStyle HorizontalAlign="Center" />
                </asp:TemplateField>






Sunday 3 August 2014

Creating New Outlook mail Item Using C#


using Microsoft.Office.Interop.Outlook;
using OutlookApp = Microsoft.Office.Interop.Outlook.Application;

-----------------------------------------------------------------------------


               OutlookApp outlookApp1 = new OutlookApp();
                MailItem _mi =(MailItem) outlookApp1.CreateItem(OlItemType.olMailItem);
                _mi.Subject = "This is the subject";
                _mi.To = "someone@example.com";
                _mi.Body = "This is the message.";
                _mi.Attachments.Add(@"C:/Users/Manjunath.le/Downloads/Annexure.pdf");
                _mi.Display(false);


// This will open New Outlook mail Create Window.

Wednesday 4 June 2014

Preventing user to select date greater than today in Ajax calender extender.

<script type="text/javascript">

function checkDate(sender, args) {
            if (sender._selectedDate > new Date()) {
                alert("You cannot select a day Greater than today!");
                sender._selectedDate = new Date();
                // set the date back to the current date
                sender._textbox.set_Value(sender._selectedDate.format(sender._format))
            }

</script>


Design:


  <asp:TextBox ID="txt_FDate" runat="server" Width="100px"></asp:TextBox>
                <img id="calendar_Img1" src="Images/calendar.gif" alt="Calendar" />
                <cc1:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txt_FDate"
                    CssClass="cal_Theme1" Format="yyyy-MM-dd" PopupButtonID="calendar_Img1" OnClientDateSelectionChanged="checkDate">
                </cc1:CalendarExtender>

Wednesday 28 May 2014

Getting Data table from the Excel Sheet Using C#

        string connectionString = "";
        bool flag = true;
        object value;
        try
        {

            string fileName = Path.GetFileName(fb_master.PostedFile.FileName);
            string fileExtension = Path.GetExtension(fb_master.PostedFile.FileName);
            string folder = ConfigurationManager.AppSettings["TargetFiles"];
            string fileLocation = ConfigurationManager.AppSettings["TargetFiles"]+System.DateTime.Today.ToString("dd-MMyyyy")+"_"+ fileName;
            DirectoryInfo dir = new DirectoryInfo(folder);
            if (!dir.Exists)
                dir.Create();

            fb_master.SaveAs(fileLocation);

            if (fb_master.HasFile)
            {
                //Check whether file extension is xls or xslx
                if (fileExtension == ".xls")
                {
                    connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
                }
                else if (fileExtension == ".xlsx")
                {
                    //connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\"";
                    connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
                }

                //Create OleDB Connection and OleDb Command
                OleDbConnection con = new OleDbConnection(connectionString);
                OleDbCommand cmd = new OleDbCommand();
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.Connection = con;
                OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
                DataTable dtExcelRecords = new DataTable();
                con.Open();
                DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
                cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "] where Finyear is not null ";
                dAdapter.SelectCommand = cmd;
                dAdapter.Fill(dtExcelRecords);
                con.Close();
          }

        }
        catch (Exception ex)
        {
            UserMessage.ShowUserMessage("Excel file cannot be uploaded.please check the data in Excel file.It may contains Null values.");
            _gb.ErrorLog(ex.Message);
        }

Tuesday 8 April 2014

Avoiding special characters in C# using javascript

 function isNumber(evt)
       {
                   evt = (evt) ? evt : window.event;
                   var charCode = (evt.which) ? evt.which : evt.keyCode;
                   if (charCode > 59 && charCode < 64)     // here m checking for < > ? characters only
                  {
                      return false;
                   }
                   return true;
        }


// Call this javascript function onkeypress event of the text box like -   onkeypress="return isNumber(event)"


Thursday 20 February 2014

If any design issues in internet explorer because of version level , add the below code in Web.config

      <system.webServer>
    <httpProtocol>
      <customHeaders>
        <clear/>
   <!--This setting will make document mode to highest mode available we need have mode 8 and above-->
       <add name="X-UA-Compatible" value="IE=Edge"/>
      </customHeaders>
    </httpProtocol>
  </system.webServer>


Simple things effects a lot ... happy coding.........

Tuesday 18 February 2014

Example for delegate in C# - here i will show how to call the child page button click on clicking the button which is inside user control of the parent page

In User Control lets name like horizantalmenu.ascx, i will define the event handler and i will use it in the particular button click event



 public event EventHandler ButtonClickDemo;   // define it globally

protected void Page_Load(object sender, EventArgs e)
 {
   
 }


protected void Button_Click(object sender, ImageClickEventArgs e)
    {
        ButtonClickDemo(sender, e);    // m using the event here
    }


--------------------------------------------------------------------------------------------------

In all the successive pages where you are calling  horizantalmenu.ascx in your page ,

trigger that event in the page load of your page

protected void Page_Load(object sender, EventArgs e)
    {
        HorizontalMenu.ButtonClickDemo += new EventHandler(GetMainQueryOnNotepad);
                                                                             // assigning with one function to call on button click
    }


 protected void GetMainQueryOnNotepad(object sender, EventArgs e)
    {
           /// you can do what ever you want to do in this function.
    }


Thursday 6 February 2014

Creating simple error log in Asp.net / C#

 public void ErrorLog(string sMessage)
    {
     
        string LogPath = ConfigurationManager.AppSettings["ErrorlagPath"].ToString();
        string filename = "ErrorLog_" + DateTime.Now.ToString("dd-MM-yyyy") + ".txt";
        string filepath = LogPath + filename;

        if (!Directory.Exists(LogPath))
            Directory.CreateDirectory(LogPath);
        string sFilePath = filepath;

        StreamWriter objSw = new StreamWriter(sFilePath, true);
        objSw.WriteLine("-------------------START-------------" + DateTime.Now + " -----------------");
        objSw.WriteLine(sMessage);
        objSw.WriteLine("-------------------END-------------" + DateTime.Now + " -----------------");
        objSw.Close();
    }

Tuesday 7 January 2014

Sql server Date formats

WHEN 'mmm dd yyyy hh:mm AM/PM' THEN 100
WHEN 'mm/dd/yy' THEN 1
WHEN 'mm/dd/yyyy' THEN 101
WHEN 'yy.mm.dd' THEN 2
WHEN 'dd/mm/yy' THEN 3
WHEN 'dd.mm.yy' THEN 4
WHEN 'dd-mm-yy' THEN 5
WHEN 'dd Mmm yy' THEN 6
WHEN 'Mmm dd, yy' THEN 7
WHEN 'hh:mm:ss' THEN 8
WHEN 'yyyy.mm.dd' THEN 102
WHEN 'dd/mm/yyyy' THEN 103
WHEN 'dd.mm.yyyy' THEN 104
WHEN 'dd-mm-yyyy' THEN 105
WHEN 'dd Mmm yyyy' THEN 106
WHEN 'Mmm dd, yyyy' THEN 107
WHEN 'Mmm dd yyyy hh:mm:ss:ms AM/PM' THEN 9
WHEN 'Mmm dd yyyy hh:mi:ss:mmm AM/PM' THEN 9
WHEN 'Mmm dd yy hh:mm:ss:ms AM/PM' THEN 109
WHEN 'mm-dd-yy' THEN 10
WHEN 'mm-dd-yyyy' THEN 110
WHEN 'yy/mm/dd' THEN 11
WHEN 'yyyy/mm/dd' THEN 111
WHEN 'yymmdd' THEN 12
WHEN 'yyyymmdd' THEN 112
WHEN 'dd Mmm yyyy hh:mm:ss:Ms' THEN 113
WHEN 'hh:mm:ss:Ms' THEN 14
WHEN 'yyyy-mm-dd hh:mm:ss' THEN 120
WHEN 'yyyy-mm-dd hh:mm:ss.Ms' THEN 121
WHEN 'yyyy-mm-ddThh:mm:ss.Ms' THEN 126
WHEN 'dd Mmm yyyy hh:mm:ss:ms AM/PM' THEN 130
WHEN 'dd/mm/yy hh:mm:ss:ms AM/PM' THEN 131
WHEN 'RFC822' THEN 2
WHEN 'dd Mmm yyyy hh:mm' THEN 4