<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Dot Net Thoughts &#187; VB.Net</title>
	<atom:link href="http://www.dotnetthoughts.net/tag/vb-net/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dotnetthoughts.net</link>
	<description>thoughts about .Net, WPF, Sharepoint, Javascript and more.</description>
	<lastBuildDate>Wed, 28 Jul 2010 09:59:26 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Custom Places in FileDialog box</title>
		<link>http://www.dotnetthoughts.net/2010/06/21/custom-places-in-filedialog-box/</link>
		<comments>http://www.dotnetthoughts.net/2010/06/21/custom-places-in-filedialog-box/#comments</comments>
		<pubDate>Tue, 22 Jun 2010 04:06:18 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Windows 7]]></category>
		<category><![CDATA[Windows Forms]]></category>
		<category><![CDATA[C#.Net]]></category>
		<category><![CDATA[FileDialog]]></category>
		<category><![CDATA[VB.Net]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=925</guid>
		<description><![CDATA[If you ever tried to Open a File from Visual Studio, you may notice something like Projects Folder in the Open File Dialog. We can also implement the same functionality in our applications by using CustomPlaces collection property of FileDialog class. The OpenFileDialog and SaveFileDialog classes allow you to add folders to the CustomPlaces collection. [...]]]></description>
			<content:encoded><![CDATA[<p>If you ever tried to Open a File from Visual Studio, you may notice something like Projects Folder in the Open File Dialog.</p>
<div id="attachment_926" class="wp-caption aligncenter" style="width: 209px"><a href="http://www.dotnetthoughts.net/wp-content/uploads/2010/06/openfile_vs2010.png"><img class="size-full wp-image-926" title="Open File Dialog in Visual Studio" src="http://www.dotnetthoughts.net/wp-content/uploads/2010/06/openfile_vs2010.png" alt="Open File Dialog in Visual Studio" width="199" height="398" /></a><p class="wp-caption-text">Open File Dialog in Visual Studio</p></div>
<p>We can also implement the same functionality in our applications by using  CustomPlaces collection property of FileDialog class. The OpenFileDialog and SaveFileDialog classes allow you to add folders to the CustomPlaces collection.</p>
<pre class="brush: csharp;">
openFileDialog.CustomPlaces.Add(@&quot;C:\Users&quot;);
</pre>
<p>You can also specify GUID of Windows Vista known folder. Known Folder GUIDs are not case sensitive and are defined in the KnownFolders.h file in the Windows SDK. If the specified Known Folder is not present on the computer that is running the application, the Known Folder is not shown.</p>
<pre class="brush: csharp;">
openFileDialog.CustomPlaces.Add(@&quot;C:\Users&quot;);
//Desktop Folder
openFileDialog.CustomPlaces.Add(new Guid(&quot;B4BFCC3A-DB2C-424C-B029-7FE99A87C641&quot;));
//Downloads Folder
openFileDialog.CustomPlaces.Add(new Guid(&quot;374DE290-123F-4565-9164-39C4925E467B&quot;));
</pre>
<div id="attachment_929" class="wp-caption aligncenter" style="width: 417px"><a href="http://www.dotnetthoughts.net/wp-content/uploads/2010/06/openfile_custom.png"><img src="http://www.dotnetthoughts.net/wp-content/uploads/2010/06/openfile_custom.png" alt="Open File Dialog with Custom Places " title="Open File Dialog with Custom Places " width="407" height="479" class="size-full wp-image-929" /></a><p class="wp-caption-text">Open File Dialog with Custom Places </p></div>
<p>Note: This feature will not have any effect in Windows XP. Also you must set the AutoUpgradeEnabled to True(default) to enable this feature in Vista or Windows 7.</p>
<p>The following table lists few Windows Vista Known Folders and their associated Guid.  </p>
<ol>
<li>Contacts : 56784854-C6CB-462B-8169-88E350ACB882</li>
<li>ControlPanel : 82A74AEB-AEB4-465C-A014-D097EE346D63</li>
<li>Desktop : B4BFCC3A-DB2C-424C-B029-7FE99A87C641</li>
<li>Documents : FDD39AD0-238F-46AF-ADB4-6C85480369C7</li>
<li>Downloads : 374DE290-123F-4565-9164-39C4925E467B</li>
<li>Favorites : 1777F761-68AD-4D8A-87BD-30B759FA33DD</li>
<li>Fonts : FD228CB7-AE11-4AE3-864C-16F3910AB8FE</li>
<li>Music : 4BD8D571-6D19-48D3-BE97-422220080E43</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2010/06/21/custom-places-in-filedialog-box/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Application development using Gtk# in .Net</title>
		<link>http://www.dotnetthoughts.net/2009/10/17/application-development-using-gtk-in-net/</link>
		<comments>http://www.dotnetthoughts.net/2009/10/17/application-development-using-gtk-in-net/#comments</comments>
		<pubDate>Sun, 18 Oct 2009 02:53:04 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Windows Forms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C#.Net]]></category>
		<category><![CDATA[Gtk]]></category>
		<category><![CDATA[Mono]]></category>
		<category><![CDATA[VB.Net]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=532</guid>
		<description><![CDATA[When I started my software development career, I got introduced to some cool tools for GUI application development in Linux. I was using Glade and the library was Gtk. Then later I become a MS fan and started working on ASP, VB and .Net. Yesterday I got a chance to download Mono and Monodevelop. And [...]]]></description>
			<content:encoded><![CDATA[<p>When I started my software development career, I got introduced to some cool tools for GUI application development in Linux. I was using Glade and the library was Gtk. Then later I become a MS fan and started working on ASP, VB and .Net. Yesterday I got a chance to download Mono and Monodevelop. And the Gtk for Windows and .Net called Gtk#. I explored in Mono Develop(I was downloaded MonoDevelop-2.2 beta 2) a little, but it was crashed for me two time. <img src='http://www.dotnetthoughts.net/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' />  Then I started using Gtk# in VC# Express. And I created a simple Text File Viewer using C#, with Gtk# for UI. Most of the things in Gtk# is pretty different from .Net Windows Forms development. And I like the concept to in built support for predefined MenuItems, Icons etc. I think MS took the idea of commands in WPF from this.</p>
<p>I created a Windows Application Project and Added reference of the following libraries</p>
<p>atk-sharp.dll<br />
gdk-sharp.dll<br />
glade-sharp.dll<br />
glib-sharp.dll<br />
gtk-dotnet.dll<br />
gtk-sharp.dll</p>
<p>And I deleted the Form1. And modified the Program.cs; the Program.cs</p>
<pre class="brush: csharp;">
namespace HelloGtk
{
    using System;
    using Gtk;

    public class Program
    {
        private MainWindow mainWindow = null;

        public Program()
        {
            Application.Init();
            mainWindow = new MainWindow();
            Application.Run();
        }

        static void Main()
        {
            new Program();
            return;
        }
    }
}
</pre>
<p>And the added a class MainWindow.cs, and wrote the code</p>
<pre class="brush: csharp;">
namespace HelloGtk
{
    using Gtk;
    using System.IO;

    public class MainWindow : Gtk.Window
    {
        private string title = &quot;Text File Viewer&quot;;
        private VBox vbox;
        private MenuBar menubar;
        private Statusbar statusbar;
        private TextView textView;
        private ScrolledWindow scrolledWindow;
        private AccelGroup accelGroup;
        private Toolbar toolbar;
        public MainWindow()
            : base(&quot;Text File Viewer&quot;)
        {
            this.DefaultSize = new Gdk.Size(600, 500);
            this.DeleteEvent += new DeleteEventHandler(MainWindow_DeleteEvent);
            this.Build();
        }

        private void MainWindow_DeleteEvent(object o, DeleteEventArgs args)
        {
            Application.Quit();
            args.RetVal = true;
        }

        private void Build()
        {
            this.Title = this.title;
            this.vbox = new VBox(false, 0);
            this.CreateMenubar();
            this.vbox.PackStart(this.menubar, false, true, 0);
            this.toolbar = new Toolbar();
            this.CreateToolbar();
            this.vbox.PackStart(this.toolbar, false, true, 0);
            this.textView = new TextView();
            this.textView.Editable = false;
            this.textView.WrapMode = WrapMode.Word;
            this.scrolledWindow = new ScrolledWindow();
            this.scrolledWindow.SetPolicy(PolicyType.Automatic, PolicyType.Automatic);
            this.scrolledWindow.Add(this.textView);
            this.vbox.PackStart(this.scrolledWindow, true, true, 0);
            this.statusbar = new Statusbar();
            this.vbox.PackStart(this.statusbar, false, true, 0);
            this.Add(this.vbox);
            this.ShowAll();
        }
        private void CreateToolbar()
        {
            ToolButton OpenToolBarBtn = new ToolButton(&quot;gtk-open&quot;);
            OpenToolBarBtn.Clicked += this.openMenu_Activated;
            SeparatorToolItem Sep1 = new SeparatorToolItem();
            ToolButton CopyToolBarBtn = new ToolButton(&quot;gtk-copy&quot;);
            CopyToolBarBtn.Clicked += this.copyMenu_Activated;
            SeparatorToolItem Sep2 = new SeparatorToolItem();
            ToolButton AboutToolBarBtn = new ToolButton(&quot;gtk-about&quot;);
            AboutToolBarBtn.Clicked += this.aboutMenu_Activated;

            this.toolbar.Add(OpenToolBarBtn);
            this.toolbar.Add(Sep1);
            this.toolbar.Add(CopyToolBarBtn);
            this.toolbar.Add(Sep2);
            this.toolbar.Add(AboutToolBarBtn);
        }

        private void CreateMenubar()
        {
            this.accelGroup = new AccelGroup();
            this.menubar = new MenuBar();
            MenuItem fileMenu = new MenuItem(&quot;_File&quot;);
            MenuItem editMenu = new MenuItem(&quot;_Edit&quot;);
            MenuItem helpMenu = new MenuItem(&quot;_Help&quot;);
            helpMenu.RightJustified = true;

            Menu fileSubMenu = new Menu();
            TearoffMenuItem fileMenuTearOff = new TearoffMenuItem();
            ImageMenuItem openMenu = new ImageMenuItem(&quot;gtk-open&quot;, accelGroup);
            openMenu.Activated += new System.EventHandler(openMenu_Activated);
            SeparatorMenuItem fileMenuSep = new SeparatorMenuItem();
            ImageMenuItem exitMenu = new ImageMenuItem(&quot;gtk-quit&quot;, accelGroup);
            exitMenu.Activated += new System.EventHandler(exitMenu_Activated);
            fileSubMenu.Add(fileMenuTearOff);
            fileSubMenu.Add(openMenu);
            fileSubMenu.Add(fileMenuSep);
            fileSubMenu.Add(exitMenu);
            fileMenu.Submenu = fileSubMenu;

            Menu editSubMenu = new Menu();
            ImageMenuItem copyMenu = new ImageMenuItem(&quot;gtk-copy&quot;, accelGroup);
            copyMenu.Activated += new System.EventHandler(copyMenu_Activated);
            TearoffMenuItem editMenuTearOff = new TearoffMenuItem();
            editSubMenu.Add(editMenuTearOff);
            editSubMenu.Add(copyMenu);
            editMenu.Submenu = editSubMenu;

            Menu helpSubMenu = new Menu();
            ImageMenuItem aboutMenu = new ImageMenuItem(&quot;gtk-about&quot;, accelGroup);
            TearoffMenuItem helpMenuTearOff = new TearoffMenuItem();
            helpSubMenu.Add(helpMenuTearOff);
            helpSubMenu.Add(aboutMenu);
            aboutMenu.Activated += new System.EventHandler(aboutMenu_Activated);
            helpMenu.Submenu = helpSubMenu;

            this.menubar.Add(fileMenu);
            this.menubar.Add(editMenu);
            this.menubar.Add(helpMenu);
        }

        void aboutMenu_Activated(object sender, System.EventArgs e)
        {
            using (Dialog dialog = new MessageDialog(this,
                                  DialogFlags.Modal | DialogFlags.DestroyWithParent,
                                  MessageType.Info,
                                  ButtonsType.Ok,
                                  &quot;Text File Viewer - A simple text file viewer using gtk#\nDeveloped by Anuraj\nPowered by dotnetthoughts.net\n\nUnder GNU GPL v2.&quot;))
            {
                dialog.Title = &quot;About&quot;;
                dialog.Run();
                dialog.Hide();
            }
        }

        private void copyMenu_Activated(object sender, System.EventArgs e)
        {
            Clipboard clipboad = this.textView.GetClipboard(Gdk.Selection.Clipboard);
            this.textView.Buffer.CopyClipboard(clipboad);
        }

        void exitMenu_Activated(object sender, System.EventArgs e)
        {
            Application.Quit();
        }
        FileChooserDialog dlg;
        private void openMenu_Activated(object sender, System.EventArgs e)
        {
            dlg =
                new FileChooserDialog(&quot;Select Text File&quot;, this, FileChooserAction.Open, &quot;&quot;);
            dlg.AddButton(&quot;Open File&quot;, ResponseType.Ok);
            dlg.AddButton(&quot;Cancel&quot;, ResponseType.Cancel);

            FileFilter filter = new FileFilter();
            filter.AddPattern(&quot;*.txt&quot;);
            filter.AddPattern(&quot;*.*&quot;);
            dlg.Filter = filter;

            dlg.TypeHint = Gdk.WindowTypeHint.Dialog;
            dlg.SelectMultiple = false;
            dlg.WindowPosition = WindowPosition.Center;
            dlg.Parent = this;
            dlg.Modal = true;
            dlg.KeepAbove = true;
            dlg.DestroyWithParent = true;
            dlg.State = StateType.Normal;

            dlg.Response += new ResponseHandler(dlg_Response);
            dlg.DeleteEvent += new DeleteEventHandler(dlg_DeleteEvent);

            dlg.Run();
            dlg.Destroy();

        }

        private void dlg_DeleteEvent(object o, DeleteEventArgs args)
        {
            dlg.Destroy();
        }

        private void dlg_Response(object o, ResponseArgs args)
        {
            if (args.ResponseId == ResponseType.Ok)
            {
                this.Title = string.Format(&quot;{0} - {1}&quot;, this.title, System.IO.Path.GetFileName(dlg.Filename));
                using (StreamReader reader = new StreamReader(dlg.Filename, true))
                {
                    this.textView.Buffer.Text = reader.ReadToEnd();
                }
            }
            dlg.Destroy();
        }
    }
}
</pre>
<p>And run the application. Here is the screenshot, Text File Viewer running on my machine.</p>
<div id="attachment_541" class="wp-caption alignnone" style="width: 510px"><img src="http://www.dotnetthoughts.net/wp-content/uploads/2009/10/Text_File_Viewer_Using_GTK.jpg" alt="Text File Viewer using GTK#" title="Text File Viewer using GTK#" width="500" height="326" class="size-full wp-image-541" /><p class="wp-caption-text">Text File Viewer using GTK#</p></div>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2009/10/17/application-development-using-gtk-in-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Color Picker Dropdown using C#</title>
		<link>http://www.dotnetthoughts.net/2009/10/15/color-picker-dropdown-using-c/</link>
		<comments>http://www.dotnetthoughts.net/2009/10/15/color-picker-dropdown-using-c/#comments</comments>
		<pubDate>Fri, 16 Oct 2009 04:05:52 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C#.Net]]></category>
		<category><![CDATA[Color Picker]]></category>
		<category><![CDATA[Drawing]]></category>
		<category><![CDATA[Drawmode]]></category>
		<category><![CDATA[Dropdown]]></category>
		<category><![CDATA[VB.Net]]></category>
		<category><![CDATA[Windows Forms]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=527</guid>
		<description><![CDATA[While playing around one of hobby project, I found there is a nice color picker dropdown available in WordPad, for setting the font color. I was using Windows Color Dialog. So I thought of implementing a WordPad like color picker. And I think I almost readed my goal. I need to try this in the [...]]]></description>
			<content:encoded><![CDATA[<p>While playing around one of hobby project, I found there is a nice color picker dropdown available in WordPad, for setting the font color. I was using Windows </p>
<p>Color Dialog. So I thought of implementing a WordPad like color picker. And I think I almost readed my goal. I need to try this in the Toolstrip dropdown too.</p>
<pre class="brush: csharp;">
//On the Form load I am loading the colors to the Dropdown.
//You can also bind the p to the Dropdown.
Type t = typeof(Color);
PropertyInfo[] p = t.GetProperties();
foreach (PropertyInfo item in p)
{
    if (item.PropertyType.FullName.Equals(&quot;System.Drawing.Color&quot;, StringComparison.CurrentCultureIgnoreCase))
    {
        this.comboBox1.Items.Add(item.Name);
    }
}
</pre>
<p>And I set the Dropdown&#8217;s DrawMode property to &#8220;OwnerDrawFixed&#8221;. And in the DrawItem event of the Dropdown I wrote the code.</p>
<pre class="brush: csharp;">
if (e.Index != -1)
{
    e.DrawBackground();
    e.Graphics.FillRectangle(GetCurrentBrush(comboBox1.Items[e.Index].ToString()), e.Bounds);
    Font f = comboBox1.Font;
    e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), f, Brushes.Black, e.Bounds, StringFormat.GenericDefault);
    e.DrawFocusRectangle();
}
</pre>
<p>And the GetCurrentBrush() function returns the Brush for painting the rectangle. You can write the code in the DrawItem event too, but initialy I thought about setting the font color using the same color. But later that idea changed.</p>
<pre class="brush: csharp;">
private Brush GetCurrentBrush(string colorName)
{
    return new SolidBrush(Color.FromName(colorName));
}
</pre>
<p>One issue I found in this code is, for black color, I can&#8217;t see the color name. And here is the screenshot of Color Picker Dropdown running on my machine.</p>
<div id="attachment_529" class="wp-caption alignnone" style="width: 285px"><img src="http://www.dotnetthoughts.net/wp-content/uploads/2009/10/color_dropdown.PNG" alt="Color Picker Dropdown screenshot" title="Color Picker Dropdown screenshot" width="275" height="385" class="size-full wp-image-529" /><p class="wp-caption-text">Color Picker Dropdown screenshot</p></div>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2009/10/15/color-picker-dropdown-using-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to check remote file exists using C#</title>
		<link>http://www.dotnetthoughts.net/2009/10/14/how-to-check-remote-file-exists-using-c/</link>
		<comments>http://www.dotnetthoughts.net/2009/10/14/how-to-check-remote-file-exists-using-c/#comments</comments>
		<pubDate>Thu, 15 Oct 2009 06:49:25 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C#.Net]]></category>
		<category><![CDATA[File Existance]]></category>
		<category><![CDATA[Remote File exists]]></category>
		<category><![CDATA[VB.Net]]></category>
		<category><![CDATA[Windows Forms]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=493</guid>
		<description><![CDATA[Sometime you require to display remote images in the Web Pages, like Ads, Banner etc, it may be from different domain or a different application. This code will help you to check the existence of a Remote file using C#. using System.Net; /// /// Checks the file exists or not. /// /// The URL of [...]]]></description>
			<content:encoded><![CDATA[<p>Sometime you require to display remote images in the Web Pages, like Ads, Banner etc, it may be from different domain or a different application. This code will help you to check the existence of a Remote file using C#.</p>
<pre class="brush: csharp;">
using System.Net;

///
/// Checks the file exists or not.
///
/// The URL of the remote file.
/// True : If the file exits, False if file not exists
private bool RemoteFileExists(string url)
{
    try
    {
        //Creating the HttpWebRequest
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        //Setting the Request method HEAD, you can also use GET too.
        request.Method = &quot;HEAD&quot;;
        //Getting the Web Response.
        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
        //Returns TURE if the Status code == 200
        return (response.StatusCode == HttpStatusCode.OK);
    }
    catch
    {
        //Any exception will returns false.
        return false;
    }
}
</pre>
<p>You can also use WebClient class for the same purpose. Like this.</p>
<pre class="brush: csharp;">
using System.Net;

///
/// Checks the file exists or not.
///
/// The URL of the remote file.
/// True : If the file exits, False if file not exists
private bool RemoteFileExists(string url)
{
    bool result = false;
    using (WebClient client = new WebClient())
    {
        try
        {
            Stream stream = client.OpenRead(url);
            if (stream != null)
            {
                result = true;
            }
            else
            {
                result = false;
            }
        }
        catch
        {
            //Any exception will returns false.
            result = false;
        }
    }
    return result;
}
</pre>
<p>Internally WebClient is using the HttpWebRequest and HttpWebResponse classes, so it is good to use the first method.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2009/10/14/how-to-check-remote-file-exists-using-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Adding and Reading files from SQL Server 2008 Filestream</title>
		<link>http://www.dotnetthoughts.net/2009/09/22/adding-and-reading-files-from-sql-server-2008-filestream/</link>
		<comments>http://www.dotnetthoughts.net/2009/09/22/adding-and-reading-files-from-sql-server-2008-filestream/#comments</comments>
		<pubDate>Tue, 22 Sep 2009 12:38:46 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Windows Forms]]></category>
		<category><![CDATA[SQL Server 2008]]></category>
		<category><![CDATA[VB.Net]]></category>

		<guid isPermaLink="false">http://anuraj.wordpress.com/?p=393</guid>
		<description><![CDATA[Few days back I wrote a Post about FileStream feature in SQL 2008.(Filestream in SQL Server 2008). In this post I am trying to write the how to manage or use the FileStream feature from .Net managed code. For adding a File to FileStream enabled table, we are using a new Data Type, SqlFileStream, which [...]]]></description>
			<content:encoded><![CDATA[<p>Few days back I wrote a Post about FileStream feature in SQL 2008.(<a href="http://www.dotnetthoughts.net/2009/07/06/filestream-in-sql-server-2008/">Filestream in SQL Server 2008</a>). In this post I am trying to write the how to manage or use the FileStream feature from .Net managed code.</p>
<p>For adding a File to FileStream enabled table, we are using a new Data Type, SqlFileStream, which comes with .Net 3.5.</p>
<p>I am using the Table structure as in the Previous post, as the example, that Table contains 3 columns, FileID(PK), FileName and FileContents.<br />
For inserting a File you need to begin a transaction, insert an row in to the Table, without the contents of the File, for reading the Transaction context. Then using FileStream, write the contents of the File to the Row. After writting the stream, need to commit the transaction to update the file to the Database. I am writing the code in VB.Net.</p>
<p>Code for saving the File to the Database</p>
<pre class="brush: vb;">
Private Sub AddFile(ByVal fileName As String)
	Dim _Transaction As SqlTransaction
	Dim _Command As SqlCommand
	Dim _DataReader As SqlDataReader
	Dim _Connection As SqlConnection
	Dim _FileId As String
	Dim _FilePath As String
	Dim _FileNameParameter As SqlParameter
	Dim _FileIdParameter As SqlParameter
	Dim _FilePathParameter As SqlParameter

	Dim _SQLFileStream As SqlTypes.SqlFileStream
	Dim _Context As Byte()

	Try
		_Connection = New SqlConnection(&quot;Server=.\SQL2008;Integrated Authentication=SSPI;Database=FileSystemExample;&quot;)
		_Connection.Open()
		_Transaction = _Connection.BeginTransaction()
		_Command = New SqlCommand(&quot;xsp_InsertFile&quot;, _Connection, _Transaction)
		_Command.CommandType = CommandType.StoredProcedure
		_Command.Parameters.AddRange(New Object() {_FileIdParameter, _FileNameParameter, _FilePath})
		_FileId = Guid.NewGuid().ToString

		_FileIdParameter = New SqlParameter(&quot;@FileId&quot;, SqlDbType.UniqueIdentifier)
		_FileIdParameter.Value = _FileId

		_FileNameParameter = New SqlParameter(&quot;@FileName&quot;, SqlDbType.VarChar)
		_FileNameParameter.Value = fileName

		_FilePathParameter = New SqlParameter(&quot;@FilePath&quot;, SqlDbType.VarChar)
		_FilePathParameter.Direction = ParameterDirection.Output

		_DataReader = _Command.ExecuteReader(CommandBehavior.SingleRow)
		If _DataReader.HasRows Then
			_FilePath = _DataReader(&quot;FilePath&quot;).ToString
		End If
		If Not _DataReader.IsClosed Then
			_DataReader.Close()
		End If

		_Command = New SqlCommand(&quot;SELECT GET_FILESTREAM_TRANSACTION_CONTEXT() FROM SQLFileSystem&quot;, _Connection, _Transaction)
		_Context = _Command.ExecuteScalar()

		_SQLFileStream = New SqlFileStream(_FilePath, _Context, FileAccess.Write)
		_SQLFileStream.Write(_Context, 0, _Context.Length)
		_SQLFileStream.Close()

		_Transaction.Commit()
	Catch ex As Exception
		If _Transaction IsNot Nothing Then
			_Transaction.Rollback()
		End If
	Finally
		If _Connection IsNot Nothing Then
			_Connection.Close()
		End If
	End Try
End Sub
</pre>
<p>Code for reading the File from the Database</p>
<pre class="brush: vb;">
Private Function ReadFile(ByVal fileId As String) As Byte()
	Dim _Transaction As SqlTransaction
	Dim _Command As SqlCommand
	Dim _DataReader As SqlDataReader
	Dim _Connection As SqlConnection
	Dim _FilePath As String
	Dim _FileIdParameter As SqlParameter

	Dim _SQLFileStream As SqlTypes.SqlFileStream
	Dim _Context As Byte()

	Try
		_Connection = New SqlConnection(&quot;Server=.\SQL2008;Integrated Authentication=SSPI;Database=FileSystemExample;&quot;)
		_Connection.Open()
		_Transaction = _Connection.BeginTransaction()
		_Command = New SqlCommand(&quot;SELECT FileStreamData.PathName() AS [FilePath],GET_FILESTREAM_TRANSACTION_CONTEXT() AS [Context] FROM SQLFileSystem WHERE FileId=@FileId&quot;, _Connection, _Transaction)
		_Command.CommandType = CommandType.StoredProcedure

		_FileIdParameter = New SqlParameter(&quot;@FileId&quot;, SqlDbType.UniqueIdentifier)
		_FileIdParameter.Value = fileId
		_Command.Parameters.Add(_FileIdParameter)

		_DataReader = _Command.ExecuteReader(CommandBehavior.SingleRow)
		If _DataReader.HasRows Then
			_FilePath = _DataReader(&quot;FilePath&quot;).ToString()
			_Context = TryCast(_DataReader(&quot;Context&quot;), Byte())
		End If

		_SQLFileStream = New SqlFileStream(_FilePath, _Context, FileAccess.Read)
		_SQLFileStream.Read(_Context, 0, _Context.Length)
		_SQLFileStream.Close()

		_Transaction.Commit()
	Catch ex As Exception
		If _Transaction IsNot Nothing Then
			_Transaction.Rollback()
		End If
	Finally
		If _Connection IsNot Nothing Then
			_Connection.Close()
		End If
	End Try
	Return _Context
End Function
</pre>
<p>Stored Procedure</p>
<pre class="brush: sql;">
CREATE PROCEDURE xsp_InsertFile
(
@FileName VARCHAR(255),
@FileId UNIQUEIDENTIFIER,
@FilePath VARCHAR(MAX) OUTPUT)
AS
BEGIN
SET NOCOUNT OFF
INSERT INTO SQLFileSystem (FileId, FileName) VALUES(@FileId, @FileName)
SELECT @FilePath = SystemFile.PathName() from SQLFileSystem where FileId = @FileId
END
</pre>
<p>Note: I didn&#8217;t tested the code. Please let me know if you found any issues in the implementation.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2009/09/22/adding-and-reading-files-from-sql-server-2008-filestream/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using background worker in C#</title>
		<link>http://www.dotnetthoughts.net/2009/08/19/using-background-worker-in-c/</link>
		<comments>http://www.dotnetthoughts.net/2009/08/19/using-background-worker-in-c/#comments</comments>
		<pubDate>Wed, 19 Aug 2009 07:57:47 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Windows Forms]]></category>
		<category><![CDATA[Background Worker]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Threading]]></category>
		<category><![CDATA[UI]]></category>
		<category><![CDATA[VB.Net]]></category>

		<guid isPermaLink="false">http://anuraj.wordpress.com/?p=366</guid>
		<description><![CDATA[Background worker is a component introduced by Microsoft in .Net 2.0 which will help developers to do background operations without the knowledge of threading and deadlocks. In the current application I am working we used to copy some files from hard drive to specified USB drive, based on some criteria. For the IO operation we [...]]]></description>
			<content:encoded><![CDATA[<p>Background worker is a component introduced by Microsoft in .Net 2.0 which will help developers to do background operations without the knowledge of threading and deadlocks. In the current application I am working we used to copy some files from hard drive to specified USB drive, based on some criteria. For the IO operation we used some background worker, but for the progress reporting we used a very easy method, we just put a progress bar and set the Style property to Marquee. It will display a block moving always from right to left. We were aware of the ProgressChanged event, but when I tried it, it throws some cross thread exception. After working around the documentation in MSDN I found the solution for this.</p>
<p>Example Code</p>
<p>Make sure the background worker WorkerReportProgress Property set to</p>
<pre class="brush: csharp;">

//BackGround Worker DoWork Event.
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
//Do the long running job here
int index = 0;
while(true)
{
	if(index &gt;= 100)
	{
		break;
	}
	index ++;
	Thread.Sleep(100);
	//The second parameter is required only
	//if you want to display some output
	//Here we are updating the Progress.
	this.bgWorker.ReportProgress(index, index);
}
}

//BackGround Worker Progress Changed Event.
private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
	this.pbStatus.Value = e.ProgressPercentage;
	this.lstValues.Items.Add(e.UserState);
}

//BackGround Worker Work completed Event.
private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
	MessageBox.Show(&quot;Successfully completed&quot;);
}
</pre>
<p>In this code, I am counting from 0 to 100, also updating a Progress bar and Listbox in Userinterface with the values.</p>
<p>Links :<br />
<a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.progresschanged.aspx" target="_blank">Back Ground worker in MSDN</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2009/08/19/using-background-worker-in-c/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
