Friday, November 21, 2008
C# Nullable Numeric Data Types
The nullable types described in this article were introduced to the C# programming language with version 2.0 of the .NET framework. In order to achieve similar results using earlier framework versions, the developer must create a new structure or class. Structures will be looked at in a later article.
Null Value
When a program works with numeric information, particularly when it utilises information in a database, it is often the case that a value is undefined. An example of this is when a series of simple yes / no questions is asked and the result of each question held in a Boolean format. After a question is answered, the Boolean value can be set to either true or false to indicate the result. However, before the answer is given what should the value hold? The answer is null.
Nullable Numeric Data Types
Null is a special value that represents information that has not yet been defined. When the C# language was originally defined, the value null existed but could not be applied to numeric variables. In .NET framework 2.0, Microsoft rectified this problem by introducing nullable versions of these data types. Prior to this, the developer would need to work around this problem using values that would not normally be used by the variable or by holding a Boolean value indicating whether the numeric variable should be considered as defined or not.
All of the basic numeric data types have nullable equivalents. There are several ways to declare a variable as a nullable type. The simplest and most readable method is to simply append a question mark (?) to the data type. The following example shows the declaration and assignment of several nullable variables:
int? nullableInt;
int? nullValue = null;
int? notNull = 123;
bool? answer1 = true;
bool? answer2 = false;
bool? answer3 = null;
You can see from the above example that creating a nullable variable is similar to creating a standard numeric variable. As with other numeric variables, a value must be assigned to a variable before it is used, even if that value is null. The following code produces an error if you attempt to compile it.
int? nullableInt;
int? copy = nullableInt; // Invalid as nullableInt is not yet assigned
Data Type Conversion
Numeric nullable data types include very similar implicit and explicit conversion between the various sizes of nullable integers and floating point values. Values can also be converted between their nullable and non-nullable versions. As you would expect, conversion between two incompatibly sized types requires a cast statement, as does casting from a nullable to a non-nullable type.
int standardInteger = 123;
int? nullableInteger;
decimal standardDecimal = 12.34M;
// Implicit conversion from int to int?
nullableInteger = standardInteger;
// Explicit conversion from int? to int
standardInteger = (int)nullableInteger;
// Explicit cast from decimal to int?
nullableInteger = (int?)standardDecimal;
Care must be taken when casting a nullable value as a non-nullable data type. If the value of the nullable data type is null, this cannot be represented in the destination value and a run-time error will occur. This can be avoided by checking if the value is set to null before attempting the conversion.
Arithmetic Operators
The standard arithmetic operators can be used with numeric nullable data types. However, if the value of any of the operands is null, the result will always be null regardless of any other values.
int? a = 55;
int? n = null;
int? result;
result = a * 2; // result = 110
result = a * n; // result = null
Boolean Operators
When using nullable Boolean data types, the binary standard Boolean logical operators can be used. Where both of the operands used are set to either true or false, the results of the operation are exactly the same as for non-nullable Booleans. Where one or both of the operands used in a logical operation are set to null, the result is usually null. There are two special cases where this does not happen. In a logic OR operation, if any value is true then the result is true, even if the other operand is null. For logical AND operations, if either value is false then the result is also false.
bool? result;
result = true & null; // result = null
result = false & null; // result = false
result = true | null; // result = true
result = false | null; // result = null
result = true ^ null; // result = null
result = false ^ null; // result = null
Relational Operators
The relational operators are all valid for use with nullable numeric data types. However, when the value being compared is null, the results are not always as expected. The equal to and not equal to operators are able to make comparisons with both numeric and null values. With all of the other relational operators, the result of the comparison is always false when a value being compared is null.
int? a = 55;
int? n = null;
bool result;
result = a == n; // result = false
result = a != n; // result = true
result = n == null; // result = true
result = a > n; // result = false
result = a < result =" false" style="font-weight: bold;">Testing for Null Values
The previous section showed the use of the relational operators with numeric nullable types. Included in the examples you can see that it is possible to use the equal to or not equal to operators to test if the value of a variable is null. In addition to these operators, the nullable data types define several properties and methods for checking if the value is null and for retrieving the value where it is not.
HasValue Property
The first property of the numeric nullable types of interest is the HasValue property. This property simply returns a Boolean value indicating whether the nullable variable contains a real value or a null value. To access the value of a property, the member access operator is used. This is simply a full stop (period or dot) placed between the name of the variable and the name of the member (property or method) to be used. The following example shows the HasValue property used to set a non-nullable value to the value of a nullable type with a default value of -1 where the nullable variable has no value.
int? a = 10;
int? n = null;
int result;
bool checkIfNull;
checkIfNull = a.HasValue; // checkIfNull = true
result = checkIfNull ? (int)a : -1; // result = 10
checkIfNull = n.HasValue; // checkIfNull = false
result = checkIfNull ? (int)n : -1; // result = -1
Value Property
The numeric nullable data types include a second property that can be used to retrieve the value from a variable as a non-nullable type. This provides the same effect as a cast from a nullable type to its non-nullable counterpart. As with this type of cast however, a run-time error will occur should the value of the variable be null. The previous example can therefore also be written as follows:
int? a = 10;
int? n = null;
int result;
bool checkIfNull;
checkIfNull = a.HasValue; // checkIfNull = true
result = checkIfNull ? a.Value : -1; // result = 10
checkIfNull = n.HasValue; // checkIfNull = false
result = checkIfNull ? n.Value : -1; // result = -1
result = n.Value; // This causes a run-time error.
GetValueOrDefault Method
The GetValueOrDefault method is available to all of the numeric nullable data types. This method provides all of the functionality of the previous example in a single line of code. The method can be called in two ways. If the method is used without a parameter then the numeric value of the nullable data is returned. If the variable in question has a null value, a zero is returned instead. The second manner to call the method includes passing a parameter to specify the default value to replace nulls with. As with all methods, the parameter is held in parentheses with an empty pair of parentheses should no parameter be specified.
int? a = 10;
int? n = null;
int result;
result = a.GetValueOrDefault(); // result = 10
result = n.GetValueOrDefault(); // result = 0
result = n.GetValueOrDefault(-1); // result = -1
The Null Coalescing Operator
The null coalescing operator is a new operator introduced as a part of the .NET framework version 2.0. This operator can be used on any numeric nullable data type and also other nullable data types that have yet to be introduced in the C# Fundamentals tutorial.
The null coalescing operator tests the value of a variable to check if it is null. If the value is not null then the variable's value is returned unaffected. If the variable is null however, a substitute value is provided as a second operand. The operator provides similar functionality to the GetValueOrDefault method with the benefit that it can be used on data that does not provide this functionality. The operator's symbol is a double question mark (??).
int? a = 10;
int? n = null;
int result;
result = a ?? -1; // result = 10
result = n ?? -1; // result = -1
Citation here
Wednesday, November 12, 2008
Say Hello to Gmail Voice & Video Chat
That's why today Google is launching voice and video chat -- right inside Gmail. They've tried to make this an easy-to-use, seamless experience, with high-quality audio and video -- all for free. All you have to do is download and install the voice and video plugin and it'll take care of the rest. And in the spirit of open communications, designed this feature using Internet standards such as XMPP, RTP, and H.264, which means that third-party applications and networks can choose to interoperate with Gmail voice and video chat.
Once you install the plugin, to start a video chat, just click on the "Video & more" menu at the bottom of your Gmail chat window, and choose "Start video chat." You'll have a few seconds to make sure you look presentable while it's ringing, and then you'll see and hear your friend live, right from within Gmail. You can click the "pop-out" iconto make the video larger, or click the fullscreen iconin the upper left-hand corner for a fully immersive experience. See this all in action in the video below.
Team is spread between Google offices in the US and Sweden, and video has really changed the way we work. Collaborating across continents and timezones is a fact of life, and it sure is easier (and greener) to click "Start video chat" than to get on a plane! And when I do have to visit another office, I can use Gmail voice and video chat to check in with my family.
They've just started to roll out Gmail voice and video chat for both PCs and Macs, so if you don't see it right away, don't worry -- it could take a day or so for this feature to be available in all Gmail and Google Apps accounts. If you want to download the plugin right away, visit http://gmail.com/videochat.
Citation here
Custom shortcuts in the Windows XP dialog box
Note: This also works in Windows Vista Ultimate Edition, but not sure about the other versions of Vista.
1. Click Start and select Run. In the Run window enter gpedit.msc and click OK.
2. The Group Policy editor will appear.
3. In the left window select the + (plus sign) next to User Configuration to expand the list. Next select the plus sign next to Administrative Templates and then Windows Explorer. Finally, select the Common Open File Dialog entry.
4. Double-click the Items displayed in Places Bar entry in the main Group Policy window.
5. The Items displayed in Places Bar Properties window will open.
6. Select Enabled and then enter in the locations you’d like to have displayed in the Save As dialog box. You need to enter the full path to the location for the shortcuts to work.
For example, if you want to have a shortcut to your My Documents folder, enter in:
C:\Documents and Settings\Your User Name\My Documents\
7. Once you’ve entered in all the locations you’d like to appear in the Save As window, click Apply and then OK.
8. Back in the Group Policy editor, you should see that the Items displayed in Places Bar is now Enabled. Close the Group Policy editor.
9. Test it out by saving a file. You should now have the new shortcuts displayed.
10. The same shortcuts will be used in the Open dialog box, not just the Save As box.
Citation here
Sunday, May 25, 2008
How to set up and use remote debugging in Visual Studio .NET?
The Remote Debugging Monitor runs as a Microsoft Windows application. The user interface shows that the Remote Debugging Monitor is running and makes remote debugging easy to set up.
Let's consider an example to understand this situation clearly. Molly Clark and Adam Barr are both employees at Adventure Works. Adventure Works has a Microsoft Windows NT domain named adventure-works.com. Adam is having trouble with some software that Molly wrote. Molly would like to debug this software on Adam's computer. Molly and Adam follow these steps:
- Adam doesn't have the remote debugger on his computer. To set up the remote debugger, Molly decides to share out the Program Files\Microsoft Visual Studio 8\Common7\IDE\Remote Debugger directory on her computer. She creates a file share called Remote.
- Adam runs \\MollyComputerName\Remote\x86\Msvsmon.exe.
- After the remote debugger starts, Adam clicks Permissions on the Tools menu to configure the remote debugger by using the Permissions dialog box. He gives Molly permission to debug.
- Note: Adam could also configure the remote debugger by passing the /allow option when the remote debugger starts.
- Molly starts Visual Studio 2005.
- To open the Attach to Process dialog box, Molly clicks Attach to Process on the Tools menu.
- Molly connects to Adam's computer by entering adventure-works.com\Adam@AdamComputerName in the Qualifier box.
- Under Available Processes, Molly selects the worker process that her application is using and then clicks Attach.
- Molly opens a browser and provides the URL to the remote application. The execution stops where the breakpoint is placed in the application.
http://support.microsoft.com/kb/910448
http://support.microsoft.com/kb/318041
Saturday, May 24, 2008
log4net - Quick Reference
log4net is a tool to help the programmer output log statements to a variety of output targets. In case of problems with an application, it is helpful to enable logging so that the problem can be located. With log4net it is possible to enable logging at runtime without modifying the application binary. The log4net package is designed so that log statements can remain in shipped code without incurring a high performance cost. It follows that the speed of logging (or rather not logging) is crucial.
At the same time, log output can be so voluminous that it quickly becomes overwhelming. One of the distinctive features of log4net is the notion of hierarchical loggers. Using these loggers it is possible to selectively control which log statements are output at arbitrary granularity. log4net is designed with two distinct goals in mind: speed and flexibility.
For more technical details and details, visit
Friday, May 9, 2008
Google Account Hijacked???
I just got a message in Facebook from a friend whose Google Account was hijacked and the password was changed by the hacker. That person is now looking for some kind of a Google helpline to help him revive the account.
It can be a nightmare if someone else takes control of your Google Account because all your Google services like Gmail, Orkut, Google Calendar, Blogger, AdSense, Google Docs and even Google Checkout are tied to the same account.
Here are some options suggested by Google Support when your forget the Gmail password or if someone else takes ownership of your Google Account and changes the password:
1. Reset Your Google Account Password:
Type the email address associated with your Google Account or Gmail user name at google.com/accounts/ForgotPasswd - you will receive an email at your secondary email address with a link to reset your Google Account Password.
This will not work if the other person has changed your secondary email address or if you no longer have access to that address.
2. For Google Accounts Associated with Gmail
If you have problems while logging into your Gmail account, you can consider contacting Google by filling this form. It however requires you to remember the exact date when you created that Gmail account.
3. For Hijacked Google Accounts Not Linked to Gmail
If your Google Account doesn’t use a Gmail address, contact Google by filling this form. This approach may help bring back your Google Account if you religiously preserve all your old emails. You will be required to know the exact creation date of your Google Account plus a copy of that original “Google Email Verification” message.
It may be slightly tough to get your Google Account back but definitely not impossible if you have the relevant information in your secondary email mailbox.
Gmail has limits!
Gmail imposes a limit on the attachment size (20 MB) and the overall storage space (6 GB and growing) but there’s also a daily quote on sending email. Break the rules and Google will disable you Gmail account temporarily without any warnings.
So while sending an email message to a large group of friends using Gmail, read the following rules to avoid temporary shut-down of Gmail:
Rule 1. If you access Gmail via POP or IMAP clients (like Microsoft Outlook), you can send an email message to a maximum of 100 people at a time. Cross the limit and your account will be disabled for a day with the error "550 5.4.5 Daily sending quota exceeded."
Rule 2. If you access Gmail from the browser, you may not address an email message to more than 500 people at a time. Try adding any more recipients in the To, CC or BCC field and your Gmail account will get probably disabled for 24-72 hours. Error: "Gmail Lockdown in Secton 4"
Rule 3. Always double check email addresses of recipients before hitting the Send button in Gmail. That’s because your account will get disabled if the email message contains a large number of non-existent or broken addresses (<25>
Rule 4. This is slightly unrelated but still important - Google will disable your Gmail account permanently if you don’t check your Gmail email for a period of nine months. All the stored messages will be deleted and you Gmail address (user name) may be released for others to grab it.
Sources: Beth Kanter, Gmail Policies, Sending Limits
Monday, May 5, 2008
How to load an application and run from memory using C#?
First Step
Load the exe file in one stream and read it as an array of bytes:
// read the bytes from the application exe file
FileStream fs = new FileStream(filePath, FileMode.Open);
BinaryReader br = new BinaryReader(fs);
byte[] bin = br.ReadBytes(Convert.ToInt32(fs.Length));
fs.Close();
br.Close();
Using the FileStream class is possible to open the exe file (location indicated in the filePath variable), read and close it to release resources.
Second Step
Use the Assembly.Load method to load the exe file (as array of bytes) into the Assembly cache:
// load the bytes into Assembly
Assembly a = Assembly.Load(bin);
Now we can try to find the Entry Point of the application:
// search for the Entry Point
MethodInfo method = a.EntryPoint;
if (method != null) { ... }
If an Entry Point is found, is possible to create an Istance of the Application Main method and invoke it from our application launcher:
// create an istance of the Startup form Main method
object o = a.CreateInstance(method.Name);
// invoke the application starting point
method.Invoke(o, null);
If all will be ok, the called application will start without using the source EXE file (try to move it to check).
NOTE: Pay attention to the Application.SetCompatibleTextRenderingDefault method of the called application. Visual Studio 2005 applies this line in the Main method (located inside the Program.cs file) to use the new GDI+ library in our applications, but it will throw an exception because it must be called before the first IWin32Window object is created.
Saturday, May 3, 2008
How do you convert a String into an Enum in C#?
One of my colleagues came up with the answer yesterday; it's one of those methods that you can never find when you're looking for it, but once discovered it seems blindingly obvious:
object Enum.Parse(System.Type enumType, string value, bool ignoreCase);
So you can write the following kind of code:
enum Colour
{
Red,
Green,
Blue
}
Colour c = (Colour) Enum.Parse(typeof(Colour), "Red", true);
Console.WriteLine("Colour Value: {0}", c.ToString());
// Picking an invalid colour throws an ArgumentException. To
// avoid this, call Enum.IsDefined() first, as follows:
string nonColour = "Polkadot";
if (Enum.IsDefined(typeof(Colour), nonColour))
c = (Colour) Enum.Parse(typeof(Colour), nonColour, true);
else
MessageBox.Show("Uh oh!");
What a time saver - Thanks, Simon!
Footnote: interestingly, whilst writing this up I noticed that Enum.IsDefined() doesn’t offer the ignoreCase parameter. If you don’t know whether the casing is right, it seems the only way to do the conversion is using the Parse method and catching the ArgumentException. That's not ideal, since it runs a lot slower. I wonder if this is a loophole in the design; no doubt someone like Brad could cast light on it...
Monday, April 21, 2008
Installing Windows Service from Command Prompt
installutil myService.exe
installutil /u myService
Using command line to install Windows Service
This usefull command is not the most intuitive command. The sc command allows you to install/delete Windows Services. I have used this nifty command quite often in the past project to remove erroneous Windows Service. Microsoft has a good KB article.
Things to watch out is the escaping of the binPath. If there are spaces in your binPath you must escape it using the " character which must be escaped again using the \ character.
For example: c:\sc create MyService binPath= "\"c:\program files\my service\service.exe\""
Sunday, April 20, 2008
How to Import Music from an iPod?
Here's a way to quickly get files off a PC iPod without any extra software.
- Plug in your iPod.
- From the Desktop, go to My Computer and find the iPod (usually designated by a drive letter. i e. E: or F:)
- Open the folder.
- Go to Tools > Folder Options > View (the tab) > scroll to Show Hidden Files and Folders and click it.
- Click OK
- Go back to your iPod folder/drive, there you will find a new folder called iPod_Control
- Open it.
- The Music folder in it will have a bunch of folders named F00, F01 and so on. THEY HAVE YOUR MP3s. Look through the folders to find your stuff.
Friday, April 18, 2008
Using Visual Studio .NET Built-in Web Server from Command Line
Everyone should take time to browse the command line from time-to-time. You never know what you'll find lurking about in the recesses of all those folders on your system. The other day, I was exploring the .NET Framework 2.0 folder, \WINDOWS\Microsoft.NET\Framework\v2.0.50727. I found all of the utilities I expected — and one that I didn't.
It was a new application, named WebDev.WebServer.EXE. Other than the very odd filename, anyone who's worked with Visual Web Developer will instantly understand the implications of that application. This program lets you execute Web applications from within Visual Web Developer and Visual Studio 2005 using the built-in Web server.
I can't stress enough the importance of this particular application. The built-in Web server is one of the best ideas that Microsoft has had in a long time. You can create a local Web site using a folder containing Web files of any type, not just ASP.NET files. For example, I tested it with my personal Web site. It came right up in the browser using the built-in Web server.
While that's kind of cool, you should know the whole story before you decide about this particular .NET Framework 2.0 feature. No one but you can access the built-in Web server. First, it can use odd port numbers instead of the more common port 80. Also, Microsoft didn't design the server for outside access. Consequently, you can run your personal server without fear of prying eyes.
Wednesday, April 16, 2008
Clearing MS VS.NET 2005 Recent Project History
Page" which contains the history of recent projects opened. The number
for projects opened to be remembered can be configured at
Tools>Options>Environment>General>Recent Files
If a history project's solution or project file was moved/deleted, then
the VS.NET itself would recognize it and would ask the user to if it
needs to remove it from the history list. But what if, I need to remove
a project in the history list even if it is not moved/deleted?
I just found a registry solution.
HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0\ProjectMRUList
The above registry path refers to the location where VS.NET stores the
recently opened projects. You can clear this location to make VS.NET
remember afresh.
Get calling function name from the called function in C#
function is called so that I can use it for logging purpose. I found
that it could be obtained using StackFrame object which contains the
entire hierarchy of the function stack.
private StackFrame GetCallingStackFrame()
{
// determine the method that called the one that is calling this one.
// this is not just two up the stack because of rich exception support.
StackFrame sf = null;
// start at 2. 1 for this one and another for the one above that.
StackTrace st = new StackTrace(2, true);
Type thisType = GetType();
foreach (StackFrame sfi in st.GetFrames())
{
// find a calling method that is not part of this log class but is part of the same namespace
Type callType = sfi.GetMethod().DeclaringType;
if (callType != thisType && callType.Namespace == thisType.Namespace && !callType.IsInterface)
{ sf = sfi; break; }
}
return sf;
}
This can then be used like so.
StackFrame sf = GetCallingStackFrame();
if (sf != null) // if found add info to log message
{
System.Reflection.MethodBase mb = sf.GetMethod();
string methodName = mb != null ? mb.Name : string.Empty;
string fileName = sf.GetFileName();
if (fileName != null)
fileName = fileName.Substring(fileName.LastIndexOf('\\') + 1);
int lineNumber = sf.GetFileLineNumber();
if (fileName != null)
strMsg = fileName + " (" + lineNumber + ") - " + methodName + "
- " + strMsg;
else
strMsg = "unknown - " + methodName + " - " + strMsg;
}