Friday, 16 January 2015

Recommendations for Abstract Classes vs. Interfaces

The choice of whether to design your functionality as an interface or an abstract class (a MustInherit class in Visual Basic) can sometimes be a difficult one. An abstract class is a class that cannot be instantiated, but must be inherited from. An abstract class may be fully implemented, but is more usually partially implemented or not implemented at all, thereby encapsulating common functionality for inherited classes. For details, see Abstract Classes.
An interface, by contrast, is a totally abstract set of members that can be thought of as defining a contract for conduct. The implementation of an interface is left completely to the developer.
Both interfaces and abstract classes are useful for component interaction. If a method requires an interface as an argument, then any object that implements that interface can be used in the argument. For example:
' Visual Basic
Public Sub Spin (ByVal widget As IWidget)
End Sub
// C#
public void Spin (IWidget widget)
{}
This method could accept any object that implemented IWidget as the widget argument, even though the implementations of IWidget might be quite different. Abstract classes also allow for this kind of polymorphism, but with a few caveats:
  • Classes may inherit from only one base class, so if you want to use abstract classes to provide polymorphism to a group of classes, they must all inherit from that class.
  • Abstract classes may also provide members that have already been implemented. Therefore, you can ensure a certain amount of identical functionality with an abstract class, but cannot with an interface.
Here are some recommendations to help you to decide whether to use an interface or an abstract class to provide polymorphism for your components.
  • If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
  • If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
  • If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
  • If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.

Wednesday, 3 April 2013

Generate Password in Sql


--Select dbo.ufn_GeneratePassword(8)
CREATE VIEW [dbo].[RandomNewID]
AS
SELECT NEWID() AS [NewID]
GO


Alter FUNCTION [dbo].[ufn_GeneratePassword] ( @PasswordLength INT )
RETURNS VARCHAR(20)
AS
BEGIN


DECLARE @Password     VARCHAR(20)
DECLARE @ValidCharacters   VARCHAR(100)
DECLARE @PasswordIndex    INT
DECLARE @CharacterLocation   INT


SET @ValidCharacters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890'




SET @PasswordIndex = 1
SET @Password = ''


WHILE @PasswordIndex <= @PasswordLength
BEGIN
 SELECT @CharacterLocation = ABS(CAST(CAST([NewID] AS VARBINARY) AS INT)) %
LEN(@ValidCharacters) + 1
 FROM [dbo].[RandomNewID]


 SET @Password = @Password + SUBSTRING(@ValidCharacters, @CharacterLocation, 1)


 SET @PasswordIndex = @PasswordIndex + 1
END


RETURN @Password


END

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.

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...