Welcome to weblogs.com.pk Sign in | Join | Help

ASP.NET provides wide spectrum; you can develop reusable interface components using User Controls, Server Controls and Web Parts (WebForms world). There are three ways to develop ASP.NET Server Controls.

Render Contents

You can override RenderContents and using the writer can flush out the HTML text you want. Its more or less the same Classic ASP like spaghetti approach. To make things bit object oriented there are some base methods that you can override. In the example below; I am trying to write out <a href=”http://weblogs.com.pk”>Weblogs.com.pk Link</a>

[ToolboxData(@"<{0}:RenderContentsControl runat=""server"" />")]
public class RenderContentsControl : WebControl
{
    protected override HtmlTextWriterTag TagKey
    {
        get
        {
            return HtmlTextWriterTag.A;
        }
    }
 
    protected override void AddAttributesToRender(HtmlTextWriter writer)
    {
        writer.AddAttribute(HtmlTextWriterAttribute.Href, "http://weblogs.com.pk");
    }
 
    protected override void RenderContents(HtmlTextWriter writer)
    {
        writer.Write("Weblogs.com.pk Link");
    }
}

Inherited Control

The second option is you find the most suitable control and inherit your control from it adding the missing functionality from your perspective. You can inherit from as simple as Label control to as complex as TreeView control. In the example below; I have inherited my control from Panel giving it red borders as default look.

[ToolboxData(@"<{0}:PanelInheritedControl runat=""server""></{0}:PanelInheritedControl>")]
public class PanelInheritedControl :Panel
{
    public PanelInheritedControl()
    {
        this.BorderStyle = BorderStyle.Solid;
        this.BorderColor = Color.Red;
    }
}

Composite Control

The third option is that you override OnInit and add one or more controls into the control’ Controls collection. In the example below I have added couple of controls and one child control even has post back event!

[ToolboxData(@"<{0}:CompositeControl runat=""server"" />")]
public class CompositeControl : WebControl
{
    protected override void OnInit(EventArgs e)
    {
        LinkButton lb = new LinkButton();
        lb.Text = "Weblogs.com.pk Link";
        lb.Click += new EventHandler(lb_Click);
        this.Controls.Add(lb);
 
        this.Controls.Add(new LiteralControl("<br />"));
 
        HtmlAnchor anchor = new HtmlAnchor();
        anchor.HRef = "mailto:khurram@sharpcoders.net";
        anchor.InnerText = "Mail Link to Khurram";
        this.Controls.Add(anchor);
    }
 
    void lb_Click(object sender, EventArgs e)
    {
        this.Page.Response.Redirect("http://weblogs.com.pk");
    }
}

The ASPX hosting these three controls will look like this:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestWebApplication._Default" %>
<%@ Register Assembly="Weblogs.Web" Namespace="Weblogs.Web" TagPrefix="weblogs" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <weblogs:PanelInheritedControl ID="PanelInheritedControl1" runat="server">
            <weblogs:RenderContentsControl ID="RenderContentsControl1" runat="server" />
            <br />
            <weblogs:CompositeControl ID="CompositeControl1" runat="server" />
        </weblogs:PanelInheritedControl>
    </div>
    </form>
</body>
</html>

I am also attaching the Visual Studio 2008 Solution of the above samples with this post.

Do you use any other technique of developing Server Controls, please share with us!

Posted Friday, July 03, 2009 1:49 AM by khurram | 0 Comments
Filed under: ,

Attachment(s): Weblogs.zip

Application Development- 19 Reasons Why Microsoft Is Huge with Developers (and 1 Reason Why Not)

The 1 reason why not, its cent percent true!

There are number of tricks in debugging JavaScript / Ajax Applications, its very hard to explain new developers in team and I was looking for some nice article to use as reference. The tutorial at asp.net  http://www.asp.net/learn/ajax/tutorial-06-cs.aspx has very nicely compiled information on this topic, even though its oriented towards ASP.NET camp, but it has enough information for other platform folk as well. It covers debugging with Visual Studio and Visual Web Developer (Free) as IDE, Internet Explorer and Firefox as browser, Firebug and Nikhil’s Web Developer Helper as browser’s addin. The article then winds up with information on ASP.NET AJAX’ debugging support.

BTW, ASP.NET AJAX is two fold offering, it has stuff for ASP.NET developer as well as its JavaScript client library which you can use in other platforms, like PHP for which there is even PHP for Microsoft AJAX Library

Get the SkyFire from http://m.skyfire.com, a free browser for S60-3rd Edition (Nokia N/E Series) and Windows Mobile 5 (and above) which supports Silverlight and Flash 10 along with JavaScript/Ajax support…

Visit http://skyfire.com for more info!

Visual Studio 2010 Beta 1 is available to try. Don't forget to download the Visual Studio 2010 and .NET Framework 4 Training Kit – May Preview

Pros

  • Further Improved JavaScript intelli-sence
  • Work side by side with Visual Studio 2008
  • HTML Snippets
  • Loads of Code Editor Improvements

Cons

  • Resource Hungry
  • No offline Help
  • No Express Editions
  • No Silverlight 3 Design Tools

Related Links

I am biased towards C#

GSM Phones can be hooked with your PC and the drivers that usually come with them get it configured as Modem. Once setup, you can open the serial port and send AT commands to it and with it can send SMS!

A friend of mine asked for some utility to send SMSes in bulk, and I gave him the above info. He is hobbyist programmer and I think he can get it done…However I wrote a small such application a while ago, when .NET v2 was released with Serial ports support…I digged and found this!

class SmsEngine : IDisposable
{
    SerialPort serialPort;
 
    SmsEngine() { }
 
    public SmsEngine(string comPort)
    {
        this.serialPort = new SerialPort();
        this.serialPort.PortName = comPort;
        this.serialPort.BaudRate = 9600;
        this.serialPort.Parity = Parity.None;
        this.serialPort.DataBits = 8;
        this.serialPort.StopBits = StopBits.One;
        this.serialPort.Handshake = Handshake.RequestToSend;
        this.serialPort.DtrEnable = true;
        this.serialPort.RtsEnable = true;
        this.serialPort.NewLine = System.Environment.NewLine;
    }
 
    public bool SendSMS(string CellNumber, string SMSMessage)
    {
        string messageToSend = null;
        if (SMSMessage.Length <= 160)
        {
            messageToSend = SMSMessage;
        }
        else
        {
            messageToSend = SMSMessage.Substring(0, 160);
        }
        if (this.IsOpen == true)
        {
            this.serialPort.WriteLine(@"AT" + (char)(13));
            Thread.Sleep(200);
            this.serialPort.WriteLine("AT+CMGF=1" + (char)(13));
            Thread.Sleep(200);
            this.serialPort.WriteLine(@"AT+CMGS=""" + CellNumber + @"""" + (char)(13));
            Thread.Sleep(200);
            this.serialPort.WriteLine(SMSMessage + (char)(26));
            return true;
        }
        return false;
    }
 
    public void Open()
    {
        if (this.IsOpen == false)
        {
            this.serialPort.Open();
        }
    }
 
    public void Close()
    {
        if (this.IsOpen == true)
        {
            this.serialPort.Close();
        }
    }
 
    public bool IsOpen
    {
        get
        {
            return this.serialPort.IsOpen;
        }
    }
 
    public void Dispose()
    {
        if (this.IsOpen)
            this.Close();
    }
}

I am also attaching a small command line utility (requires Microsoft.NET v2) with a hope that it will work…I am not testing it this time, as I am unable to find my mobile phone’ cable right now!

Usage

You can also use this program as
SmsAt [COM] [NUMBER] [PathToSomeFileHavingMessage]
eg SmsAt COM3 03008479254 Message.txt

I am stuck in pushing a project to its “end” this month…still few more steps to do..but we are seeing the end! I had a feeling that I am giving the most and doing the kind of work which I am not supposed to do…I wanted to confirm it statistically..so I asked at StackOverFlow http://stackoverflow.com/questions/796926/team-foundation-subversion-who-has-how-much-contrribution-in-the-repository

BigToe there directed me to StatSVN!

StatSVN retrieves information from a Subversion repository and generates various tables and charts describing the project development, e.g. timeline for the lines of code, contribution of each developer etc. The current version of StatSVN generates a static suite of HTML or XDOC documents containing tables and chart images.

My repository is Team Foundation Server based, I setup SvnBridge to access my repository with SubVersion clients..everything worked..it took some time but I had some interesting facts

  1. 79.9% of the code in our repository is written by me and rest by my peer (we are two member team assigned ourselves to push this project to its end by the end of this calendar month)
  2. My peer revise 15% of the code they commit earlier and I do 20% (which is reasonable as I also review his code and it increases my share of code as depicted in [1] :)
  3. The top activity is during 7PM – 8PM; ah that’s why my wife is not very happy with me these days
  4. Tuesday and Wednesday are good for project, Friday is worst and Saturday is second last..my teammate is from out station…interesting fact to consider while composing next team
  5. 25% is the pure code (C# in our case), rest is others (auto generated, web resources etc)
  6. The two most lengthy (and hence bad smelled) classes are ****** and ******
  7. The two most touched files (hence poorly thought) are ***** and ******
  8. I have good productivity in the start of the week and drops in the end (I am working remote and visit the work place at the end of the week)
  9. My fellow worker’s productivity (commits) increases from Tuesday till Thursday and then drastically fall, hmm seems like as he is from out of station his weekend’s travels is affecting badly
  10. I was active on code from 33%th day till end and my fellow team workers got the pace from 50%th day till 70%th day and since then its falling
  11. 45% of the time my teammate is working in UI layer; hmm..we still need to put more efforts to mature business layer and bring code pieces from UI layer to business layer

The last two are interesting, it appears that my teammate has not relevant exposure and being junior in career he is unable to help during the last and start of the sprint…I should arrange trainings and couch him how to push his boundry (from start as well as end) i-e designing and architecting skills….requirement elicitation skills…refactoring skills…skills for getting the bugs fixed fastly…and do something that he realizes how to put balanced effort across all layers…UI layer should be lean and should not take 45% of efforts!

As soon as this ends…I need a break :) Boss!! I have the figures now..

And the reason why I could not blog regularly

Microsoft announced beta of Silverlight 3 featuring lot of Media Improvement (which shows their commitment to continue to add attractions in Silverlight so it become the preferred media delivery platform) and tons of improvement around Line of Business…they still lacking printing support! (and webcam/microphone support which would be great for web VoIP dialers)

You can get the developer runtime, the development and designing tool (Visual Studio and Blend 3) from http://silverlight.net/getstarted/silverlight3 (Sad part is; your Silverlight 2 tools will need to be uninstalled and yet you cannot do Silverlight 2 development with these new beta/preview tools). So either get a separate machine or prepare a virtual machine! Fortunately I have a spared Windows Server installed on my notebook which I require time to time to try out some server pieces…but I am super busy till mid of April (both at work and at home)

To compliment beta of Silverlight 3; a free ebook whose title is the title of this post is available here!

With Windows Shell Extension (Oct 2008) in Team Foundation Server Power Tools, you can interact with TFS Source Control directly from Windows Explorer!

image

Its great for non Visual Studio users like designers who need to work with TFS Source Control. While installing Power Tools; this extension doesn't get installed; you need to select it from Advanced option!

clip_image001

Windows Desktop Search 4 supports Remote Queries; if you install it on multiple machines; each indexing their local data; you can then query these multiple indexes…

Simplest way is to open the network share and use the Search Box…if the particular shared folder is in the remote machine’ indexed folder; your local Search applet will send the query to remote machine and show the result using it!

clip_image001

From Windows Search 4.0 Administrator’s Guide

Remote Query

Windows Search 4.0 extends the ability to search across remote desktops. Previously, only Windows Vista users could query recognizable indexes on remote Vista computers; now, WS4 enables users to query remote computers running any supported operating system. Remote querying includes the following features:

  • Queries work across all supported OSes (Windows XP, Server 2003, Home Server, and Vista).
  • All shared NTFS folders are automatically indexed (excludes all FAT file systems).
  • All shared, and therefore indexed, locations can be remotely queried.

The location on the remote computer must be shared and it must be indexed. With Group Policy, administrators can control whether shared locations are automatically indexed.

Querying from Windows Vista or Windows Server 2008

To query a remote computer, users use Windows Explorer to browse the shared, indexed folder on another machine and enter their searches in Explorer’s search box. If the location is not indexed, then Vista falls back to a slower GREP search instead of WS4.

Happy Eid Melad-un-Nabi!

In my last post about Delegates and Generics, we had the following delegate to play with…

delegate T ComplexDelegate<S, T>(S[] values);

Over the different releases of .NET / C#, defining delegate instances is becoming compact…Due to anonymous method, instead of establishing a separate method altogether; we can have an inline code..

ComplexDelegate<int, double> averageLogic = new ComplexDelegate<int, double>(
   delegate(int[] values)
   {
       return values.Average();
 
   });
 
//if you dont need the delegate parameters e-g
ComplexDelegate<int, double> alwaysReturn1Logic = new ComplexDelegate<int, double>(
   delegate
   {
       return 1;
   });

With support of lambda expressions in C# 3 / .NET 3.5; we dont need to repeat things i-e first telling what the type of variable is and then telling again while “newing” it up…

ComplexDelegate<int, double> sumLogic = ( values ) =>
{
   return values.Sum();
};
//And its more compact variation can be
ComplexDelegate<int, double> maxLogic = values => values.Max();

And in case you are wondering from where these .Average(), .Sum() and .Max() are coming; its due to Extension Methods in System.Linq; another feature they introduced in .NET 3.5 / C# 3. Lets define one to get our hands dirty with it too :)

//The class needs to be static; i-e you can only have static methods in this class
static class ExtensionMethods
{
    public static int MyRandom(this IEnumerable<int> values)
    {
        int len = values.Count();
        Random r = new Random(DateTime.Now.Second);
        int random = r.Next(len - 1);
 
        IEnumerator<int> enumerator = values.GetEnumerator();
        int looper = 0;
        int toReturn = default(int);
        while(looper<=random && enumerator.MoveNext())
        {
            toReturn = enumerator.Current;
            looper++;
        }
        return toReturn;
    }
}

Now you can magically call this method to any instance of int[]; all you need is to import this class’ namespace e-g

//I guess use of lambda is clear by now
ComplexDelegate<int, double> randomLogic = values => values.MyRandom();

Almost all .NET developers know about delegates; its one of the feature which makes .NET distinct from other VMs…Here’s one lame example

class Program
{
    delegate double SimpleDelegate(int[] values);
 
    static double average(int[] values)
    {
        return values.Average();
    }
 
    static double sum(int[] values)
    {
        return values.Sum();
    }
 
    static void Main(string[] args)
    {
        SimpleDelegate averageLogic = new SimpleDelegate(Program.average);
        Console.WriteLine("Average of 1, 2, 3 is {0}", averageLogic(new int[] { 1, 2, 3 }));
 
        Console.ReadLine();
    }
}

Now some of these .NET developers might know that you can use Generics while defining the delegate…e-g

class Program
{
    delegate double SimpleDelegate(int[] values);
    delegate T ComplexDelegate<S, T>(S[] values);
 
    static double average(int[] values)
    {
        return values.Average();
    }
 
    static double sum(int[] values)
    {
        return values.Sum();
    }
 
    static void Main(string[] args)
    {
        SimpleDelegate averageLogic = new SimpleDelegate(Program.average);
        ComplexDelegate<int, double> sumLogic = new ComplexDelegate<int, double>(Program.sum);
        Console.WriteLine("Average of 1, 2, 3 is {0}", averageLogic(new int[] { 1, 2, 3 }));
        Console.WriteLine("Sum of 1, 2, 3 is {0}", sumLogic(new int[] { 1, 2, 3 }));
 
        Console.ReadLine();
    }
}

If you get yourself comfortable with Delegates with Generics…you can easily then go through many of the delegates in Base Class Library; like family of Action<T> and family of Func<T> delegates which appears to be heavily used in the source code of Silverlight Toolkit

This is one of the basic requirement of any LoB Silverlight application, and is bit tricky for new comers…

Silverlight controls can be embedded with either well established techniques; like the one used for Flash or bit more easily using ASP.NET controls, here is how you will be doing it…

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="RealTimeBandwidthMonitor.ascx.cs"
    Inherits="Resellers.RealTimeBandwidthMonitor" %>
<%@ Register Assembly="System.Web.Silverlight" Namespace="System.Web.UI.SilverlightControls"
    TagPrefix="asp" %>
    
<asp:Silverlight ID="Xaml1" runat="server" Source="/ClientBin/BandwidthMonitor.xap"
    Height="500" Width="640"
    MinimumVersion="2.0.31005.0" />

 

//Code behind of ASCX
public partial class RealTimeBandwidthMonitor : System.Web.UI.UserControl
{
    protected void Page_Init(object sender, EventArgs e)
    {
       this.Xaml1.InitParameters = "Key1=Val,LoggedOnUserName=" + this.Context.User.Identity.Name;
    }
 
    protected void Page_Load(object sender, EventArgs e)
    {
       //..
    }
}

 
//Code behind of App.xaml of your Silverlight app
public partial class App : Application
{
    public IDictionary<string, string> InitValues = null;
 
    public App()
    {
        this.Startup += this.Application_Startup;
    }
 
    private void Application_Startup(object sender, StartupEventArgs e)
    {
        //.
        if (null != e.InitParams)
            this.InitValues = e.InitParams;
    }
}

Now that you have your init parameters in the Silverlight app; you can you it where you need; e-g

//Code behind of Page.xaml
public partial class Page : UserControl
{
    string loggedOnUserName = string.Empty;
 
    public Page()
    {
        InitializeComponent();
        this.Loaded += new RoutedEventHandler(Page_Loaded);
    }
 
    void Page_Loaded(object sender, RoutedEventArgs e)
    {
        this.TextBlockForLoggedOnUserName.Text = "Default Value";
 
        App ourApp = Application.Current as App;
        if (null != ourApp)
        {
            if (ourApp.InitValues.Keys.Contains("LoggedOnUserName"))
            {
                this.loggedOnUserName = ourApp.InitValues["LoggedOnUserName"];
                this.TextBlockForLoggedOnUserName.Text = this.loggedOnUserName;
            }
        }
    }
}

 

Happy Lighting up the web!

One of my colleague is developing a web interface featuring couple of RIA components. He has chosen Silverlight for its “buzz”, “light-ness” and its support of languages like C# and so forth. I engaged myself for the week in his R&D activities in choosing and exploring different components, techniques and libraries etc. I availed the opportunity and do bit exploration on Flash/Flex scene and found, Ensemble Tofino using which you can develop Flex applications from Visual Studio…great product indeed…

>> http://www.ensemble.com

An Adobe® Flex™ plugin for Microsoft® Visual Studio®

It allows you to create Visual Studio solution/projects for Flex app, let you debug (with breakpoints of course), you can navigate ActionScript classes from Visual Studio’ Object Browser, and above all, Intellisense code completion and the best part is, its FREE!

In case you are wondering what is Flex, visit http://learn.adobe.com/wiki/display/Flex/Animated+Overview

With XN4SL, you can easily port your 2D XNA Games to Silverlight, and thus make them available over the web! SilverlightPlatformer is one such sample ported game!

Read this How To, to learn how this can be done…The author is intending to release the library source code here soon!

More Posts Next page »