Showing posts with label CLR. Show all posts
Showing posts with label CLR. Show all posts

Friday, March 2, 2018

Working with Files and Folders using PowerShell

In this article I’ll explain various PowerShell commands to perform File/Directory operations.

Get-ChildItem

You can use ‘Get-ChildItem’ command to get list of all the files and folder of given path.

Get-ChildItem -Path C:\PowerShell 

You can use below commands to list either files or folders only of given path

Get-ChildItem -Path C:\PowerShell -File

Get-ChildItem -Path C:\PowerShell -Directory

You can use below command to filter files and folders as per your requirement.

Get-ChildItem -Path C:\PowerShell -Filter *.pdf



You can you below command to list all the files and folders of give path recursively.

Get-ChildItem -Path C:\PowerShell -Recurse




You can also use Include or Exclude parameters with Get-ChildItem command to filter files.

Get-ChildItem -Path C:\PowerShell -Include "*.pdf" -Exclude "s*.PDF" –Recurse


New-Item
You can use ‘New-Item’ command to create new file or directory.

New-Item -Type File "C:\PowerShell\First1.txt"

New-Item -Type Directory "C:\PowerShell\MyFolder"




Copy-Item

You can use Copy-Item command to copy files and directories.

Copy-Item First1.txt Mitesh\First2.txt
Get-ChildItem -Path C:\PowerShell\Mitesh


Remove-Item

You can use Remove-Item command to delete files and directories.

Remove-Item c:\PowerShell\Mitesh\First2.txt
Get-ChildItem -Path C:\PowerShell\Mitesh


Rename-Item

You can use ‘Rename-Item’ command to rename file and directories.

Rename-Item First1.txt First3.txt
Get-ChildItem -Path C:\PowerShell\Mitesh




Move-Item
You can use ‘Move-Item’ command to move files and directories.

Move-Item c:\PowerShell\First3.txt C:\PowerShell\Mitesh\First1.txt
Get-ChildItem C:\PowerShell\Mitesh



Summary

Alias
Cmdlet
Description
dir
Get-ChildItem
List files and folders
ni
New-Item
Create new files and folders
copy
Copy-Item
Copy files and folders
del/rmdir
Remove-Item
Delete files and folders
ren
Rename-Item
Rename files and folders
move
Move-Item
Move files and folders


I hope you now have some basic understanding about PowerShell file and folder cmdlets to play around it. 

Thank you for reading this article. Please leave your feedback in comments below.

Reference –

See Also –

Saturday, February 24, 2018

Introduction to Windows PowerShell


As name suggest, Windows PowerShell is powerful command line shell. Windows PowerShell is built on top of .Net framework and internally uses .Net framework objects to run commands. PowerShell uses cmdlets (“command-let”) to perform various actions. PowerShell ships with hundreds of cmdlets and you can also create your own cmdlets as per your need. Windows PowerShell is installed by default with Windows 7 SP1 onwards editions.

PowerShell is a tool and can be used to perform day to day activities. This tool is very useful to developers and administrators to do their activities and they can write scripts or programs to ease their work. Like many other shells, Windows PowerShell allows you to access file/directory system and other computer/network/remoting related information.

In this article, I’ll explain how to start PowerShell and introduce some basic commands for you to start with PowerShell.


How to start PowerShell


For windows 10 – search PowerShell on search bar. (Pre-installed with windows 10)

Once you launch PowerShell below window will appear.


You can use directory commands like DIR, CD, CD\, CD.., MKDIR, RMDIR, COPY, DEL etc with PowerShell that you already using with Command Prompt.

When you execute these commands on PowerShell, internally PowerShell uses other cmdlets. For example, when you type DIR command on PowerShell window, it will internally use Get-ChildItem command to list all directories and files.

Get-Alias


You can use Get-Alias command to check which underlying command is mapped with alias.

Get-Alias dir

To check the entire alias you can type Get-Alias command without parameter. 

Get-Alias

Get-Command


You can use ‘Get-Command’ to check what all commands available in PowerShell. You can use ‘|more’ to view details in page wise manner.

Get-Command | more



You can also search available command using wildcards like below.

Get-Command *process

You can also use verb or noun parameters to get all the commands with specified verb or noun

Get-Command -Verb get | more

Get-Command -noun process

You can use below command to check total commands currently available in PowerShell.

(Get-Command).Count

Get-Help

You can use Get-Help command to get help about any commands in PowerShell.

Get-Help Get-ChildItem | more

If you would like to know help only about specific parameter of that command then you can use below command.

Get-Help Get-ChildItem -Parameter filter

You can get help of any command in all the details with example using below command.

Get-Help Get-ChildItem -Full |more

If your PowerShell help is not updated since long time then you can use below command to update help. This command will take some time to execute and download help.

Update-Help -Force

I hope you now have some basic knowledge about how to start PowerShell and how to search various commands and get help about them. 

Thank you for reading this article. Please leave your feedback in comments below.

Reference –


Wednesday, July 6, 2016

How to set default value to auto properties in C#?

There are many ways to initialize properties with default value. The most common way to set default value of any property is to set its local variable with default value. See below example.

Code –
public partial class DefaultValueProperties : Window
{
    private int age = 25;

    public int Age
    {
        get { return age; }
        set { age = value; }
    }

    public DefaultValueProperties()
    {
        InitializeComponent();

        Console.WriteLine(string.Format("Age - {0}", Age));
        Console.ReadLine();
    }

}

Output –
Age - 25

But when you are using auto-properties you don’t need to declare local variable for it since it’s internally taken care by CLR. So how to set default value to auto-properties? There is a way, you can set default value to auto-property using DefaultValue attribute. DefaultValue attribute is part of System.ComponentModel namespace. See below example.

Code –
public partial class DefaultValueProperties : Window
{
    //DefaultValue Attribute to set Default Value of Age property
    [DefaultValue(35)]
    public int Age { get; set; }

    //Constructor
    public DefaultValueProperties()
    {
        InitializeComponent();

        //This method sets value for all the properties reading from DefaultValue attribute
        InitializeDefaultProperties(this);
           
        Console.WriteLine(string.Format("Age - {0}", Age));
        Console.ReadLine();
    }

    public static void InitializeDefaultProperties(object obj)
    {
        foreach (PropertyInfo prop in obj.GetType().GetProperties())
        {
            foreach (Attribute attr in prop.GetCustomAttributes(true))
            {
                if (attr is DefaultValueAttribute)
                    prop.SetValue(obj, ((DefaultValueAttribute)attr).Value, null);
            }
        }
    }
}

Output –
Age - 35

As you can see in above example, Age property is decorated with DefaultValue attribute. DefaultValue attribute will not automatically set Property value. You need to manually set its value in constructor using refection. The good part of initializing value of property using Default Value is more consistent with design and less error prone. Since this approach involves reflection, this is not very efficient way to set default value to properties.

With C# 6.0, you can set default value to auto-properties even more better and easiest way. See below code.

Code - 
public partial class DefaultValueProperties : Window
{
    public int Age { get; set; } = 30;

    //Constructor
    public DefaultValueProperties()
    {
        InitializeComponent();

        Console.WriteLine(string.Format("Age - {0}", Age));
        Console.ReadLine();
    }
}

Output –
Age - 30


Hope you liked this article. Your feedback/comments are most welcome. Happy reading. J


References –

See Also –


Tuesday, December 13, 2011

How to create custom Application Domain?



Each .NET application by default creates one application domain. The default application domain created by CLR automatically when process (application) starts. Application domain is the runtime unit of isolation in which runs .net application in managed memory boundary. Application domain created under process and process can have one or more application domains. See below figures.

Process with single Application Domain


 Process with multiple Application Domains



Creating Custom Application Domains

AppDomain class is provided by .Net to create custom application domain. AppDomain.CreateDomain and AppDomain.Unload methods are provided to create and destroy custom application domain. Let’s have a look on below code.

public class MyClass
{
       public static void Main()
       {
              AppDomain appDomain = AppDomain.CreateDomain("My Domain");
appDomain.DoCallBack(new CrossAppDomainDelegate(HelloMethod));
Console.ReadLine();
AppDomain.Unload(appDomain);
       }
       public static void HelloMethod()
       {
              Console.WriteLine("Hello from " + AppDomain.CurrentDomain.FriendlyName);
       }     
}



In above example, AppDomain.CreateDomain method creates new application domain named “My Domain” and AppDomain.Unload method unloads or removes "My Domain". DoCallBack method is used to execute action on another application domain. The HelloMethod is static so DoCallBack (CrossAppDomainDelegate) delegate is referencing a static method.

AppDomain also provides ExecuteAaasembly method which will execute an assembly file.

AppDomain appDomain = AppDomain.CreateDomain("My Domain");
appDomain.ExecuteAssembly("WPFApplication1.exe");
Console.ReadLine();
AppDomain.Unload(appDomain);

When you create a new application domain within your current process, CLR keeps isolated one application domain from other. So each application domain has its own separate memory and objects which can’t clash with other application domain.

Sharing Data between application domains

We can share data between application domains using named slots. AppDomain instance provides SetData method to set data as name and data pair. While the GetData method retrieves an object (data) based on given name. Below are the signatures of both the methods. 

public void SetData(string name, object data);
public object GetData(string name);

Let’s have a look on below code.

public class MyClass
{
       public static void Main()
       {
              AppDomain appDomain = AppDomain.CreateDomain("My Domain");
appDomain.SetData("AppDomainOwner", "Mitesh Sureja");
appDomain.DoCallBack(new CrossAppDomainDelegate(HelloMethod));
Console.ReadLine();
AppDomain.Unload(appDomain);
       }
       public static void HelloMethod()
       {
              Console.WriteLine("Hello from " + AppDomain.CurrentDomain.FriendlyName);
       Console.WriteLine("Created By " + AppDomain.CurrentDomain.GetData("AppDomainOwner"));
       }     
}


As shown in above example, SetData method set name as “AppDomainOwner” and data as “Mitesh Sureja”. While GetData method retrieves data as an object based on given name.

Another way to share data between multiple application domains is using Remoting.

Hope you liked this post related to application domain. Please feel free to write your comments/feedback in comments section below.

See Also - 

Thursday, June 23, 2011

WPF Architecture


The Major components of WPF Architecture are Presentation Framework, Presentation Core and Media Integration Layer. The architecture divides in three major groups Managed Layer, Media Integration Layer (Unmanaged code) and Core Operating System.

Managed layer contains WindowsBase, Presentation Framework and Presentation Core assembly. Media Integration Layer contains Milcore(Media Integration Library Core)  and WindowsCodecs modules and both are unmanaged code. Media Integration Layer interacts with Direct3D and Direct3D interacts with Device Driver.



Presentation Framework – Holds top level WPF types includes Window, Controls, Styles, and Layout Panels etc. The code and controls written in WPF Application is mostly interacting with this layer.

Presentation Core – Holds base types such as UI Element and Visual. Almost all the controls you are directly interacting with are derived from these types. Presentation Framework uses most of the types defined in this layer.

MilCore – Media Integration Library is core rendering system. MIL is unmanaged code. This layer converts WPF elements into the format that Direct3D expects. Windows7 and Windows Vista uses this assembly to render its Desktop.

WindowsCodecs– provides supports for imaging like image processing, image displaying and scaling etc.

Direct3D – This layer is used to render graphics created using WPF Applications. 

Tuesday, May 17, 2011

Bindable Run - New Features in WPF 4.0



Bindable Run

Run element is used to display formatted text. Paragraph element uses Run element internally and Paragraph element mostly used in FlowDocuments.

In previous version of WPF, Run.Text element was not Bindable because it was implemented as normal CLR property but in WPF 4.0 Microsoft converted it to Dependency Property. So now Run.Text supports Binding and you can take full advantage of it. Please have a look on below example.

<Window x:Class="WPFTestApplication.BindableRun"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="BindableRun" Height="100" Width="300">
    <Window.Resources>
       <TextBlock Text="This is" x:Key="TextSample1" />
       <TextBlock Text=" Sample" x:Key="TextSample2" />
       <TextBlock Text=" Binding " x:Key="TextSample3" />
       <TextBlock Text=" on" x:Key="TextSample4" />
       <TextBlock Text=" Run." x:Key="TextSample5" />
    </Window.Resources>
    <StackPanel>
        <TextBlock Margin="10">
         <Run FontFamily="Arial" FontStyle="Italic"
             Text="{Binding Source={StaticResource TextSample1},
             Path=Text}" />
         <Run Background="Aqua"
             Text="{Binding Source={StaticResource TextSample2},
             Path=Text}" />
         <Run FontWeight="Bold" 
             Text="{Binding Source={StaticResource TextSample3},
             Path=Text}" />
         <Run Foreground="Brown"
             Text="{Binding Source={StaticResource TextSample4},
             Path=Text}" />
         <Run FontSize="25"
             Text="{Binding Source={StaticResource TextSample5},
             Path=Text}" />
        </TextBlock>
    </StackPanel>
</Window>

Output