Wednesday, February 25, 2015

AngularJs append string by comma

  var roomUtiliesstr = '';
        angular.forEach($scope.RoomUtilisitesCollection, function (item) {

            if (item) {
                if (item.value == 'true') {
                    roomUtiliesstr += item.Title + ',';
                    // selectedUtility.push(item.Title);
                    //$scope.view.RoomUtilities.push(item.Title);
                }
            }
        });

Tuesday, February 24, 2015

AngularJs $http

The $http service is a core Angular service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP.

The $http service is a function which takes a single argument — a configuration object — that is used to generate an HTTP request and returns a promise with two $http specific methods: success and error.

// Simple GET request example :
$http.get('/someUrl').
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });
// Simple POST request example (passing data) :
$http.post('/someUrl', {msg:'hello word!'}).
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

Render json in table using AngularJs

1) HTML

<div ng-app="myApp">
<div ng-controller="PeopleCtrl">
    <p>    Click <a ng-click="loadPeople()">here</a> to load data.</p>
<table>
    <tr>
        <th>Id</th>
        <th>First Name</th>
        <th>Last Name</th>
    </tr>
    <tr ng-repeat="person in people">
        <td>{{person.id}}</td>
        <td>{{person.firstName}}</td>
        <td>{{person.lastName}}</td>
    </tr>
</table>
</div>
</div>
       
2) Controller.js

//Declare json
var mockDataForThisTest = "json=" + encodeURI(JSON.stringify([
    {
    id: 1,
    firstName: "Peter",
    lastName: "Jhons"},
{
    id: 2,
    firstName: "David",
    lastName: "Bowie"}
]));
//end of declaring json

var app = angular.module('myApp', []);//define app MyApp should be equal to  ng-app="myApp" in HTML

//controller will get call from ng-controller="PeopleCtrl"
function PeopleCtrl($scope, $http) {

    $scope.people = [];

    $scope.loadPeople = function() {
        var httpRequest = $http({
            method: 'POST',
            url: '/echo/json/',
            data: mockDataForThisTest

        }).success(function(data, status) {
            $scope.people = data;
        });

    };

}


Monday, February 23, 2015

JSON Data Types

Number{ "myNum": 123.456 }
A series of numbers; decimals ok; double-precision floating-point format.
String{ "myString": "abcdef" }
A series of characters (letters, numbers, or symbols); double-quoted UTF-8 with backslash escaping.
Boolean{ "myBool": true }
True or false.
Array{ "myArray": [ "a", "b", "c", "d" ] }
Sequence of comma-separated values (any data type); enclosed in square brackets.
Object{ "myObject": { "id": 7 } };
Unordered collection of comma-separated key/value pairs; enclosed in curly braces; properties (keys) are distinct strings.
Null{ "myNull": null }
Variable with null (empty) value.

What JSON looks like


JSON Example reads a menu from myTutorials.txt, and displays the menu in a web page

<div id="id01"></div>

<script>
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var myArr = JSON.parse(xmlhttp.responseText);
        myFunction(myArr);
    }
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

function myFunction(arr) {
    var out = "";
    var i;
    for(i = 0; i < arr.length; i++) {
        out += '<a href="' + arr[i].url + '">' + 
        arr[i].display + '</a><br>';
    }
    document.getElementById("id01").innerHTML = out;
}
</script>

Older browsers without the support for the JavaScript function JSON.parse() can use the eval() function to convert a JSON text into a JavaScript object:

var text = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';



var obj = eval ("(" + text + ")");

JSON Data can be modified like

var employees = [
    {"firstName":"John""lastName":"Doe"},
    {"firstName":"Anna""lastName":"Smith"},
    {"firstName":"Peter","lastName""Jones"}
];


employees[0].firstName = "Gilbert";

employees[0]["firstName"] = "Gilbert";

first entry in the JavaScript object array can be accessed like

var employees = [
    {"firstName":"John""lastName":"Doe"},
    {"firstName":"Anna""lastName":"Smith"},
    {"firstName":"Peter","lastName""Jones"}
];


// returns John Doeemployees[0].firstName + " " + employees[0].lastName;


// returns John Doeemployees[0]["firstName"] + " " + employees[0]["lastName"];

JSON vs XML

For AJAX applications, JSON is faster and easier than XML:
Using XML
  • Fetch an XML document
  • Use the XML DOM to loop through the document
  • Extract values and store in variables
Using JSON
  • Fetch a JSON string
  • JSON.Parse the JSON string

JSON Object Creation in JavaScript

<!DOCTYPE html>
<html>
<body>

<h2>JSON Object Creation in JavaScript</h2>

<p id="demo"></p>

<script>
var text = '{"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}'

var obj = JSON.parse(text);

document.getElementById("demo").innerHTML =
obj.name + "<br>" +
obj.street + "<br>" +
obj.phone;
</script>

</body>
</html>

JSON Object Creation in JavaScript

What is JSON

  • JSON stands for JavaScript Object Notation
  • JSON is a lightweight data-interchange format
  • JSON is language independent *
  • JSON is "self-describing" and easy to understand

XML example defines an employees object with 3 employee records

<employees>
    <employee>
        <firstName>John</firstName> <lastName>Doe</lastName>
    </employee>
    <employee>
        <firstName>Anna</firstName> <lastName>Smith</lastName>
    </employee>
    <employee>
        <firstName>Peter</firstName> <lastName>Jones</lastName>
    </employee>
</employees>

JSON example defines an employees object, with an array of 3 employee records

{"employees":[
    {"firstName":"John""lastName":"Doe"}, 
    {"firstName":"Anna""lastName":"Smith"},
    {"firstName":"Peter""lastName":"Jones"}
]}

Friday, February 20, 2015

C programming examples

asp.net complete lifecycle of a Web page

  • Page request - During this stage, ASP.NET makes sure the page either parsed or compiled and a cached version of the page can be sent in response
  • Start - During this stage sets the Request and Response page properties and the page check the page request is either a postback or a new request
  • Page Initialization - During this stage, the page initialize and the control's Unique Id property are set
  • Load - During this stage, if the request is postback, the control properties are loaded without loading the view state and control state otherwise loads the view state
  • Validation - During this stage, the controls are validated
  • Postback event handling - During this stage, if the request is a postback, handles the event
  • Rendering - During this stage, the page invokes the Render method to each control for return the output
  • Unload - During this stage, when the page is completely rendered and sent to the client, the page is unloaded.

Destructor in C#

Destructor is a special method that get invoked / called automatically whenever an object of a given class gets destroyed. Main idea behind using destructor is to free the memory used by the object.

Constructor in C#

Constructor is a special method that get invoked / called automatically whenever an object of a given class gets instantiated.

Interfaces in C#

An interface is similar to a class with method signatures. There wont be any implementation of the methods in Interface. Classes which implements interface should have implementation of methods defined in abstract class

Sealed Classes in c#

If a class is defined as Sealed it cannot be inherited in derived class.

public sealed class Car
{

public Car()
{
Console.WriteLine("Base Class Car");
}

public void DriveType()
{
Console.WriteLine("Right Hand ");
}
} 

Abstract Class in C#

If we don't want a class object to be created define the class as abstract. An abstract class can have abstract and non abstract classes. If a method in abstract id defined as abstract , it must be implemented in derived class. For example , in the classes given below , method DriveType is defined as abstract. 

abstract class Car
{
public Car()
{
Console.WriteLine("Base Class Car");
}
public abstract void DriveType();
}

class Ford : Car
{
public void DriveType()
{
Console.WriteLine("Right Hand ");
}
}

Method Hiding in C#

If the derived class doesn't want to use methods in base class , derived class can implement the same method in derived class with same signature. For example in the classes given below, DriveType() is implemented in the derived class with same signature. This is called Method Hiding.

class Car
{
public void DriveType()
{
Console.WriteLine("Right Hand Drive");
}
}

class Ford : Car
{
public void DriveType()
{
Console.WriteLine("Right Hand ");
}
}

Monday, February 16, 2015

Javascript How to get unique values in a array

var a = ["1", "1", "2", "3", "3", "1"];
var unique = a.filter(function(item, i, ar){ return ar.indexOf(item) === i; });

asp.net access values from dictionary

IDictionary<string, object> keyValueCollection //- Dictionary variable

KeyValuePair<string, object> escalateres;


         escalateres = keyValueCollection.Where(x => x.Key.ToLower().Trim() == "escalateres" &&
                   null != x.Value && x.Value.ToString() != "All").FirstOrDefault(); //access values of key "escalateres"

 List<object> lstEscalatersDetails = null; //define list variable

  lstEscalatersDetails = escalateres.Value as List<object>;

  foreach (object lstEscalatersDetail in lstEscalatersDetails)
                {
                    IDictionary<string, object> keyValueCollectionHelpDeskEcalatorTime = new Dictionary<string, object>();
                 
                    keyValueCollectionHelpDeskEcalator = lstEscalatersDetail as IDictionary<string, object>;

                    FormatEscalateTime = Convert.ToString(keyValueCollectionHelpDeskEcalator["Hrs"]) + ":" + Convert.ToString(keyValueCollectionHelpDeskEcalator["Mins"]);

                    KeyValuePair<string, object> EscalateTime = new KeyValuePair<string, object>("EscalateTime", FormatEscalateTime);

                    keyValueCollectionHelpDeskEcalatorTime.Add(EscalateTime);
                    keyValueCollectionHelpDeskEcalatorTime.Add("HelpDeskSLAId", id);
                    Save(keyValueCollectionHelpDeskEcalatorTime, "HelpDeskEscalators");

                }

Friday, February 13, 2015

ASP.NET Remove value from Dictionary

  keyValueCollection.Remove("ResolvedHrs");
                keyValueCollection.Remove("ResolvedMin");

Thursday, February 12, 2015

ASP.NET access value from Dictionary and format it and add value again in dictionary

   FormatResolvedHrsMins = Convert.ToString(keyValueCollection["ResolvedHrs"]) + ":" + Convert.ToString(keyValueCollection["ResolvedMin"]);
                KeyValuePair<string, object> ExpectedClosure = new KeyValuePair<string, object>("ExpectedClosure", FormatResolvedHrsMins);
                keyValueCollection.Add(ExpectedClosure);

Wednesday, February 11, 2015

SharePoint disable loopback check (DisableLoopbackCheck dword in registry)

Ive found this very handy.. recently, I was working on a server and we were trying to access the local SharePoint site http://127.0.0.1 or http://nameoflocalserver/pages/default.aspx and I was constantly prompted for the username and password. In SharePoint 2010, it can really annoy you by not accepting your username password credentials in the popup window.
Its a ‘feature’ on the server that you need to disable as a workaround (if you are an Admin/Developer) on a DEVELOPMENT and PREPROD environment.
Caution: Microsoft Best practices is out of scope in this article. Do your own research on this topic.
There are two methods to do this:
1.  Specify the host names in the registry – BackConnectionHostNames (more secure and recommended for PRODUCTION servers). Refer http://support.microsoft.com/kb/896861
2. Disable the loopback check – DisableLoopbackCheck (less secure and recommended for DEVELOPMENT environments). Read on to use this method 2 and add via an easy powershell cmd.
You would need to create a DWORD registry key in the registry called DisableLoopbackCheckand set it to 1.
Follow these steps:
Option 1: Add this registry entry by PowerShell
New-ItemProperty HKLM:\System\CurrentControlSet\Control\Lsa -Name "DisableLoopbackCheck" -value "1" -PropertyType dword
Option 2: Add this registry entry manually
Click Start, click Run, type regedit, and then click OK
In Registry Editor, locate the following registry key:HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa
Right-click Lsa, point to New, and then click DWORD Value. (In Win 2008, its DWORD 32bit)
Type DisableLoopbackCheck, and then press ENTER.
Right-click DisableLoopbackCheck, and then click Modify.
In the Value data box, type 1 and then click OK.
Quit Registry Editor.
You may need to restart your server.
For more information about this, click the following article number to view the article in the Microsoft Knowledge Base: 281308 (http://support.microsoft.com/kb/281308/ ) Connecting to SMB share on a Windows 2000-based computer or a Windows Server 2003-based computer may not work with an alias name.

Monday, February 9, 2015

Sharepoint CSOM adds a field to a SharePoint list

// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

SP.List list = context.Web.Lists.GetByTitle("Announcements"); 

SP.Field field = list.Fields.AddFieldAsXml("<Field DisplayName='MyField2' Type='Number' />", 
                                           true, 
                                           AddFieldOptions.DefaultValue); 
SP.FieldNumber fldNumber = context.CastTo<FieldNumber>(field); 
fldNumber.MaximumValue = 100; 
fldNumber.MinimumValue = 35; 
fldNumber.Update(); 

context.ExecuteQuery(); 

Sharepoint CSOM Delete a SharePoint list

// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

// The SharePoint web at the URL.
Web web = context.Web; 

List list = web.Lists.GetByTitle("My List"); 
list.DeleteObject(); 

context.ExecuteQuery();  

Sharepoint CSOM Create and update a SharePoint list

// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

// The SharePoint web at the URL.
Web web = context.Web; 

ListCreationInformation creationInfo = new ListCreationInformation(); 
creationInfo.Title = "My List"; 
creationInfo.TemplateType = (int)ListTemplateType.Announcements; 
List list = web.Lists.Add(creationInfo); 
list.Description = "New Description"; 

list.Update(); 
context.ExecuteQuery(); 

Sharepoint CSOM LoadQuery method to store the return value in another collection, rather than use the web.Lists property

// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

// The SharePoint web at the URL.
Web web = context.Web; 

// Retrieve all lists from the server, and put the return value in another 
// collection instead of the web.Lists. 
IEnumerable<SP.List> result = context.LoadQuery(web.Lists.Include( // For each list, retrieve Title and Id.
                                                                   list => list.Title, 
                                                                   list => list.Id)); 

// Execute query. 
context.ExecuteQuery(); 

// Enumerate the result. 
foreach (List list in web.Lists) 
{ 
    label1.Text = label1.Text + ", " + list.Title; 
} 

Sharepoint CSOM Retrieve all SharePoint lists in a web

// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

// The SharePoint web at the URL.
Web web = context.Web; 

// Retrieve all lists from the server. 
context.Load(web.Lists, 
             lists => lists.Include(list => list.Title, // For each list, retrieve Title and Id. 
                                    list => list.Id)); 

// Execute query. 
context.ExecuteQuery(); 

// Enumerate the web.Lists. 
foreach (List list in web.Lists) 
{ 
    label1.Text = label1.Text + ", " + list.Title; 
} 

Sharepoint CSOM Create a new SharePoint website

// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

WebCreationInformation creation = new WebCreationInformation(); 
creation.Url = "web1"; 
creation.Title = "Hello web1"; 
Web newWeb = context.Web.Webs.Add(creation); 

// Retrieve the new web information. 
context.Load(newWeb, w => w.Title); 
context.ExecuteQuery(); 

label1.Text = newWeb.Title; 

Sharepoint CSOM Write to website's properties

// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

// The SharePoint web at the URL.
Web web = context.Web; 

web.Title = "New Title"; 
web.Description = "New Description"; 

// Note that the web.Update() does not trigger a request to the server
// because the client library until ExecuteQuery() is called. 
web.Update(); 

// Execute the query to server.
context.ExecuteQuery();