Archive

Posts Tagged ‘.NET’

C# 4.0 “dynamic” versus “var”

November 26, 2008 Simeon Lobo Leave a comment

The C# language is evolving so fast that it does take effort to keep up with Anders Hejlsberg, C#’s designer at Microsoft :)  

Talking about the next version of C# in this video, Anders describes implementing a runtime operation called “dynamic” that eliminates all type safety for a variable. This essentially means that until the code is run, there is no way to determine if operations on the variable will fail.

There seems to be confusion about dynamic and var, so here is my 2 cents worth:

An example of using “var”:
//While using “var”, the compiler essentially figures out the
//type of the variable using type inferencing
var
a = “G’Day Mate!!!”;

//The below operation can be validated for errors at compile time (as opposed

//to runtime in the case of using “dynamic”)

a = a.ToUpper();


An example of using “dynamic”:
//Sample dynamic instantiation
dynamic<IHuman> dyn = GetObject();

//An attempt to run dynamic code

//Only after we run this code, we will know whether we have errors

dyn.Walk();

 

 

 

Categories: Technical, Theoretical Tags: ,

Start of a new era in computing – Microsoft Windows Azure

October 28, 2008 Simeon Lobo Leave a comment

Microsoft has finally announced it’s cloud computing platform at PDC ‘08. I found a very good introduction to the technology on Channel 9 from Manuvir Das, a Director in the Windows Azure team at Microsoft. The link to the video can be found here  http://channel9.msdn.com/posts/Charles/Manuvir-Das-Introducing-Windows-Azure/.

A Software Development Kit and CTP version has also been made available at Windows Azure’s official site at http://www.microsoft.com/azure/default.mspx 

The possibilities of the new platform seem endless and I can’t wait to test Azure’s Service Platform (see below).

Image from Azure's Official Site

Image from Azure's Web Site

Reusable Java and WCF Service Test Clients

October 1, 2008 Simeon Lobo 1 comment

I needed a reusable method to recursively test a WCF service host I had written from both the Java and .NET worlds. I wanted to be able to submit the test harness with service WSDL and pass in test parameters. 

Being familiar with Microsoft technology, I knew exactly where I could find a reusable WCF client test harness (located at %installDir%:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\WCFTestClient.exe). However when it came to locating a reusable test client in the Java world, I was stumped. A colleague at work directed me to download Eclipse for Java development but I easily ended up spending a few evenings learning to use the GUI and Java language specifics. Time pressures outside my work schedule did not allow me to code from scratch a generic Java test harness for the future.

By chance, I happened to stumble on Eclipse’s Web Services Explorer :). The Web Services Explorer was exactly what I was after!!!

It was now possible for me to seamlessly test services built from both Java and .NET environments without having to write a single line of code. The below screenshots display both the Eclipse Java EE Web Services Explorer tool and Microsoft’s WCF Test Client tool.

Eclipse Java Web Services Explorer

Eclipse Java Web Services Explorer

 

Microsoft WCF Test Client

Microsoft WCF Test Client

Categories: Technical Tags: ,

User Impersonation in WCF

September 30, 2008 Simeon Lobo Leave a comment

In some integration scenarios, impersonation is required, where a WCF service is required to assume the caller’s identity. Though this usually happens for a single call, the impersonation token could be retained for future use by the WCF servce. The reason impersonation is most relevant to integration scenarios is because all WCF service code running under the priviledges of the caller ensures that only resources and data available to the caller are made available.

I found this to be partcularly useful while integrating middle layers of various heterogeneous systems. I did not have to add additional integration code to ensure that application-level authorization was being implemented because I could be assured that the impersonated thread would be denied access if relevant permissions to resources have not been authorized in the target system.

Inline code to support impersonation in WCF is as shown below:

[OperationBehavior(Impersonation = ImpersonationOption.Required)]
public int AddNumbers(int i, int j)
{
    return (i + j);
}

To implement impersonation on all Operations, a behavior could be configured as shown below: 

<behaviors>
    <serviceBehaviors>
       
<behavior name=ServiceBehavior>
           
<serviceAuthorization principalPermissionMode=UseWindowsGroups
                                 
impersonateCallerForAllOperations=true>
           
</serviceAuthorization>
       
</behavior>
   
</serviceBehaviors>
</behaviors>

Categories: Technical Tags: ,

Summary of default WCF Bindings

September 10, 2008 Simeon Lobo Leave a comment

A binding in WCF is one of the most important concepts behind the WCF architecture itself. Developers can create their own bindings if the below default WCF bindings do not suit a purpose by extending CustomBinding.

First a definition of what a binding controls. A WCF binding controls the following:

  1. Transport (HTTP, MSMQ, Named Pipes, TCP)
  2. Channel (one-way, duplex, request-reply)
  3. Encoding (XML, binary, MTOM, JSON)
  4. Supported WS-* protocols

I found the below matrix extremely helpful when determining which implementation of default binding to use when determining a solution architecture.

Binding Configuration Security Default
Session
Transactions Duplex
basicHttpBinding Basic Profile 1.1 None No   -
wsHttpBinding WS Message Optional Yes  -
wsDualHttpBinding WS Message Yes Yes Yes
wsFederationHttpBinding WS-Federation Message Yes Yes No
netTcpBinding .NET Transport Optional Yes Yes
netNamedPipeBinding .NET Transport Yes Yes Yes
netMsmqBinding .NET Transport Yes Yes No
netPeerTcpBinding Peer Transport  -  - Yes
msmqIntegrationBinding MSMQ Transport Yes Yes  -

The above information has been condensed from Microsoft MSDN for ease of reference.

Categories: Technical Tags: ,

Demystifying SilverLight (Updated)

Microsoft have released and renamed versions of SilverLight thereby causing some confusion. The below release timeline may help,

  • SilverLight 1.0.20816 RTW (Release-to-Web): 05-Sep-2007
  • SilverLight 1.1.20926.0 Alpha Refresh (re-christened SilverLight 2.0): 05-Sep-2007
  • SilverLight 1.0.21115.0 Service Release: 20-Nov-2007 
  • SilverLight 2.0 RTM is scheduled to be released at the end of 2008

I also hope the following perspectives help with understanding where the technology currently stands, what is envisaged and what licensing restrictions (if any) exist.

SilverLight 1.0 – Brief Architectural Perspective:

  • A SilverLight 1.0 app invokes an embedded SilverLight control in a HTML web page that in turn locates and invokes a XAML file that contains the all-important Canvas object.
  •  All other entities in a SilverLight app are hosted within the Canvas object.
  • Each of these entities may have custom events associated to them.
  • The event handlers are implemented by developers who can invoke the Canvas object DOM via JavaScript only.
  • Data models are based on JSON and XML.   

SilverLight 1.0 – Licensing Restrictions: Free install as a plug-in for the browser. Browsers include IE 6 SP2, IE 7, FireFox and Safari. There is currently no support for Opera or Konqueror. 

SilverLight 2.0 – Brief Architectural Perspective:

  •  Following Microsoft’s strategy for implementing WPF/E (Windows Presentation Foundation Everywhere), SilverLight 2.0 is powered by atleast one running instance of a CoreCLR in a browser process, noting that there can be many more.
  • The CoreCLR is basically a mini .NET Framework that is so portable, that it can be run in the browser. This makes the architecture more consistent and a developer’s life easier as s/he can now write code in VB.NET or C#. The inclusion of the LINQ API implies seamless ORM and a robust data access API. It must be noted that currently there is no LINQ to XML support within SilverLight 1.1 Alpha Refresh.
  • Improving upon the scripting model in version 1.1, Microsoft have written managed wrappers for the Canvas object’s DOM access.  
  • Data models can now be based upon RSS, POX, JSON and XML. 
  • The SilverLight 2.0 Architectural Stack is as shown below:

SilverLight Architectural Stack 

SilverLight 2.0 – Licensing Restrictions:

  • SilverLight 1.1 was re-christened to SilverLight 2.0 in late November 2007.
  • SilverLight 2.0 is to be distributed as a free browser plug-in.
  • Microsoft is to announce the SilverLight 2.0 Beta release during MIX ’08 in early March 2008.
  • SilverLight 2.0 Beta 1 released on 05-Mar-2008.
  • SilverLight 2.0 Beta 2 is scheduled to be released during the 2nd quarter of 2008.
  • SilverLight 2.0 RTM is scheduled to be released at the end of 2008.
  • Visual Studio 2008 requires a license for development.
  • Visual Studio Tools for SilverLight is an empowering Visual Studio 2008 add-in that is currently (as of this writing) in Beta 1. Click here to download.
Categories: Analytical, Technical Tags: , ,

.NET Security: Class for Symmetric Encryption

December 24, 2007 Simeon Lobo Leave a comment

Reusable class that seamlessly abstracts Symmetric Encryption

using System;

using System.IO;

using System.Security.Cryptography;

using System.Text;

namespace Simeon.Lobo.Security

{

    public class SymmetricEncryption

    {

        public SymmetricEncryption()

        {

            this.Algorithm = SymmetricAlgorithm.Create();

            for (int num1 = 0; num1 < this.Algorithm.LegalKeySizes.Length; num1++)

            {

                this.KeySize = this.Algorithm.LegalKeySizes[num1].MinSize;

                if (this.Algorithm.ValidKeySize(this.KeySize))

                {

                    break;

                }

            }

            this.Algorithm.Mode = CipherMode.ECB;

        }

        public SymmetricEncryption(SymmetricAlgorithm Algorithm)

        {

            this.Algorithm = Algorithm;

            for (int num1 = 0; num1 < this.Algorithm.LegalKeySizes.Length; num1++)

            {

                this.KeySize = this.Algorithm.LegalKeySizes[num1].MinSize;

                if (this.Algorithm.ValidKeySize(this.KeySize))

                {

                    return;

                }

            }

        }

        public SymmetricEncryption(SymmetricAlgorithm Algorithm, int KeySize)

        {

            this.Algorithm = Algorithm;

            if (!this.Algorithm.ValidKeySize(KeySize))

            {

                for (int num1 = 0; num1 < this.Algorithm.LegalKeySizes.Length; num1++)

                {

                    this.KeySize = this.Algorithm.LegalKeySizes[num1].MinSize;

                    if (this.Algorithm.ValidKeySize(this.KeySize))

                    {

                        return;

                    }

                }

            }

        }

        private string ByteArrayToString(byte[] source)

        {

            string text1 = string.Empty;

            StringBuilder builder1 = new StringBuilder(source.Length);

            foreach (byte num1 in source)

            {

                builder1.Append((char)num1);

            }

            return builder1.ToString();

        }

        public string Decode(string Input)

        {

            return this.ByteArrayToString(Convert.FromBase64String(Input));

        }

        private string Decrypt(string plaintext, byte[] key, byte[] initializationVector)

        {

            string text1 = string.Empty;

            try

            {

                MemoryStream stream1 = new MemoryStream();

                CryptoStream stream2 = new CryptoStream(stream1, this.Algorithm.CreateDecryptor(key, initializationVector), CryptoStreamMode.Write);

                stream2.Write(this.StringToByteArray(plaintext), 0, plaintext.Length);

                stream2.FlushFinalBlock();

                stream2.Flush();

                stream2.Close();

                text1 = this.MemoryStreamToString(stream1);

                stream1.Close();

                return text1;

            }

            catch (Exception)

            {

                return “”;

            }

        }

        public string DecryptString(string Input, string Key)

        {

            return this.DecryptString(Input, Key, Key);

        }

        public string DecryptString(string Input, string Key, string IV)

        {

            try

            {

                if (Key.Length != 0)

                {

                    goto Label_0019;

                }

                return “”;

            Label_0010:

                Key = Key + Key;

            Label_0019:

                if (Key.Length >= this.KeySize)

                {

                    Key = Key.Substring(0, this.KeySize);

                    if (IV.Length == 0)

                    {

                        IV = Key;

                    }

                    while (IV.Length < 0×10)

                    {

                        IV = IV + IV;

                    }

                    IV = IV.Substring(0, 0×10);

                    byte[] buffer1 = this.StringToByteArray(Key);

                    byte[] buffer2 = this.StringToByteArray(IV);

                    return this.Decrypt(this.Decode(Input), buffer1, buffer2);

                }

                goto Label_0010;

            }

            catch (Exception)

            {

                return “”;

            }

        }

        public string Encode(string Input)

        {

            return Convert.ToBase64String(this.StringToByteArray(Input));

        }

        private string Encrypt(string plaintext, byte[] key, byte[] initializationVector)

        {

            string text1 = string.Empty;

            try

            {

                MemoryStream stream1 = new MemoryStream();

                CryptoStream stream2 = new CryptoStream(stream1, this.Algorithm.CreateEncryptor(key, initializationVector), CryptoStreamMode.Write);

                stream2.Write(this.StringToByteArray(plaintext), 0, plaintext.Length);

                stream2.FlushFinalBlock();

                stream2.Flush();

                stream2.Close();

                text1 = this.MemoryStreamToString(stream1);

                stream1.Close();

                return text1;

            }

            catch (Exception)

            {

                return text1;

            }

        }

        public string EncryptString(string Input, string Key)

        {

            return this.EncryptString(Input, Key, Key);

        }

        public string EncryptString(string Input, string Key, string IV)

        {

            try

            {

                if (Key.Length != 0)

                {

                    goto Label_0019;

                }

                return “”;

            Label_0010:

                Key = Key + Key;

            Label_0019:

                if (Key.Length >= this.KeySize)

                {

                    Key = Key.Substring(0, this.KeySize);

                    if (IV.Length == 0)

                    {

                        IV = Key;

                    }

                    while (IV.Length < 0×10)

                    {

                        IV = IV + IV;

                    }

                    IV = IV.Substring(0, 0×10);

                    byte[] buffer1 = this.StringToByteArray(Key);

                    byte[] buffer2 = this.StringToByteArray(IV);

                    return this.Encode(this.Encrypt(Input, buffer1, buffer2));

                }

                goto Label_0010;

            }

            catch (Exception)

            {

                return “”;

            }

        }

        private string MemoryStreamToString(MemoryStream source)

        {

            string text1 = string.Empty;

            return this.ByteArrayToString(source.ToArray());

        }

        private byte[] StringToByteArray(string s)

        {

            byte[] buffer1 = new byte[s.Length];

            for (int num1 = 0; num1 < s.Length; num1++)

            {

                buffer1[num1] = (byte)s[num1];

            }

            return buffer1;

        }

        public SymmetricAlgorithm Algorithm

        {

            get

            {

                return this.moAlgorithm;

            }

            set

            {

                this.moAlgorithm = value;

            }

        }

        public int KeySize

        {

            get

            {

                return this.mKeySize;

            }

            set

            {

                this.mKeySize = value / 8;

            }

        }

        private int mKeySize;

        private SymmetricAlgorithm moAlgorithm;

    }

}

 

 

Categories: Technical Tags: , ,

C# .NET Optional logging with StackTrace

December 22, 2007 Simeon Lobo 2 comments

In the event that simple application logging is required the below code could be used,

 

<!– application specific settings –>

<appSettings>

  <!– Use a value of either “OVERWRITE” or “APPEND” –>

  <add key=loggingType value=OVERWRITE />

</appSettings>

<!– Implementation –>

using System;

using System.Collections.Generic;

using System.Text;

using System.IO;

using System.Configuration;

using System.Diagnostics;

using System.Reflection;

    public class Log

    {

        private string _loggingType = String.Empty;

        private string _logFilePhyPath = String.Empty;

        public Log()

        {

            _loggingType = ConfigurationSettings.AppSettings["loggingType"];

            _logFilePhyPath = ConfigurationSettings.AppSettings["logFilePhyPath"];

        }

        public void WriteToErrorLog(string errorDesc, string errorStackTrace, string userName)

        {

            StackTrace stackTrace = new StackTrace();

            StackFrame stackFrame = stackTrace.GetFrame(1);

            MethodBase methodBase = stackFrame.GetMethod();

            if (_loggingType == “OVERWRITE”)

            {

                StreamWriter sw = new StreamWriter(_logFilePhyPath);

                sw.WriteLine(“========================\r\n” + “TIMESTAMP: “ + DateTime.Now + “\r\n\r\nUSER: “ + userName + “\r\n\r\nERROR LOCATION: “ + methodBase + “\r\n\r\nERROR DESCRIPTION: “ + errorDesc + “\r\n\r\nSTACKTRACE: “ + errorStackTrace + “\r\n========================”);

                sw.Close();

            }

            else if (_loggingType == “APPEND”)

            {

                StreamWriter sw = new StreamWriter(_logFilePhyPath, true);

                sw.WriteLine(“\r\n========================\r\n” + “TIMESTAMP: “ + DateTime.Now + “\r\n\r\nUSER: “ + userName + “\r\n\r\nERROR LOCATION: “ + methodBase + “\r\n\r\nERROR DESCRIPTION: “ + errorDesc + “\r\n\r\nSTACKTRACE: “ + errorStackTrace + “\r\n========================”);

                sw.Close();

            }

        }

    }

 

Categories: Technical Tags: ,

Stripping XML nodes imperatively

December 22, 2007 Simeon Lobo Leave a comment

Depending on the situation and in certain circumstances, XSL transformations may be unwieldy. The ability to parse and strip custom nodes from an XML fragment is very handy in the these situations. The below code can be modified and used for this purpose,

//Strip unwanted nodes
i = ProcessFile(Server.MapPath(“Extract.xml”), “AccessControl”, String.Empty, String.Empty);

//Strip unwanted attributes
xml = StripXmlAttribute(xml, “ThesaurusTerm”);

//Strip unwanted attributes
public string StripXmlAttribute(string inputString, string nodeNameToStripAllAttributes)
{
   
return System.Text.RegularExpressions.Regex.Replace(inputString, @”<( )*” + nodeNameToStripAllAttributes +
                                                       
“([^>])*>”, “<” + nodeNameToStripAllAttributes + “>”,
                                                       
System.Text.RegularExpressions.RegexOptions.IgnoreCase);

}

    /// <summary>
    /// This function removes a specified node from the specified XML file
    /// It can search for the node based solely on name
    /// OR it can also use an attribute name to further select a node
   
/// OR it can use the attribute value to pin-point a node
   
/// </summary>

    /// <param name=”xmlFileName”>The fully qualified name of the XML file to remove the node from</param>

    /// <param name=”nodeName”>The name of the node to remove</param>

    /// <param name=”attributeName”>Optional: Any attribute name of the node to be deleted</param>

    /// <param name=”attributeValue”>Optional: Any attribute value of the above attribute</param>

    /// <returns>a int to indicate the number of nodes removed</returns>

    public int ProcessFile(string xmlFileName, string nodeName, string attributeName, string attributeValue)

    {

        XmlDocument doc = new XmlDocument();

        int removedNodeCount = 0;

        // if the node name provided is null or empty, fail

        if ((nodeName == null) || (nodeName == string.Empty))

        {

            Console.WriteLine(“Invalid node name provided”);

            return 0;

        }

        try

        {

            doc.Load(xmlFileName);

            removedNodeCount = ScanAndDeleteNodes(doc.DocumentElement, nodeName, attributeName, attributeValue);

            // if had some node removals, save the file

            if (removedNodeCount > 0)

                doc.Save(xmlFileName);

        }

        catch (XmlException xe)

        {

            Console.WriteLine(“Error loading the document”);

            Console.WriteLine(xe.Message);

            return 0;

        }

        return removedNodeCount;

    }

    /// <summary>

    /// Recursive function to scan and delete child nodes

    /// </summary>

    /// <param name=”node”>the root node to scan</param>

    /// <param name=”nodeName”>The name of the node to remove</param>

    /// <param name=”attributeName”>Optional: Any attribute name of the node to be deleted</param>

    /// <param name=”attributeValue”>Optional: Any attribute value of the above attribute</param>

    /// <returns>a int to indicate the number of nodes removed</returns>

    private int ScanAndDeleteNodes(XmlNode node, string nodeName, string attributeName, string attributeValue)

    {

        // Delete matching children of this node

        int removedNodeCount = DeleteChildren(node, nodeName, attributeName, attributeValue);

        // get the remaining children of this node

        XmlNodeList childNodes = node.ChildNodes;

        foreach (XmlNode child in childNodes)

            removedNodeCount += ScanAndDeleteNodes(child, nodeName, attributeName, attributeValue);

        return removedNodeCount;

    }

    /// <summary>

    /// Deletes Matching children of the node passed in

    /// </summary>

    /// <param name=”rootNode”>the root node to scan the child nodes to be deleted</param>

    /// <param name=”nodeName”>The name of the node to remove</param>

    /// <param name=”attributeName”>Optional: Any attribute name of the node to be deleted</param>

    /// <param name=”attributeValue”>Optional: Any attribute value of the above attribute</param>

    /// <returns>An XmlNode if found, otherwise null</returns>

    private int DeleteChildren(XmlNode rootNode, string nodeName, string attributeName, string attributeValue)

    {

        ArrayList nodesToRemove = new ArrayList();

        // find the nodes requested by the user

        foreach (XmlNode node in rootNode.ChildNodes)

        {

            if (CheckNode(node, nodeName, attributeName, attributeValue))

                nodesToRemove.Add(node);

        }

        // remove the nodes

        if (nodesToRemove.Count > 0)

        {

            foreach (XmlNode node in nodesToRemove)

                rootNode.RemoveChild(node);

        }

        return nodesToRemove.Count;

    }

    private bool CheckNode(XmlNode node, string nodeName, string attributeName, string attributeValue)

    {

        // if we have a node name match

        if (node.Name == nodeName)

        {

            // now we have a node name match

            // try to see if attribute name is specified

            // if no attribute name was specified, this is our node

            if ((attributeName == null) || (attributeName == string.Empty))

                return true;

            // the user has atleast specified attibute name

            // so lets try to see if this element has that attribute or not

            XmlAttribute attr = node.Attributes[attributeName];

            if (attr != null)

            {

                // now we have an attribute name match

                // and we need to see if attribute value is specified

                if (attributeValue == null)

                {

                    // if no attribute value was specified, then the user does not care about the value.

                    // let’s give him this node

                    return true;

                }

                else if (attr.Value == attributeValue) // we have an attribute value

                {

                    // and we have a match too

                    return true;

                } // end of else if

            } // end of attr != null

        } // // end of nodeName match

        return false;

    }

 

 

 

Categories: Technical Tags: , ,