Category Archives: Microsoft

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.

Getting Started with ASP.NET vNext

Article posted on Asp.Net vNext Overview

Getting Started with ASP.NET vNext
By
Mike Wasson |

The next version of ASP.NET (“ASP.NET vNext”) has been re-designed from the ground up. The goal is to create a lean and composable .NET stack for building modern cloud-based apps.

Here are some of the features of ASP.NET vNext:

  • vNext includes new cloud-optimized versions of MVC, Web API, Web Pages, SignalR, and Entity Framework.
  • MVC, Web API, and Web Pages will be merged into one framework, called MVC 6. The new framework removes a lot of overlap between the existing MVC and Web API frameworks. It uses a common set of abstractions for routing, action selection, filters, model binding, and so on. You can use the framework to create both UI (HTML) and web APIs.
  • ASP.NET vNext apps can use a cloud-optimized subset of .NET vNext. This subset is factored for server and web workloads, has a smaller footprint than the full .NET vNext, and supports side-by-side deployment.
  • MVC 6 has no dependency on System.Web. The result is a leaner framework, with faster startup time and lower memory consumption.
  • vNext will support true side-by-side deployment. If your app uses the cloud-optimized subset of .NET vNext, you can bin deploy all of your dependencies, including the .NET vNext (cloud optimized) packages. That means you can update your app without affecting other applications on the same server.
  • vNext is host agnostic. You can host your app in IIS, or self-host in a custom process. (Web API 2 and SignalR 2 already support self-hosting; ASP.NET vNext brings this same capability to MVC.)
  • Dependency injection is built into the framework. Use your preferred IoC container to register dependencies.
  • vNext uses the Rosyln compiler to compile code dynamically. You will be able to edit a code file, refresh the browser, and see the changes without rebuilding the project.
  • vNext is open source and cross platform.

In order to accomplish these goals, ASP.NET vNext contains breaking changes. The current frameworks (Web Forms 5, MVC 5, Web API 2, Web Pages 3, SignalR 2, and Entity Framework 6) will continue to ship in Visual Studio, and will be fully supported in .NET vNext.

This overview is designed to get you started with ASP.NET vNext. Because vNext is still an early preview, I won’t walk through creating an entire real-world application. Instead, I want to highlight some of the features and show enough code to get you started.

The overview assumes you are familiar with either MVC 5 or Web API 2. If not, here is some terminology that is used in ASP.NET MVC.

  • A controller handles HTTP requests and executes application logic.
  • Actions are methods on a controller that get invoked to handle HTTP requests. The return value from an action is used to construct the HTTP response.
  • Routing is the mechanism that selects which action to invoke for a particular HTTP request, usually based on the URL path and the HTTP verb.
  • A view is a component that renders HTML. Controllers can use views when the HTTP response contains HTML.
  • A model is an object that represents the domain data in your application. Typically an app either renders the model as HTML, or serializes the model into a data format such as JSON.
  • Razor syntax is a simple programming syntax for embedding server-based code in a web page.

I’ve defined some of these terms in a way that is specific to ASP.NET. For example, controllers have a particular purpose in ASP.NET MVC, but “model-view-controller” is a more general pattern, used by many frameworks.

Getting Started with ASP.NET vNext

Currently, there is no Visual Studio integration for ASP.NET vNext, so you will build and run applications from the command line.

Use kvm (the version manager) to get the latest version of the runtime. Follow the instructions on the project wiki.

A minimal vNext project contains two files:

  • project.json. This file lists the dependencies for the application.
  • A startup class.

For now, the best way to create a project.json file is to copy the example from HelloMvc sample.

The startup class is where you configure the HTTP request pipeline for your application. Here is a simple example.

using Microsoft.AspNet.Builder;

public class Startup
{
    public void Configure(IBuilder app)
    {
        app.UseWelcomePage();
    }
}

By default , the hosting environment expects the startup class to be named Startup. The startup class must contain a method named Configure with the signature shown here. Inside this method, use the IBuilder interface to configure the application.

The UseWelcomePage methods adds a middleware component that just displays a welcome page. The welcome page is useful for diagnostic purposes, to make sure your project is configured and running correctly.

To start the application, open a command prompt and type the following commands:

kpm restore
k web

The kpm restore command resolves the dependencies listed in the project.json file, and downloads the necessary NuGet packages. The k web command starts the HTTP listener.
Notice there is no explicit build step. The k web command compiles the code on the fly. After you install the NuGet packages, you can make changes to the code and run k web again, without running kpm restore.

Next, launch a browser and navigate to http://localhost:5001. You should see the welcome page.

The web command is defined in the project.json file:

  "commands": {
    "web": "Microsoft.AspNet.Hosting server=Microsoft.AspNet.Server.WebListener server.urls=http://localhost:5001"
  },

This command starts the hosting environment and listens on the specified localhost address. You can edit the project.json file to use a different port number.

Serving Static Files

The welcome page is not too interesting, so lets’s enable the app to serve static files. Add the following entry to the “dependencies” section of the project.json file:

"Microsoft.AspNet.StaticFiles": "0.1-alpha-build-0402"

Modify the Startup class as follows.

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.StaticFiles;

public class Startup
{
    public void Configure(IBuilder app)
    {
        app.UseStaticFiles();
    }
}

Getting Started with MVC 6

In the rest of this overview, we’ll explore some of the features of MVC 6. To enable MVC, modify the Startup class as follows.

using Microsoft.AspNet.Routing;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;

public class Startup
{
    public void Configure(IBuilder app)
    {
        app.UseServices(services =&gt;
        {
            services.AddMvc();
        });

        app.UseMvc(routes =&gt;
        {
            routes.MapRoute(
                name: "Default",
                template: "{controller}/{action}/{id?}",
                defaults: new { controller = "Home", action = "Index" });
        });

    }
}

This code enables MVC and defines a route. If you’ve used earlier versions of MVC, the MapRoute method should look familiar. For comparison, here are the same routes defined in MVC 5 and MVC 6:

// MVC 5 route
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index",
        id = UrlParameter.Optional }
);

// MVC 6 route
routes.MapRoute(
    name: "Default",
    template: "{controller}/{action}/{id?}",
    defaults: new { controller = "Home", action = "Index" }
);

The ‘?’ character in the template means the {id} segment is optional.

Next, add a controller class. The following controller defines a single action named Index that returns a view.

using Microsoft.AspNet.Mvc;

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

Except for the namespace, this code would compile in MVC 5.

Now add a view. Create a file named ./Views/Home/index.cshtml and paste in the following code.

@{
  var message = "Hello World";
}

<!DOCTYPE html>

<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>Index Page</title>
</head>
<body>
  <h1>@message</h1>
  <p>Index page</p>
</body>
</html>

I included a @message variable just to show that this is a Razor file and not just static HTML.

Here is the file structure for the project:

.\HomeController.cs
.\project.json
.\Startup.cs
.\Views\Home\Index.cshtml

Run the app by using the k web command, and then navigate to http://localhost:5001. You should see the HTML that is rendered by the Index view.

View Models

You can pass a model to the view. Let’s add a model class:

public class MessageModel
{
    public string Message { get; set; }
}

Modify the action by passing an instance of MessageModel to the View method:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MessageModel { Message = "Hello ASP.NET" };
        return View(model);
    }
}

Update index.cshtml to refer to the model.

<!DOCTYPE html>

<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>Hello World Page</title>
</head>
<body>
  <h1>@Model.Message</h1>
</body>
</html>

Now when you run the app, “Hello ASP.NET” is rendered inside the H1 tag.

Creating Web APIs and REST-Style Actions

If the route template does not include {action}, the framework uses the HTTP verb to select the action name. This style of routing is similar to convention-based routing in the current version of ASP.NET Web API, and is useful for REST-style APIs.

Here is an example of a route template without an {action} variable.

app.UseMvc(routes =&gt;
{
    routes.MapRoute("ApiRoute", "{controller}/{id?}");
});

Using this route template, the action name maps to the HTTP verb in the request. For example, a GET request will invoke a method named Get, a PUT request will invoke a method named Put, and so forth. The {controller} variable still maps to the controller name.

The following controller uses this style of routing.

using Microsoft.AspNet.Mvc;

public class ValuesController : Controller
{
    // GET /values
    public string Get()
    {
        return "Values";
    }

    // GET /values/1
    public string Get(int id)
    {
        return "Value " + id.ToString();
    }

    // POST /values
    public ActionResult Post()
    {
        return new HttpStatusCodeResult(201);
    }
}

The following table shows the web API that is defined by ValuesController.

Request Method URI Path Controller Action
GET /values Get
GET /values/1 Get(id)
POST /values Post

The two Get actions both return strings. In that case, the framework writes the string into the body of the HTTP response, and sets the Content-Type header to “text/plain”. For example, if you send a GET request to /values/1, the response will look similar to the following.

HTTP/1.1 200 OK
Content-Type: text/plain
Server: Microsoft-HTTPAPI/2.0
Date: Wed, 30 Apr 2014 00:16:38 GMT
Content-Length: 7

Value 1

The Post action returns an HttpStatusCodeResult. The framework translates this into an HTTP status code.

HTTP/1.1 201 Created
Content-Length: 0
Server: Microsoft-HTTPAPI/2.0
Date: Wed, 30 Apr 2014 00:18:58 GMT

If you are familiar with ASP.NET Web API, you may have noticed that ValuesController derives from Controller, not ApiController. That’s because vNext does not have a separate controller class for web APIs.

In the current ASP.NET framework, MVC 5 and Web API 2 use completely different classes and namespaces. That means a controller is either an MVC controller or a Web API controller. Web API controllers use separate routes, and they can’t use MVC filters or MVC model binders.

One goal of ASP.NET vNext is to merge MVC and Web API into a single framework, which shares a single pipeline and uses the same routing, action selection, filters, model binding, and so forth. The result will be a more consistent programming model, and code that is more re-usable.

Returning JSON

To serialize an object into JSON format, call Controller.Json. This method returns a JsonResult, which is an action result that serializes an object to JSON format. For example, let’s add a model class named Movie.

public class Movie
{
    public string Title { get; set; }
    public int Year { get; set; }
    public string Genre { get; set; }
}

Here is a controller that returns a list of movies in JSON format.

using Microsoft.AspNet.Mvc;

public class MoviesController : Controller
{
    public ActionResult Get()
    {
        var movie = new Movie
        {
            Title = "Maximum Payback", Year = 1990, Genre = "Action"
        };
        return Json(movie);
    }
}

The response from the Get action will look similar to the following.

HTTP/1.1 200 OK
Content-Type: application/json
Server: Microsoft-HTTPAPI/2.0
Date: Fri, 02 May 2014 20:39:25 GMT
Content-Length: 120

[{"Title":"Maximum Payback","Year":1990,"Genre":"Action"},{"Title":"Fatal Vengeance 2","Year":2012,"Genre":"Action"}]

Note: The preview release does not support content negotiation yet.

Areas

Areas are a way to group controllers, models, and views. In previous versions of MVC, you register areas by calling AreaRegistration.RegisterAllAreas. Area controllers are placed in a special Areas folder.

In MVC 6, you create a route template with an {area} parameter, and then decorate area controllers with the [Area] attribute. The following code defines an area route.

app.UseMvc(routes =&gt;
{
    routes.MapRoute(
        name: "AreasRoute",
        template: "{area}/{controller}/{action}");

    routes.MapRoute(
        name: "Default",
        template: "{controller}/{action}/{id?}",
        defaults: new { controller = "Home", action = "Index" });
});

Given these routes, you could define two Home controllers, as follows:

namespace MyApp.Controllers
{
    public class HomeController : Controller
    {
        // Home/Index
        public ActionResult Index()
        {
            return View();
        }
    }
}
namespace MyApp.Areas.Controllers
{
    [Area("Books")]
    public class HomeController : Controller
    {
        // Books/Home/Index
        public ActionResult Index()
        {
            return View();
        }
    }
}

The second controller is assigned to the Books area.

URI Controller
/Home/Index MyApp.Controllers.HomeController
/Books/Home/Index MyApp.Areas.Controllers.HomeController

Views for an area go into a folder named “Areas/{area name}/Views/{controller}”. So in this example, the view for the Books/Home/Index action would go in a file named “Areas\Books\Views\Home\index.cshtml”.

Previously, the Web API framework did not support areas. Because MVC 6 merges the two frameworks, you can now organize web API-style controllers into areas.

View Components and Child Views

View components are similar to child actions in previous versions of MVC. They allow a view to invoke an action and render the result within the view. The following code shows a simple view component that writes a text string.

[ViewComponent(Name = "MyViewComponent")]
public class SimpleViewComponent : ViewComponent
{
    public IViewComponentResult Invoke(int num)
    {
        var message = String.Format("The secret code is: {0}", num);
        return Result.Content(message);
    }
}

To include this view component in a view, call Html.Component.

<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>Index Page</title>
</head>
<body>
  <p>@Component.Invoke("MyViewComponent", 42)</p>
</body>
</html>

When the view is rendered, the p tag will contain the string “The secret code is 42”. Notice that you can pass parameters to the view component’s Invoke method.

POCO Controllers

In MVC 6, controllers do not need to derive from Microsoft.AspNet.Mvc.Controller. You can write a controller as a simple class or “POCO” (plain old CLR object).
Here is an example.

public class HomeController
{
    // Helpers can be dependency injected into the controller
    public HomeController(IActionResultHelper resultHelper)
    {
        Result = resultHelper;
    }

    private IActionResultHelper Result { get; set; }

    public ActionResult Index()
    {
        return Result.Json(new { message = "Poco controllers!" });
    }
}

IActionResultHelper is a helper for creating action results. Notice that the IActionResultHelper instance is injected into the controller via the constructor. The framework provides a default IActionResultHelper implementation, and automatically injects it. You could also provide your own implementation of IActionResultHelper.

Previously, I showed a controller calls Controller.Json to return JSON data. That method is really just syntactic sugar for calling IActionResultHelper.Json.

The Controller class also gives you convenient access to the HTTP request context, the current principal (IPrincipal), a view bag, and other useful properties. So the Controller class is certainly useful, but it’s not required. For a light-weight controller, you might prefer a POCO controller.

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

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

ASP.Net web services (ASMX) vs WCF web services

The following are the few things which distinguish ASMX services to WCF webservices:
–WCF web services provide many bindings
–WCF web services are written to implement contracts defined by interfaces.
–For ASMX web services, you add attributes to the methods. For WCF web services, you add attributes to the interfaces.
–ASMX web services must be hosted in IIS, but WCF web services can ei

Reactive Extensions

While testing little bit with the reactive extensions, I felt the same thing which we used to do with many lines of code can be done using the reactive extensions so easily just by subscribing. The basic principle used is “Observer Pattern”: some objects observe a certain event or we can say as some subscribed objects get notified when a certain event or action occurs. With the linq in built this was fascinating to work with.

As enumerator uses pull the observer uses push.

The entire library revolves around two interfaces IObserve and IObservable. It’s like any object that observes should implement IObserve interface and the objects that are going to emit should implement IObservable interface. Earlier IObserve and IObservable were implemented in different assembly, now they are in System.Core, so it’s global and very useful.

The general syntax will be like

var query = from n in Enumerable.Range(1, 5) select n;
foreach(var n in query)
     Console.WriteLine(n);

//call the method which writes "I'm Done" to the console

The same can be written in Rx

var query = from n in Enumerable.Range(1, 5) select n;
var observableQuery = query.ToObservable();
observableQuery.Subscribe(Console.WriteLine, () => {Console.WriteLine("I'm Done");});

If we look at the code here, we are converting an Range [1, 2, 3, 4, 5] into Observable. When the system access each item , that item is passed to the Console.WriteLine which is observer her and the next parameter is a callback.

There is lot more than this..
We can make the operation to be performed on one thread and dispatch using the other.. For time consuming operations this will be good

If we have a WPF application and in that we have a button “Send” and textbox results

	private string stringWait(string str)
		{
			Thread.Sleep(250);
			return str;
		}
		protected void btnSend_Click(Object sender, EventArgs e)
		{
			var query = (from n in Enumerable.Range(1, 25) select stringWait(n.ToString())).ToObservable(Scheduler.ThreadPool);
			query.ObserveOnDispatcher().Subscribe(
				(string x) => {	Results.AppendText(String.Format("{0}\n", x));}
			);
			
		}

In the above code the query is observed by the dispatcher whereas the the operation is performed in the thread pool. If we use the same thread to dispatch that will raise and clr exception. To resolve this concurrency issue we can use ObserveOnDispatcher method, which will write the data.

There are many methods in the Observable which are useful

var source = Observable.Generate(0, i=>i<5, i=>i+1, i=>i*2, i=>TimeSpan.FromSeconds(i));

The above code will generate the sequence with the timespan difference.

			IDisposable subscription = source.Subscribe(
				(int x) => {Console.WriteLine("Received {0} from source and the thread {1}", x, Thread.CurrentThread.ManagedThreadId);Thread.Sleep(1000);},
			                                            (Exception ex)=> {Console.WriteLine("Received error: {0}", ex.Message);},
			                                            () => {Console.WriteLine("End of subscription");});

The subscribe method creates a subscription which implements IDisposable, which will be disposed when the subscription is completed.

the “Subscribe” method will emit data for 3 occurences “onNext”, “onError”, “onCompleted”.
Subscribe(onNext, onError, onCompleted)

Any object can be subscribed to any particular event too.. just like an event handler to notify the objects of the event. The same thing can be handled with the Rx, rx won’t replace the existing event handler system but we can use it in multiple scenarios

With the current version you can subscibe to an event like the following

var lbl = new Label{Text="Hello There", AutoSize=true};
			var txt = new TextBox {Width=200};
			txt.TextChanged += (sender, e) => {lbl.Text = "text changed" + txt.Text;};
			var frm = new Form{
				Controls = {
					lbl,
					txt
				}
					};
			var events = Observable.FromEventPattern<MouseEventHandler, MouseEventArgs>(h => h.Invoke, eh => frm.MouseMove += eh, eh => frm.MouseMove -= eh);
			using(events.Subscribe( evt => {
			                 	lbl.Text += Environment.NewLine + evt.EventArgs.Location.ToString();
			                 	Console.WriteLine("Current Location: {0} at {1}", evt.EventArgs.Location.ToString(), DateTime.Now.ToShortTimeString());
			                        }))
				
			{
			
			Application.Run(frm);
			}

Could not set focus on the invisible object – AjaxControlToolkit

Recently when we updated our AjaxControlToolkit library, strangely it was giving an “Could not set focus on the invisible Object” error on some machines. When I debugged it, the error raised with the tab panel. The same code is working fine with the older AjaxControlToolkit library version. But we modified our pages to suit the latest version so we had to tweek the current version js function. The developers of AjaxControlToolkit have added a method to set focus on the tab panels. The following code resolved the issue..


        //To resolve an error(set focus) with the current AjaxControlToolkit version (4.1.51116.0)
        if (Sys.Extended.UI.TabPanel != 'undefined' && Sys.Extended.UI.TabPanel) {
            Sys.Extended.UI.TabPanel.prototype._setFocus = function (a) {
                var x = $get("__tab_" + a.get_element().id);
                if (x.hidden == false && x.style.visibility != 'hidden' && x.style.display != 'none')
                    x.focus();
            }
        }
   

Powershell – Basics 2

If we look more into powershell, like conditional statements and looping like (if..else, switch, while) just like in .Net basically syntax looks similar to c#

#----------------------------
# Conditional statements
#---------------------------

Clear-Host
#Condition - if/else
$var = 2
if ($var -eq 1)
{
Clear-Host
"If loop"
}
else
{
clear-host
"else loop"
}

# if elseif
if($var -eq 1)
{
 clear-host
 "If -eq 1 loop"
}
else
{
    if ($var -eq 2)
    {
    clear-host
    "If -eq 2 loop"
    }
    else
    {
    clear-host
    "else else loop"
    }
}

#Switch statement for multiple conditions
clear-host
$var = 43 #Also test with 43 and 49

switch ($var)
{
    41 {"Forty one"}
    43 {"Forty three"}
    49 {"Forty nie"}
    default {"Fifty"}
}


#Will match all lines that match
clear-host
$var = 42
switch($var)
{
    42 {"Forty two"}
    "42" {"Forty Two string"}
    default {"default"}
}

#To Stop processing once a block is found use break
clear-host
$var = 42
switch($var)
{
    42 {"Forty two";break}
    "42" {"Forty Two string";break} 
    default {"default"}
}

#Swtich works with collections, looping and execyting for each match
clear-host
switch (3,1,2,42)
{ 
1 {"One"}
2 {"Two"}
3 {"Three"}
default {"The default answer"}
}

# String compares are case insensitive by default
clear-host
switch ("Some")
{
    "some" {"lowercase"}
    "SOME" {"UpperCase"}
    "Some" {"Mixedcase"}
}

# Use the -casesensitive switch to make it sensitive
clear-host
switch -casesensitive ("Some")
{
  "some" {"lowercase"}
    "SOME" {"UpperCase"}
    "Some" {"Mixedcase"}
}

# Supports wildcards
clear-host
switch -Wildcard ("Some")
{
  "so*" {"*"}
    "?ome" {"?"}
    "So??" {"???"}
}

# Note it will also support regex matches

##

#-----------------------------------------------------------
# Looping
#-----------------------------------------------------------

#while
clear-host
$i = 1
while ($i -le 5)
{
    "`$i = $i"
    $i = $i +1
}

# won't execute if condition is already true
clear-host
$i = 6
while ($i -le 5)
{
    "`$i = $i"
    $i = $i +1
}


#Do
clear-host
$i = 1
do
{
    "`$i = $i"
    $i++
}while ($i -le 5)

# Do will always execute at least once
clear-host
$i = 6
do
{
    "`$i = $i"
    $i++
}while ($i -le 5)

# Use until to make the check more positive
clear-host
$i = 1
do
{
    "`$i = $i"
    $i++
}until ($i -gt 5)

# For loop iterate a number of times
clear-host
for ($f =0;$f -le 5;$f++)
{
    "`$f = $f"
}

#Note the initializer can be set seperately
clear-host
$f=1
for (;$f -le 5;$f++)
{
    "`$f = $f"
}

# Iterating over a collection 1 by 1
clear-host
$array = 11,12,13,14,15  # Simple array
for ($f =0;$f -lt $array.Length ;$f++)
{
    "`$array[$f] =" +$array[$f]
}

# foreach works on a collection
clear-host
$array = 11,12,13,14,15  # Simple array
foreach ($item in $array)
{
    "`$item = $item"
}

# foreach works with an array of objects
clear-host
$array = 11,12,13,14,15  # Simple array
foreach ($item in Get-ChildItem)
{
  $item.Name
}

# Combine with if to give a better focus
clear-host
set-location "C:\Users\kpatil\Documents\Powershell_Tut"
$array = 11,12,13,14,15  # Simple array
foreach ($item in Get-ChildItem)
{
    if($item.Name -like "*.ps1")
    {
        $item.Name
     }
}

# Use break to get out of the loop
clear-host
set-location "C:\Users\newuser\Documents\Powershell_basics"
$array = 11,12,13,14,15  # Simple array
foreach ($item in Get-ChildItem)
{
    if($item.Name -like "*.ps1")
    {
        $item.Name
        break # Exits the loop on first hit
     }
}

# Use continue to skip the rest of a loop but got onto the next iteration
clear-host
set-location "C:\Users\newuser\Documents\Powershell_Tut"
foreach ($item in Get-ChildItem)
{
    if($item.Name -like "*.ps1")
    {
        $item.Name
        continue # 3xits the loop on first hit
     }
     "This isn't a powershell command: $item"
}

# When used in a nested loop, break exits to the outer loop
clear-host
foreach ($outside in 1..5)
{
"`$outside = $outside"
    foreach($inside in 6..9)
    {
        "   `$inside = $inside"
        break
    }
}

# Use loop labels to break to a certain loop
clear-host
:outsideloop foreach ($outside in 1..5)
{
"`$outside = $outside"
    foreach($inside in 6..9)
    {
        "   `$inside = $inside"
        break outsideloop
    }
}

# Using continuew inside an inner loop
clear-host
foreach ($outside in 1..5)
{
"`$outside = $outside"
    foreach($inside in 6..9)
    {
        "   `$inside = $inside"
        continue
        "this will never execute as continue goes back to start of inner for loop"
        #note, because we continue to the inside loop, the above line
        # will never run but it will go through all itereations of the inner loop
    }
}

clear-host
:outsideloop foreach ($outside in 1..5)
{
"`$outside = $outside"
    foreach($inside in 6..9)
    {
        "   `$inside = $inside"
        continue outsideloop
        "this will never execute as continue goes back to start of inner for loop"
        #here, because we break all the way to the outer loop the last two
        # iterations (8 and 9) never run
    }
    "this will never run too"
}

##

Powershell – Basics

It’s very interesting to learn and work with powershell. It’s very powerful and uses most of the Microsoft .Net Class Library. If we look at the basics

#Get-Command - Retrieves a list of all powershell commands
Get-Command

# Can expand by searching for just a verb or noun
Get-Command -verb "get"
Get-Command -noun "service"

# Get-Help can be used to explain a command
Get-Help Get-Command
Get-Help Get-Command -examples
Get-Help Get-Command -detailed
Get-Help Get-Command -full

#Most Command can also be passed a -? parameter to get help
Get-Command -?

#Moving around the file tree
#Get-ChildItem list all items in current path
Get-ChildItem

# set-Location will change the current path
Set-Location c:\app
Set-Location "C:\New_folder\"

# Pipelining -combine CmdLets for Power
Get-ChildItem | Where-Object {$_.Length -gt 1kb }

Get-ChildItem | Where-Object {$_.Length -gt 1kb } | Sort-Object Length

#Can break commands up among several lines
# (note pipe must be last char on line)
Get-ChildItem |
    Where-Object {$_.Length -gt 1kb } |
    Sort-Object Length
    
#To Specify columns in the output and get nice formatting, use Format-Table
Get-ChildItem |
    Where-Object {$_.Length -gt 1kb } |
    Sort-Object Length |
    Format-Table -Property Name, Length -AutoSize

#You can also use the Select-Object to retrieve certain properties from an object
Get-ChildItem |
    Select-Object Name, Length | Where-Object {$_.Length -gt 1kb }|
    Sort-Object Length
    
# .Net Everywhere
$str = "I am now a powershell novice"
$str            //Gets the string
$str.Length     //Gets the length of the string
$str.GetType()  //String

why people hate microsoft..

I don’t understand why people hate Microsoft, all the software and applications developed by Microsoft are just to make life easier for all the users. Just take a look at windows OS or Visual Studio, these are things I use most, Windows is so easy for any kind of user to operate. Visual Studio, makes life easy for the developers but still developers hate it.
The only drawback with Microsoft is they keep on releasing new upgrades and discontinue support to older version. I mean when you compare .Net with java, in java they still use all the core techonology they created ofcourse there will be updates and easier ways to use. When we look at Visual Studio, now we won’t use all the older version controls or coding methodologies, we need to learn all the newer techonogies. with newer version there comes lot to learn. The same thing we used to do changes. Ofcourse, techonology always upgrades.