Mesosphere’s new data center mother brain will blow your mind

Gigaom

Mesosphere has been making a name for itself in the the world of data centers and cloud computing since 2013 with its distributed-system smarts and various introductions of open-source technologies, each designed to tackle the challenges of running tons of workloads across multiple machines. On Monday, the startup plans to announce that its much-anticipated data center operating system — the culmination of its many technologies — has been released as a private beta and will be available to the public in early 2015.

As part of the new operating system’s launch, [company]Mesosphere[/company] also plans to announce that it has raised a $36 million Series B investment round, which brings its total funding to $50 million. Khosla Ventures, a new investor, drove the financing along with Andreessen Horowitz, Fuel Capital, SV Angel and other unnamed entities.

Mesosphere’s new data center operating system, dubbed DCOS, tackles the complexity behind trying to…

View original post 1,120 more words

Advertisements

ASP.NET MVC CRUD Operations with entity framework (Scaffolding)

In this article I will create a simple ASP.NET MVC application with entity framework scaffolding method. Scaffolding is very easy way to quickly build application with create, update and delete features. Scaffolding is a basic structure of code  using which you can edit and customize according to software need. With scaffolding you don’t have to write code for doing basic data manipulation which is done by MVC Razor Engine. It gives you a fast way to get some useful working code, which you can edit and adapt according to your needs. Its actually good start for ASP.NET MVC first timers, instead of getting stuck where to begin you can have basic structure of project. This happened with me, initially I thought scaffolding is just for learning and not much used in live environment but yeah scaffolding can be helpful to quickly build product prototypes. Also If your work involves repeatedly creating similar classes of some kind then you can build your own custom scaffolders with MvcScaffolding package. Lets not get into details of scaffolding, our agenda for this article is to build MVC application using Scaffolding.

I am going to create simple Song Track list Application which will list all the songs with albums and artists name. I am using Visual Studio 2013 with MVC 5 and Entity Framework 6.02. Lets add new project and select ASP.NET Web Application and select MVC template (For other visual studio version MVC project type is separate project type ). This will create new MVC project with basic controllers and views.

For this I am using three models Album,Song,Artist. Below are the entity diagram of three models this is what model will look like.

EDMX

Before going any further lets add some packages to the projects. For this project I am going to add EntityFramework (ER) package, to do this use nuget package manager. In Package Manager Console add following command to get latest version of ER or if you need specific version of ER add version flag in command.

NuGet is an integrated package management tool for adding libraries and tools to .NET projects. More on Nuget go to this link.
 
 

PM> Install-package EntityFramework //installs latest ER to project

PM> Install-package EntityFramework –Version 6.02 //installs ER 6.02 to project

 

Here is the step-by-step instructions.

STEP 1 : Create Model class

Add new folder called Models and add new class to define tables. Below are the three model class code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCScafolding.Models
{
public class Song
{
public int SongID { get; set; }
public string TrackName { get; set; }
public int AlbumID { get; set; }
public int ArtistID { get; set; }
public string Genre { get; set; }
public int ratings { get; set; }

public virtual Album Album { get; set; }
public virtual Artist Artist { get; set; }
}
}
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCScafolding.Models
{
public class Artist
{
public int ArtistID { get; set; }
public string ArtistName { get; set; }
public string MembersName { get; set; }
public System.DateTime DateOfFormation { get; set; }

public virtual ICollection<Song> Songs { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCScafolding.Models
{
public class Album
{
public int AlbumID { get; set; }
public string AlbumName { get; set; }

public virtual ICollection<Song> Songs { get; set; }
}
}
When class with ID as a property is created ER considers it as Primary key. So in above example Album class as AlbumID property will be interpreted as primary key during creation of table.
 
STEP 2: Create Context Class
 
Next step is to create database context class named ArtistContext.cs with DAL folder. This class coordinates Entity Framework functionalities. You can create this class by deriving from the System,Data.Entity.DbContext class. Code for this class is shown below.

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Web;
using MVCScafolding.Models;

namespace MVCScafolding.DAL
{
public class ArtistContext:DbContext
{
public DbSet<Album> Albums { get; set;}
public DbSet<Song> Songs {get; set;}
public DbSet<Artist> Artists {get; set;}



protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}

}
}

In the above code listing you will notice that I have overridden OnModelCreating method. This method will remove or not pluralize the table name on creation. If you don’t do this, the generated tables would be named Songs, Artists, and Albums. It is just a naming convention some developer use plural table names and some don’t. I don’t like to see my table name to be in plural form and create confusion.

 
 
STEP 3: Add Connection String
 
Add connection string in web.config file to mention the database name and instance.  Here I have given the name of the connection string as “ArtistContext” which is same as Database context class name. This is done because ER by default looks for connection string  named as the DbContext class. Even if you don’t mention the connection string it uses default string internally to create database.
<add name="ArtistContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=SongsDb;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\SongsDb.mdf" providerName="System.Data.SqlClient" />    
 
STEP 4: Enable Code First Migration
Using Package Manger Console you can enable migrations for the models. To do this use enable-migrations command entire code is shown below. You have to add contexttypename as flags in my case its ArtistContext.

 

PM> enable-migrations -contexttypename ArtistContext
Checking if the context targets an existing database...
Code First Migrations enabled for project MVCScafolding.

When you execute above command its going to create Migrations folder with Configuration.cs class file with Seed method. This Seed method is called when the database is created and also its get updated  when the data model changes.  Seed method enables you to add sample initial data into the database tables every time its created or changed.
In my application configuration.cs looks like below which contains some data in all the three tables (Album, Song, Artist).
 

namespace MVCScafolding.Migrations
{
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using MVCScafolding.Models;

internal sealed class Configuration : DbMigrationsConfiguration<MVCScafolding.DAL.ArtistContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}

protected override void Seed(MVCScafolding.DAL.ArtistContext context)
{

var artists = new List<Artist>
{

new Artist {ArtistName = "Coldplay", MembersName="Chris Martin, Johnny Buckland, Guy Berryman, Will Champion", DateOfFormation= DateTime.Parse("1996-01-01")},
new Artist {ArtistName = "Green Day", MembersName="Billie Joe Armstrong, Mike Drint, Tre Cool, Jason White", DateOfFormation= DateTime.Parse("1987-01-01")},
new Artist {ArtistName = "Eminem", MembersName="Marshall Bruce Mathers III", DateOfFormation= DateTime.Parse("1990-01-01")},
new Artist {ArtistName = "Lorde", MembersName="Lorde", DateOfFormation= DateTime.Parse("2012-01-01")}
};
artists.ForEach(s => context.Artists.AddOrUpdate(p => p.ArtistName, s));
context.SaveChanges();



var albums = new List<Album> {
new Album {AlbumName = "Hybrid Theory"},
new Album {AlbumName = "A Thousand Suns"},
new Album {AlbumName = "Living Things"},
new Album {AlbumName = "A Rush of Blood to the Head"},
new Album {AlbumName = "Recovery"},
new Album {AlbumName = "Relapse"},
new Album {AlbumName = "Encore"}
};
albums.ForEach(s => context.Albums.AddOrUpdate(p => p.AlbumName, s));
context.SaveChanges();



var songs = new List<Song>
{
new Song {TrackName ="Lost in the Echo" , AlbumID = albums.Single(s=>s.AlbumName == "Living Things").AlbumID, ArtistID=artists.Single(a=> a.ArtistName == "Linkin Park").ArtistID, Genre="Rock", ratings=5 },
new Song {TrackName ="Boulevard of Broken Dreams", AlbumID = albums.Single(s=>s.AlbumName == "American Idiot").AlbumID, ArtistID=artists.Single(a=> a.ArtistName == "Green Day").ArtistID, Genre="Rock", ratings=5 },
new Song {TrackName ="Know Your Enemy", AlbumID = albums.Single(s=>s.AlbumName == "21st Century Breakdown").AlbumID, ArtistID=artists.Single(a=> a.ArtistName == "Green Day").ArtistID, Genre="Rock", ratings=5 },
new Song {TrackName ="Not Afraid", AlbumID = albums.Single(s=>s.AlbumName == "Recovery").AlbumID, ArtistID=artists.Single(a=> a.ArtistName == "Eminem").ArtistID, Genre="Hip Hop", ratings=5 }
};

 



foreach (Song g in songs)
{
var songsInDatabase = context.Songs.Where(
s => s.Artist.ArtistID == g.ArtistID &&
s.Album.AlbumID == g.AlbumID
).SingleOrDefault();

if (songsInDatabase == null)
{
context.Songs.Add(g);
}
}
context.SaveChanges();

}
}
}

Next is to build the project before going to next step.
 
STEP 5: Execute First Migration
 
To execute first migration you have to use add-migration command in package manager console. This command creates a class file in Migrations folder which contains database creation code. In below code listing you will notice I have used InitialCreate in command which is  nothing but file name this can be anything. After execution of command, migrations folder will have filename called [DateStamp]_InitialCreate.
PM> add-migration InitialCreate
Scaffolding migration 'InitialCreate'.
The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration InitialCreate' again.

 

After this you need to apply seed data to newly created database in previous step. To do this command update-database must be executed. This command will run seed method of configuration file.

PM> update-database

Specify the '-Verbose' flag to view the SQL statements being applied to the target database.

Applying explicit migrations: [201402170935556_InitialCreate].

Applying explicit migration: 201402170935556_InitialCreate.

Running Seed method.

 
Note: With update-database you can use –Verbose flag to view what SQl statements being applied to the target database.

 

STEP 6 Creating Controller and Views

This is the final step which is very important and also easy one. First you need to add controller for a corresponding model.  When you add new controller try to follow the MVC convention i.e use controller name same as Model name followed by “Controller”. For e.g controller ArtistController is for Artist model this avoids confusion and makes project better understandable and readable.

In MVC 5, when you add Controller it creates views at the same time. To add new controller right click on Controller folder on Add select Controller this will bring Add Scaffold dialog box in which select MVC5 Controller with Views, using entity framework. Then this will open Add Controller Dialog box in which give controller name then select Model Class and select data context class. For views you need to ensure that Generate Views is checked and click Add button. This will not create controller for given model and but also generates Views with CRUD operations.

I am putting up the screenshots for adding ArtistController, these steps will be same for other Data models.

AddController

 

ControllerDialog

Adding a controller will create controllers with all CRUD operations methods. You can check the controllers code under controller folder also can change the code to adapt the project needs.

Also under views folder you can see there will folder with model name inside there will five different view files each for CRUD operations. For e.g Edit view file is for editing existing records. I am not getting in details in this article as this only explains how you can build simple MVC application using scaffolding. In my next article, I will try to explain controllers and views in details.

 Scaffolding

 

So to build basic MVC application with CRUD Operations using Scaffolding follow above mentioned 6 Steps. You can download complete project from link given below.

Download Demo Project:

https://app.box.com/s/sv86u5milug7fo97n8rw

 
 
 
 
 
 
 

Update and delete data in repeater control

Repeater control is most flexible data control compared to other controls in ASP.Net. It is raw control which can be customized according to our needs. In this article I am going shows how to use repeater control to edit existing record or delete records. For this we are going to create new web application project and add repeater control to the page. In this application orders for customers are listed with shipment name, city and country. Here shipment name, city and country will be editable whearas CustomerID and OrderDate cannot be edited.

Below is code listing of repeater control.

<asp:Repeater ID=”editRepeater” runat=”server” onitemcommand=”editRepeater_ItemCommand” onitemdatabound=”editRepeater_ItemDataBound”>

<ItemTemplate>

<tr class=”rowCss”>

<td Width=”2px” ><asp:CheckBox ID=”chkDelete” runat=”server” /></td>

<td><asp:Label ID=”lblOid” runat=”server” Visible=”false” Text='<%#DataBinder.Eval(Container.DataItem,”OrderID”) %>’></asp:Label></td>

<td><asp:Label ID=”lblCid” runat=”server” Text='<%#DataBinder.Eval(Container.DataItem,”CustomerID”) %>’></asp:Label></td>

<td><asp:Label ID=”lblOdate” runat=”server” Text='<%#DataBinder.Eval(Container.DataItem,”OrderDate”) %>’></asp:Label></td>

<td><asp:Label ID=”lblSname” runat=”server” Text='<%#DataBinder.Eval(Container.DataItem,”ShipName”) %>’></asp:Label>

<asp:TextBox ID=”txtSname” runat=”server” Visible=”false” Text='<%#DataBinder.Eval(Container.DataItem,”ShipName”) %>’></asp:TextBox></td>

<td><asp:Label ID=”lblScity” runat=”server” Text='<%#DataBinder.Eval(Container.DataItem,”ShipCity”) %>’></asp:Label>

<asp:TextBox ID=”txtScity” runat=”server” Visible=”false” Text='<%#DataBinder.Eval(Container.DataItem,”ShipCity”) %>’></asp:TextBox></td>

<td><asp:Label ID=”lblScountry” runat=”server” Text='<%#DataBinder.Eval(Container.DataItem,”ShipCountry”) %>’></asp:Label>

<asp:TextBox ID=”txtScountry” runat=”server” Visible=”false” Text='<%#DataBinder.Eval(Container.DataItem,”ShipCountry”) %>’></asp:TextBox></td>

<td><asp:LinkButton ID=”lnkEdit” runat=”server” CommandName=”Edit” CommandArgument='<%#DataBinder.Eval(Container.DataItem,”OrderID”) %>’ >Edit</asp:LinkButton>

<asp:LinkButton ID=”lnkUpdate” runat=”server” CommandName=”Update” CommandArgument='<%#DataBinder.Eval(Container.DataItem,”OrderID”) %>’ >Update</asp:LinkButton>

<asp:LinkButton ID=”lnkCancel” runat=”server” CommandName=”Cancel” CommandArgument='<%#DataBinder.Eval(Container.DataItem,”OrderID”) %>’ >Cancel</asp:LinkButton>

<asp:LinkButton ID=”lnkDelete” runat=”server” CommandName=”Delete” OnClientClick=’javascript:return confirm(“Are you sure you want to delete?”)’

CommandArgument='<%# DataBinder.Eval(Container.DataItem, “OrderID”) %>’>Delete</asp:LinkButton></td>

</tr>

</ItemTemplate>

</asp:Repeater>

To make certain columns editable lets add textbox control and to view data add label. For e.g ShipName textbox is used to make it editable and label is used to view shipment name. As we can see visibility of textbox is false so on first load of page it will show label and on click of edit button textbox will be visible and label will get hide.

<asp:Label ID=”lblSname” runat=”server” Text='<%#DataBinder.Eval(Container.DataItem,”ShipName”) %>’></asp:Label>

<asp:TextBox ID=”txtSname” runat=”server” Visible=”false” Text='<%#DataBinder.Eval(Container.DataItem,”ShipName”) %>’></asp:TextBox>

Also i have added 4 link buttons (Edit, Update, Cancel and Delete) to perform operations. Now let’s look how to fill and edit the data in the repeater. Binding repeater control is same as my previous post on repeater control shown below.

 

private int FillRepeater()

{

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[“ConnString”].ConnectionString);

string query = “select OrderID,CustomerID,OrderDate,ShipName,ShipCity,ShipCountry from Orders”;

SqlCommand cmd = new SqlCommand(query, conn);

conn.Open();

SqlDataAdapter da = new SqlDataAdapter(cmd);

DataSet ds = new DataSet();

da.Fill(ds);

PagedDataSource pds = new PagedDataSource();

pds.DataSource = ds.Tables[0].DefaultView;

pds.AllowPaging = true;

pds.PageSize = 8;

int count = pds.PageCount;

pds.CurrentPageIndex = CurrentPage;

if (pds.Count > 0)

{

lbtnPrev.Visible = true;

lbtnNext.Visible = true;

lbtnFirst.Visible = true;

lbtnLast.Visible = true;

lblStatus.Text = “Page ” + Convert.ToString(CurrentPage + 1) + “of” + Convert.ToString(pds.PageCount);

}

else

{

lbtnPrev.Visible = false;

lbtnNext.Visible = false;

lbtnFirst.Visible = false;

lbtnLast.Visible = false;

}

lbtnPrev.Enabled = !pds.IsFirstPage;

lbtnNext.Enabled = !pds.IsLastPage;

lbtnFirst.Enabled = !pds.IsFirstPage;

lbtnLast.Enabled = !pds.IsLastPage;

editRepeater.DataSource = pds;

editRepeater.DataBind();

if (conn.State == ConnectionState.Open)

conn.Close();

return count;

}

Now for editing part ItemCommand event of repeater control is used. This event raises when button in repeater control is clicked in this case its linkbutton. Based on linkbutton clicked different operations is performed. Below is shown code list for performing different operations based on linkbuttons clicked.

 

protected void editRepeater_ItemCommand(object source, RepeaterCommandEventArgs e)

{

LinkButton lnkEdit = (LinkButton)e.Item.FindControl(“lnkEdit”);

LinkButton lnkUpdate = (LinkButton)e.Item.FindControl(“lnkUpdate”);

LinkButton lnkCancel = (LinkButton)e.Item.FindControl(“lnkCancel”);

LinkButton lnkDelete = (LinkButton)e.Item.FindControl(“lnkDelete”);

Label lblOid = (Label)e.Item.FindControl(“lblOid”);

Label lblSname = (Label)e.Item.FindControl(“lblSname”);

TextBox txtSname = (TextBox)e.Item.FindControl(“txtSname”);

Label lblScity = (Label)e.Item.FindControl(“lblScity”);

TextBox txtScity = (TextBox)e.Item.FindControl(“txtScity”);

Label lblScountry = (Label)e.Item.FindControl(“lblScountry”);

TextBox txtScountry = (TextBox)e.Item.FindControl(“txtScountry”);

CheckBox chkDelete = (CheckBox)e.Item.FindControl(“chkDelete”);

if (e.CommandName == “Edit”)

{

lnkCancel.Visible = true;

lnkDelete.Visible = true;

lnkEdit.Visible = false;

txtSname.Visible = true;

lblSname.Visible = false;

txtScity.Visible = true;

lblScity.Visible = false;

txtScountry.Visible = true;

lblScountry.Visible = false;

}

else if(e.CommandName == “Cancel”)

{

FillRepeater();

}

else if(e.CommandName == “Update”)

{

string query = “update Orders set ShipName = @Sname,ShipCity = @Scity,ShipCountry = @Scountry where OrderID = @Oid “;

SqlCommand cmd = new SqlCommand(query, conn);

cmd.Parameters.Add(“@Sname”, SqlDbType.VarChar).Value = txtSname.Text;

cmd.Parameters.Add(“@Scity”, SqlDbType.VarChar).Value = txtScity.Text;

cmd.Parameters.Add(“@Scountry”, SqlDbType.VarChar).Value = txtScountry.Text;

cmd.Parameters.Add(“@Oid”, SqlDbType.VarChar).Value = e.CommandArgument;

try

{

conn.Open();

cmd.ExecuteNonQuery();

}

catch (Exception ex)

{

ex.Message.ToString();

}

finally

{

if(conn.State == ConnectionState.Open)

conn.Close();

}

FillRepeater();

}

else if (e.CommandName == “Delete”)

{

string inquery = “delete [Order Details] where OrderID = @Oid “;

SqlCommand cmd1 = new SqlCommand(inquery, conn);

cmd1.Parameters.Add(“@Oid”, SqlDbType.VarChar).Value = e.CommandArgument;

string query = “delete Orders where OrderID = @Oid “;

SqlCommand cmd = new SqlCommand(query, conn);

cmd.Parameters.Add(“@Oid”, SqlDbType.VarChar).Value = e.CommandArgument;

try

{

conn.Open();

cmd1.ExecuteNonQuery();

cmd.ExecuteNonQuery();

}

catch (Exception ex)

{

ex.Message.ToString();

}

finally

{

if (conn.State == ConnectionState.Open)

conn.Close();

}

FillRepeater();

}

}

So when edit link button is clicked labels are made hidden and textbox is show for editing purpose. Similarly for update and delete linkbutton is clicked respective operations are performed. When Cancel linkbutton is clicked it will cancel operations and list all records. In Delete section two delete statements are used to perform delete operations if table as foreign key constraints implemented. So first delete statement deletes records in Order Details table and then other one deletes records from Orders table.

For multiple deletions of records I have included checkbox for each record and linkbutton at bottom of the page. Deletions method is similar to one shown above here is linkbutton click event. To perform multiple deletions I have used foreach loop to delete each records one by one.

 

protected void LinkButton1_Click(object sender, EventArgs e)

{

foreach (RepeaterItem Item in editRepeater.Items)

{

CheckBox chkDelete = (CheckBox)Item.FindControl(“chkDelete”);

Label lblrptID = (Label)Item.FindControl(“lblOid”);

if (chkDelete.Checked)

{

string inquery = “delete [Order Details] where OrderID = @Oid “;

SqlCommand cmd1 = new SqlCommand(inquery, conn);

cmd1.Parameters.Add(“@Oid”, SqlDbType.VarChar).Value = lblrptID.Text;

string query = “delete Orders where OrderID = @Oid “;

SqlCommand cmd = new SqlCommand(query, conn);

cmd.Parameters.Add(“@Oid”, SqlDbType.VarChar).Value = lblrptID.Text;

conn.Open();

cmd1.ExecuteNonQuery();

cmd.ExecuteNonQuery();

if(conn.State == ConnectionState.Open)

conn.Close();

}

}

FillRepeater();

}

More posts on Repeater controls:

Download Project files

https://app.box.com/Editable Repeater

Note: Project uses AdventureWorks sample database which can be downloaded from-

http://northwinddatabase.codeplex.com/

Using Nested repeater control

This article will show how to implement nested repeater control in a web application. Assuming that you have working knowledge of repeater control, if not you can take look over my previous post on repeater control.

Nested repeater control is very useful if we want to show category and its subcategories or if we want to show products belongs to which category etc. For sample web application I am going to show employees and their respective customers to whom they are serving. The sample database for this particular application is Northwind.

Let’s begin by creating simple web application project and add repeater control to it. To add nested repeater control we will add repeater control within repeater control as shown below.

<asp:Repeater ID = “RepeaterOuter” runat=”server” >

<ItemTemplate>

<dl>

<dt> <h3 class=”hdrCss”> <%#DataBinder.Eval(Container.DataItem,”FirstName”) %> Customer List </h3> </dt>

<asp:HiddenField ID = “EmpID” runat=”server” Value='<%#DataBinder.Eval Container.DataItem,”EmployeeID”) %>’/>

<asp:Repeater ID=”RepeaterInner” runat=”server”>

<ItemTemplate>

<dd class=”rowCss”> – <%#DataBinder.Eval(Container.DataItem, “CompanyName”)%> </dd>

</ItemTemplate>

</asp:Repeater>

</dl>

</ItemTemplate>

<SeparatorTemplate>

<hr />

</SeparatorTemplate>

</asp:Repeater>

 

Above snippet shows nested repeater control which shows two repeater control one is RepeaterOuter which binds to Employee name and ID and other is RepeaterInner which binds to customers associated to particular employee. I trying to show Employees which are serving to which customers.

Data binding of repeater control is same as my first article on repeater control. Here important point to understand is how we going to bind our inner repeater control where in this case it lists all customers based on employee id. Below code shows entire data binding of control.

 

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[“ConnString”].ConnectionString);

string query = “select * from Employees”;

SqlCommand cmd = new SqlCommand(query, conn);

conn.Open();

SqlDataAdapter da = new SqlDataAdapter(cmd);

DataSet ds = new DataSet();

da.Fill(ds);

PagedDataSource pds = new PagedDataSource();

pds.DataSource = ds.Tables[0].DefaultView;

pds.AllowPaging = true;

pds.PageSize = 8;

int count = pds.PageCount;

pds.CurrentPageIndex = CurrentPage;

if (pds.Count > 0)

{

lbtnPrev.Visible = true;

lbtnNext.Visible = true;

lbtnFirst.Visible = true;

lbtnLast.Visible = true;

lblStatus.Text = “Page ” + Convert.ToString(CurrentPage + 1)+ “of” + Convert.ToString(pds.PageCount);

}

else

{

lbtnPrev.Visible = false;

lbtnNext.Visible = false;

lbtnFirst.Visible = false;

lbtnLast.Visible = false;

}

lbtnPrev.Enabled = !pds.IsFirstPage;

lbtnNext.Enabled = !pds.IsLastPage;

lbtnFirst.Enabled = !pds.IsFirstPage;

lbtnLast.Enabled = !pds.IsLastPage;

RepeaterOuter.DataSource = pds;

RepeaterOuter.DataBind();

foreach(RepeaterItem rpitem in RepeaterOuter.Items)

{

query = “select distinct top 5 o.EmployeeID,c.CustomerID,c.CompanyName from Orders o, Customers c where o.CustomerID = c.CustomerID and o.EmployeeID = @empID”;

cmd = new SqlCommand(query, conn);

cmd.Parameters.Add(“@empID”, SqlDbType.Int).Value = ((HiddenField)rpitem.FindControl(“EmpID”)).Value;

da = new SqlDataAdapter(cmd);

ds = new DataSet();

da.Fill(ds);

((Repeater)(rpitem.FindControl(“RepeaterInner”))).DataSource = ds;

((Repeater)(rpitem.FindControl(“RepeaterInner”))).DataBind();

}

return count;

}

Here I have used foreach loop to populate inner control which gets top 5 customers name for each employee (ID). Also I have added paging to outer control.

Download the Project File:

  https://app.box.com/nestedrepeater

Note: Project uses AdventureWorks sample database which can be downloaded from-

http://northwinddatabase.codeplex.com/

LINQ and asp.net web application

LINQ stands for Language Integrated Query is a set of keywords that allows developers to write query in sql command style without need of using quotes. It is built on .Net framework 3.5. Linq can be used with any data source. LINQ provides strongly typed and compile time checking of query expression and also provides full intellisense, debugging and rich refactoring support. LINQ is supported across different data adapters (Linq to Object, Linq to Sql, Linq to XML).However this article covers LinqtoSql with sample web application.

Linq to Sql – is an O/RM (Object Relational mapping) which basically creates model of relational database to which query the database using LINQ without need to write query in quotes. It supports all features which enables us to manipulate the data in the database.

For using LinqtoSql in a asp.net web application we will create a new web application project in visual studio.

Follow these steps to use LinqtoSql in a project

1>Add LINQ to SQL classes to the project by right clicking the project file in the solution explorer and click add new item and select Data in the Installed Template section and select the LINQ to SQL Classes. This will create dbml file in the project which is L2S file which includes designer.cs and layout.

 

image

 

2> Open newly created dbml file (NorthDB.dbml) which is a designer for adding tables from database along with relations. To add tables connect to a database through Server Explorer and drag and drop the tables from the database whichever required for the project. This creates the model of tables and maps it. So when we give select query it first hits the Model which was created by L2S and then actual data is retrieved from database.

The mapping of table can be found in the .designer.cs of dbml file.

 

image

 

image

 

This is only initial requirement to connect to database using L2S.

Now to utilize the LINQ to select data from the table is done as follows.

To use the data model we must create the object of the class of dbml file. In this case NorthDBDataContext is the class name of dbml file now we access the members of this class i.e. data models of our database. Following code snippet is the typical way of getting the data from table.

 

Using (NorthDBDataContext NContext = new NorthDBDataContext())

{

Var data = (

From cus in NContext.Customers

Select cus}

);

}

 

Insert/Update/Delete using LINQ

All data operations on database are possible using LINQ (Insert/Update/Delete). For our demo application we are using Customers table in Northwind Database. In below code snippet we will insert the values to customer table using Linq method SubmitChanges. First we wil create object of our customer class which is generated by LINQ engine. And map each property against corresponding text field on the page. In the end will pass entity to InsertOnSubmit method which will save it to entity (cust) and on submitchanges it gets inserted to actual database table.

Insert New Record

using (NorthDBDataContext NContext = new NorthDBDataContext())

{

Customer cust = new Customer();

{

cust.CustomerID = txtCustid.Text;

cust.CompanyName = txtComname.Text;

cust.ContactName = txtContact.Text;

cust.ContactTitle = txtContitle.Text;

cust.City = txtCity.Text;

cust.Country = txtContry.Text;

cust.Address = txtAddress.Text;

cust.Phone = txtPhone.Text;

cust.PostalCode = txtPostalcode.Text;

cust.Region = txtRegion.Text;

cust.suffix = txtsuffix.Text;

cust.Fax = txtFax.Text;

};

try

{

NContext.Customers.InsertOnSubmit(cust);

NContext.SubmitChanges();

lblMsg.Text = “New Record inserted!”;

CleartextBoxes(this);

}

catch(Exception ex)

{

Response.Write(“Error: “+ex);

}

}

Similarly same applies for update data on the table. But on update we use SubmitChanges methods without using InsertOnSubmit method as we have to update the existing record. Here we retrieve data from the table and set record to a corresponding text field and then update accordingly. Code remains more or less similar to above code. Below is update code.

Update Record

using (NorthDBDataContext NContext = new NorthDBDataContext())

{

var detail = (

from cust in NContext.Customers

where cust.CustomerID == ListBox1.SelectedValue

select cust

);

foreach (Customer cust in detail)

{

cust.CustomerID = txtCustid.Text;

cust.CompanyName = txtComname.Text;

cust.ContactName = txtContact.Text;

cust.ContactTitle = txtContitle.Text;

cust.City = txtCity.Text;

cust.Country = txtContry.Text;

cust.Address = txtAddress.Text;

cust.Phone = txtPhone.Text;

cust.PostalCode = txtPostalcode.Text;

cust.Region = txtRegion.Text;

cust.suffix = txtsuffix.Text;

cust.Fax = txtFax.Text;

};

NContext.SubmitChanges();

lblMsg.Text = “Update was Successful!”;

Response.Write(“Error: ” + ex);

Finally to delete a record from table can be done by using DeleteOnSubmit method. We will retrieve required record and then delete the same. Below is the code for delete.

Delete Record

using (NorthDBDataContext NContext = new NorthDBDataContext())

{

var detail = (

from cust in NContext.Customers

where cust.CustomerID == ListBox1.SelectedValue

select cust

);

foreach(Customer custDetail in detail)

{

NContext.Customers.DeleteOnSubmit(custDetail);

}

try

{

NContext.SubmitChanges();

lblMsg.Text = “Record Deleted!”;

loadListbox();

}

catch(Exception ex)

{

Response.Write(“Error: ” + ex);

}

}

Download the Demo Project:

https://www.box.com/s/LinqTestProject

Note: Project uses Northwind sample database which can be downloaded from-

http://northwinddatabase.codeplex.com/

Using xml and json in asp.net.

Using XML in asp.net application

XML stands for EXtensible Markup Language generally used to store and transport data across web. Xml file can be used as database to store data. XML is standard format which is accessible across all platform. In .NET we can use XML in many different scenario from web applications to web services. In .Net XML methods and functions can be found in System.Xml namespace.

Following code snippet shows how to create xml document.

XmlDocument xd = new XmlDocument();

xd.Load(MapPath(“Data/Country.xml”));

XmlElement parentelement = xd.CreateElement(“Country”);

XmlElement name = xd.CreateElement(“Name”);

name.InnerText = txtCtry.Text;

XmlElement capital = xd.CreateElement(“Capital”);

capital.InnerText = txtCapital.Text;

parentelement.AppendChild(name);

parentelement.AppendChild(capital);

xd.DocumentElement.AppendChild(parentelement);

xd.Save(MapPath(“Data/country.xml”));

XmlDocument is the main xml class which can be used to access the methods related to XML. This contains Load method which is used to load the xml file. Other relevant class is XmlElement which is used to create a structure of xml. In above code first we have created parent node called Country then the child nodes Name and Capital respectively.

Also we have appended these child nodes to parent node using AppendChild method. And in the end we have saved the xml .

The Above code will generate following XML

<?xml version=”1.0″ encoding=”utf-8″?>

<countries>

<Country>

<Name>India</Name>

<Capital>New Delhi</Capital>

</Country>

</countries>

Loading XML in a asp.net control

Loading XML in to a control requires Dataset to load the xml data and then assign this dataset as datasource to a control (Listbox) as shown in below code snippet.

Loading Listbox with Country from XML

DataSet dtxml = new DataSet();

dtxml.ReadXml(MapPath(“Data/Country.xml”));

ListBox1.DataSource = dtxml;

ListBox1.DataTextField = “Name”;

ListBox1.DataBind();

Searching For a value in a given XML

To do this we are using XmlNode class to find the particular node and within that we will find for a value. Below function finds capital for given country name , first it finds root node countries then it finds Country within root node and atlast it finds capital for country name. It uses XmlNode class with SelectSingleNode method to get given node.

To find particular value from given xml file

private void findinXML(string name)

{

XmlDocument doc = new XmlDocument();

doc.Load(MapPath(“Data/Country.xml”));

XmlNode root = doc.SelectSingleNode(“//countries”);

XmlNode node = doc.SelectSingleNode(“//Country[Name = ‘”+name+”‘]”);

//string Name = node.InnerText;

root = node.SelectSingleNode(“Capital”);

string capital = root.InnerText;

lblCtry.Text = “Capital of “+name+ ” is “+capital;

}

Using JSON in asp.net application

A JSON stand for JavaScript Object Notation is also used to transport data in a web scenario just like XML but more lightweight and easy to implement. It is text based human readable format independent to any programming language.

More info on JSON: http://www.json.org

We will use json.net to read and write json file in asp.net application. Of course we can use built class to read and write json but json is one of the most preferred json serializer. For more information please visit http://www.json.net. In .NET we can use DataContractJsonSerializer to serialize type to JSON string and deserialize JSON string to type instance. This comes under System.Runtime.Serialization.Json namespace.

Lets begin with our sample application to read and create JSON using JSON.NET. For this we need to download JSON.NET binary from following link http://json.codeplex.com/releases/view/106328 and add the JSON.NET dll to our application. Also include its namespace i.e Newtonsoft.Json.

In this application we are taking two values from user namely Country and Capital values and on submit it gets store in a list and then this list serialized in PreRender event of Page to form JSON file.

Our JSON file looks like something like this.

[
  {
    “Country”: “India”,
    “Capital”: “New Delhi”
  },
  {
    “Country”: “USA”,
    “Capital”: “Washingtan DC”
  },
  {
    “Country”: “China”,
    “Capital”: “Bejing”
  }

]

Following code snippet shows how to use  JSON.NET method.

Serialize and Deserialize using JSON.NET

serialize a List object to JSON

JsonConvert.SerializeObject(ctnew, Formatting.Indented)

On the same line to deserialize the JSON

JsonConvert.DeserializeObject<List<country>>(File.ReadAllText(MapPath(“Data/countrycaps.json”)));

 

Page_PreRender event looks like this.

protected void Page_PreRender(object sender, EventArgs e)

{

File.WriteAllText(MapPath(“Data/countrycaps.json”), string.Empty); File.AppendAllText(MapPath(“Data/countrycaps.json”), JsonConvert.SerializeObject(ctnew, Formatting.Indented));

}

We have used List to maintain the state during postback in a session. Following code shows List property with class country to store the values one by one in a List.

List for storing value during postback.

public List<country> ctnew

{

get

{

if (HttpContext.Current.Session[“ctnew”] == null)

{

HttpContext.Current.Session[“ctnew”] = new List<country>();

}

return HttpContext.Current.Session[“ctnew”] as List<country>;

}

set

{

HttpContext.Current.Session[“ctnew”] = value;

}

}

public class country

{

public string Country { get; set; }

public string Capital { get; set; }

}

Loading JSON in a asp.net control

Just like XML we can use Listbox to load json values in this application we have used to 2 listbox one loads all the countries and other loads all the capitals. Here we have used List as a Datasource for Listbox this is shown below.

Load Listbox with values from JSON file

ListBox1.DataSource = j.ctnew;

ListBox1.DataTextField = “Country”;

ListBox1.DataBind();

 

Searching For a value in a given JSON file

To search the particular value with JSON wecan use 2 methods one via Find method of List and other via LINQtoJSON method called FirstOrDefault. Both the methods are shown below.

To find specific value from json file

Find Method underneath uses regular for loop to find the particular record.

var response = j.ctnew.Find(s => s.Country == “India”);

On the other hand FirstOrDefault is LINQ way of finding the values.

var response = j.ctnew.FirstOrDefault(c => c.Capital == val );

Download the Demo Project:

https://www.box.com/XMLandJSON

Add paging to repeater control using c#

The Repeater control is used to display a repeated list of items that are bound to the control. The Repeater control may be bound to a database table, an XML file, or another list of items. Repeater control lacks paging and sorting of data like other data bound controls such as Datagrid, GridView, DetailsView and FormView. But we can add this feature to repeater control which is explained and sampled below.

For more information on repeater control visit the following link

http://msdn.microsoft.com/en-us/magazine/cc163780.aspx

To begin with I gonna create a web application and add repeater on to the web form. Before binding any datasource we have to create the structure of the control. This can be done by using simple html table in the control. Repeater control contains different section which can be easily customized or created using html tags. This is shown below.

<asp:Repeater ID=”Repeater1″ runat=”server”>

<HeaderTemplate>

<table class=”tblCss”>

<tr class=”hdrCss”>

                 <th><asp:Label ID=”lblordid” Text=”OrderID” runat=”server”></asp:Label></th>

                 <th><asp:Label ID=”lblcustid” Text=”CustmerID” runat=”server”></asp:Label></th>

                 <th><asp:Label ID=”lblOrddt” Text=”Order Date” runat=”server”></asp:Label></th>

                 <th><asp:Label ID=”lblname” Text=”Name” runat=”server”></asp:Label></th>

                 <th><asp:Label ID=”lblcity” Text=”City” runat=”server”></asp:Label></th>

                <th><asp:Label ID=”lblctry” Text=”Country” runat=”server”></asp:Label></th>

</tr>

</HeaderTemplate>

<ItemTemplate>

<tr class=”rowCss”>

                 <td><%#DataBinder.Eval(Container.DataItem,”OrderID”) %></td>

                 <td><%#DataBinder.Eval(Container.DataItem,”CustomerID”) %></td>

                 <td><%#DataBinder.Eval(Container.DataItem,”OrderDate”) %></td>

                <td><%#DataBinder.Eval(Container.DataItem,”ShipName”) %></td>

                <td><%#DataBinder.Eval(Container.DataItem,”ShipCity”) %></td>

                <td><%#DataBinder.Eval(Container.DataItem,”ShipCountry”) %></td>

</tr>

</ItemTemplate>

<SeparatorTemplate>

<tr>

<td><hr /> </td>

<td><hr /> </td>

<td><hr /> </td>

<td><hr /> </td>

<td><hr /> </td>

<td><hr /> </td>

</tr>

</SeparatorTemplate>

<FooterTemplate>

<tr class=”footCss”>

<td> All order entry data </td>

</tr>

</table>

</FooterTemplate>

</asp:Repeater>

Headertemplate used to add header to the control

Itemtemplate is used to define or render each data item in the control

AlternatingItemTemplate is used to define or render each alternate data item in the control

SeparatorTemplate is used to render elements between each item

FooterTemplate is used to add footer in the control

Now we will  Add a button to get data from datasource on click event

<asp:Button ID=”btnData” runat=”server” Text=”Get Data”

onclick=”btnData_Click” />

Also, Add linkbuttons for paging purpose this will include First, Previous, Next, Last

<asp:LinkButton ID=”lbtnFirst” runat=”server” onclick=”lbtnFirst_Click”>First</asp:LinkButton>

<asp:LinkButton ID=”lbtnPrev” runat=”server” onclick=”lbtnPrev_Click”>Previous</asp:LinkButton>

<asp:LinkButton ID=”lbtnNext” runat=”server” onclick=”lbtnNext_Click”>Next</asp:LinkButton>

<asp:LinkButton ID=”lbtnLast” runat=”server” onclick=”lbtnLast_Click”>Last</asp:LinkButton>

<asp:Label ID=”lblStatus” runat=”server” Text=”Label”></asp:Label>

Now we will add setting for Dataconnection in web.config file . For this Northwind database is used and Orders table is used. New connectionStrings is added to web.config file

<connectionStrings>

<add name=”ConnString”connectionString=”Data Source=10.2.1.20;Initial Catalog=Northwind;Persist Security Info=True;User ID=sa;Password=admin”providerName=”System.Data.SqlClient”/>

</connectionStrings>

For paging purpose we will use PagedDataSource class which is the same class used for paging in other databound controls. Following snippets creates the object of the PagedDataSource class and utilizes some of its methods.

 
private int FillRepeater(){SqlConnection conn = new SqlConnection ConfigurationManager.ConnectionStrings[“ConnString”].ConnectionString);string query = “select OrderID,CustomerID,OrderDate,ShipName,ShipCity,ShipCountry from Orders”;SqlCommand cmd = new SqlCommand(query, conn);conn.Open();SqlDataAdapter da = new SqlDataAdapter(cmd);

DataSet ds = new DataSet();

da.Fill(ds);

PagedDataSource pds = new PagedDataSource();                                                                               pds.DataSource = ds.Tables[0].DefaultView;                                                                                               pds.AllowPaging = true;                                                                                                                                           pds.PageSize = 8;

int count = pds.PageCount;                                                                                                                  pds.CurrentPageIndex = CurrentPage;

if (pds.Count > 0) {

lbtnPrev.Visible = true;                                                                                                                                  lbtnNext.Visible = true;                                                                                                                                     lbtnFirst.Visible = true;                                                                                                                                      lbtnLast.Visible =true;

lblStatus.Text = “Page ” + Convert.ToString(CurrentPage + 1) + “of” + Convert.ToString(pds.PageCount);

}

else{

lbtnPrev.Visible = false;                                                                                                                                    lbtnNext.Visible = false;                                                                                                                                 lbtnFirst.Visible = false;                                                                                                                                        lbtnLast.Visible = false;

}

lbtnPrev.Enabled = !pds.IsFirstPage;                                                                                                        lbtnNext.Enabled = !pds.IsLastPage;                                                                                                         lbtnFirst.Enabled = !pds.IsFirstPage;                                                                                                            lbtnLast.Enabled = !pds.IsLastPage;

Repeater1.DataSource = pds;                                                                                                                     Repeater1.DataBind();

return count;

}

After this simple  property used to get the current page value as follows. This simply uses the viewstate to store the current state of the Data page. And also I will add functionality to linkbutton which gets First, Last, Previous and Next page on click event  as shown below.

 
public int CurrentPage { get{ object obj = this.ViewState[“_CurrentPage”]; if (obj == null)                                                                                                                       {                                                                                                                                               return 0; }                                                                                                                                                            else                                                                                                                                                            {                                                                                                                                           

return (int)obj;

}

}

set

{

//set in viewstate the current page number

this.ViewState[“_CurrentPage”] = value;

}

protected void lbtnPrev_Click(object sender, EventArgs e)

{                                                                                                                               

CurrentPage -= 1;                                    

FillRepeater();

}

protected void lbtnNext_Click(object sender, EventArgs e) {                                                                                                                                                       

CurrentPage += 1;    

FillRepeater();

}

protected void lbtnFirst_Click(object sender, EventArgs e)

{                                                                                                                                           

CurrentPage = 0;    

FillRepeater();

}

protected void lbtnLast_Click(object sender, EventArgs e)

{                                                                                                                                                  

CurrentPage = FillRepeater() – 1;

FillRepeater();

}

Paging of Repeater Control is done and same thing can also be applied to DataList Control.

Download the Project File:

https://www.box.com/Datalistandrepeater

Note: Project uses AdventureWorks sample database which can be downloaded from-

http://northwinddatabase.codeplex.com/

entity framework 4.0 in asp.net web application (Sample)

 

Entity framework is a object relational mapper that enables to work with relational data using domain-specific objects. This post is about creating simple web application to display data using entity framework 4.0. To accomplish this we are using linq to interact with data.

To begin we will create new web application

(New>Projects>ASP.NET Web Application)

This will create web site with all required files for creating web application.Now add Entity framework model to project. This can be done by right clicking on the application in solution explorer and click on add new item and select ADO.NET Entity Data Model this will create entity data model file (.edmx) within App_code folder. If App_code folder is not created it will ask for it click yes on the alert box and it places the data model in  App_code folder. (See the image below)

 
image

Next Entity Data Model Wizard will open through we can select database for which model we want or we can select empty model. Here select Generate from database option as we are using database which is already created.

Select Generate from database(Data-first approach)
Capture2

 

NOTE: There are three approaches for creating entity data model

  1. Code- first approach-This type of approach uses heavy coding where every thing is controlled by programmer without using EF designer.
  2. Data-first approach – In this database is first created or is present from which entity model is created.
  3. Model-first approach- In this approach conceptual model is created first for a application and using this model database is generated.

In next screen it ask for connection details select the database from the server. Also in this it will ask for if you want to show the sensitive data or not in the connection string. This is optional, any option will do. Check save to web config checkbox this will create the connection string entry in the web.config file.

Capture3

In last screen of wizard it will give tables,views and stored procedure within the database. Select the required tables and hit finish this will create the model for the database.

Capture4

In we check the web config file we will find the newly created connection string got created.

 

 

<configuration>
  <connectionStrings>     
    <add name=”AdventureWorksEntities1″ connectionString=”metadata=res://*/App_Code.AdventuresEF.csdl|res://*/App_Code.AdventuresEF.ssdl|res://*/App_Code.AdventuresEF.msl;
provider=System.Data.SqlClient;
provider connection string=&quot;data source=SUDHAKAR-PC;initial catalog=AdventureWorks;user id=sa;password=admin;multipleactiveresultsets=True;App=EntityFramework&quot;” providerName=”System.Data.EntityClient” />
   </connectionStrings>
<configuration>

Above is the connection string is created by wizard with name AdventureWorksEntites 1.

Now in default.aspx page where we want to show our data, we will add datagridview to display the data from employee table from AdventureWorks database. We will use page load event to load the data at the page load in datagridview control code for doing this shown below.

 

protected void Page_Load(object sender, EventArgs e)
    {      
          var empDetails = new AdventureWorksModel.AdventureWorksEntities1();      

          var Linquery =  (from s in empDetails.Employees                     
                                            select new { s.EmployeeID, s.Employee2,s.BirthDate,   

                                            s.ContactID,s.Title,s.HireDate,s.SalariedFlag}).Take(50);

         GridView1.DataSource = Linquery.ToList();
         GridView1.DataBind();

      
    }

In the above code we have used Linq to select the records from employees table and loaded on gridview control. To list the results from var linquery on the gridview converted it to list and simply databind it to gridview.

Note: When edmx file is created it creates its new namespace look into .Designer.cs file of edmx file

Download the project files:

 https://www.box.com/s/lhc4q08nat4sqh3sx8n6                                                                                                                                                    

 

Note: Project uses AdventureWorks sample database which can be downloaded from-            http://msftdbprodsamples.codeplex.com/

 

User Profile on ASP.net web application

This post is tutorial on how to set user profile in ASP.NET web application. User profile is generally used to identify the visitors who are visiting the site again and sets personal custom settings which they set on the last visit.

User profile can also be used to identify the anonymous user who are not a logged on member of the application or website.

To begin with user profile we will start with fresh asp.net web application. We are using asp.net web application which as default.aspx and about.aspx page and user account feature. We are only concern with default.aspx page where all the action is going to take place. 

First thing is to add database for storing the user details in web.config file. As we are using default web application database is already set in the  web.config file. This default profile database is called aspnetdb.mdf and is created by ASP.NET using sql express.

Web.config flle with default database and provider

<connectionStrings>
  <add name=”ApplicationServices”
       connectionString=”data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true”
       providerName=”System.Data.SqlClient” />
</connectionStrings>


 

<profile>    
     <providers>
       <clear/>
       <add name=”AspNetSqlProfileProvider” type=”System.Web.Profile.SqlProfileProvider” connectionStringName=”ApplicationServices” applicationName=”/”/>
     </providers>    
   </profile>

After that we add provider for profile properties in web.config. This can be done by defining the fields to store the user details in our case Name and LastvVsitedOn withing <profile> element in web.config under <properties> element. As shown below…

Defining fields to be stored

<anonymousIdentification enabled=”true”/>
<profile>
  <properties>
    <add name =”Name” allowAnonymous=”true” />
    <add name =”LastVisitOn” type=”System.DateTime” allowAnonymous=”true” />
  </properties>

</profile>

By default, a user profile and its properties are enabled only for authenticated users—those
users who provide logon credentials for your site and then are authenticated against a user
data store. For that we have included allowAnonymous=”true” property in each field. This allows anonymous or unauthenticated visitor to be recognized.

Now we will add some controls on our Default.aspx page to get the name of the visitor. To do that we will use one textbox to ask visitor guest to enter his/her name and a save button to save it. Other than these input controls we  will also include labels  to show the date time and name of last visited guest. The following code shows how to set and recognize the visitors name and last visited date time. Application sets the name of the visitor on btnSave_click event and date time on Page_Unload event. At Page_Load event the details of the last visitors is shown on the labels.

code on the Default.aspx.cs page

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string name = Profile.Name;
            string lastvisit = Profile.LastVisitOn.ToString();         

            if (name == “”)
            {
                lblName.Text = “Guest”;

            }
            else
            {
                lblName.Text = name;
            }
            if (lastvisit == “1/1/0001 12:00:00 AM”)
            {
                lblLastvisiton.Text = “Never visited”;
            }
            else
            {
                lblLastvisiton.Text = lastvisit;
            }

        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        Profile.Name = txtName.Text;
        Profile.Save();
        Response.Redirect(“Default.aspx”);
    }

    protected void Page_Unload(object sender, EventArgs e)
    {
        Profile.LastVisitOn = DateTime.Now;
        Profile.Save();
    }

Download the demo project –                                                                            

https://www.box.com/s/cupus6sz9m9k08ioj6mq

Encrypting and Decrypting the connection string in web.config

To encrypt the connection string of the database connection to hide the connection details we can do that using visual studio command prompt. The command to encrypt is as follows …

Encrypt connectionStrings tag in web.config file.
aspnet_regiis –pef “connectionStrings” “C:\…\Website” 

Here “connectionStrings”  is tag from web.config and
“C:\…\Website”  is the path of the website folder.

Similarly to decrypt the connection string we use following command…

Decrypt connectionStrings tag in web.config file.
aspnet_regiis –pdf “connectionStrings” “C:\…\Website” 

Here just changing the switch from –pef to –pdf for decrypting.

Note: Open Visual Studio command prompt as Administrator.