Updating tableadapters to use join

Dataset designer donot generate the auto insert, update and delete ad-hoc sql command when there is join in the select statement. But it generates for subquery. To introduce join in select statement, you first generate the CRUD statements without introducing join, and later we change it to introduce join. And if you use stored procedure, it doesnot affect the insert, delete and update command which remains intact.

Geek

Subquery or Join : which is better?

Ans: There is somewhat equal execution plan for both subquery and join. So there is almost no performance difference. But, join is generally used to find the existence of records whereas subquery is used to eliminate the duplicate the data.

some useful links: how to perform sql join

Developing simple custom controls

chapter 2: part 1 ( custom controls)

The word “render” has a special meaning in the context of server control development, which is different from the common meaning of the word where rendering refers to the Web browser’s task of displaying or rendering the HTMLmarkup that the browser receives from the server. Rendering in the context of server control development means generating the HTMLmarkup text that the server sends to the browser. In other words, server controls render (generate) the HTMLmarkup text that browsers render (display).

At runtime, the containing page creates an instance of a class named HtmlTextWriter and passes the instance into the Render methods of the server controls that the page contains. The HtmlTextWriter class exposes a method named write that these server controls can use to write out their HTMLmarkup text.

Adding Design-Time Attributes to Your Custom Controls

Property level attributes

[BrowsableAttribute(true)]

[DescriptionAttribute(“Gets and sets the payment method”)]

[DefaultValueAttribute(“Payment Method”)]

[CategoryAttribute(“Appearance”)]

public virtual string PaymentMethodText

{

get { return this.paymentMethodText; }

set { this.paymentMethodText = value; }

}

This code takes the following actions:

1. Annotates the PaymentMethodText property with the BrowsableAttribute(true) attribute to instruct the property browser to display the name and value of this property. By default, every public property is considered browsable. You should use this attribute on read-only properties to tell the property browser not to display them because there is no point in displaying a property if page developers can’t change its value.

2. Annotates the property with the DescriptionAttribute(“Gets and sets the payment method”) attribute to instruct the property browser to display the text “Gets and sets the payment method” every time the page developer selects the property.

3. Annotates the property with the DefaultValueAttribute(“Payment Method”) attribute to instruct the property browser to display the text “Payment Method” as the default value of the property.

4. Annotates the property with the CategoryAttribute(“Appearance”) attribute to instruct the property browser to display this property under the Appearance category.

Class level Attributes

When page developers select a server control in Visual Studio, they expect to see a particular property

of the control highlighted. This property is known as the default property of the server control. The following code annotates the CreditCardForm2 custom control with the DefaultPropertyAttribute(“CardholderNameText”) to mark the CardholderNameText property as the default property:

DefaultPropertyAttribute(“CardholderNameText”)]

public class CreditCardForm2 : Control

The following code annotates the CreditCardForm2 custom control with the class-level attribute ToolboxDataAttribute to specify default values for the properties of the CreditCardForm2 control:

[ToolboxData(“<{0}:CreditCardForm2 PaymentMethodText=’Payment Options’ CreditCardNoText=’Credit Card Number’ CardholderNameText=’Cardholder Full Name’

SubmitButtonText = ‘Send’ runat=’server’></{0}:CreditCardForm2>”)]

public class CreditCardForm2 : Control

This attribute instructs the designer to add the following line to the .aspx page when the page developer drags CreditCardForm2 from the Toolbox onto the designer surface:

<ccl:CreditCardForm2 runat=’server’ CardholderNameText=’Cardholder Full Name’ CreditCardNoText=’Credit Card Number’ PaymentMethodText=’Payment Options’ SubmitButtonText=’Send’></ccl:CreditCardForm2>

Assembly-Level Attributes

As discussed, when page developers drag a CreditCardForm2 control from the Toolbox onto the design

surface, the designer adds the following two lines to the .aspx file:

<%@ Register Assembly=”CustomComponents” Namespace=”CustomComponents”

TagPrefix=”cc1” %>

<cc1:CreditCardForm2 ID=”CreditCardForm2” runat=”server”/>

Notice that the designer uses the default cc1 as the prefix. You can add the following assembly-level attribute to the AssemblyInfo.cs file to instruct the designer to use “custom” as the tag prefix:

using System.Web.UI;

[assembly: TagPrefix(“CustomComponents”,”custom”)]

The HtmlTextWriter-Related Enumerations

public class CreditCardForm3 : CreditCardForm2

{

protected override void Render(HtmlTextWriter writer)

{

writer.AddStyleAttribute(HtmlTextWriterStyle.Width,“287px”);

writer.AddStyleAttribute(HtmlTextWriterStyle.Height, “124px”);

writer.AddStyleAttribute(HtmlTextWriterStyle.BorderWidth, “0”);

writer.AddAttribute(HtmlTextWriterAttribute.Id, “mytable”);

writer.RenderBeginTag(HtmlTextWriterTag.Table);

writer.RenderBeginTag(HtmlTextWriterTag.Tr);

writer.RenderBeginTag(HtmlTextWriterTag.Td);

writer.Write(PaymentMethodText);

writer.RenderEndTag();

writer.RenderBeginTag(HtmlTextWriterTag.Td);

writer.AddAttribute(HtmlTextWriterAttribute.Name, “PaymentMethod”);

writer.AddAttribute(HtmlTextWriterAttribute.Id, “PaymentMethod”);

writer.AddStyleAttribute(HtmlTextWriterStyle.Width, “100%”);

writer.RenderBeginTag(HtmlTextWriterTag.Select);

writer.AddAttribute(HtmlTextWriterAttribute.Value, “0”);

The HtmlTextWriter class exposes one method for rendering each of the preceding parts as follows:

RenderBeginTag: Renders or generates the opening tag of an HTMLelement.

AddAttribute: This method is called once for each attribute to generate or render the attribute on the opening tag of the HTMLelement. This method must be called before RenderBeginTag.

AddStyleAttribute: This method is called once for each style attribute to generate or render the attribute as part of the style attribute of the HTMLelement. This method must also be called before RenderBeginTag. ASP.NET automatically generates a single attribute named style that contains all of the style attributes such as width, height, and so on. In other words, multiple calls of the AddStyleAttribute method are accumulated in a single style attribute on the opening tag of the element.

Write: Recall that an HTMLelement can contain text, other elements, or both. Use the Write method to generate any type of textual content such as string, int, float, and so on. You should use the RenderBeginTag, AddAttribute, AddStyleAttribute, and RenderEndTag methods to generate non-textual content, that is, child elements of an element.

RenderEndTag: Renders or generates the closing tag of an HTMLelement.

writer.AddStyleAttribute(HtmlTextWriterStyle.Width, “287px”);

writer.AddStyleAttribute(HtmlTextWriterStyle.Height, “124px”);

writer.AddStyleAttribute(HtmlTextWriterStyle.BorderWidth, “0”);

writer.AddAttribute(HtmlTextWriterAttribute.Id, “mytable”);

writer.RenderBeginTag(HtmlTextWriterTag.Table);

Writer.RenderEndTag();

State Management

public class CreditCardForm4 : CreditCardForm3

{

public override string PaymentMethodText

{

get { return ViewState[“PaymentMethodText”] != null ?

(string)ViewState[“PaymentMethodText”] : “PaymentMethod”; }

set { ViewState[“PaymentMethodText”] = value; }

}

public override string CreditCardNoText

{

get { return ViewState[“CreditCardNoText”] != null ?

(string)ViewState[“CreditCardNoText”] : “CreditCardNo”; }

set { ViewState[“CreditCardNoText”] = value; }

}

After converting each object to its string representation, ASP.NET stores these string values to a hidden field named __VIEWSTATE and sends them to the client. Therefore, the size of the string representations of the objects you store in ViewState matters.

When it comes to storing objects to ViewState you must keep the following two important things in mind:

ViewState is optimized to convert certain types such as System.String, System.Int32, System.Boolean, System.Drawing.Color, System.Unit, and Hashtable, Array, and ArrayList of Int32, Boolean, Color, and Unit values. If your custom control needs to store

other types to ViewState, you should write a custom type converter that is optimized to convert your custom type to its string representation.

Because the string representations of the objects you add to ViewState are stored on the ASP.NET page, you must store only necessary information to ViewState to reduce the size of the ASP.NET page. For example, you shouldn’t store values that you can easily evaluate for each

request.

The ASP.NET 2.0 Framework

I’m going to show developing asp.net web server controls as a multipart series. This has been completely referenced from Professional ASP.NET 2.0 server control and component development book written by Dr. Shahram Khosravi.

Chapter 1:

ASP.NET is a framework that processes request for web resources.

Everything starts when the user attempts to download the Default.aspx page; that is, the user makes a request for this page. Internet Information Services (IIS) picks up the request and passes it to an ISAPI extension named aspnet_isapi.dll. After passing through some intermediary components, the request finally arrives in a .NET component named HttpRuntime. This component creates an instance of a .NET class named HttpContext that contains the complete information about the request, and exposes this information in the form of well-known, convenient managed objects such as Request, Response, Server, and so on. The request finally arrives in a .NET component named HttpApplication. This component creates a pipeline of .NET components known as HTTP modules to perform pre-processing operations such as authentication and authorization. The results of these operations are stored in the HttpContext object. After HTTPmodules pre-process the request, HttpApplication passes the pre-processed request to a component known as an HTTPHandler. The main responsibility of an HTTPHandler is to generate the markup text that is sent back to the requester as part of the response. Different types of HTTPHandlers generate different types of markup texts. For example, the HTTPhandler that handles the requests for the .aspx extension, such as the Default.aspx page shown in Listing 1-1, generates HTMLmarkup text. The HTTPhandler that handles the requests for the .asmx extension, on the other hand, generates XML markup text. Therefore, ASP.NET instantiates and initializes the appropriate HTTPHandler to handle or process the request for the specified extension.

WHY DEVELOP CUSTOM CONTROLS?

You need to develop custom components because there are many situations in which the contributions of the existing standard ASP.NET components do not add up to the markup text that would adequately service the request. In following sections, we’ll cover situations to give you a flavour of what you can achieve with the skills, knowledge, and experience that this book provides you.

1.

  1. Data source controls
  2. Role manager modules and principals
  3. Role providers
  4. Membership providers
  5. Customizing web services and their clients
  6. Developing Ajax enabled controls and components
  7. Developing web part controls
  8. Developing custom data control fields
  9. Developing custom http handlers and modules
  10. Developing custom provider-based services

asdfasdfasdf

asdfasdfasdf

Microsoft…words from Bigyan RajBhandari

Well, there are few things. First ‘aspiration’, I have always wanted to work for the software giant, the fact that you have opportunity to impact millions of people by your work is impassable. Second, working with smarter people and chance to learn new things every day is appealing. And rest like benefits, location etc.. are definitely added bonus.

Good Developer’s Most Essential Qualities

Good Communication skills – In the software world, people usually define good communication skills as fluency in a spoken language. That’s not really what it is. It is how effectively you are able to communicate with others. As a ‘good’ developer, you should be able to express yourself well, listen well, as well as manage the communication process well.

Positive Attitude – ‘Your attitude determines your altitude’. I am sure you must have heard that phrase. From a developer’s context, this means believe in you, stop blaming others and adapt to changes without fretting. Remember that you always get what you want because you always want what you get.

Read Books – Read plenty of them to get a good idea of different technologies. Reading books gives you quick and handy insight into a technology. You should choose books that are usually written by known professionals who recommend best practices and different methods of solving a business problem using the technology. During the course of time, you will learn to develop your own methods. Who knows you may one day write a book!!

Practice, Practice and Practice – I have seen a lot of developers having good amount of theoretical knowledge. They read a lot of books and technical material. However when it comes to applying that knowledge, they take a back foot. That is because they do not practice. Efficiency and effectiveness in your work can only be attained if you practice code. The only way you can make a good developer of yourself is to practice, and then practice some more.

Follow Patterns and Best Practices – Patterns & practices reflect technical guidance, technical problem domain and engineering practices based on real-world experiences. The process to learn it is gradual, but once done; it can save you a lot of time and efforts and enable you to work smartly. Follow a Code Design Guideline. Always use a code analysis tools that will evaluate and analyze your code.

Discussion/Newsgroup – Participating in communities develops the quality of leadership and contribution, both ingredients of success. Having participated in a good technical discussion on the community leaves you with a feeling of self-satisfaction. It also increases your knowledge, as you find smart people who can validate your solutions, as you validate theirs. It also teaches you to appreciate suggestions. Do not forget to ‘pat someone on the back’ if he/her has made a positive contribution. Believe me it makes all the difference.

Knowledge of Networking and Databases – People may contradict this point, but during my career as a developer, I have realized that a good developer should know the basics of networking and databases. Almost all the solutions that we create, involve interactions with networks and databases. Having knowledge of these two, helps you write better code and saves you on a lot of time too.

Blog/ Write Articles – How many of us can remember everything? I cannot. So I document them. It helps me to reference stuff when I need them. Over and above, it also helps me get some good feedback from readers and shows me multiple approaches to do the same stuff. I have received a lot of feedback about my work, some good and some not so good. However, I do validate them and learn from this process. It develops the developer in you.

KISS – Keep Implementations/Approaches Short and Simple. Do not over complicate things by using jargons, which people find it hard to understand. The key is to simplify your designs and avoid over-engineering things.

Think as a Tester – Developers and Testers; two sets of people from different camps, ready to take on each other. I have observed that the intersection of the two produces good results. It does not harm taking off the developer’s hat for some time and putting on the tester’s hat. In fact, in the long run it helps you reduce bugs/defects in your code. You develop a mindset of about breaking your code, when you are creating one.

Consistency is the name of the game – Do you hop jobs too often or are bitten by the ‘salary’ bug? If yes, then it’s time for you to sit down, relax and plan. Invest time in thinking and let your decisions not be spontaneous. To move ahead, you need a solid foundation and that comes with consistency.

Attend technology seminars and events – If there is one hosted in your city, make sure you take out time to attend one. Most of them are free and provide a valuable source of information about new technologies.

Jack of all or Master of One? – Well that’s a difficult one to answer. In today’s scenario, you have to master more than one technology. Practically it is quiet difficult to do so, but the good ones do it. However the key is adaptability over here. If you are good at any one technology and confident in it, given an opportunity, it would be easier for to relate to a new technology in a short period of time. Try it out as it enables you to compare technologies and make decisions, once you have worked with them.

Stop complaining – Did the software fail or are the testers giving you a tough time by finding a lot of bugs? A natural tendency for a lot of developers is to react and then overreact in such situations. While the reaction is natural, it may not be desirable. Analyze why the software failed or why was the bug reported. It is going to be a learning experience and will help you in your future projects.

At the end, just remember that you are not going to remain a programmer for ever. So once you are satisfied and get a feeling that you have proven yourself as a good programmer, it’s time to re-program yourself. Expand your interests. Development is just a part of the process. Understanding the users and business is in itself an art, one should aim for and should master over a period of time

My Nuwakot Cycling Adventure

dasd

Factory Method Design Pattern

The factory method pattern is a design pattern that allows for the creation of objects without specifying the type of object that is to be created in code. A factory class contains a method that allows determination of the created type at run-time.

What is the Factory Method Pattern?

The factory pattern is a Gang of Four design pattern. This is a creational pattern as it is to control class instantiation. The factory pattern is used to replace class constructors, abstracting the process of object generation so that the type of the object instantiated can be determined at run-time.

A good example of the use of the factory pattern is when creating a connection to a data source if the type of the data source will be selected by the end-user using a graphical interface. In this case, an abstract class named “DataSource” may be created that defines the base functionality of all data sources. Many concrete subclasses may be created, perhaps “SqlDataSource”, “XmlDataSource”, “CsvDataSource”, etc, each with specific functionality for a different type of data. At run-time, a further class, perhaps named “DataSourceFactory”, generates objects of the correct concrete class based upon a parameter passed to the factory method.


The UML class diagram above describes an implementation of the factory method design pattern. In this diagram there are four classes:

  • FactoryBase. This is an abstract base class for the concrete factory classes that will actually generate new objects. This class could be a simple interface containing the signature for the factory method. However, generally an abstract class will be used so that other standard functionality can be included and inherited by subclasses. In simple situations the factory method may be implemented in full here, rather than being declared as abstract.
  • ConcreteFactory. Inheriting from the FactoryBase class, the concrete factory classes inherit the actual factory method. This is overridden with the object generation code unless already implemented in full in the base class.
  • ProductBase. This abstract class is the base class for the types of object that the factory can create. It is also the return type for the factory method. Again, this can be a simple interface if no general functionality is to be inherited by its subclasses.
  • ConcreteProduct. Multiple subclasses of the Product class are defined, each containing specific functionality. Objects of these classes are generated by the factory method.

The following code shows the basic code of the factory method design pattern implemented using C#:

public abstract class FactoryBase
{
public abstract Product FactoryMethod(int type);
}


public class ConcreteFactory : FactoryBase
{
public override Product FactoryMethod(int type)
{
switch (type)
{
case 1:
return new ConcreteProduct1();

case 2:
return new ConcreteProduct2();

default:
throw new ArgumentException("Invalid type.", "type");
}
}
}


public abstract class ProductBase { }

public class ConcreteProduct1 : ProductBase { }



public class ConcreteProduct2 : ProductBase { }


In this skeleton structure you can see five distinct classes. The first of these is the FactoryBase class. This is the base class for all concrete factories. A single abstract method is declared, accepting a parameter specifying the type of object to create and returning a Product instance.

The ConcreteFactory class is derived from FactoryBase. This class is used to generate product objects. You can see that the FactoryMethod method overrides the base class version. It accepts an integer parameter and uses this in a switch statement to decide which type of product to instantiate and return. If the parameter is invalid, an exception is thrown.

The ProductBase class is the base class for all classes that can be created by the factory. When a new object is instantiated by the factory it is returned in a ProductBase object.

Finally we have two subclasses of ProductBase. These are the concrete products that can be created by the factory and would contain the specialised functionality required for each type.

Example Factory Method

To show a simple example of the factory method design pattern in action, we will create two factories that generate car objects. Each factory will be responsible for a different manufacturer of car. The generated objects could be objects that represent cars in a racing game.

public abstract class CarFactory
{
public abstract Car CreateCar(string model);
}


public class HyundaiCarFactory : CarFactory
{
public override Car CreateCar(string model)
{
switch (model.ToLower())
{
case "coupe":
return new HyundaiCoupe();

case "i30":
return new HyundaiI30();

default:
throw new ArgumentException("Invalid model.", "model");
}
}
}


public class MazdaCarFactory : CarFactory
{
public override Car CreateCar(string model)
{
switch (model.ToLower())
{
case "mx5":
return new MazdaMX5();

case "6":
return new Mazda6();

default:
throw new ArgumentException("Invalid model.", "model");
}
}
}


public abstract class Car { }

public class HyundaiCoupe : Car { }

public class HyundaiI30 : Car { }

public class MazdaMX5 : Car { }

public class Mazda6 : Car { }

Testing the Factory Method

The above implementation of the factory method pattern can now be tested. The following sample code uses one of the factories to create a new Car object using a parameter that could have been selected by the player at run-time. When the object’s underlying type is outputted, we can see that the correct car subclass was selected.


CarFactory hyundai = new HyundaiCarFactory();
Car coupe = hyundai.CreateCar("coupe");
Console.WriteLine(coupe.GetType()); // Outputs "HyundaiCoupe"


C# Type Conversion with the "As" Operator

Implicit casting occurs when an object is assigned as the value of a variable or method parameter. It happens if the target variable is of a compatible type that is higher in the inheritance hierarchy (a superclass), or is of an interface that is implemented by the object‘s class, either directly or indirectly. In these cases, no additional work is required of the developer; the conversion happens automatically.

Explicit casting must be used when the conversion is in the opposite direction to that required by implicit casting. For example, when casting an object to one of its subclasses or casting from an interface to a class. To perform explicit casting, the cast operator is used.

class Program

{

static void Main(string[] args)

{

Subclass sub = new Subclass();

Superclass super = sub; // Implicit cast

Subclass sub2 = (Subclass)super; // Explicit cast

}

}

class Superclass { }

class Subclass : Superclass { }

Explicit casting is useful but can be problematic when the variable

being cast is not compatible with the target type. In this situation an

exception is thrown. This can be demonstrated by modifying the contents of the Main method in the previous example as follows:

Superclass super = new Superclass();

Subclass sub = (Subclass)super; // Exception

The “as” Operator

C# includes another method of performing explicit conversions. Using the “as” operator, an object can be converted from one type to another. Unlike with explicit casting, if the conversion is not possible because the types are incompatible the operation does not throw an exception. Instead, the resultant variable simply contains null.

Subclass sub = new Subclass();

Superclass super = sub;

Subclass sub2 = super as Subclass;

Instead of throwing an exception, the target variable is assigned the

null value. This can then be checked for and appropriate action taken.

Superclass super = new Superclass();

Subclass sub = super as Subclass;

if (sub == null)

Console.WriteLine(“Incompatible!”); // Outputs “Incompatible!”