Wednesday, December 4, 2013

Fixing TF215097 error while using Nugetter on TFS Build 2010

I got the following the error while trying to run a build on TFS Build 2010 that was supposed to create a nuget package using Nugetter of a simple class library project.

TF215097: An error occurred while initializing a build for build definition \Project\BuildDefinitionName: Cannot set unknown member 'Microsoft.TeamFoundation.Build.Workflow.Activities.SyncWorkspace.RequestsFailed'.

My environment:

TFS 2010 Build Server

Nugetter 2.1

Cause: Nugetter version 2.1 is good for TFS2012 and not for TFS2010. 

Solution: For TFS 2010 version you have download 1.2 version. Another catch you have to keep in mind is that if you are using VS2012 or VS2013 then you will get error while creating a new Build Definition inside the process section.  This is because the process templates you downloaded with 1.2 version has certain assemblies related to VS2010 hard coded into it.  And for that reason you will have to clean the xaml process templates as demonstrated by  Jason Prickett in this blog post.

Friday, November 22, 2013

Show selected item details from Autocomplete dropdownlist of jQuery using PartialView

This is a continuation of a series around Autocomplete using jQuery in Asp.net MVC4.

1. Implement Autocomplete using jQuery UI inside Asp.Net MVC4 Application

2. Show selected item details from Autocomplete dropdownlist of jQuery UI – (using Knockout)

3. Show selected item details from Autocomplete dropdownlist of jQuery UI – (using PartialView)

In the last post we looked at how to display details about a selected person from the dropdownlist of jQuery UI Autocomplete using Knockout.js. Knockout.js allowed us to databind our ViewModel with our view.  In this post we are going to look at how to do show details of a person but using a PartialView. 

1. Right click on the Home folder>Add>View.

image

2. Type the name of the view as _Person

image

3. Create another method named GetPerson just like the following but this one returns a PartialViewResult instead of JsonResult.  And in our select statement of LINQ query we are return a custom class with all the properties.  We had to do otherwise we won’t be able to strongly type our view.  For demo purposes I have created the class in the same class as the controller but in real world application I create separate ViewModel folder and create classes there.

[HttpGet]
public PartialViewResult GetPerson(int id)
{
var user = (from p in db.People
join e in db.Employees
on p.BusinessEntityID equals e.BusinessEntityID
join be in db.BusinessEntityAddresses on p.BusinessEntityID equals be.BusinessEntityID
join ad in db.Addresses on be.AddressID equals ad.AddressID
join st in db.StateProvinces on ad.StateProvinceID equals st.StateProvinceID
where p.BusinessEntityID == id
select new PersonDetail
{
Id = p.BusinessEntityID,
FullName = p.LastName + ", " + p.FirstName,
LastName = p.LastName,
FirstName = p.FirstName,
JobTitle = e.JobTitle,
HireDate = e.HireDate,
AddressLine1 = ad.AddressLine1,
City = ad.City,
PostalCode = ad.PostalCode,
State = st.Name
}).ToList().First();
if (user == null)
{
HttpNotFound();
}
return PartialView("_Person", user);
}

Add the following class for PersonDetail below the controller class in your HomeController.

public class PersonDetail
{
public int Id { get; set; }
public string FullName { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string JobTitle { get; set; }
public DateTime HireDate { get; set; }
public string AddressLine1 { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public string State { get; set; }
}

Let's make sure our PartialView _Person.cshtml accepts our model of type PersonDetail.

@model AspNetDemo06.Controllers.PersonDetail
<p>@Model.Id </p>
<p>@Model.FullName </p>
<p>@Model.LastName </p>
<p>@Model.FirstName </p>
<p>@Model.JobTitle </p>
<p>@Model.HireDate </p>
<p>@Model.AddressLine1 </p>
<p>@Model.City = ad.City </p>
<p>@Model.PostalCode </p>
<p>@Model.State </p>

Finally fix few things to fix in our Index.cshtml page. First create a div with id selectedPerson.

<div id="selectedPerson">

</div>

Then in our javascript code, first instead of FindPerson change it to GetPerson. Then in the success method of ajax call just replace the div with the returned partial view.

 $(document).ready(function () {
$("#SearchString").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/Find",
data: "{ 'prefixText': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.value,
value: item.value,
id: item.id,
firstname: item.firstname,
lastname: item.lastname
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
select: function (even, ui) {
var businessEntityId = ui.item.id;
$.ajax({
url: "/Home/GetPerson",
type: "GET",
data: { "id": businessEntityId}
}).done(function () {
}).success(function (person) {
$("#selectedPerson").html(person);
});
}
});
});

In the above code line 36 the person object is our partial view that we inserting in the div of id selectedPerson.


image

Monday, November 18, 2013

Show selected item details after selecting an item from autocomplete dropdownlist using Knockout.js

This is a continuation of previous post where we looked at how to implement autocomplete functionality into Asp.net MVC 4 application using jQuery UI and Ajax.  In the previous post when you selected a particular user it redirected you to a different page.  What if we want to show information about that user on the same page without any page refresh.  In this post we are going to do exactly the same thing.  Well there are many ways to do this but I want to show you the one using Knockout.js. To use Knockout.js first include it in our BundleConfig.cs  

bundles.Add(new ScriptBundle("~/bundles/knockout").Include("~/Scripts/knockout-*"));

Second lets tell our _layout.cshtml page to load knockout.

<body>
@RenderBody()
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryui")
@Scripts.Render("~/bundles/knockout")
@RenderSection("scripts", required: false)
</body>

Add the following javascript below the autocomplete method in Index.cshtml page. This is a PersonViewModel which has properties like LastName, FirstName and BusinessEntityID.

 
//ViewModels Knockout
function PersonViewModel(data) {
this.LastName = ko.observable(data.lastname);
this.FirstName = ko.observable(data.firstname);
this.BusinessEntityId = ko.observable(data.id);
}

We created a ViewModel for the Person Object called PersonViewModel. And ko.observable(data.lastname) means that lastname is an observable property. Next add the following div section where we are going to display selected person’s information.  Inside the span tag see the data-bind=”text: LastName” it will be replaced by the LastName returned from our select function inside autocomplete.

<div style="display: none;" data-bind="visible: true">
<span data-bind="text: LastName"></span>
<span data-bind="text: FirstName"></span>
</div>

In this post I want to just focus on people who are employees. So lets make sure we allow users to search just for Employees. Make appropriate changes suggested below

[HttpPost]
public JsonResult Find(string prefixText)
{
var suggestedUsers = from x in db.People
where x.LastName.StartsWith(prefixText) && x.PersonType == "EM"
select new {
id = x.BusinessEntityID,
value = x.LastName + ", " + x.FirstName,
firstname = x.FirstName,
lastname = x.LastName};
var result = Json(suggestedUsers.Take(5).ToList());
return result;
}

One last thing before we run our application. Replace the window.location.href line with  ko.applyBindings(new PersonViewModel(ui.item));  This will databind our selected person to the datatemplate shown above.

@section scripts{
<script type="text/javascript">
//Javascript function to provide AutoComplete and Intellisense feature for finding Users.
$(document).ready(function () {
$("#SearchString").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/Find",
data: "{ 'prefixText': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.value,
value: item.value,
id: item.id,
firstname: item.firstname,
lastname: item.lastname
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
select: function (even, ui) {
ko.applyBindings(new PersonViewModel(ui.item));
}
});
});
//ViewModels Knockout
function PersonViewModel(data) {
this.LastName = ko.observable(data.lastname);
this.FirstName = ko.observable(data.firstname);
this.BusinessEntityId = ko.observable(data.id);
}
</script>
}

image


I just wanted to show that it could be done with Knockout. At this point our search button is non-functional. We will make it functional later. One thing to notice here is that the information about the selected user is grabbed from the initial query we did to find suggested users.  To bring in more information we would have to adjust our LINQ query.  And I know what you are thinking right now, “But Mitul, that would bring in all the unnecessary information about other users in which we are not interested.” So we are going to write another method in our HomeController to bring in information just about that selected person. Before doing that let’s update our model to bring in additional information about our selected person.


Open the ADworks.edmx file inside our Models folder and then click anywhere next to the entity and select “Update Model from Database


image


And then check on these entities Employee, Address, BusinessEntityAddress, StateProvince. 


image

Now FindPerson method will return detailed information about the selected person.
        [HttpGet]
public JsonResult FindPerson(int id)
{
var user = (from p in db.People
join e in db.Employees
on p.BusinessEntityID equals e.BusinessEntityID
join be in db.BusinessEntityAddresses on p.BusinessEntityID equals be.BusinessEntityID
join ad in db.Addresses on be.AddressID equals ad.AddressID
join st in db.StateProvinces on ad.StateProvinceID equals st.StateProvinceID
where p.BusinessEntityID == id
select new
{
Id = p.BusinessEntityID,
FullName = p.LastName + ", " + p.FirstName,
LastName = p.LastName,
FirstName = p.FirstName,
JobTitle = e.JobTitle,
HireDate = e.HireDate,
AddressLine1 = ad.AddressLine1,
City = ad.City,
PostalCode = ad.PostalCode,
State = st.Name
}).ToList().First();
if (user == null)
{
HttpNotFound();
}
return Json(user, JsonRequestBehavior.AllowGet);
}

Inside our select function of AutoComplete we are going to make an ajax call [line 31] to this method passing in the BusinessEntityID [line 35] for the Person to FindPerson method [line 33]. Also I have made changes to the PersonViewModel to reflect all the properites returned from the FindPerson method.

@section scripts{
<script type="text/javascript">
$(document).ready(function () {
$("#SearchString").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/Find",
data: "{ 'prefixText': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.value,
value: item.value,
id: item.id,
firstname: item.firstname,
lastname: item.lastname
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
select: function (even, ui) {
var businessEntityId = ui.item.id;
$.ajax({
url: "/Home/FindPerson",
type: "GET",
data: { "id": businessEntityId}
}).done(function () {
}).success(function (person) {
ko.applyBindings(new PersonViewModel(person));
});
}
});
});
//Person Detailed View Model
function PersonViewModel(p) {
this.Id = ko.observable(p.Id);
this.FullName = ko.observable(p.FullName);
this.LastName = ko.observable(p.LastName);
this.FirstName = ko.observable(p.FirstName);
this.JobTitle = ko.observable(p.JobTitle);
this.HireDate = ko.observable(p.HireDate);
this.AddressLine1 = ko.observable(p.AddressLine1);
this.City = ko.observable(p.City);
this.PostalCode = ko.observable(p.PostalCode);
this.State = ko.observable(p.State);
}
</script>
}

Finally lets update our div to reflect all the udpated user properties.

<div style="display: none;" data-bind="visible: true">
FullName:<span data-bind="text: FullName"></span>
<br/> LastName:<span data-bind="text: LastName"></span>
<br/> FirstName:<span data-bind="text: FirstName"></span>
<br/> HireDate:<span data-bind="text: HireDate"></span>
<br/> Job Title:<span data-bind="text: JobTitle"></span>
<br/> AddressLine1: <span data-bind="text: AddressLine1"></span>
<br/> City: <span data-bind="text: City"></span>
<br/> PostalCode: <span data-bind="text: PostalCode"></span>
<br/> State: <span data-bind="text: State"></span>
</div>

Run the application and search a particular user.


image


In this post, we looked at how to show selected user’s information after search for a user using jQuery UI’s autocomplete method.  Initially to display the selected user we simply data binded the object returned by the select object, we didn’t went to server to find more information.  In the final attempt we did another ajax call to the server to find more information about the user.  In the next post we will look into how to show detailed information about a person using a PartialView. 

Friday, November 15, 2013

Implement Autocomplete using Jquery UI inside Asp.NET MVC4 application

I think the title explains what I am going to accomplish in this blogpost.  I assume you have AdventureWorks2012 database, visual studio 2012 installed. So let’s get started.
1. Open Visual Studio 2012/2013. I am using VS2012 for this demo.
2. Create an Asp.Net MVC 4 Application and Click on basic application for this demo.
3. Add a new controller to your project. I am naming it as HomeController and using Empty MVC Controller as template.
image
4. Right Click on Models Folder and Add new Item. From the Data section add a new ADO.NET Entity Data Model.  I named it as ADWorks.edmx
image
5. Choose the AdventureWorks2012 database when prompted during new connection.   Choose Person.Person table when “Choose Your Database Objects and Settings” dialog appears in the Entity Data Model Wizard as shown in the figure.  After adding the model build the project once [Ctrl+Shift+B].
image
6. Open HomeController.cs file and Add Reference to your Models. Then create a new method to find the person.
private AdventureWorks2012Entities db = new AdventureWorks2012Entities();

        [HttpPost]
        public JsonResult Find(string prefixText)
        {
            var suggestedUsers = from x in db.People
                                 where x.LastName.StartsWith(prefixText)
                                 select new { id = x.BusinessEntityID, 
                                     value = x.LastName + “, ”+ x.FirstName, 
                                     firstname = x.FirstName, 
                                     lastname = x.LastName };
            var result = Json(suggestedUsers.Take(5).ToList());
            return result;
        }

In the above code we find all the users that match the text that is entered by the user and only return 5. One thing to note here is that the Value field is the one that is going to be displayed when the dropdown for all the possible values shows up. I pass in a anonymous object with all the possible properties that I want for additional stuff. Usually id is a unique identifier and value is something you want to display. Another thing is notice the HttpPost attribute somehow I tried with HttpGet and it doesn’t like because you have to set JsonRequestBehavior to allow GET.

7. Next Add Index.cshtml page to your View Folder and then add the Html.TextBox where we will enter Person’s LastName, inside Html.BeginForm() as shown in the code. 
    </p>
        Search the Person by typing in the LastName of the user.
    </p>
    <div>
        @using (Html.BeginForm())
        {  
            <p>
                @Html.TextBox("SearchString")
                <input type="submit" value="Search">
            </p>
        }
  </div>

8. Add @scripts.Render("~/bundles/jqueryui") to the _Layout.cshtml page as shown below.
image
9. Open Index.cshtml page and now we will add the Javascript code that will query our Find method of Step6 using ajax method of jQuery and autocomplete method of jQuery UI.  We will add the following script inside section called scripts that will place all this javascript code in place of @RenderSection(“scripts”,required: false) in our _layout.cshtml page. 
@section scripts{
    <script type="text/javascript">
        //Javascript function to provide AutoComplete and Intellisense feature for finding Users.
        $(document).ready(function () {
            $("#SearchString").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: "/Home/Find",
                        data: "{ 'prefixText': '" + request.term + "' }",
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        dataFilter: function (data) { return data; },
                        success: function (data) {
                            response($.map(data, function (item) {
                                 return {
                                    label: item.value,
                                    value: item.value,
                                    id: item.id,
                                    firstname: item.firstname,
                                    lastname: item.lastname
                                }
                            }))
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(textStatus);
                        }
                    });
                },
                minLength: 2,
                select: function (even, ui) {
                    window.location.href = '/Home/details/' + ui.item.id;
                    }
            });
        });
    </script>
}

In this step, we use autocomplete method of jQuery UI.  The nested function inside autocomplete takes two object request and response.  We take the response object and pass the text that was entered to the Find method of our controller using jQuery Ajax method. In the case of a success event we take the response object and grab the data and for each item return value, id, firstname and lastname.  On the user interface side we are only going to see the value property in the form of a dropdown list.  Once you select a particular object the select function or callback is triggered with even, ui parameters.  The ui parameter has all the properties that we returned from the success event of the ajax method.  In our select event, I want to redirect the user to a different page where you can see the details of the person.  I have included this in the sample code available on my github account.  Redirection is done by setting window.location.href to the url you wish.

Its time to spin this project in the browser so lets run and see what happens when we type a person’s lastname. 

image

10. Fix CSS. Notice the dropdown style is messed up.  Your marketing department and users would be frustrated.  Let’s fix that. Oh ! But you might say that there is CSS file already included for the autocomplete I see in the Content folder under themes/base right. Actually we forgot to include that in our _Layout.cshtml file. If you use any of the jQuery UI things then replace the existing Styles.Render line with the following. Because in the Bundles.Config file we already have created jQuery UI CSS Style Bundle. We just need to include it if we use it.
    @Styles.Render("/Content/themes/base/css", "~/Content/css")

Test it out if the CSS has changed or not. F5.

image

The full source code for this sample is available on github. In the next post we will check out some fun stuff with the help of Knockout.

Friday, November 1, 2013

Lessons learned in sending emails to users in a complex Asp.Net MVC application using MvcMailer

There are multiple ways to handle mailing in a .net application.  System.Net.Mail is a well known assembly we often use for sending simple email messages.  I am building a fairly complex website with couple of different workflows [nothing to do with Windows Workflow] into it.  In each workflow, the website could be sending multiple emails with different text.  I wanted something maintainable and flexible.  MvcMailer is a very good open source library by SM Sohan to send mails using Razor views.  Razor Views!! yes, I am already sold on this.  It also supports other view engines btw. There is a good documentation on the gitHub and it details all the scenarios.  It is so cool and has already been on Scott Hansleman’s blog.  If you want to pass in strongly typed view then you can check this stackoverflow answer by Darin Dimitrov. Again very cool.  I like the idea of strongly typing and I have no other choice due to sheer complexity of the web application.

I wanted to share some of the lessons I learned in sending multiple emails with different content to different types of users.  Some of the things here is not related to coding but is very important in keeping yourself organized.  I tend to work backwards focusing on what the user will see.  So I first start documenting an Email Template in word document and keep adding them as new ones pop-up.  And I follow most of the steps shown below.

1. Maintain a word document with Email Templates.

This is applicable only if you are building a fairly complex MVC application with different stake holders.  It is very important to get it reviewed by different people involved in the project.  Sometimes you might get the text wrong and may be the intent is not conveyed properly to the end user.  I am not perfect at English and I like to get it reviewed by someone.  I am going to share some tidbits of such a word document. 

Template Name – Send Email to Vendors for product pickup

TemplateId – ET0001

Description

The following email will be sent to all the recipients listed below after all the products requested ready for shipping. After all the requested products are packaged, an order is considered as ready for shipping.

Recipients

1. To the shipping vendor to notify about product pickup for shipping.

Subject

Order ready for pickup

Email Body

[Shipping Vendor’s Full Name],

Your next products order has been ready for pickup and you can come on and no later than [pickup date]

Products Ordered [List Dynamically Populated]

1. Gel

2. Shaving Cream

3. Toothbrush

If you have, any questions or concerns related to your order pickup please contact [contact email address].

[Signature]

 

The purpose of this type of word document is to make sure that all the content you put in front of the user is appropriate for its intended audience. Is the wording right? Is there any misleading information? Are we conveying our intent to the user in a clear and concise manner? All these and more questions need to be ironed out before you ship this feature.  Because later down the road it will be difficult when you have say 25 or 50 different Razor Views, ViewModels sending emails. Right now my application has not reached to that level of complexity but I do see it reaching it. All the text that is underlined in the Email Body will be replaced by strongly typed ViewModel.  The Email Body will closely resemble the Razor Views in the Web Application.  Once you know the structure of all the emails you can start coding Razor Views.  So again it reviewed or proof checked by Project manager or immediate supervisor.

2. Use Strongly Typed Views

After I have my text templates ready, I can directly copy them into the web application.  I scaffold my views as necessary using the Scaffold command.  From point 1 we can create our Strongly Typed View named ET001 [TemplateId].

@using WebsiteName.ViewModels

@model OrderPickupEmailViewModel

@Model.VendorFullName,

Your next products order has been ready for pickup and you can come on and no later than @Model.PickupDeadline

Products Ordered

<ul>

@foreach (var item in @Model.Products)
{
<li>@item</li> 
}
</ul>

If you have, any questions or concerns related to your order pickup please contact @Model.ContactInfo

@Model.Signature

3. Use ViewModels to pass information to Razor Views.

After I construct my Razor Views I know what Properties I should be adding to my ViewModel.  I then create my ViewModel named OrderPickupEmailViewModel see point 2.

public class OrderPickupEmailViewModel

{

public string ToAddress {get;set;}

public string Subject {get;set;}

public string VendorFullName{get;set;}

public DateTime PickupDeadline {get;set;}

public List<string> Products {get;set;}

public string ContactInfo {get;set;}

public string Signature {get;set;}

}

4.  Modify the Interface and Class to accept your custom ViewModels

After the ViewModels are ready I go and modify the interface IUserMailer.cs methods to use my CustomViewModels. 

public interface IUserMailer
{
MvcMailMessage OrderPickupConfirmation(OrderPickupViewModel ordp);
}
After that I modify the method inside UserMailer.cs created as a part of scaffolding.

public virtual MvcMailMessage OrderPickupConfirmation(OrderPickupViewModel ordp)
{
       ViewData = new ViewDataDictionary(ordp);
return Populate(x =>
{
x.Subject = ordp.Subject;
x.ViewName = "RequestSubmissionConfirmation";
x.To.Add(ordp.ToAddress);                });
}
Finally send the email in the respective controller.

[HttpPost]
public ActionResult SendEmail(OrderPickupViewModel model)
{
UserMailer.OrderPickupConfirmation(model).Send();
}
5. Keep common settings inside your web.config file just like MvcMailer stores smtp settings inside web.config file.  You can use web.config transforms to send emails to a redirectfolder and to end users when in production.  
If you are following any techniques or best practices to keep your self then please share in the comments below. I would like to know and get better.

Tuesday, October 15, 2013

How to render grouped entities using strongly typed View in Asp.NET MVC?

In this post, we are going to learn how to show grouped entities using strongly typed Asp.net MVC View, for example, show all the products by subcategories as shown in the figure below. The first column shows the SubCategories and other columns show products. Another thing to notice is SubCategory’s Name property isn't populated more than once.  The style for just that row is colored and all other rows have background color as white.
image
I am using AdventureWorks2012 sample database for this example. I assume you know certain basics of Asp.Net MVC applications, little bit of LINQ and EntityFramework.  I am using database first approach with EntityFramework. 
  1. Create a basic Asp.net MVC4 Application. I am naming it as AspNetAjaxSamples101.  
  2. Add new empty Controller named HomeController
  3. Add a new ADO.NET Entity Data Model to your application.
  4. Open your HomeController and add following lines to your Index method.
We are passing the View an Object of type IEnumerable<IGrouping<string,AspNetAjaxSamples101.Models.Product>>. Add a new empty view to by right clicking on the View(ProductsBySubCategories.ToList()).
Copy the following code into your Index.cshtml page. Something about the code. Our view is a strongly typed view of type IEnumerable<IGrouping<string,AspNetAjaxSamples101.Models.Product>> that you can see on the top. Next piece of the puzzle is inside the tbody tag of table. First we do a foreach loop and get the group item then we iterate through each group item i.e. Product and show product details using for loop not foreach. The reason we use for loop is we want to know which row we are rendering. If it is the first row which we determine using the if statement then render SubCategory name using item.Key.ToString(). And if it is not the first row then skip the first td cell of the row and don’t show anything. Final piece in this project is styling. In the Site.css file add following style. In Index.cshtml page, inside second for loop if the i==0 then we assign class trsubheader to the row element of the table. So there you have it.

Thursday, September 19, 2013

Use Processmonitor to debug command line syntax passed through PowerShell

If you are trying to find out why a certain formatted command within PowerShell is not working then I strongly recommend using ProcessMonitor tool from SysInternals suite of tools.  When you initially fire up the ProcessMonitor then it will show you lots of information and it can be overwhelming. 
image_thumb[1]
So there is a powerful filtering functionality built into the utility.  Click on the filter tab and click on filter.
image_thumb[3]
Then on the filter section add two filters as shown in the figure below.
image_thumb[7]
The first filter is Path is “C:\Program Files\7-zip\7z.exe” and second one is Operation is “Load Image”.  After applying the filter and running my PowerShell script I can narrow down my desired line.
image_thumb[9]
So if next time any command line utility is behaving weird then debug using ProcessMonitor.

Tuesday, September 17, 2013

Use PowerShell variables after escaping parsing in PowerShell v3.0

Recently I answered a question on StackOverflow related to passing parameters inside a PowerShell script to command line utility 7z.exe for unzipping zip files.  In the process of debugging the issue, I tried different options and learned few tricks in working with PowerShell and debugging issues. In this post, I am going to talk about how to pass powershell variables after you use the stop parsing --% trick.

Did you knew that you can tell PowerShell to stop parsing command?
In PowerShell V3, there is a neat trick you can use to tell it to stop parsing anything after typing --%. All you have to do is use --% after your command say & 7z.exe and PowerShell will directly pass the string after the --% to the command line utility. Check out below help snippet about parsing easily found by typing PS>C:\help about_parsing
STOP PARSING:  --%
    The stop-parsing symbol (--%), introduced in Windows PowerShell 3.0,
    directs Windows PowerShell to refrain from interpreting input as
    Windows PowerShell commands or expressions.
 
    When calling an executable program in Windows PowerShell, place the
    stop-parsing symbol before the program arguments. This technique is
    much easier than using escape characters to prevent misinterpretation.
So in the following example you don't have to include those parameters after --% in double or single quotes and do voodoo magic to figure out which one works.


But there is one problem with this approach, if you want to use PowerShell variables after the --% it won’t work. To solve this issue, you have to create a variable and initialize its value to --% and pass everything after it in variable(s). In the example below, I am using $stopparser variable with value --%. Finally I am passing everything using variables so PowerShell first evaluates the variables and then ignores parsing while executing the actual command. Isn't it magic.  I love PowerShell. If you know some neat trick about PowerShell then share in the comments section.

Sunday, August 25, 2013

Quickly explore 159 samples of windows 8 SDK using PowerShell and touch on Surface Pro

I was looking sample source code on windows 8 and I found this collection of 159 windows 8 app samples in C#. You can also find windows 8 and 8.1 app samples in c#, vb.net, C++ and Javascript. Many windows 8 developers might be aware of it already but it becomes painful after some time to go and open each solution. However, I think most people only open a particular solution when the need arises. However, I wanted to explore all of them (159 of them), run, and see what all the different features Windows 8.1 and 8 SDK has. That way I am at least aware of the features and use them in my application whenever needed. The only problem is opening each of them through the explorer window and locate .sln file three layers deep. One more thing I am doing this all on a surface pro sitting while on a couch.

Part of my frustration with these samples was, first you have to download them samples (that’s ok), unblock them since they are downloaded from internet (fine by me), then navigate to the solution folder and open the .sln file (not good for 159 of them). There is a lot of context switching when I launch the application from Visual Studio and then the modern interface opens up another context switch. Now try to do this on a Windows 8 pro tables like the Surface Pro while sitting on your couch or lying in the bed. Too much hassle right, but I have figured out an easy way to overcome this problem.  My Answer to the problem is Powershell. I have attempted to solve this problem before(link) but it was not as elegant as this one is.
Check this powershell one-liner


I extracted windows8 samples to the folder C:\windows8samples. This one-liner first finds all the .sln files in the samples folders, then selects just the name and fullname property of the the .sln file, and then sorts them by name, and then shows you list of .sln files in a gridview window. If you are running windows 8 for viewing all the windows 8 samples, you have powershell v3. In PS v3, you can pass the object(s) you select from the gridview down to the on going pipeline. You can select a single object which what I have done here because I do not want to open multiple solutions. This is done by the –Outputmode single property. After selecting the object in the gridview interface you click ok and then I use invoke item command to open the file in the default program configured for the file.

Ok so what's simple in this as you might ask right. Copy this one-liner, create a powershell script named OpenVSSolutions.ps1, and create a shortcut on the desktop. Open the properties of the shortcut file and change the target field in the property window to this

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle Hidden -NonInteractive C:\Scripts\OpenVSSolutions.ps1



This will hide powershell window and present you gridview with all solutions and then you can select one solution and hit ok. It will open visual studio. Done. Then just run the application and explore. To ease surfing source code inside visual studio 2012 or 2013 is switch scroll to use map mode scrolling (now supported in VS2013 and productivity power tool for VS2012).

You can change icon of your script too to reflect something else than powershell icon. Mine looks like the following.

You can place the shortcut on the toolbar or pin it to start page.

Now that is simple and easy solution to browse all samples quickly using touch on a Surface Pro lying in the bed when you don’t want to sit at your desk.

This solution works for other purposes too. I have folder named C:\BadSourceCodes\ which contains ad-hoc solutions I create to quickly test a concept. Over a time the folder contains lots of solutions and finding them is also pain.  Instead I use above technique to open solutions.  I have couple of such folders with lots of Visual Studio solutions some contains samples from various books I have purchased over the years, my production source code library, badsourcecode library and others.  To make our experiment more generic lets change our one line of powershell to replace the hardcoded path with a $path variable.   Save the script file.

Now you can create multiple shortcuts for your folders and edit target property of each shortcut.
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle Hidden -NonInteractive C:\Scripts\OpenVSSolutions.ps1 “C:\BadSourceCode"

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle Hidden -NonInteractive C:\Scripts\OpenVSSolutions.ps1 “C:\Windows8Samples"

Pin different shortcuts to your taskbar and now you easily open any solution without having to navigate different folders, switch context and later forget what you were trying to do.

Bonus. Download samples of C#, Linq101 samples, windows 8 and others to create a shortcut menu like this.

This is my first attempt at creating gifs but if I click or double tap on any of the above shortcuts on my desktop then it displays a list of visual studio solutions and I can open any one of it.










Wednesday, June 5, 2013

Low cost method for organizing electronics components

So there is one problem you will have to deal with when you are beginning to work with electronics projects and that is organizing these tiny components like resistors, capacitors, diodes, transistors, etc.  There are different suggestions as this stackexchange question highlights. I ended by putting all these small components into tiny zip lock bags. The ones available in the grocery section of a super store will not work because they are little bit big.  I bought those pill bags found in the pharmacy section.  They look like this.
 You can put a strip of resistances say 1M ohms in one bag and use permanent marker to label it.
 Then I arranged ones with values like 10ohms, 100ohms, 150 ohms, 1k and so on in one big zip lock bag.

Yeah it is little bit hassle taking them out and putting back in.  In that case you might want to try those compartment boxes that you take along with you for fishing. They have adjustable dividers and you can put them in those.  In fact in the future that is way I am going to organize them.  I have one carry-on box with three decks in which I just dump all these zip lock bags and if I needed to carry entire box then I can do it.

Monday, June 3, 2013

New toy in the house: BealgeBone Black

Recently I purchased a new toy known as BeagleBone Black, a tiny computer worth only $45 which has Linux operating system on it just like Raspberry Pi.  This one has Linux Angstrom distribution on it but you can load Ubuntu on it if you want. BeagleBone was around for a long time and its earlier version BealgeBoard was little bit expensive but $45 is just the right price for me.


And by tiny I mean it is really very small just check out in this image in perspective below.

I also have an Arduino UNO R3 but I haven’t played with it much.  Arduino doesn’t have an operating system on it.  It is just a microcontroller but that is not the reason I haven’t played with it much.

Raspberry Pi is really very popular because of its low cost $25 and some of the cool things people are able to do with it.  For starters Raspberry Pi is really very good and for a lot of reasons. Few things I liked about Raspberry Pi compared to BeagleBone Black are: one you have two usb ports which you can use to connect a keyboard and a mouse, second to connect to an external monitor like your TV you have HDMI output and so you can directly plug into your TV without requiring any external adapter (assuming you have an HDMI cable) and third some of the boards that are available for Raspberry PI. In BeagleBone Black you only have one USB port so you will need a USB hub to plug in a keyboard and a mouse, plus it uses a micro HDMI port so you use some kind of adapter again to hook up to your TV or just buy one of these.  For a full comparison you look this post and this comparing Raspberry Pi, BealgeBone Black and Arduino.

BeagleBone is rock solid in terms of no of I/Os (65) you have available. So if you are interested in robotics applications which require lots of I/O pins then BeagleBone Black is the board you want. And that was my primary motivation to buy BeagleBone Black. Check out expansion connectors section in the image below.

It has Arduino style programming library, and by that I mean you can turn a particular pin High and Low just like you would do in Arduino but in JavaScript.  Did I just said JavaScript?  Yes you heard it right, it does all this magic using JavaScript.  So BeagleBone Black has python, node.js (Ah! I like it) and Cloud9 IDE along with Angstrom Linux distribution.  You can program using either python, node.js or plain C. I chose node.js.  There is BoneScript, a JavaScript file which does all the magic to turn a pin High or Low on BeagleBone Black. I will go into basics of programming BealgeBone in next couple of blog posts where I show you my little experiment with BealgeBone Black.  BBB uses 5V power supply and you can use USB cable to power it.  If you are interfacing multiple sensors then I recommend using an external power supply.  Typical voltage on the I/O pins of BealgeBone has 3.3 volts.  Once you plug BBB into your computer then getting started is really easy.  This link has all the details but just visit http://192.168.7.2 and you are in business in your browser (don’t use IE).

I had a spare old Sony Vaio sitting around which I wasn't using anymore so I loaded Ubuntu on it to play with BBB.  It is really very cool once you figure out the basics.   Below are few things I learned on the way to playing with Linux and electronics.

1. Electronics: Research first about what you are buying.  There are components that you will end up buying that you might not need or they might not be of different specifications. Ask somebody on the forums and there are really awesome people hanging out in these forums who will help you with it.

2. Don't update operating system on BeagleBone Black before checking what it does for you.  I tried updating OS and it blew up on me and I had to reload using a 4GB microSD card.  So another tip is keep one microSD card handy.  You will need it.

3. Learn some quick Linux OS commands to work in the terminal.  Being able to navigate into the OS will help you are lot.

4. Create a plan, sketch it out and make a list of components you will be needing to complete a project.  So this one I learned it the hard way. If you don't make a list of components and you start playing around and when you think you will need something then you will end up making multiple trips to RadioShack paying more or end up waiting for components to arrive in the mail.  And waiting for stuff is really annoying because you are so excited to hack into different project but you can't until it comes.

5. Buying the board is not the only thing you will do in an electronics project.  You will need a soldering iron, wires, resistors, transistors, de-soldering wire, multimeter, capacitors, leds, batteries, breadboard, boards and sensors.  So have some budget and buy everything at once so you don't end up wasting time and money buying them separately.

6. Safety: This has to be number one thing but please be careful with electronics and understand what you are doing. If you are young then have your parents by your side or someone who knows what you are doing.     Be safe and if you aren't not sure then please ask.

Electronics is a lot fun and don't get intimidated by it.  I have a bachelors degree in electronics and communication but trust me I am just like any new person trying to learn it first time.  I didn't liked electronics initially and was turned away by it because the way I was introduced to some of the concepts in electronics by the education system.  However, six years later I am digging deeper into the open web and YouTube to discover my lost passion into electronics once again. So don't give up.  Play with it.  If you get stuck then just ask somebody in person or on online forums, read online, watch YouTube videos and play again.

Monday, April 15, 2013

Visual Studio Trick - Convert Find Box into Command Box

In this blog post, I am going to show you how you can easily accomplish certain tasks within Visual Studio using Visual Studio commands from the Find Box that is provided at the top[see image below]. The Find Box is not enabled by default to appear in the toolbar, as a result few developers know about it.  The trick is that Find Box can be converted into a command box when you place a greater than < symbol in it and execute Visual Studio commands.  When I found about this I was totally psyched.  To get started lets see if you have the Find Box in the toolbar above like me.  See the image below.

If not then here is how you can enable it.  By default this will not be enabled in a fresh install of visual studio.  First click on the Add or Remove Buttons option to enable it.  Then below the Find in Files option there is just a Find option as highlighted in red box.  Click in front of it to enable it.
Once you have enabled it you can use Ctrl+D to quickly search something.  Pretty cool right but we are not there just yet. In the Find Box put a > character then start typing like File.Open or Edit.Replace something like that.  Did you just see what happened!!!

Find Box has now become a command box.  It shows all Visual Studio commands which you can use to do certain tasks without leaving your keyboard.  You might be tempted to ask me, "So Mitul is there a shortcut to insert > sign into the Find [or sorry command] Box so I can directly start typing Visual Studio commands?".  Yes there is.  Ctrl + / and it will insert > sign in the Find Box to convert it into a command box.

"So how is this useful?" and "How is this going to save me time?"

In this case you have to constantly think which tasks you do most frequently with mouse in visual studio and you can perhaps find a command for that action.  Then you can take advantage of this feature to save time.  There are predefined aliases for some of these commands.

So one of my favorite uses of command box is to open up Pending Changes window and TFS SourceControl Explorer window.  Go ahead and try to find TFS SourceControl Explorer window from the Menu and see how much time it takes.  Or even from the Team Explorer because I don’t have it always opened in visual studio.

But Ctrl + / and type View.TfsSourceExplorer and hit enter. Its opens up TFS SourceControl Explorer window for you. Again for the PendingChanges window use TFSDynamicSlientCheckin.  Opens up Pending Changes and there you are.  It is very quick and easy.  It depends on person to person how they might find this feature useful.


Pretty cool feature and yet unexplored by many Visual Studio developers out there. Check it out yourself and enjoy the productivity.  And please don't forget to share how you use this command feature in Visual Studio in the comments below.


Sunday, April 7, 2013

How to do Ajax in Asp.Net MVC4 Application?

In this post, I am going to show you how to do Ajax in an Asp.net MVC4 Application using C#.  It is very easy to create a very simple Ajax demo up and running.  Here are few things you need in order to get basic Ajax demo running in your application.  The complete source code for this application is available on my gitHub account.

0. Create basic Asp.net MVC4 application using VS2012
1. You need an Ajax.ActionLink in one of your views
2. Public Method that will return a Partial View
3. PartialView with some content

Open Index.cshtml and remove all the content and paste Ajax.ActionLink as below.  Ajax.ActionLink has 12 overloads (msdn link) to do Ajax and all of them are very self explanatory.  In the code below, I am passing in the text to display as link text, the controller action to hit, and Ajax Options that’s it. 
We need a div whose content we wish to replace or the target location where we wish to replace the contents.
Then we need a public method inside our home controller that will return a partial view with some data in it.  You can pass data to the Partial View using a ViewBag.  As in our case I am using ViewBag.Tiffin variable to hold that data and retrieve inside Partial View. Next in our Partial View we retrieve it.
Hit F5 and click on the link to see what happens.  All of the text will be replaced if you created a default Asp.net MVC4 Internet application.  Because by default Asp.net Template for MVC4 Internet Application doesn’t load the Jquery Validation bundle to do Unobtrusive JavaScript.  Include this line @Scripts.Render("~/bundles/jqueryval") in your _layout.cshtml page and you are all good to go.  Run again and you should see the output.

You might be curious to ask why are you using a POST instead of GET inside Ajax.ActionLink? Because depending on which browser you are running it will cache the response and will not trigger an ajax request every time you wish to do Ajax.  To overcome this problem you can disable cache for just that method use GET in Ajax.ActionLink

I have recorded a screencast video to show upto this point. Check it out and if you have any feedback let me know.
Now moving on to some more stuff like how can we put animated gifs showing that something is running.  That is actually even more easy.  For this purpose we are going to use few more attributes of AjaxOptions object.  This object has some events like OnCompleted, OnBegin, OnSuccess, OnFailure and we will assign javascript functions to them.  So when we trigger a ajax request then OnBegin function we will load the gif and OnCompleted we will hide the image. 
What about passing Parameters? For this we will use another overloaded method of Ajax.ActionLink which will pass routeparameters to our public method.  We are going to change our public method and Ajax.ActionLink as shown in the code below.
Ok I get it but what about some HtmlAttributes?  Actually there is very easy you use another overload of Ajax.ActionLink and you can pass in an anonymous object with values to it.  There are different options you can consider for HtmlAttributes. And also what about jQuery mobile data-role attribtues? For jQuery data attributes you will have to use _ instead of - as shown below.  Alright but now I want to implement Async and Await into this mix how can I do that?  Hmmm. For this we will have to modify our public method inside our controller to return Task of type PartialViewResult.  That is pretty easy too.
Oh! But I am told to just use jQuery to do Ajax then you have be a little bit careful. Please check your jQuery version. If you have jQuery 1.7 then Ajax is done differently and jQuery 1.9 does little bit differently. I am using 1.9 for this demo. There is a difference where you detect start and success events. You attach these events to the document object (see upgrade guide).


What-If Error
Why Ajax is still not working out for me? Here are some very common issues which I ran into while learning Ajax in MVC4 application. 

1. Always debug using Internet Explorer.  If you run your application then Chrome will show you red error count only if you inspect the page but will happily show you the page.  Compare this to Internet Explorer it will give you Microsoft JavaScript Runtime Error.  Doing a quick StackOverflow search will give you most of the common problems’ solutions.

2. Check if you have loaded Jquery Validation bundle

3. Check if you are even loading jQuery or not. Actually this should be number 0.

4. Check if you are loading multiple versions of Jquery or validation, if yes then deletes older ones.

5. Open up fiddler to see what is going on. If I am working with web then I have fiddler open by default most of the times. And it has affected my debugging skills.

6. Put breakpoints as this is very basic debugging skill.

7. Try deleting packages for jQuery and delete related entry in packages.config and again install those packages using Nuget.

8.  The complete source code for this application and demo is at gitHub.  Check this link

Monday, April 1, 2013

Visual Studio Trick - Block Edit Code

I love Visual Studio 2012 and the improvements made in it.  You can check out my post on Visual Studio 2012 goes search first here.  However there are some features which are hidden and aren't much talked about.  And these features were there even before Visual Studio 2012.  My favorite one it how you can block edit your code using this trick.  I have always been a fan of this trick.  It has saved me a lot of typing.  Find and Replace is not always useful and quick.  I have recorded my first video demonstrating this trick which is embedded below.  

This trick can be very helpful when you have to edit a block of text at once.  You can select a block of text by pressing the Alt key and select a piece of code with your mouse. Once you have selected the text you can type or delete that piece of text.  You can also use your keyboard to select a block of code and edit.  Just press Shift + Alt + Down Arrow to select number of lines and keep Shift + Alt pressed and then press Right Arrow to select the number of characters in those lines and then simply edit.  Check out this video below.


Thursday, February 28, 2013

Web Deploy Check list for deploying website to IIS7 from Visual Studio and TFS

Web Deploy is one of the mechanisms to publish websites to IIS from Visual Studio.  You can utilize this mechanism to publish from Visual Studio, TFS or manually if you have existing website packaged as a zip file.  If you haven’t checked this gem of resources (Vishal Joshi's Blog) on web deploying and publishing then please do yourself a favor.  In this post I am going to talk about a checklist to make sure before you wish to publish site to IIS.  Here is the list:

  • Installed the latest Web Deploy on windows server (Check this IIS website).  
  • Web Management Service is started and running
  • Web Deployment Agent Service started and running
  • Created a website inside IIS and created application pool for it  
  • Given the user IIS Manager Permissions at the site level inside IIS
  • Configured website for Web Deploy publishing
  • Saved Web publish settings on a local desktop
  • Import Web publish settings from the local desktop from Visual Studio publish dialog
  • Publish url is over Https 
  • Checked connectivity to the site from the Visual Studio publish dialog 

Now before you jump on to the TFS side of things to publish, please make sure that you have done following things:

  • Team Foundation Server Build service account is added to IIS Manager Permission section for the website inside IIS
  • Able to publish successfully from visual studio using web deploy?
  • Check the MSBuild parameters for web deploy (I have provided what works for me below).
If you have some more checklist you have formed over the years then let me know I will add to this list.

What-If-Error
When you click publish from visual studio you will have to select a publish method and at that point select Web Deploy.  You have the option to import the profile you have created from that publish dialog.  This will pre-populate all the details.  You will have to provide the user name and password for the user who has the permission in IIS Manager Permissions as described in earlier.  At this point if you see any errors then this is a nice website where all the errors are listed.  I think you will see these errors only if you do some mistake while manually typing out the details in the publish dialog.  I haven’t found any issues if you import site details through import mechanism.

Here are TFS MSBuild parameters I use to publish a website from TFS to IIS7.

/p:DeployOnBuild=True
/p:DeployTarget=MsDeployPublish
/p:CreatePackageOnPublish=True
/p:MSDeployPublishMethod=WMSVC
/p:MSDeployServiceUrl=https://ServerName:8172/MSDeploy.axd /p:DeployIisAppPath="NameofWebsiteOnIISServer"
/p:AllowUntrustedCertificate=True
/p:UserName="domain\serviceaccount"
/p:Password="AwesomeSecurePassword"

If you are still unsuccessful in publishing the website from TFS Build then it could be that your TFS Build server is 2010 and you are using Visual Studio 2012 and it might be missing some binaries.  If you install Visual Studio 2012 on the build server then this issue could be resolved.