Shalvin Interests

Wednesday, October 14, 2015

AngularJS for .Net Developers : Routes and AngularJS Seed

Just like Asp .Net MVC AngularJS too have Routes.
In AngularJS the difference is that it is client side Routing. Here you specify the Fragment Identified identified by #. The difference in using Fragment Identifier is it the Web Application is not making a round trip to the server which is an essential concept in Single Page Application.


A Module can have Config. Config in turn have Route.
In the previous example we hard coded Controller into View.

$routeProvider Service

The $routeProvider service is used to define a route.

AngularJS Seed

Instead of  manually creating the structure for AngularJS project we can make use of AngularJS Seed. AngularJS Seed will create the necessary routes, views, scripts, etc. for you.



Here I am adding AngularJS Seed to an empty Web Application Project.





App.js

App.js is present inside js folder.

angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives']).
  config(['$routeProvider', function($routeProvider) {
      $routeProvider
          .when('/view1', {
          template: '/partials/partial1.html',
          controller: MyCtrl1});
      $routeProvider
          .when('/view2', {
              template: '/partials/partial2.html',
              controller: MyCtrl2
          });
      $routeProvider
          .otherwise({ redirectTo: '/view1' });
  }]);


$routeProvider is having a when function which expects a Fragment Identifier, template, controller.

Template is a View or a piece of html functionality. Here when you access view1 fragment you will be accessing partial1.html template.



_LayoutAngular.cshtml

<!doctype html>
<html ng-app="myApp">
<head>
  <meta charset="utf-8">
  <title>My AngularJS App</title>
  <link rel="stylesheet" href="/css/app.css"/>
</head>
<body>
  <ul class="menu">
    <li><a href="#/view1">view1</a></li>
    <li><a href="#/view2">view2</a></li>
  </ul>

  @RenderBody()
  
  <div>Angular seed app: v<span app-version></span></div>

  <script src="/lib/angular/angular.js"></script>
  <script src="/js/app.js"></script>
  <script src="/js/services.js"></script>
  <script src="/js/controllers.js"></script>
  <script src="/js/filters.js"></script>
  <script src="/js/directives.js"></script>
</body>
</html>


Inside _LayouAngular.cshtml layout there are Urls.

ng-view

ng-view is the AngularJS equivalent of RenderBody in MVC or ContentPlaceHolder in Web
Forms.

Index.cshtml
@{
    Layout = "~/Views/Shared/_LayoutAngular.cshtml";
}
<h3>Shalvin P D - Index</h3>

<ng-view></ng-view>


Index.cshtml present inside Views/Angular is having the ng-view directive. Here the template will get injected.


Monday, August 24, 2015

Web Forms Contact Management with Entity Framework

We are going to revisit the Contact Management System in Web Forms with Entity Framework. The details of Contact Management is taken up in this blog. There are basically two tables, viz. ContactGroups and  Contacts.

I am using Asp .Net Web Forms Site so that there will be inbuilt Master Page.

I am using Entity Framework,  Generate from Database option, the details I have blogged here.

I  the Default.aspx I am using a GridView to display the Group details.

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
   
</asp:Content>

<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
    <p>
        <a href="InsertGroup.aspx">Insert Group</a> <a href="EditDeleteGroups.aspx">Edit/Delete Groups</a>&nbsp;</p>
<p>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
        <Columns>
            <asp:BoundField DataField="GroupName" HeaderText="Group Name" />
        </Columns>
    </asp:GridView>
    <br />
</p>
    </asp:Content>

 ContactManagementEntities ctx = new ContactManagementEntities();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = ctx.ContactGroups.ToList();
            DataBind();

        }
    }



Inserting Records to Parent Table


<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" Runat="Server">
    <p>
        <asp:Label ID="lblMessage" runat="server"></asp:Label>
        <br />
        <asp:Label ID="Label1" runat="server" Text="Group Name"></asp:Label>
        <asp:TextBox ID="txtGroupName" runat="server"></asp:TextBox>
    </p>
    <p>
        <asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click" Text="Save" />
    </p>
</asp:Content>


public partial class InsertGroup : System.Web.UI.Page
{
    ContactManagementEntities ctx = new ContactManagementEntities();

   
    protected void btnSave_Click(object sender, EventArgs e)
    {
        var c = (from p in ctx.ContactGroups
                 where p.GroupName == txtGroupName.Text
                 select p).Count();
       
        if (c != 0)
        {
            lblMessage.Text = "Value already exist";
            txtGroupName.Text = "";
            txtGroupName.Focus();
        }
        else
        {

            ContactGroup cg = new ContactGroup { GroupName = txtGroupName.Text };
            ctx.ContactGroups.Add(cg);
            ctx.SaveChanges();
            Response.Redirect("default.aspx");
           
        }
    }
}

Here I am checking for uniqueness of entered value.


Edit and Delete Contact Groups


<asp:Content ID="Content2" ContentPlaceHolderID="FeaturedContent" Runat="Server">
    <p>
        <br />
        Select Group
        <asp:DropDownList ID="ddlGroup" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlGroup_SelectedIndexChanged">
        </asp:DropDownList>
    </p>
    <p>
        Group Name<asp:TextBox ID="txtGroupName" runat="server"></asp:TextBox>
    </p>
    <p>
        <asp:Button ID="btnEdit" runat="server" OnClick="btnEdit_Click" Text="Edit" />
&nbsp;<asp:Button OnClientClick ="return confirm('Do you wan't to Delete')" ID="btnDelete"  runat="server" OnClick="btnDelete_Click" Text="Delete" />
    </p>
    <p>
        &nbsp;</p>
</asp:Content>

public partial class EditDeleteGroups : System.Web.UI.Page
{
    ContactManagementEntities ctx = new ContactManagementEntities();
    protected void Page_Load(object sender, EventArgs e)
    {
        if(! IsPostBack )
        {
            ddlGroup.DataSource = ctx.ContactGroups.ToList();
            ddlGroup.DataTextField = "GroupName";
            ddlGroup.DataValueField = "GroupId";
            DataBind();
        }
    }
    protected void ddlGroup_SelectedIndexChanged(object sender, EventArgs e)
    {
         var Grp = GetGroup();
        txtGroupName.Text = Grp.GroupName;
    }

    private ContactGroup GetGroup()
    {
        int intGroupId = Int32.Parse(ddlGroup.SelectedValue.ToString());
        var Grp = (from p in ctx.ContactGroups
                   where p.GroupId == intGroupId
                   select p).FirstOrDefault();
        return Grp;
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        try
        {

            var Grp = GetGroup();

            ctx.ContactGroups.Remove(Grp);
            ctx.SaveChanges();
            Response.Redirect("Default.aspx");
        }
        catch (DbUpdateException due)
        {
            lblMessage.Text = String.Format("There is records in the Contacts table which points to this '{0}'. First delete the the records in Contacts table refering to {0} and then delete the record.", txtGroupName.Text);
        }
        catch (Exception ex)
        {
            lblMessage.Text = "An error has occured";
        }
    }
    protected void btnEdit_Click(object sender, EventArgs e)
    {
        var Grp = GetGroup();
        Grp.GroupName = txtGroupName.Text;
        ctx.SaveChanges();
        Response.Redirect("Default.aspx");
    }
}

Here I am writing a function called GetGroup which returns a single Contact Group based on the selection from Drop Down List.

On selecting an item from DropDownList I am filling the TextBox(es) with its corresponding data.

I  have also added exception handling to Delete so that Foreign key violation error is handled.


Wednesday, February 11, 2015

SharePoint SPWeb Class

using Microsoft.SharePoint;

 static void Main(string[] args)
        {
            SPSite s = new SPSite("http://toshiba-pc");

            SPWeb w = s.RootWeb;
            Console.WriteLine(w.Title );
            Console.WriteLine(w.CurrentUser);

            Console.WriteLine("");

         

            Console.WriteLine("All users");
             foreach (var item in w.AllUsers )
            {
                Console.WriteLine(item);
            }

             Console.WriteLine("Fields");
             foreach (var item in w.Fields)
             {
                 Console.WriteLine(item);
             }

        }

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();

     }
    }
}