July 5, 2011

WaitHandles’ Switch

Filed under: .net,multi-threading Himanshu @ 3:57 pm

I will say it again: “I like extension methods”. They provide great way of increase readability of the code in languages like C#.

Anyway this post is not about extension method. Have you ever needed to write code that will wait on different wait handles (WaitHandle) and execute different piece of code depending up on which handle is signaled. Here is one way to implement that:

public static void WaitSwitch(this WaitHandle[] waitHandles, params Action[] actions)
  
{
  
    waitHandles.DoEmptyOrNullArgCheck("waitHandles");
  
    actions.DoEmptyOrNullArgCheck("waitHandles");
  
    if (waitHandles.Length != actions.Length)
  
        throw new ArgumentException("length of wait handles and actions has to be same");
  
    var triggerIndex = WaitHandle.WaitAny(waitHandles);
  
    actions[triggerIndex]();
  
}
  

And then client code will become as:

(new[] { shutdownTriggeredEvent, updateAvailableEvent }).WaitSwitch(
  
    () => isShutdownRequested = true,
  
    DownloadNextUpdate
  
);
  

January 5, 2011

ASP.NET Postback on table row click

Filed under: .net,asp.net Himanshu @ 8:34 am

When you need to go back to the server for further processing on clicking of a html element, for example on html table row click, below code may help you provide such functioning in ASP.NET.

Well, actually to allow control to support bubbling of the events, and allow user of the control to specify CommandName and CommandArgument while being used in template controls,  there is some extract effort, essentially will need to implement IButtonControl. Let’s see the code below that I have implemented to provide function of  selecting row when clicked on it.

   1:  [ToolboxData("<{0}:ListViewRowClickCommand  CommandName=\"Select\" runat=\"server\"></{0}:ListViewRowClickCommand>")]
   2:  public class ListViewRowClickCommand : HtmlTableRow, IButtonControl, IPostBackEventHandler
   3:  {
   4:      public bool DisableCommand { get; set; }
   5:      protected override void Render(HtmlTextWriter writer)
   6:      {
   7:          writer.WriteBeginTag("tr");
   8:          if (ID != null)
   9:              writer.WriteAttribute("id", ClientID);
  10:          if (!DesignMode)
  11:          {
  12:              if (!DisableCommand)
  13:                  writer.WriteAttribute("onclick", "javascript:" +
  14:                      Page.ClientScript.GetPostBackEventReference(this, CommandArgument));
  15:          }
  16:          Attributes.Render(writer);
  17:          writer.Write(HtmlTextWriter.TagRightChar);
  18:  
  19:          RenderChildren(writer);
  20:          writer.WriteEndTag("tr");
  21:      }
  22:  
  23:      public bool CausesValidation
  24:      {
  25:          get { return (bool)(ViewState["CausesValidation"] ?? true); }
  26:          set { ViewState["CausesValidation"] = value; }
  27:      }
  28:  
  29:      public string CommandArgument
  30:      {
  31:          get { return (string)ViewState["CommandArgument"]; }
  32:          set { ViewState["CommandArgument"] = value; }
  33:      }
  34:  
  35:      public string CommandName
  36:      {
  37:          get { return (string)ViewState["CommandName"]; }
  38:          set { ViewState["CommandName"] = value; }
  39:      }
  40:  
  41:      public string PostBackUrl
  42:      {
  43:          get { return (string)ViewState["PostBackUrl"]; }
  44:          set { ViewState["PostBackUrl"] = value; }
  45:      }
  46:  
  47:      public string ValidationGroup
  48:      {
  49:          get { return (string)ViewState["ValidationGroup"]; }
  50:          set { ViewState["ValidationGroup"] = value; }
  51:      }
  52:  
  53:      public event EventHandler Click;
  54:      public event CommandEventHandler Command;
  55:  
  56:      public void RaisePostBackEvent(string eventArgument)
  57:      {
  58:          if (CausesValidation)
  59:          {
  60:              if (Page.IsPostBack)
  61:                  Page.Validate();
  62:              if (!Page.IsValid)
  63:                  return;
  64:          }
  65:  
  66:          OnClick(EventArgs.Empty);
  67:          OnCommand(new CommandEventArgs(CommandName, CommandArgument));
  68:      }
  69:  
  70:      protected virtual void OnCommand(CommandEventArgs eventArgs)
  71:      {
  72:          if (Command != null)
  73:              Command(this, eventArgs);
  74:  
  75:          RaiseBubbleEvent(this, eventArgs);
  76:      }
  77:  
  78:      protected virtual void OnClick(EventArgs eventArgs)
  79:      {
  80:          if (Click != null)
  81:              Click(this, eventArgs);
  82:      }
  83:  }

Above control can be used as below:

   1:  ...
   2:  
   3:  <asp:ListView ID="listViewOfSomething" runat="server" OnSelectedIndexChanging="OnSelectedIndexChanging">
   4:      <LayoutTemplate>
   5:          <table id="htmlTableOfSomething" >
   6:              <tbody>
   7:                  <asp:PlaceHolder ID="itemPlaceholder" runat="server" />
   8:              </tbody>
   9:          </table>
  10:      </LayoutTemplate>
  11:      <ItemTemplate>
  12:          <vdd:ListViewRowClickCommand ID="ListViewRowClickCommand" runat="server"
  13:              CommandName="Select" Class="SomeCssClassForRow" >
  14:              <td class="CssClassForColumn">
  15:  
  16:  ...

Feel free to put comments in case if things are not clear.

February 2, 2010

Ignorance is not bliss. EventWaitHandle.OpenExisting throws WaitHandleCannotBeOpenedException

Filed under: .net,windows plateform Himanshu @ 12:06 pm

My development computer got upgraded to Windows 7, Windows 7 is good experience.

For one of our client, I needed to setup mechanics such that admin users should be able to initiate a process in Windows Service using GDI based .NET application. We had also developed the windows service in .NET. As both of them are .NET applications, there are more than one ways to IPC between them. As in this case there was only need to give signal to the service, I choose to do it through Windows Event. .NET BCL provides wrapper around Win32 functions to do this through type named EventWaitHandle.

I completed the code like I used to do in my old days, and tried the first use of it. On call to OpenExisting, client application failed with exception “No handle of the given name exists”. My first thought was that this could be because of UAC, but in that case it should say something like access violation. I tried running application in Windows 2003 Server and it worked perfectly. I decided to check documentation.

After some time I landed to msdn page for namespaces of kernel objects, which indicates that:

For processes started under a client session, the system uses the session namespace by default. However, these processes can use the global namespace by prepending the “Global\” prefix to the object name

changed my client code to have name prefixed with “Global\”, and everything started behaving the way I wanted it to in Windows 7 as well.

November 12, 2009

Extending code readability by extension methods

Filed under: .net,programming Himanshu @ 9:40 am

If you haven’t noticed, note that extension methods can also be called on null objects. Meaning, there can be extension method which checks whether an object is null or not. So,

public void Operate(InputType inputObject)
{
    if (null != inputObject) 
    { 
        . . .
    }
} 

public void Operate(InputType inputObject)
{
    if (null == inputObject) 
    { 
        . . .
    }
} 
 

Can be replaced by

 
public void Operate(InputType inputObject)
{
    if (inputObject.IsNotNull()) 
    { 
        . . .
    }
} 

public void Operate(InputType inputObject)
{
    if (inputObject.IsNull()) 
    { 
        . . .
    }
} 

May 15, 2009

Sending email message having embedded image (.NET)

Filed under: .net,asp.net,programming Himanshu @ 5:16 am

Does your .net application send email messages? Does it send formatted email messages? I think applications should always send formatted email messages instead of text only. (Are asking why? Simple, formatted messages are much more capable, presentable, …).

Counter argument: Some user uses email client that are not capable to show HTML messages. Or someone is doing it for security purpose. Okay, I agree, then send both the views; text view as well as HTML view. Using .NET, one can send multi view email messages, depending on email client settings and/or capability, client is expected to pick the right view and shows that to the user.

Next question is, say we have decided to send email in html and text view, can we send images and style sheets embedded with email? Answers is yes. Here is how one can send multi-part email message using .net libraries that has embedded image.

Here goes the first step, create MailMessage object and setup that with appropriate values

   1: var from = new MailAddress("admin@objectpattern.com", "Himanshu");
   2: var to = new MailAddress("himanshu@objectpattern.net");
   3: var message = new MailMessage(from, to) { Subject = "Hi from ObjectPattern"};

next step changes. As we want to have two views – text and html, we will have to create email body differently.

in these lines of code, there are certain important points

   1: //creating text view
   2: var textViewContent = "Test content for text view";
   3: var textView = AlternateView.CreateAlternateViewFromString(textViewContent, Encoding.UTF8,
   4:                                                            MediaTypeNames.Text.Plain);
   5: //creating html view 
   6: var htmlViewContent = "

Html content containing image logo

Thanks,
ObjectPattern
logo";
   7: var htmlView = AlternateView.CreateAlternateViewFromString(htmlViewContent, Encoding.UTF8,
   8:                                                            MediaTypeNames.Text.Html);

that I would like to bring in to your notice.

  • Notice that we are not assigning Body property of MailMessage type
  • While creating view, we are specifying media type name as either plain text or html text, it can also be rich text.
  • We have created an img tag that referring to source as ‘cid:logo.png’

okay now how we will embed image into email message? That’s easy as well:

   1: var logo = new LinkedResource("images/logo.png", MediaTypeNames.Image.Jpeg) {ContentId = "logo.png"};
   2: htmlView.LinkedResources.Add(logo);

here in first line, first parameter of constructor (“image/logo.png” text) specifies the path of the image file. One can also supply image content as stream if its not coming directly from the file. Now remember, in above section, we had specified the src attribute of img tag, that should match with content id. Else image will not be shown correctly in email client. Also notice that we are adding this image to html view.

We are almost done now. All we need to do now is to add views to message object and sending using SMTP client.

   1: message.AlternateViews.Add(textView);
   2: message.AlternateViews.Add(htmlView);
   3:

January 13, 2009

Changing version of .net framework dependency for setup and deployment project in visual studio 2008

Filed under: .net,vs.net Himanshu @ 3:50 pm

Its easy to do, but not obvious to locate, at least to me. It took a while for me to find, so I thought let’s log it, in case if I need it in future, or someone else might need it. I need to create setup that depends on .NET framework 2.0. instead of 3.5 which is default in VS.NET 2008.

After creating setup and deployment project, double click on dependency of .net framework in solution explorer:

doubleClickDependency

Now, you should be able to see launch condition for .net framework in “Launch Conditions” tab. Until you double click for the first time, node do not appear in launch conditions. And that’s where I wasted some hours:

lauch condition

Select the node and see the property window, where you will find the answer of the question:

version

November 21, 2008

Navigate and injecting C# code using visual studio macro

Visual studio macros are great, probably I will write this in all posts that I write for macros :). Sometime back, I need to change a fairly big CF.NET application such a way that it will log a line on each function entry and on function exit. We were tracing for cause of intermittently occurring GWES.EXE error, and we were tracing it from multiple directions. The error code of GWES was 0xC0000005, which means someone was trying to access something, which was never allocated or is being accessed after releasing it. Application was multi-threaded, and hence it was difficult to understand which thread will do what at what time.

Moving back to original point, we wanted to log entry and exit of each functions. There can be more then one way to do that, but we have selected to change each functions. And to change each functions I have selected to use developer named “VS.NET macro”.

From macro it is possible to navigate through solution and projects. So macro first needs to find out all class types from a project, and then for each class, iterate through its member and find out functions that has body. If function has body, inject the code that logs line on function entry and exit.

It was easy to find function entry, but there can be many way function ends, like exception is being thrown, or based of some condition it may execute “return”, or body of the function is ended and hence return. To accommodate such cases, we decide to use “using statement” of C#.

All right, enough of the background, have look at Macro code here

August 5, 2008

Paging of SQL Server records

Filed under: .net,sql server Himanshu @ 6:29 am

In one of my ASP.NET, SQL Server project, we were expected to provide paging in the ASP.NET GridView. Microsoft’s very common sample will do this using Dataset filled with all records. If someone is doing GridView paging, s/he is doing it not waste server’s or client’s precious resources, Isn’t it?

To me, it make more sense to do paging of records being fetched in server memory along with view paging. What if table in question has more then 100,000 (1 lack) records?

Digging a bit further, I found a resource which explains how to do paging of records being sent from stored procedure. But it was expecting to have auto identity as primary key in the table. And we were so fortunate that we couldn’t have db design such that we can afford to have auto identity primary key, and so that solution to the paging problem. On doing some more finding, we all agreed to a solution that is described below. It’s not fully optimized, as it do not have any optimization for SQL Server to prepare result sets. But worked for our need in specific project as even in 100,000 records it was working very fast.

In our solution, stored procedure that will fetch records from table and return to caller will needs to have two addition parameters, @RowIndexFrom and @RowIndexTo

Getting customers by page will look like following,

CREATE PROCEDURE [dbo].[GetCustomersPage]
(
    @RowIndexFrom int,
    @RowIndexTo int
)
AS
BEGIN
    SET NOCOUNT ON;

    WITH IndexedCustomers AS
    (
        SELECT
            ROW_NUMBER() OVER (ORDER BY Id) AS rowIndex,
            Customers.*
        FROM
            Customers
    )
    SELECT * FROM IndexedCustomers WHERE rowIndex BETWEEN @RowIndexFrom AND @RowIndexTo

    SELECT COUNT(*)
    FROM
        Customers
END
GO

 

The stored procedure returns two result set, first will be records for given page (defined by different between @RowIndexFrom and @RowIndexTo parameters). And the second result set will give total number of records for give query. Second result set will help preparing pages list. So, if first page needs to be retrieved of page size 10, parameter values should be 1 and 10 respectively.

March 27, 2008

Sending keystrokes (Key press) from .Net to active application

Filed under: .net,programming,robo coding Himanshu @ 5:32 pm

Many of the part of windows works on messages – windows messages. One code can send different kind of messages to another application using Windows API. Keyboard messages and mouse messages are one of them.

.NET is one more layer above OS, e.g. Windows. If someone needs to emulate keyboard strokes to another application from .NET there is a choice of using .NET class library. To emulate keyboard events from .NET it’s easier to use

  • System.Windows.Forms.SendKeys.Send(string) and
  • System.Windows.Forms.SendKeys.SendWait(string)

Recently, I used this to auto log into a application that I’m developing if it’s debug build. Just to get a change from AutoHotKey.

The problem of this is it sends keystrokes to only active application.

March 17, 2008

VS.NET, macro creating string const, and macro creating string resource entry

Filed under: .net,programming,robo coding,vs.net Himanshu @ 2:08 pm

Per me, macro is one of the most important feature for any text editor or software IDE. And hence, it is very import for VS.NET user to understand and then use macros available in VS.NET. VS.NET macros are very powerfully tool and they help in lot more different ways.

I have created two macros that are very common in their need. While programming, we need to create string const on regular bases. It becomes inconvenient to go to top of the class while writing a method body for same class and create constant. Macro in library attached with this post becomes handy at that time.

Same use case hold very much true for creating string resources while writing method body. And it becomes really very easy if string resource can be created while writing method body.

For those who thinks like me (or want to 🙂 ), I have attached two macros with this post. Macro works for VS.NET 2005, haven't tested in any other version. But should work fine in VS.NET 2003 or VS.NET 2008

Powered by WordPress