Impersonate - accessing a network folder from .NET

Thursday, 8 May 2008 09:22 by Myself

This is and neat class I've put together that allows you to specify username and password (and optionally a domain) and act under that identity. Primarily to access a shared folder, but you could easily find more areas of use.

   1: using (new Impersonator(true, "username", "password", "123.123.123.123"))
   2: {
   3:     // The new idenity is only active inside this using clause
   4:     if (!Directory.Exists(@"\\123.123.123.123\Foo\bar"))
   5:         Directory.CreateDirectory(@"\\123.123.123.123\Foo\bar");
   6: } 
   7:  

It makes use of the Win32 API "LogonUser".

Download the source code and give it a try!

Impersonator.7z (3.60 kb)

Tags:   ,
Categories:   Development
Actions:   E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

FTP Upload from SQL Server 2005

Friday, 28 March 2008 13:24 by Myself

The credit of this script goes to Nigel Rivett. I have merely added what I felt was missing and adjusted it to SQL 2005.

Change list:

  • Generates a random temporary script (allows for many concurrent executions)
  • Deletes the temporary script afterwards (we don't want to reveal the FTP credentials too easy)
  • The use of an in-memory-table instead of a temp table.
  • Friendlier output and return code validation.
  • I prefer to have these kind of stored procedures under my Tools schema.

Nothing fancy but rather fundamental.

   1: IF NOT EXISTS(SELECT SCHEMA_ID('Tools'))
   2:     EXEC('CREATE SCHEMA Tools') -- CREATE SCHEMA needs to be the first statement of a batch
   3:     
   4: IF EXISTS (select * from sysobjects where id = object_id(N'[Tools].[PutFile]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
   5:     DROP PROCEDURE [Tools].[PutFile]
   6: GO
   7:  
   8: CREATE PROCEDURE [Tools].[PutFile]
   9: (
  10:     @FTPServer      nvarchar(128) ,
  11:     @FTPUser        nvarchar(128) ,
  12:     @FTPPWD         nvarchar(128) ,
  13:     @FTPPath        nvarchar(128) ,
  14:     @FTPFileName    nvarchar(128) ,
  15:  
  16:     @SourcePath     nvarchar(128) ,
  17:     @SourceFile     nvarchar(128) ,
  18:  
  19:     @WorkDir        nvarchar(128)
  20: )
  21: AS
  22:     SET NOCOUNT ON;
  23: /*
  24: exec [Tools].[PutFile]    
  25:         @FTPServer = 'myftp.com' ,
  26:         @FTPUser = 'usr' ,
  27:         @FTPPWD = 'pwd' ,
  28:         @FTPPath = '/Upload_Here/' ,
  29:         @FTPFileName = 'from_sql_2005.txt' ,
  30:         @SourcePath = 'c:\temp\' ,
  31:         @SourceFile = 'mytable.txt' ,
  32:         
  33:         @workdir = 'c:\temp\'
  34: */
  35:  
  36:     declare    @cmd varchar(1000)
  37:     declare @workfilename varchar(128)
  38:     DECLARE @returncode int
  39:     
  40:     /* We insert a 4 character random string to the temporary ftp script - Otherwise two concurrent calls would interfere w/ eachother */
  41:     select @workfilename = 'ftpcmd_{rand}.txt' 
  42:     SELECT @workfilename = REPLACE(@workfilename,'{rand}', LEFT(CAST(NEWID() AS nvarchar(max)),4))
  43:     
  44:     -- deal with special characters for echo commands
  45:     select @FTPServer = replace(replace(replace(@FTPServer, '|', '^|'),'<','^<'),'>','^>')
  46:     select @FTPUser = replace(replace(replace(@FTPUser, '|', '^|'),'<','^<'),'>','^>')
  47:     select @FTPPWD = replace(replace(replace(@FTPPWD, '|', '^|'),'<','^<'),'>','^>')
  48:     select @FTPPath = replace(replace(replace(@FTPPath, '|', '^|'),'<','^<'),'>','^>')
  49:     
  50:     select    @cmd = 'echo '                    + 'open ' + @FTPServer
  51:             + ' > ' + @workdir + @workfilename
  52:     exec master..xp_cmdshell @cmd, NO_OUTPUT
  53:     select    @cmd = 'echo '                    + @FTPUser
  54:             + '>> ' + @workdir + @workfilename
  55:     exec master..xp_cmdshell @cmd, NO_OUTPUT
  56:     select    @cmd = 'echo '                    + @FTPPWD
  57:             + '>> ' + @workdir + @workfilename
  58:     exec master..xp_cmdshell @cmd, NO_OUTPUT
  59:     select    @cmd = 'echo '                    + 'put ' + @SourcePath + @SourceFile + ' ' + @FTPPath + @FTPFileName
  60:             + ' >> ' + @workdir + @workfilename
  61:     exec master..xp_cmdshell @cmd, NO_OUTPUT
  62:     select    @cmd = 'echo '                    + 'quit'
  63:             + ' >> ' + @workdir + @workfilename
  64:     exec master..xp_cmdshell @cmd, NO_OUTPUT
  65:     
  66:     select @cmd = 'ftp -s:' + @workdir + @workfilename
  67:     
  68:     DECLARE @result TABLE (id int identity(1,1), s varchar(1000))
  69:     insert @result
  70:     exec @returncode = master..xp_cmdshell @cmd
  71:     
  72:     IF(@returncode = 0)
  73:         INSERT @result SELECT 'FTP command successfully executed'
  74:     
  75:     select [output] = s from @result WHERE s IS NOT NULL 
  76:         AND s NOT LIKE 'quit'
  77:     
  78:     /* Remove the ftp cmd afterwards*/
  79:     select @cmd = 'delete ' + @workdir + @workfilename
  80:     exec master..xp_cmdshell @cmd, NO_OUTPUT
  81: go
  82:  

 

This was my first post using Live Writer. I've installed some useful plugins such as

And on the blogengine.net side

Tags:   ,
Categories:   Development | Sql Server 2005
Actions:   E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Painless backup on SQL 2005

Wednesday, 26 March 2008 10:27 by Myself

I found this great Backup and Maintenance script for SQL 2005 on Ola Hallengrens blog

I am no fan of Maintenance Plans in SQL Server. Even though maintenance isn't my job - I write databases - I couldn't help to be annoyed by all the backup jobs causing chaos in the Job Agent list. Every database had it's M.Plan and corresponding job. So I decided to find a better solution. One that I could feel comfortable with.

Moving the entire backup plan to this script will make it much more sustainable. I am going to test it this week.

Windows services and their configuration files

Saturday, 16 June 2007 01:44 by Myself

I discovered that reading app.config from a windows service can be quite tricky. It’s all about naming and, I might need to add, the sufficient rights. The default name of the app.config is {assemblyName.exe}.config.

Eg) MyService.exe.config.

All is good this far, but let's say you deploy the application and want to change a value by editing the xml. You might end up with no change, because when the runtime engine fails to find the config file it defaults to the value from the time of compilation.

If the service is running under “Local System”, the config file should be

{assemblyName.exe}.local.config

Or it might also be (but the one above has >priority)

{assemblyName}.config. (note that the file extension is stripped)

I ran SysInternals FileMon during the start to find this out, a real handy tool that can shed some light on the most peculiar problem.


Knowing this hopefully saves you some time.

I’ve straightened out all of my problems for now, and my Windows Service is successfully hosting a WCF endpoint and the debugging works!

I finally uninstalled Visual Studio 2005, since Orcas demands monopoly, and I don’t regret it… Yet. Time for some WPF!

Tags:   ,
Categories:   Development
Actions:   E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Impersonate in order to access a share in .NET

Thursday, 5 April 2007 02:38 by Myself

Today I discovered the best way to access a shared folder across the local network.

This example works outside a domain as well.

I tried to use the web.config directive first, .
But this had too many unwanted effects, when all I wanted to do was upload a file to a shared folder.

So, by using the LogonUser Win32 API I was able to wrap a class around this nicely


22 using (new Impersonator(true, "username", "password", "123.123.123.123"))


23 {


24 if (!Directory.Exists(@"\\123.123.123.123\Foo\bar"))


25 Directory.CreateDirectory(@"\\123.123.123.123\Foo\bar");


26 }


All calls made inside the using clause will then be impersonated.

You might as well use an overloaded constructor to provide the username, password and domain/machine/IP.

Source code: download (Temporarily down) 

Cheers!

Tags:   , , ,
Categories:   Development
Actions:   E-mail | Permalink | Comments (1) | Comment RSSRSS comment feed

Mail-to-blogger success and Orcas October dissapointment

Thursday, 16 November 2006 17:44 by Myself

I recently discovered how hard it is to spare some time for blog writing. I spend a lot of time writing emails though. And this is my first mail-to-blogger experience. If it works good, it’s definitely a great tool!

Yesterday I tried the September CTP of Visual Studio 2006 aka Orcas. I had to install VirtualPC to begin with, that went good.

In order to download the entire image which was around 3,4Gb, I think, I needed a download manager. Because the speed was terribly slow from Microsoft.

I wrote a quick download manager of my own. Using a .net Bits wrapper I found on MSDN.

What a great experience! In 30 minutes a had a fully functional download manager with resuming functions and background downloading and loads of other stuff. I’ve already got two colleagues signed up for the first beta :p

Back to the topic.

When it came to booting the image I was missing the Base01.vhd. It turned out I also needed the base OS image which wasn’t included.

After downloading that too (1.x Gb) I was ready to go.

To make a long story short; I was disappointed. There was no new templates or installed components for .Net 3.X in Orcas. Just a System.Core.dll, which I had to reference, in %Windows%\Microsoft.Net\3.5…\. It allowed me to use a few objects such as QueryExpression. They could at least have supplied a sample project.

I was expecting too much, apparently.

Tags:   , , ,
Categories:   Development
Actions:   E-mail | Permalink | Comments (1) | Comment RSSRSS comment feed
 
Software