Friday, 27 February 2015

Setting maxlength to a textarea

The maxlength attribute is new for the <textarea> tag in HTML5.

But what if  you are not using html5 or what if your browser doesn't support this attribute.

You might have faced this issue where you being not able to set maxlength property to a textarea.

So here is the trick using the power of Jquery  :P.

var maxLength = 50; //Set the length here
$(document).ready(function(){
setMaxLenTexrArea();
});
function setMaxLenTexrArea() {
    $("textarea").each(function () {
        $(this).on('change keydown keyup keypress paste blur', function () {
            restrictLength($(this).prop('id'));
        });
    });
}
function restrictLength(ta) {
 
    var txtVal = $("#" + ta).val();
    if (txtVal.length > maxLength) {
        txtVal = txtVal.substring(0, maxLength);
        $("#" + ta).val(txtVal);
    }
}
Explanation: 

  • maxLength variable will hold the length.
  • On document load we will be calling setMaxLenTexrArea() method.
  • We will be restricting the user to enter (type/paste) only allowed number of characters by checking the existing values length in the textarea and not allowing further if it has reached thr limit.
Hope it helped you :)

Friday, 13 February 2015

LINQ: Dynamic Groupby, OrderBy, and Dynamic Aggregates.

How to dynamically achieve groupby, orderby and aggregates using LINQ ?
huh.. what..? Is it is possible.. yes it is.. Here is the solution.

Here are some of our helper methods:

private static object GetPropertyValue(object obj, string propertyName)
        {
            return obj.GetType().GetProperty(propertyName).GetValue(obj, null);
        }
private static double GetPropertyValueDouble(object obj, string propertyName)
        {
            double ret = Convert.ToDouble(obj.GetType().GetProperty(propertyName).GetValue(obj, null));
            return ret;
        }
Consider below sample example:
 public class test
    {
        public string City { get; set; }
        public string Name { get; set; }
        public string State { get; set; }
        public double Cost { get; set; }
    } 
          List<test> xxx = new List<test>(){
                            new test(){City="MNG",Name="Jhon",State="KNK",Cost=10},
                            new test(){City="MNG",Name="Jhon",State="KNK",Cost=19},
                            new test(){City="BLR",Name="Jhon",State="DL",Cost=66},
                            new test(){City="BLR",Name="Jhon",State="DL",Cost=67},
                            new test(){City="BLR",Name="Jhon",State="DL",Cost=67}
                        };

                    switch (aggregate)
                    {
                        case "Count":
                            var grouped1 = xxx.GroupBy(x => GetPropertyValue(x, "City"))
                                            .Select(n => new
                                            {
                                                EntityName = n.Key,
                                                TotalCost = n.Count()
                                            });
                            return grouped1;
                        case "Sum":
                            var grouped2 = xxx.GroupBy(x => GetPropertyValue(x, "City"))
                                            .Select(n => new
                                            {
                                                EntityName = n.Key,
                                                TotalCost = n.Sum(a => GetPropertyValueDouble(a, "Cost"))
                                            });
                            return grouped2;
                        case "Average":
                            var grouped3 = xxx.GroupBy(x => GetPropertyValue(x, "City"))
                                             .Select(n => new
                                             {
                                                 EntityName = n.Key,
                                                 TotalCost = n.Average(a => GetPropertyValueDouble(a, "Cost"))
                                             });
                            return grouped3;

                        default:
                            break;
                    }

Hope it helped you. :)

C#: How to dynamically invoke a method from a Class, when you know the ClassName and Method Name as string

How to invoke a method from a Class, when you know the ClassName and Method Name as string in C#.
Here is the Solution.

Consider below helper method: (change the namespace, version and public key tokens accordingly)
 public static Type GetTypeFromClassName(string ClassName)
        {
            string ss = string.Format("Solutions.Common.{0}, Solutions.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3a6a3aa5a3aed1e3", ClassName);
            Type typeYouWant = Type.GetType(ss);
            if (typeYouWant != null)
            {
                return typeYouWant;
            }
            return null;
        }
For explanation of above method, read my below post.
Creating Object of a Class dynamically when you have name of the Class as string in C#?


string ClassName="MyClass";
string MethodName="MyMethod";
string param1="IT";
Type ClassType = GetTypeFromClassName(ClassName);
var myObj = Activator.CreateInstance(ClassType);
MethodInfo method = ClassType.GetMethod(MethodName);
var ReportData = method.Invoke(myObj, new object[] { param1});
Explanation:
First , get the type of the Class using GetTypeFromClassName
Create the object of the class. Activator.CreateInstance does this job.
Get the method by method name. Type.GetMethod(methodNme).
Invoke the method. method.Invoke.
param1 is the parameter which is getting sent to MyMethod function.

For the above scenario, your Class and method would have defined this way:

namespace Solutions.Common
{
    public class MyClass
    {
       //class properties
       public List<Employee> MyMethod(string dept)
        {
             List<employees> emps=new List<employees> ();
             //.................
            // operations....
            //...............
            return employees;
         }
     }
}
You can also get all the methods of this class by below code:

 MethodInfo[] methods= ClassType.GetMethods();

Hope it helped you. :) 

Creating Object of a Class dynamically when you have name of the Class as string in C#?

How to create an object of a class dynamically when you have the name of class as string in c#. Here is the solution.

First, get the type of the class.
Below helper method Returns the Type of your class. Here Solutions.Common is the Namespace of your class. To get the Version and PublicKeyToken, go to run (window+r) , type assembly, search for your assembly, right click , properties and get these details.

 public static Type GetTypeFromClassName(string ClassName)
        {
            string ss = string.Format("Solutions.Common.{0}, Solutions.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3a6a3aa5a3aed1e3", ClassName);
            Type typeYouWant = Type.GetType(ss);
            if (typeYouWant != null)
            {
                return typeYouWant;
            }
            return null;
        }
So object of any class can be created by using above helper method as below:

Type CustomClassType = Helpers.GetTypeFromStringFromCommon("CustomClassName");
var CustomObj = Activator.CreateInstance(CustomClassType ); 
Now you have the object of your class using the string ClassName.

Hope it helped you.

Thursday, 12 February 2015

Reading List and List Attributes of List using REST API SharePoint 2013

We can read a SharePoint List/Library and its all attributes by consuming the REST endpoint:

http://server/_api/lists/getbytitle('listname')

For example, below url retrieves all the attributes of the library (or list) Account.

https://xxx.sharepoint.com/_api/lists/getbytitle(‘Account’)


Example JSON response (part of it) from the above REST call. Marked are some of the attributes required for us:

  "AllowContentTypes": true,
        "BaseTemplate": 101,
        "BaseType": 1,
        "ContentTypesEnabled": false,
        "CrawlNonDefaultViews": false,
        "Created": "2015-01-05T11:06:56Z",
        "DefaultContentApprovalWorkflowId": "00000000-0000-0000-0000-000000000000",
        "Description": "",
        "Direction": "none",
        "DocumentTemplateUrl": "/SalesForce Files/Forms/template.dotx",
        "DraftVersionVisibility": 0,
        "EnableAttachments": false,
        "EnableFolderCreation": true,
        "EnableMinorVersions": false,
        "EnableModeration": false,
        "EnableVersioning": true,
        "EntityTypeName": "SalesForce_x0020_Files",
        "ForceCheckout": false,
        "HasExternalDataSource": false,
        "Hidden": false,
        "Id": "d5f89928-6c33-476d-a80c-54fcf0d57164",
        "ImageUrl": "/_layouts/15/images/itdl.png?rev=38",
        "IrmEnabled": false,
        "IrmExpire": false,
        "IrmReject": false,
        "IsApplicationList": false,
        "IsCatalog": false,
        "IsPrivate": false,
        "ItemCount": 3,
        "LastItemDeletedDate": "2015-01-05T11:27:20Z",
        "LastItemModifiedDate": "2015-01-16T07:22:05Z",
        "ListItemEntityTypeFullName": "SP.Data.SalesForce_x0020_FilesItem",
        "MajorVersionLimit": 0,
        "MajorWithMinorVersionsLimit": 0,
        "MultipleDataList": false,
        "NoCrawl": false,
        "ParentWebUrl": "/",
        "ParserDisabled": false,
        "ServerTemplateCanCreateFolders": true,
        "TemplateFeatureId": "00bfea71-e717-4e80-aa17-d0c71b360101",
        "Title": "SalesForce Files"

Here as i marked in yellow:

BaseTemplate
100: List
101: Library
Created
Created Date
Description
Description of the List
Hidden
False. False indicates that it is not hidden and not system defined.
Id
Unique id of the List
ItemCount
Number of items in the Lisut
LastItemModifiedDate
Last modified date
title
Name of the List

Reading Fields for a List using REST API SharePoint 2013

We can read the all the fields in a SharePoint list by consuming the REST endpoint:

http://server/_api/lists/getbytitle('listname')/fields

for example, below url retrieves  all the fields in the library(or list) Accounts:

https://xxx.sharepoint.com/_api/lists/getbytitle('Accounts')/fields

Return value: (I have marked in yellow, some of the important noticeable properties).

{
    "d": {
        "results": [
            {
                {
                "__metadata": {
                    "id": "https://xxx.sharepoint.com/_api/Web/Lists(guid'd5f89928-6c33-476d-a80c-54fcf0d57164')/Fields(guid'0953b0e6-65c1-41e8-98da-869f106b0669')",
                    "uri": "https://xxx.sharepoint.com/_api/Web/Lists(guid'd5f89928-6c33-476d-a80c-54fcf0d57164')/Fields(guid'0953b0e6-65c1-41e8-98da-869f106b0669')",
                    "type": "SP.FieldText"
                },
                "DescriptionResource": {
                    "__deferred": {
                        "uri": "https://xxx.sharepoint.com/_api/Web/Lists(guid'd5f89928-6c33-476d-a80c-54fcf0d57164')/Fields(guid'0953b0e6-65c1-41e8-98da-869f106b0669')/DescriptionResource"
                    }
                },
                "TitleResource": {
                    "__deferred": {
                        "uri": "https://xxx.sharepoint.com/_api/Web/Lists(guid'd5f89928-6c33-476d-a80c-54fcf0d57164')/Fields(guid'0953b0e6-65c1-41e8-98da-869f106b0669')/TitleResource"
                    }
                },
                "AutoIndexed": false,
                "CanBeDeleted": true,
                "DefaultValue": null,
                "Description": "",
                "Direction": "none",
                "EnforceUniqueValues": false,
                "EntityPropertyName": "AccountId",
                "Filterable": true,
                "FromBaseType": false,
                "Group": "Custom Columns",
                "Hidden": false,
                "Id": "0953b0e6-65c1-41e8-98da-869f106b0669",
                "Indexed": false,
                "InternalName": "AccountId",
                "JSLink": "clienttemplates.js",
                "ReadOnlyField": false,
                "Required": false,
                "SchemaXml": "<Field Type=\"Text\" DisplayName=\"AccountId\" Required=\"FALSE\" EnforceUniqueValues=\"FALSE\" Indexed=\"FALSE\" MaxLength=\"255\" ID=\"{0953b0e6-65c1-41e8-98da-869f106b0669}\" SourceID=\"{d5f89928-6c33-476d-a80c-54fcf0d57164}\" StaticName=\"AccountId\" Name=\"AccountId\" ColName=\"nvarchar10\" RowOrdinal=\"0\" />",
                "Scope": "/SalesForce Files",
                "Sealed": false,
                "Sortable": true,
                "StaticName": "AccountId",
                "Title": "AccountId",
                "FieldTypeKind": 2,
                "TypeAsString": "Text",
                "TypeDisplayName": "Single line of text",
                "TypeShortDescription": "Single line of text",
                "ValidationFormula": null,
                "ValidationMessage": null,
                "MaxLength": 255
            },
            {
                "__metadata": {
                    "id": "https://xxx.sharepoint.com/_api/Web/Lists(guid'd5f89928-6c33-476d-a80c-54fcf0d57164')/Fields(guid'7d522db6-c085-4161-bbff-d11a538c57a9')",
                    "uri": "https://xxx.sharepoint.com/_api/Web/Lists(guid'd5f89928-6c33-476d-a80c-54fcf0d57164')/Fields(guid'7d522db6-c085-4161-bbff-d11a538c57a9')",
                    "type": "SP.FieldText"
                },
                "DescriptionResource": {
                    "__deferred": {
                        "uri": "https://xxx.sharepoint.com/_api/Web/Lists(guid'd5f89928-6c33-476d-a80c-54fcf0d57164')/Fields(guid'7d522db6-c085-4161-bbff-d11a538c57a9')/DescriptionResource"
                    }
                },
                "TitleResource": {
                    "__deferred": {
                        "uri": "https://xxx.sharepoint.com/_api/Web/Lists(guid'd5f89928-6c33-476d-a80c-54fcf0d57164')/Fields(guid'7d522db6-c085-4161-bbff-d11a538c57a9')/TitleResource"
                    }
                },
                "AutoIndexed": false,
                "CanBeDeleted": true,
                "DefaultValue": null,
                "Description": "",
                "Direction": "none",
                "EnforceUniqueValues": false,
                "EntityPropertyName": "File_x0020_Type0",
                "Filterable": true,
                "FromBaseType": false,
                "Group": "Custom Columns",
                "Hidden": false,
                "Id": "7d522db6-c085-4161-bbff-d11a538c57a9",
                "Indexed": false,
                "InternalName": "File_x0020_Type0",
                "JSLink": "clienttemplates.js",
                "ReadOnlyField": false,
                "Required": false,
                "SchemaXml": "<Field Type=\"Text\" DisplayName=\"File Type\" Required=\"FALSE\" EnforceUniqueValues=\"FALSE\" Indexed=\"FALSE\" MaxLength=\"255\" ID=\"{7d522db6-c085-4161-bbff-d11a538c57a9}\" SourceID=\"{d5f89928-6c33-476d-a80c-54fcf0d57164}\" StaticName=\"File_x0020_Type0\" Name=\"File_x0020_Type0\" ColName=\"nvarchar11\" RowOrdinal=\"0\" Version=\"1\" />",
                "Scope": "/SalesForce Files",
                "Sealed": false,
                "Sortable": true,
                "StaticName": "File_x0020_Type0",
                "Title": "File Type",
                "FieldTypeKind": 2,
                "TypeAsString": "Text",
                "TypeDisplayName": "Single line of text",
                "TypeShortDescription": "Single line of text",
                "ValidationFormula": null,
                "ValidationMessage": null,
                "MaxLength": 255
            },

           . . . . . . .  .

Here as i marked in yellow:

Hidden
false  (Indicates that this field is not system defined and used for internal purpose).
Internal Name
Name of the field as defined internally by SharePoint.
Title
Title of the field.
TypeAsString
Type of the field in text.
FieldTypeKind
Refer below link for possible values:         

Hope it helped you :)