Category Archives: Technology

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.

Convert rows to comma separated list and insert in a table

While performing one of my query diagnostics I had to gather some ids from one database server and use those ids in another. The best way was to gather all ids in a comma separated or in a proper list which can be used to insert into a temp table on another sql server.

I used the below query to gather the list of ids separated by ‘UNION ALL SELECT’

SELECT DISTINCT  CONVERT(varchar,ci.Id) + ' UNION ALL SELECT '
				  FROM dbo.Car c (NOLOCK)
				  INNER JOIN dbo.CarItem ci (NOLOCK) on c.CarId = ci.CarId
                   FOR XML PATH('')

The result produced an XML formatted file which I used in another server to insert in a temp table.

In the process I came to know of one restriction of the SQL Server select/insert that the maximum number of rows allowed are only 4096.

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

Running application from registry key path

This post for my reference:
I had a different version of MSAccess application and I had to run the application using Powershell script. The path of the application differs from computer to computer, since mine x64 bit the application resides in Program Files(x86) folder and in some other x32 bit machines the application is in Program Files. Moreover with different versions of Access the folder structure changes.

With the registry key it will target the latest version installed on your machine

@ECHO OFF
for /f "tokens=3*" %%x in ('reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\MSACCESS.exe" /v PATH') do set ACCESSM="%%x %%y"
"%ACCESSM%\MSACCESS.EXE \"Database Path\" /X macro-name"
@ECHO ON

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.

 

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.