Shalvin Interests

Wednesday, May 21, 2014

Html Input Type Date and MVC

View

<pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>&lt;form method =&quot;post&quot; action =&quot;/&quot;&gt;
    &lt;input type =&quot;date&quot; name =&quot;calDOJ&quot; /&gt;
    &lt;div&gt;
        &lt;input type =&quot;submit&quot; /&gt;
    &lt;/div&gt;
&lt;/form&gt;
</code></pre>

Controller

 [HttpPost]
        public ActionResult Index(FormCollection fc)
        {
            DateTime dt =DateTime.Parse(  Request.Form["calDOJ"]);
            ViewBag.Hello = dt.ToString("D");
            return View();

        }

Wednesday, February 19, 2014

Windows Forms Calculator



double Operand1, Operand2, result, value;
string Op;
Boolean clearDisplay;


private void Digit_Click(object sender, EventArgs e)
{
    if (clearDisplay)
    {
        lblDisplay.Text = "";
        clearDisplay = false;
    }
    //namespace display(): 
    Button b = (Button)sender;
    lblDisplay.Text = lblDisplay.Text + b.Text;
}

private void btnAdd_Click(object sender, EventArgs e)
{

}

private void GetOperator_Click(object sender, EventArgs e)
{
    if (lblDisplay.Text.Length == 0)
    {
        return;
    }
    Operand1 = Convert.ToDouble(lblDisplay.Text);
    Button b = (Button)sender;
    Op = b.Text;
    lblDisplay.Text = "";
    clearDisplay = true;
}

private void btnEquals_Click(object sender, EventArgs e)
{
    if (lblDisplay.Text.Length == 0)
    {
        return;
    }
    Operand2 = Convert.ToDouble(lblDisplay.Text);
    clearDisplay = true;
    switch (Op)
    {
        case "+":

            result = Operand1 + Operand2;
            lblDisplay.Text = result.ToString();
            break;

        case "-":
            result = Operand1 - Operand2;
            lblDisplay.Text = result.ToString();
            break;

        case "*":
            result = Operand1 * Operand2;
            lblDisplay.Text = result.ToString();
            break;

        case "/":
            if (Operand2 != 0)
            {
                result = Operand1 / Operand2;
                lblDisplay.Text = result.ToString();
            }
            break;
        default:
            break;
    }
}

private void btnClear_Click(object sender, EventArgs e)
{
    lblDisplay.Text = "";

}

private void btnBackSpace_Click(object sender, EventArgs e)
{
    if (lblDisplay.Text.Length == 0)
    {
        return;
    }
    lblDisplay.Text = lblDisplay.Text.Remove(lblDisplay.Text.Length - 1, 1);
}

private void btnInverse_Click(object sender, EventArgs e)
{
    if (lblDisplay.Text.Length == 0)
    {
        return;
    }
    value = Convert.ToDouble(lblDisplay.Text);
    if (value != 0)
    {
        result = 1 / value;
        lblDisplay.Text = result.ToString();
    }
}

private void btnSign_Click(object sender, EventArgs e)
{
    if (lblDisplay.Text.Length == 0)
    {
        return;
    }
    value = Convert.ToDouble(lblDisplay.Text);
    result = -1 * value;
    lblDisplay.Text = result.ToString();
}

Courtesy : Binish Babu

Tuesday, February 11, 2014

Asp .Net MVC HttpPost and BeginForm Html Helpers


public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        
     [HttpPost]
        public ActionResult Index(FormCollection frm)
        {
         string strName = Request.Form["Name"];
         ViewBag.Name = strName;
         return View();
        }
    }

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
@ViewBag.Name

@using (Html.BeginForm())
{
    @Html.Label("Name")
    @Html.TextBox("Name")

    <br />
    <input type ="submit" />

}

Monday, February 10, 2014

Asp .Net Bank with Deposit and Withdraw Functionality


using System.Data;
using System.Data.SqlClient;
public class UserInfo
{
  SqlConnection cnn;
 public DataTable GetUsers()
 {
  using (cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
  {
   cnn.Open();

   DataSet ds = new DataSet();
   SqlDataAdapter da;
   da = new SqlDataAdapter("select * from UserInfo", cnn);
   da.Fill(ds, "Usr");

   return ds.Tables ["Usr"];
  }
 }
using System.Data.SqlClient;
public partial class Admin_AdminHome : System.Web.UI.Page
{
 UserInfo ui = new UserInfo();
 SqlConnection cnn;

 double dblCurBal = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
     if (!IsPostBack)
     {
      ShowBal();
     }
    }

    private void ShowBal()
    {
     ddlUser.DataSource = ui.GetUsers();
     ddlUser.DataTextField = "UserName";
     DataBind();
    }
    protected void ddlUser_SelectedIndexChanged(object sender, EventArgs e)
    {
     using (cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
     {
      ShowBalInLabel();
     }
    }

    private void ShowBalInLabel()
    {
     if (cnn.State == System.Data.ConnectionState.Closed)
     {
      cnn.Open();
     }

     SqlCommand cmd = new SqlCommand("select * from UserInfo where UserName = @UserName", cnn);
     cmd.Parameters.AddWithValue("@UserName", ddlUser.Text);
     SqlDataReader dr = cmd.ExecuteReader();

     while (dr.Read())
     {
      lblCurBal.Text = dr["Balance"].ToString();
     }
    }


    protected void btnDeposit_Click(object sender, EventArgs e)
    {
     using (cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
     {
      cnn.Open();
      SqlCommand cmd = new SqlCommand("select * from UserInfo where UserName = @UserName", cnn);
      cmd.Parameters.AddWithValue("@UserName", ddlUser.Text);
      SqlDataReader dr = cmd.ExecuteReader();
     

      while (dr.Read())
      {
       dblCurBal = double.Parse(dr["Balance"].ToString());
      }
      dr.Close();

      double dblNewBal = dblCurBal + double.Parse(txtAmount.Text);

      cmd = new SqlCommand("update UserInfo set Balance = @NewBal where UserName = @UserName", cnn);
      cmd.Parameters.AddWithValue("@NewBal", dblNewBal);
      cmd.Parameters.AddWithValue("@UserName", ddlUser.Text);
      cmd.ExecuteNonQuery();

      ShowBalInLabel();
    
     }
    }
    protected void btnWithdraw_Click(object sender, EventArgs e)
    {
     using (cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
     {
      cnn.Open();
      SqlCommand cmd = new SqlCommand("select * from UserInfo where UserName = @UserName", cnn);
      cmd.Parameters.AddWithValue("@UserName", ddlUser.Text);
      SqlDataReader dr = cmd.ExecuteReader();


      while (dr.Read())
      {
       dblCurBal = double.Parse(dr["Balance"].ToString());
      }
      dr.Close();

      double dblNewBal = dblCurBal - double.Parse(txtAmount.Text);

      cmd = new SqlCommand("update UserInfo set Balance = @NewBal where UserName = @UserName", cnn);
      cmd.Parameters.AddWithValue("@NewBal", dblNewBal);
      cmd.Parameters.AddWithValue("@UserName", ddlUser.Text);
      cmd.ExecuteNonQuery();

      ShowBalInLabel();

     }
    }
}

Sunday, February 9, 2014

ExecuteScalar with Asp .Net


CREATE TABLE Users(
    UserId int IDENTITY primary key,
    UserName varchar(50),
    Password varchar(50))

using System.Data.SqlClient;
using System.Configuration;


SqlConnection cnn;

protected void btnLogin_Click(object sender, EventArgs e)
{
using (cnn = new SqlConnection(
@"Data Source=.\sqlexpress;Initial Catalog=CustomLogin;Integrated Security=True"))
{
  SqlCommand cmd;
  cnn.Open();
  cmd = new SqlCommand(
   "select Count(*) from Users where UserName = @UserName and Password = @Password", 
   cnn);
  

  cmd.Parameters.AddWithValue("@UserName", txtUserName.Text);
 cmd.Parameters.AddWithValue("@Password", txtPassword.Text);
 int intCount = Int32.Parse( cmd.ExecuteScalar().ToString());

 if (intCount == 1)
  Response.Redirect("Welcome.aspx");
 else
  lblMessage.Text = "Invalid credentials";
}

Saturday, February 8, 2014

Asp .Net MVC @Html.DropDownList

Hard coding the Drop Down List
Countries
@Html.DropDownList("Countries",
     new  List<SelectListItem> {
     new SelectListItem {Text = "India" },
     new SelectListItem {Text = "US" }
})

Fillling DropDownList with Database data

public ActionResult Index()
{
    ContactGroups cg = new ContactGroups();
    var cgs = cg.GetGroups();
    ViewBag.groups =new SelectList(cgs,"GroupId","GroupName");

    return View();
}
<div>
    @Html.DropDownList("groups", "select Group") 

</div>
Here groups is the name of ViewBag.

Asp .Net MVC BeginForm


@using(Html.BeginForm())
{
   @Html.TextBox("txtName")
    <BR />
    <input type ="Submit" />
}

Friday, February 7, 2014

Linq to Objects

This blog is a continuation of http://shalvinpd.blogspot.in/2008/12/linq-to-object.html.


Or |
List<string> glsAspNet = new List<string> { "Shalvin", "Manoj", "Simil", "Tina" };

 protected void btnContains_Click(object sender, EventArgs e)
 {
    var C = from p in glsAspNet
            where p.Contains("a") | p.StartsWith("S")
            select p;

    ListBox1.DataSource = C;
    DataBind();
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
List<string> obj = new List<string>{"Anjali", "Anju", "Ammu", "athira", "Minu",
    "gayathri", "gopu", "anu"};
protected void Page_Load(object sender, EventArgs e)
{
    ListBox1.Items.Clear();
//    var Astart = from p in obj where p.StartsWith("A") select p;
//    ListBox1.DataSource = Astart;
//    DataBind();

}
protected void btnContains_Click(object sender, EventArgs e)
{
    ListBox1.Items.Clear();
    var res = from p in obj
                where p.Contains("a")
                select p;
    ListBox1.DataSource = res;
    DataBind(); 
}
protected void btnEndsWith_Click(object sender, EventArgs e)
{
        
    ListBox1.Items.Clear();
    var res = from p in obj
                where p.EndsWith ("a")
                select p;
    ListBox1.DataSource = res;
    DataBind();
}
protected void btnFirst_Click(object sender, EventArgs e)
{

    ListBox1.Items.Clear();
    var res = (from p in obj
                select p).First();
    //ListBox1.DataSource = res;
    //DataBind();
    Response.Write(res);
}

protected void Button4_Click(object sender, EventArgs e)
{
    ListBox1.Items.Clear();
    var res = from p in obj
                where p.StartsWith("A") | p.StartsWith("g")
                select p;
    ListBox1.DataSource = res;
    DataBind();
       
}
protected void btnAnd_Click(object sender, EventArgs e)
{

    ListBox1.Items.Clear();
    var res = from p in obj
                where p.StartsWith("A") & p.EndsWith("a")
                select p;
    ListBox1.DataSource = res;
    DataBind();
}
protected void btnOrderBy_Click(object sender, EventArgs e)
{
    ListBox1.Items.Clear();
    var res = from p in obj
                orderby p
                select p;
    ListBox1.DataSource = res;
    DataBind();
}

protected void btnOrderByDescending_Click(object sender, EventArgs e)
{

    ListBox1.Items.Clear();
    var res = from p in obj
                orderby p descending
                select p;
    ListBox1.DataSource = res;
    DataBind();
}
protected void btnContainsOrderBy_Click(object sender, EventArgs e)
{

    ListBox1.Items.Clear();
    var res = from p in obj
                where p.Contains("a")
                orderby p 
                select p;
    ListBox1.DataSource = res;
    DataBind();
}


protected void Button9_Click(object sender, EventArgs e)
{
    ListBox1.Items.Clear();
    var res = from p in obj
                where p.Contains("a")|p.StartsWith("A")
                orderby p
                select p;
    ListBox1.DataSource = res;
    DataBind();
}
protected void btnTake_Click(object sender, EventArgs e)
{

    ListBox1.Items.Clear();
    var res = (from p in obj
                select p).Take(5);
    ListBox1.DataSource = res;
    DataBind();
}
protected void btnTake2_Click(object sender, EventArgs e)
{

    ListBox1.Items.Clear();
    var res = (from p in obj where p.StartsWith("A")
                select p).Take(5);
    ListBox1.DataSource = res;
    DataBind();
}
protected void btnSkip_Click(object sender, EventArgs e)
{
    ListBox1.Items.Clear();
    var res = (from p in obj
              select p).Skip(5);
    ListBox1.DataSource = res;
    DataBind();
}
protected void btnStartsWith2_Click(object sender, EventArgs e)
{
    ListBox1.Items.Clear();
    var res = obj.Where(p => p.StartsWith("A"));
    ListBox1.DataSource = res;
    DataBind();
}
}


Linq and Collection of Class

List<Trainee> glTrainee = new List<Trainee>
{
 new Trainee{Name = "Rejitha", Location = "Varkala", Hobby ="Music"},
 new Trainee{Name = "Sarath", Location = "Sub Station", Hobby = "Reading"},
 new Trainee{Name = "Anish", Location = "Sub Station", Hobby= "Swimming"},
  new Trainee{Name ="Anoop" , Location ="Attinkuzhi", Hobby="Blogging"},
   new Trainee{Name = "Vishnu", Location ="Front Gate", Hobby = "Photography"},
    new Trainee{Name ="Sanal", Location ="Police Station", Hobby = "Talking"},
    new Trainee{Name = "Manikandan", Location = "Police Station", Hobby = "Cricket"},
     new Trainee{Name = "Saritha", Location = "Sub Station", Hobby="Reading"},
};
protected void Page_Load(object sender, EventArgs e)
{
 if (!IsPostBack)
 {
   var Loc = glTrainee.Select(p => p.Location).Distinct().ToList();
    ddlLocation.DataSource = Loc;
    DataBind();
 }
}
protected void btnSubStation_Click(object sender, EventArgs e)
{
 var S = from p in glTrainee
         where p.Location == "Sub Station"
         select p;
 GridView1.DataSource = S;
 DataBind();

}
protected void btnStartsWithA_Click(object sender, EventArgs e)
{
 var s = glTrainee.Where(p => p.Name.StartsWith("A"));

 GridView1.DataSource = s;
 DataBind();
}
protected void ddlLocation_SelectedIndexChanged(object sender, EventArgs e)
{
 var s = from p in glTrainee
         where p.Location == ddlLocation.Text
         select p;
 GridView1.DataSource = s;
 DataBind();
}
protected void btnSelect_Click(object sender, EventArgs e)
{
 var s = from p in glTrainee
         select new {p.Name, p.Location};
GridView1.DataSource = s;
 DataBind();
}
protected void btnSortByLocation_Click(object sender, EventArgs e)
{
 var s = from p in glTrainee
         orderby p.Location
         select p;
  GridView1.DataSource = s;
 DataBind();
}
protected void btnSortByLocationThenByName_Click(object sender, EventArgs e)
{
 var s = from p in glTrainee
         orderby p.Location, p.Name
         select p;
 GridView1.DataSource = s; 
 DataBind();
}
protected void btnSingle_Click(object sender, EventArgs e)
{
 //var s = from p in glTrainee
 //        where p.Name == "Manikandan"
 //select p;

 var s = (from p in glTrainee
         where p.Name == "Manikandan"
         select p).Single();

 Label1.Text = s.Name;
 //GridView1.DataSource = s;
 //DataBind();
}
protected void btnSingleOrDefault_Click(object sender, EventArgs e)
{
 var s = (from p in glTrainee
          where p.Name == "Manikandans"
          select p).SingleOrDefault();
 if( s != null)
 Label1.Text = s.Name;

}

Thursday, February 6, 2014

Making a Div Right Align


<div style="float:right">
    Shalvin P D
</div>

Asp .Net Balance Updating with Session Variable

In the Blog Creating and Consuming Class Library in C#, Object Initializer I have demonstrated creating a simple Bank with Deposit and Withdraw functionality in Windows Forms.
Creating that in Windows Forms is straight forward.
When it comes to Web Forms (Asp .Net) you have to maintain sessions to get the same functionality.


int Balance = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ShowBal();
        }
        else
        {
            if (Session["Balance"] != null)
                Balance = (int)Session["Balance"];
        }
    }

    private void ShowBal()
    {
        lblCurBal.Text = Balance.ToString();
        txtAmount.Text = "";
        txtAmount.Focus();
    }
    protected void btnDeposit_Click(object sender, EventArgs e)
    {
        Balance += Int32.Parse(txtAmount.Text);
        Session["Balance"] = Balance;
        ShowBal();
    }
    protected void btnWithras_Click(object sender, EventArgs e)
    {
        Balance -= Int32.Parse(txtAmount.Text);
        Session["Balance"] = Balance;
        ShowBal();
    }
.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
        <asp:Label ID="Label1" runat="server" Text="Balance"></asp:Label>
&nbsp;<asp:Label ID="lblCurBal" runat="server"></asp:Label>
        <br />
        <br />
        <asp:Label ID="Label2" runat="server" Text="Amount"></asp:Label>
&nbsp;
        <asp:TextBox ID="txtAmount" runat="server"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="btnDeposit" runat="server" OnClick="btnDeposit_Click" Text="Deposit" />
&nbsp;<asp:Button ID="btnWithras" runat="server" OnClick="btnWithras_Click" Text="Withdraw" />
    </form>
</body>
</html>
 
Courtesy : Arjun Pandavath, Speridian Technologies

Monday, January 27, 2014

ASP .Net GridView Editing


<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
    <Columns>
         <asp:BoundField DataField="Contactid" HeaderText="CId" ReadOnly="True" />
         <asp:BoundField DataField="contactname" HeaderText="name" />
         <asp:BoundField DataField="Phone" HeaderText="Phone" />
         <asp:CommandField ShowEditButton="True" />
         <asp:CommandField ShowDeleteButton="True" />
    </Columns>
</asp:GridView>



using System.Configuration;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection cnn = null;

    protected void Page_Load(object sender, EventArgs e)
    
    {
        if (!IsPostBack)
        {
            GetData();
        }
    }

    private void GetData()
    {
        using (cnn = new SqlConnection(ConfigurationManager.AppSettings.Get("Cnn")))
        {

            SqlDataAdapter da = new SqlDataAdapter("select ContactId, ContactName, Phone from Contacts", cnn);
            DataSet ds = new DataSet();
            da.Fill(ds, "Co");
            GridView1.DataSource = ds.Tables["Co"];
            DataBind();
        }
    } 
    
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        GetData();

    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        using (cnn = new SqlConnection(ConfigurationManager.AppSettings.Get("Cnn")))
        {
            cnn.Open();
            string id = GridView1.Rows[e.RowIndex].Cells[0].Text;
            string name = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
            string phone = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
            string strSql = "update Contacts set ContactName = '" + name + "', phone = '" +
                phone + "' where ContactId = " + id;

            SqlCommand cmd = new SqlCommand(strSql, cnn);
            cmd.ExecuteNonQuery();
            GridView1.EditIndex = -1;
            GetData();
        }

    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        GetData();
    }
}

Saturday, January 25, 2014

C# Method Overloading


 public void Display()
  {
    Response.Write("Hello " + "<br/>");
  }
  public void Display(string Name)
  {
    Response.Write("Hello " + Name + "<br/>");
  }
  public void Display(string Name, string Location)
  {
    Response.Write("Hello " + Name + " located at " + Location + "<br/>");
  }

  protected void Button1_Click(object sender, EventArgs e)
  {
    Display();
  }
  protected void Button2_Click(object sender, EventArgs e)
  {
    Display("Aiju");
  }
  protected void Button3_Click(object sender, EventArgs e)
  {
    Display("Sarath", "Trissur");
  }

C# Abstract Class


public abstract class CalcAb
{
  public abstract int Add(int i, int j);

  public int Subtract(int i, int j)
  {
    return i - j;
  }
}

public class Calc : CalcAb
{
  public override int Add(int i, int j)
  {
    return i + j;
  }
}

protected void Page_Load(object sender, EventArgs e)
{
  Calc c = new Calc();
  Response.Write(c.Add(78, 56));
  Response.Write("<br/>");
  Response.Write(c.Subtract(78, 67));
}