Total Pageviews

Thursday, June 25, 2009

Selecting All CheckBoxes in GridView

<script type=”text/javascript”> var TotalChkBx; var Counter; window.onload = function() { //Get total no. of CheckBoxes in side the GridView. TotalChkBx = parseInt(’<%= this.gvCheckboxes.Rows.Count %>’); //Get total no. of checked CheckBoxes in side the GridView. Counter = 0; } function HeaderClick(CheckBox) { //Get target base & child control. var TargetBaseControl = document.getElementById(’<%= this.gvCheckboxes.ClientID %>’); var TargetChildControl = “chkBxSelect”; //Get all the control of the type INPUT in the base control. var Inputs = TargetBaseControl.getElementsByTagName(”input”); //Checked/Unchecked all the checkBoxes in side the GridView. for(var n = 0; n < Inputs.length; ++n) if(Inputs[n].type == ‘checkbox’ && Inputs[n].id.indexOf(TargetChildControl,0) >= 0) Inputs[n].checked = CheckBox.checked; //Reset Counter Counter = CheckBox.checked ? TotalChkBx : 0; } function ChildClick(CheckBox, HCheckBox) { //get target base & child control. var HeaderCheckBox = document.getElementById(HCheckBox); //Modifiy Counter; if(CheckBox.checked && Counter < TotalChkBx) Counter++; else if(Counter > 0) Counter–; //Change state of the header CheckBox. if(Counter < TotalChkBx) HeaderCheckBox.checked = false; else if(Counter == TotalChkBx) HeaderCheckBox.checked = true; } </script> <asp:GridView ID=”gvCheckboxes” runat=”server” AutoGenerateColumns=”False” OnRowCreated=”gvCheckboxes_RowCreated”> <Columns> <asp:BoundField HeaderText=”S.N.” DataField=”sno”> <HeaderStyle HorizontalAlign=”Center” VerticalAlign=”Middle” Width=”50px” /> <ItemStyle HorizontalAlign=”Center” VerticalAlign=”Middle” Width=”50px” /> </asp:BoundField> <asp:TemplateField HeaderText=”Select”> <ItemTemplate> <asp:CheckBox ID=”chkBxSelect” runat=”server” /> </ItemTemplate> <HeaderStyle HorizontalAlign=”Center” VerticalAlign=”Middle” Width=”50px” /> <ItemStyle HorizontalAlign=”Center” VerticalAlign=”Middle” Width=”50px” /> <HeaderTemplate> <asp:CheckBox ID=”chkBxHeader” onclick=”javascript:HeaderClick(this);” runat=”server” /> </HeaderTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <asp:CheckBox ID=”chkBx” runat=”server” /> </ItemTemplate> <ItemStyle HorizontalAlign=”Center” VerticalAlign=”Middle” Width=”50px” /> </asp:TemplateField> </Columns> <RowStyle BackColor=”Moccasin” /> <AlternatingRowStyle BackColor=”NavajoWhite” /> <HeaderStyle BackColor=”DarkOrange” Font-Bold=”True” ForeColor=”White” /> </asp:GridView> protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindGridView(); } } protected void BindGridView() { gvCheckboxes.DataSource = GetDataSource(); gvCheckboxes.DataBind(); } protected DataTable GetDataSource() { DataTable dTable = new DataTable(); DataRow dRow = null; Random rnd = new Random(); dTable.Columns.Add(”sno”); for (int n = 0; n < 10; ++n) { dRow = dTable.NewRow(); dRow["sno"] = n + “.”; dTable.Rows.Add(dRow); dTable.AcceptChanges(); } return dTable; } protected void gvCheckboxes_RowCreated(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)) { CheckBox chkBxSelect = (CheckBox)e.Row.Cells[1].FindControl(”chkBxSelect”); CheckBox chkBxHeader = (CheckBox)this.gvCheckboxes.HeaderRow.FindControl(”chkBxHeader”); chkBxSelect.Attributes["onclick"] = string.Format(”javascript:ChildClick(this,’{0}’);”, chkBxHeader.ClientID); } }

Displaying Alert Message Boxes from your .aspx page

Step 1 : Create a General class and place the following Code in it

public static void CreateMessageAlert(System.Web.UI.Page senderPage, string alertMsg, string alertKey) { ScriptManager.RegisterStartupScript(senderPage, senderPage.GetType(), alertKey, “alert(’” + alertMsg + “‘);”,true); }

Step 2 : Call the created method from where ever you wish to send the alert from

string alertmessage = “Thank You for visiting MySite.Com”;

YourClassName.CreateMessageAlert(this,alertmessage,”alertKey”);

Where YourClassName is nothing but the name of the class file where your CreateMessageAlert method resides and alertmessage is where you assign the string you wish to display.

Friday, June 19, 2009

Send Email with Inline Images & Attachments

When sending an email from an ASP.NET 2.0 page you will, typically: 1. Create a MailMessage object 2. Assign its properties 3. Create an instance of the SmtpClient class 4. Specify details about the SMTP server to use (if they’re not already specified within Web.config) 5. Send the MailMessage via the SmtpClient object’s Send method ASP.NET makes it easy to utilise e-mail in an application with the System.Web.Mail namespace. Let’s take a closer look at putting this namespace to work in your applications. MailAttachment class The basic approach is the creation of a MailMessage object followed by sending it on its way via a SmtpMail object. The MailMessage class contains numerous methods and properties for working with an e-mail message. Properties such as From, Subject, and Body provide everything you need to create an e-mail message, but a SmtpMail object is still necessary for sending it on its way. SmtpMail class The SmtpMail class includes the SmtpServer property that gets or sets the name of the SMTP relay mail server to use to send messages, and the Send method actually sends the message. The Send method is overloaded. It allows a message to send using two approaches: 1. A MailMessage object is passed to the SmtpServer object. Four string objects may be passed to the SmtpServer object with the first being the From field followed by the Recipient, Subject, and the message’s Body. 2. You’ll use the MailAttachment and SmtpMail classes together to create the necessary messages in your application, but make sure the Web server is properly configured to send a message via SMTP. Since IIS (Internet Information Services) is the most popular platform for ASP.NET applications, go ahead and use both the IIS and SMTP services to send messages from your application.

Using SMTP with IIS

You can set up both IIS and SMTP services via the Windows control panel. The SMTP service’s role is to accept and deliver the messages using the server’s configuration. It may deliver the messages directly, or utilise a smart host to deliver the message instead. When a smart host is enlisted, all messages are forwarded to it for delivery.

A little more information is appropriate for debugging. The SMTP service uses a directory structure to contain messages prior to delivery with the default directory being C:\Inetpub\mailroot. It contains numerous subdirectories including Queue, Drop, and Badmail. If you’re unable to configure your instance of the SMTP Service for delivery, you can find the message in an EML file in the Queue subdirectory. The Badmail directory contains messages that that couldn’t be delivered. Now, let’s take a look at sending mail messages from your code.

Sending e-mail messages

To compose an e-mail message in your code, you need to start by creating an instance of the MailMessage class, as shown in the following C# snippet:

MailMessage msg = new MailMessage();

Be sure to include the System.Web.Mail namespace in your code:

using System.Web.Mail;

Once the object is instantiated, the various properties of the MailMessage class are used per your application. The following lines set the recipient, sender, and subject of the message:

msg.To = “test@test.com”; msg.From = “me@test.com”; msg.Subject = “Test Message”;

The next step is setting our mail server via the SmtpServer object’s SmtpServer property:

SmtpMail.SmtpServer = “smtp server name or address”;

The final step is sending the message by passing our MailMessage object to the SmtpMail object’s Send method:

SmtpMail.Send(msg);

Here I am Providing you the Complete Example of how to send Email with Inline Image / Multiple Attachments …etc…

—————————————- Button Event Code —————————————-

protected void Button1_Click(object sender, EventArgs e) { string from = “”, to = “”, cc = “”, subject = “”, body = “”, attachedfiles = “”;

from = “yogesh@gmail.com”; to = “yrb.yogi@gmail.com;bhadauriya.yogesh@gmail.com”; // multiple entry are separated bt ‘;’ cc = “yrb.yogigmail.com”; subject = “Testing Email Module”;

//Read Mail Template StreamReader sr; StringBuilder sb = new StringBuilder(); string BodyOfMail = “”; sr = File.OpenText(Server.MapPath(”~/MailTemplate.txt”)); sb.Append(sr.ReadToEnd()); body = sb.ToString();

//attachments attachedfiles = “E:\\Images\\1.jpg;E:\\Images\\2.jpg;”; emailClass.SendEmail(from, to, cc, subject, body, attachedfiles); }

—————————————- MailTemplate.txt —————————————-

<title>Untitled Document</title> </head> <body> <form id=”form1″ name=”form1″ method=”post” action=”"> <table width=”100%” border=”0″ cellspacing=”10″ cellpadding=”10″> <tr> <td bgcolor=”#FFFFFF”> <br /> <table width=”550″ border=”0″ cellpadding=”2″ cellspacing=”0″ bordercolor=”#FFFFFF” id=”Comment Table2″> <tr> <td > Hello Friend Name,<br /> <br /> Your friend has been send you this offer. <br /> </td> </tr> <tr> <td align=”right”> <table width=”530″ border=”0″ cellpadding=”0″ cellspacing=”0″> <tr> <td > <img src=”{images/logo1.jpg” /> </td> <td > <img src=”{images/logo2.jpg” /> </td> </tr> </table> </td> </tr> </table> </td> </tr> </table> </form> </body> </html>

—————————————- emailClass Class —————————————-

using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Net.Mail; using System.Net;

///

/// Summary description for emailClass /// public class emailClass { public emailClass() { // // TODO: Add constructor logic here // } public static void SendEmail(string from, string to, string cc, string subject, string body, string attachedFiles) { try { MailMessage mailMsg = new MailMessage(); SmtpClient mailObj = new SmtpClient(”server”, 25);//”192.168.0.17″ – SmtpClient

//to authenticate we set the username and password properites on the SmtpClient mailObj.Credentials = new NetworkCredential(”yogesh@gmail.com”, “password”);

mailMsg.From = new MailAddress(from);

string[] temp = to.Split(’;'); for (int i = 0; i <> 1) mailMsg.To.Add(temp[i].ToString()); }

temp = cc.Split(’;'); for (int i = 0; i <> 1) mailMsg.CC.Add(temp[i].ToString()); } temp = attachedFiles.Split(’;'); for (int i = 0; i <> 1) mailMsg.Attachments.Add(new Attachment(temp[i].ToString())); }

mailMsg.Subject = subject; mailMsg.Body = body; mailMsg.IsBodyHtml = true; int count = 0; string oldChar = ExtractImages(body, ref count); Random RGen = new Random(); while (oldChar != “”) { string imgPath = oldChar; int startIndex = imgPath.ToLower().IndexOf(”images/”); if (startIndex > 0) { imgPath = imgPath.Substring(startIndex); imgPath = imgPath.Replace(”/”, “\\”); System.Net.Mail.Attachment A = new Attachment(HttpContext.Current.Request.PhysicalApplicationPath + “\\” + imgPath); A.ContentId = RGen.Next(100000, 9999999).ToString(); body = body.Replace(oldChar, “cid:” + A.ContentId); mailMsg.Attachments.Add(A); oldChar = ExtractImages(body, ref count); } else { oldChar = ExtractImages(body, ref count); } } mailMsg.Body = body; mailObj.Send(mailMsg); } catch (Exception ex) { System.Web.HttpContext.Current.Response.Write(ex.Message); } }

private static string ExtractImages(string body, ref int count) { int startIndex = body.ToLower().IndexOf(”= 0) { endIndex = body.IndexOf(”\”", startIndex + 10); } else { return “”; } startIndex = startIndex + 10; string imgurl = body.Substring(startIndex, (endIndex – (startIndex))); count = startIndex; return imgurl; } }

Thursday, June 4, 2009

Split Values in My Sql with using store procedure

Hello, here i m going to describe the split value function /Store procedure in mysql....

suppose i want to pass mulitple id as '12,113,14,15,10' than how can i separate.... the solution is below....use below store procedure to separate each id's

DELIMITER $$  
DROP PROCEDURE IF EXISTS `ecommerce`.`SplitValue`$$  
CREATE  PROCEDURE `SplitValue`
(    
    input VARCHAR(8000),    
    delim VARCHAR(10),    
    Ids VARCHAR(36) 
) 
BEGIN 
DECLARE foundPos TINYINT UNSIGNED; 
DECLARE tmpTxt TEXT; 
DECLARE delimLen TINYINT UNSIGNED; 
DECLARE element TEXT; 
DROP TEMPORARY TABLE IF EXISTS tmpValues;  
CREATE TEMPORARY TABLE tmpValues 
(    
    valuess DECIMAL(18,0) NOT NULL DEFAULT 0,    
    Id VARCHAR(36) 
) 
ENGINE = MEMORY; 

SET delimLen = LENGTH(delim); 
SET tmpTxt = input; 
SET foundPos = INSTR(tmpTxt,delim); 

WHILE foundPos <> 0 
DO    
    SET element = SUBSTRING(tmpTxt, 1, foundPos-1);    
    SET tmpTxt = REPLACE(tmpTxt, CONCAT(element,delim), '');    
    SET element=CAST(element AS DECIMAL(18,0));    
    INSERT INTO tmpValues (valuess,Id) VALUES ( element,Ids);    
    SET foundPos = INSTR(tmpTxt,delim);   
END WHILE; 
IF tmpTxt <> '' 
THEN    
    SET tmpTxt=CAST(tmpTxt AS DECIMAL(18,0));    
    INSERT INTO tmpValues (valuess,Id)    
    VALUES (tmpTxt,Ids); 
END IF;  
SELECT Id,valuess FROM tmpValues;  
END$$  DELIMITER ;   
   

suppose i m calling this store procedure as

CALL SplitValue('11,12,13,14,15') 

-- then the oputput of this 
-- id VALUE 
-- 1  11 
-- 2  12 
-- 3  13 
-- 4  14 
-- 5  15

Friday, May 29, 2009

Custom Paging in GridView without Object Data Source

All we need to use the Custom paging in grid view without object data source.

Here i am going to explain my code which is used in custom paging of grid view... What you will need to do is used your DataSource SP or query with this paging...

All magic lies in SQL Server 2005 ROWNumber() Function.... Simple SP for this gridview datasource is


Select Row,ID,Name
(
    Select ROW_Number()OVER(ORDER BY ID) As Row,ID,Name 
    from table1
) AS A
Where Row=>@PageIndex*PageSize
and Row<(@PageIndex+1)*PageSize;
--here @PageIndex and @PageSize are passed as parameter as gridview1.PageIndex and gridview1.PageSize  
    

if you are not familiar with RowNumber function than create one temp table use Row as primary key with auto increament number and than use insert select statement.... this will work in all database.....

Follow is the C# code for custom gridview...I m creating new grid view control here

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Text; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls;  
namespace CustomPagingGridView 
{  
    [DefaultProperty("Text")]  
    [ToolboxData("<{0}:CustomePagingGrid runat=server>CustomePagingGrid>")]  
    public class CustomePagingGrid : GridView 
    {   
        public CustomePagingGrid(): base()
        {}
        
        #region Custom properties       
        // this property is to use to find the total number of record for grid         
        [Browsable(true), Category("NewDynamic")]         
        [Description("Set the virtual item count for this grid")]         
        public int VirtualItemCount         
        {             
            get
            {
                if (ViewState["pgv_vitemcount"] == null)
                    ViewState["pgv_vitemcount"] = -1;                 
                return Convert.ToInt32(ViewState["pgv_vitemcount"]);             
            }             
            set             
            {                 
                ViewState["pgv_vitemcount"] = value;             
            }         
        }         
        
        // this is used to sort the gridview columns        
        [Browsable(true), Category("NewDynamic")] [Description("Get the order by string to use for this grid when sorting event is triggered")] 
        public string OrderBy         
        {             
            get             
            {                 
                if (ViewState["pgv_orderby"] == null)                     
                    ViewState["pgv_orderby"] = string.Empty;                 
                return ViewState["pgv_orderby"].ToString();             
            }             
            protected set             
            {                 
                ViewState["pgv_orderby"] = value;             
            }         
        }            
        
        private int Index         
        {             
            get             
            {                 
                if (ViewState["pgv_index"] == null)                     
                    ViewState["pgv_index"] = 0;                 
                return Convert.ToInt32(ViewState["pgv_index"]);             
            }             
            set             
            {                 
                ViewState["pgv_index"] = value;             
            }         
        }            
        
        public int CurrentPageIndex         
        {             
            get             
            {                 
                if (ViewState["pgv_pageindex"] == null)                     
                    ViewState["pgv_pageindex"] = 0;                 
                return Convert.ToInt32(ViewState["pgv_pageindex"]);             
            }             
            set             
            {                 
                ViewState["pgv_pageindex"] = value;             
            }         
        }            
        
        private int SetCurrentIndex         
        {             
            get             
            {                 
                return CurrentPageIndex;             
            }             
            set             
            {                 
                CurrentPageIndex = value;             
            }         
        }                 
        
        
        // if this property is set to greater than zero means custom paging neede                    
        private bool CustomPaging         
        {             
            get             
            {                 
                return (VirtualItemCount != -1);             
            }         
        }          
        #endregion             
        
        #region Overriding the parent methods           
        public override object DataSource         
        {             
            get             
            {                 
                return base.DataSource;             
            }             
            set             
            {                 
                base.DataSource = value;                 
                // we store the page index here so we dont lost it in databind                 
                CurrentPageIndex = PageIndex;             
            }         
        }     
        
        protected override void OnSorting(GridViewSortEventArgs e) 
        { 
            // We store the direction for each field so that we can work out whether next sort 
            // should be asc or desc order  PageIndex = CurrentPageIndex; SortDirection direction = SortDirection.Ascending;  
            if(ViewState[e.SortExpression]!=null&& (SortDirection)ViewState[e.SortExpression] == SortDirection.Ascending)  
            {   
                direction = SortDirection.Descending; 
            }  
            ViewState[e.SortExpression] = direction;             
            OrderBy = string.Format("{0} {1}", e.SortExpression, (direction == SortDirection.Descending ? "DESC" : ""));             
            base.OnSorting(e);         
        }            
        
        protected override void InitializePager(GridViewRow row, int columnSpan, PagedDataSource pagedDataSource)         
        {             
            // This method is called to initialise the pager on the grid. We intercepted this and override             
            // the values of pagedDataSource to achieve the custom paging using the default pager supplied             
            if (CustomPaging)             
            {                 
                pagedDataSource.AllowCustomPaging = true;                 
                pagedDataSource.VirtualCount = VirtualItemCount;                 
                pagedDataSource.CurrentPageIndex = CurrentPageIndex;             
            }             
            base.InitializePager(row, columnSpan, pagedDataSource);         
        }               
        
        // here we do custom paging         
        protected override void OnPageIndexChanging(GridViewPageEventArgs e)         
        {             
            if (CustomPaging)             
            {                 
                if (this.PagerSettings.Mode == PagerButtons.NumericFirstLast || this.PagerSettings.Mode == PagerButtons.Numeric)                 
                {                     
                    base.OnPageIndexChanging(e);                 
                }                 
                else                 
                {                     
                    if (e.NewPageIndex == -1)                     
                    {                         
                        Index -= 1;                     
                    }                     
                    else if (e.NewPageIndex == 0)
                    {                         
                        Index = 0;                     
                    }                     
                    else if (e.NewPageIndex == ((int)Math.Ceiling((decimal)(VirtualItemCount) / PageSize) - 1))                     
                    {                         
                        Index = ((int)Math.Ceiling((decimal)(VirtualItemCount) / PageSize) - 1);                     
                    }                     
                    else                     
                    {                         
                        Index += 1;                     
                    }                     
                    if (Index < 0)                     
                    { 
                        Index = 0; 
                    }
                    CurrentPageIndex = Index;                     
                    e.NewPageIndex = Index;                     
                    base.OnPageIndexChanging(e);                 
                }             
            }         
        }           
    #endregion     
    } 
}
    

if u have any doubt,please feel free to ask me....

Wednesday, May 20, 2009

Dynamic Add Controls in row of Grid View

just use following line to add row control in particular cell or row of gridview......

  // here i m adding textbox to gridview 
  TextBox textBox = new TextBox(); 
  textBox.ID = "txt" + columnName; 
  gvGeneratedTemplate2.Rows[0].Cells[i].Controls.Add(textBox);  
  
  // gvGeneratedTemplate2 this is my gridview id  same as u can add more control to grid view depending grid view's indexs.......................
  

Thursday, May 14, 2009

Generate Unique Name for Uploading File

Use following function to generate unique file name.
===================================== here i m uploading image file....so i have checked image file extension and its size too....

private string Save_InFolder()
{
    if (Validate_Image() == false)
    {
        HttpPostedFile hpf = fuBrandImage.PostedFile;
        string savePath = ConfigurationManager.AppSettings["CategoryImagePath"].ToString();
        /*  string savePath = ConfigurationManager.AppSettings["CategoryImagePath"].ToString();  
         * the path is defined in web.config file like defined in appsetting section.. 
         * add  follwoing line in your appsetting section of webconfig  add key="CategoryImagePath" value="~/Images/Category/" 
         * // this is where u save the file...  
         */
        string fileName = GetUniqueKey() + GetFileExtension(hpf.FileName);
        string saveName = Server.MapPath(savePath) + fileName;

        //--------------Save Image into  Folder---------------         
        hpf.SaveAs(saveName);
        //--------------Save Image Path into Database---------         
        savePath = savePath + fileName;
        return savePath;
    }
    return null;
}

//check file extension 
private string GetFileExtension(string FileName)
{
    char saperator = '.';
    string[] temp = FileName.Split(saperator);
    return "." + temp[1].ToString();
}

private bool Validate_Image()
{
    bool errorFlag = false;
    string errorMessage = null;
    // Get a reference to PostedFile object     
    HttpPostedFile myFile = fuBrandImage.PostedFile;
    errorMessage = ValidateImage(myFile);
    if (errorMessage != null)
    {
        ShowMessage(errorMessage);
        errorFlag = true;
    }
    return errorFlag;
}

private string ValidateImage(HttpPostedFile myFile)
{
    string msg = null;
    //Check Length of File is Valid or Not.     
    int FileMaxSize = Convert.ToInt32(ConfigurationManager.AppSettings["QueryFileAttachmentSize"].ToString());
    if (myFile.ContentLength > FileMaxSize)
    {
        msg = msg + "File Size is Too Large.";
    }
    //Check File Type is Valid or Not.        
    if (!IsValidFile(myFile.FileName))
    {
        //File Type Error                
        msg = msg + "Upload Only (.bmp, .jpg, .png, .gif, .jpeg )Image .";
    }
    return msg;
}

private bool IsValidFile(string filePath)
{
    bool isValid = false;
    string[] fileExtensions = { ".bmp", ".jpg", ".png", ".gif", ".jpeg", ".BMP", ".JPG", ".PNG", ".GIF", ".JPEG" };
    for (int i = 0; i < fileExtensions.Length; i++)
    {
        //get file extensions and check
    }
}

Blog Archive

Ideal SQL Query For Handling Error & Transcation in MS SQL

BEGIN TRY BEGIN TRAN --put queries here COMMIT; END TRY BEGIN CATCH IF @@TRANCOUNT>0 BEGIN SELECT @@ERROR,ERRO...