String.IsNullOrWhiteSpace in .NET Framework 4

By Mohammad Mahdi Ramezanpour at March 03, 2010 03:13
Filed Under: .NET General

Microsoft .NET New Logo As you know, String class in .NET Framework contains lots of methods and properties that related to strings. One of the popular methods that we had in previous versions of .NET (3.5, 2.0, etc.) was String.IsNullOrEmpty that indicates whether a String variable contains a string or it’s Null (Nothing in VB). I’m using this method a lot of time in my project it becomes one of my favorite methods in .NET.

But what if you want to check if a String variable is Null or is contains White spaces! It’s something that I wanted to explain in this post.

In Visual Studio 2010, Microsoft introduced a new method in the String class. The method is String.IsNullOrWhiteSpace that Indicates whether a specified string is null reference (Nothing in Visual Basic), empty, or consists only of white-space characters.

How it works:

The following code shows you how to use String.IsNullOrWhiteSpace method:

using System;

public class Example
{
public static void Main()
{
string[] values = { null, String.Empty, "ABCDE",
new String(' ', 20), " \t ",
new String('\u2000', 10) };
foreach (string value in values)
Console.WriteLine(String.IsNullOrWhiteSpace(value));
}
}
// The example displays the following output:
// True
// True
// False
// True
// True
// True

For more information please visit: http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace%28VS.100%29.aspx

Hope it helps.

How to change Windows Desktop Wallpaper using C# and Windows APIs

By Mohammad Mahdi Ramezanpour at February 23, 2010 04:05
Filed Under: .NET General

It’s about a week that I’m working on an advertising application which manages customer’s advertising programs. One of the cool features that my customer requested was to change user’s desktop wallpaper into a specific photo or add some advertising notes to the current wallpaper.

So I started developing this application and faced something: “How to programmatically change Windows Desktop Wallpaper?

As you know, to change anything in Windows, you have to make use of Windows APIs. This one is the same. In order to change anything in Control Panel, There is an API function, named “SystemParametersInfo” :

The SystemParametersInfo function retrieves or sets the value of one of the system-wide parameters. This function can also update the user profile while setting a parameter.

How it works:

First of all you need to import System.Runtime.InteropServices namespace. This namespace enables you to import your favorite Windows API function library.

Note that SystemParametersInfo function is in User32.dll library.

To import a Windows API library in C#, it’s necessary to use “DLLImport” attribute:

[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int SystemParametersInfo(int uAction,
int uParam,
string lpvParam,
int fuWinIni);
Now you have the function, so you have to use it somewhere:
 
string path = @"C:\Users\Public\Pictures\Sample Pictures\Desert.bmp";
const int SPI_SETDESKWALLPAPER = 20;
const int SPIF_UPDATEINIFILE = 0x01;
const int SPIF_SENDWININICHANGE = 0x02;

SystemParametersInfo(SPI_SETDESKWALLPAPER,
0,
path,
SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);

Note that, the file you specify to be the wallpaper must be in Bitmap format. If you have JPEG, PNG, etc. files, you have to convert it to Bitmap, save it in a temp folder and then set it as Windows wallpaper.


Develop your .NET 3.5 or older applications on Visual Studio 2010 IDE

By Mohammad Mahdi Ramezanpour at January 05, 2010 06:44
Filed Under: .NET General

It’s about two month that I’m working on the new version of Visual Studio 2010 and .NET 4. The new version of .NET has some cool features that you can use in order to develop your applications much better but what I’m going to write about today is the way that you can use in order to develop you .NET 3.5 or older on the Visual Studio IDE. Upgrading to the new version of .NET is sort of risky because not many web hosts support .NET 4 and the main reason is, .NET 4 is still beta! But it doesn’t mean that you cannot use the new IDE! You can easily set the “Target Framework” to 3.5 or even 2 if you’re not going to upgrade to .NET 4. In order to do this, you can follow these steps:

  • Open your project in the Visual Studio 2010 by click File -> Open Project. When you select your specified solution, the following window will be showing up:
    VS2010_UpgradeWizard
  • Click Finish and now you can see your project’s files in the VS2010’s Solution Explorer.
  • Right-Click on the solution and select properties.
  • In properties window, select Application tab and you can see the Target Framework DropDownList:
    Visual Studio 2010 Target Framework
  • As you can see in the picture above, you can select any framework that you’ve installed on your machine or you can install additional frameworks by select “Install other Frameworks” item.

Now you can develop your .NET 3.5 or older versions on the VS2010 IDE. By the way, in the next post, I’m going to write about Visual Studio IDE.

Hope it helps.

Useful Regular Expressions

By Mohammad Mahdi Ramezanpour at March 11, 2009 19:49
Filed Under: .NET General

Today I’ve developed a class library which manages some text validations and named it “RegularExpressions.cs”. It was an easy-to-develop class but, some of the expressions were good. It uses the System.Text.RegularExpressions.Regex class in order to check for the validations. In this post, I’m going to name some of the most useful regular expressions, you may need in your usual developments.

Numeric:
Pattern: ^[-+]?\d*\.?\d*$
Matches: 123 | +3.14159 | -3.14159
Non-Matches: abc | 3.4.5 | $99.95

Email Address:
Pattern: ^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$
Matches: asmith@mactec.com | foo12@foo.edu | bob.smith@foo.tv
Non-Matches: joe | @foo.com | a@a

URL:
Pattern: ^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*$
Matched: http://www.blah.com/~joe | ftp://ftp.blah.co.uk:2828/blah%20blah.gif | https://blah.gov/blah-blah.as
Non-Matches: www.blah.com | http://www.blah"blah.com/I have spaces! | ftp://blah_underscore/[nope]

For complete list of useful regular expression you can check out: http://www.regexlib.com/

How to convert DateTime to a specific culture using CLR integration

By Mohammad Mahdi Ramezanpour at February 20, 2009 21:25
Filed Under: .NET General, SQL Server

During my Pocket PC project development, I needed to convert Gregorian date to Persian date. It’s easy to do such a thing in Windows or Web applications using System.Globalization namespace (PersianCalendar class) but this feature is not available when developing a Pocket PC application. I’ve tried a lot of things such as web services, windows services, etc but none of them is as good as converting it in your database and fortunately my database is Microsoft SQL Server 2005. So I decided to use CLR integration and create an UDF (User-Defined Function) in order to do so. In this post I wanted to show you how you can use CLR to create a function in .NET environment and execute it in SQL Server 2005-2008 environments.

The first thing you need is to create a SQL Server project which is available in Database node in new Project window:

Creating a SQLServer Project

Note that I used .NET Framework 2 because I wanted to create a CLR function in SQL Server 2005. If you’re using SQL Server 2008, there’s no problem to use .NET Framework 3.5 (SP1).

After you create a SQL Server project you can add any object that is common in SQL Server to your project by right click on the project and point to add; so you add a UDF, SP, etc:

Adding a new object 

As I mentioned before, we want to create an application which converts DateTime to another culture so I need to create a UDF. I select User-Defined Function and name it “PersianDateConvertor”. As you can see, Visual Studio will create a class named UserDefinedFunctions and add a method with the name you just specified:

using System;using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString PersianDateConvertor()
{
}
};

Now you need to convert a DateTime to a Persian DateTime like before using System.Globalization.PersianCalendar class. So our class will be something like this:

[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString PersianDateConvertor(DateTime dt)
{
PersianCalendar p = new PersianCalendar();
return String.Format("{0}/{1}/{2}",
p.GetYear(dt).ToString(),
p.GetMonth(dt).ToString(),
p.GetDayOfMonth(dt).ToString());
}

By the way, As you can see our method is a static method and it returns a SqlString. You can change the return type if you want.

You’ve created you CLR library! Now it’s time to use it in Microsoft SQL Server. By default, you cannot use CLR libraries in SQL Server unless you enable it. In order to enable CLR integration, you need to make use of sp_configure system stored-procedure:

EXECUTE sp_configure 'clr enabled' , '1'

Note: In order to enable CLR, you need administrative privileges.

In order to make use of an external assembly in SQL Server, you have to create an assembly like following:

CREATE ASSEMBLY DateConvertorFROM 'D:\MMR.CRL.DateConvertor.dll'WITH PERMISSION_SET = SAFE;GO

After you’ve created your assembly, you need to use it in an UDF, SP, etc:

CREATE FUNCTION dbo.GetPersianDate(@date datetime)
RETURNS nvarchar(max)AS EXTERNAL NAME DateConvertor.UserDefinedFunctions.PersianDateConvertor;
GO

You’re DONE! now you can use your UDF and the result will be something like this:

SELECT dbo.GetPersianDate(GetDate())

Result:
-------------------------------------------------------------
1387/12/2
(1 row(s) affected)

Quote of the day