Tuesday 17 July 2012

Send Email through asp.net.


Email.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
        .style2
        {
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <table class="style1">
            <tr>
                <td class="style2">
                   
                </td>
                <td>
                    <asp:TextBox ID="NameTextBox" runat="server" Visible="False">Admin Name </asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    &nbsp;</td>
                <td>
                    <asp:TextBox ID="FromEmailTextBox" runat="server" Visible="False">adminemailaddress@gmail.com</asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    <asp:Label ID="ToEmailLabel" runat="server" Text="To Email"></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="ToEmailTextBox" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2" colspan="2">
                    <asp:Button ID="Button1" runat="server" Text="Button" Width="102px"
                        onclick="Button1_Click" />
                   </td>
            </tr>
            <tr>
                <td class="style2" colspan="2">
                    <asp:Label ID="SendLabel" runat="server" Text="Email Send" Visible="False"></asp:Label>
                   </td>
            </tr>
            <tr>
                <td class="style2" colspan="2">
                    <asp:Label ID="ErrorLabel" runat="server" Text="Error Occured" Visible="False"></asp:Label>
                   </td>
            </tr>
            <tr>
                <td class="style2" colspan="2">
                    <asp:FileUpload ID="FileUpload1" runat="server" />
                   </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>



Email.aspx.cs

protected void Button1_Click(object sender, EventArgs e)
    {
               

        String[] ToID = (ToEmailTextBox.Text).Split(',');  // for seprate multiple email addresses

        try
        {
            MailMessage MyMailMessage = new MailMessage();
            for (int x = 0; x <= ToID.Length - 1; x++)
            {
            MyMailMessage.To.Add(ToID[x].ToString());
            }
            MyMailMessage.From = new MailAddress(FromEmailTextBox.Text);
            MyMailMessage.To.Add(ToEmailTextBox.Text);
            MyMailMessage.Subject = "Hi" +NameTextBox.Text;

            MyMailMessage.Body = "This is a Test Mail.......";
           
 if(FileUpload1.HasFile){
MyMailMessage.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
 }

            SmtpClient SMTPServer = new SmtpClient("smtp.gmail.com");
            SMTPServer.Port = 25;
            SMTPServer.Credentials = new System.Net.NetworkCredential("ur email address", "ur email password");
            SMTPServer.EnableSsl = false;
            SMTPServer.Send(MyMailMessage);
           
       
                    SendLabel.Visible = true;
        }
        catch (Exception ex)
        {
            ErrorLabel.Visible = true;
        }
    }

" Use DropDownList in ASP.NET GridView Control."



Default.aspx

<asp:GridView ID="dgCountry" runat="server" CellPadding="4" ForeColor="#333333"
            AutoGenerateColumns="False" DataKeyNames="CountryId"
        GridLines="None" onrowcancelingedit="dgCountry_RowCancelingEdit"
            onrowediting="dgCountry_RowEditing"
            onrowdatabound="dgCountry_RowDataBound" onrowupdating="dgCountry_RowUpdating" >
    <AlternatingRowStyle BackColor="White" />
    <Columns>
        <asp:TemplateField HeaderText="Country Name">
            <EditItemTemplate>
                <%--<asp:TextBox ID="gdTxtName" runat="server" Text='<%# Bind("CountryName") %>'></asp:TextBox>--%>
                <asp:DropDownList ID="ddlSubCategories" runat="server" >                

        </asp:DropDownList>

            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# Bind("CountryName") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Description">
            <EditItemTemplate>
                <asp:TextBox ID="gdtxtDesc" runat="server" Text='<%# Bind("Description") %>'></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label2" runat="server" Text='<%# Bind("Description") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:CommandField ShowDeleteButton="True" />
        <asp:CommandField ShowEditButton="True" />
    </Columns>
    <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
    <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
    <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
    <SortedAscendingCellStyle BackColor="#FDF5AC" />
    <SortedAscendingHeaderStyle BackColor="#4D0000" />
    <SortedDescendingCellStyle BackColor="#FCF6C0" />
    <SortedDescendingHeaderStyle BackColor="#820000" />
    </asp:GridView>


Default.aspx.cs


// *****************Fill Grid View*************************
    public void MFill_Country()
    {
        DataSet ds = new DataSet();
        try
        {
              string connStr = @"Data Source=.\sqlexpress;Initial Catalog=JobOnlinePortal;Integrated Security=True";
              SqlConnection conn = new SqlConnection(connStr);
            SqlCommand cmd = new SqlCommand("FetchRecord",conn);
            cmd.CommandType = CommandType.StoredProcedure;

            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds);
            dgCountry.DataSource = ds.Tables[0];
            dgCountry.DataBind();
        }
        catch (Exception ex) { throw new Exception(ex.Message); }

     
    }

// *****************Cancel*************************
    protected void dgCountry_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        dgCountry.EditIndex = -1;
        MFill_Country();
    }

// *****************Edit*************************
    protected void dgCountry_RowEditing(object sender, GridViewEditEventArgs e)
    {
        dgCountry.EditIndex = e.NewEditIndex;
        MFill_Country();
    }

// *****************Method for retrieve data of  Country*************************

    private DataTable RetrieveCountryforFillDropDownGridView()
    {

        //fetch the connection string from web.config

        string connStr = @"Data Source=.\sqlexpress;Initial Catalog=JobOnlinePortal;Integrated Security=True";
     

        //SQL statement to fetch entries from Country

        string sql = @"select CountryId,CountryName from tblCountry";

        DataTable dtSubCategories = new DataTable();

        //Open SQL Connection

        using (SqlConnection conn = new SqlConnection(connStr))
        {

            conn.Open();

            //Initialize command object

            using (SqlCommand cmd = new SqlCommand(sql, conn))
            {

                SqlDataAdapter adapter = new SqlDataAdapter(cmd);

                //Fill the result set

                adapter.Fill(dtSubCategories);

            }

        }

        return dtSubCategories;

    }

// ***************** Country data which Fill DropDown in GridView *************************

    protected void dgCountry_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            //check if is in edit mode

            if ((e.Row.RowState & DataControlRowState.Edit) > 0)
            {

                DropDownList ddlSubCategories =

                          (DropDownList)e.Row.FindControl("ddlSubCategories");

                //Bind subcategories data to dropdownlist

                ddlSubCategories.DataTextField = "CountryName";

                ddlSubCategories.DataValueField = "CountryId";

                ddlSubCategories.DataSource =  RetrieveCountryforFillDropDownGridView() ;

                ddlSubCategories.DataBind();


                DataRowView dr = e.Row.DataItem as DataRowView;

                ddlSubCategories.SelectedValue =

                             dr["CountryId"].ToString();

            }

        }

    }



    private void UpdateProduct(int id, string Name, string Description)
{
//fetch the connection string from web.config
string connString = @"Data Source=.\sqlexpress;Initial Catalog=JobOnlinePortal;Integrated Security=True";
//SQL statement to update a product          "select , from ";
using (SqlConnection conn = new SqlConnection(connString))
{
    conn.Open();
    //Initialize command object
    SqlCommand cmd = new SqlCommand("UpdateCountry", conn);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@id", id);
    cmd.Parameters.Add("@Name", Name);
    cmd.Parameters.Add("@Description", Description);
    cmd.ExecuteNonQuery();
}
    }


//************************ Update Row ****************
    protected void dgCountry_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        // Get the product id of the selected product    

        string productID = dgCountry.DataKeys[e.RowIndex].Value.ToString();
        int cid = Convert.ToInt32(productID);

        // Get the GridViewRow object that represents the row being edited

        // from the Rows collection of the GridView control.            

        GridViewRow row = dgCountry.Rows[e.RowIndex];



        // Get the controls that contain the updated values. In this

        // example, the updated values are contained in the TextBox

        // controls declared in the edit item templates of each TemplateField

        // column fields in the GridView control.

        DropDownList ddlSubCategories =

                          (DropDownList)row.FindControl("ddlSubCategories");

        TextBox txtCDesc = (TextBox)row.FindControl("gdtxtDesc");

     

        //update the product

        UpdateProduct(cid,ddlSubCategories.SelectedItem.ToString(), txtCDesc.Text);

        dgCountry.EditIndex = -1;

         MFill_Country();

    }






Friday 13 July 2012

Open a Alert Box and open a new Window


//Open A Alert box.
ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", @"alert('Invalid Login Email & Password.');", true);

//Open a Alert Box then press "Ok" which redirect the Page.
ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('valid Login Email & Password.'); window.location.href = 'HomeAdmin.aspx';", true);

//Open a New Asp page in new Window

ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", "window.open(\"Default3.aspx\")", true);

//Open a New website in new Window
        ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", "window.open('http://www.google.com')", true);

//Constant width and height of the new Window and not resize.

string fullURL = "window.open('http://www.google.com', '_blank', 'height=500,width=800');";
ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", fullURL, true);

Response.Redirect throws exception which is “Thread was being aborted” in asp.net/c#


Solutions:

1) Set the EndResponse (the 2nd parameter) to false. 
e.g:  Response.Redirect("AdminHome.aspx",false);
2) Move the Response.Redirect outside the try/catch block.

Monday 9 July 2012

For Login Using Stored Procedures instead of specific SQL statements is very useful in ASP.NET using c#




 protected void Button1_Click(object sender, EventArgs e)
    {
 //Procure1
           //   SPVerifyLogin(TextBox1.Text, TextBox2.Text);  


//Procedure 2
              // SPVerifyLogins(TextBox1.Text, TextBox2.Text);  

//Procedure 3
        SQLAdopterSPVerifyLogins(TextBox1.Text, TextBox2.Text); 

    }



Procedure 1:
private void SPVerifyLogin(string username, string password)
       {
           try
           {
               SqlConnection conn = (SqlConnection)NConnection.Connection.Connection_Method();
               SqlCommand cmd = new SqlCommand("ChechAdminLogin", conn);
               cmd.CommandType = CommandType.StoredProcedure;

              // cmd.Parameters.Add("@Adminlogin_Name", username);
               //cmd.Parameters.Add("@AdminLogin_Password", password);

               cmd.Parameters.AddWithValue("@AdminLogin_Name", username);
               cmd.Parameters.AddWithValue("@AdminLogin_Password", password);
               
               cmd.ExecuteNonQuery();

            //   lbl.Text = TextBox1.Text;
                            
cmd.Connection.Close();  //close Connection.
             
  ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('Password & UserName Correct'); window.location.href = 'HomeAdmin.aspx';", true);  
           }
           catch (Exception ex)
           {
               throw new Exception(ex.Message);
           }
}



Procedure 2:


private void SPVerifyLogins(string username, string password)
    {
        try
        {
            ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter();
            SqlConnection conn = (SqlConnection)NConnection.Connection.Connection_Method();
            SqlCommand cmd = new SqlCommand("ChechAdminLogin", conn);
            cmd.CommandType = CommandType.StoredProcedure;

            // cmd.Parameters.Add("@Adminlogin_Name", username);
            //cmd.Parameters.Add("@AdminLogin_Password", password);

            cmd.Parameters.AddWithValue("@AdminLogin_Name", username);
            cmd.Parameters.AddWithValue("@AdminLogin_Password", password);

            da.SelectCommand = cmd;
            da.Fill(ds);

            if (ds.Tables[0].Rows.Count > 0)
            {
          
                ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert(' Password & UserName Correct '); window.location.href = 'HomeAdmin.aspx';", true);
               // Response.Redirect("HomeAdmin.aspx");  // throw a Exception
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", @"alert('Invalid Login Email & Password.');", true);
            }
         
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
       }


Procedure 3:


 private void SQLAdopterSPVerifyLogins(string username, string password)
    {
        try
        {
            ds = new DataSet();
           
// Create a Connection.
            SqlConnection conn = (SqlConnection)NConnection.Connection.Connection_Method();


//Create a DataAdapter, and then provide the name of the stored procedure.

            SqlDataAdapter da = new SqlDataAdapter("ChechAdminLogin", conn);


//Set the command type as StoredProcedure.

            da.SelectCommand.CommandType = CommandType.StoredProcedure;


// Add a parameter and Value to Parameters collection for the stored procedure.

            da.SelectCommand.Parameters.Add("@Adminlogin_Name", username);
            da.SelectCommand.Parameters.Add("@AdminLogin_Password", password);


//Fill the DataSet with the rows that are returned.

            da.Fill(ds);

            if (ds.Tables[0].Rows.Count > 0)
            {
              
                ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('valid Login Email & Password.'); window.location.href = 'HomeAdmin.aspx';", true);
              
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", @"alert('Invalid Login Email & Password.');", true);
            }



        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }



Command: Register asp.net with IIS where IIS was not already present, and just later decided to add IIS.

If you install the .NET Framework on a system that has IIS already installed, IIS is automatically configured to handle requests to ASP.NET pages, and to redirect the execution to the ASP.NET runtime. However, it may happen that you installed the framework on a Windows 2000, XP ,Vista, Window 7  where IIS was not already present, and just later decided to add IIS.


If Microsoft Visual Studio is installed:


Step 1:



Start->Microsoft Visual Studio->Visual Studio Tools->Visual Studio Command Prompt --> right Click : Run as Administrator.


Step 2:
            aspnet_regiis -i  
                    or
            aspnet_regiis.exe -i 


if Microsoft Visual Studio is not installed:



Step 1:


Open the Windows command prompt console window:


From the Windows Start menu, select Run.


Type CMD and click OK.


Step 2.


At the command prompt, type:
   <WinDir>\Microsoft.NET\Framework\<Ver>\aspnet_regiis.exe -i


Where <WinDir> is the directory of your Windows folder (e.g. C:\WINDOWS) and <Ver> is the actual version number of the .NET Framework (e.g. v1.1.4322).


Press Enter to run the executable. When it completes, close the command prompt console window.