Perfil de MohammadMohammad's spaceFotosBlogListasMais Ferramentas Ajuda

Blog


17/10/2009

Talking about Visual Studio Beta 1 For Everyone

 

Quote

Visual Studio Beta 1 For Everyone

Even if you do not have an MSDN subscription, you are in luck. Visual Studio 2010, beta 1, is now available on Microsoft download. Here is a list of public links I was sent just recently. The downloads are all on Microsoft download. You will also want to join Microsoft connect for feedback.

VS 2010 Beta


· VS2010 Download page

· VS2010 Walkthroughs

· MSDN Library: What’s New in Visual Studio 2010

· VS2010 Connect

· Forums: VS, VB, C#, F#

· Samples: VS, VB, C#, F#

· Language specs: VB, C#, F#

· IronPython 2.6 CTP for .NET 4.0 Beta1

SKU/download page

Format

Size

Download page fwlinks

Visual Studio 2010 Shell (Integrated) Beta 1 Redistributable Package

exe

521 MB

http://go.microsoft.com/fwlink/?LinkId=147419

Visual Studio 2010 Shell (Isolated) Beta 1 Redistributable Package

exe

593 MB

http://go.microsoft.com/fwlink/?LinkId=147418

Visual Studio 2010 Professional Beta 1 – Web Installer

Bootstrapper

5 MB

http://go.microsoft.com/fwlink/?LinkId=147408

Visual Studio 2010 Professional Beta 1 – ISO

iso

1.2 GB

http://go.microsoft.com/fwlink/?LinkId=150591

Visual Studio Team System 2010 Team Suite Beta 1 – Web Installer

Bootstrapper

5 MB

http://go.microsoft.com/fwlink/?LinkId=147407

Visual Studio Team System 2010 Team Suite Beta 1 - ISO

iso

1.3 GB

http://go.microsoft.com/fwlink/?LinkId=150592

Visual Studio Team System 2010 Test Load Agent Beta 1 - DTEA

exe

185 MB

http://go.microsoft.com/fwlink/?LinkId=147420

Visual Studio Team System 2010 Test Load Agent Beta 1 - DTEC

exe

599 MB

same as above

Visual Studio Team System 2010 Team Foundation Server Beta 1

iso

2.3 GB

http://go.microsoft.com/fwlink/?LinkId=147412

Microsoft Visual Studio Lab Management 2010 Beta 1

no package

 

http://go.microsoft.com/fwlink/?LinkId=147413

Visual Studio Team System 2010 Lab Agent Beta 1

exe

427 MB

http://go.microsoft.com/fwlink/?LinkId=147414

Microsoft .NET Framework 4.0 Beta 1 – x86

exe

78 MB

http://go.microsoft.com/fwlink/?LinkID=147415

Microsoft .NET Framework 4.0 Beta 1 – IA64

exe

146 MB

same as above

Microsoft .NET Framework 4.0 Beta 1 – x64

exe

149 MB

same as above

Microsoft .NET Framework 4.0 Client Profile Beta 1 – x86

exe

35 MB

http://go.microsoft.com/fwlink/?LinkID=147417

Microsoft .NET Framework 4.0 Client Profile Beta 1 – x64

exe

73 MB

same as above

Visual Studio 2010 SDK Beta 1

exe

14 MB

http://go.microsoft.com/fwlink/?LinkId=147422

Microsoft Visual Studio 2010 Remote Debugger (Beta 1) – x86

exe

4 MB

http://go.microsoft.com/fwlink/?LinkId=147421

Microsoft Visual Studio 2010 Remote Debugger (Beta 1) – x64

exe

8 MB

same as above

· Channel 9 Video

· Product Survey

· Samples

· VB 2010 Resources page

· Visual C# 2010 Resources page

· F# Dev Center

This is great news for those of you who like to stay on the bleeding edge of technology. Thus far, I have enjoyed playing with the beta. It is still a bit slow, especially in a VPC environment, but far less so than the betas of Visual Studio 2008, so I am happy. I will be posting some tutorials soon, so you can learn how to use the new technology.

5/12/2008

Surprise

I really surprised by new changes in Widows Live. In my i existing things are:
  1. New Interface in all over Windows Live (Mostly in Phote Slide Show, Home, Profile, and SkyDrive)
  2. Integrated them in everywhere
  3. Adding "Move" and "Copy" features to SkyDrive


Hopefully, this is a beginig of being universal.

19/9/2008

Clear Your Traces

Note: From now, all the code samples, can be dependent on the previous posts.

Suppose that you want to clear all your traces in a computer, including:

  • Internet Cache
  • Internet URL History
  • Forms on IE
  • What you've typed in "Run" dialog box
  • Recent Programs on Start menu
  • Recent documents
  • Recycle Bin

The first one we want to clean is "Internet Cache". To do that, we must find its folder path using Environment.SpecialFolder.InternetCache. After that, by looping on each folder, we delete all of files. To make sure that no error will occurs (some files maybe in use), let's create a method, which deletes file in try..catch:

   1: private static void DeleteFileSystem(string fileSystem)
   2: {
   3:     try
   4:     {
   5:         Directory.Delete(fileSystem, true);
   6:     }
   7:     catch
   8:     {
   9:         try
  10:         {
  11:             File.Delete(fileSystem);
  12:         }
  13:         catch
  14:         {
  15:         }
  16:     }
  17: }
Now, let's use it:
   1: Directory.GetDirectories(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache) + @"\Content.IE5\").ForEach(dir => Directory.GetFiles(dir).ForEach(DeleteFileSystem));
Now, we can easily delete the remaining empty folders:
   1: Directory.GetDirectories(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache) + @"\Content.IE5\").ForEach(DeleteFileSystem);
At the next step, we clean the directory that contains our most recently used documents:
   1: Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.Recent)).ForEach(DeleteFileSystem);

Internet URL History, Forms; "Run" dialog box history and recent programs in Start menu, are kept in Windows Registry. As before, let's create a method to delete registry keys in try...catch:

   1: private static void DeleteRegKey(string regKey)
   2: {
   3:     try
   4:     {
   5:         Registry.CurrentUser.DeleteSubKeyTree(regKey);
   6:     }
   7:     catch
   8:     {
   9:     }
  10: }
Now, all we have to do is to create a list of the keys to delete:
   1: new string[]
   2: {
   3:       @"Software\Microsoft\Internet Explorer\IntelliForms" // Forms
   4:     , @"Software\Microsoft\Internet Explorer\TypedURLs" // Internet URL History
   5:     , @"Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU" //Run
   6:     , @"Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist\{75048700-EF1F-11D0-9888-006097DEACF9}\Count" //Recent Programs
   7:     , @"Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs"
   8: }.ForEach(DeleteRegKey);

It's almost done. Finally, we clean Recycle Bin. To do that, we must use an API: SHEmptyRecycleBin. So let's add an external method to our class, and decorate it with DllImport:

   1: [DllImport("Shell32.dll", CharSet = CharSet.Unicode)]
   2: static extern uint SHEmptyRecycleBin(IntPtr hwnd, string pszRootPath, RecycleFlags dwFlags);
Now, use it:
   1: try
   2: {
   3:     SHEmptyRecycleBin(IntPtr.Zero, null, RecycleFlags.SHERB_NOCONFIRMATION | RecycleFlags.SHERB_NOPROGRESSUI | RecycleFlags.SHERB_NOSOUND);
   4: }
   5: catch
   6: {
   7: }
It's over. What we have done is: (Without line numbers - as a friend suggested)
static class Program
{
    [DllImport("Shell32.dll", CharSet = CharSet.Unicode)]
    static extern uint SHEmptyRecycleBin(IntPtr hwnd, string pszRootPath, RecycleFlags dwFlags);
 
    static void Main(string[] args)
    {
        Directory.GetDirectories(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache) + @"\Content.IE5\").ForEach(dir => Directory.GetFiles(dir).ForEach(DeleteFileSystem));
        Directory.GetDirectories(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache) + @"\Content.IE5\").ForEach(DeleteFileSystem);
        Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.Recent)).ForEach(DeleteFileSystem);
        new string[]
        {
              @"Software\Microsoft\Internet Explorer\IntelliForms" // Forms
            , @"Software\Microsoft\Internet Explorer\TypedURLs" // Internet URL History
            , @"Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU" //Run
            , @"Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist\{75048700-EF1F-11D0-9888-006097DEACF9}\Count" //Recent Programs
            , @"Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32\LastVisitedMRU" //??
            , @"Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32\OpenSaveMRU" //?
            , @"Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs"
            , @"Software\Microsoft\Windows\CurrentVersion\Explorer\StreamMRU"
        }.ForEach(DeleteRegKey);
        try
        {
            uint result = SHEmptyRecycleBin(IntPtr.Zero, null, RecycleFlags.SHERB_NOCONFIRMATION | RecycleFlags.SHERB_NOPROGRESSUI | RecycleFlags.SHERB_NOSOUND);
        }
        catch
        {
        }
    }
 
    private static void DeleteFileSystem(string fileSystem)
    {
        try
        {
            Directory.Delete(fileSystem, true);
        }
        catch
        {
            try
            {
                File.Delete(fileSystem);
            }
            catch
            {
            }
        }
    }
    
    private static void DeleteRegKey(string regKey)
    {
        try
        {
            Registry.CurrentUser.DeleteSubKeyTree(regKey);
        }
        catch
        {
        }
    }
 
    private static void ForEach<TSource>(this IEnumerable<TSource> source, Action<TSource> actor)
    {
        foreach (var item in source)
            actor(item);
    }
}
11/9/2008

Some Extension Methods for "IEnumerable"s

System.Linq.Enumerable has a lot of extension methods to make it easy to use the classes which are inherited from System.Collections.IEnumerable and System.Collections.Generic.IEnumerable<T>. To extend this class in my projects, I created a class with some other extension methods, named"Mohammad.Library.CoreLib.Helpers.EnumerableHelper". Here, I show you a set of these methods:

   1: public static void ForEach<TSource>(this IEnumerable<TSource> source, Action<TSource> actor)
   2: {
   3:     foreach (TSource item in source)
   4:         actor(item);
   5: }
   6: public static void ForEach(this IEnumerable source, Action<Object> actor)
   7: {
   8:     foreach (Object item in source)
   9:         actor(item);
  10: }
  11: public static void ForEach(this IDictionary source, Action<Object, Object> actor)
  12: {
  13:     foreach (object Key in source.Keys)
  14:         actor(Key, source[Key]);
  15: }
  16: public static void ForEach<TKey, TValue>(this IDictionary<TKey, TValue> source, Action<TKey, TValue> actor)
  17: {
  18:     foreach (TKey Key in source.Keys)
  19:         actor(Key, source[Key]);
  20: }
   1: public static Collection<TSource> ToCollection<TSource>(this IEnumerable<TSource> source)
   2: {
   3:     Collection<TSource> result = new Collection<TSource>();
   4:     source.ForEach(result.Add);
   5:     return result;
   6: }
   7:  
   8: public static IEnumerable IfZero<TSource>(this IEnumerable source, IEnumerable defaultSource)
   9: {
  10:     return source.Cast<object>().Any() ? source : defaultSource;
  11: }
   1: public static T Fold<T, U>(this IEnumerable<U> items, Func<T, U, T> func, T acc)
   2: {
   3:     foreach (var item in items)
   4:         acc = func(acc, item);
   5:  
   6:     return acc;
   7: }
   8:  
   9: public static T FoldLeft<T, U>(this IList<U> list, Func<T, U, T> func, T acc)
  10: {
  11:     for (int index = 0; index < list.Count; index++)
  12:         acc = func(acc, list[index]);
  13:  
  14:     return acc;
  15: }
  16:  
  17: public static T FoldRight<T, U>(this IList<U> list, Func<T, U, T> func, T acc)
  18: {
  19:     for (int index = list.Count - 1; index >= 0; index--)
  20:         acc = func(acc, list[index]);
  21:  
  22:     return acc;
  23: }
  24:  
  25: public static void ForIndex<T>(this IEnumerable<T> items, Action<int, T> action)
  26: {
  27:     int index = 0;
  28:     foreach (var item in items)
  29:     {
  30:         action(index, item);
  31:         index++;
  32:     }
  33: }
To be continued...

One Really Big Query Expression!

   1: var pixelsQuery =
   2:     from y in Enumerable.Range(0, screenHeight)
   3:     let recenterY = -(y - (screenHeight / 2.0)) / (2.0 * screenHeight)
   4:     select from x in Enumerable.Range(0, screenWidth)
   5:            let recenterX = (x - (screenWidth / 2.0)) / (2.0 * screenWidth)
   6:            let point = Vector.Norm(Vector.Plus(scene.Camera.Forward,
   7:                        Vector.Plus(Vector.Times(recenterX, scene.Camera.Right),
   8:                        Vector.Times(recenterY, scene.Camera.Up))))
   9:            let ray = new Ray { Start = scene.Camera.Pos, Dir = point }
  10:            let computeTraceRay = (Func<Func<TraceRayArgs, Color>, Func<TraceRayArgs, Color>>)
  11:             (f => traceRayArgs =>
  12:              (from isect in
  13:                   from thing in traceRayArgs.Scene.Things
  14:                   select thing.Intersect(traceRayArgs.Ray)
  15:               where isect != null
  16:               orderby isect.Dist
  17:               let d = isect.Ray.Dir
  18:               let pos = Vector.Plus(Vector.Times(isect.Dist, isect.Ray.Dir), isect.Ray.Start)
  19:               let normal = isect.Thing.Normal(pos)
  20:               let reflectDir = Vector.Minus(d, Vector.Times(2 * Vector.Dot(normal, d), normal))
  21:               let naturalColors =                   from light in traceRayArgs.Scene.Lights
  22:                   let ldis = Vector.Minus(light.Pos, pos)
  23:                   let livec = Vector.Norm(ldis)
  24:                   let testRay = new Ray { Start = pos, Dir = livec }
  25:                   let testIsects = from inter in
  26:                                        from thing in traceRayArgs.Scene.Things
  27:                                        select thing.Intersect(testRay)
  28:                                    where inter != null
  29:                                    orderby inter.Dist
  30:                                    select inter
  31:                   let testIsect = testIsects.FirstOrDefault()
  32:                   let neatIsect = testIsect == null ? 0 : testIsect.Dist
  33:                   let isInShadow = !((neatIsect > Vector.Mag(ldis)) || (neatIsect == 0))
  34:                   where !isInShadow
  35:                   let illum = Vector.Dot(livec, normal)
  36:                   let lcolor = illum > 0 ? Color.Times(illum, light.Color) : Color.Make(0, 0, 0)
  37:                   let specular = Vector.Dot(livec, Vector.Norm(reflectDir))
  38:                   let scolor = specular > 0 
  39:                                ? Color.Times(Math.Pow(specular, isect.Thing.Surface.Roughness), light.Color) 
  40:                                : Color.Make(0, 0, 0)
  41:                   select Color.Plus(Color.Times(isect.Thing.Surface.Diffuse(pos), lcolor),
  42:                                     Color.Times(isect.Thing.Surface.Specular(pos), scolor))
  43:               let reflectPos = Vector.Plus(pos, Vector.Times(.001, reflectDir))
  44:               let reflectColor =                   traceRayArgs.Depth >= MaxDepth
  45:                   ? Color.Make(.5, .5, .5)
  46:                   : Color.Times(isect.Thing.Surface.Reflect(reflectPos), 
  47:                                 f(new TraceRayArgs(new Ray { Start = reflectPos, Dir = reflectDir }, 
  48:                                                    traceRayArgs.Scene,
  49:                                                    traceRayArgs.Depth + 1)))
  50:               select naturalColors.Aggregate(reflectColor, (color, natColor) => Color.Plus(color, natColor)))
  51:                                   .DefaultIfEmpty(Color.Background).First())
  52:            let traceRay = Y(computeTraceRay)
  53:            select new { X = x, Y = y, Color = traceRay(new TraceRayArgs(ray, scene, 0)) };
  54:  
  55: foreach (var row in pixelsQuery)
  56:     foreach (var pixel in row)
  57:         setPixel(pixel.X, pixel.Y, pixel.Color.ToDrawingColor());

 

Reference:

9/9/2008

IDE Enhancements: What's a Visualizer?

Hi,

As you surely know, while debugging your project, you can use "QuickWatch" to view the content of the variables in the current scope.

image

In a few cases, you can also use Visualizers (image) in a meaningful way, to view the variables, as what they exactly are. For instance, if you want to view the records of a DataTable, you should press the DataTable Visualizer button on the right corner of the name of DataTable in QuickWatch dialog box. Or if you want to see the content of a string variable you do same.

image 

Now what if I want to see my own data types, or the types which IDE's visualizer does not support? Let's suppose that you want to see an Image in debug time. You can write a custom visualizer. In order to do that, you must create a Class Library (.dll), create your visualizers, put your dll in a specific directory. For example, let's create an Image Visualizer step by step:

Open Visual Studio, go to File > New Project > Class Library.

IDE creates a class library and adds a class, by default. Rename the class to "Image".

Each visualizer must be inherited from Microsoft.VisualStudio.DebuggerVisualizers.DialogDebuggerVisualizer which is located in Microsoft.VisualStudio.DebuggerVisualizers.dll. So we must add it's reference to our project by right clicking on the project and choosing "Add Reference" item, in Solution Explorer. now inherit your "Image" class from "DialogDebuggerVisualizer". DialogDebuggerVisualizer has an abstract method: "Show". As you can guess, this method must be implemented in our class. So paste the following code into our "Image" class:

protected override void Show(IDialogVisualizerService windowService, IVisualizerObjectProvider objectProvider)
{
}
Before everything, we must find the object which users wants to be visualized. The second parameter is "objectProvider". This parameter contains what we want. To extract the object (here the image), we can use objectProvider.GetObject(). Now by casting the given object to image, we will have it.
System.Drawing.Image image = (System.Drawing.Image)objectProvider.GetObject();
We must now create a Form on the fly, add a PictureBox to the form and set its Image to the image we extracted.
   1: Form form = new Form()
   2: {
   3:     Text = string.Format("Mohammad Image Visualizer {0} * {1}", image.Width, image.Height),
   4:     ClientSize = new System.Drawing.Size(image.Width, image.Height),
   5:     FormBorderStyle = FormBorderStyle.FixedToolWindow,
   6:     ShowInTaskbar=false
   7: };
   8: PictureBox pictureBox = new PictureBox()
   9: {
  10:     Image = image,
  11:     Parent = form,
  12:     Dock = DockStyle.Fill,
  13: };
Finally, IDE should show our form as modal:
   1: windowService.ShowDialog(form);
Now let's inform IDE about the type our visualizer supports. The only limitation is: One visualizer per assembly. So we must decorate our visualizer assembly using DebuggerVisualizer and pass the type as a parameter. In the last step of coding steps, our visualizer must use code that runs in the debugger process (the debugger side) and code in the process being debugged (the debuggee side). to do this, we use the 6th overload of DebuggerVisualizer constructor which requires the type of the communicator. Here, in our example, we use VisualizerObjectSource:
   1: [assembly: System.Diagnostics.DebuggerVisualizer(typeof(Mohammad.Library.Visualizers.Image), typeof(VisualizerObjectSource), Target = typeof(System.Drawing.Image), Description = "Mohammad Image Visualizer")]
   2: namespace Mohammad.Library.Visualizers
   3: {
   4:     class Image : DialogDebuggerVisualizer
   5:     {
   6:         protected override void Show(IDialogVisualizerService windowService, IVisualizerObjectProvider objectProvider)
   7:         {
   8:             System.Drawing.Image image = (System.Drawing.Image)objectProvider.GetObject();
   9:             Form form = new Form()
  10:             {
  11:                 Text = string.Format("Mohammad Image Visualizer {0} * {1}", image.Width, image.Height),
  12:                 ClientSize = new System.Drawing.Size(image.Width, image.Height),
  13:                 FormBorderStyle = FormBorderStyle.FixedToolWindow,
  14:                 ShowInTaskbar=false
  15:             };
  16:             PictureBox pictureBox = new PictureBox()
  17:             {
  18:                 Image = image,
  19:                 Parent = form,
  20:                 Dock = DockStyle.Fill,
  21:             };
  22:             windowService.ShowDialog(form);
  23:         }
  24:     }
  25: }

It's almost done. Now we must install our visualizer by pasting its output file to a specific folder. To do that, MSDN says:

To install a visualizer
  1. Locate the DLL that contains the visualizer you have built.

  2. Copy the DLL to either of the following locations:

    Install path\Microsoft Visual Studio 8\Common7\Packages\Debugger\Visualizers

    —or—

    My Documents\Visual Studio 2005\Visualizers

  3. If you want to use the visualizer for remote debugging, copy the DLL to the same path on the remote computer.

  4. Restart the Visual Studio debugging session.

Ok, after installing, let's test the visualizer using a test windows application:

image

image

image

The visualizer is ready. Enjoy it!

Have a good time.

5/9/2008

Some Converting methods

   1: #region ToBin
   2: /// <summary>
   3: /// Returns a string representing the binary value of a number.
   4: /// </summary>
   5: /// <param name="num">Required. Any valid numeric expression or String expression.</param>
   6: /// <returns>Returns a string representing the binary value of a number.</returns>
   7: public static string ToBin(this int num)
   8: {
   9:     return ConvertBase(num.ToString(), 10, 2);
  10: }
  11: #endregion
  12:  
  13: #region ToHex
  14: /// <summary>
  15: /// Returns a string representing the hexadecimal value of a number.
  16: /// </summary>
  17: /// <param name="num">Required. Any valid numeric expression or String expression.</param>
  18: /// <returns>Returns a string representing the hexadecimal value of a number.</returns>
  19: public static string ToHex(this int num)
  20: {
  21:     return num.ToString("X");
  22: }
  23: #endregion
  24:  
  25: #region HexToDec
  26: /// <summary>
  27: /// Converts a hexadecimal number to decimal.
  28: /// </summary>
  29: /// <param name="hexNumber">Hexadecimal number</param>
  30: /// <returns></returns>
  31: public static int HexToDec(string hexNumber)
  32: {
  33:     return Convert.ToInt32(hexNumber, 16);
  34: }
  35: #endregion
  36:  
  37: #region ConvertBase
  38: /// <summary>
  39: /// Cast any number in any base to any number in any base.
  40: /// </summary>
  41: /// <param name="num"></param>
  42: /// <param name="sourceBase"></param>
  43: /// <param name="desctinationBase"></param>
  44: /// <returns></returns>
  45: public static string ConvertBase(string num, int sourceBase, int desctinationBase)
  46: {
  47:     return Convert.ToString(Convert.ToInt32(num, sourceBase), desctinationBase);
  48: }
  49: #endregion
  50:  
  51: #region BinToDec
  52: /// <summary>
  53: /// Converts a binary number to decimal.
  54: /// </summary>
  55: /// <param name="binaryNumber">Binary number</param>
  56: /// <returns></returns>
  57: public static int BinToDec(string binaryNumber)
  58: {
  59:     return ConvertBase(binaryNumber, 2, 10).ToIntNullable().Value;
  60: }
  61:  
  62: /// <summary>
  63: /// Converts a binary array to decimal.
  64: /// </summary>
  65: /// <param name="bits">Binary array</param>
  66: /// <returns></returns>
  67: public static int BinToDec(this BitArray bits)
  68: {
  69:     return BinToDec(bits.Merge());
  70: }
  71: #endregion
  72:  
  73: #region BinToHex
  74: /// <summary>
  75: /// Converts a binary string to hexadecimal
  76: /// </summary>
  77: /// <param name="binaryNumber">Binary number</param>
  78: /// <returns>Hexadecimalled string</returns>
  79: public static string BinToHex(string binaryNumber)
  80: {
  81:     return ConvertBase(binaryNumber, 2, 16);
  82: }
  83: #endregion
  84:  
  85: #region HexToBin
  86: /// <summary>
  87: /// Converts a hex string into binary values
  88: /// </summary>
  89: /// <param name="hex"></param>
  90: /// <returns></returns>
  91: public static string HexToBin(string hex)
  92: {
  93:     return ConvertBase(hex, 16, 2);
  94: }
  95: #endregion
<no description />

Some useful extension methods

Let's suppose that we retrieved some data from database using by a datareader or a table. As you know both datareader and datatble's gathered data are object. Therefore, we must convert them to the actual data type, if we want to use them. For instance if the fist columns is an ID, it can be long or int. It can be easy done by using convert class. but an easier way is to create a set of extension methods in order to do this conversion. some things like these:
   1: public static int ToInt(this object obj)
   2: {
   3:     return Convert.ToInt32(obj);
   4: }
   5:  
   6: public static int ToInt(this object obj, int defaultValue)
   7: {
   8:     if (obj == null)
   9:         return defaultValue;
  10:     return obj.ToString().ToIntNullable() ?? defaultValue;
  11: }
  12:  
  13: public static long ToLong(this object obj)
  14: {
  15:     return Convert.ToInt64(obj);
  16: }
  17:  
  18: public static int? ToIntNullable(this string str)
  19: {
  20:     int result;
  21:     return int.TryParse(str, out result) ? default(int?) : null;
  22: }
  23:  
  24: #region ToDouble
  25: /// <summary>
  26: /// Converts str to double
  27: /// </summary>
  28: /// <param name="str">object to convert</param>
  29: /// <param name="defaultValue">Will be used if not succed.</param>
  30: /// <returns>return converted number, if obj could be converted, otherwise defualtValue will be returned.</returns>
  31: public static double ToDouble(string str, double defaultValue)
  32: {
  33:     return ToDouble(str) ?? defaultValue;
  34: }
  35:  
  36: public static double? ToDouble(string str)
  37: {
  38:     double num;
  39:     return double.TryParse(str.ToString(), out num) ? num : default(double?);
  40: }
29/8/2008

My 1st post

In the name of God
Hi all,
 
This is my 1st post in my live space. I'm not so expert in blogging. So i will have a lot of problems to do that. But I think it doesn't matter. The bigger problem is my poor English language. I'm Iranian. So English is not my main language. Please excuse me, if you see any lingual problems.
In this space I want to start to share my experiences in C# development. And I'll try to explain one or more of my experiences in each post. I'll show you some exmaple codes and maybe some simple project according to what i am talking about,
Please DO NOT FORGET to let me know, if you have any ideas, or suggestions or anything else.
 
With thanks,
Mohammad