Retrieve CheckboxList selected value by JAVASCRIPT

This code is help full to retrieve checkboxlist’s (asp.net server side control) selected value in JavaScript.

Below are the Java script function for that, if there are at least one of the value selected then its return true else that will return as false.

function CheckCheckBoxSelected() {

var options = document.getElementById('');

for (i = 0; i < options.cells.length; i++) {
var opt = options.cells[i];

if (opt.childNodes[0].checked) {
return true;
}
}
return false;
}

Here ChkActions is my Check box list ID. We can modify this function as per requirement but this is base concept of how to retrieve check box list controls value in JavaScript.

Thanks,
Amit Patel
“Happy Programming”

About these ads

Sent Mail C# code by Template

Below article is use full for sent a mail functionality from template, In real scenario in web application we have to send multiple mails to different operation from system and they all have different contents.

This article contains below things.

  • Sent mail
  • Mail content pick from template
  • Add Dynamic parameter in mail contents.
  • So I have implemented common class with that class use few required parameter and based on that we can sent a mail as per contents provided in temperate.

      Store email Template:

    For simple and common method, we are storing html email template file in text file in any specific folder in application directory
    Add Dynamic Value in Template:

    Mail template never be static contents there is always a dynamic data like stack holder name or data from database.

    So that in template we are storing that contents as {0},{1}……. And original value we are passed in list collection in that class and inside the class that is handle this part.

    Below is the class for Sent mail.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net.Mail;
    using System.IO;
    using System.Text;

    namespace Library
    {
    public class SentMail
    {
    public SentMail()
    {
    }
    private string _SMTPAddress;
    public string SMTPAddress
    {
    get
    {
    if(string.IsNullOrEmpty(_SMTPAddress))
    return System.Configuration.ConfigurationSettings.AppSettings["SMTPSERVER"].ToString();
    else
    return _SMTPAddress;
    }
    set
    {
    _SMTPAddress = value;
    }
    }
    private string _FromDisplayName;
    public string FromDisplayName
    {
    get
    {
    if (string.IsNullOrEmpty(_SMTPAddress))
    return System.Configuration.ConfigurationSettings.AppSettings["FROMDISPLAY"].ToString();
    else
    return _FromDisplayName;
    }
    set
    {
    _FromDisplayName = value;
    }
    }
    private string _FromAddress;
    public string FromAddress
    {
    get
    {
    if (string.IsNullOrEmpty(_SMTPAddress))
    return System.Configuration.ConfigurationSettings.AppSettings["FROMADDRESS"].ToString();
    else
    return _FromAddress;
    }
    set
    {
    _FromAddress = value;
    }
    }
    ///

    /// To Address if multiple then add ; in between each address
    ///

    public string ToDisplayName { get; set; }
    public string ToAddress { get; set; }
    ///

    /// CC Address if multiple then add ; in between each address
    ///

    public string CCAddress { get; set; }
    ///

    /// BCC Address if multiple then add ; in between each address
    ///

    public string BCCAddress { get; set; }
    public string Body { get; set; }
    public string Subject { get; set; }
    public List SubjectParameter { get; set; }
    public List Attachment { get; set; }
    public bool HighPriority { get; set; }
    public List DynamicParameter { get; set; }
    public string TemplateFile { get; set; }

    public bool Sent()
    {
    bool bReturn = true;
    try
    {
    SmtpClient oSMTLClient = new SmtpClient();
    oSMTLClient.Host = this.SMTPAddress;

    MailMessage message = new MailMessage();
    message.From = new MailAddress(this.FromAddress, this.FromDisplayName);
    if (!string.IsNullOrEmpty(this.ToAddress))
    {
    string[] ToAddress = this.ToAddress.Trim().Split(";".ToCharArray());
    foreach (string itemTo in ToAddress)
    {
    message.To.Add(itemTo);
    }
    }
    // CC address
    if (!string.IsNullOrEmpty(this.CCAddress))
    {
    string[] CCAddress = this.CCAddress.Trim().Split(";".ToCharArray());
    foreach (string itemCC in CCAddress)
    {
    message.CC.Add(itemCC);
    }
    }
    // BCC address
    if (!string.IsNullOrEmpty(this.BCCAddress))
    {
    string[] BCCAddress = this.BCCAddress.Trim().Split(";".ToCharArray());
    foreach (string itemBCC in BCCAddress)
    {
    message.Bcc.Add(itemBCC);
    }
    }

    message.Body = string.Format(this.MailBodystring(), this.DynamicParameter.ToArray());
    message.IsBodyHtml=true;
    if (this.HighPriority)
    {
    message.Priority = MailPriority.High;
    }

    if (this.Attachment != null && this.Attachment.Count > 0)
    {
    // Attachment code
    }

    message.Subject = string.Format(this.Subject, this.SubjectParameter.ToArray());
    oSMTLClient.Send(message);
    bReturn = true;
    }
    catch (Exception ex)
    {
    bReturn = false;
    }

    return bReturn;

    //message.CC = this.CCAddress

    }
    private string MailBodystring()
    {
    string MailBody = "";
    if (File.Exists(this.TemplateFile))
    {
    StreamReader SR = new StreamReader(this.TemplateFile);
    MailBody = SR.ReadToEnd();
    SR.Close();
    SR.Dispose();
    }
    return MailBody;
    }
    }
    }

    Below is the code for how to use this class.

    SentMail oMail = new SentMail();
    oMail.SMTPAddress = "mail.myserver.com";// if not provide that consider value from web.config
    oMail.FromAddress = "amit.patel@myserver.com";// if not provide that consider value from web.config

    oMail.DynamicParameter = new List { "Amit Patel", "5P Admin" };
    oMail.SubjectParameter = new List { "Amit Patel" };
    oMail.FromDisplayName = "Amit Patel";// if not provide that consider value from web.config

    oMail.HighPriority=false;
    oMail.ToAddress = "amit.patel@myserver.com";
    oMail.Subject = "Leave Application for : {0}";
    oMail.TemplateFile = Server.MapPath("HTMLPage.txt");
    oMail.Sent();

    Thanks,
    Amit Patel
    Happy Programming :)

    Create Autogenerated Number

    Below are the code is use full when we want to create our username , order no or invoice no by automatically by sytem with predefine pattern and that must be unique based on sequentially.
    Here in this code I have used few part as static and few part as dynamically (based on auto identity).
    Like “ORD-YYYY-0004’

    So here ORD is static and YYYY current years but 0004 is number hence that is next identity number from table where I have added 3 zero as prefix that can be 3,2 or 1 so that is give minimum 4 digit number if id increased then it can be increased like 10001.
    Below are the SQL code for that..

    GO
    /****** Object: StoredProcedure [dbo].[OrderNo] Script Date: 04/06/2011 14:15:54 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    -- =============================================
    -- Author: Amit
    -- Create date: 25-Feb-2011
    -- Description: Generate OrderNo
    --exec OrderNo

    -- =============================================
    ALTER PROCEDURE [dbo].[OrderNo]
    AS
    BEGIN
    DECLARE @OrderNoAS varchar(25)
    DECLARE @ComapyCode AS varchar(5)
    set @ComapyCode='ORDCUST'
    DECLARE @INVOICEid AS BIGINT
    DECLARE @STARTDATE AS DATETIME
    DECLARE @ENDDATE AS DATETIME

    DECLARE @Year1 int
    DECLARE @Year2 int

    if(MONTH(Getdate()) <=3)
    BEGIN
    SET @Year1 = Year(Getdate())-1
    SET @Year2 = Year(Getdate())
    END
    ELSE
    BEGIN
    SET @Year1 = Year(Getdate())
    SET @Year2 = Year(Getdate())+1
    END
    print @Year1
    SET @STARTDATE = cast('04-01-' + CAST(@Year1 AS VARCHAR(4)) as DATETIME)
    SET @ENDDATE = cast('03-31-' + CAST(@Year2 AS VARCHAR(4)) as DATETIME)

    SELECT @INVOICEid = MAX(iNVOICEid)+1 FROM DBO.Invoices AS Inv WHERE Inv.InvoiceDate between @STARTDATE and @ENDDATE
    set @INVOICEid = ISNULL(@INVOICEid,1)
    Set @OrderNo= CAST(@INVOICEid as varchar(10));
    While(LEN(@OrderNo) = 4)
    BEGIN
    break;
    END
    ELSE
    BEGIN
    set @OrderNo= '0' + @OrderNo;
    END

    END

    set @OrderNo= @ComapyCode + '/' + @OrderNo+ '/' + CAST(@Year1 as varchar(10)) + '-' + CAST(@Year2 as varchar(10))

    SELECT @OrderNo
    END

    Error Handling Mechanisms in ASP.NET Application

    In ASP.NET application we need to consider below factors while creating error handling ability in system

  • Show User friendly message in UI
  • Log all detail level error
  • Log error process should be very simple and generic so there are minimum chances of the error comes in log generation
    process and that should be easy to accessible to each user.
    i.e. if we are storing login in database and error comes related to database connectivity then we never get any kind of logs and also that is difficult to retrieve that log
  • Show User Friendly message in UI:

    Add below tags in your web.config file

    Also need to add Errorpage.aspx and pagenotfound.aspx(if required) with user friendly messages.

    Log all detail level error

    For maintain each error log we need to add below code in global.asax page in Application_Error event.

    void Application_Error(object sender, EventArgs e)
    {
    Exception ex = Server.GetLastError().GetBaseException();
    string PageUrl = Request.Url.ToString();

    string strLogFile = Server.MapPath(@"~\ErrorLog\LogFile_" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + ".txt");
    ErrorHnadling.ErrorHandling(ex, strLogFile, Request.Form.ToString(), PageUrl);
    }

    So when ever error occurs this event fires and error is logged.

    Error Log Process
    We have implemented error log process in Errorhadling class with errorhandling methods with all error details.
    We are storing error in text file with predefine web root folder with todays date as naming convention so any time user can access that file data by browsing it by web directory (with predefine name by date)

    Below are the class for error handling.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Diagnostics;
    using System.IO;
    /* Created By : Amit Patel
    * Created Date : 21th Feb 2011
    * Description : Error Handling for application level
    */
    namespace Common
    {
    public class ErrorHnadling
    {
    ///

    /// Log Exception Log file (log file is maintain based on Date
    ///

    /// Exception Message
    /// Log File
    /// Request Form name
    /// Query String Name
    public static void ErrorHandling(Exception ex, string strLogFile, string strFormName, string strQueryString)
    {

    StreamWriter oSW;
    if (File.Exists(strLogFile))
    {
    oSW = new StreamWriter(strLogFile, true);
    }
    else
    {
    oSW = File.CreateText(strLogFile);
    }

    oSW.WriteLine("================================" + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString() + "================================");
    oSW.WriteLine("MESSAGE : " + ex.Message);
    oSW.WriteLine("SOURCE : " + ex.Source);
    oSW.WriteLine("TARGETSITE : " + ex.TargetSite);
    oSW.WriteLine("STACKTRACE : " + ex.StackTrace);
    oSW.WriteLine("INNEREXCEPTION : " + ex.InnerException);
    oSW.WriteLine("FORM : " + strFormName);
    oSW.WriteLine("QUERYSTRING : " + strQueryString);
    oSW.Close();
    }
    ///

    /// Log Exception Log file (log file is maintain based on Date
    ///

    /// Exception Message
    /// Log File
    /// Request Form name
    /// Query String Name
    /// Data for Error Handling (user id or any other session variable
    public static void ErrorHandling(Exception ex, string strLogFile, string strFormName, string strQueryString, string strData)
    {

    StreamWriter oSW;
    if (File.Exists(strLogFile))
    {
    oSW = new StreamWriter(strLogFile, true);
    }
    else
    {
    oSW = File.CreateText(strLogFile);
    }

    oSW.WriteLine("================================" + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString() + "================================");
    oSW.WriteLine("MESSAGE : " + ex.Message);
    oSW.WriteLine("SOURCE : " + ex.Source);
    oSW.WriteLine("TARGETSITE : " + ex.TargetSite);
    oSW.WriteLine("STACKTRACE : " + ex.StackTrace);
    oSW.WriteLine("INNEREXCEPTION : " + ex.InnerException);
    oSW.WriteLine("FORM : " + strFormName);
    oSW.WriteLine("QUERYSTRING : " + strQueryString);
    oSW.WriteLine("Data : " + strData);
    oSW.Close();
    }
    }
    }

    Also we have added another method to capture application/session related data. That will help if any specific error comes on special data or specific user.

    Hope you will enjoy with code to trace any error in production application.

    Follow

    Get every new post delivered to your Inbox.

    Join 238 other followers