Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts

Monday, February 10, 2014

ASP .Net Membership and LINQ

I am going to demonstrate working with Asp .Net Membership and LINQ with a simple Bank comprising of only Deposit, Withdraw and Balance checking functionality.

The application is having two roles: Admin and Secured users.  The Admin will be the Bank official who will be performing depositing and withdraw functionality for the user.




The Secured used can login and view their Balance.

The User Information  is stored in User Info  table which is integrated into Membership and Roles tables.


CREATE TABLE [UserInfo](
    [UserId] [int] IDENTITY(1,1),
    [UserName] [varchar],
    [Balance] [numeric](18, 2))

<connectionStrings>
    <add name="DefaultConnection" providerName="System.Data.SqlClient" 
connectionString="Data Source=.\sqlexpress;InitialCatalog=ShalvinBankSimple;Integrated Security=True"/>
</connectionStrings>

 In the class I am defining the class corresponding to the table. Functions for retrieving generic list of  UserInfo is GetUserInfo. Likewise I am defining functions for retieving User Information, Deposit and Withdraw functionalities.
UserInfo.cs
public class UserInfo
{
 public int UserId { get; set; }
 public string UserName { get; set; }
 public double Balance { get; set; }

 SqlConnection cnn;
 public List<UserInfo> GetUserInfo()
 {
  using (cnn = new SqlConnection(
   ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
  {
   cnn.Open();

   List<UserInfo> glUserInfo = new List<UserInfo>();

   SqlCommand cmd = new SqlCommand("select * from UserInfo", cnn);
   SqlDataReader dr;
   dr = cmd.ExecuteReader();
   while (dr.Read())
   {
    UserInfo ui = new UserInfo
    {
     UserId = Int32.Parse(dr["UserId"].ToString()),
     UserName = dr["UserName"].ToString(),
     Balance = double.Parse(dr["Balance"].ToString())
    };
    glUserInfo.Add(ui);
   }

   return glUserInfo;
  }
 }

 public void InsertUser(UserInfo u)
 {
  using (cnn = new SqlConnection(
   ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
  {
   cnn.Open();
   SqlCommand cmd = new SqlCommand("Insert into UserInfo values (@UserName, @Balance)", cnn);
   cmd.Parameters.AddWithValue("@UserName", u.UserName);
   cmd.Parameters.AddWithValue("@Balance", u.Balance);
   cmd.ExecuteNonQuery();
  }
 }

 public UserInfo GetInfoByName(string UserName)
 {
  var UserI = (from p in GetUserInfo()
               where p.UserName == UserName
               select p).SingleOrDefault();
  return UserI;
 }

 public void Deposit(UserInfo u)
 {
  using (cnn = new SqlConnection(
  ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
  {
   cnn.Open();

   SqlCommand cmd = new SqlCommand("update Userinfo set Balance = Balance + @Balance where UserName=@UserName", cnn);
   cmd.Parameters.AddWithValue("@UserName", u.UserName);
   cmd.Parameters.AddWithValue("@Balance", u.Balance);

   cmd.ExecuteNonQuery();
  }
 }
 public void Withdraw(UserInfo u)
 {
  using (cnn = new SqlConnection(
  ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
  {
   cnn.Open();

   SqlCommand cmd = new SqlCommand("update Userinfo set Balance=Balance-@balance where UserName=@UserName", cnn);
   cmd.Parameters.AddWithValue("@username", u.UserName);
   cmd.Parameters.AddWithValue("@balance", u.Balance);

   cmd.ExecuteNonQuery();
  }
 }
}

Register.aspx.cs
UserInfo objUserInfo = new UserInfo();
protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
{
 UserInfo ui = new UserInfo{
  UserName = CreateUserWizard1.UserName,  Balance = 0 };
 objUserInfo.InsertUser(ui);
}

Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
 if (User.IsInRole("Admin"))
  Response.Redirect("Admin/AdminHome.aspx");
 else if (User.Identity.IsAuthenticated)
  Response.Redirect("Secured/SecuredHome.aspx");
}

AdminHome.aspx.cs
using System.Linq;
public partial class Admin_AdminHome : System.Web.UI.Page
{
 UserInfo objUser = new UserInfo();
    protected void Page_Load(object sender, EventArgs e)
    {
     if (!IsPostBack)
     {
      ddlUsers.DataSource = objUser.GetUserInfo();
      ddlUsers.DataTextField = "UserName";
      DataBind();
     }
    }
    protected void ddlUsers_SelectedIndexChanged(object sender, EventArgs e)
    {
     ShowBalanceForUser();
    }
    protected void btnDeposit_Click(object sender, EventArgs e)
    {
     objUser.Deposit(new UserInfo { UserName = ddlUsers.SelectedItem.ToString(), Balance = Double.Parse(txtAmount.Text) });
     ShowBalanceForUser();
    }

    private void ShowBalanceForUser()
    {
     var User = objUser.GetInfoByName(ddlUsers.Text);
     lblCurBal.Text = User.Balance.ToString();
    }
    protected void btnWithdraw_Click(object sender, EventArgs e)
    {
     objUser.Withdraw(new UserInfo { UserName = ddlUsers.SelectedItem.ToString(), Balance = Double.Parse(txtAmount.Text) });
     ShowBalanceForUser();
    }
} 

SecureHome.aspx.cs
UserInfo objUserInfo = new UserInfo();
    protected void Page_Load(object sender, EventArgs e)
    {
     var User = objUserInfo.GetInfoByName(Membership.GetUser().ToString());

     lblCurBal.Text = User.Balance.ToString();
    }

Wednesday, December 10, 2008

Linq to Xml (Code Snippets)

Linq to Xml enables you to query an Xml document using the familiar LINQ syntax. Linq to Xml features and found within System.Xml.Linq namespace.
System.Xml.Linq introduces a series of objects such as XDocument, XElement and XAttributes which makes creating XML document a breeze.

XAttribute
private void btnXElement_Click(object sender, RoutedEventArgs e)
{
XElement xe = new XElement(new XElement("Shalvin",
new XElement("Students",
new XElement("Name", "Shalvin"))));
textBox1.Text = xe.ToString();

}


XElement


using System.Xml.Linq;

private void Form1_Load(object sender, EventArgs e)
{
XElement xml = new XElement("contacts",
new XElement("contact",
new XAttribute("contactId", "2"),
new XElement("firstName", "Shalvin"),
new XElement("lastName", "PD")
),
new XElement("contact",
new XAttribute("contactId", "3"),
new XElement("firstName", "Praseed"),
new XElement("lastName", "Pai")
)
);
textBox1.Text = xml.ToString();
}


XDocument

using System.Xml.Linq;

protected void Page_Load(object sender, EventArgs e)
{
XDocument xd = new XDocument();
XElement contacts =
new XElement("contacts",
new XElement("contact",
new XElement("name", "Shalvin"),
new XElement("Location", "Kochi")
),
new XElement("contact",
new XElement("name", "Viju"),
new XElement("Location", "Trichur")
)
);
xd.Add(contacts);
xd.Save("c:\\Shalvin.xml");
System.Diagnostics.Process.Start("iexplore", "c:\\Shalvin.xml");
}

Output

<?xml version="1.0" encoding="utf-8"?>
<contacts>
<contact contactId="2">
<firstName>Shalvin</firstName>
<lastName>P D</lastName>
</contact>
<contact contactId="3">
<firstName>Praseed</firstName>
<lastName>Pai</lastName>
</contact>
</contacts>

XDocument Parse

private void button3_Click(object sender, RoutedEventArgs e)
{
XDocument xd = XDocument.Parse(@"<contacts>
<contact contactId='2'>
<firstName>Shalvin</firstName>
<lastName>P D</lastName>
</contact>
<contact contactId='3'>
<firstName>Praseed</firstName>
<lastName>Pai</lastName>
</contact>
</contacts>");

textBox1.Text = xd.ToString();

}


Querying an Xml Document














using System.Xml.Linq;
private void Form1_Load(object sender, EventArgs e){
XDocument xmlFile = XDocument.Load("c:\\Shalvin.xml");
var query = from c in xmlFile.Elements("contacts").Elements("contact").Elements("name")

select c;
foreach (XElement nam in query)

{
listBox1.Items.Add(nam);
}

}

Related Blogs
Linq to Objects
Linq to Sql
.Net Working with Xml

Monday, December 8, 2008

Linq to Objects

LINQ (Language Integrated Query) is a Microsoft .NET framework component that adds native data querying capabilities to C# and Visual Basic .NET (VB.NET) programming languages.
It allows developers to write database-like queries against various data sources including in-memory objects, SQL databases, and XML data sources.
LINQ enables developers to perform queries in a more concise, readable and expressive way, compared to traditional loops and conditional statements.
This blog assumes that you are know Type Inference in C#, Generics and Collection Initializer.

private void Form1_Load(object sender, EventArgs e)
{
List<string> interests = new List<string>{"Music", "Singing", "Swimming"};
var result = from w in interests
where w.Contains("ing")
select w;

foreach (string s in result)
listBox1.Items.Add(s);
}


Lambda
protected void btnLambda_Click(object sender, EventArgs e)
{
   List<string> interests = new List<string>{"Music", "Singing", "Swimming"};
   var result = interests.Where(p => p.Contains("ing"));
        
   foreach (string s in result)
     ListBox1.Items.Add(s);
}


The Linq query retrives all values form Generic List that ends with "ing". You can use Linq with any objects that implements IEnumerable or Generic IEnumerable interface.

StartsWith
private void btnStartsWith_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Clear();
var ms = from p in interests
            where p.StartsWith("M")
            select p;
foreach (string s in ms)
    listBox1.Items.Add(s);
}

EndsWith
private void btnEndWith_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Clear();
var ms = from p in interests
            where p.EndsWith("g")
            select p;
foreach (string s in ms)
    listBox1.Items.Add(s);
}


Equals
private void btnEquals_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Clear();
var ms = from p in interests
            where p.Equals("Music")
            select p;
foreach (string s in ms)
    listBox1.Items.Add(s);
}


First
First can be used to extract only the first item in the collection.
private void btnFirst_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Clear();
var ms = (from p in interests
            select p).First();
listBox1.Items.Add(ms);
}

Last
private void btnLast_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Clear();
var ms = (from p in interests
            select p).Last();
listBox1.Items.Add(ms);
}

Count
Using the Count operator I am taking a counts of items inside the Generic List. I will get a value 3.

private void btnCount_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Clear();
var ms = (from p in interests
            select p).Count();
listBox1.Items.Add(ms);
}

Count of EndsWith
Here I am taking a count of items ending with "ing". I will get an output of 2 ie. the count of "Swimming" and "Singing".

private void btnCountEndWithIng_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Clear();
var ms = (from p in interests
          where p.EndsWith("ing")  
          select p).Count();
listBox1.Items.Add(ms);
}

Count Equals

private void btnCountEquals_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Clear();
var ms = (from p in interests
where p.Equals("Music")
          select p).Count();
listBox1.Items.Add(ms);
}

Linq and Generic List of Integer
Having seen working with Generic List of string let's turn out attention to Generic List of Inteters. 


List<int> gliMarks = new List<int> { 98, 56, 88, 79, 96 };

GreaterThan Operator

private void btnShowGreaterThan90_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Clear();
var G90 = from p in gliMarks
    where p > 90
    select p;
listBox1.ItemsSource = G90;
}


Sum

private void btnSum_Click(object sender, RoutedEventArgs e)
{
    listBox1.Items.Clear();
           
    var vSum = (from p in gliMarks
                select p).Sum();
    listBox1.Items.Add(vSum);
}



Average

private void btnAverage_Click(object sender, RoutedEventArgs e)
{
    listBox1.Items.Clear();
    var Avg = (from p in gliMarks
                    select p).Average();
    listBox1.Items.Add(Avg);
}

Max

private void btnMaximum_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Clear();
var Maxi = (from p in gliMarks
            select p).Max();
listBox1.Items.Add(Maxi);
}

Or

private void btnSOr_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Clear();
var vOr = from p in gliMarks
    where p== 98 | p == 88 
    select p;
listBox1.ItemsSource = G90;
}



Linq on Collection of Objects

class Session
{
public string Speaker { get; set; }
public string SessionName { get; set; }
}

List<Session> glSessions = new List<Session>{
new Session{Speaker = "Shalvin P D", SessionName= "Entity Framework 4"},
new Session{Speaker="Arun Kumar", SessionName="Powershell"}};

var G = from p in glSessions
where p.Speaker == "Shalvin P D"
select new { p.Speaker, p.SessionName };


dataGrid1.ItemsSource = G.ToList();
}

Sunday, October 26, 2008

LINQ to Sql

I am going to demonstrate LINQ to Sql by writing code.

Support you have a table called Categories in Shalvin database you need to first create a Entity. An Entity is a class that represents a Table or a view in the database.

Create a class as follows:
Set a reference to Data.Linq.

using System.Data.Linq.Mapping;

[Table]
public class Categories
{
[Column(IsPrimaryKey=true, IsDbGenerated=true)]
public int CategoryId { get; set; }

[Column]
public string CategoryName { get; set; }

[Column]
public string Description { get; set; }
}

Each property should have Column Atribute. I am also setting values of IsPrimaryKey and IsDbGenerated for CategoryId column. Editing is possible only if IsPrimaryKey is set to true. IsDbGenerated Indicated that it is an Identity column.


In the asp .net page :

using System.Data.Linq;
protected void Page_Load(object sender, EventArgs e)
{
string ConString = "Integrated Security=sspi;Initial Catalog=Shalvin";
DataContext db = new DataContext(ConString);
var tMovies = db.GetTable<categories>();
GridView1.DataSource = tMovies;
DataBind();
}Now suppose you are interested only in viewing the Categories table with CategoryName 'Confections'.

GridView1.DataSource = tMovies.Where(m => m.CategoryName.Contains("Beverages"));
The DataContext is the source of all entities mapped over a database connection. It tracks changes that you made to all retrieved entities .

Linq to Sql with Visual Studio Tools

Having seen the internals lets turn our attention to the Visual Studio Support of Linq to Sql.
Here I have started an Empty Visual Studio Project and Added a Linq to Sql Classes from the Add New Item Dialog. I have renamed it AirLines.dbml



On to the design surface it is possible to drag the table from Database Explorer.



That's all I have to do and I am ready to do CRUD operation with the selected tables.

AirLinesDataContext context = new AirLinesDataContext();
protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
    GridView1.DataSource = context.Locations;

    DropDownList1.DataSource = context.Locations;
    DropDownList1.DataTextField = "LocationName";
    DropDownList1.DataValueField = "LocationId";

    DataBind();
  }
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
  Response.Write(DropDownList1.SelectedValue.ToString());
}

protected void btnInsertLocation_Click(object sender, EventArgs e)
{
  var loc = new Location { LocationName = "London", Latitude =67 };
  context.Locations.InsertOnSubmit(loc);
  context.SubmitChanges();
}


Related Blogs
Linq to Objects
Linq to Xml (Code Snippets)

Wednesday, April 16, 2008

Generics and Collection Initializer in .Net

Before explaining Generics lets take up an example of ArrayList.

ArrayList

using System.Collections;

int intTotal = 0;
ArrayList alMarks = new ArrayList();
private void btnTotal_Click(object sender, EventArgs e)
{
alMarks.Add(98);
alMarks.Add(99);
alMarks.Add(89);
//alMarks.Add("Shalvin");

foreach (int i in alMarks)
intTotal += i;

MessageBox.Show(intTotal.ToString());
}



'VB .Net
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim intTotal As Integer = 0
Dim alMarks As New ArrayList()
alMarks.Add(98)
alMarks.Add(99)
alMarks.Add(89)
For Each i As Integer In alMarks
intTotal += i
Next
MessageBox.Show(intTotal.ToString())
End Sub



It works perfectly fine. Nothing prevents you from giving a string value to array list as shown in the commented line in the code. Because an arraylist accepts parameter of type object. But when you run the application you will receive a runtime error.

Generics
Framework 2.0 introduced generic collection which as type safe collections.

List<int> intMarks = new List<int>();
private void Form1_Load(object sender, EventArgs e)
{
intMarks.Add(98);
intMarks.Add(90);
intMarks.Add(99);

int sum = 0;
foreach (int i in intMarks)
sum += i;
MessageBox.Show(sum.ToString());
}


VB.Net
Dim intMarks As New List(Of Integer)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
intMarks.Add(98)
intMarks.Add(90)
intMarks.Add(99)

Dim sum As Integer = 0

For Each i As Integer In intMarks
sum += i
Next
MessageBox.Show(sum.ToString())
End Sub

Now if you try to give a string value to the the generic list you will get a compiler error which proves the fact that generics are type safe.

C# 3.0 Collection Initializer
With C# 3.0 it is possible to initialize a list as follows:



which is undoubtedly a great code saver.

Generic List of Custom Class

class Session
{
public string Speaker { get; set; }
public string SessionName { get; set; }
}


List<Session> glSessions = new List<Session>{
new Session{Speaker = "Shalvin P D", SessionName= "Entity Framework 4"},
new Session{Speaker="Praseed Pai", SessionName="Powershell"}};

dataGrid1.ItemsSource = glSessions;


Related Blog
Linq to Objects
Hashtable and DictionaryEntry ReadOnlyCollectionBase Class