It’s fare to guess or assume, in fact it helps moving forward in at least one direction, and is inevitable many a times. But started believing that a guess or assumption is truth, can be really harmful. Eventually questioning guesses and assumptions is important, and that also helps being open for multiple perspectives.
April 18, 2010
February 2, 2010
Ignorance is not bliss. EventWaitHandle.OpenExisting throws WaitHandleCannotBeOpenedException
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 with Google and documentation. I found this, which gave me a relieving thought – “I’m not the only one in this world!”
.
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
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)
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";
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
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:

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:

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

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
August 6, 2008
OpenID, myOpenID Rocks!
I have been using openID from last 5-6 months as and when I got chance to use it. It’s getting popular more and more now a days. I see more and more sites supporting it. When first time I learned about it, first thing that came to my mind was to support openID login for my site. And second thing that came to my mind was, MS passport got competition
. I haven’t seen passport authentication much popular apart from Microsoft sites.
As I didn’t had anything to secure on my site. So far I haven’t actively started working on to support openID login. It also make sense to have user ids for features like customization, but my site is not supporting that either. I would like to support openID authentication as soon as I finish coding with site-spaces that supports customization and security. Mainly when I need user authentication.
On root (http://root.objectpattern.com) page, that is like dashboard, I’m planning to have UI that supports customization/personalization. And once I finish coding Media Gallery, I will need authorization their for different spaces/albums of it, yeah some media will be private to my family and friends. I have done some initial tests using DotNetOpenID (http://code.google.com/p/dotnetopenid/). But that library didn’t worked well on GoDaddy hosting, because of trust level that GoDaddy Deluxe hosting gets. Haven’t done much research on that to fix it some how.
Also did some initial tests with myOpenId (http://myopenid.com) to setup such that I/someone can have openId as http://openid.objectpattern.com/
Anyway, I’m posting this to let you know a) openID Rocks
b) I’m planning to be openID consumer, c) setup with help of myOpenId is ready to have openID as openid.objectpattern.com/*.
By the way, did I told you what is openID? Oh, never mind just take a look at it’s official site (http://www.openid.net) if you don’t know what is openID and after that if you have any further queries about it, send me email or comment your query against this post, and I will try answering them.
August 5, 2008
Paging of SQL Server records
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.
July 23, 2008
Creating a windows shortcut using AutoIt
AutoIt library do have function to create windows shortcut, FileCreateShortcut. AutoIt script to create new shortcut of specified target in specified file/folder. Once compiled and created executable, use it in following way.
Usage:
shortCut.exe
First parameter is required and should be path of file/folder for which to create shortcut
Second parameter is optional and if specified, should be full existing path including shortcut file name. If not specified shortcut will be created in the folder from where executable is run.
If ($CmdLine[0] < 1) Then
MsgBox(16, "Error", "Insufficent parameters. In first parameter, specify for which file, shortcut should be created.")
Return
EndIf
$shortcutOf = $CmdLine[1]
If (Not FileExists($shortcutOf)) Then
MsgBox(16, "Error", "File/directory """ & $shortcutOf & """ do not exists")
Return
EndIf
$shortcutPath = @WorkingDir & "\" & "Shortcut of " &
$shortcutOf & ".lnk"
If ($CmdLine[0] = 2) Then
$shortcutPath = $CmdLine[2]
If (StringLower( StringRight($shortcutPath , 4)) <> ".lnk" ) Then
$shortcutPath = $shortcutPath & ".lnk"
EndIf
EndIf
$objShell = ObjCreate("Wscript.Shell")
$shortcut = $objShell.CreateShortcut($shortcutPath)
$shortcut.TargetPath = $shortcutOf
$shortcut.WindowStyle = 1
$shortcut.Save()
If you want to download script file click here
Let me know if you need any further help in it.
"