Saturday, September 12, 2015

SharepPoint 2013 + Windows Server 2012 R2 Pre-requisite Install (Part 1)

This will save some time when building a SharePoint 2013 dev envionrment or when setting up SharePoint server in general.
Import-Module ServerManager

Add-WindowsFeature NET-WCF-HTTP-Activation45, NET-WCF-TCP-Activation45, NET-WCF-Pipe-Activation45

Add-WindowsFeature Net-Framework-Features,Web-Server,Web-WebServer,Web-Common-Http,Web-Static-Content,Web-Default-Doc,Web-Dir-Browsing,Web-Http-Errors,Web-App-Dev,Web-Asp-Net,Web-Net-Ext,Web-ISAPI-Ext,WEB-ISAPI-Filter,Web-Health,Web-Http-Logging,Web-Log-Libraries,Web-Request-Monitor,Web-Http-Tracing,Web-Security,Web-Basic-Auth,Web-Windows-Auth,Web-Filtering,Web-Digest-Auth,Web-Performance,Web-Stat-Compression,Web-Dyn-Compression,Web-Mgmt-Tools,Web-Mgmt-Console,Web-Mgmt-Compat,Web-Metabase,Application-Server,AS-Web-Support,AS-TCP-Port-Sharing,AS-WAS-Support,AS-HTTP-Activation,AS-TCP-Activation,AS-Named-Pipes,AS-Net-Framework,WAS,WAS-Process-Model,WAS-NET-Environment,WAS-Config-APIs,Web-Lgcy-Scripting,Windows-Identity-Foundation,Server-Media-Foundation,Xps-Viewer


Note: The third command is a single line. Remove any line-feed / carriage-return before running the script in PowerShell.

Sunday, September 6, 2015

.NET optimization service at very high CPU utilization

On Server 2012 R2, after running Windows Update to install important updates, the CPU utilization of the server could get pegged at 100% due to .NET optimization service (Ngen.exe).

As the name suggests, all installed .NET frameworks are being optimized via re-compiling, which leads to a prolonged period of 100% CPU usage.

Run the following if you want to get this optimization process over with at your command. Run it and come back after a while (10~20 min). When it is done, the server should behave normally.

 Get-ChildItem $env:SystemRoot\Microsoft.net\NGen.exe -recurse | ForEach-Object { & $_ executeQueuedItems }


Basically, the command above lets us to run "Ngen.exe  executeQueuedItems" per each .NET Framework versions manually at the time of our choosing, rather than letting the server finish when it can later, which may cause unexpected slowness in performance.

After optimization is done for each .NET Framework version, when running the command again, you will see confirmation message like below.


Thursday, September 3, 2015

C# quick extension method refresher - Left() and Right() methods

Here's a quick refresher of C#'s extension methods. If you are not familiar with or forgot about extension methods, check out this post at dotnetperls.


using System;
     
public class Program
{
 public static void Main()
 {
  Console.WriteLine("Hello World");
  
  string a = "Hello Orange County";  
  Console.WriteLine("a.Right(6) = " + a.Right(6));
  Console.WriteLine("a.Left(7) = " + a.Left(12));
 }
}

public static class ExtensionMethods
{
 public static string Right(this string original, int numChar)
 {
  string retVal = "";
  if(original != null && numChar >= 0)
  {
   return original.Substring(numChar > original.Length ? 0 : original.Length - numChar); 
  }
  return retVal;
 }
 
 public static string Left(this string original, int numChar)
 {
  string retVal = "";
  if(original != null && numChar >= 0)
  {
   return original.Substring(0, (numChar > original.Length ? original.Length : numChar));
  }
  return retVal;
 }
}

By the way, there is an amazing online C# compiler tool called ".NET Fiddle". It lets you quickly build and test your C# prototype program online, including ASP.NET MVC-based prototypes. Just like the JSFiddle, you can create your own account and start building your own personal code libraries.

Here's a review article about .NET Fiddle.

.Net Fiddle Screenshot

Monday, December 22, 2014

Chrome's console.table

Google Chrome's console.table( ) is a great feature.  The following example code (source) shows how powerful and useful this feature of Chrome can be.

var arr = [];
for( var i = 0; i < 256; i++ ){
  var char = String.fromCharCode( i );
  if( encodeURI( char ) !== encodeURIComponent( char )){
    arr.push({  
      character: char, 
      encodeURI: encodeURI( char ),
      encodeURIComponent: encodeURIComponent( char )
    });
  }
}
console.table( arr );

It produces the following table within the console of Chrome.
** Note: to enter line break in the Chrome's console, use [Shift] + [Enter] keys.


Sunday, November 23, 2014

Smooth Scroll in Visual Studio on VM Windows in Parallels Desktop

When using Visual Studio in Windows running on Parallels Desktop on Mac, I used to have a jumpy scroll issue on the Source Code or the Solution Explorer window. Whether I used the built-in MacBook Pro's TrackPad or an external mouse's scroll wheel, I was not able to fine-control the number of lines to scroll up or down while using the Visual Studio. The only way to scroll a few lines at a time was by using the scroll bar on the right, but this can be very counter-intruitive, since we are so used to the scrolling via the scroll wheel.

The easy workaround to this nuisance is rather simple. Go into the VM settings in the Parallels Desktop VM, select Hardware --> Mouse & Keyboard, and then un-check "Enable smooth scrolling".

Un-check "Enable smooth scrolling" to Enable smooth scrolling.

Wednesday, September 10, 2014

Static Member in C#

A good explanation and examples are found at http://csharp.net-tutorials.com/classes/static-members/

public class Rectangle
{
    private int width, height;
    public Rectangle(int width, int height)
    {
        this.width = width;
        this.height = height;
    }
    public void OutputArea()
    {
        Console.WriteLine("Area output: " + Rectangle.CalculateArea(this.width, this.height));
    }
    public static int CalculateArea(int width, int height)
    {
        return width * height;
    }
}


I like the author's example using Rectangle.CalculateArea( this.width, this.height) as an example of using a static member in a non-static class.

Thursday, September 4, 2014

Entity Framework : Update only changed fields instead of all fields

If we follow the Entity Framework's general approach to edit, it would be something similar to this.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "FacilityID, FacilityName, AddressLine1, AddressLine2")] 
Facility facility)
{
  ...
  if( ModelState.IsValid )
  {
    db.Entry(facility).State = EntityState.Modified;
    db.SaveChanges();
    return RedirectToAction("Index");
  }
..
}

The code in the above treats all fields as `Modified` and saves all field data into the database whether the old and new value of each field is the same or different.

However, there are times that we need to update only certain fields, instead of updating all fields data. The above example would update all field data (FacilityName, AddressLine1, AddressLine2), even when only AddressLine1 was changed by user. In order to save only the changed field data into the database, we can try the following approach: compare each field's value between old and new first and perform update only on the ones that are different.
using System.Data.Entity.Infrastructure;
...
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(
  [Bind(Include = "FacilityID, FacilityName, AddressLine1, AddressLine2")] 
   Facility facility)
{
  ...
  if( ModelState.IsValid)
  {
    db.Facilities.Attach( facility );
    DbEntityEntry entry = db.Entry( facility );
    foreach( var propertyName in entry.OriginalValues.PropertyNames )
    {
      // Get the old field value from the database.
      var original = entry.GetDatabaseValues().GetValue<object>(propertyName);
      // Get the current value from posted edit page.
      var current = entry.GetCurrentValues.GetValue<object>(propertyName);
      if(!object.Equals(original, current))
      {
        entry.Property( propertyName ).isModified = true;
      }
    }
    db.SaveChanges();
  }
}


Here we first get all property names (field names) and inspect each property's old and new values. Old values are retrieved from the database. New values are ones submitted by user through post.
// Get the old field value from the database.
var original = entry.GetDatabaseValues().GetValue<object>(propertyName); 
// Get the current value from posted edit page.
var current = entry.GetCurrentValues().GetValue<object>(propertyName); 
When the two values of original and current of a property are not equal,
that property will be assigned `IsModifed = true`, and its current value will be saved into the database.

On the other hand, if current field's values exist in the database already, those field values will be skipped while db.SaveChanges() is performed .