# Tuesday, January 24, 2006

Tuesday, January 24, 2006 2:23:03 PM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 

In one of my current projects (yes, there are more at the moment and yes that is the reason why it's a bit quiet around here) i neede to write an encrypted file to the hard disc using DPAPI (Data Protection API). After I unsuccessfully searched the web and the msdn (the sample reads all bytes to the buffer at once - not so nice), I wrote the following sample app:

using System;

using System.IO;

using System.Security.Cryptography;

 

public class DataProtectionSample

{

    public static void Main()

    {

        using(MemoryStream ms = new MemoryStream())

        {

            StreamWriter swriter = new StreamWriter(ms);

            swriter.WriteLine("Text to encrypt to file.");

            swriter.Flush();

 

            Console.WriteLine("Protecting data ...");

            DataProtection.Protect("D:\\_temp\\DPAPI.dat", ms, false);

        }

        Console.WriteLine("Unprotecting data ...");

        using(MemoryStream ms2 =

            (MemoryStream)DataProtection.Unprotect("D:\\_temp\\DPAPI.dat", false))
        {

            StreamReader sreader = new StreamReader(ms2);

            Console.WriteLine("");

            Console.WriteLine("Decrypted string: " + sreader.ReadToEnd());

        }

        Console.ReadLine();

    }

}

 

public class DataProtection

{

    private static byte[] _additionalEntropy = { 9, 8, 7, 6, 5 };

    private static int _bufferLength = 1024;

 

    public static void Protect(string filename, Stream stream,

        bool machineLevel)

    {

        if (File.Exists(filename))

        {

            File.Delete(filename);

        }

        using (FileStream fs = new FileStream(filename, FileMode.CreateNew))

        {

            byte[] buffer = new byte[_bufferLength];

            long byteCount;

            stream.Position = 0;

            while ((byteCount =

               stream.Read(buffer, 0, buffer.Length)) > 0)

            {

                buffer = ProtectedData.Protect(buffer, _additionalEntropy,

                    ((machineLevel) ? DataProtectionScope.LocalMachine :

                    DataProtectionScope.CurrentUser));

                fs.Write(buffer, 0, buffer.Length);

                fs.Flush();

            }

        }

    }

 

    public static Stream Unprotect(string filename, bool machineLevel)

    {

        MemoryStream ms = new MemoryStream();

       

        using (FileStream fs = new FileStream(filename, FileMode.Open))

        {

            byte[] buffer = new byte[_bufferLength + 146];

            long byteCount;

 

            while ((byteCount =

               fs.Read(buffer, 0, buffer.Length)) > 0)

            {

                buffer = ProtectedData.Unprotect(buffer, _additionalEntropy,

                    ((machineLevel) ? DataProtectionScope.LocalMachine :

                    DataProtectionScope.CurrentUser));

                ms.Write(buffer, 0, buffer.Length);

                ms.Flush();

            }

        }

        ms.Position = 0;

        return ms;

    }

}

 

 

 

C# | Projects | Security
Tuesday, January 24, 2006 2:13:08 PM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Monday, January 23, 2006
Monday, January 23, 2006 4:57:23 PM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Tuesday, January 17, 2006

MDFExec
 Executing CREATE statements from within Visual Studio 2005

Snippy
 Editor for creating and modifying Visual Studio 2005 Code Snippets

WebServer Here Context Menu

Exclude From Sharepoint

NDoc Macro

Cropper
 Screenshot tool

Ruler

Folder Size Browser

Convert.NET
 C# 2 VB.NET Converter

ChalkTalk

Mistaya
 LDAP Explorer

WinMerge

 

 

Thomas list...

Event | Misc
Tuesday, January 17, 2006 11:24:57 AM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Thursday, January 12, 2006

Thursday, January 12, 2006 10:36:48 AM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  | 
# Sunday, January 08, 2006

If you try to run a CREATE statement in a query (right click on a database in the Server Explorer) you receive this message.

So i wrote a small utility which will do the job for me.

using System;

using System.IO;

using System.Data.SqlClient;

using System.Collections.Generic;

using System.Text;

using System.Windows.Forms;

 

namespace MdfExec

{

    class Program

    {

        static void Main(string[] args)

        {

            string _cnStr;

 

            if (args.Length == 2)

            {

                _cnStr =

                    "data source=.\\SQLEXPRESS;Integrated Security=SSPI;" +

                    "AttachDBFilename=" + args[1] + ";User Instance=true;";

            }

            else

            {

                OpenFileDialog fd = new OpenFileDialog();

 

                fd.AddExtension = true;

                fd.DefaultExt = ".mdf";

                fd.ShowDialog();

 

                _cnStr =

                    "data source=.\\SQLEXPRESS;Integrated Security=SSPI;" +

                    "AttachDBFilename=" + fd.FileName + ";User Instance=true;";

            }

 

            using (SqlConnection _cn = new SqlConnection(_cnStr))

            {

            using(SqlCommand _cmd = _cn.CreateCommand())

                   {

                    using (StreamReader fs = File.OpenText(args[0]))

                    {

                        _cmd.CommandText = fs.ReadToEnd();

                        _cmd.Connection.Open();

                        _cmd.ExecuteNonQuery();

                    }

                   }

            }

        }

    }

}

 

You can now right click on a *.sql file choose "open with ..." and select MdfExec.exe to execute the SQL statement.

Since there is no second parameter (but needed to define to which database to connect) a OpenFileDialog will prompt:

 

Happy coding

Sunday, January 08, 2006 3:31:55 PM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  | 

I'm quite busy with a project I'm on with Clemens (the last before he'll join the Indigo team at Microsoft) - just to explain why it got bit quiet around me :-)

Here is a modified version of the prop snippet that I want to share ( and remember :-P ).

<?xml version="1.0" encoding="utf-8" ?>

<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">

      <CodeSnippet Format="1.0.0">

            <Header>

                  <Title>prop</Title>

                  <Shortcut>prop</Shortcut>

                  <Description>Code snippet for property and

                  backing field</Description>

                  <Author>Microsoft Corporation</Author>

                  <SnippetTypes>

                        <SnippetType>Expansion</SnippetType>

                  </SnippetTypes>

            </Header>

            <Snippet>

                  <Declarations>

                        <Literal>

                             <ID>type</ID>

                              <ToolTip>Property type</ToolTip>

                             <Default>int</Default>

                        </Literal>

                        <Literal>

                             <ID>property</ID>

                             <ToolTip>Property name</ToolTip>

                             <Default>MyProperty</Default>

                        </Literal>

                        <Literal>

                             <ID>field</ID>

                             <ToolTip>The variable backing this

                             property</ToolTip>

                             <Default>myVar</Default>

                        </Literal>

                  </Declarations>

                  <Code Language="csharp"><![CDATA[#region $property$

     

      // This field holds the $property$

      private $type$ $field$;

 

      /// <summary>Gets/sets the $property$.</summary>

      /// <value>A <see cref="$type$">$type$</see>

      /// containing the $property$.</value>

      /// <remarks>This property gets/sets the $property$.</remarks>

      [System.ComponentModel.Description("Gets/sets the $property$.")]

      public $type$ $property$

      {

            get { return $field$;}

            set { $field$ = value;}

      }

      #endregion

      $end$]]>

                  </Code>

            </Snippet>

      </CodeSnippet>

</CodeSnippets>

Sunday, January 08, 2006 2:54:09 PM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Friday, December 23, 2005

Friday, December 23, 2005 11:19:04 AM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Sunday, December 18, 2005

I just finished writing some ASP.NET code where I also typed the following lines: 

 <ItemTemplate>
	<asp:Image ID="IsOnline" 
	runat="server" 
	ImageUrl='<%# GetImageUrl((MembershipUser)Container.DataItem) %>' 
	/>
</ItemTemplate>

...

protected string GetImageUrl(MembershipUser user)
{
	if (user.IsLockedOut)
	{
		return "~/images/BadUser.gif";
	}
	else if (!user.IsApproved)
	{
		return "~/images/GreyUser.gif";
	}
	else if (user.IsOnline)
	{
		return "~/images/OnlineUser.gif";
	}
	else
	{
		return "~/images/OfflineUser.gif";
	}
}

Before I shutdown my machine I fetchted Mail and Feeds when i ran accross this posting by ScottGu pointing to Fritz Onions Blog.

;-)

Sunday, December 18, 2005 12:59:36 AM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Thursday, December 15, 2005

No Comment :-P

Thursday, December 15, 2005 10:41:59 AM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  |