:::: MENU ::::

Wednesday, February 24, 2010

Believe me it’s easy. If only you won’t get caught up with the 'Impersonation' word. A lot of sites took me for a jolly ride on the Impersonation road.

Here's a demo of the code:



using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Net;

public class ShareThis
{

 //used in calling WNetAddConnection2
 [StructLayout (LayoutKind.Sequential)]
  public struct NETRESOURCE
 {
  public int dwScope;
  public int dwType;
  public int dwDisplayType;
  public int dwUsage;
  [MarshalAs (UnmanagedType.LPStr)]
  public string lpLocalName;
  [MarshalAs (UnmanagedType.LPStr)]
  public string lpRemoteName;
  [MarshalAs (UnmanagedType.LPStr)]
  public string lpComment;
  [MarshalAs (UnmanagedType.LPStr)]
  public string lpProvider;
 }

 //WIN32API - WNetAddConnection2
 [DllImport("mpr.dll", CharSet=System.Runtime.InteropServices.CharSet.Auto)]
 private static extern int WNetAddConnection2A (
  [MarshalAs (UnmanagedType.LPArray)]
  NETRESOURCE [] lpNetResource,
  [MarshalAs (UnmanagedType.LPStr)]
  string lpPassword,
  [MarshalAs (UnmanagedType.LPStr)]
  string lpUserName,
  int dwFlags
  );

 //WIN32API - WNetCancelConnection2
 [DllImport("mpr.dll", CharSet=System.Runtime.InteropServices.CharSet.Auto)]
 private static extern int WNetCancelConnection2A (
  [MarshalAs (UnmanagedType.LPStr)]
  string lpName,
  int dwFlags,
  int fForce
  );

 public static void CopyFile (string share, string username, string password,
  string dirFrom, string dirTo, string filename)
 {
  NETRESOURCE [] nr = new NETRESOURCE [1];
  nr[0].lpRemoteName = share;
  nr[0].lpLocalName = ""; //mLocalName;
  nr[0].dwType = 1; //disk
  nr[0].dwDisplayType = 0;
  nr[0].dwScope = 0;
  nr[0].dwUsage = 0;
  nr[0].lpComment = "";
  nr[0].lpProvider = "";
  WNetAddConnection2A (nr, password, username, 0);

  // Do you stuff here, copy files, create dirs etc
  File.Copy (dirFrom + "\\" + filename, dirTo + "\\" + filename);

  WNetCancelConnection2A (share, 0, -1);
 }

 public static void Main(string[] args)
 {
  CopyFile(@"\\sa191", "username", "password", @"f:\shared",
   @"\\sa191\shared", "123.shp");
 }
}

 

Thursday, February 18, 2010

Every good developer knows never to re-invent the wheel, especially if there is software out there that has been tested by others, and has an established track record. As a developer using the .NET framework I’ve found some of these libraries invaluable, so I’m sharing them for some of the other dev’s out there with a brief outline of how to use.

Yedda Twitter Library.

URL: http://devblog.yedda.com/index.php/twitter-c-library/

I’ve used this on a number of very simple twitter projects, where I’ve just needed to send an update. As the site says its more of a wrapper for the Twitter API than an actual library, but none the less its an easy way to integrate with the service via a drop in dll. Here’s how to use it.

  1. Dim objYedda As New Yedda.Twitter
  2. Dim status as String
  3. Dim strTwitterUser as String = “username”
  4. Dim strTwitterPassword as String = “password”
  5. status = “Hello World”
  6. objYedda.Update(strTwitterUser, strTwitterPassword, strStatus, Yedda.Twitter.OutputFormatType.RSS)

This small section of code will update your Twitter stream (provided you have a reference to the DLL), and your username and password correct.

FileHelpers Library

URL: http://filehelpers.sourceforge.net/

The FileHelpers library was created to stop developers from continuing to parse CSV. If you are doing any kind of importing and exporting within your application using the CSV format to get data in or out, look no further.

You can strong type your flat file simply by coding up a class that maps a data type to each record. This way data consistency, and import / export reliability can be tightened up on quite a bit.  Writing out to a new file is also pretty easy once you’ve created your base classes defining the structure. Great little library for your toolkit.

First define the structure class…

  1. <DelimitedRecord(“,”)>_
  2. Public Class Product
  3. Public ProductName As String
  4. Public ProductCode As Integer
  5. etc..
  6. End Class

Add a reference to the FileHelper.dll, and read from the file , casting to a array of product objects.

  1. Dim engine As New FileHelperEngine(GetType(Product))
  2. Dim myProduct As Product() = DirectCast(engine.ReadFile(“product.txt”), Product())

Perform actions on the array of Products.

  1. For Each pro As Product In myProduct)
  2. Response.Write(pro.ProductName)
  3. Next

Elmah

URL: http://code.google.com/p/elmah/

Elmah stands for error logging module and handlers. It is a completely pluggable in system for error handling within your .NET app. It catches bot thrown and unhandled exceptions across the scope of your app, logs them, and allows you to browse the full stack trace, all without exposing the error to the users of your application. That’s useful for a number of reasons. Firstly you aren’t getting the performance hit of using debug=true within your application (which by the way you should never be using in a production environment anyway) – and it means you can still get to the bottom of little blips as and if they happen. Coolio.

Elmah works as an HTTP module, so it takes little or no effort to deploy on any project. Just configure a few bits and bobs, and away it goes. All of the configuration is performed in the configuration file – just telling it whether you want your errors logged in a database, in memory or in a txt file is as simple as changing some web config parameters. You can even grab recent errors via RSS and get notified like that.

Log4Net

URL: http://logging.apache.org/log4net/

Following in the same vein as Elmah – Log4Net is a port of the well known logging framework for Java log4J. Whilst Elmah concentrates on exceptions that are thrown, Log4Net allows a much more granualar approach to program debugging.

With log4net it is possible to enable logging at runtime without modifying the original application binary and without incurring a high performance cost. Multiple “levels” of logging can be set within your program as well, and so you can determine quickly where “fatal” errors occur, and where “warnings” occur that can be ignored in the safe running of your application.

Log4Net enables all of these things whilst providing the same level of control over the logging format and location as Elmah. You can decide whether you’d like your debug message sent  to a database, a text file, or indeed a TCP port. Different “Appenders” define where and how to send the messages, so if there’s somewhere else you’d like to see errors, you can easily write your own appender to perform this. Again, the appenders are defined in the web.config file.

  1. Imports log4net
  2. Imports log4net.Config
  3. Private Shared log As log4net.ILog
  4. Public Sub Page_Load(Byval s as Object, Byval e As EventArgs) Handles MyBase.Load
  5. log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
  6. BasicConfigurator.Configure()
  7. log.Debug(“Debug Message”)
  8. log.Warn(“Warning Message”)
  9. log.Fatal(“Fatal Message”)
  10. End Sub

Enterprise DT FTP Library

URL: http://www.enterprisedt.com/products/edtftpnet/overview.html

Enterprise DT is a great little FTP library, that performs all the needful without you getting your hands too dirty. It works with both web and offline applications, and again is a port of a Java library. I’ve used it for automating FTP tasks at the command line, sending photos between two sites automatically via FTP, and for sending feeds to google. It’s really easy to use, and saves you from having to write your own FTP operations. Fire it up, pass some usernames and passwords to it, and away we go. As below:

  1. Dim ftp as FTPConnection = new FTPConnection()
  2. ftpConnection.ServerAddress = “myserver”
  3. ftpConnection.UserName = userName
  4. ftpConnection.Password = password
  5. ftpConnection.Connect()
  6. ftpConnection.UploadFile(localFilePath, remoteFileName)
  7. ftp.Close()

HtmlAgilityPack

URL: http://www.codeplex.com/htmlagilitypack

The Html Agility Pack is a library for parsing HTML. It is particularly useful if you are doing any kind of scraping work, with the main object of the software to transform real world HTML into structured and parseable DOM structure. It supports plain XPATH or XSLT syntax for traversing through HTML, making loops and extraction of text a breeze.  Knowing these two technologies isn’t a pre-requisite to using it, but it sure as heck helps.  You don’t have to setup the WebRequest or anything to grab remote files, which is handy – as you’ll see from the example.

  1. Dim hw As New HtmlAgilityPack.HtmlWeb
  2. Dim doc As HtmlAgilityPack.HtmlDocument
  3. doc = hw.Load(“http://blog.webdistortion.com”)
  4. For Each s As HtmlAgilityPack.HtmlNode In doc.DocumentNode.SelectNodes(“//a[@href]“)
  5. Dim att As HtmlAgilityPack.HtmlAttribute = s.Attributes(“href”)
  6. Response.Write(att.Value & vbCrLf)
  7. Next

OpenAuth Library

URL: http://code.google.com/p/oauth-dot-net/

Open Auth is slowly becoming the norm, with web apps many preferring its usage over other less secure forms of authentication. This library is a .NET implementation of OpenAuth, and is mighty useful if you need to get up and running quickly. You are sure to run into a web service that needs you to auth via it. Google, Yahoo, Netflix and Twitter all support OpenAuth to interact with their service. The code needed for open auth is more extensive than some of the other bits and bobs, and has been better explained by others. Some of these links are worth a look.

  • Shannon Whitley offers this example: Code | Live demo
  • Daniel Crenna’s examples:

OAuth Specification

The OAuth Workflow

OAuth Walkthrough

Microsoft AntiXSS library

URL: http://bit.ly/toCrt

This is one of the security packs that MS have released to help .NET developers write better, more secure code. Essentially it is an encoding library designed to help protect ASP.NET web-based applications from XSS attacks, and works on the principals of inclusion (white-listing) to accept valid characters. I’ve used it successfully on a couple of projects, and some of the pre-written methods have been rigourously tested by leading security experts.

  1. Microsoft.Security.Application.AntiXss.HtmlEncode(strNotrust)
  2. Microsoft.Security.Application.AntiXss.JavaScriptEncode(strNotrust)

C5 Collections – Collections for .NET

URL: http://www.itu.dk/research/c5/

C5 provides functionality and data structures not provided by the standard .Net System.Collections.Generic namespace, such as persistent tree data structures, heap based priority queues, hash indexed array lists and linked lists, and events on collection changes. Also, it is more comprehensive than collection class libraries on other similar platforms, such as Java. Unlike many other collection class libraries, C5 is designed with a strict policy of supporting “code to interface not implementation”. Definitely worth a look.

Honourable Mentions

Dependency Injection/Inversion of Control

Logging

Compression

Ajax

Data Mapper

ORM

Charting/Graphics

PDF Creators/Generators

Unit Testing/Mocking

Automated Web Testing

URL Rewriting

Controls

Unclassified

More

Tuesday, February 2, 2010

I’m not using NAnt or anything fancy for most of my projects—so I needed a simple, MSBuild way to automate my version numbers in a project..

<tangent>
HOLY CRAP! Why isn’t this built into Visual Studio Pro?
</tangent>

Here we go:

1. Download the latest build of AssemblyInfoTask (download here) (was 1.0.51130.0 for me).  This is a semi-Microsoft supported MSBuild task that gives you a lot of flexibility over your AssemblyInfo.cs files.

2. Install AssemblyInfoTask.  When prompted where—install into the GAC.  If you don’t have access to the GAC on your workstation, then why aren’t you developing on a VM? ;)

3. Locate the Microsoft.VersionNumber.targets file.  If you installed to the GAC, it should be at %ProgramFiles(x86)%\MSBuild\Microsoft\AssemblyInfoTask Or %ProgramFiles%\MSBuild\Microsoft\AssemblyInfoTask (depending on your architecture).

4. Copy the Microsoft.VersionNumber.targets file into a location in your solution or project.  I recommend $(SolutionDir) so you can share it amongst all of your projects.  The guilde recommend pointing to the file directly; however, you can’t modify the base Major versions that way (without setting the same major version for ALL projects you ever work on).  You can also rename it as approprate.

“Int16s Are Too Small” Or “Why 2007 Broke Versioning” Fix

According to experts who are much smarter than me, the build version numbers are Int16s—meaning 65535 caps out the number.  Unfortunately, the year 2007 breaks this (070101 or 70101 for 07 jan 01) doesn’t fit within an Int16.  Stellar.

The MSBuild team recommended taking out the year and simply placing a 1 infront of it.  That works; however, I really like having the year in there somewhere.

For me, I’ve placed the year into the MinorVersion.  After reviewing most of our practices, the minor version for most of our projects changes with annual maintenance OR not at all (we bump the major version).  This, if nothing else, will help standardize when it changes. :)  As always, YMMV.

No matter which solution you choose, you’ll need to remove the year from the BuildNumberFormats.

In your Targets file, you can change the two lines to report out the MMdd (0309, for example, today) to work around the bug.  I’ve bolded the two lines below.  As you can see, I also added the “9” to the MinorVersion to represent 2009. 

<PropertyGroup>

  <AssemblyMajorVersion>3</AssemblyMajorVersion>

  <AssemblyMinorVersion>9</AssemblyMinorVersion>

  <AssemblyBuildNumber></AssemblyBuildNumber>

  <AssemblyRevision></AssemblyRevision>

  <AssemblyBuildNumberType>DateString</AssemblyBuildNumberType>

  <AssemblyBuildNumberFormat>MMdd</AssemblyBuildNumberFormat>

  <AssemblyRevisionType>AutoIncrement</AssemblyRevisionType>

  <AssemblyRevisionFormat>00</AssemblyRevisionFormat>

</PropertyGroup>

 

<!– Properties for controlling the Assembly File Version –>

<PropertyGroup>

  <AssemblyFileMajorVersion>3</AssemblyFileMajorVersion>

  <AssemblyFileMinorVersion>9</AssemblyFileMinorVersion>

  <AssemblyFileBuildNumber></AssemblyFileBuildNumber>

  <AssemblyFileRevision></AssemblyFileRevision>

  <AssemblyFileBuildNumberType>DateString</AssemblyFileBuildNumberType>

  <AssemblyFileBuildNumberFormat>MMdd</AssemblyFileBuildNumberFormat>

  <AssemblyFileRevisionType>AutoIncrement</AssemblyFileRevisionType>

  <AssemblyFileRevisionFormat>00</AssemblyFileRevisionFormat>

</PropertyGroup>

 

This results in a version string that looks like 3.9.0309.{increment}.

5. Open up your project’s solution and unload the project you are wanting to auto-increment. Towards the end of the file, you’ll see the default MSBuild C# build path; add the location to your new .targets file in your solution directory.

<Import Project=$(SolutionDir)MyProject.VersionNumber.targets />

7. Save and Close and Reload the project.

8. Build/Rebuild your project and the AssemblyInfo.cs should set to the specified increment scheme.

You’re done!

“Too Many WebResources?” Fix 

My project references numerous resources for images and style sheets; however, having these inside of AssemblyInfo.cs seems to cause it to go haywire and throw array errors (assumingly because there is more than one [assembly:WebResource()] call).

To fix this, I moved my WebResources out of AssemblyInfo.cs and into a new file under Properties called WebResources (Add New Item > Assembly Information File).  Strip out everything except the WebResources you copy in and the project now compiles like a champ.

For additional setup details and options within the .targets files, the AssemblyInfoTask installer comes with a CHM help file that covers additional customizations available.

More