Category Archives: .Net 4.0

Dynamic ItemsSource in WPF

I was just playing around and I had an idea of binding data dyanmically to a telerik gridview. I have some 25 tables in a database and I give the option to select the table to the user and the gridview should display data from that table.

I used some help from stackoverflow.

  <telerik:RadGridView ItemsSource="{Binding TableData}" AutoGenerateColumns="True"/>

and a extension method for data reader

        public static IEnumerable<dynamic> AsEnumerable(this System.Data.IDataReader source)
        {
            if (source == null)
                throw new ArgumentNullException("source");
            var columns = Enumerable.Range(0, source.FieldCount).Select(source.GetName).ToList();

            while (source.Read())
            {
                
                dynamic dRow = new ExpandoObject();
                foreach (var column in columns)
                {
                    ((IDictionary<string, object>)dRow).Add(column, source[column]);
                }
                yield return dRow;
            }
        }

and bind it to the ObservableCollection. That’s it.

WPF TemplateSelector for contentTemplate

I wanted to dynamically change template of the tab content based on the tab selected. I used ContentTemplateSelector. It’s so simple:
Write a custom template selector inheriting DataTemplateSelector and override SelectTemplate method

    public class CustomTabItemSelector
        : DataTemplateSelector
    {
        public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
        {
            FrameworkElement element = container as FrameworkElement;
            if (element != null && item != null && item is object)
            {
                if (item.ToString().ToLower() == "related" || item.ToString().ToLower() == "linked")
                    return element.FindResource("TabContentQuestionDetails") as DataTemplate;
                else if(item.ToString().ToLower() == "comments")
                    return element.FindResource("TabContentComments") as DataTemplate;
                else
                    return element.FindResource("TabContentAnswers") as DataTemplate;
                
            }
            return null;
        }
    }

You need to declare DataTemplates in the ResourceDictionary or in the window resources or any where the element can be able to find the resource

    <DataTemplate x:Key="TabContentQuestions">
            <telerik:RadGridView
                             ItemsSource="{Binding DataContext.Questions, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"
                             Height="300" Width="Auto"
                             AutoGenerateColumns="False"
                            x:Name="QuestionGrid" AllowDrop="False"
                             >
                <telerik:RadGridView.Columns>
                    <telerik:GridViewDataColumn Header="Title" DataMemberBinding="{Binding Title}"/>
                </telerik:RadGridView.Columns>
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="PreviewMouseLeftButtonDown">
                        <i:InvokeCommandAction Command="{Binding DataContext.SelectedQuestionCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" CommandParameter="{Binding ElementName=QuestionGrid, Path=SelectedItem}">

                        </i:InvokeCommandAction>
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </telerik:RadGridView>
        </DataTemplate>

you need to add the reference to the customtemplateselector assembly and declare it in the xaml

//refering the assembly
 xmlns:ts="clr-namespace:SomeAssemblyNamespace;assembly:SomeReferencingAssemblyName"

//Declare the customselector
<ts:CustomTabItemSelector x:Key="myCustomTabItemSelector"/>

//Using the selector in the tabcontrol
<telerik:RadTabControl x:Name="SomeTab"
                       ContentTemplateSelector="{StaticResource myCustomTabItemSelector}"

Powershell module to MapNetworkDrive

At my work, every few days I have to change the user and connect to a network drive. The mapping process every time used to be little bit difficult. I have created some powershell modules which helped me in this process. This is for my reference and if it helps others that’s great:
I have powershell 2.0 so the modules need to be created in VS 2008 for binary type modules, one can create powershell scripts and imports them as modules too. I wrote it in VS 2008, you need to add reference to System.Management and System.Management.Automation.dll(this is in powershell folder).

I wrote 4 different commandlets in this module, each will perform a different functionality.
Get-Drives – Gets all the logical drives and network paths
Get-FreeDriveLetter – Gets the available drive letter in the descending order which can be used.
Map-AuthNetworkDrive – Maps the network drive with the provided credentials or default credentials
Map-DisconnectNetworkDrive – Removes the map

Get-Drives

    [Cmdlet(VerbsCommon.Get, "Drives")]
    public class GetDrives: PSCmdlet
    {
        protected override void ProcessRecord()
        {
            try
            {
                var drives = CommonMethods.GetDrives();

                this.WriteObject(drives, true);
            }
            catch (Exception ex)
            {
                this.WriteError(new ErrorRecord(ex, "1001", ErrorCategory.NotImplemented, null));
            }

        }
               
    }

    //CommonMethods.GetDrives
 internal static IEnumerable<object> GetDrives2()
        {
            IList<object> driveInfo = new List<object>();
            try
            {
                SelectQuery query = new SelectQuery("Select DeviceID, DriveType, ProviderName From Win32_LogicalDisk");
                ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
                foreach(ManagementObject disk in searcher.Get())
                {
                    driveInfo.Add(new { DeviceID = disk["DeviceID"], DriveType = (DiskType)disk["DriveType"], ProviderName = disk["ProviderName"] });
                }
            }
            catch (Exception ex)
            {
                throw ex;

            }

            return driveInfo;
        }

  public enum DiskType : uint
    {
        Unknown = 0,
        RemovableDisk = 2,
        LocalDisk = 3,
        NetworkDrive = 4,
        CompactDisk = 5,
        RAMDisk = 6
    }

Get-FreeDriveLetter

   [Cmdlet(VerbsCommon.Get, "FreeDriveLetter")]
    public class GetFreeDriveLetter : PSCmdlet
    {
        protected override void ProcessRecord()
        {
            try
            {
                string freeDrive = CommonMethods.GetFreeDriveLetter();

                this.WriteObject(freeDrive);
            }
            catch (Exception ex)
            {
                this.WriteError(new ErrorRecord(ex, "1001", ErrorCategory.NotImplemented, null));
            }
        }
    }

   //in CommonMethods.GetFreeDriveLetter method
      internal static string GetFreeDriveLetter()
        {
            string freeDrive = "";
            string[] driveLetters = { "D:", "E:", "F:", "G:", "H:", "I:", "J:", "K:", "L:", "M:", "N:", "O:", "P:", "Q:", "R:", "S:", "T:", "U:", "V:", "W:", "X:", "Y:", "Z:" };
            var drives = System.IO.DriveInfo.GetDrives().Select(x => x.Name.Replace("\\", ""));
       
            foreach (var s in driveLetters.Reverse())
            {
                if (drives.Contains(s))
                {
                    freeDrive = "";
                }
                else
                {
                    freeDrive = s;
                    break;
                }
            }

            return freeDrive;
        }

For map and unmap I used Windows Script Host object model reference(IWshRuntimeLibrary)

     [Cmdlet("Map","AuthNetworkDrive")]
    public class MapNetworkDrive: PSCmdlet
    {
        [Parameter(Mandatory=true, Position=0,ValueFromPipeline=false)]
        public string UNCPath { get; set; }

        [Parameter(Mandatory=false, Position=1)]
        public PSCredential Credential { get; set; }

        protected override void ProcessRecord()
        {
            try
            {
                WshNetwork network = new WshNetwork();
                if (Credential == null)
                {
                    network.MapNetworkDrive(CommonMethods.GetFreeDriveLetter(), UNCPath, false);
                }
                else
                {
                    network.MapNetworkDrive(CommonMethods.GetFreeDriveLetter(), UNCPath, true, Credential.UserName, Credential.GetNetworkCredential().Password);
                }
            }
            catch (Exception ex)
            {
                this.WriteError(new ErrorRecord(ex, "1001",ErrorCategory.MetadataError, null));
            }
        }
    }

    [Cmdlet("Map", "DisconnectNetworkDrive")]
    public class UnMapNetworkDrive : PSCmdlet
    {
        [Parameter(Mandatory=true, Position=0)]
        public string DriveName { get; set; }

        protected override void ProcessRecord()
        {

            try
            {
                
                    IWshRuntimeLibrary.WshNetwork network = new IWshRuntimeLibrary.WshNetwork();
                    network.RemoveNetworkDrive(DriveName, true, true);
                
            }
            catch (Exception ex)
            {
                this.WriteError(new ErrorRecord(ex, "1001", ErrorCategory.MetadataError, null));
            }
        }
    }

Once the build, you can import the module from powershell ise

Import-Module 'module dll path'

this will be available for that session. One can copy to the powershell module path, so that it can be available all the time.

Regular expression reference

Regular expression reference table list

Regular ExpressionExplanation
a-zmatches small letters starting from 'a' - 'z'
A-Zmatches capital letters starting from 'A' - 'Z'
.dot(.) represents single wildcard character (joker in a card game)
\escape character. To escape the actual representation and represent actual character
^is used to negate a batch of character like [^a-z] -- matches the characters other than 'a' - 'z'
\ddigits
{m, n}m, n are integers here. represents any preceding character appears atleast 'm' times and atmost 'n' times. ex: a[1, 3] 'a' can appear 1-3 times
*represents the preceding expression can occur from 0 to any number of times. ex: \d* any digit can appear from 0 to any number of times
+represents the preceding expression will occur atleast once. ex: \d+ - digit will appear atleast once.
?represents the preceding character is optional(it may occur). ex: a? -- the match may have 'a' & ab?c -- 'b' is optional.
\wrepresents alphanumeric [a-zA-Z0-9_]
-space
\ttab
\nnewline
\rcarriage return
\sspace (represents space, tab, newline or carriage return)
^....$^ starting an expressiong and $ represents ending of the expression
()capturing part
|OR (cats|dogs|birds) - cats or dogs or birds
\bboundary between a word and a non-word character.
Any expression written in CAPITAL LETTER represents opposite of actual definition
ex: \D - non digits
\W - non alphanumeric
\S - non whitespace
Referencing any captured groups using parenthesis('()')
--- there can be many groups clubbed together and to refer each group use
ex: (\d*\.([,\d*]?))*$
\0 - full matched text
\1 - group 1
\2 - group 2

Nuget package listing fails on the machine behind corporate firewall

I was unable to browse packages from visual studio, Package Manager Console or GUI. The message would be no packages found in the current source. Using Fiddler, I am opted to watch the traffic being sent, and all HTTP requests are successfully made and completed. When searching for “Log” I get a single request for the count of items (45), and then the follow up filter request with all 45 package items in detail. To verify if something within our corporate network was blocking the request, I also made each of the requests from Internet Explorer, and both were successful.

I realised that the response type is different and seems our corporate firewall policy is blocking them. I browsed for the solution and I found the it in Nuget Issue tracker which is helpful:
You can get around it with Fiddler2 and FiddlerScript. Edit the FiddlerScript, find the method “OnPeekAtResponseHeaders” and add the following code fragment before the method closing brace.


  if (oSession.HostnameIs("packages.nuget.org") && oSession.oResponse["Content-type"].Contains("text/xml")) {
        oSession.oResponse["Content-type"] = oSession.oResponse["Content-type"].Replace("text/xml", "application/atom+xml");
    }

This will modify the response type. Thank you Nuget guys…

Creating a fixedwidth text file in excel using macro

To the data if you know the width that need to be specified set the columnwidths for each column, if you want all the columns to a fixed width you can select all the data columns and set theri their widths.

  Select the Developer>Visual Basic in the excel file

select insert module and write the method

Eg:-


Sub ExportText()
    ' Modify as needed
    Const strFile = "C:\Export\Test.txt"

    Dim r As Long
    Dim m As Long
    Dim c As Long
    Dim n As Long
    Dim f As Long
    Dim lngMaxWidth As Long
    Dim strLine As String
    Dim lngColWidth As Long

    m = Cells.Find(What:="*", SearchOrder:=xlByRows, _
        SearchDirection:=xlPrevious).Row
    n = Cells.Find(What:="*", SearchOrder:=xlByColumns, _
        SearchDirection:=xlPrevious).Column
    ReDim lngWidths(1 To n) As Long
    For c = 1 To n
       ' lngMaxWidth = 0
      '  For r = 1 To 100
       '     lngColWidth = Cells(r, c).ColumnWidth
        '    If Len(Cells(r, c).Text) > lngMaxWidth Then
         '       lngMaxWidth = Len(Cells(r, c).Text)
          '  End If
        'Next r
       
       
        lngWidths(c) = Cells(1, c).ColumnWidth
        'lngMaxWidth + 1
    Next c
    f = FreeFile
    Open strFile For Output As #f
    For r = 1 To m
        strLine = ""
        For c = 1 To n
            strLine = strLine & Cells(r, c).Text & _
                Space(lngWidths(c) - Len(Cells(r, c).Text))
        Next c
        Print #f, strLine
    Next r
    Close #f
End Sub

Service and Operation behaviors in WCF

Behaviors in WCF are used to say how it’s going to behave at the service level, endpoint level or operation level. ServiceBehaviorAttribute  is used to apply behaviors at the service level. To apply behaviors at operation level use OperationBehaviorAttribute.

ServiceBehaviorAttribute: This attribute can be applied only to service implementations. It has properties that are useful in enabling a specified feature for the service.

  •  AddressFilterMode: specifies the type of filter that the dispatcher system uses to locate the endpoint that handles requests.

  1. Any:  matches on any address of an incoming message
  2. Exact: exact match on the address of an incoming message
  3. Prefix: prefix match on the address of an incoming message
  • AutomaticSessionShutdown: allows to automatically close the session when the channel is closed and the service has finished processing any remaining messages.(true/false)
  • ConcurrencyMode: controls the internal threading model, enabling support for reentrant or multithreaded services.

  1. Single: Service instance is single-threaded and does not accept reentrant calls (other messages must wait)
  2. Reentrant:Service instance is single-threaded accepts reentrant calls. the reentrant service accepts calls when you call another service (make the object state consistent before callouts and make operation-local data is valid after callouts.)
  3. Multiple: service is a multi-threaded. (Synchronization need to be maintained).
  • ConfigurationName: used to declare a name for use in the name attribute of the <service> element in the config file.
  • IgnoreExtensionDataObject: enables the run time to ignore extra serialization informatin that is not required to process the message.(true/false).
  • IncludeExceptionDetailInFaults: enables the unhandled exceptions in a service to return in SOAP faults. Used for debugging purposes.(true/false)
  • InstanceContextMode: specifies whether and when services and their service objects are to be recycled during an exchange with a client.

  1. persession: new instance object is created for each session.
  2. percall: new instance object is created prior to and recycled subsequent to each call.(defaults for no session)
  3. Single: only one instance object is used for all incoming calls.
  • MaxItemsInObjectGraph: used to limit on the number of items in an object graph that are serialized.(number)
  • Name and Namespace: controls the name and namespace for WSDL.
  • ReleaseServiceInstanceOnTransactionComplete: specifies whether the service object is recycled when a transaction completes.(true/false)
  • TransactionAutoCompleteSessionClose: specifies whether outstanding transactions are completed when the session closes.(true/false)
  • TransactionIsolationLevel: specifies the transaction isolation level that the contract supports.(isolationlevel of)

  1. Serializable: volatile data can be read but not modified, and no new dat can be added during the transaction.
  2. RepeatableRead:volatile data can be read but not modified during the transaction. New data can be added during the transaction.
  3. ReadCommitted: volatile data cannot be read during the transaction, but can be modified.
  4. ReadUncommitted: volatile data can be read and modified during the transaction.
  5. snapshot:volatile data can be read. Before a transaction modified data, it verified if another transaction has changed the data after it was intitially read. If the data has been updated, an error is raised. This allows a transaction to get to the previously committed value of the data.
  6. chaos: pending changes from more highly isolated transactions cannot be overwritten.
  7. upspecified:a different isolation level than the one specified is being used, but the level cannot be determined. An exception is thrown if this value is set.
  • TransactionTimeout: specifies the time period within which a transaction must complete or it aborts.
  • UseSynchronizationContext: indicates whether to synchronize inbound method calls with the user interface thread automatically.
  • ValidateMustUnderstand: informs the system whether it should confirm that SOAP headers marked as MustUnderstand have, in fact, been understood.

 

Windows Communication Foundation

Since WCF has been introduced in .Net 3.0, it’s keep growing and the features available are also improving. Lets see how WCF works.

Actually there are many reasons to communicate one application to another or utilize resources available in the market. There are different connection scenarios for this. Webservices is one such where one application exposes a service which can consumed by clients which are able access that. There can be one-way, request-reply or duplex types of communications.
Earlier Microsoft shipped different tools for each type of communications. So it’s really a correct solution. So they introduced WCF which is able to perform all the major communication types available in the market.
The process of WCF is simple:
Typically, for any client to consume the service what it needs is
1. Where to find the service?
2. How to connect the service?
3. And What are the operations available from the service?
With the WCF, they have provided different bindings(System Provided) to define the connectivity part

BindingConfiguration ElementDescription
BasicHTTPBinding<basicHttpBinding>This binding is more suitable for communication with basic WS-Basic profile webservices. Similar to ASP.Net Webservices (ASMX). This uses HTTP as transport protocol and MTOM(xml) as default message encoding. Supports Transport, Message and Mixed security modes. Will not support Sessions and Transactions. Supports buffered streaming.
WSHTTPBinding<wsHttpBinding>Provides secure and interoperable communication (WS*), suitable for non duplex connections. Uses SOAP protocol, and text as default encoding. Supports security (Transport, Mixed, Message modes), by default at message mode. Supports Sessions (Reliable, Security) by default none.
WSDualHttpBinding<wsDualHttpBinding>Provides secure, interoperable, reliable and duplex communication contract with text encoding by default. Supports Security at message level by default and only security mode available. Supports sessions(Reliable, Security) with reliablesession as default.
WSFederationHttpBinding<wsFederationHttpBinding>This binding is basically used federation communication. supports security(Message, Mixed, none) at Message level by default. Supports sessions (Reliable, Security). Transactions are allowed.
NetHttpBinding<netHttpBinding>This binding is basically designed for consuming HTTP or websocket services and uses binary encoding by default. Websockets are only supported on Windows 8. NetHttpBinding will check for request-reply or duplex contract and change its behavior accordingly. It will use HTTP for request-reply and websockets for duplex.
NetHttpsBinding<netHttpsBinding>A secure netHttpBinding.
NetTcpBinding<netTcpBinding>This binding replaces the earlier .net remoting. This secure way of communicating between two WCF capable services.
NetNamedPipeBinding<netNamedPipeBinding>This binding generates a run-time communication stack by default, which uses transport security, named pipes for message delivery and a binary message encoding. This is appropriate for on machine WCF communications. It also supports transactions.
NetMsmqBinding<netMsmqBinding>This binding provides support for queuing by using Message Queuing (MSMQ) as a transport and enables support for loosely-coupled applications, failure isolation, load leveling and disconnected operations.
NetPeerTcpBinding<netPeerTcpBinding>This binding provides a secure connection for multiple machine communication. provides support for the creation of peer networking applications that use a TCP-level peer-to-peer mesh infrastructure. Each PeerNode instance can host multiple peer channels defined with this binding type.
MsmqIntegrationBinding<msmqIntegrationBinding>This binding is suitable for cross-machine communication between a WCF application and existing MSMQ applications.
WebHttpBinding<webHttpBinding>WCF allows to expose WCF web services through HTTP requests that use "plan old XML" (POX) style messaging instead of SOAP-based messaging. For clients to communicate with a service using HTTP requests, an endpoint of the service must be configured with the WebHttpBinding that has the WebHttpBehavior attached to it. The WCF also requires that the individual service operations are annotated with WebGet or WebInvoke attributes.

Implementing an MVC action filter to throttle requests

The following is from StackOverflow , for my future reference

    /// <summary>
/// Decorates any MVC route that needs to have client requests limited by time.
/// </summary>
/// <remarks>
/// Uses the current System.Web.Caching.Cache to store each client request to the decorated route.
/// </remarks>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class ThrottleAttribute : ActionFilterAttribute
{
    /// <summary>
    /// A unique name for this Throttle.
    /// </summary>
    /// <remarks>
    /// We'll be inserting a Cache record based on this name and client IP, e.g. "Name-192.168.0.1"
    /// </remarks>
    public string Name { get; set; }

    /// <summary>
    /// The number of seconds clients must wait before executing this decorated route again.
    /// </summary>
    public int Seconds { get; set; }

    /// <summary>
    /// A text message that will be sent to the client upon throttling.  You can include the token {n} to
    /// show this.Seconds in the message, e.g. "Wait {n} seconds before trying again".
    /// </summary>
    public string Message { get; set; }

    public override void OnActionExecuting(ActionExecutingContext c)
    {
        var key = string.Concat(Name, "-", c.HttpContext.Request.UserHostAddress);
        var allowExecute = false;

        if (HttpRuntime.Cache[key] == null)
        {
            HttpRuntime.Cache.Add(key,
                true, // is this the smallest data we can have?
                null, // no dependencies
                DateTime.Now.AddSeconds(Seconds), // absolute expiration
                Cache.NoSlidingExpiration,
                CacheItemPriority.Low,
                null); // no callback

            allowExecute = true;
        }

        if (!allowExecute)
        {
            if (String.IsNullOrEmpty(Message))
                Message = "You may only perform this action every {n} seconds.";

            c.Result = new ContentResult { Content = Message.Replace("{n}", Seconds.ToString()) };
            // see 409 - http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
            c.HttpContext.Response.StatusCode = (int)HttpStatusCode.Conflict;
        }
    }
}
  

Sample Usage

    [Throttle(Name="TestThrottle", Message = "You must wait {n} seconds before accessing this url again.", Seconds = 5)]
public ActionResult TestThrottle()
{
    return Content("TestThrottle executed");
}
  

You can also implement input throttling at the web server. With IIS 7.0 or 7.5, consider
using Dynamic IP restrictions, which are available for download at http://www.iis.net/
download/dynamiciprestrictions.

Planning Role Management in ASP.Net

When planning role management, follow these best practices:
1> Use Windows authentication for intranet applications when users have Active Directory domain accounts. This provides single sign-on for users and centralizes account management. If you use Windows authentication, ASP.Net uses roles to represent group memberships.
2> If you must create accounts for users separate from their Active Directory domain accounts, work with systems administrators to include the application’s role management in their account management process. For example, when a user leaves the organization, systems administrators will need to remove both the user’s Active Directory domain account and the application account.
3> Never assign privileges to an individual user. Instead, add users to roles, and assign privileges to those roles. If an employee leaves the organization, you only need to remove the user from the role rather than modifying how privileges are assigned.
4> Create separate roles for different management tasks. For example, instead of creating roles for just users and administrators of a blog application, create separate roles for readers, writers, editors, content approvers, and website managers. Even though it might require you to add users to multiple roles, having more granular roles simplifies delegating tasks if more flexibility is required in the future.
5> Always derive new security classes from existing .NET classes. Microsoft has carefully reviewed and tested the security components of the .NET framework. This does not mean the .NET framework does not contain security weaknesses; all code does. However, the .NET framework’s extensive review and testing helps to make them more secure than classes written by individual developers.