Home

Tuesday, 19 July 2016

Convert C# Object Value in JSON using C#

Step 1-Write Below Code in Application where Data is fix.If required you can change static data in dynamic.
public class Student
{
    public int Id { get; set; }
public string Name { get; set; }
    public string fatherName { get; set; }
    public DateTime? BirthDate { get; set; }
    public string Phone { get; set; }

    public Student()
    {
        Id = 123; Name = "XYZ";fatherName = "ABC"; BirthDate = new DateTime(1991, 5, 13); Phone = "12345678";
    }
    public Student(int id, string name,String FatherName, DateTime? dob, string phone)
    {
        Id = id; Name = name;fatherName= FatherName; BirthDate = dob; Phone = phone;
    }
}

public class StudentRecord
{
    public IEnumerable<Student> Students { get; set; }

    public StudentRecord()
    {
        Students = new List<Student>
        {
            new Student(1213, "ABC","vbs", new DateTime(1991, 7, 18), "123432123"), 
            new Student(23412, "vtyd","aghgh", new DateTime(1998, 11, 21), "123432123"), 
            new Student(2345, "ghghgh","hjhj", new DateTime(1997, 3, 9), "767678445"), 
        };
    }
}

Step 2-Output Data is in JSon which is Available below.

{
  "Id": 123,
  "Name": "XYZ",
  "fatherName": "ABC",
  "BirthDate": "1991-05-13T00:00:00",
  "Phone": "12345678"
}

{
  "Students": [
    {
      "Id": 1213,
      "Name": "ABC",
      "fatherName": "vbs",
      "BirthDate": "1991-07-18T00:00:00",
      "Phone": "123432123"
    },
    {
      "Id": 23412,
      "Name": "vtyd",
      "fatherName": "aghgh",
      "BirthDate": "1998-11-21T00:00:00",
      "Phone": "123432123"
    },
    {
      "Id": 2345,
      "Name": "ghghgh",
      "fatherName": "hjhj",
      "BirthDate": "1997-03-09T00:00:00",
      "Phone": "767678445"
    }
  ]
}

Find Max value within Matrix using C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ArrayMax
{
    class Program
    {
         int mvalue = 0;
        int[,] array = { { 3, 7, 8 }, { 17, 32, 1 }, { 32, 45, 7 } };
        public int max(int[,] array)
        {

            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    if (i == 0)
                        mvalue= array[0, 0];
                    else
                    {
                        if (array[i, j] > mvalue)
                            mvalue = array[i, j];
                    }
                }
            }
            return 0;
        }
       static void Main()
       {
            Program p = new Program();
            p.max(p.array);
            Console.WriteLine("Max Value: {0}", p.mvalue);
            Console.ReadLine();
        }

    }
}

Saturday, 16 July 2016

Create a NotePad Application using C#

Step 1) Take a Form and Add Below Code in Class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MyNotepad
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

Step 2) Run application its open a window with Notepad.

Find Inverse Of Matrix Using C#

Below Application find Inverse of Given Matrix .

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[,] a = new int[3, 3];
            int i, j;
            float determinant = 0;

            Console.WriteLine("Enter the 9 elements of matrix: ");
            for (i = 0; i < 3; i++)
                for (j = 0; j < 3; j++)
                    a[i, j] = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("\nThe matrix is\n");
            for (i = 0; i < 3; i++)
            {
                Console.WriteLine("\n");
                for (j = 0; j < 3; j++)
                    Console.Write("{0}\t", a[i, j]);
            }

            for (i = 0; i < 3; i++)
                determinant = determinant + (a[0, i] * (a[1, (i + 1) % 3] * a[2, (i + 2) % 3] - a[1, (i + 2) % 3] * a[2, (i + 1) % 3]));

            Console.WriteLine("\nInverse of matrix is: \n\n");
            for (i = 0; i < 3; i++)
            {
                for (j = 0; j < 3; j++)
                    Console.Write("{0}\t", ((a[(i + 1) % 3, (j + 1) % 3] * a[(i + 2) % 3, (j + 2) % 3]) - (a[(i + 1) % 3, (j + 2) % 3] * a[(i + 2) % 3, (j + 1) % 3])) / determinant);
                Console.WriteLine("\n");
            }
            Console.ReadLine();
        }
    }
}

Friday, 15 July 2016

Delete Data From SQL server After click on GridView field By ID Using C# Asp.net

Step 1) Bind Grid Data Where One field Contain Record ID.
Step 2) Add below code on RecordId Click Event.
 protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["id"].ToString());
            BusinessObject bo = new BusinessObject();
            bo.Id = id;
            try
            {
                int retVal = objDAL.DeleteProjRecord(bo);

                if (retVal > 0)
                {
                    lblmessage.Text = "Record deleted successfully";
                    lblmessage.ForeColor = System.Drawing.Color.Green;
                }
                else
                {
                    lblmessage.Text = "Book details couldn't be deleted";
                    lblmessage.ForeColor = System.Drawing.Color.Red;
                }
            }
            catch (Exception ex)
            {
                Response.Write("Oops! error occured :" + ex.Message.ToString());
            }
       }
Step 3) Use Bussiness object as Previous Post Bussiness Object Class.
https://developerprob.blogspot.in/2016/07/user-registration-application-using-c.html

Step 4)  After that add below code on DataBase Layer class Add below method-
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=TestProj;Integrated Security=True");
        public Int32 DeleteProjRecord(BusinessObject objBEL)
        {
            int result;
            try
            {
                SqlCommand cmd = new SqlCommand("DeleteRecord", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@id", objBEL.Id);
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }
                result = cmd.ExecuteNonQuery();
                cmd.Dispose();
                if (result > 0)
                {
                    return result;
                }
                else
                {
                    return 0;
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                if (con.State != ConnectionState.Closed)
                {
                    con.Close();
                }
            }
        }
Step 5) Use Below stored Procedure for delete record from database.
  BEGIN
   DELETE FROM Emp WHERE id = @id
END

 Step 6) After Successful Completion of Above Code Record deleted from database.

User Registration application using c# Asp.net

Step 1) Add a Page Aspx page in application and Write below code on aspx page.
<body>
    <form id="form1" runat="server">
    <div>
        .<table class="auto-style1">
            <tr>
                <td class="auto-style2" colspan="2"><strong>&nbsp;New User Register Here</strong></td>
            </tr>
            <tr>
                <td class="auto-style4">&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td class="auto-style5">Name</td>
                <td>
                    <asp:TextBox ID="txtname" runat="server" Width="269px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="auto-style5">Password</td>
                <td>
                    <asp:TextBox ID="txtpassword" runat="server" TextMode="Password" Width="269px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="auto-style5"><strong>Confirm Password</strong></td>
                <td>
                    <asp:TextBox ID="txtconfirmpass" runat="server" TextMode="Password" Width="269px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="auto-style5">Address</td>
                <td>
                    <asp:TextBox ID="txtAddress" runat="server" TextMode="MultiLine" Width="269px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="auto-style5">EmailId</td>
                <td>
                    <asp:TextBox ID="txtEmailId" runat="server" Width="269px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="auto-style5">Mobileno</td>
                <td>
                    <asp:TextBox ID="txtMobile" runat="server" Width="269px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="auto-style3">&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td class="auto-style4">&nbsp;</td>
                <td>
                    <asp:Button ID="btnRegister" runat="server" OnClick="btnRegister_Click" Text="Register" Width="85px" />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <asp:Button ID="btnlogin" runat="server" OnClick="btnlogin_Click" Text="Login" Width="72px" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>

Step 2) After that on btnRegistration Event add below code
  protected void btnRegister_Click(object sender, EventArgs e)
        {
            BusinessLogic bl = new BusinessLogic();
            BusinessObject bo = new BusinessObject();
            bo.Name = txtname.Text;
            bo.Password = txtpassword.Text;
            bo.Address = txtAddress.Text;
            bo.Email = txtEmailId.Text;
            bo.MobileNo = txtMobile.Text;
            int result = bl.insertUserDetails(bo);
            if (result > 0)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('User Register Successfully'),window.location.href = 'Login.aspx'", true);
                //Response.Redirect("Login.aspx");
            }

        }

Step 3) Add below code in Bussiness logic class library class
public int insertUserDetails(BusinessObject bo)
        {
            try
            {
                return dal.AddUserDetails(bo);
            }
            catch
            {
                throw;
            }
        }
Step 4) After that use below code for data base intraction and add data in Sql Server.
 SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=TestProj;Integrated Security=True");
        public int AddUserDetails(BusinessObject userdetails)
        {
            try
            {
                SqlCommand cmd = new SqlCommand("userdetails", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Name", userdetails.Name);
                cmd.Parameters.AddWithValue("@Password", userdetails.Password);
                cmd.Parameters.AddWithValue("@Address", userdetails.Address);
                cmd.Parameters.AddWithValue("@Email", userdetails.Email);
                cmd.Parameters.AddWithValue("@MobileNo", userdetails.MobileNo);
                con.Open();
                int res = cmd.ExecuteNonQuery();
                return res;
            }
            catch 
            {
                throw;
            }
            finally
            {
                con.Dispose();
                con.Close();
            }
        }
Step 4) Where BussinessObject is class contain below code
 public class BusinessObject
    {
        private int id;
        public int Id
        {
            get { return id; }
            set { id = value; }
        }
        private string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        private string address;
        public string Address
        {
            get { return address; }
            set { address = value; }
        }
        private string email;

        public string Email
        {
            get { return email; }
            set { email = value; }
        }
        private string mobileNo;
        public string MobileNo
        {
            get { return mobileNo; }
            set { mobileNo = value; }
        }
        private string password;
        public string Password
        {
            get { return password; }
            set { password = value; }
        }
    }
Step 5) After using this successfully intract with database and user inserted in Sql Server Data base.

Login Application Using asp.net C#

Step 1-Add a Login1.aspx Page in Application.And Add below Code for User Input-
<body>
    <form id="form1" runat="server">
    <div>
    
        <table class="auto-style1">
            <tr>
                <td colspan="2">&nbsp;</td>
            </tr>
            <tr>
                <td class="auto-style3">&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td class="auto-style3">&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td class="auto-style3">&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td class="auto-style3">&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td class="auto-style2" colspan="2"><strong>LOGIN HERE</strong></td>
            </tr>
            <tr>
                <td class="auto-style3">&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td class="auto-style3">&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td class="auto-style4">UserName</td>
                <td>
                    <asp:TextBox ID="txtname" runat="server" Width="229px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="auto-style4">Password</td>
                <td>
                    <asp:TextBox ID="txtpassword" runat="server" TextMode="Password" Width="230px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="auto-style3">&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td class="auto-style3">&nbsp;</td>
                <td>
                    <asp:Button ID="btnLogin" runat="server" OnClick="btnLogin_Click" Text="Login" Width="82px" />
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <asp:Button ID="btnRegister" runat="server" OnClick="btnRegister_Click" Text="New User Register Here" Width="166px" />
                </td>
            </tr>
        </table>    
    </div>
    </form>
</body>
Step 2-Add below code on Button Click event-

          BusinessLogic bl = new BusinessLogic();
        BusinessObject bo = new BusinessObject();
 protected void btnLogin_Click(object sender, EventArgs e)
        {
            string username = txtname.Text;
            string password = txtpassword.Text;
            int a = bl.ballogin(username, password);
            txtname.Text = "";
            txtpassword.Text = "";
            if (a == 1)
            {
                Session["username"] = username;
                Response.Redirect("Project.aspx");
            }
        }
Step 3-Add A class Library in Application and Add Class in Class Library name is BussinessLogic and Bussines Object,add Below Code in BissinessLogic Class-
public int ballogin(string username, String password)
        {
            try
            {
                int a = dal.userLogin(username, password);
                if (a == 1)
                {
                    return 1;
                }
                else
                {
                    return 0;
                }          
            }
            catch (Exception e)
            {
                e.GetType();
            }
            return 0;
        }
Step 4-Add Below Code in Data Layer Logic class.
 public int userLogin(string username, string password)
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("select count(*) from Registration where Name='" + username + "'and password='" + password + "'",con);
             // cmd.ExecuteScalar();
              //return 1;
                int a = Convert.ToInt32(cmd.ExecuteScalar());
                return a;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                con.Close();
            }
        }
Step 5-Add below Connection string in Data access class-
 SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=ProjectTest;Integrated Security=True");
Step 6-After Completion this  Create Table and add some l data and use this code for login with application and authenticate user from database
    

Send Data to another Page Using Session in Asp.net c#(Using Session State Management)

Step 1) Use Previous webForm1.aspx and WebForm2.aspx for User Input and User Output.
Step 2)After that use below code on Button Click event
 protected void Button1_Click(object sender, EventArgs e)
        {
            Session["Name"] = TextBox1.Text;
            Session["Email"] = TextBox2.Text;
            Response.Redirect("~/WebForm2.aspx");
        }
Step 3) After this page Completion Go to WebForm2.aspx PageLoad Event and write below code.
 protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["Name"] != null && Session["Email"] != null)
            {
                Label1.Text = Session["Name"].ToString();
                Label2.Text = Session["Email"].ToString();
            }
        }

Thursday, 14 July 2016

Send Mail Using C# Asp.net

Step 1) Write below code in Button Click and get data and assign it property of Mail-message-

protected void Page_Load(object sender, EventArgs e)
        {
            MailMessage mailAddress = new MailMessage("x@gmail.com", "y@gmail.com");
            mailAddress.Subject = "Testing Email";
            mailAddress.Body = "Hello";
             SmtpClient smtp = new SmtpClient();
           smtp.Send(mailAddress);
    }

Where x@gmail.com is Sender Mail address and y@gmail.com is Recipient mail address


Step 2)Add Below code in web.config file-
<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
    <system.web>
      <compilation debug="true" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />
    </system.web>
  <system.net>
    <mailSettings>
      <smtp deliveryMethod="Network">
        <network host="smtp.gmail.com" port="587" userName="x@gmail.com" password="fgfgfgag" enableSsl="true"/>
      </smtp>
    </mailSettings>
  </system.net>
</configuration>

Send Data from One page from another page without using state Management(Cookies,Session) Using c# Asp.net

Step 1) Create Form as a previous Post Name is WebForm1.aspx and write below code on Button Click-
 public string Id { get { return TextBox1.Text; } }
        public string Name { get { return TextBox2.Text; } }
        protected void Button1_Click(object sender, EventArgs e)
        {
            Server.Transfer("WebForm2.aspx");
        }
Step 2-Create another web Form where display Input Data name is webForm2.aspx and addbelow code in Form Body-
 <form id="form1" runat="server">
        <table class="auto-style1">
            <tr>
                <td>ID</td>
                <td>
                    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>Name</td>
                <td>
                    <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
                </td>
            </tr>
        </table>
    </form>
Step 3-Write Below code in WebForm2.aspx.cs in PageLoad method.
 protected void Page_Load(object sender, EventArgs e)
        {            
            if (!IsPostBack)
            {
                Page LastPage = (Page)Context.Handler;
                if (LastPage is WebForm1)
                {
                    Label1.Text = ((WebForm1)(LastPage)).Id;
                    Label2.Text = ((WebForm1)(LastPage)).Name;
                }
            }
        }
 Step 4-Run application after that we get form1 pass data in form2 after enterning input in textbox and click on Button

Send Data from one Page to another using Query String in c# Asp.net

Step 1) Create Form for user interaction-
WebForm1.aspx
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table>
        <tr>
            <td>Name</td>
            <td>
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td>
        </tr>
        <tr>
            <td>Email</td>
            <td>
                <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></td>
        </tr>
        <tr>
            <td colspan="2">
                <asp:Button runat ="server" ID="Botton1" Text="Send Data" OnClick="Botton1_Click"  />
            </td>
        </tr>  
    </table>
    </div>
    </form>
</body>
</html>
Step 2-Write Below code in WebForm1.aspx.cs on Button Click Event
 protected void Botton1_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/WebForm1.aspx?Name=" + Server.UrlEncode(TextBox1.Text) + "&Email=" + Server.UrlEncode(TextBox2.Text));
            //Response.Redirect("~/WebForm1.aspx?Name=" +TextBox1.Text.Replace("&","%26") + "&Email=" +TextBox2.Text.Replace("&","%26"));
        }
 Step 3-Write Below code in WebForm1.aspx where show query string data-
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table class="auto-style1">
            <tr>
                <td>Name</td>
                <td>
                    <asp:Label ID="Label1" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    email</td>
                <td>
                    <asp:Label ID="Label2" runat="server"></asp:Label>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>
Step 4- Add below code in WebForm2.aspx.cs PageLoad method
 protected void Page_Load(object sender, EventArgs e)
        {
           Label1.Text= Request.QueryString[0];
           Label2.Text = Request.QueryString[1];
        }
Step 5) Run application and enter field data after click on button we get below query string in URL-

http://localhost:2210/WebForm1.aspx?Name=pankaj&Email=pankaj%40gmail.com

Working with Cookies using C# Asp.net

Step 1- Create UI where user give input name is WebForm1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Cokkies.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>    
        Name<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
&nbsp;Email
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
&nbsp;&nbsp;
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
        <br />
        <asp:Label ID="Label2" runat="server" Text="msg"></asp:Label>    
    </div>
    </form>
</body>
</html>
Step 2-Write below code in WebForm1.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Cokkies
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.Browser.Cookies)
                {
                    if (Request.QueryString["Cookiecheck"] == null)
                    {
                        HttpCookie cookies = new HttpCookie("Test", "1");
                        Response.Cookies.Add(cookies);
                        Response.Redirect("~/WebForm1.aspx?Cookiecheck=1");
                    }

                    else
                    {
                        HttpCookie cookie = Response.Cookies["Test"];
                        if (cookie == null)
                        {

                            Label2.Text = "We Detected your browser cookie are disable please enable cookie";
                        }
                    }
                }
                else
                {
                    Response.Write("Not Support");
                }
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            HttpCookie _cookie = new HttpCookie("UserInfo");
            _cookie["Name"] = TextBox1.Text;
            _cookie["Email"] = TextBox2.Text;
            //_cookie.Expires.AddDays(10);
            Response.Cookies.Add(_cookie);
            Response.Redirect("~/WebForm2.aspx");
        }
    }
}
Step 3-Create another aspx page where user seen given value in WebForm1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="Cokkies.WebForm2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        Name=
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Email =<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>    
    </div>
    </form>
</body>
</html>
Step 3-Add below code in WebForm1.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Cokkies
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpCookie _cookie = Request.Cookies["UserInfo"];
            if (_cookie != null)
            {
                Label1.Text = _cookie["Name"];
                Label2.Text = _cookie["Email"];
            }
        }
    }

Know How many user access application using C#(Anonymous User)

Step 1) Write Front end code for user interaction where display user count.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="ApplicationExample.WebForm1" %>
<!DOCTYPE html>
<html xmlns="">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <!-- display no of user access application -->
    </div>
    </form>
</body>
</html>
Step 2) Add below code as a back end in class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ApplicationExample
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write("No Of User Online " +Application["OnlineUser"]);
        }
    }
}
 Step 3) Write below code in Global.asax.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
namespace ApplicationExample
{
    public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            Application["OnlineUser"] = 0;
        }
        protected void Session_Start(object sender, EventArgs e)
        {
            Application.Lock();
            Application["OnlineUser"] = (int)Application["OnlineUser"] + 1;
            Application.UnLock();
        }
        protected void Session_End(object sender, EventArgs e)
        {
            Application.Lock();
            Application["OnlineUser"] = (int)Application["OnlineUser"] - 1;
            Application.UnLock();     
        }
    }
}

Tuesday, 12 July 2016

HashSet and its method with Example Using C#

HashSet is collection which stored unique element in unordered manner.In HashSet perform below operation like-
1) Add
2) Remove
3) Contains
4) Clear 
5) CopyTo etc.

Syntax-
HashSet<int> hashset=new HashSet<int>();

1) Add Element in Hashset-
hashset.Add(1);
hashset.Add(2);
hashset.Add(3);
hashset.Add(4);

2) Remove Element from HashSet-
hashset.remove("Element name");
hashset.RemoveWhere(s=>s=="Elementname");

3)Clear  HashSet
hashset.clear();

Example-

using System;
using System.Collections;
namespace TestApp
{  
  class Program
    {
        static void Main(string[] args)
        {
           HashSet<string> name = new HashSet<string> ();
  //Adding Element
  name.Add("Pankaj");
  name.Add("Ravi");
  name.Add("Kushal");
  name.Add("Amar");
          //Remove Element
            name.RemoveWhere(s=>s.Contains("Ravi"));
foreach (string npa in name)
{
Console.WriteLine(npa);
}
        }
    }
}

Monday, 11 July 2016

What is MongoDB? How to Connect with this using C#

MongoDB-
1) Mongo DB is open Source Database written in C++. It is schema less data base.i.e no row and column available,
2) Mongo DB store data in JSon Format.
3) MongoDB is easy to install-able.
4) MongoDb Stored data in collection format .

Where it used-
1) Its used in Big Data.
2) Schema less data structure means where no of field not fixed.

MongoDb stored data in key and value format.
e.g.

{
    'id' : 1,
    'name' : { 'first' : 'Pankaj', 'last' : 'Singh' },
    'Address' : 'Delhi',
    'Education' : [
        {
            'BCA' : 'xyz',
            'MCA' : 'abc',
        }
    ]
}

Connection with MongoDB using C#-
Step 1-MongoDB officially provide a driver to connect with c# name is MongoDB C# Driver.
Download it .we can download this from below link-
https://docs.mongodb.com/ecosystem/drivers/csharp/

Step 2-Add Below DLL reference in application-
1) MongoDB.Bson.dll
2) MongoDB.Driver.dll
3) MongoDB.Driver.Core.dll

Step 3-Add below package in application-
1) using MongoDB.Bson;
2) using MongoDB.Driver;

After that add below code in application-

protected static IMongoClient client;
protected static IMongoDatabase database;

client=new MongoClient();
database=client.getDatabase("databasename");

Sunday, 10 July 2016

Sample Application Using View Model and Controller With Asp.net MVC

Step 1- Add Controller in Application Keep name as StudentController. Paste Below Code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TsetMVC.Models;
namespace TsetMVC.Controllers
{
    public class EmployeeController : Controller
    {
        // GET: Employee
        public ActionResult Index()
        {
            var empyeeList = new List<Employee>{
                            new Employee() { empId = 1, employeeName = "ravi", age = 12 } ,
                            new Employee() { empId = 2, employeeName = "pankaj", age = 25 } ,
                            new Employee() { empId = 3, employeeName = "dilip", age = 26 } ,
                            new Employee(){ empId = 4, employeeName = "amar", age = 25 } ,
                            new Employee(){ empId = 5, employeeName = "umesh", age = 34 } ,
                            new Employee(){ empId = 6, employeeName = "Pawan", age = 21 } ,
                            new Employee(){ empId = 7, employeeName = "Rajan", age = 27 } ,
                        };
            // Get the students from the database in the real application

            return View(empyeeList);
        }
}

Step 2-Create a Model Class and keep name as Student in Model Folder.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TsetMVC.Models
{
    public class Employee
    {
        public int empId { get; set; }
        public string employeeName { get; set; }
        public int age { get; set; }
    }
}
Step 3-After that add View in View Folder and Write Below code in Index.cshtml.
 
@model IEnumerable<TsetMVC.Models.Employee>
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.employeeName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.age)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.employeeName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.age)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.empId }) |
                @Html.ActionLink("Details", "Details", new { id = item.employeeName }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.empId })
            </td>
        </tr>
    }
</table>
Step 4- After completed Above step build and run application and type below URL
http://localhost:64484/Employee/Index

 Where localhost:64484 is a your Machine host name with Port No.

Step 5 After Completion of above step  below output Came.

Thursday, 7 July 2016

Register Route in ASP.NET MVC Application

After successfully configure route in RouteConfig.cs need to register this configuration in Global.asax of AppStart()  method.


Below code is used to register Route config in Global.asax
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace MVCTest
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            RouteConfig.RegisterRoutes(RouteTable.Routes);
           
    }
}