Microsoft Articles

Creating custom HTML helper functions in ASP.NET MVC

ASP.NET MVC provides several  HTML helper functions that generates HTML automatically. E.g. Html.TextBox, Html.CheckBox etc. We can also create our own custom helper functions as well. For creating HTML functions following steps have to be performed:

1. Create a static class

2. Add a static method that returns either string or MvcHtmlString

3. First Parameter should use this and it should be of  type HtmlHelper. HtmlHelper is the class to which we are essentially adding an extension method for each helper function.

Here are a bunch of helper functions:

public static class SimpleCustomHtmlHelpers
{

  public static MvcHtmlString SubmitButton(this HtmlHelper helper, 
                                                 string id, 
                                                 string title)
 {
   string str = string.Format("<input type='submit' id='{0}'” +
                                “ value='{1}' />",  id, title);

   return MvcHtmlString.Create(str.ToString());
 }
 public static string MailTo(this HtmlHelper helper, 
                                    string emailAddress, 
                                    string textToDisplay)
{
   return String.Format("<a href='mailto:{0}'>{1}</a>", 
         emailAddress, textToDisplay);
}

public static string Image(this HtmlHelper helper, 
                                   string imageUrl, 
                                   string altText)
{
   return String.Format("<img src='{0}' alt='{1}' />", imageUrl, altText);
}
}
Using the above code will let us use following helper functions:
1. Html.SubmitButton(‘btnSubmit’, ‘Register’) 
2. Html.MailTo(‘abc@xyz.com’, ‘Email’)
3. Html.Image(‘/images/img.jpg’,’image’)

No Comments

SharePoint Server 2016 RC is now available

Both SharePoint 2016 and Project Server 2016 Release Candidate are not available. SharePoint 2016 RC is mostly feature complete and it’s now safe enough to evaluate it to get an overall picture of the final product. If you have older Beta 2 then it can be upgraded to RC.

If you have InfoPath 2013 and SharePoint Designer 2013 then they will continue to work with SharePoint 2016. Both will be supported for the duration of SharePoint 2016’s support lifecycle.

You can read about the prominent changes made to 2016 version in this blog post:

Permanent Link- Changes in SharePoint 2016

MinRole in SharePoint 2016

Permanent Link- Changes in SharePoint 2016 installation and deployment

No Comments

Exception handling in ASP.NET MVC applications

For exception handling we have been using try..catch..finally block since forever in various languages. In this blog we will see how to handle the unhandled exceptions in ASP.NET MVC. Unhandled exceptions are the exceptions that are not handled using try..catch..finally block. For handling unhandled exceptions or for creating a global exception handler we have to perform following steps:

1. In web.config add following line in the system.web section

<customErrors mode=”RemoteOnly”></customErrors>

2. Before each controller add following annotation:

[HandleError]

public ActionResult Index()

3. In Views folder create a sub-folder named Shared and create a file there named Error. Extension can be .cshtml (razor) or .aspx (web forms engine)

4. Optionally to the Error file add following code to display the actual error message:

@Model.Exception.Message

 

In case if you want to name the Error page something else then change the annotation before controller to [HandleError(View=”custom_name”)]. Replace custom_name with whatever your error page name is.

No Comments

New SharePoint CSOM version released for SharePoint Online

SharePoint supports two main development / deployment techniques for creating SharePoint projects: Server Object Model and Client-Side Object Model. If you plan on doing development for the hosted version of SharePoint, i.e. Office 365 / SharePoint Online, then you CSOM is the only option. A new SharePoint CSOM has been been released for SharePoint Online / Office 365. It also allows development for Project Online (hosted Project Server). It can be downloaded using “Manage NuGet Packages” option in Visual Studio. Just search for the id “Microsoft.SharePoitOnline.CSOM” and VS will download the required files.

No Comments

Microsoft has acquired Xamarin

Xamarin has been known for offering a native cross-platform development solution. It allows writing code using .NET and then running the same code on iOS, Android and WIndows devices. Microsoft has been supporting Xamarin tools in Visual Studio since VS 2013. But, now Microsoft has purchased Xamarin. It might boost Windows phone development and we might see more apps coming over to Windows. Even if Windows Phone apps don’t become popular it would still let .NET developers create cross-platform apps.

No Comments

Changes in SharePoint 2016

SharePoint 2016 is due later this year. It includes several changes based on the available preview version. Here are some of the prominent changes: (Note: they could change by the time the final version becomes available)

  1. 5,000 List View Threshold limit

    Technically, SharePoint 2013 allows 30 million items per list. But, OOB, as far as end-users are concerned it enforces 5,000 item limit since querying a large number of items from SQL Server content database is a very resource intensive operation. In SharePoint 2016, end-users won’t have to worry about 5,000 view threshold limit anymore. Technically, the limit is still there but SharePoint 2016 automatically creates indexed columns to overcome the limit.

  2. Upload File Size

    In older versions the max possible upload file size is 2GB. In SharePoint 2016 although there’s no real limit as such but Microsoft recommends 10GB as the max. file size. Anything larger than that can potentially result in time-out.

  3. Faster site collection creation

    In older version it took fairly long time to create a site collection. Depending on your hardware configuration it takes 30+ seconds to create a new site collection. In SharePoint 2016 now it’s possible to create a new site collection in a second. It requires some configuration with PowerShell to make this work.

  4. Improved Compliance Center

    Holds and retention policies have been available in older version. In SharePoint 2016, retention policies can be applied to files stored in OneDrive for Business as well.

  5. Mobile Device Support

    Although SharePoint 2013 also works on mobile devices, but SharePoint 2016 has even better support. It has better responsive web design and which makes it more touch friendly and distinguishes between a small screen device, e.g. a cell phone, and  a larder mobile device, e.g. a tablet.

  6. Zero Downtime Patching

    Admins should be pleased with this feature. SharePoint 2016 allows patching without requiring downtime. Also, the size and number of packages have been reduced which means patching should be performed much faster.

  7. MinRole

    This feature allows selecting a role for SharePoint server at the time installation. Selecting a role optimizes the SharePoint for that role. SharePoint 2016 also lets us check running services and if they are compliant with the MinRole. You can read more on MinRole in my blog post: http://blog.webagesolutions.com/archives/1522

  8. Same Codebase

    In the past Office 365 / SharePoint Online and on-premises SharePoint 2013 had separate codebase. SharePoint 2016 uses the same codebase for cloud and on-premises. It results in a more streamlined UI and development experience.

  9. Hybrid Cloud Search

    SharePoint 2016 search can index the content in the cloud as well which results in a more unified search experience. In order to make this work, Office 365 is necessary.

No Comments

SQL Server 2016 includes R Language

SQL Server 2016 should hit RTM sometime later this year. It includes several new features. You can read about some of the new features in my previous blog posts:

http://blog.webagesolutions.com/archives/1482

http://blog.webagesolutions.com/archives/1429

 

SQL Server 2016 also includes the R language for statistical computing and graphics. Here are some more details on the topic:

http://www.theregister.co.uk/2015/10/28/sql_server_2016_with_r/

,

No Comments

Generating Class(es) from JSON in Visual Studio

JSON is a very popular lightweight data-interchange format. Visual Studio makes it very easy to generate class / classes out of JSON. Say, we have the following JSON available:

{
  "players": {
    "player": [
      {
        "playerId": 1,
        "playerName": "Crosby",
        "gamesPlayed": 100
      },
      {
        "playerId": 2,
        "playerName": "Niedermayer",
        "gamesPlayed": 300
      }
    ]
  }
}

 

To generate C# classes out of the above JSON, copy the JSON to clipboard, in Visual Studio click Edit > Paste Special > Paste JSON as Classes.
It will generate following classes:
 
 public class Rootobject
    {
        public Players players { get; set; }
    }

    public class Players
    {
        public Player[] player { get; set; }
    }

    public class Player
    {
        public int playerId { get; set; }
        public string playerName { get; set; }
        public int gamesPlayed { get; set; }
    }
 
 
Now you can fine-tune some of the code, e.g. change Player[] to List<Player> etc.
 
This paste special option works well in Visual Studio 2015. In case if you have any older version of Visual Studio then you might want to 
add NewtonSoft JSON NuGet package to your project to make it work:
 
image

No Comments

Object Oriented Programming: JavaScript vs TypeScript in Visual Studio 2015

JavaScript has been the defacto web language for a very long time. It’s used for implementing client-side validation, animation, DOM manipulation, AJAX and for several other reasons. Developers have been using JavaScript in one form or other: e.g. plain vanilla JavaScript, jQuery, AngularJS etc. OOP in JavaScript is quite different than other languages, say C++/Java/C# etc. Here’s an example of a simple class in JavaScript:

//class, constructor function
var Employee = function (employeeId, employeeName, department) {
    //properties
    this.employeeId = employeeId;
    this.employeeName = employeeName;
    this.department = department;

    //method
    this.insertEmployee = function () {
        //insertEmployee logic goes here
    };
};
 
Alternatively, the above code can be written like this:
 
function Employee(employeeId, employeeName, department) { 
  this.employeeId = employeeId; 
  this.employeeName = employeeName; 
  this.department = department; 
} 
 
Employee.prototype.addEmployee = function () { 
  //insertEmployee logic goes here 
}; 
 
 
 
Wait, what? There’s no class keyword? No data types? class is a function? Yes! everything is a function in JavaScript.
Now you might say that you have spent years learning OOP syntax in other languages so how can you use similar syntax in JavaScript.
That’s where TypeScript comes into play. It’s created by Microsoft and lets you use a more “natural” / typical syntax and generates the JavaScript code 
behind the scenes. TypeScript is gaining popularity especially since AngularJS 2.0 is heavily utilizing it.
 
If you have Visual Studio 2015 then TypeScript is available OOB. For older version, like 2013, extension can be downloaded here: 
https://visualstudiogallery.msdn.microsoft.com/b1fff87e-d68b-4266-8bba-46fad76bbf22
 
Right click a web project in Visual Studio 2015, click Add New Item and select TypeScript:
image
 
Here’s the code for Employee.ts file:
 
class Employee {
    employeeId: number;
    employeeName: string;
    department: string;

    constructor(employeeId: number, employeeName: string, department: string) {
        this.employeeId = employeeId;
        this.employeeName = employeeName;
        this.department = department;
    }

    addEmployee() {
        //insertEmployee logic goes here
    }
};

 

That’s much closer to typical OOP syntax. There’s class keyword, properties construction & methods have much easier syntax and data types are there as well.
Visual Studio generates the corresponding JavaScript file behind the scenes

image

Here’s what the auto-generated code looks like:

var Employee = (function () {
    function Employee(employeeId, employeeName, department) {
        this.employeeId = employeeId;
        this.employeeName = employeeName;
        this.department = department;
    }
    Employee.prototype.addEmployee = function () {
        //insertEmployee logic goes here
    };
    return Employee;
})();
;

Here it’s using IIFE JavaScript syntax to return Employee function which represents the class.

So, we can see TypeScript has a much easier syntax. On day to day basis we can maintain the code in a TypeScript .ts file, but we do have to reference the auto-generated JavaScript file since web browsers only understand JavaScript, not the TypeScript.

, ,

No Comments

TDD / Unit Testing JavaScript in Visual Studio using Jasmine and Chutzpah

 

In this post we will see how to unit test JavaScript in Visual Studio using Jasmine and Chutzpah. We will use Visual Studio’s built-in Test Explorer window for displaying the results. Jasmine is a an open source unit testing / behavior-driven framework. It lets us write test cases. Chutzpah is an open source test runner. It runs jasmine tests, pulls in the results and displays them in Visual Studio’s Test Explorer window. It utilizes phantomjs framework, under the hood, for pulling in the results.

Let’s do some homework and create a bunch of JavaScript functions that we will unit test.

SimpleCalculator.js

var SimpleCalculator = function () {
    this.square = function (num1) {
        return num1 + num1;
    };

    this.sum = function (num1, num2) {
        return num1 * num2;
    };
};

Notice, we have added logical errors to the code so that tests can fail.

Next, we will add some extensions / NuGet packages to perform unit testing. 

Adding Jasmine framework

1. Right click the project and click Manage NuGet Packages

2. Search for Jasmine and install it

image

3. Notice Jasime has added a bunch of files.

image

Installing Chutzpah extension

1. In Tools menu, click Extensions and Updates

2. Search for Chutzpah and install Chutzpah Test Adapter for the Test Explorer

image

3. After installing Chutzpah, restart Visual Studio

4. In Tests menu, click Windows > Test Explorer. This is where all tests will show up.

Create unit tests using Jasmine framework

1. Create another JavaScript file where we will organize tests for SimpleCalculator that we created previously. Let’s name the file SimpleCalculator_Tests.js. Here are the file contents:

 

/// <reference path="../jasmine/jasmine.js" />
/// <reference path="../SimpleMath.js" />
describe("SimpleMath_Test", function () {
 var sc = new SimpleCalculator();

    it("sum_test", function () {
 var num1 = 5;
 var num2 = 6;
 var expected = 11;
 var actual = sc.sum(num1, num2);
        expect(actual).toBe(expected);
 });

    it("square_test", function () {
 var num1 = 5;
 var expected = 25;
 var actual = sc.square(num1);
        expect(actual).toBe(expected);
 });
});

 

As soon as we write a test, it appears in the Test Explorer win

dow. This is happening due to the Chutzpah plugin.

image

Running tests

In the Text Explorer, click Run All. Notice both tests have failed.

image

Go back to your original SimpleCalculator.js, fix the issues by changing operators used in sum and square functions and run the tests again. Notice, this time they have both passed.

image

Conclusion

Both Jasmine and Chutzpah are open source and make it very easy to unit test JavaScript code. It can be used with plain vanila JavaScript with libraries like JQuery and with frameworks like AngularJS etc.

, , ,

No Comments