Friday 1 April 2016

Convert DateTime in particular format in Asp.Net C#

If you have date 5 March,1989 as 03/05/1989 in MM/dd/yyyy format and you want to convert it to
dd/MM/yyyy i.e. 05/03/1989 , then use below C# code for that :


DateTime dtValidity = DateTime.ParseExact(strDate, "M/d/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

return dtValidity.ToString("d/M/yyyy");


Saturday 31 October 2015

Steps to create Timer Job and Event Receiver

Timer Job :

Timer Job is the automated schudled task , which runs in the background of SharePoint.

Steps to create Timer Job :
(1) Create Empty SharePoint Solutions.
(2) Select Farm Solution and then validate the Site.
(3) Create New class ... Inherite it with the SPJobDefination Class
(4) Define three diffrent type of constructors of that class
(5) Also Override the Execute method => Which contains the actual code/ Bussiness logic we need to execure

(6) Now, we need to cretae Feature and also need to add Event Receiver ...!!!
(7) Add feature to the Solution and make its scope to WebApplication level. => Feature task done.
(8) Now, Add Event Receiver and write some code in it which will execute while FeatureActivated and FeatureDeactivated method.
We need to create  CreateJob and DeleteJob Functions here and then we need to call the class of which we just created.
We also need to Schedule calls in to job.schedule class to the timer job class.
Also, we can set the time for fire the Timer job here.

(9) And then deploy the solution .. timer job is deployed .
=======================================================

 Event Receiver :

(1) For this we need to add the Event Receiver Template in the solution.
(2) We need to select, what is the source for the event receiver... after that we need to select the method on which we need to fire the code / Business Logic.
(3) We can also add these methods after wards as required , by go in the property window for the event receiver.
(4) To get the ListItem , we can use the [SPEventProperties]properties parameter of that method like properties.ListItem["FeildName"]

To get the current site url , we can get the => properties.site.openWeb() -> Will give the current web Url.

(5) If we need to fire the Event Receiver to some specific list only, then we can set the List
<Receivers ListUrl="Lists/Facilities" > , in the element.xml file
after that the event receiver will only fire on that list only.
=> We can also check this while execute the code by => properties.ListTilte = "" => and then we can execute the code.

(6) Try to put the feature of the event receiver separate.

============================


Friday 16 October 2015

SharePoint Custom Solution Deployement PowerShell Command

stsadm –o addsolution –name SharePointProject2.wsp

Add-SPSolution c:\code\SharePointProject2\bin\debug\SharePointProject2.wsp

=====================================

stsadm –o deploysolution –name SharePointProject2.wsp –url http://moss-server –allowCasPolicies –immediate

Install-SPSolution –Identity SharePointProject2.wsp –WebApplication http://sp2010 -GACDeployment

====================================

stsadm –o upgradesolution –name SharePointProject2.wsp –filename SharePointProject2.wsp –immediate –allowCasPolicies

Update-SPSolution –Identity SharePointProject2.wsp –LiteralPath c:\code\SharePointProject2\bin\debug\SharePointProject2.wsp –GACDeployment

===================================

Uninstall-SPSolution –Identity SharePointProject2.wsp –WebApplication http://sp2010

Remove-SPSolution –Identity SharePointProject2.wsp

================
Get-Help

=======================

stsadm.exe –o activatefeature –name Reporting –url http://sp2010

Enable-SPFeature –Identity Reporting –url http://sp2010

============================

Get-SPFeature [ –Web, –Site, –WebApplication, and –Farm] http://sp2010

Get-SPFeature –Identity [FeatureName] –Site http://sp2010


========================

Disable-SPFeature –Identity Reporting –url http://sp2010

Disable-SPFeature –Identity Reporting –url http://sp2010 –Confirm:$false


=========================

I also want to share the url for the blog from where I found the above commands , it is very useful L

http://www.dotnetmafia.com/blogs/dotnettipoftheday/archive/2009/12/02/adding-and-deploying-solutions-with-powershell-in-sharepoint-2010.aspx

http://www.dotnetmafia.com/blogs/dotnettipoftheday/archive/2011/01/04/activating-and-deactivating-features-with-powershell-in-sharepoint-2010.aspx

These blogs have the detail for all the commands and also have some extra information for the poweshell and stsadm commands.

Thanks.

Tuesday 18 August 2015

Hide the SharePoint Team site Page Ribbon and Quick Launch using css in SharePoint 2013

Put the below code snippet in the "PlaceHolderAdditionalPageHead" content place holder.


<SharePoint:StyleBlock runat="server">
body #s4-leftpanel {
display:none;
}
.s4-ca {
margin-left:0px;
}

.ms-core-listMenu-verticalBox,#s4-ribbonrow {display:none;}
#s4-titlerow {display:none!important;}
.ms-webpartPage-root {
&nbsp;&nbsp;&nbsp;&nbsp; border-spacing: 0px
!important;
}
.ms-webpartzone-cell {
margin: 0px !important;
&nbsp;}
#suiteBar{display:none;}
</SharePoint:StyleBlock>

Friday 14 August 2015

ECMAScript Crud operation in SharePoint 2013




$(document).ready( function(){

$("#btnSave").click(function(){ AddListItem();} );


$("#btnUpdate").click(function(){ UpdateListItem();} );


$("#btnDelete").click(function(){

alert('Delete button is clicked ...!!!!');
DeleteListItem1();} );
}

);







function AddListItem(){
alert('AddListItem called ..!!');

    var ListName = "TestList";
    var context = new SP.ClientContext.get_current(); // the current context is taken by default here
    //you can also create a particular site context as follows
    //var context = new SP.ClientContext('/Sites/site1');
    var lstObject = context.get_web().get_lists().getByTitle(ListName);
    var listItemCreationInfo = new SP.ListItemCreationInformation();
    var newItem = lstObject.addItem(listItemCreationInfo);
    newItem.set_item('Title', 'This is new item');
    // set values to other columns of the list here
    newItem.update();
   
    alert('Hi...');
   
//context.executeQueryAsync(Function.createDelegate(this, this.onAddSuccess),Function.createDelegate(this, this.onAddFailure));

context.executeQueryAsync( function onAddSuccess() { alert('Item created: ' + newItem.get_id());} , Function.createDelegate(this, this.onAddFailure));


   
 }
     function onAddSuccess() { alert('Item created: ' + newItem.get_id());}

    function onAddFailure(sender, args) {

        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }











function UpdateListItem()
{
var ListName = "TestList";
var context = new SP.ClientContext.get_current(); // the current context is taken by default here
//you can also create a particular site context as follows
//var context = new SP.ClientContext('/Sites/site1');

var lstObject = context.get_web().get_lists().getByTitle(ListName);
this.lstObjectItem = lstObject.getItemById(75);
lstObjectItem.set_item('Title', 'This is updated item');
lstObjectItem.update();
lstObject.set_description("Updated description using ECMAScript");
lstObject.update();
context.executeQueryAsync(Function.createDelegate(this, this.onUpdateSuccess),
Function.createDelegate(this, this.onUpdateFailure));
}

function onUpdateSuccess() {
alert('Item udated');
}

function onUpdateFailure(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}







function DeleteListItem1()
{
alert('Delete function is callaed ...!!');

var ListName = "TestList";
var context = new SP.ClientContext.get_current(); // the current context is taken by default here
//you can also create a particular site context as follows
//var context = new SP.ClientContext('/Sites/site1');

var lstObject = context.get_web().get_lists().getByTitle(ListName);
this.lstObjectItem = lstObject.getItemById(75);
lstObjectItem.deleteObject();

context.executeQueryAsync(Function.createDelegate(this, this.onSuccess),
Function.createDelegate(this, this.onFailure));
}

function onSuccess() {
alert('Item Deleted');
}

function onFailure(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

CRUD Operation with REST API in SharePoint 2013

Here , for example we take a custom List named 'TestList' with two columns .
(1) Title
(2) Designation

Below is the js file code snipped which have the CRUD operation functions.




// handle the click event of the button

$(document).ready( function(){


$("#btnSubmit").click(function(){

//alert ("Site" + _spPageContextInfo.siteAbsoluteUrl  );

//alert( "Web" +   _spPageContextInfo.webAbsoluteUrl );

CreateNew();

}  );


// Upadte Button


$("#btnUpdate").click( function() {

Update();

});



$("#btnDelete").click( function(){

deleteItem(54);
}
);



});



//===============   Start Create Item ============================================ //



// occurs when a user clicks the create button
function CreateNew() {
    var listName = "TestList";
    var newItemTitle = "New Title Item";
    CreateListItemWithDetails(listName, newItemTitle) ;
}

// CREATE Operation
// listName: The name of the list you want to get items from
// weburl: The url of the web that the list is in.
// newItemTitle: New Item title.
// success: The function to execute if the call is sucesfull
// failure: The function to execute if the call fails
function CreateListItemWithDetails(listName, newItemTitle) {
    var itemType = GetItemTypeForListName(listName);
    var item = {
        "__metadata": { "type": itemType },
        "Title": newItemTitle,
        "Designation" : 'Project Manager'
       
    };

 alert(JSON.stringify(item));


    $.ajax({
        url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
        type: "POST",
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(item),
        headers: {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function (data) {
             success();
           
            //alert('success');
        },
        error: function (data) {
            failure();
         
           //alert('Error');
        }
    });
}

// Get List Item Type metadata
function GetItemTypeForListName(name) {
    return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}



//function success() { alert("New Item has been created successfully."); } // getListItems("TestList");}


function failure() {
     alert("Ooops, an error occured. Please try again.");
 }



//===============   End Create Item ============================================ //





// ============================================== Start Update Item  =================================================== //



// occurs when a user clicks the update button
function Update() {
    var listName = "TestList";
    var url = _spPageContextInfo.webAbsoluteUrl;
    var itemId = "55"; // Update Item Id here
    var title = "New Updated Title";
    updateListItem(itemId, listName, url, title, function () {
        alert("Item updated, refreshing avilable items");
    }, function () {
        alert("Ooops, an error occured. Please try again");
    });
}

// Update Operation
// listName: The name of the list you want to get items from
// siteurl: The url of the site that the list is in. // title: The value of the title field for the new item
// itemId: the id of the item to update
// success: The function to execute if the call is sucesfull
// failure: The function to execute if the call fails
function updateListItem(itemId, listName, siteUrl, title, success, failure) {


//alert('In UpdatelistItem');

    var itemType = GetItemTypeForListName(listName);

    var item = {
        "__metadata": { "type": itemType },
        "Title": title
    };

    getListItemWithId(itemId, listName, siteUrl, function (data) {
   
    alert('Update success function is called ..!!!'+ data.__metadata.uri );
   
    alert("Etag is  : " + data.d.__metadata.etag );
   
        $.ajax({
            url: data.__metadata.uri,
            type: "POST",
            contentType: "application/json;odata=verbose",
            data: JSON.stringify(item),
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "X-HTTP-Method": "MERGE",
                "If-Match": data.d.__metadata.etag
               // "If-Match": "*"
            },
            success: function (data) {
               // success(data);
               
                alert ('success');
               
            },
            error: function (data) {
                //failure(data);
               
                alert ('error');
            }
        });
    }, function (data) {
        failure(data);
    });
}


function getListItemWithId(itemId, listName, siteurl, success, failure) {

//alert('In GetListItemWithId');


    var url = siteurl + "/_api/web/lists/getbytitle('" + listName + "')/items?$filter=Id eq " + itemId;
   // alert(url);
   
    $.ajax({
        url: url,
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            if (data.d.results.length == 1) {
             
// alert('Item is fetched ..!!!'+ JSON.stringify(data.d.results[0]) );              
  success(data.d.results[0]);              
             
            }
            else {
               // failure("Multiple results obtained for the specified Id value");
            }
        },
        error: function (data) {
            //failure(data);
           
            alert('Item not found ...!!!');
           
        }
    });
}




// ============================================== End Update Item  =================================================== //







// ============================= Start Delete Item ================================================================= //




function deleteItem(id) {
alert('Delete Function is called ..!!!');

var DeleteItemUrl = "/_api/Web/Lists/GetByTitle('TestList')/getItemById('"+id+"')";
    $.ajax({      
        url: _spPageContextInfo.webAbsoluteUrl + DeleteItemUrl,
        type: "POST",
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "If-Match": "*",
            "X-Http-Method": "DELETE"
        },
        success: function (data) {
           alert('Delete Successfully ..!!!');
        },
        error: function (error) {
            alert(JSON.stringify(error));
        }
    });
}












// ============================= End Delete Item ================================================================= //


function getListItems(listname ) {
// Getting our list items
$.ajax({
//url: url + "/_api/web/lists/getbytitle('" + listname + "')/items(" + id + ")",
//url: url + "/_api/web/lists/getbytitle('" + listname + "')/Items",
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listname + "')/Items",

method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
// Returning the results
 
  var items = data.d.results;
 
  var html = "<table>";
 
  for (var i = 0; i < items.length; i++)
  {          
//alert(items[i].Id+ " : " + items[i].Title);      

html = html + "<tr> <td>"+items[i].Id+"</td> <td>"+items[i].Title+"</td> </tr>";

}

html = html+ "</table>" ;

//$("#resultarea").append(html);



$("#resultarea").html(html);



},
error: function (data) {
alert('In Error..'+JSON.stringify(data)); }
});
};


function complete(data) {
alert("Completed successfully."  );



var jsonObject = JSON.parse(data.body);

alert(jsonObject );

var results = jsonObject.d.results;

for (var i = 0; i < results.length; i++) {

           alert('In for loop ..!!!' +  results[i].Title);

        }


}
function failure(data) {
alert("Operation failed.");
}

Thursday 13 August 2015

HTML Table Export To Excel _ In SharePoint Using Custom WebPart

I had some requirement that I want to export my html table to Excel sheet. So, I used to below some line of code for that.

public void ExportExcel()
        {
            Response.AppendHeader("content-disposition", "attachment;filename=ExportedHtml.xls");
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = "application/vnd.ms-excel";
            this.EnableViewState = false;
            Response.Write(ExportDiv);
            Response.End();

        }

But, Here I got some problem. After downloading the excel sheet by browser, the Page was unresponsive i.e. no postback was there after the file downloaded. That was very strange for me, because the same code was working with the normal asp.net page and not with the SharePoint Page.
But thanks to Google and StackOverflow, that I got some link with the excect issue and solution.

Actually, when we download the excel file using the http, at that time for SharePoint Page , there is one property named _spFormOnSubmitCalled becomes true , which is by default false.
We will set it to the false again and the postback will work for us.

The detailed information you will get from the below link :
http://stackoverflow.com/questions/2336883/post-back-does-not-work-after-writing-files-to-response-in-asp-net



Here, when we download the Excel file, we got the warning for the formate of the excel sheet , we need to use another way to solve it.

We need to use below code for that : 

Hope, this blog will help you.

Thanks.