Friday, June 24, 2016

Check if SharePoint page is in edit mode in Javascript

If embedded javascript code needs to check if the sharepoint page is in edit mode, the script below can be used.

var inDesignMode = document.forms[MSOWebPartPageFormName].MSOLayout_InDesignMode.value;

if (inDesignMode == "1")
{
    // page is in edit mode
}
else
{
    // page is in browse mode
}

Copied from http://sharepoint.stackexchange.com/questions/12792/how-do-i-know-if-the-page-is-in-edit-mode-from-javascript

Wednesday, June 22, 2016

SQL Server error Cannot execute as the database principal because the principal “dbo” does not exist

After restoring adventure works database, when trying to see database diagrams I got an error Cannot execute as the database principal because the principal “dbo” does not exist.

The solution is to reassign database owner using script
use [databasename] EXEC sp_changedbowner 'sa'

More Info

Tuesday, June 21, 2016

Add sharepoint snap in to all powershell windows

The post below explains a very convenient way to add SharePoint snap in to powershell windows on dev server.

In brief:

  1. Run following command in Powershell ISE
    • if (!(test-path $profile.AllUsersAllHosts)) {new-item -type file -path $profile.AllUsersAllHosts –force} powershell_ise $profile.AllUsersAllHosts
  2. Append following code to the newly open powershell file
    • $ver = $host | select version if ($ver.Version.Major -gt 1) {$host.Runspace.ThreadOptions = "ReuseThread"} if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) { Add-PSSnapin "Microsoft.SharePoint.PowerShell" }
Also, you might like the environment path to include some of the key locations e.g.

$env:Path = $env:Path + "C:\Program Files
\Common Files\Microsoft Shared\Web Server Extensions\15\Bin;C:\Windows\System32\inetsrv\;C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools\x64"


https://blogs.msdn.microsoft.com/kaevans/2011/11/14/add-microsoft-sharepoint-powershell-snap-in-to-all-powershell-windows/

Monday, May 30, 2016

Knockout Datepicker update not triggerred

In a project which uses knockout datepicker binding mentioned at
http://stackoverflow.com/questions/6612705/jquery-ui-datepicker-change-event-not-caught-by-knockoutjs the datepicker update event was not triggered and hence observable value was not being updated.

I found a solution by changing "changeDate" event to simply "change".

so finally the binding handler looks like
ko.bindingHandlers.datepicker = {
    init: function(element, valueAccessor, allBindingsAccessor) {
        //initialize datepicker with some optional options
        var options = allBindingsAccessor().datepickerOptions || {},
            $el = $(element);

        $el.datepicker(options);

        //handle the field changing by registering datepicker's changeDate event
        ko.utils.registerEventHandler(element, "change", function () {
            var observable = valueAccessor();
            observable($el.datepicker("getDate"));
        });

        //handle disposal (if KO removes by the template binding)
        ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
            $el.datepicker("destroy");
        });

    },
    update: function(element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor()),
            $el = $(element);

        //handle date data coming via json from Microsoft
        if (String(value).indexOf('/Date(') == 0) {
            value = new Date(parseInt(value.replace(/\/Date\((.*?)\)\//gi, "$1")));
        }

        var current = $el.datepicker("getDate");

        if (value - current !== 0) {
            $el.datepicker("setDate", value);
        }
    }
};
and html looks like
<input data-bind="datepicker: myDate, datepickerOptions: { minDate: new Date() }" />

Tuesday, April 5, 2016

C# Sort two objects based on property names as string

I faced a situation where it was not possible to data in sql queries using any of the standard ways (Linq to SQL, Entity Framework, Stored Procedures, etc.) thus the data had to be sorted at controller method.

Little uncomfortable using static property names and wanted to pass the property name of the sort column as a string value, I ended up writing a custom comparer class as below

/// <summary>
    /// Compares two objects of same type based on value of the SortBy property
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class SortComparer<T> : Comparer<T>
    {
        public string SortBy = string.Empty;
        public bool SortDescending = true;

        public SortComparer() { }

        public SortComparer(string sortBy, bool sortDescending)
        {
            SortBy = sortBy;
            SortDescending = sortDescending;
        }

        public override int Compare(T x, T y)
        {
            PropertyInfo propInfo = x.GetType().GetProperty(SortBy);
            if (propInfo != null)
            {
                var obj1 = propInfo.GetValue(x, new object[0]) as IComparable;
                var obj2 = propInfo.GetValue(y, new object[0]) as IComparable;
                if (obj1 != null)
                {
                    if (obj2 != null)
                    {
                        return SortDescending ? obj2.CompareTo(obj1) : obj1.CompareTo(obj2);
                    }
                    else
                    {
                        return SortDescending ? -1 : 1;
                    }
                }
                else if (obj2 != null)
                {
                    return SortDescending ? 1 : -1;
                }
            }
            return 0;
        }
    }

c# linq Sort by column name stored in a string variable

Frequently I have encountered the requirement to implent sort on individual columns in a table. I thought that the easiest and most intutive way of implementing this in MVC controller was to express the column name as a string variable value. But after a couple of attempts I realised that the default Sort method of IQueryable interface in linq does not work and hence we need to add our own method to do this task.

Google search quickly returned some nice results, but in short something like this should work.

private static IOrderedQueryable<T> OrderingHelper<T>(IQueryable<T> source, string propertyName, bool descending, bool anotherLevel)
{
    ParameterExpression param = Expression.Parameter(typeof(T), string.Empty); // I don't care about some naming
    MemberExpression property = Expression.PropertyOrField(param, propertyName);
    LambdaExpression sort = Expression.Lambda(property, param);
    MethodCallExpression call = Expression.Call(
        typeof(Queryable),
        (!anotherLevel ? "OrderBy" : "ThenBy") + (descending ? "Descending" : string.Empty),
        new[] { typeof(T), property.Type },
        source.Expression,
        Expression.Quote(sort));
    return (IOrderedQueryable<T>)source.Provider.CreateQuery<T>(call);
}
public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string propertyName)
{
    return OrderingHelper(source, propertyName, false, false);
}
public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string propertyName)
{
    return OrderingHelper(source, propertyName, true, false);
}
public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string propertyName)
{
    return OrderingHelper(source, propertyName, false, true);
}
public static IOrderedQueryable<T> ThenByDescending<T>(this IOrderedQueryable<T> source, string propertyName)
{
    return OrderingHelper(source, propertyName, true, true);
}
 
 
 
More Links

Monday, March 21, 2016

Leaning Topics

Newtonsoft.Json 
Bigazi Modeller
Tiny MCE Editor
Less CSS
Kendo UI
MVC
Entity Framwork
DataAnnotations 
 Supergoo ABCpdf converter
Hammer.js 
Typemock
 

Regex Email validation in c# dot net core

 Use this regex /^_?[a-zA-Z0-9]([a-zA-Z0-9]*[._+-])*[a-zA-Z0-9_]+@(?!-)[A-Za-z0-9-]{1,63}(?<!-)(\.(?!-)[A-Za-z0-9-]{1,63}(?<!-))*\.[A-...