Tuesday, 6 November 2012

Crystal Reports in vs 2010


This tutorial focuses on creating a crystal report in Visual studio 2010. The report uses a stored procedure to get its data from an Sql server 2008 R2 database. In order to create the report you will need to download and install crystal reports for Visual Studio 2010. This is because VS 2010 does not ship with crystal reports. However you can download crystal reports from SAP websitehttp://downloads.businessobjects.com/akdlm/cr4vs2010/CRforVS_13_0.exe
  1. Start by running the following scripts in sql database to create a test table, insert some records and also create a procedure that will retrieve the records.
    --===========================================
    --create a test customer table
    CREATE TABLE t_Customers
    (
        CustomerID VARCHAR(20),
        FirstName VARCHAR(25),
        LastName VARCHAR(25)
    )
    --===========================================
    --insert dummy data into the test table
    INSERT INTO t_Customers(CustomerID,FirstName,LastName)
    VALUES('12345','Evans','Amenya')
    INSERT INTO t_Customers(CustomerID,FirstName,LastName)
    VALUES('324132123','ASas','ASasASas')
    INSERT INTO t_Customers(CustomerID,FirstName,LastName)
    VALUES('234234','evans','asdasdasd')
    --===========================================
    --create procedure to retrieve the records
    CREATE PROCEDURE sp_getCustomers
    AS
        SELECT CustomerID,FirstName,LastName FROM t_Customers
    --=========================================== 
  2. Create a new Visual Studio 2010 project
  3. Right-click on the project on the solution explorer and click on Add New Item on the pop-up menu as shown below
    adding a new item in visual studio 2010
  4. The Add New Item dialogue box will appear as shown below. Select Crystal Reports in the middle pane then enter the name as “CustomersReport.rpt” in the Name field.
    selecting crystal report in add item dialogue box
  5. Click the Add button.
    Crystal Reports Gallery dialogue box will appear as shown below
    Crystal Reports Gallery
    Select As a Blank Report in Create a New Crystal Report Document options. Then click the OK button
  6. A blank report will appear. Right-click on any blank area on the report, then point to Database on the pop-up menu that appears. Click on Database Expert as shown below
    right-click on blank database image
  7. The Database Expert dialogue box will appear as shown below. Expand the Create New Connection node. Then expand the OLE DB (ADO) node.
    Creating a connection to database
  8. OLE DB Provider dialogue box will appear as shown below. Scroll down and select SQL Server Native Client 10.0 from the list of Providers. Then click the Next button.
    OLE DB (ADO) - OLE DB Provider dialogue box
  9. OLE DB Connection information dialogue box will appear as shown below. Provide necessary information to log on and click Next.
    OLE DB (ADO) - Connection Information dialogue box
  10. The Advanced Information dialogue box will appear as shown below. Click the Finish button.
    OLE DB (ADO) - Advanced Information dialogue box
  11. The connected database will appear as shown in the screen below. Expand the Database name node.
    Expand the dbo node. Expand the Stored Procedures node. Select the stored procedure to use,
    “sp_getCustomers”, then click the right-pointing single arrow to move the procedure to the right-hand pane.
    Database Expert - Data dialogue box
  12. Click OK button.
    The Database Expert dialogue box closes and the blank report is visible.
    Expand the Database Fields node on the Field Explorer box. Expand procedure name node ("sp_getCustomers") as shown below.
    Field explorer box
  13. Drag and drop the fields from the Field Explorer box onto the blank report just below the Details
    section. After you release the mouse key, the heading should automatically appear as shown below.
    Drag fields from field explorer and drop on report designer
  14. The linking of our crystal report to sql server database is complete. Now we can create a .aspx page that will call it.
    Add web form to the project and choose C# as the programming language. Also make sure the option to place code in separate file is selected. Name the page "CustomerReportViewer.aspx"
  15. Drag and drop a CrystalReportViewer control from the Reporting tab onto the CustomerReportViewer.aspx page. Your page should appear as shown below,
    CrystalReportViewer control on a page
  16. Add the following code on the code file
    ...
    using System.Reflection;
    using CrystalDecisions.CrystalReports.Engine;
    using CrystalDecisions.Shared;
    using CrystalDecisions.Reporting;
    using CrystalDecisions;
    using System.Data.SqlClient;
    public partial class CustomerReportViewer : System.Web.UI.Page
    {
        ReportDocument doc;
        protected void Page_Unload(object sender, EventArgs e)
        {
            if (doc != null)
                doc.Close();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            ShowReport(Server.MapPath(".\\CustomersReport.rpt"), "sp_getCustomers");
        }
        protected void ShowReport(String fileName, String strProcedureName)
        {
            TableLogOnInfo crTableLogOnInfo = new TableLogOnInfo();
            ConnectionInfo crConnectionInfo = new ConnectionInfo();
            CrystalDecisions.CrystalReports.Engine.Database crDatabase;
            CrystalDecisions.CrystalReports.Engine.Tables crTables;
            doc = new ReportDocument();
            doc.Load(fileName);
            crConnectionInfo.ServerName = "HP-PC";
            crConnectionInfo.DatabaseName = "ProgrammingSamples";
            crConnectionInfo.UserID = "xxxxxxx";
            crConnectionInfo.Password = "yyyyyyyy";
            crConnectionInfo.Type = ConnectionInfoType.SQL;
            crConnectionInfo.IntegratedSecurity = false;
            crDatabase = doc.Database;
            crTables = crDatabase.Tables;
            SqlConnection conn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.AppSettings["ConnectionString"].ToString());
            SqlCommand cmd = new SqlCommand("dbo." + strProcedureName, conn);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter adpt = new SqlDataAdapter(cmd);
            DataSet dataSet = new DataSet();
            adpt.Fill(dataSet, "Customers");
            foreach (CrystalDecisions.CrystalReports.Engine.Table crTable in crTables)
            {
                crTableLogOnInfo = crTable.LogOnInfo;
                crTableLogOnInfo.ConnectionInfo = crConnectionInfo;
                crTable.ApplyLogOnInfo(crTableLogOnInfo);
            }
            doc.SetDataSource(dataSet.Tables[0]);
            CrystalReportViewer1.ReportSource = doc;
        }
  17. Set "CustomerReportViewer.aspx" as the startup page and run the project.
    The report will be displayed as shown below.Crystal report displaying records from database

Download the complete source code for the example project


Monday, 5 November 2012

jQuery dynamic textbox example

<html>
<head>
<title>jQuery add / remove textbox example</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<style type="text/css">
div{
padding:8px;
}
</style>
</head>
<body>
<h1>jQuery add / remove textbox example</h1>
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
</head><body>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label><input type='text' id='textbox1' >
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
</body>
</html>

Saturday, 3 November 2012

LINQ To MySQL


LINQ to SQL is a great tool that saves a lot of time. However it has one disadvantage – it supports only SQL Server. Anyway it’s possible to write your own LINQ provider. Sure, there is one for MySQL. It is called DbLinq, in fact in supports many databases:
  • MySQL
  • Oracle
  • PostreSql
  • Ingress
  • SqlLite
It’s not finished yet, however you can still try to use it. I’m going to explain how to use it in this article; we’ll go through 3 steps:
  1. Installation
  2. Using DbLinq in a console application
  3. Using DbLinq in a ASP.NET application

Installation

  1. Go here and download the ZIP archieve
  2. Unpack the archive
  3. Open the Visual Studio solution - DbLinq
  4. Build the solution

Using DbLinq in a console application

Ok, let’s try it in action, we are going to create a console application that will retrieve, insert, update and delete records from the database.
First, we need to generate the data context and the table classes. Unfortunately you cannot do this in Visual Studio, but there is a command line utility called DbMetal and its visual analogue – Visual Metal that is written in WPF, by the way.

Go to the \dblinq2007\DbMetal\ folder, there are several BAT files, open in your favourite text editor run_myMetal.bat, since we are dealing with MySQL, and change the necessary parameters, save and run it. You must have got a generated CS file, copy it to your console application project.
Then, it’s time to add the references, you should add the following:
  • System.Data.Linq
  • DbLinq.dll (located in \dblinq2007\DbLinq.MySql\bin\release\)
  • DbLinq.MySql.dll (located in \dblinq2007\DbLinq.MySql\bin\release\)
  • MySql.Data.dll (located in \dblinq2007\lib\)
Since the table is called Products, I want the class that represents a stored entity to be called Product, not Products, as it was called by DbMetal. So, I change the generated code.

Compile the project to check if there are no errors. If you get any error, check if there are all the necessary references.

Let’s write some code; basically we want just to display the data:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient; //Don't forget to add this line

namespace MySqlLinqTest
{
    class Program
    {
        static void Main(string[] args)
        {
            LinqTest db = new LinqTest(new MySqlConnection("Database=<your database>;Data Source=localhost;User Id=<user>;Password=<password>"));

            var products = from p in db.Products
                           where p.Category == "Sport cars"
                           select p;

            foreach (var product in products)
            {
                Console.WriteLine(product.Name);
            }
        }
    }
}
That works. What about inserting a new record? No pro blems!
db.Products.InsertOnSubmit(new Product { Name = "Some car", Category = "Some category" });
db.SubmitC hanges();

var products = from p in db.Products
               orderby p.Name
               select p; 

foreach (var product in products)
{
    Console.WriteLine(product.Name);
}
Ok, let’s remove the newly added record:
Product someCar = (from p in db.Products
                      where p.Name == "Some car"
                      select p).First();

db.Products.DeleteOnSubmit(someCar);
db.SubmitChanges();
Let’s update something:
Product bentley = (from p in db.Products
                   where p.Name == "Bentley"
                   select p).First();

bentley.Name = "Bentley Continental";
db.SubmitChanges();

Using DbLinq in an ASP.NET application

It was funny enough, but the console applications are not very useful when dealing with the database, let’s write something that is closer to a real world – an ASP.NET application.

Create a C# web site; copy the generated file we used in the previous example.

Don’t forget to add the necessary references.

We are going to add a GridView and bind the data retrieved from the database.

Default.aspx
<asp:GridView ID="gridProducts" runat="server">
</asp:GridView>

Default.aspx.cs 
protected void Page_Load(object sender, EventArgs e)
{
    LinqTest db = new LinqTest(new MySqlConnection("Database=<your database>;Data Source=localhost;User Id=<user>;Password=<password>"));

    gridProducts.DataSource = from p in db.Products
                              orderby p.Name
                              select p;
    gridProducts.DataBind();
}
It works.

What about LinqDataSource, can we use it with DbLinq? Yes, we can, but it’s a bit tricky. If we add a LinqDataSource, we’ll get an error saying that there’s no parametless constructor in our DataContext. That is a thing that hopefully will be fixed in the new versions, but now we have to write a wrapper around a generated DataContext.
App_Code/Products.cs
public class MyDataContext
{
    private LinqTest _db;

    public MyDataContext()
    {
        _db = new LinqTest(new MySqlConnection("Database=<your database>;Data Source=localhost;User Id=<user>;Password=<password>"));
    }

    public Table<Product> Products { get { return _db.GetTable<Product>(); } }
}
Then, we can use LinqDataSource as usual:

<asp:LinqDataSource ID="dsProducts" runat="server" ContextTypeName="MysqlLinqTest.MyDataContext"     TableName="Products"></asp:LinqDataSource> <asp:GridView ID="gridProducts" runat="server" DataSourceID="dsProducts">  </asp:GridView>

Conclusion

As you see you can use LINQ to work with MySQL, unfortunately sometimes it’s not very convenient and we have to wait for the new versions or wait for a LINQ to MySQL provider from MySQL.

Friday, 2 November 2012

Resizable asp.net Gridview columns using Jquery

.aspx.cs code


 public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string Designation { get; set; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        var employees = new List<Employee>()
    {
        new Employee(){ Id = 1, Name = "Ms. Nancy Davolio",     Address = "507 - 20th Ave. E.  Apt. 2A",    Designation = "Sales Representative"},
        new Employee(){ Id = 2, Name = "Dr. Andrew Fuller",     Address = "908 W. Capital Way",             Designation = "Vice President Sales"},
        new Employee(){ Id = 3, Name = "Ms. Janet Leverling",   Address = "722 Moss Bay Blvd.",             Designation = "Sales Representative"},
        new Employee(){ Id = 4, Name = "Mrs. Margaret Peacock", Address = "4110 Old Redmond Rd.",           Designation = "Sales Representative"},
        new Employee(){ Id = 5, Name = "Mr. Steven Buchanan",   Address = "14 Garrett Hill",                Designation = "Sales Manager"},
        new Employee(){ Id = 6, Name = "Mr. Michael Suyama",    Address = "Coventry House  Miner Rd.",      Designation = "Sales Representative"},
        new Employee(){ Id = 7, Name = "Mr. Robert King",       Address = "Edgeham Hollow  Winchester Way", Designation = "Sales Representative"},
        new Employee(){ Id = 8, Name = "Ms. Laura Callahan",    Address = "4726 - 11th Ave. N.E.",          Designation = "Inside Sales Coordinator"},
        new Employee(){ Id = 9, Name = "Ms. Anne Dodsworth",    Address = "7 Houndstooth Rd.",              Designation = "Sales Representative"}
    };

        GridView1.DataSource = employees;
        GridView1.DataBind();
    }



.aspx code


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery.js" type="text/javascript"></script>
    <script src="Scripts/colResizable-1.3.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.cookie.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            if ($.cookie('colWidth') != null) {
                var columns = $.cookie('colWidth').split(',');
                var i = 0;
                $('.GridViewStyle th').each(function () {
                    $(this).width(columns[i++]);
                });
            }

            $(".GridViewStyle").colResizable({
                liveDrag: true,
                gripInnerHtml: "<div class='grip'></div>",
                draggingClass: "dragging",
                onResize: onSampleResized
            });

        });

        var onSampleResized = function (e) {
            var columns = $(e.currentTarget).find("th");
            var msg = "";
            columns.each(function () { msg += $(this).width() + ","; })
            $.cookie("colWidth", msg);
        };
    </script>
</head>
<body>
    <form id="Form1" runat="server">
    <asp:Label ID="Label1" runat="server"></asp:Label>
    <br />
    <br />
    <asp:GridView ID="GridView1" runat="server" CssClass="GridViewStyle">
    </asp:GridView>
    <br />
    <br />
    <asp:Button ID="Button1" runat="server" Text="Test Postback" />
    </form>
</body>
</html>

Wednesday, 31 October 2012

Turning an ascx user control into a redistributable custom control


This article applies to ASP.NET 2.0 and Visual Studio 2005.

Background

Since its early days, ASP.NET has always supported two different ways of authoring server controls:
  1. Custom Controls: these are controls written from scratch exclusively using code.  Essentially, you write a class which extends Control (directly or indirectly), and you take care of everything.  You need to write logic to create child controls that you want to use, and you override the Render method to perform rendering.  Typically, you build this control into a redistributable assembly (i.e. a DLL), which can then be used by any ASP.NET applications, simply by placing the assembly in the 'bin' directory of the app (or in the Global Assembly Cache).
  2. User Controls: these control are written using an ascx file, which looks much like an aspx page.  i.e. you can simply drag and drop the UI elements that you want to use into the design surface.  You don't need to worry about control creation, nor about overriding the Render method.
Looking at those two methods, they are very different, and each has a number of advantages and disadvantages.  I won't discuss them all, but will focus on those that are relevant to this article:
  • Custom Controls require a lot of development expertise to be written, while User Controls are authored using an advanced designer, and are much more approachable.  For this reason, User Controls typically take a lot less time to write.
  • Custom Controls can easily be redistributed without having to give away their sources.  On the other hand, User Controls are always used based on an ascx text file, making it less ideal for reuse across applications.
The goal of this article is to show how you can have the best of both world by turning an ascx user control into a redistributable custom control, by making use of ASP.NET 2.0's new precompilation features.

Brief outline of the steps

The basic steps to make this happen are as follows:
  1. Write your User Control as you normally would, typically using the Visual Studio designer.
  2. Test it using a simple page before trying to deploy it.
  3. Deploy the app to precompile it.
  4. Grab the user control's assembly produced by the deployment step, and you're essentially done: you have your Custom Control.
  5. Finally, use your Custom Control in other apps the same way as you always use Custom Control's.
We will look at those steps in more detail in the rest of the article.
 

Step 1: Authoring the User Control

To author the User Control, it is best to start with an empty site (not web app!) that contains nothing other than the ascx.  While the authoring of the User Control uses 'standard' techniques, there are some restrictions that you need to be aware of in order for it to be successfully turned into a standalone Custom Control.
The main restriction is that the User Control needs to be self contained.  That is, it cannot be dependent on app global things like App_Code or global.asax.  The reason for this is that since the goal is to turn the UserControl into a standalone DLL, it would break in other apps if it relied on code that is not part of that DLL.
One exception to this rule is that the UserControl can be dependent on assemblies that live in the bin directory (or in the GAC).  You just have to make sure that the other assemblies are always available when you use your Custom Control in other apps.
Another tricky thing is the use of static resources, like images.  After you turn it into a Custom Control in a standalone assembly, it becomes hard for it to keep such references, and avoiding them simplifies deployment.  If you really must have such references, one option is to use absolute URL's if you can guarantee that the resource will always be available on a certain site.  Or you can look into machine wide resources (e.g. src="http://blogs.msdn.com/MyImages/welcome.jpg"), though you will then need to make sure the resources are installed on the server machine (e.g. as part of some setup).
Ok, so let's start and actually author the User Control.  Visual Studio 2005 gives you the choice to place the code in a separate file, or use inline code.  This is a matter of personal preference, and either one will work to create a Custom Control.  For this article, we will use inline code.  When you create the User Control (say MyTestUC.ascx), VS creates it with the a @control directive that looks like this:
<%@ Control Language="C#" ClassName="MyTestUC" %>
This is fine, except for one thing: we want the class to live within a namespace of our choice (instead of 'ASP', which is what's used by default).  To do this, we simply modify the ClassName attribute to include the namespace (this is a new feature in 2.0).  e.g.
<%@ Control Language="C#" ClassName="Acme.MyTestUC" %>
That's really the only 'special' thing you need to do.  Now you can go ahead and implement your User Control as you always would: add some server control, some client HTML, server script, client script, etc...

Step 2: Testing your User Control

Before trying to turn the User Control into a Custom Control, it is a good idea to test it in the source app using a simple page.  To do this, simply create a new Page in Visual Studio, go to design View, and drag and drop your User Control into it.
The two notable pieces of your page are the Register directive:

<%@ Register Src="MyTestUC.ascx" TagName="MyTestUC" TagPrefix="uc1" %>

and the User Control declaration:

        <uc1:MyTestUC ID="MyTestUC1" runat="server" />

Note that at this point, the Register directive uses the User Control syntax (Src/TagName/TagPrefix) and not the Custom Control syntax (TagPrefix/Namespace/Assembly).  This will change after we turn the User Control into a Custom Control.
Run your page (Ctrl-F5) and make sure the User Control works the way you want before moving to the next step.


Step 3: Use the Publish command to precompile the site

The next step is to use the new Publish command to precompile your site and turn your User Control into a potential Custom Control.  You'll find the command under Build / Publish Web Site.  In the Publish dialog, do the following:
  • Pick a Target Location.  This is the location on your hard drive that your site will be precompiled to.
  • Uncheck 'Allow this precompiled site to be updatable'.  In updatable mode, only the code behing file (if any) would get compiled, and the ascx would be left unprocessed.  This is useful in some scenarios, but is not what you want here since you want the resulting DLL to be self contained.
  • Check 'Use fixed naming and single page assemblies'.  This will guarantee that your User Control will be compiled into a single assembly, which will have a name based on the ascx file.  If you don't check this, your User Control could be compiled together with other pages and User Controls (if you had some), and the assembly would get a random name that would be more difficult to work with.
Though it is entirely optional, note that the Publish Web Site dialog lets you strong name the generated assemblies.  This allows you to sign the assembly so that it cannot be tempered with.  Additionally, it allows you to place the assemblies in the Global Assembly Cache (GAC), which makes it easier to use machine wide.  More on this in Step 5.
Go ahead and complete the dialog, which will perform the precompilation.
Note: This same step can also be accomplished without using Visual Studio by using the new aspnet_compiler.exe command line tool.  The options it supports are basically the same as what you see in the Publish dialog.  So if you are more command line inclined, you might prefer that route.  e.g. you would invoke it using the command: 'aspnet_compiler -p c:\SourceApp -v myapp -fixednames c:\PrecompiledApp'.

Step 4: finding the resulting Custom Control

Now, using the Windows Explorer or a command line window, let's go to the directory you specified as the target so we can see what was generated.  You will see a number of files in there, but let's focus on the one that is relevant to our goal of turning the User Control into a Custom Control.
In the 'bin' directory, you will find a file named something like App_Web_MyTestUC.ascx.cdcab7d2.dll.  You are basically done, as this file is your User Control transformed into a Custom Control!  The only thing that's left to do is to actually use it.
Note: In case you're curious, the hex number within the file name (here 'cdcab7d2') is a hash code that represents the directory that the original file was in.  So all files at the root of your source app will use 'cdcab7d2', while files in other folders will use different numbers.  This is used to avoid naming conflicts in case you have files with the same name in different directories (which is very common for default.aspx!).

Step 5: Using your new Custom Control

Now that we have created our Custom Control, let's go ahead and use it in an app!  To do this, let's create a new Web application in Visual Studio.  We then need to make our Custom Control available to this application:
  • In the solution explorer, right click on your application, and choose Add Reference.
  • In the Add Reference dialog, choose the Browse tab.
  • Navigate to the location of your Custom Control (App_Web_MyTestUC.ascx.cdcab7d2.dll) and select it.  It will be copied to the bin directory of your new app.
Note: as an alternative, you can choose to place the assembly in the GAC instead of the 'bin' directory.  In order to do this, you need to choose the Strong Name option in Step 3.  You then need to add your assembly in the <assemblies> section of web.config in the Web application that wants to use it (or in machine.config to make to globally usable).
Now let's create a test page that uses the Custom Control.  This is similar to Step 2, except that you are now dealing with a Custom Control instead of a User Control.
First, add a Register directive to your page.  It should look something like this:

<%@ Register TagPrefix="Acme" Namespace="Acme" Assembly="App_Web_mytestuc.ascx.cdcab7d2" %>

Note how we are using a different set of attributes compared to Step 2.  Recall that in Step 1, we made sure that the ClassName attribute included a namespace.  This is where it becomes useful, as Custom Control registration is namespace based.  Also, you need to specify the assembly name, which is why having a name that is easily recognizable is useful, as discussed in Step 3.
Now, let's declare a tag for the Custom Control.  e.g.

    <Acme:MyTestUC id="MyUC" runat="server" />
That's it, you can now run your app (Ctrl-F5), and you are using your new Custom Control!
This shows how to use your Custom Control declaratively, but note that it can also be used dynamically, just like any other control.  To do this, just create the control using 'new'.  Here is what the previous sample would look like using dynamic instantiation:

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    
protected void Page_Load(object sender, EventArgs e) {
        Label1.Controls.Add(
new Acme.MyTestUC());
    
}</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<body>
    
<form id="form1" runat="server">
    
<div>
        
<asp:Label ID="Label1" runat="server"></asp:Label></div>
    
</form>
</body>
</html>


Note: instantiating your Custom Control dynamically as above is basically the equivalent of instantiating your original User Control using the LoadControl API.  Note that you can no longer use the standard LoadControl API after converting it to a Custom Control, since Custom Controls don't have a virtual path.  However, ASP.NET 2.0 has a new LoadControl override which takes a Type, and that you could use in this case.  The one reason I can think of that you might choose to call LoadControl instead of just using 'new' is to take advantage of fragment caching (aka partial caching).  If you use 'new', any OutputCache directive in your ascx will be ignored.

Conclusion

This article outlines how to turn a User Control into a Custom Control, in order to take advantage of the strength of each model.  While there are some limitations with this hybrid model (see Restrictions in Step 1), there are many scenarios for which it can be useful.
In the future, the ASP.NET team is looking at simplifying this scenario and make it more powerful with some new tools that are in the work.  For example, you would be able to take an entire application containing an App_Code directory and multiple User Control, and turn it all into a single assembly that can easily be dropped into the 'bin' directory of other apps.  Though it will allow some more powerful scenarios, note that the basic idea behind it is essentially the same as what is shown in this article.

Wednesday, 17 October 2012

Difference between MVC and 3-tier architecture

3-tier design

 MVC pattern
Meaning that:

1. In the 3-tier equivalent, communication between layers is bi-directional and always passes through the Middle tier

2. In the MVC equivalent the communication is in unidirectional; we could say that each "layer" is updated by the one at the left and, in turn, updates the one at the right –where "left" and "right" are merely illustrative

P.S. Client would be the View and Middle the Controller

Tuesday, 16 October 2012

ASP.NET MVC 3: CREATING A SIMPLE SIGN-UP FORM


In this article I'm going to demonstrate how to create a simple sign-up form using ASP.NET MVC 3. So basically in this demo you will learn the following:

How to insert data to the database with Entity Framework
How to validate the Form using Data Annotations
How to Authenticate users after sign up using FormsAuthentication

Note that before you continue reading this article be sure that you have the basic understanding about ASP.NET MVC in general. You can refer the following links below to learn more about ASP.NET MVC:

http://msdn.microsoft.com/en-us/library/dd381412%28VS.98%29.aspx
http://www.asp.net/mvc/whatisaspmvc



STEP 1. Adding a new ASP.NET MVC project

Let's go ahead and fire up Visual Studio 2010 and then select File -> New Project -> ASP.NET MVC 3 Web Application. See the screen shot below for more clearer view:



Now click OK and on the next form select Empty Template -> select Razor as the View engine and then click OK to generate the default files.


STEP 2: Setting up the Model

In this demo, I'm going to use Entity framework as our Data Access mechanism sothat we can program against the conceptual application model instead of progamming directly against  our database.

Add the following folders under the Models folder:

    DB
    ObjectManager
    ViewModel

The application structure would like something like below:




We will create our Entity Model (EDMX) in the DB folder. To do this right click on the "DB" folder and select Add -> New Item -> Data -> ADO.NET Entity Data Model. 



Noticed that I named the entity as "SampleModel" just for the purpose of this demo. You may want to name it to a more appropriate name based on your requirements but for this example let's just use "SampleModel". Now click Add to continue and on the next step select "Generate from database" and click Next. On the next step you can connect or browse to the database that you want to use in the application and test the connection string by clicking on the "Test Connection" button and if it succeeds then you can continue by clicking OK and then Next.

Note that in this example I created a simple database called "DeveloperReport.mdf" and added it into the application's App_Data folder and use it as our database. See the screen shot below:




On the next step we can add the table(s), views or stored procedures that we want to use in the application by selecting the checkbox. See below screenshot: 



Noticed that I've only selected the "SysUser" table. This is because we are going to use this table for doing insert and we don't need anything else. Now click on Finish button to generate the entity model for you. See the screenshot below: 



What happend there is that EF will automatically generates the Business object for you within the Entity Data Model(EDM) that we have just created and let you query against it.The EDM is the main gateway by which you retrieve objects from the database and resubmit changes.


STEP 3: Adding the ViewModel Class

Just to recap Entity Framework will generate the business objects and manage Data Access within the application. As a result, the class SysUser is automatically created by EF and it features all the fields in the database table as properties of the class.

I don't want to use this class direclty in the View so I decided to create a separate class that just holds the properties I need in the View. Now let's add a the UserView class by right-clicking on the "ViewModels" folder then select Add -> Class. Here's the code block for the "UserView.cs" class.
using System.ComponentModel.DataAnnotations;

namespace MVCDemo.Models.ViewModels {
    public class UserView {
        [Required]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }

        [Required]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }

        [Required]
        [Display(Name = "Contact Number")]
        public string ContactNumber { get; set; }

        [Required]
        [Display(Name = "Login ID")]
        public string LoginID { get; set; }

        [Required]
        [Display(Name = "Password")]
        public string Password { get; set; }
    }
}


Noticed that I added the Required and DisplayName attributes for each property in the UserView class. This attributes is called Data Annotations. Data annotations are attribute classes that live in the System.ComponentModel.DataAnnotations namespace that you can use to to decorate classes or properties to enforce pre-defined validation rules.

I'll use this validation technique because I want to keep a clear separation of concerns by using the MVC pattern and couple that with data annotations in the model, then your validation code becomes much simpler to write, maintain, and test.

For more information about Data Annotations then you can refer this link: http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx. And of course you can find more examples about it by doing a simple search at google /bing 


STEP 4: Adding the UserManager Class

The next step that we are going to do is to create the User manager class that would handle the (CRUD operations) create,update,fetch and delete operations of a certain table. The purpose of this class is to separate the actual data opertions from our controller and to have a central class for handling insert,update,fetch and delete operations. But please note that in this example I'm only be doing the insert part in which a user can add new data from the View to the database. I'll talk about how to do update,fetch and delete with MVC in my next article. So this time we'll just focus on the insertion part first.

Now right click on the "Model" folder and add a new class by selecting Add -> Class and since we are going to manipulate the SysUser table then we will name the class as "UserManager". Here's the code block for the "UserManager.cs" class:

using System.Linq;
using MVCDemo.Models.DB;
using MVCDemo.Models.ViewModels;

namespace MVCDemo.Models.ObjectManager {
    public class UserManager {

        private DeveloperReportEntities dre = new DeveloperReportEntities();

        public void Add(UserView user) {
            DB.SysUser sysUser = new DB.SysUser();
            sysUser.SysUserLoginID = user.LoginID;
            sysUser.SysPassword = user.Password;
            sysUser.FirstName = user.FirstName;
            sysUser.LastName = user.LastName;
            sysUser.ContactNumber = user.LastName;

            dre.AddToSysUsers(sysUser);
            dre.SaveChanges();
        }

        public bool IsUserLoginIDExist(string userLogIn) {
            return (from o in dre.SysUsers where o.SysUserLoginID == userLogIn select o).Any();
        }
    }
}


STEP 4: Adding the Controllers

Since our model is already set then let's go ahead and add the "AccountController". To do this just right click on the "Controllers" folder and select Add -> Controller. Since our aim is to create a simple sign-up form then name the controller as "AccountController" and then click Add to generate the "AccountController" class for you.

Now here's the code block for the "AccountController":

using System.Web.Mvc;
using System.Web.Security;
using MVCDemo.Models.ViewModels;
using MVCDemo.Models.ObjectManager;

namespace MVCDemo.Controllers
{
    public class AccountController : Controller
    {
        // GET: /Account/SignUp
        public ActionResult SignUp() {
            return View("SignUp");
        }

        // POST: /Account/SignUp
        [HttpPost]
        public ActionResult SignUp(UserView user) {
            try {
                if (ModelState.IsValid) {
                    UserManager userManager = new UserManager();
                    if (!userManager.IsUserLoginIDExist(user.LoginID)) {
                        userManager.Add(user);
                        FormsAuthentication.SetAuthCookie(user.FirstName, false);
                        return RedirectToAction("Welcome", "Home");
                    }
                    else {
                        ModelState.AddModelError("", "LogID already taken");
                    }
                }
            }
            catch {
                return View(user);
            }

            return View(user);
        }
    }
}

The AccountController has two main methods. The first one is the "SignUp" which returns the "SignUp.cshtml" View. The second one also named as "SignUp" but it is decorated with the "[HttpPost]" attribute. This attribute specifies that the overload of the "SignUp" method can be invoked only for POST requests.

The second method is responsible for inserting new entry to the database and automatically authenticate the users using FormsAuthentication.SetAuthCookie() method. this method creates an authentication ticket for the supplied user name and adds it to the cookies collection of the response, or to the URL if you are using cookieless authentication. After authenticating, we then redirect the users to the Welcome.cshtml page.

Now add another Controller and name it as "HomeController". This controller would be our controller for our default page. We will create the "Index" and the "Welcome" View for this controller in the next step. Here's the code for the "HomeController" class:
using System.Web.Mvc;

namespace MVCDemo.Controllers
{
    public class HomeController : Controller
    {
        // GET: /Home/
        public ActionResult Index()
        {
            return View();
        }

        [Authorize]
        public ActionResult Welcome() {
            return View();
        }

    }
}

Noticed that we have two ActionResult method in the "HomeController". The "Index" method serve as our default redirect page and the "Welcome" method will be the page where we redirect the users after they have successfully registered. We also decorated it with the "[Authorize]" attribute so that this method will only be available for the logged-in users. 

STEP 5: Adding the Views

First let's add the following folders below under the "Views" folder:

    Home
    Account

Note: The reason for this is that the folder name should match the name of the Controllers you've created. So if you have HomeController then you should have a "Home" folder within your View.

Now under the "Home" folder add a new View. To do this just right click on the "Home" folder and select Add -> View. Name the view as "Index" and click Add to generate the Web Page (.cshtml). Here's the mark-up of the Index.cshtml:
@{
    ViewBag.Title = "Welcome";
}

<h2>Welcome</h2>

@Html.ActionLink("Click here to sign-up", "SignUp", "Account")

As you can see there's no fancy about the mark-up above except that it contains the ActionLink which redirect you to the "SignUp" view within the "Account" folder. Now add again another View under the "Home" folder and name the view as "Welcome". The reason why we add the Welcome.cshtml view is because we will redirect the user in this page after they successfully signed up and nothing more. Here's the mark-up of the Welcome.cshtml:
@{
    ViewBag.Title = "Welcome";
}

<h2>Hi <b>@Context.User.Identity.Name</b>! Welcome to my website!</h2>
Now under the "Account" folder add a new view and name it as "SignUp" and check the checkbox that says "create a strongly-typed views and in the Model class dropdownlist select "UserView" and then in the Scaffold template select "Create" and finally click Add to generate the Web Page for you. Take a look at the screen shot below for more clearer view of what I am talking about:





And here's the generated mark up of the SignUp.cshtml:
@model MVCDemo.Models.ViewModels.UserView

@{
    ViewBag.Title = "SignUp";
}

<h2>Sign-Up</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>UserView</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.FirstName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.LastName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.LastName)
            @Html.ValidationMessageFor(model => model.LastName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ContactNumber)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ContactNumber)
            @Html.ValidationMessageFor(model => model.ContactNumber)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.LoginID)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.LoginID)
            @Html.ValidationMessageFor(model => model.LoginID)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Password)
        </div>
        <div class="editor-field">
            @Html.PasswordFor(model => model.Password)
            @Html.ValidationMessageFor(model => model.Password)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Return to Home page","Index", "Home")
</div>

The mark-up above is a strongly-type view. This strongly typed approach enables better compile-time checking of your code and richer IntelliSense in the Visual Studio editor. By including a @model statement at the top of the view template file, you can specify the type of object that the view expects. In this case it uses the MVCDemo.Models.ViewModels.UserView.

The View structure would like something like below:
 

STEP : Running the Application

Running the page will give you the following outputs:

On initial load:



After clicking on the Sign-Up link:



Sample screen shot that shows the validation



Completing the form



After successfully registered


What should you required to learn machine learning

  To learn machine learning, you will need to acquire a combination of technical skills and domain knowledge. Here are some of the things yo...