A Straight Forward ASP.NET AJAX Solution With MS Ajax, Restful WCF Services, and A Dash Of JQuery

One of the main advantages of JSON is that, like XML, it can represent an object graph of any shape.  JSON allows for the natural structure of entity Types to be expressed in the form of nested and aggregated object literals.  The simplicity and small footprint of this format has made it a popular choice for data interchange with the dynamic languages crowd, where JSON can be parsed into native objects with basic language constructs.  This is what makes it most appealing for JavaScript developers.  This article will demonstrate a straight forward way of doing Ajax with WCF Rest, MS Ajax, Object Bakery, and JQuery.

1.       Create a new WebForms project.

2.       Drag in a ScriptManager to Default.aspx’s form element.

3.       Add JQuery-1.3.2.min.js to the project.

4.       Drag JQuery-1.3.2.min.js into the head section.

5.       Add an empty <p /> to the form.

6.       Switch to design view.

7.       Drag in an HTML input button and double click it.

Your markup should now look something like this:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="OBWeb._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html xmlns="http://www.w3.org/1999/xhtml"&gt;

<head runat="server"> 

     <title></title>

          <script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>

          <script type="text/javascript">

               function Button1_onclick() {

              }

          </script>

</head>

<body>

<form id="form1" runat="server">

     <div>

          <asp:ScriptManager ID="ScriptManager1" runat="server" />

          <input id="Button1" type="button" value="submit" onclick="return Button1_onclick()" />

          <p />

     </div>

</form>

</body>

</html>

  Notice that we have a stubbed out JavaScript function wired to our button.

8.       Add a reference to ObjectBakery.dll, available here.

9.       Add a new “Ajax-enabled WCF Service” to your project.

10.   Name it Service1.

11.   Create a sample POCO that we can use for the demo.  Here’s mine:

 public class TestObject

 {

     public int ID { get; set; }

     public string Description { get; set; }

 }

 

12.   Change the stubbed out DoWork method in Service1 to look like this.

[WebGet]

[OperationContract]

public string DoWork(int id)

{

     //fab some data objects

     List<TestObject> obs = new List<TestObject>();

     obs.Add(new TestObject { ID = id, Description = "ASDFASDF" });

     obs.Add(new TestObject { ID = id + 1, Description = "QWER" });

     obs.Add(new TestObject { ID = id + 2, Description = "DFFG" });

     obs.Add(new TestObject { ID = id + 3, Description = "ZXCV" });

            //magic

            var helper = new ObjectBakery.Helpers.SerializationHelper();

            var txtO = helper.JsonSerialize(obs.ToArray());

            return txtO;

       }

 

13.   In the page designer right mouse click your ScriptManager and go to properties.

14.   In the property designer click the ellipsis next to Services

15.   Add a Service, setting the Path property to the url of Service1, i.e. “/Service1.svc”.

16.   Now lets write some JavaScript.

<script type="text/javascript">

     function Button1_onclick() {

          var service = new Service1();

          service.DoWork(3, onSuccess, null, null);

     }

            function onSuccess(result) {

               var objects = eval("(" + result + ")");

               for (var i in objects) {

                    $("p").append(objects[i].Description + "<br />");

               }

          }

          </script>

What  we did here is fill out our Button1_onclick with code that news up a Service1 reference and invokes its DoWork.  The first argument will be passed as the id parameter to our WebMethod.  The second argument is a callback, in our case the onSuccess method.  Notice the signature of onSuccess takes a result param.  This will be our JSON string returned from DoWork.  Note that we can parse the result into a native JavaScript object graph with a single line of code.

var objects = eval("(" + result + ")");

 

This is pretty cool.   We trust our own service, so there’s no issue with using eval, instead of parseJSON().  In our for loop, we use JQuery to add new DOM elements holding the Description property from each of our objects.

$("p").append(objects[i].Description + "<br />");

That’s the basic story.  What we’ve been able to do here is enable the basic async data exchange paradigm between an ASPX page and data enabled Rest services.  There are some fun bits here when you couple this approach with ORM frameworks, such as Entity Framework or NHibernate.  We now have the capability to move objects between JavaScript and C# seamlessly.  Object Bakery has helper methods to move between JSON and CLR graphs with a single line of code.  I have found this approach helpful when I need to share objects between client and server, and  I don’t want to worry about the details of data interchange.   Note that Object Bakery also works with Anonymous Types, which allows us to project out objects containing only the data our front-end needs and thus keeps our graphs and their isomorphic JSON strings as small as possible.  Your users will appreciate every bit of responsivity you can give them.

You can download the code for this project here.

Enjoy..

Get Control Of Your Enterprise Library Logging Application Block Logs

Enterprise Library’s Logger is powerful and convenient.  It’s default TextFormatter provides a suitable human readable format, and it also allows you to implement custom formatters to suite your needs.  I think that being able to work with log data without having to manually parse strings, can really simplify the development of tools for mining logs.   To this end, I whipped up a small WinForms app that demonstrates how to take log entries originating from a text spool, convert them into objects, and query them with Linq.  The primary goal was to provide simple UI that enables log search, filter, and find, with sorting, grouping, etc.

First off, the heavy lifting in this sample is provided by the EntLib Contrib LogParser.  Their FilteredLogReader class drives a tokenizer, which creates and populates LogEntry objects out of log text.   The tokenizer will use any formatting template, in our case, I’ve used the built in “Text Formatter”.   When it executes, it generates a RegularExpression capable of matching and trapping the values involved in populating our collection of LogEntry objects.  Ultimately, we are provided with a simple API for driving all of this.  Here’s a brief sample:

string configFile = "abc.config";

            string traceLog = "trace.log";

 

            FilteredLogFileReader reader =

new FilteredLogFileReader(traceLog, configFile,

                        new TimeStampParser(CultureInfo.CurrentCulture));

 

            Filter filter = new Filter

            {

                StartTime = DateTime.Now.AddHours(-1),

                StopTime = DateTime.Now

            };

 

            IEnumerable<LogEntry> entries = reader.ParseLogFile(filter);

The basic idiom here is:

1.       Get a FilteredLogFileReader

2.       Setup a Filter

3.       Feed the filter to the reader’s ParseLogFile

To facilitate a flexible set of filtering concepts at the UI, I decided to use a simple FilterExpression class to represent a set of keys, values, and match operators.  Here’s a quick way to get the intersection result set from applying a set of filters with a single pass through the logs.

       

        private IList<LogEntry> FilterLogEntries(List<LogEntry> lst,

                                                 List<FilterExpression> exprs)

        {

            var matchAllExprs = new List<LogEntry>();

                       List<PropertyInfo> props = typeof(LogEntry).GetProperties().ToList();

            lst.ForEach(entry =>

                {

                    int matchCount = 0;

                    exprs.ForEach(expr =>

                    {

                        string value = props.Find(prop => prop.Name.Equals(expr.Key))

                                                      .GetValue(entry, null).ToString();

                        switch (expr.Operator.ToLower())

                        {

                            case "contains":

                                if (value.Contains(expr.Value))

                                    matchCount++;

                                break;

                            case "!contains":

                                if (!value.Contains(expr.Value))

                                    matchCount++;

                                break;

                            case "regex match":

                                if (new Regex(expr.Value).IsMatch(value))

                                    matchCount++;

                                break;

                            case "==":

                                if (expr.Value.Equals(value))

                                    matchCount++;

                                break;

                            case "!=":

                                if (!expr.Value.Equals(value))

                                    matchCount++;

                                break;

                            default:

                                throw new Exception("operator not found");

                        }

                    });

                    if (exprs.Count == matchCount)

                        matchAllExprs.Add(entry);

                });

            return matchAllExprs;

        }

 

If any of the LogEntries match all of the expressions, then those are returned to the caller.  Now we can place the log data onto our screen for users.

this.dataGridView1.DataSource = 

    new BindingList<LogEntry>(FilterLogEntries(lst,

        lbxFilterExpressions.Items.Cast<FilterExpression>().ToList()));

The sample app that I’ve included, gives users the ability to create, configure, and apply FilterExpressions on the fly.  Here’s a screenshot.

You can get the source for this sample here.  Enjoy..   

Object Bakery – Fun with .NET Serialization and Crypto: Part 2

In my last article, I demonstrated how to use .NET serialization to dehydrate and rehydrate objects with helpers that drive XmlSerializer, DataContractSerializer, SoapFormatter, and BinaryFormatter.  This is part 2, where I expand upon these concepts demonstrating how to use the DESCryptoServiceProvider to securely save off your objects for later consumption.   For this, I created a few helpers that encrypt an object stream and save it to disk, as well as the reverse.  Only instead of using MemoryStream as we did in the last article, we use the CryptoStream and a shared key.   Here is a test that shows a secure round trip that saves an encrypted Product instance to disk and reads it back out.

        [TestMethod]

        public void CanEncyptToDecryptFromDisk()

        {

            string strKey = ObjectHelper.GenerateKey();

            ObjectHelper objectHelper = new ObjectHelper();

            FileInfo file = new FileHelper().GetTempFile();

 

            List<Asset> assets = new TestAssetFactory().Build();

 

            objectHelper.EncryptObjectToDisk(file.FullName, assets, strKey);

 

            List<Asset> assets2 =

               (List<Asset>)objectHelper.DecryptObjectFromDisk(file.FullName, strKey);

 

            Assert.IsNotNull(assets2);

 

            file.Delete();

        }

A notable difference from the samples in part 1 is that we generate a key first and then use it to symmetrically encrypt and decrypt our persisted object.   The single assertion here is not particularly impressive, so here is a test that runs the same idiom with a DataSet and then compares the values of each field in each row for match fidelity.

        [TestMethod]

        public void CanDehydrateRehydrateDataSetToFile()

        {

            string dataKey = ObjectHelper.GenerateKey();

 

 

            FileInfo file = new FileHelper().GetTempFile();

            DataTable productsDataTable = new TestTableFactory().Build();

            DataSet productsDataSet = new DataSet("Products");

            productsDataSet.Tables.Add(productsDataTable);

 

            ObjectHelper objectHelper = new ObjectHelper();

            objectHelper.EncryptObjectToDisk(file.FullName, productsDataSet, dataKey);

            DataSet productsDataSet2 =

                (DataSet)objectHelper.DecryptObjectFromDisk(file.FullName, dataKey);

 

            Assert.IsTrue(productsDataSet2 != null);

 

            for (int j = 0; j < productsDataSet.Tables["Products"].Rows.Count; j++)

            {

                DataRow pRow = productsDataSet.Tables["Products"].Rows[j];

                DataRow pRow2 = productsDataSet2.Tables["Products"].Rows[j];

 

                for (int i = 0; i < pRow.ItemArray.Length; i++)

                {

                    Assert.IsTrue(pRow.ItemArray[i].ToString() ==

                       pRow2.ItemArray[i].ToString());

                }

            }

 

            file.Delete();

        }

 

Finally, here is the ObjectHelper class demonstrated above..

    public class ObjectHelper

    {

        public static string GenerateKey()

        {

            // Create an instance of Symetric Algorithm. Key and IV is generated automatically.

            DESCryptoServiceProvider desCrypto =

                 (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();

 

            // Use the Automatically generated key for Encryption.

            return ASCIIEncoding.ASCII.GetString(desCrypto.Key);

        }

 

        public bool EncryptObjectToDisk(string fileFullPath, object data, string eKey)

        {

            FileStream fsEncrypted =

                 new FileStream(fileFullPath, FileMode.Create, FileAccess.Write);

            bool saveSuccess = false;

            try

            {

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();

                des.Key = ASCIIEncoding.ASCII.GetBytes(eKey);

                des.IV = ASCIIEncoding.ASCII.GetBytes(eKey);

                CryptoStream cryptostream =

                     new CryptoStream(fsEncrypted, des.CreateEncryptor(), CryptoStreamMode.Write);

                BinaryFormatter bin =

                     new BinaryFormatter(null, new StreamingContext(StreamingContextStates.File));

                using (StreamWriter streamWriter = new StreamWriter(cryptostream))

                {

                    bin.Serialize(streamWriter.BaseStream, data);

                    streamWriter.Flush();

                    streamWriter.Close();

                    saveSuccess = true;

                }

            }

            finally

            {

                if (fsEncrypted != null)

                    fsEncrypted.Close();

            }

            return saveSuccess;

        }

 

        public object DecryptObjectFromDisk(string fileFullPath, string eKey)

        {

            if (!File.Exists(fileFullPath))

                return null;

            FileStream fsEncrypted =

                  new FileStream(fileFullPath, FileMode.Open, FileAccess.Read);

            try

            {

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();

                des.Key = ASCIIEncoding.ASCII.GetBytes(eKey);

                des.IV = ASCIIEncoding.ASCII.GetBytes(eKey);

                CryptoStream cryptostream =

                     new CryptoStream(fsEncrypted, des.CreateDecryptor(), CryptoStreamMode.Read);

                object data = null;

                BinaryFormatter bin =

                     new BinaryFormatter(null, new StreamingContext(StreamingContextStates.File));

                using (StreamReader reader = new StreamReader(cryptostream))

                {

                    data = bin.Deserialize(reader.BaseStream);

                    reader.Close();

                }

                return data;

            }

            finally

            {

                if (fsEncrypted != null)

                    fsEncrypted.Close();

            }

        }

    }

The samples I provide here are from a Utility library that I use in some of my apps, you can download the working src and tests here.  If anyone out there finds some use in these or can suggest improvements or other applications, I’d love to hear about it.  Thanks and happy baking..

Object Bakery – Fun with .NET Serialization and Crypto: Part 1

Being able to snapshot an object graph at runtime can be a valuable capability.  I have had occasion to capture objects during a run for the purpose of analyzing and debugging problems that require comparison across multiple runs.  Additionally, the power to dehydrate objects and store them in a disk based cache, can also prove quite useful in certain scenarios.  Some other capabilities include capturing archetypal object instances to file and adding them as embedded resources to test projects to serve as  stubs and/or test doubles.  Some other ways to work with objects offline might include sending dehydrated objects through FTP, Email , Message Queues, etc.  I present here a few helper classes that I have used for the purposes described and more. 

First, when security is not a concern, serialization to plain text Xml can be an effective means of quick object dehydration.  I wrote the SerializationHelper for this purpose.  Below is a test that demonstrates instancing a serializable entity class (a Product), converting it to an Xml string representation, and converting the string back into an object.

        [TestMethod]

        public void CanSerializeToandFromXml()

        {

Product product1 = new TestProductFactory().Build()[0];

            SerializationHelper serializationHelper = new SerializationHelper();

            string sProduct1 = serializationHelper.XmlSerialize(product1);

            Product product2 = serializationHelper.XmlDeserialize<Product>(sProduct1);

            XmlDocument testLoadDoc = new XmlDocument();

            testLoadDoc.LoadXml(sProduct1); //throws exception if not well formed

 

            Assert.IsTrue(product1.ID.Equals(product2.ID) &&

                    product1.Name.Equals(product2.Name));

 

            //the products themselves are not the same instance, but instead deep copies

            Assert.IsFalse(product1.Equals(product2));

        }

As you can see the assertions, show that the two Product objects have the same data, but they are in fact not the same object.  With this we have created a deep copy of the original product as it makes it through the round trip.  The dehydrated Product looks in this case looks something like this:

<?xml version="1.0"?>

<Product xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

  <ID>1</ID>

  <SKU>fa8f0777-74e7-4aeb-926f-a554b5dc191e</SKU>

  <Name>Monkey</Name>

  <Description>Squirrel Monkey.  Aggressive disposition.  Likes icecream and hugs.</Description>

  <Assets>

    <Asset>

      <Format>Docx</Format>

      <Data>

        UEsDBBQABgAIAAAAIQAeGe91cwEAAFQFAAATAAgCW0NvbnRlbnRfVHlwZXNdLnhtbCCiBAIooAACAAAAAAAAAAAAAAA</Data>

        <ID>1</ID>

      <Name>Brochure</Name>

    </Asset>

    <Asset>

      <Format>Jpg</Format>

      <Data>/9j/4U5uRXhpZgAATU0AKgAAAAgACgEPAAIAAAAGAAAAhgEQAAIAAAAPAAAAjAESAAMAAAABAAEAAAEaAAUAAAA</Data>

        <ID>2</ID>

      <Name>Image1</Name>

    </Asset>

    <Asset>

      <Format>Jpg</Format>

      <Data>/9j/4VsfRXhpZgAATU0AKgAAAAgACgEPAAIAAAAGAAAAhgEQAAIAAAAPAAAAjAESAAMAAAABAAEAAAEaAAUAAAAB</Data>

      <ID>3</ID>

      <Name>Image2</Name>

    </Asset>

  </Assets>

</Product>

Note that in this case, the Product class carries with it a generic List of Assets, which themselves carry byte arrays that represent images, documents, brochures, etc..  Thus with this approach I’m able to flatten an object graph that carries file assets send it somewhere as Xml, reconstitute it, save off its byte arrays to disk, and then open them with the appropriate program.

If the entity objects that you are working with do not implement ISerializable, they should be tagged with the Serializable attribute.  In the case where you have not explicitly implemented ISerializable and some of the properties are not set, you’ll find that these properties are missing from the Xml that results from serialization with XmlSerializer, SoapFormatter, or BinaryFormatter.  The DataContractSerialize/DataContractDeserialize helper methods allow you to provide a Type that is attributed with WCF DataContract and DataMember attributes to give the serializer hints on how to work with the object. 

        [TestMethod]

        public void CanDataContractSerializeDeserialize()

        {

            Product product = new TestProductFactory().Build()[0];

            var serializationHelper = new  SerializationHelper();

 

            var pBytes = serializationHelper.DataConractSerialize<Product>(product);

            string xstring = Encoding.UTF8.GetString(pBytes);

 

            var pBytes2 = Encoding.UTF8.GetBytes(xstring);

            Product product2 = serializationHelper.DataConractDeserialize<Product>(pBytes2);

 

            //verify

            Assert.IsTrue(product.Name.Equals(product2.Name) && product.ID.Equals(product2.ID));

            Assert.IsFalse(product.Equals(product2)); //deep copy

        }

Now the Class..

    public class SerializationHelper

    {

        public string XmlSerialize(object Member)

        {

            using (MemoryStream b = new MemoryStream())

            {

                XmlSerializer xs = new

                    XmlSerializer(Member.GetType());

                xs.Serialize(b, Member);

                return Encoding.UTF8.GetString(b.ToArray());

            }

        }

        public T XmlDeserialize<T>(string Serialized)

        {

            using (MemoryStream b =

                new MemoryStream(Encoding.UTF8.GetBytes(Serialized)))

                {

                    XmlSerializer xs = new XmlSerializer(typeof(T));

                    return (T)xs.Deserialize(b);

                }

        }

        public byte[] SoapSerialize<T>(T obj)

        {

            byte[] bytes = null;

            using (MemoryStream b = new MemoryStream())

            {

                SoapFormatter formatter = new SoapFormatter();

                formatter.Serialize(b, obj);

                bytes = b.ToArray();

            }

            return bytes;

        }

        public T SoapDeserialize<T>(byte[] blob)

        {

            T obj = default(T);

            using (MemoryStream b = new MemoryStream(blob))

            {

                SoapFormatter formatter = new SoapFormatter();

                obj = (T)formatter.Deserialize(b);

            }

            return obj;

        }

        public byte[] BinarySerialize(object obj)

        {

            byte[] bytes = null;

            IFormatter formatter = new BinaryFormatter();

            using (MemoryStream stream = new MemoryStream())

            {

                formatter.Serialize(stream, obj);

                bytes = stream.ToArray();

            }

            return bytes;

        }

        public T BinaryDeserialize<T>(byte[] bytes)

        {

            T instance = default(T);

            IFormatter formatter = new BinaryFormatter();

            using (MemoryStream stream = new MemoryStream(bytes))

            {

                instance = (T)formatter.Deserialize(stream);

                bytes = stream.ToArray();

            }

            return instance;

        }

        public virtual T DataConractDeserialize<T>(byte[] bytes)

        {

            T result = default(T);

            using (var stream = new MemoryStream(bytes))

            {

                XmlReader reader = XmlReader.Create(stream);

                DataContractSerializer serializer = new DataContractSerializer(typeof(T));

                result = (T)serializer.ReadObject(reader);

            }

            return result;

        }

        public virtual byte[] DataConractSerialize<T>(T obj)

        {

            byte[] bytes = new byte[] { };

            using (var stream = new MemoryStream())

            {

                XmlWriter writer = XmlWriter.Create(stream);

                DataContractSerializer serializer = new DataContractSerializer(typeof(T));

                serializer.WriteObject(writer, obj);

                writer.Flush();

                bytes = stream.ToArray();

            }

            return bytes;

        }

    }

Thats the basic scenario.  In part 2 of this article, I’ll demonstrate how to do secure object persistence to disk.  You’ll also be able to download the source for both parts.  Enjoy and happy baking… 

Symmetric Hashing With .NET Crypto Service Providers and COM Interop

I wrote the DotNetCryptoCOM (DNCC) library because I  wanted to be able to generate and reverse cypher text between .NET and COM applications using a single .dll.  It allows developers to drive the builtin .NET Cryptographic Service Providers with a simple API.  I’ve used this lib in VB, Managed C++, and of course C# applications.  Some of you may find it useful as well.
 
A few notes of interest:
 
1.  If you plan to use it from COM apps, you’ll need to do the following from a cmd shell:

(hint, use a Visual Studio Shell to have the path var in your env setup properly)

     copy DotNetCryptoCOM.dll  %windir%\system32

     cd %windir%\system32

     regasm %windir%\system32\DotNetCryptoCOM.dll /tlb:DotNetCryptoCOM.tlb

     gacutil /i DotNetCryptoCOM.dll

2.  If you plan to use it in Classic ASP apps, you’ll also need to remember to configure IIS to support ASP pages and from a cmd shell type:

     iisreset.

Now, I present a brief sample that shows how to use DNCC. 

First, I’ll encrypt some text in VBScript with it:

——————————————————————–

‘ Set raw text

Dim

strRawData

strRawData =

"super secret message"

‘ Set secret key

Dim strKey

strKey = "shhhh"  

‘ Set an instance of the CryptoProvider

Set dncc = CreateObject("DotNetCryptoCOM.CryptoClass")

‘ Encrypt the data with key

strEncryptedData = dncc.Encrypt(strRawData, strKey)

——————————————————————–

Now assume you’ve provided strEncryptedData to a C# .NET application.

——————————————————————–

string

secretKey = "shhhh";

DotNetCryptoCOM.

CryptoClass dncc = new DotNetCryptoCOM.CryptoClass();

string

 strRawData = dncc.Decrypt(strEncryptedData, secretKey);

——————————————————————–

Voila..  Secure trip between domains.  Note, the default Cryptographic Service Provider is DES.

If you’re interested in DNCC’s internal implementation, I’ll leave that to your curiosity and reflector

Its really pretty straight forward if you take a look inside…

I have provided the DNCC library for download here.

A more complete example of an ASP to ASP.NET shared authentication solution uses it here.

Happy hashing and best of luck..

A config-based approach to pluggable composition

I wanted to share this sample to demonstrate a simple way to implement a configuration based approach to switching out pluggable dependencies.  The example here uses reflection to dynamically load an assembly and then instantiate the targeted class contained therein.  The idea with this approach is that you may have different implementations of an interface contained in different assemblies.  Thus,  you’re able to simply target the different implementations of the interface by switching an app config key that specifies a different assembly name.  Note the following:

1.  The path variable is the fully qualfied assembly name.

2.  The className variable is path with the name of the class that implements an expected interface appended to it.  In this case, we expect the assembly to contain an implementation of IOrder.

From PetShop.NET 4.0 reference app source:

using System;

using System.Reflection;

using

System.Configuration;

namespace

PetShop.MessagingFactory

 {

         /// <summary>

        /// This class is implemented following the Abstract Factory pattern to create the Order

        /// Messaging implementation specified from the configuration file

        /// </summary>

        public sealed class QueueAccess

        {

             // Look up the Messaging implementation we should be using

             private static readonly string path = ConfigurationManager.AppSettings["OrderMessaging"];

             private QueueAccess() { }

             public static PetShop.IMessaging.IOrder CreateOrder() {

             string className = path + ".Order";

             return (PetShop.IMessaging.IOrder)Assembly.Load(path).CreateInstance(className);

          }

    }

}

Simple Random Password Generator

 
Simple C# function to generate random passwords:
 

Random randomizer = new Random();

public string CreateTemporaryPassword(int length)

{

    string letters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    var chars = new char[length];

    for (int i = 0; i < length; i++)

        chars[i] = letters[randomizer.Next(0, letters.Length)];

    return new string(chars);

}

TSQL function to parse delimeted string and return a memory table containing the values

This script is useful when you need to generate a rowset from a delimeted string.  It allows the "WHERE IN" clause to be used against the values in the string, because they are converted into table rows.  This UDF is designed to be plugged into other queries where this need is present.  Here’s an example of how to use it:
 
Basic Usage:

select VALUE from PARSE_STRING(‘a,b,c,d,e’, ‘,’)

GO

Real World Usage:

select

* from customers where last_name in (select VALUE from PARSE_STRING(‘obama,biden,clinton,holder’, ‘,’))

GO

 
The Function:
 

SET

ANSI_NULLS ON

GO

SET

QUOTED_IDENTIFIER ON

GO

— =============================================

— Author: Joel Holder

— Description: parses a delimeted string and returns a table

— =============================================

 

/****** Object: UserDefinedFunction [dbo].[PARSE_STRING] ******/

IF

EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N‘[dbo].[PARSE_STRING]’) AND type in (N‘FN’, N‘IF’, N‘TF’, N‘FS’, N‘FT’))

    DROP

FUNCTION [dbo].[PARSE_STRING]

go

CREATE

FUNCTION PARSE_STRING  (@string nvarchar(max),  @delimeter char(1))

RETURNS

@result_table TABLE (POSITION int, VALUE nvarchar(max))

AS

BEGIN

— Fill the table variable with the rows for your result set

declare @pos int

declare @piece varchar(500)

declare @id int

set @id = 0

— Need to tack a delimiter onto the end of the input string if one doesn’t exist

    if right(rtrim(@string),1) <> @delimeter

    set @string = @string + @delimeter

    set @pos = patindex(‘%’ + @delimeter + ‘%’ , @string)

    while (@pos <> 0)

        begin

            set @id = @id + 1

            set @piece = left(@string, @pos 1)

            — You have a piece of data, so insert it, print it, do whatever you want to with it.

            insert into @result_table values (@id, @piece)

            set @string = stuff(@string, 1, @pos, )

            set @pos = patindex(‘%’ + @delimeter + ‘%’ , @string)

        end

 

return

END 

GO

AutoFocus the UserName field of an ASP.NET Login Control

Even if you’re not using a templated version of the Login Control, the builtin TextBox for username entry can be targeted like this:

protected void Page_Load(object sender, EventArgs e){

           SetFocus(Login1.FindControl("UserName"));

SetFocus is in the Page class.

Easy joy..

Demonstration of Dynamic Type Creation and Resolution

This is a modified sample from the .NET Framework SDK.  Basically demonstrates how to programmatically drive the ILGenerator to emit code resulting in a method definition.  Note that it is wrapped in a programmatically created assembly that exists only in memory.  In the Main of this Application, the dynamic assembly is unwrapped and reflection is used to invoke the method that was generated. 

 

Instuctions: Create a new Console Application.  Replace the entire contents of Program.cs with the following.  Then run.

 

using System;

using System.Reflection;

using System.Reflection.Emit;

using System.Threading;

using System.Runtime.Remoting;

 

class App

{

static Assembly TypeResolveHandler(Object sender, ResolveEventArgs e)

{

Console.WriteLine("In TypeResolveHandler");

AssemblyName assemblyName = new AssemblyName();

assemblyName.Name = "DynamicAssem";

// Create a new assembly with one module

AssemblyBuilder newAssembly =

Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);

ModuleBuilder newModule = newAssembly.DefineDynamicModule("DynamicModule");

// Define a public class named "ANonExistentType" in the assembly.

TypeBuilder myType = newModule.DefineType("ANonExistentType", TypeAttributes.Public);

// Define a method on the type to call

MethodBuilder simpleMethod = myType.DefineMethod("SimpleMethod", MethodAttributes.Public, null, null);

ILGenerator il = simpleMethod.GetILGenerator();

il.EmitWriteLine("Method called in ANonExistentType");

il.Emit(OpCodes.Ret);

// Bake the type

myType.CreateType();

return newAssembly;

}

static void Main()

{

// Hook up the event handler

Thread.GetDomain().AssemblyResolve +=new ResolveEventHandler(App.TypeResolveHandler);

// Find a type that should be in our assembly but isn’t

ObjectHandle oh = Activator.CreateInstance("DynamicAssem", "ANonExistentType");

Type mt = oh.Unwrap().GetType();

// Construct an instance of a type

Object objInstance = Activator.CreateInstance(mt);

// Find a method in this type and call it on this object

MethodInfo mi = mt.GetMethod("SimpleMethod");

mi.Invoke(objInstance, null);

Console.ReadKey();

}

}