Saturday, December 31, 2016

Display Images in GridView Control using the path stored in SQL Server database

Show Image in GridView Using ASP.NET



 Display_Image.aspx  
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Display_Image.aspx.cs" Inherits="Display_Image" %>  
 <!DOCTYPE html>  
 <html xmlns="http://www.w3.org/1999/xhtml">  
 <head runat="server">  
   <title></title>  
 </head>  
 <body>  
   <form id="form1" runat="server">  
    <h3 style="color: #0000FF; font-style: italic">Display Image in GridView Using ASP.NET</h3>  
   <div>  
   <asp:FileUpload ID="fileupload" runat="server" />  
     <br />  
     <asp:Button ID="upload" runat="server" Font-Bold="true" Text="Upload" OnClick="upload_Click" />  
     <br />  
     <br />  
   </div>  
     <div>  
       <asp:GridView runat="server" ID="gdImage" HeaderStyle-BackColor="Tomato" AutoGenerateColumns="false">  
         <Columns>  
           <asp:BoundField DataField="ImageId" HeaderText="ImageId" />  
           <asp:BoundField DataField="ImageName" HeaderText="ImageName" />  
           <asp:ImageField DataImageUrlField="Image" HeaderText="Image"></asp:ImageField>            
         </Columns>  
       </asp:GridView>  
     </div>  
   </form>  
 </body>  
 </html>  


 Display_Image.aspx.cs  
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Web.UI;  
 using System.Web.UI.WebControls;  
 using System.Data;  
 using System.Data.SqlClient;  
 using System.IO;  
 using System.Configuration;  
 public partial class Display_Image : System.Web.UI.Page  
 {  
   SqlConnection con;  
   SqlDataAdapter da;  
   DataSet ds;  
   SqlCommand cmd;  
   protected void Page_Load(object sender, EventArgs e)  
   {  
   }  
   protected void upload_Click(object sender, EventArgs e)  
   {  
     try  
     {  
       string filename = Path.GetFileName(fileupload.PostedFile.FileName);  
       fileupload.SaveAs(Server.MapPath("~/Images/" + filename));  
       con = new SqlConnection(ConfigurationManager.ConnectionStrings["ImageSql"].ConnectionString);  
       con.Open();  
       cmd = new SqlCommand("insert into Image_Details (ImageName,Image) values(@ImageName,@Image)", con);  
       cmd.Parameters.AddWithValue("@ImageName", filename);  
       cmd.Parameters.AddWithValue("@Image", "Images/" + filename);  
       cmd.ExecuteNonQuery();  
       da = new SqlDataAdapter("select * from Image_Details",con);  
       ds = new DataSet();  
       da.Fill(ds);  
       gdImage.DataSource = ds;  
       gdImage.DataBind();  
     }  
     catch (Exception ex)  
     {  
       upload.Text = ex.Message;  
     }  
   }  
 }  


Monday, December 5, 2016

User Login in ASP.Net using C# with session


HTML Markup

The HTML markup consists of an ASP.Net Login control for which the OnAuthenticate event handler has been specified. <form id="form1" runat="server"> <asp:Login ID = "Login1" runat = "server" OnAuthenticate= "ValidateUser"></asp:Login> </form>

Namespaces

You will need to import the following namespaces. using System.Data; using System.Configuration; using System.Data.SqlClient; using System.Web.Security; Stored Procedure to Validate the User Credentials The following stored procedure is used to validate the user credentials, this stored procedure first checks whether the username and password are correct else returns -1. If the username and password are correct but the user has not been activated then the code returned is -2. If the username and password are correct and the user account has been activated then UserId of the user is returned by the stored procedure. CREATE PROCEDURE [dbo].[Validate_User] @Username NVARCHAR(20), @Password NVARCHAR(20) AS BEGIN SET NOCOUNT ON; DECLARE @UserId INT, @LastLoginDate DATETIME SELECT @UserId = UserId, @LastLoginDate = LastLoginDate FROM Users WHERE Username = @Username AND [Password] = @Password IF @UserId IS NOT NULL BEGIN IF NOT EXISTS(SELECT UserId FROM UserActivation WHERE UserId = @UserId) BEGIN UPDATE Users SET LastLoginDate = GETDATE() WHERE UserId = @UserId SELECT @UserId [UserId] -- User Valid END ELSE BEGIN SELECT -2 -- User not activated. END END ELSE BEGIN SELECT -1 -- User invalid. END END Validating the User Credentials The below event handler gets called when the Log In button is clicked. Here the Username and Password entered by the user is passed to the stored procedure and its status is captured and if the value is not -1 (Username or password incorrect) or -2 (Account not activated) then the user is redirected to the Home page using FormsAuthentication RedirectFromLoginPage method. protected void ValidateUser(object sender, EventArgs e) { int userId = 0; string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("Validate_User")) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Username", Login1.UserName); cmd.Parameters.AddWithValue("@Password", Login1.Password); cmd.Connection = con; con.Open(); userId = Convert.ToInt32(cmd.ExecuteScalar()); con.Close(); } switch (userId) { case -1: Login1.FailureText = "Username and/or password is incorrect."; break; case -2: Login1.FailureText = "Account has not been activated."; break; default: FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet); break; } } } Home Page After successful login user will be redirected to this page. HTML Markup In this page I have made use of ASP.Net LoginName control to display the name of the Logged In user and LoginStatus control to allow user Logout. <div> Welcome <asp:LoginName ID="LoginName1" runat="server" Font-Bold = "true" /> <br /> <br /> <asp:LoginStatus ID="LoginStatus1" runat="server" /> </div> Namespaces You will need to import the following namespaces. using System.Web.Security; Verify whether User has Logged In Inside the Page Load event, first we verify whether the User is authenticated using the IsAuthenticated property. If the user is not authenticated then he is redirected back to the Login page using FormsAuthentication RedirectToLoginPage method. protected void Page_Load(object sender, EventArgs e) { if (!this.Page.User.Identity.IsAuthenticated) { FormsAuthentication.RedirectToLoginPage(); } } Web.Config Configuration You will need to add the following configuration in the Web.Config file in the <system.web> section. <authentication mode="Forms"> <formsdefaultUrl="~/Home.aspx" loginUrl="~/Login.aspx" slidingExpiration="true" timeout="2880"></forms> </authentication>

LOGIN FORM USING C# & Sql Server

Login Credential from sqlserver database

 using System;   
 using System.Collections.Generic;   
 using System.ComponentModel;   
 using System.Data;   
 using System.Drawing;   
 using System.Linq;   
 using System.Text;   
 using System.Windows.Forms;   
 using System.Data.Sql;   
 using System.Data.OleDb;   
 using System.Data.SqlClient;   
 namespace login_form   
 {   
   public partial class Form1 : Form   
   {   
     SqlConnection con = new SqlConnection();   
     public Form1()   
     {   
       SqlConnection con = new SqlConnection();   
       con.ConnectionString = "Data Source=KRISHNA-PC\\SQLEXPRESS;Initial Catalog=STUDENT;Integrated Security=True";   
       InitializeComponent();   
     }   
     private void Form1_Load(object sender, EventArgs e)   
     {   
       
       SqlConnection con = new SqlConnection("Data Source=Home-PC\\SQLEXPRESS;Initial Catalog=STUDENT;Integrated Security=True");   
       con.Open();   
       {   
       }   
     }   
     private void button1_Click(object sender, EventArgs e)   
     {   
       SqlConnection con = new SqlConnection();   
       con.ConnectionString = "Data Source=Home-PC\\SQLEXPRESS;Initial Catalog=STUDENT;Integrated Security=True";   
       con.Open();   
       string userid = textBox1.Text;   
       string password = textBox2.Text;   
       SqlCommand cmd = new SqlCommand("select userid,password from login where userid='" + textBox1.Text + "'and password='" + text      Box2.Text + "'", con);   
       SqlDataAdapter da = new SqlDataAdapter(cmd);   
       DataTable dt = new DataTable();   
       da.Fill(dt);   
       if (dt.Rows.Count > 0)   
       {   
         MessageBox.Show("Login sucess Welcome to Homepage https://logicerrors.blogspot.in/");   
         System.Diagnostics.Process.Start("https://logicerrors.blogspot.in/");   
       }   
       else   
       {   
         MessageBox.Show("Invalid Login please check username and password");   
       }   
       con.Close();   
     }   
     private void button2_Click(object sender, EventArgs e)   
     {   
       Application.Exit();   
     }   
   }   
 }