Tuesday, May 01, 2007
Developing a Simple Custom Control
I will name the control FoodMards.ascx. The first step will be to add the DropDownList control on to the form.
//Create a Class level Dataset object
#code
private DataSet dsFoodMard;
#end code
Create a BindData function that pulls all of the data into the drop down list:
#code
private void BindData()
{
dsFoodMard = new DataSet();
SqlConnection cnn = new SqlConnection("Data Source=(local);Initial
Catalog=pubs;Integrated Security=SSPI");
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand("SELECT FoodMard_id, FoodMard _name, FoodMard_address, city, state, zip FROM FoodMard", cnn);
adapter.Fill(dsFoodMard, "FoodMard");
storeList.DataSource = dsFoodMard;
storeList.DataMember = "FoodMard";
storeList.DataTextField = "FoodMard_name";
storeList.DataBind();
Session.Add("Data", dsFoodMard);
}
#end code
I added the DataSet object to the Session variable in order to have the data available throughout the duration of the session and when passing the data during the firing of our Control Event. Make sure the Page_OnLoad event is properly filled out:
#code
private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
BindData();
}
}
#end code
Let's test the code by dragging the new control onto the aspx page and running the project:
Paging with ASP.NET Repeater Control

The PagedDataSource class encapsulates the properties of the DataGrid control that allow it to perform paging. But we can use the class with Repeater and DataList controls to perform paging in much the same way as a DataGrid. The Repeater control is great for situations, where you need a finer degree of control over the emitted HTML in order to layout the content in a unique or precise manner. One drawback to the Repeater is that it does not have built-in paging capability, a feature the DataGrid offers. Since I would need to display potentially hundreds of records in the catalog, it was essential that I provided paging support for the Repeater.
The Repeater control is great for situations, where you need a finer degree of control over the emitted HTML in order to layout the content in a unique or precise manner. One drawback to the Repeater is that it does not have built-in paging capability, a feature the DataGrid offers. Since I would need to display potentially hundreds of records in the catalog, it was essential that I provided paging support for the Repeater.Conclusion
As you can see, adding the paging functionality%2
Some of the .Net Features
Networking Features in .NET Framework 2.0
The System.Net.NetworkInformation namespace contains a number of new classes that allow you to access network information about the local computer. The accessible information includes items such as the number of network cards configured on the machine, IP address, and the configuration settings of each card. Many of the classes in the NetworkInformation namespace provide respective static GetXXX methods to retrieve instances of whatever configuration or information object they represent.
- IPAddressInformation-- Allows you to get information (such as the IP address) about a network interface address
- IPGlobalProperties-- Allows you to get information about the network connectivity (such as domain name, host name) of the local computer
- IPGlobalStatistics-- As the name suggests, this class provides information about IP statistical data
- IPInterfaceProperties-- Allows you to get information about the network interfaces that support IPv4 or IPv6 protocols
- NetworkChange-- Allows you to detect changes in the network such as when the IP address of a network interface changes
- NetworkInterface-- Represents the network interface and provides configuration and statistical information about a network interface
- PhysicalAddress-- This class represents the MAC address for a network interface
- Ping-- This class provides you with the ability to determine if a remote computer is accessible over the network
- TcpStatistics-- Allows you to get information about TCP statistical data such as the current TCP connections, maximum allowed connections and so on
- UdpStatistics-- Allows you to get UDP statistical information such as the number of UDP data grams that were received and sent
Refractoring
Making changes to your code like, "pulling a large stretch of inline code into its own method" or "converting a field to be a property." The Refactoring support makes this easy to do The key tenet of Extreme Programming created by Kent Beck is constant Refactoring. Under this programming model, you are developing code rapidly and iteratively, but to keep your code from becoming a jumbled mess, you must constantly Refactor. Refactoring is a C# only feature
Generics
Generic Interface represents a collection of objects that can be individually accessed by index. First, you will need to import the System.Collections.Generic namespace.
using System.Collections.Generic;
The System.Collections.Generic namespace contains interfaces and classes that define generic collections, which allow users to create strongly typed collections that provide better type safety and performance than non-generic strongly typed collections.
Class Library (DLL) Using Visual Studio .NET
DLLs are Dynamic Link Libraries, which means that they're linked into your program at run time instead of build time. There are three parts to a DLL:
· the exports
· the code and data
· the import library
Dynamic linking differs from static linking in that it allows an executable module (either a DLL or .EXE file) to include only the information needed at run time to locate the executable code for a DLL function. In static linking, the linker gets all of the referenced functions from the static link library and places it with your code into your executable.Using dynamic linking instead of static linking offers several advantages. DLLs save memory, reduce swapping, save disk space, upgrade easier, provide after-market support, provide a mechanism to extend the MFC library classes, support Multilanguage programs, and ease the creation of international versions.The different kind of DLL’s available in Dot Net.
In order to create your own dlls first open the Visual studio then
1) File->New->Project-> select the Class Library template.
2) After opening the editor you will find the below code:
using System;
namespace ClassLibrary1{
///
///
{
public Class1(){
//
// TODO: Add constructor logic here
}
// Write your functions properties here.}}
3) Build the solution. This will create the dll in the bin directory.
Friday, June 23, 2006
Since this is new ground for many developers, let's start out with some definitions of the key terms.
Metadata - In the most generic terms, when you have a thing, then the data that describes that thing is called metadata. In the context of .NET and types, metadata describes the information about the type itself: its constructors, methods, properties, etc.
Reflection - Reflection is the process of walking the metadata about a type and finding out things; for instance, how many constructors a type has, and what the parameters are. It also allows you to dynamically create and invoke types.
System.Reflection.Assembly:
It defines an assembly which is a reusable,versionable and self describing building block of a Common Language Run time application.I will discuss here only the functions that I have used in my code.
objAssembly=System.Reflection.Assembly.LoadFrom(str);
LoadFrom function takes the path of the assembly to load and loads it and returns that Assembly.
After loading the assembly we want to get all the types in that assembly.This class provides a function GetTypes() (It returns an array of System.Type objects in that assembly) which will do that for us and that line for the code is.
arOfTypes=objAssembly.GetTypes();
Now having touched System.Type class,Let us talk about it.
System.Type:
This class represents type declarations.(class types,interface types,array types,value types and enumeration types.)
It is the root of all Reflection operations.It is the primary means by which we access metadata and it acts as a Gateway to Reflection API.It provides methods for obtaining information about a Type declaration, such as the constructors,properties,methods and Events.
public class MagicConverter
{
public MagicConverter()
{
[...]
}
public MagicConverter(double quantumFlux)
{
[...]
}
public double QuantumFlux
{
get
{
[...]
}
set
{
[...]
}
}
protected double SpeedOfLight
{
get
{
[...]
}
}
public SillyClass PerformConversion(double accelerant, double fudgeFactor)
{
[...]
}
}
Extracting Constructor Information:
ConstructorInfo[] ctrInfo=t.GetConstructors(); //t is an object of type System.Type.This method returns an array of objects of type ConstructorInfo.This calss is part of System.Reflection Name space
Extracting Properties Information:
PropertyInfo[] pInfo = t.GetProperties() ;//t is an object of type System.Type.This method returns an array of objects of type PropertyInfo.This calss is part of System.Reflection Name space.
Extracting Method Information:
MethodInfo[] mInfo=t.GetMethods();
For e.g
foreach (MethodInfo mi in typeInfo.GetMethods())
{
Console.WriteLine("{0}(...)", mi.Name);
}Which results in:
GetHashCode(...)
Equals(...)
ToString(...)
get_QuantumFlux(...)
set_QuantumFlux(...)
PerformConversion(...)
GetType(...)
· We can call MemberType on the MethodInfo object to find out what type of methods we're looking at. The member types include Methods, Properties, Fields, Events, and Constructors.
· We can also find out what the visibility of the method is, using the set of properties on the MethodInfo like IsPublic, IsPrivate, IsVirtual.
· We can get the TypeInfo for the return type from the method using the ReturnType property.
Extracting Event Information:
EventInfo[] eInfo=t.GetEvents();
Once I get all this info,I am presenting it in a tree view control.This should fairly give a good idea of getting information about a Type.
Once you know all the information about a class,What do you want to do?Probably you want to create an instance of that class and execute one of its methods.Let us look at this code.
Type t= Type.GetType("MyReflection.MyClass1");
Let us look at Activator class and see what we can do with this class and Type class.
System.Activator:
This class contains methods to create types of objects locally or remotely or obtain references to existing objects.I have used CreateInstance() of this class to create an instance of MyClass1.This method needs a Type object as argument to creat an instance of that type.It returns an object.Next I have used GetType() on object and then used InvokeMember() on the Type object to invoke method M1 of MyClass1.Here is that piece of code.
obj1=Activator.CreateInstance(t);
obj1.GetType().InvokeMember("M1",BindingFlags.Default BindingFlags.InvokeMethod,null,obj1,new object[]{});
For starters, reflection can be rather expensive, so you should do it sparingly, caching the results wherever possible. Also, the de-coupling that happens when things are done indirectly through reflection is a double edged sword, because it can be difficult to figure out which code depends on which other code; debugging reflection-heavy code can also be quite a burden sometimes.
Reflection in moderation is very powerful.
Friday, June 16, 2006
Key points for VB.Net
Array Declarations:Unspecified array element sizes are also to be dropped, so declarations such as:
Dim arrData() As String
will no longer be accepted. Array declarations must include the number of elements, as follows:
Dim arrData(5) As String
This will result in an array with 5 elements, with indexes 0 to 4.
Direct control Referencing:Calling controls on a form externally, from a BAS module currently works as all controls are Public, but VB.NET requires controls to be declared as Public Shared for this to continue working. Ideally, controls should be referenced through Public Property Get and Let procedures as used in classes.
Sub & Function Declarations:All parameters passed to procedures must either be ByVal or ByRef explicitly. With VB.NET, ByVal is the default, but parameters must be declared ByRef if the procedure is to change those parameters.
Default Optional Parameters:Optional parameters in VB.NET will be handled differently. At present, omitted optional parameters can be determined with the IsMissing keyword. However, this keyword is to be dropped and all optional parameters must have default values assigned in the event of omissions.
Variable Declarations:
The rules defining variable declarations are to change, by including new syntax and not supporting some of the current syntax. Multiple datatype declarations can be coded on one line as follows:
Dim strName as String, intAge as Integer, decSalary as Decimal
While default datatype declarations such as:
Dim Wage, ShoeSize as Integer
where Wage would have become Variant in VB6, will become Integer in VB.NET. Unless screen space is a real issue, play safe and declare variables on separate lines.
Currency and Variant Datatype to go:
VB.NET will no longer support currency and variant datatypes. Currency will be replaced with the new 64 bit Long datatype (or Decimal datatype). NOTE: Datatypes cannot be declared as Decimal, but can be converted using cDec to make them a Decimal subtype.
Variant datatypes are to be replaced with Object datatypes for most purposes, but best avoided if possible, especially where a more appropriate datatype can be employed.
API Call Arguments:
As the Long datatype in VB.NET will be 64 bit, and Win32 API calls accept 32 bit Long arguments, most API calls will fail unless these arguments are re-declared as the new Integer datatype. To clarify....
VB6's Integer will become 'Short' in VB.NET; VB6's Long will become 'Integer' in VB.NET; and VB.NET new 64 bit 'Long' doesn't have an equivalent in VB6.
Split out your Business and Presentation Logic
Look for opportunities to encapsulate your logic in classes, as classes are the easiest modules to migrate to VB.NET. Where your applications are based around rich clients containing a mixture of business and presentation logic, these will prove the most difficult to accommodate. Ideally, the more logic you have in components and classes, and the thinner client, the better. This is due to the introduction of WebForms and WinForms, and a greater distinction between the UI and code components/classes.
