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 10, 2009

Knowing memory usage from Compact Framework application

For any handheld device application, memory usage is an important element to observer. .NET Compact framework have very less code that gives information about physical or virtual memory. But using native libraries – by doing pInvoke, one can retrieve memory usage statistics.

There can be more than one level of report that can be captured. Today, lets start with summary. GlobalMemoryStatus function in coredll can help identifying how much total physical memory available in the device and how much of it is free. Same way, how much of virtual memory available to process and how much of it is free.

Lets see how can we use GlobalMemoryStatus. We will have to define a class which will be passed to function and will be filled by GlobalMemoryStatus function. Layout of it is defined as structure by MS team, but its alright to use class here. By having it as class, we will be able to write default constructor unlike structure in C#.

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    internal class MemoryStatus
    {
        public uint dwLength;
        public uint dwMemoryLoad;
        public uint ullTotalPhys;
        public uint ullAvailPhys;
        public uint ullTotalPageFile;
        public uint ullAvailPageFile;
        public uint ullTotalVirtual;
        public uint ullAvailVirtual;
        public uint ullAvailExtendedVirtual;
        public MemoryStatus()
        {
            this.dwLength = (uint)Marshal.SizeOf(typeof(MemoryStatus));
        }
    }

Now, lets define extern method for GlobalMemoryStatus

        [return: MarshalAs(UnmanagedType.Bool)]
        [DllImport("coredll.dll", CharSet = CharSet.Auto, SetLastError = true, EntryPoint = "GlobalMemoryStatus")]
        static extern bool GlobalMemoryStatusWinCE([In, Out] MemoryStatus lpBuffer);

And here is how we can call the method

    MemoryStatus internalReport = new MemoryStatus();
    if (GlobalMemoryStatusWinCE(internalReport))
	

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

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

March 10, 2008

Automation, Software Engineering, Productivity

Filed under: programming,robo coding,vs.net Himanshu @ 12:22 pm

It’s good to use computer as far as it is possible to do. Around the world, many computer engineers work for others to generate code-base that instructs computers to act as it’s user would like it to. Computers gives more accessibility to the information, knowledge, gives more processing power, help to be more managed and allow us to utilize much more clock cycle of our main thread – a human main thread, which can really do the thinking. Ultimately that what the difference is between human and machines in today edge. That is why we have many software built today. Operating systems, financial applications, engineering application and many others, including the RAD (Rapid application development) tools. RAD in compare to the edge where programmers need to punch the cards makes developer very efficient in generating computer instructions. And of-course even computers are also much more efficient now a days.

Anyway, many of us knows most of above that I have written. The point here is use computers, as much as you can to increase productivity. And it applies to software engineers as well. To support that, I’m planning to take several efforts that will include blog-posts, posting some tools, VS.NET macros, snippets and something else that will help.

Although this wouldn’t be the only goal of this blog-post repository (making it explicit as this is first blog-post in this repository), I’m starting with posting first version of first macro that creates resource entry of a selected string in the code. The macro is posted separately to make both more manageable. I’m linking my first macro with this blog post here, but will not do same for other automation posts that I will post later. To find them you should see posts tagged under RoboCoding. Please mind that the macro is in version-1, I will fix and enhance it as time ticks and the need. As well as more of such will come in future.

Powered by WordPress