Welcome to fuzzydev Sign in | Join | Help
in Search

.Net

  • Shrink SQL Server Log File

    I have hosted my site on a shared hosting server and have to live with the reality of limited database/web space, recently my database space was shooting up and I was really worried about it.

    My posting (blogs) are not too long to reach a whopping 114 MB and so I was stunned to see the database size. After carefull investigation of each table I thought of checking at database level using the below given sp...

    sp_helpdb 'DATABASE_NAME'

    To my surprise I found the data file size as 10 MB and 104 MB was my log file. After googling for right way to shrink the log file, I found a really simple and perfect one...

    USE DATABASE_NAME;

    GO

    -- Truncate the log by changing the database recovery model to SIMPLE.

    ALTER DATABASE DATABASE_NAME

    SET RECOVERY SIMPLE;

    GO

    -- Shrink the truncated log file to 1 MB.

    DBCC SHRINKFILE (LOF_FILE_NAME, 1);

    GO

    -- Reset the database recovery model.

    ALTER DATABASE DATABASE_NAME

    SET RECOVERY FULL;

    GO

    The above solution was taken from http://msdn2.microsoft.com/en-us/library/ms189493.aspx

     

    posted 19 August 2006 by sachinjoshi | 5 Comments
    Filed Under:
  • ASP.Net 2.0 DataList Control - Basics

    DataList control is a template driven data control which allows us to display a list of data in a customizable format. Simply speaking we will define how the data is to be displayed and assign a data source, the control in turn uses the data source and simply displays the data using the definition. The power of this control is realized when we need to perform some operation on the displayed data.

    At the end of this post we will be able to perform some common operations using DataList control, we will walkthrough a development scenario, imagine we are developing a blog site and one of the page will allow us to manage the blog categories. We will leverage the DataList control to achieve the below given objectives

    Objective

  • Display blog categories
  • Edit/Update blog categories
  • Delete blog categories
  • Add new blog category

    How to...?

    Hmm.. that's a very basic and common operation, we will configure our DataList control to use the ObjectDataSource control, so that it brings the blog categories from the database and hands it over to the DataList control. One important thing to note is once you configure the data source of the DataList control set the DataKeyField to a primary/unique field. This is how the control looks in default template after binding it with ObjectDatasourceControl

    DataList control default template

    Ok so now let's sprinkle some color on this little beauty and make it look more adorable, use the Autoformat option and select a scheme of your choice.

    Here comes the fun part, we will now define how our data will be displayed, right click on the DataList control and go to "Edit Template" -> "Item Templates",

    DataList control edit item template mode

    In the above image you will notice that there are four sections,

  • Item Template
  • Alternating Item Template
  • Selected Item Template
  • Edit Item Template

    The template names are self explanatory so I won't brag about them, edit item template is going to be our point of focus, let's just remove the "Id" field from the templates as we don't want to display that field, we are only going to display the blog category and we will be able to edit the category description.

    Now let's drop a textbox control inside the edit item template and configure it's datasource, with this we are asking the DataList control "hey whenever the control is in edit mode display this textbox with the category description".

    Now drop two LinkButton control's in Item Template, one for Edit and the other one for Delete and set the CommandName to "EDIT" and "DELETE" respectively.

    Similarly drop two LinkButton control's in Edit ItemTemplate, one for Update and one for Cancel operation set their CommandName to "UPDATE" and "CANCEL" respectively. Below given is the snapshot

    We have the UI ready for Edit,Update and Delete operations, only thing missing from the list is a way to add new blog category. For this we will use the footer template and add one Textbox control to allow the user to input the description and a Linkbutton to perform an add operation. Below given is the snapshot of the DataList control after the template modifications.

    Now let's look at the event arsenal of DataList control, there are 5 events which sounds interesting, allow me to list down these events

  • EditCommand
  • UpdateCommand
  • CancelCommand
  • DeleteCommand
  • ItemCommand

    The first four events are perfect for our needs, but what about adding new blog category this is where ItemCommand is useful. So far so good and we still have our hands neat and clean, but we will get our hands dirty with some code. Let's subscribe to all the five events and write some code.

    //EditCommand

    protected void DataList1_EditCommand(object source, DataListCommandEventArgs e)

    {

    if (e.CommandName == "EDIT")

    {

    DataList1.EditItemIndex = e.Item.ItemIndex;

    DataList1.DataBind();

    }

    }

    //UpdateCommand

    protected void DataList1_UpdateCommand(object source, DataListCommandEventArgs e)

    {

    if (e.CommandName == "UPDATE")

    {

    string sId = DataList1.DataKeys[e.Item.ItemIndex].ToString();

    string sDesc = ((TextBox)e.Item.FindControl("DescText")).Text;

    BlogCategory objBlogCategory = new BlogCategory(Convert.ToInt32(sId));

    objBlogCategory.Description = sDesc;

    BlogManager.UpdateBlogCategory(objBlogCategory);

    DataList1.EditItemIndex = -1;

    DataList1.DataBind();

    }

    }

    //CancelCommand

    protected void DataList1_CancelCommand(object source, DataListCommandEventArgs e)

    {

    DataList1.EditItemIndex = -1;

    DataList1.DataBind();

    }

    //DeleteCommand

    protected void DataList1_DeleteCommand(object source, DataListCommandEventArgs e)

    {

    if (e.CommandName == "DELETE")

    {

    string sId = DataList1.DataKeys[e.Item.ItemIndex].ToString();

    BlogManager.DeleteBlogCategory(Convert.ToInt32(sId));

    DataList1.DataBind();

    }

    }

    //ItemCommand

    protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)

    {

    if (e.CommandName == "ADDNEW")

    {

    string sDesc = ((TextBox)e.Item.FindControl("txtCategoryDesc")).Text;

    BlogCategory objBlogCategory = new BlogCategory();

    objBlogCategory.Description = sDesc;

    BlogManager.AddBlogCategory(objBlogCategory);

    DataList1.DataBind();

    }

    }

    How it works?

    The event model is pretty straight forward, we set the EditItemIndex to the row index that needs to be edited, this is provided to us by the DataList control so there is no complexity.

    During update the update command event is fired and we get the blog category description from the TextBox that holds the data by using the FindControl method.

    Delete is very simple one just use the DataKeys collection of DataList and get the category id to delete.

    Adding of new category seems to follow the same pattern and since this operation doesn't have a specific event associated to it we use the ItemCommand event to meet our objective.

    Final output

    Below given snapshot is the final output to manage our blog category, pretty neat and clean is it :)

    Once you catch hold of the DataList control and play around you will find the control very usefull and a powerfull tool.

  • posted 08 August 2006 by sachinjoshi | 8 Comments
    Filed Under:
  • System.Net.Mail - How to add Alternate views and Embed Images

    System.Net.Mail provides us with a very intuitive object model to construct and send an email message.

    These days almost all the web and windows email clients gives us more control over the email content we wish to view (a.k.a HTML view, plain text view). This is to make us aware that the email content we are viewing may contain explicit images or externally linked images. Now imagine the recipient have disabled HTML content in his/her settings then the email content will be displayed as is(with HTML tags).

    We definitely don't want garbled text to be viewed by the recipient, now here is where the Alternate view comes to our rescue. As the name suggests it allows us to add alternate content that can be viewed by the receipient in case HTML content is disabled in his/her settings.

    Similarly many web/windows email clients disable external images in the mail message to avoid linking of external images we can use the LinkedResource to embed images in our email message.

    Although the core topic is about adding alternate views and embedding resources(images, etc) to an email, I will also touch upon configuration settings in web.config and Network Credentials.

    MailMessage:

    The MailMessage class plays a key role by wrapping all the email details like

    • From address
    • To address (collection)
    • CC address (collection)
    • BCC address (collection)
    • Email Subject
    • Email Body
    • Priority
    • Delivery notification options
    • Alternate views (Plain text, HTML)
    • Linked Resources (images, etc)

    Below given is a typical code used to send an email, the code is pretty straight forward apart from the AlternateViews, LinkedResources and some SMTPClient config section.

    //========================================================  
    MailMessage objMailMessage = new MailMessage();

    //File Attachment
    if (fileUploadEmailAttachment.HasFile)
    {
    objMailMessage.Attachments.Add(
    new Attachment(
    fileUploadEmailAttachment.FileContent,
    fileUploadEmailAttachment.FileName));

    }

    //From
    objMailMessage.From = new MailAddress(txtEmailFrom.Text,
    txtDisplayName.Text);

    //To
    objMailMessage.To.Add(new MailAddress(txtEmailTo.Text));

    //CC
    if (txtEmailCC.Text.Length > 0)
    {
    objMailMessage.CC.Add(new MailAddress(txtEmailCC.Text));
    }

    //BCC
    if (txtEmailBCC.Text.Length > 0)
    {
    objMailMessage.Bcc.Add(new MailAddress(txtEmailBCC.Text));
    }

    //Subject
    objMailMessage.Subject = txtSubject.Text;

    //Plain Text Alternative Email Content
    AlternateView objPlainAltView = AlternateView.CreateAlternateViewFromString(
    txtAlternateView.Text);
    objMailMessage.AlternateViews.Add(objPlainAltView);

    //HTML Alternative Email Content
    LinkedResource objLinkedRes = new LinkedResource(
    Server.MapPath(".")
    + "\\fuzzydev-logo.jpg", "image/jpeg");
    objLinkedRes.ContentId = "fuzzydev-logo";

    AlternateView objHTLMAltView = AlternateView.CreateAlternateViewFromString(
    txtHTMLBody.Text,
    new System.Net.Mime.ContentType("text/html"));

    objHTLMAltView.LinkedResources.Add(objLinkedRes);
    objMailMessage.AlternateViews.Add(objHTLMAltView);

    //High Priority
    objMailMessage.Priority = MailPriority.High;

    //Notify On Sucessfull Delivery
    objMailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
    SmtpClient objSMTPClient = new SmtpClient(txtHostName.Text);
    objSMTPClient.DeliveryMethod = SmtpDeliveryMethod.Network;

    if(chkBoxEnableSSL.Checked)
    objSMTPClient.EnableSsl = true;

    //Credentials (username, password)
    string sUserName = txtEmailFrom.Text.Split('@')[0];
    objSMTPClient.Credentials = new System.Net.NetworkCredential(
    sUserName, txtEmailFromPassword.Text);

    //Send Email
    objSMTPClient.Send(objMailMessage);

    //========================================================

    Now let me concentrate on the Alternateview, adding an alternate view is very easy, just create an object of the AlternateView class using the static method of the AlternateView class called CreateAlternateViewFromString passing the email text and the MIME type.

    For example if we want to create a plain text view then we will do something like this

    AlternateView objPlainAltView = AlternateView .CreateAlternateViewFromString(
    txtAlternateView.Text);
    objMailMessage.AlternateViews.Add(objPlainAltView);

    Now if we need HTML view then

    AlternateView objHTLMAltView = AlternateView.CreateAlternateViewFromString(
    txtHTMLBody.Text,
    new System.Net.Mime.ContentType("text/html"));
    objMailMessage.AlternateViews.Add(objHTLMAltView);

    That looks pretty simple, now the good news is the recipient will view the email message based on the email clients settings. So if HTML content is disabled then plain text message is displayed otherwise the HTML content is displayed.

    Let us move forward and get our hands dirty by embedding an image in an HTML content message. In order to embed an image in our email we can use LinkedResource class, we can add this object to the LinkedResource collection of the AlternateView object.

    LinkedResource objLinkedRes = new LinkedResource(
    Server.MapPath(".")
    + "\\fuzzydev-logo.jpg",
    "image/jpeg");
    objLinkedRes.ContentId = "fuzzydev-logo";

    AlternateView objHTLMAltView = AlternateView.CreateAlternateViewFromString(
    "<img src='cid:fuzzydev-logo' />",
    new System.Net.Mime.ContentType("text/html"));
    objHTLMAltView.LinkedResources.Add(objLinkedRes);
    objMailMessage.AlternateViews.Add(objHTLMAltView);

    In the above code we are passing an image file path and also specifying the content type as an jpeg image to the LinkedResource object. Next line of code is very interesting, we are assigning a unique ContentId which will be used to set the src of our HTML image tag. In our case the content id is fuzzydev-logo and if you look at the HTML alternate view object in the constructor section we are having an image tag which refers to the same content id.

    Now it's the email clients responsibility to understand the embedded resource and the reference in the image tag and display the image.

    SMTPClient:

    Now coming to the SMTP client configuration, let's just look in to what is the minimum configuration settings that SMTP client object expects from us.

    • Host name or IP address
    • Delivery Method (Network, Pick up directory from IIS, custom pickup directory)
    • EnableSsl (whether Secured Socket Layer is required)
    • Credentials (user name, password)

    SMTPClient configuration in web.config:

    	<configuration>
    <system.net>
    <mailSettings>
    <smtp deliveryMethod="Network" from="from@domain.com">
    <network host="smtp.gmail.com"
    userName="email user name"
    password="email passowrd"
    />

    </smtp>
    </mailSettings>
    </system.net>
    <system.web>
    <compilation debug="false"/>
    <pages validateRequest="false" />
    </system.web>
    </configuration>

    The above configuration helps us in quickly changing the delivery method, from mail address, host name (or IP address) , user name and password. Although the configuration is not mandatory it is the recommended way of implementing the email functionality.

    Below given code doesn't depend on the web.config for it's configuration needs

    	SmtpClient objSMTPClient = new SmtpClient(txtHostName.Text);
    objSMTPClient.DeliveryMethod = SmtpDeliveryMethod.Network;
    if(chkBoxEnableSSL.Checked)
    objSMTPClient.EnableSsl = true;

    //Credentials (username, password)
    string sUserName = txtEmailFrom.Text.Split('@')[0];
    objSMTPClient.Credentials = new System.Net.NetworkCredential(
    sUserName, txtEmailFromPassword.Text);

    //Send Email
    objSMTPClient.Send(objMailMessage);

    We don't need to specify the host name, etc if it's available in the web.config, this is usefull as in different part's of our application we can just use the specified configuration and if required then specify manually.

    Now that deserves a round applause for those involved in the development of System.Net.Mail classes.

    posted 23 July 2006 by sachinjoshi | 4 Comments
    Filed Under: ,
  • .Net Profile Object "my customers, my ambassadors" - Part 2

    For those who haven't read my previous posting on ASP.Net profile object (.Net Profile Object "my customers, my ambassadors") can read here

    This has been long overdue I couldn't post sequel as I was held up with other commitments.

    Anyway, let's kick start the Story Of Profiling part 2.

    To be short and sweet, a good website should remember my preferrences. So that the next time I visit , I get a personalized welcome.

    So how do we achieve this without using the out of the box solution provided by ASP.Net 2.0?

    • Create couple of tables and stored procedures to store and manipulate user profile details.
    • Write few classes' which will hold user's preferrence.
    • Write data access code to store and retrieve user's preferrence.

    That's not much work and we can very well go ahead and develop our own personalization framework.

    What does ASP.Net 2.0 provide?

    It not only provides us with predefined set of tables, stored procedures and classes but like all other new features it's using provider model and so customization is not a painfull task. Provider model is the best thing that has happened to ASP.Net as it allows us to plug and play the implementations, this is acieved with the mixture of configuration settings and judicious use of reflection.

    Let's dive in to the code and config settings to implement personalization.

    Before we get our hands dirty with any code let's just set the required configuration. Below given is the sample profile properties.

    <configuration><system.web>

    <profile>

    <properties>
    <add name="DisplayName">
    <add name="ShowOnlineStatus" type="System.Boolean">
    <group name="UserInterface">
    <add name="PageTheme" defaultValue="Green">
    <add name="EmailArticles" type="System.Boolean" defaultValue="false">
    <group>
    </properties>

    </profile>

    </system.web></configuration>

    The green colored config section is specific to profile. Although the elements are self describing let me explain the elements and it's attributes. By adding these elements and attributes we are asking the IDE and ASP.Net to recognize these properties as part of the profile object exposed in our Page class.

    So in the above scenario our profile object will have properties like DisplayName, ShowOnlineStatus which is of type boolean and also we are asking to group PageTheme and EmailArticles inside UserInterface. So the final profile object will have the below given structure

    Page.Profile.DisplayName                           = "Sachin Joshi";
    Page.Profile.ShowOnlineStatus                   = true;
    Page.Profile.UserInterface.PageTheme     = "Blue";
    Page.Profile.UserInterface.EmailArticles    = false;

    But hold a second, how did our profile object in our page got to know about the configuration and exposed these strongly-typed properties. It's not magic but the ASP.Net parser have recognized the profile configuration and have generated a class called ProfileCommon inherited from ProfileBase and have exposed the configured properties. Just check your App_Code folder and you will find a class called ProfileCommon inherited from ProfileBase.

    So far so good, we have created a very simple configuration for personalization and in our web pages we will give our users  the ability to save these details. But the question here is where exactly these details are saved.

    Actually we have not yet configured any profile provider which helps us in storage and retrieval of these customized profile. SqlProfileProvider comes to our rescue, this class is part of the ASP.Net 2.0 framework and as the name suggests it stores and retrieves profile data to and from Sql Server.

    Below given is the sample configuration of profile provider.

    <configuration><system.web>

    <profile>
      <providers defaultprovider="SqlServerProfileProvider">
        <add name="SqlServerProfileProvider"
             connectionStringName="SqlServer2005"
             applicationName="/"
             type="System.Web.Profile.SqlProfileProvider" />
      </providers>
    </profile>

    </system.web></configuration>

    In the above config we are asking ASP.Net to use the connection string from the specified section and use the SqlProfileProvider. So when we use the profile object ASP.Net in turn will be responsible to create an instance of the right provider and use the provider to store and retrieve the profile data.

    Below is the final configuration we will end up with to acieve the objective.

    <configuration><system.web>

    <!-- Connection String START-->
    <connectionStrings>

    <add
    name="SqlServer2005"
    connectionString="server=SOME_SERVER;database=SOME_DB;uid=XXXXXX;pwd=XXXXXX;"
    />

    <add
    name="MYSql"
    connectionString="server=SOME_SERVER;database=SOME_DB;uid=XXXXXX;pwd=XXXXXX;"
    />

    </connectionStrings>
    <!-- Connection String END-->


    <profile>

    <!-- Profile Properties START-->
      <properties>
        <add name="DisplayName">
        <add name="ShowOnlineStatus" type="System.Boolean">
        <group name="UserInterface">
          <add name="PageTheme" defaultValue="Green">
          <add name="EmailArticles" type="System.Boolean" defaultValue="false">
        <group>
      </properties>
    <!-- Profile Properties END-->

    <!-- Profile Providers START-->
      <providers defaultprovider="SqlServerProfileProvider">
        <add name="SqlServerProfileProvider"
             connectionStringName="SqlServer2005"
             applicationName="/"
             type="System.Web.Profile.SqlProfileProvider" />

        <add name="MySqlProfileProvider"
             connectionStringName="MySql"
             applicationName="/"
             type="fuzzydev.Providers.MySqlProfileProvider" />
      </providers>
    <!-- Profile Providers END-->
     
    </profile>

    </system.web></configuration>

    Note that in the above configuration there are two connection strings, one pointing to Sql Server and the other to MySql. Similarly there are two providers one for each DBMS, now we can switch to any provider by changing the defaultProvider attribute in the providers section.

    Our UI need not worry about which provider or dbms is being used, this is made possible with combination of polymorphism, configuration and reflection.

    Before you start playing with it there are couple of things which would be helpfull.

    • Serialization

              By default all the primitive types are serialized as string, this can be

    overriden by specifying the serializeAs attribute in the configuration

    <add name="DisplayName" serializeAs="Binary" />

    or

    <add name="DisplayName" serializeAs="Xml" />

    • Allow Profiling For Anonymous Users

    Profiling can also be done for anonymous users we just need to specify

    allowAnonymous="true" in the configuration.

    <add name="DisplayName" allowAnonymous="true" serializeAs="Xml" />

    Anonymous users are tracked using cookies, this discussion will require a

    whole new blog entry and so further details are deferred.

    This is just a brief introduction of ASP.Net profiling, there are lot of things which needs to be looked in to like

    1. Writing our own custom profile class by inheriting from ProfileBase and setting the attributes like allowAnonymous, serializeAs to the properties.
    2. Writing our own profile provider for our custom data store for example Xml, Access, etc.
    3. Migration of saved preferrences of anonymous users when they are promoted to registered users.

    ASP.Net profiling is a great way of adding richness to your website with the simplicity and flexibility of plug and play components.

    posted 01 July 2006 by sachinjoshi | 3 Comments
    Filed Under:
  • Excellent resource on 3-tiered data architecture with ASP.NET 2.0

    Scott Mitchell has put together an awesome tutorial on building and using 3-tiered date architecture  with ASP.Net 2.0

    It's available here

    The flow of the tutorial is excellent, you can also download the tutorials in pdf format.

    C# Tutorial in PDF format is available at http://www.asp.net/learn/dataaccess/datatutorials1_10cs.zip and http://www.asp.net/learn/dataaccess/datatutorials11_15cs.zip

    VB.Net Tutorial in PDF format is available at http://www.asp.net/learn/dataaccess/datatutorials1_10vb.zip and http://www.asp.net/learn/dataaccess/datatutorials11_15vb.zip

    If you want to kick start directly to a specific topic, I have listed down the different topics and the corresponding links for tutorial and source code for both C# and VB.Net.

    Introduction

    1. Creating a Data Access Layer 

    View this tutorial at C# VB.Net

    Download source code: C# VB.Net

    2. Creating a Business Logic LayerView this tutorial at C# VB.Net

    Download source code: C# VB.Net

    3. Master Pages and Site Navigation

    View this tutorial at C# VB.Net

    Download source code: C# VB.Net

    Basic Reporting


    1. Displaying Data With the ObjectDataSource

    View this tutorial at C# VB.Net

    Download source code: C# VB.Net

    2. Declarative Parameters

    View this tutorial at C# VB.Net

    Download source code: C# VB.Net

    3. Programmatically Setting the ObjectDataSource's Parameter Values

    View this tutorial at C# VB.Net

    Download source code: C# VB.Net

    Master/Detail Reporting


    1. Master/Detail Filtering With a DropDownList

    View this tutorial at C# VB.Net

    Download source code: C# VB.Net

    2. Master/Detail Filtering With Two DropDownLists

    View this tutorial at C# VB.Net

    Download source code: C# VB.Net

    3. Master/Detail Filtering Across Two Pages

    View this tutorial at C# VB.Net

    Download source code: C# VB.Net

    4. Master/Detail Using a Selectable Master GridView with a Details DetailView

    View this tutorial at C# VB.Net

    Download source code: C# VB.Net

    Custom formatting

    1. Custom Formatting Based Upon Data

    View this tutorial at C# VB.Net

    Download source code: C# VB.Net

    2. Using TemplateFields in the GridView Control

    View this tutorial at C# VB.Net

    Download source code: C# VB.Net

    3. Using TemplateFields in the DetailsView Control

    View this tutorial at C# VB.Net

    Download source code: C# VB.Net

    4. Using the FormView's Templates

    View this tutorial at C# VB.Net

    Download source code: C# VB.Net

    5. Displaying Summary Information in the GridView's Footer

    View this tutorial at C# VB.Net

    Download source code: C# VB.Net

    Scott Mitchell blogs here

    Excellent work Scott, the tutorial is very usefull and interesting as well.  

     

    posted 25 June 2006 by sachinjoshi | (Comments Off)
    Filed Under:
  • .Net Profile Object "my customers, my ambassadors"

    At first it might look irrelevant and you might ask "What has .Net Profile to do with my optical business?", just  sit back, relax and read on as it will be evident that it is relevant.

    Around 5 years back while I was pursuing my graduation degree, I opened an optical showroom, it was one heck of time to juggle between college and look after the business. Yet somehow I managed it, this log is not about how professionally/successfully Stick out tongue [:P] I managed my business; but it's about what I learnt out of it.

    While I was busy with my college I used to spent lot of time thinking of different strategies to develop my business. During the second year out of the blue many such showrooms started to pop up and there was tough competition, people started slashing their prices of spectacles and the business started to soar. Now the business was evenly divided among the showrooms.

    Many showroom owners came up with special discounts, spent lavishly on promotion and started to attract more customers. Some showrooms roped in professional advertising agency with good models to be their ambassador. All this made me insecure and due to capital constraints we were not spending on advertisements and had to rethink our business strategy.

    As I was pursuing Bachelor's of Business Administration I had the knowledge on marketing management and came up with a great idea which really worked.

    Before I talk about it, let me put forth few questions to you.

    Q. To impress a girl what do you do?

    A. You try to know what she likes and gift her.

    Q. To impress an HR what do you speak?

    A. You speak what he wants to listen to.

    Do you see a pattern and something hidden in the above answers, well in order to impress a girl or HR you need to know what they like and so you need to collect information about their likes and dislikes  and use that information to your advantage.

    That's what I did; I started collecting information about my customers. Every time I got a new customer I collected their address, phone number, date of birth, anniversaries, etc. So how do collecting customer information improve my business, key here is what you do with that information. I used that data to analyze and send mails to remind them of regular eye check-up, special discounts for being our customer, wishing them on their birthday, etc.

    Also it was not just about collecting info in a diary but even my mind was collecting data like storing customers image and recognizing and greeting them with their name when they pay their next visit.

    Don't you feel good when you visit a coffee pub and the waiter or manager smiles at you and greets you with your name as if indirectly telling you "I know you, you are my valuable customer", especially when you are with your friends/GF Wink [;)]

    These little gestures proved to be steroids to my business and the business started to boom again; the new customers were actually my old customers relatives, friends, neighbors, etc. So I made "my customers, my ambassadors" note the quote my dear marketing guys you won't find this in any books or research papers. My customers were marketing for me and my business was back into action.

    Little did I know after around 5 years I will be doing this again, but this time I am not going to collect the information one-on-one but through the Profile object provided by .Net.

    Huh...you will be thinking at last this guy is talking about Profile object.

    Read Story of Profiling part 2

     

    posted 17 June 2006 by sachinjoshi | (Comments Off)
    Filed Under:
  • Tech.Ed 2006 - for geeks in Chennai

    Tech.Ed 2006 in Chennai will be held at Chennai Trade Centre and kick starts on 15th June and will end with a bang(entertainment/party) on 17th June.

    Where is Chennai Trade Centre?
    Chennai Trade Centre
    Mount Poonamallee High Road
    Nandambakkam
    Chennai: 600089
    Ph: 91-44-22316033, 22315551

    Map of Chennai Trade Centre is available at http://www.indiasoft.ind.in/venue_map.htm

    Complete details of all the session is available at http://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032295913&Culture=en-IN

    Visit http://forums.techedindia.com/ a forum started by MVP's to answer all your developer and IT Pro related questions.

    Visit http://spaces.msn.com/vineetgupta/ and know what Vineet Gupta is cooking for the TechEd sessions. He is loaded with and willing to share his wisdom on Data Platform and Architecture tracks.

    posted 10 June 2006 by sachinjoshi | 1 Comments
    Filed Under: ,
  • Date with DataSource Control - Ms. ObjectDataSource

    Developer's are the most busiest guys on the earth and unfortunately I am one of them. So what do we do about it? Well, I have decided to go out on date with the five beautifull girls. Their names are listed below.

    • Ms. ObjectDataSource
    • Ms. SqlDataSource
    • Ms. AccessDataSource
    • Ms. XmlDataSource
    • Ms. SiteMapDataSource

    So let me start with Ms. ObjectDataSource...

    Where can we find her?

    She hangs out almost everyday in the data tab of the VS IDE toolbox.

    What's her nature of job?

    She works for a framework called .Net 2.0 and is a thorough professional providing data for all the data bound controls. She is a very smart lady, she is aware of the fact that enterprise applications market is a multi billion dollar industry and many developers these days are part of this industry. If the application is not scalable then the industry doesn't have a chance to survive. She allows developers to use the data source controls yet have the abstraction layer intact.

    How does she deliver her role?

    I remember once she told me that she is been entrusted with this responsibility and going to seek help from her close friend (her name is Ms. Reflection stays in System).

    Discussion about reflection is deferred until I go out on date with all the Ms. Datasource's Wink [;)] 

    Well back to Ms. ObjectDataSource; she told me that Ms. Reflection have some magical powers and so she can get her details about anybody(Object) and also hypnotise anyone(Object) to perform certain actions. This was what Ms. ObjectDataSource was looking for to impress the developers like us. There are few things which she expects from us and once we provide her with those details we can introduce our data control friends to her and ask her to handover the data to them.

    Sounds complicated, ok let me simplify there is a contract between Ms. ObjectDataSource(promising to fetch, insert, update, delete data) by invoking methods(hyptonising through her friend Reflection and making objects to perform certain actions). And our data control friends uses those data to display in the form they are requested to.

    I have taken a couple of screen shots, this should help you to better understand her.

    There are few things we need to know....

    To get the data, assign the method name(the one which fetches data) of your business object to Ms. ObjectDataSource's SelectMethod.

    //Example

    objDSCustomers.SelectMethod = "GetCustomers";

    For insert, update, delete follow the same pattern and bind objDSCustomers to the data control.

    //Example

    grdViewCustomers.DataSourceID = "objDSCustomers";

    Although there are many things about Ms. ObjectDataSource which I haven't discussed, but with the above information I am sure now you have a better idea about her.

     

    posted 10 June 2006 by sachinjoshi | (Comments Off)
    Filed Under:
  • Operation could destabilize the runtime

    Hmm "Operation could destabilize the runtime" sounds too scary, what operation on earth is this; which can destabilize the .Net runtime?

    It looks like  the 1.1 C#/VB.Net compiler had case boundary with the generated IL code, the massive overhaul done for the new features in 2.0 forced some low level code changes in CLR; this in turn is haunting few 1.1 assemblies.

    One of the well known case is the switch statement having more than 8 conditions. If you try to use 1.1 assembly having a code block of switch statement exceeding 8 conditions then you might face the horrifying exceptions like...

    System.Exceptions.PageLoadException

    System.Security.VerificationException

    Try changing the switch case to if..else condition that will solve the problem.

    For more details check the below given link

    http://forums.asp.net/thread/1255521.aspx

     

    posted 10 June 2006 by sachinjoshi | 1 Comments
    Filed Under:
  • String.IsNullOrEmpty(String)

    As simple as it gets, C# 2.0 has brought with it loads of language features. Some made a huge difference and few less talked about.

    One of them is String's IsNullOrEmpty method, let's do a comparision of C# 1.1 and 2.0 logic to check for a empty and null string.

    We have been doing this past several years, a condition where in we check a string object is null or empty and perform certain actions based on the the outcome of the condition.

    //C# 1.1 Sample code

    string sParam = null;

    if( (sParam != null) && (sParam != string.Empty) ) {

    //Do something

    }

     //C# 2.0 Sample code 

    string sParam = null;

    if( string.IsNullOrEmpty(sParam) ) {

    //Do something

    }

    Now the difference is pretty clear....same logic but well simplified. Many of you will be wondering why the method IsNullOrEmpty is a static member of string class. Point here is we are checking for null or empty string and if that instance of string is null then it will throw a NullReference exception.

    Can the word simply be more simplied? Wink [;)]

    posted 10 June 2006 by sachinjoshi | 1 Comments
    Filed Under:
  • String.Contains(String)

    In our .Net 1.1 days we used to check whether a string object contains a specified string(text) using IndexOf method.

    Here is the typical code to check the existence of a string in an string object.

    //Sample code

    string sName = "John Smith";

    if(sName.IndexOf("Smith") > -1) {

    //Smith exists in string object sName

    }

    Now let's take a closer look at the above code...... What we want is to know whether an instance of string contains some string(text).

    Did I say contains......that's exactly C# .Net 2.0 provides us with.

    Let's revisit the same functionality using 2.0

    //Sample code 

    string sName = "John Smith";

    if(sName.Contains("Smith")) {

    //Smith exists in string object sName

    }

    Wallah.....it's so simple and sophisticated.

    posted 10 June 2006 by sachinjoshi | 3 Comments
    Filed Under:
  • System.Nullable A.k.a Nullable types

    Developers were always looking forward to the inclusion of Nullable types in C#. I love the way it's been implemented using generics. Before we go in to the specifics of Nullable types; let's look at what is a Nullable type and it's usage.

    What's a Nullable type?
    A nullable type is a value type which can be assigned a null value. Type's like int/bool/double/etc... now can be assigned null values.

    Usage:
    A simple case for nullable type is while assigning a database column value to a value type.

    Example:
    int iEmpId = 0;
    //Will throw an error if the DataReader value is null
    iEmpId = (int)drEmployee["id"];

    Now let's see how a value type can be promoted to a Nullable type with the magic of generics.

    Declaring a nullable type is straight forward..

    System.Nullable<int> iEmpId;
    or
    int? iEmpId; //that's a shorthand
    iEmpId = null; //Allowed as it's Nullable
    if(iEmpId.HasValue){
    //do something
    }

    So for assigning a value from let's say a datareader, we could do something like this.

    int? iEmpId = null;
    iEmpId = (int?)drEmployee["id"];
    if(iEmpId.HasValue){
    //do something
    }

    Hmm that certainly makes sense, isn't it?

    posted 09 June 2006 by sachinjoshi | (Comments Off)
    Filed Under:
  • Interned string

    Interned string is nothing but a locked up version of a string, so that it can be shared.

    Memory allocation can be avoided by using string.Empty.

    string sFirstName = string.Empty;

    The C# compiler is intelligent enough to generate code based on our declaration, if we declare a string object with either string.Empty it just refers to a shared empty string object. As we know string object are immutable(cannot be changed) once created so any assignment will not affect the shared string object.

    posted 09 June 2006 by sachinjoshi | 1 Comments
    Filed Under:
  • Generics an overview

    We all have come across a situation where we need to store a collection of a specific type.

    Let's say for example we have a class called Customer and we need to have a collection of customers.

    Simple way of doing that may be to use ArrayList and add customer class to it. But we have to pay a heavy price for using an ArrayList.

    For those of you who don't know the pitfalls of using ArrayList, let me briefly list it out.

    • The default initial capacity of an ArrayList is 16, even if you add only 2 items to the ArrayList object it will still occupy memory area of 16 elements.
    • Assume you have added 17th element in your ArrayList object then your object will grow to 32 capacity, that's real waste of memory.
    • ArrayList stores everything as object and so any value type you store goes through an overhead of boxing and unboxing. Boxing and Unboxing is the most performance intensive operation in .Net as it has to convert a value type to a reference type and the vice versa.
    • There is no type safety as you can store any type in an ArrayList object.

    Now where do the Generics come in picture.......??

    Well they are the saviors in this .Net world, don't believe me then look how simple and smart generics are.

    Now we have a class called Customer and I want a collection of Customer to store n numbers of customers.

      //Sample code
      <Customer> objCustomerColl = new List<Customer>();

    Essentially what we are doing in the above given line of code is we are using the List class which is part of the System.Collections.Generic namespace.
    The declaration is pretty simple we are telling the compiler that create a list of Customer class.

    With this simple piece of code we have our CustomerCollection ready for use.
    Now we can add, remove and perform many different operations on it.

      //Sample code
      objCustomerColl.Add(new Customer());
      Points to be noted....

    This generic list is type safe.

    • If you use a value type to create a generic list it doesn't require boxing/unboxing.
    • All the incrementing/decrementing of the list is done under the hood.

    Few more examples of Generic list....just to give you an idea of how powerfull are generics.

    List<int> IntCollection = new List<int>();
    List<string> StringCollection = new List<string>();

    posted 08 June 2006 by sachinjoshi | 1 Comments
    Filed Under:

This Blog

Post Calendar

<July 2008>
SuMoTuWeThFrSa
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

Sponsored Links

Syndication

Copyright 2006, Sachin Joshi. All rights reserved.
The content on this site represents my own personal opinions and thoughts at the time of posting, and does not reflect those of my employer's in any way.
Powered by Community Server, by Telligent Systems