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.


Wednesday 12 August 2015

Disable List Form Feilds Using Jquery in SharePoint

<!--Start Additional Custom Code -->

<script type="text/javascript" src="../../SiteAssets/jquery-1.11.3.min.js"></script>

<script type="text/javascript">

$(document).ready(function(){




$("input[Title='Title']").attr('disabled', 'disabled');    // To set the Title Feild Disable



alert( $("Select[Title='ServiceStage'] option:selected").text());  // To get the  dropdown ServiceStage Selected Value


$("textarea[Title='Title']").attr('disabled', 'disabled');  // To Disable the Multiline Feild




});
</script>




<!--End Additional Custom Code -->

Tuesday 30 June 2015

SharePoint Designer Workflow : Set the Custom List Field using LookUp Feild in SPD Workflow

Here, we need to set the Custom list Feild using Lookup item Value.

For that we used Sharepoint Workflow 2010 version and as we got some error to getting the Lookup value as a Text in the SharePoint Workflow 2013.

The Workflow is as below, this is the final workflow :





To set the  lookup item , we need to set the values as below.


And to set the Find the list Item section, we need to set the value as below  :


Then, we need to save and publish the workflow.
And also need to do some settings when we need to fire the workflow as per our requirement.


Filter the Lookup feild data based on some condition

We may have some requirement that we do not want to show all data of the lookup to every one.

I have some scenario as below :

I have the Master custom list named OfficeMaster and I use the lookup using this in Child list 'FacilityStatus'.

OfficeMaster Custom also had one more column named OfficeAdmin , which have the office Admin name, who can add data for this office.

In that, I just want to show that Office To admin , which office is assigned to him in the OfficeMaster List.

For that, I used the SPServices named "SPFilterDropdown()".

So, when Office Admin Login into the site, he can only see that offices whom Admin he is.

$().SPServices.SPFilterDropdown({
                                                  relationshipList: "OfficeMaster",
                                                  relationshipListColumn: "OfficeLocation",
                                                  columnName: "OfficeName",                                                                                                
                                                                                             
                                                  CAMLQuery: "<Eq><FieldRef Name='OfficeAdmin' /><Value Type='User'>"+username+"</Value></Eq>",
                                                  completefunc: null,
                                                  debug: true
                                                });
 
 


Here , username parameter is used which uses the users username. I am using the ECMA script for that and put that code above that.

this.context= SP.ClientContext.get_current();
            if (this.context!= undefined && context!= null) {

//assume we have a client context called context.
var web = context.get_web();
var user = web.get_currentUser(); //must load this to access info.
context.load(user);
//alert('start In Middle');
context.executeQueryAsync(function(){
  // alert("User is: " + user.get_title()); //there is also id, email, so this is pretty useful.
   
   username=user.get_title();
}, function(){alert(":(");});
}

ECMA Script : Can we pass some parameter in the function ?

Yes, we can pass some parameter in the ECMA Script function as normal as we are doing in the javascript function.


<script type="text/javascript" >

$(document).ready(function() {

$("Select[Title='OfficeName']").change(function() {

getLookUp($("Select[Title='OfficeName']").val());

});




});

</script>


<script language-="ecmascript" type="text/ecmascript">

 function getItemById(OfficeName)
{
        // get the Item for using the OfficeName.
}


</script>

ECMA Script : Call the ECMA Script funcation when page loads

If we want to call the ECMAScript function on page load , we can get the error like
"Unable to get property 'get_current' of undefined or null reference"

Because , before sp.js loads which is required to run our ECMAScript function, was not loaded and our ECMA funcation calls.

So, we need to wait untill our sp.js loads.
So, we need to call that function as below :


$(document).ready(function(){                                            
   var reslt= ExecuteOrDelayUntilScriptLoaded( getUserTitle, "sp.js");
});
                 

                });


function GetUserTitle()
{
          // function defination
}          

          

ECMA Script : Get list Item Count

In the below code, using ECMA Script , we get the data from some custom list and after that we can count the number of items in ECMA Script.




function retrieveListItems() {
var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('FacilityStatus');
 
    var camlQuery = new SP.CamlQuery();


    camlQuery.set_viewXml('<View><Query><Where><And><Eq><FieldRef Name=\'Process\' /><Value Type=\'Lookup\'>Physical Space Allocation</Value></Eq><Eq><FieldRef Name=\'FacilityName\' /><Value Type=\'Lookup\'>Training Room</Value></Eq></And></Where></Query></View>');

    this.collListItem = oList.getItems(camlQuery);
           
    clientContext.load(collListItem);
   

    clientContext.executeQueryAsync( function () {  count= collListItem.get_count(); } ,function(){alert(":(");});              
}

</script>

Append Data on Choice Field by getting the data using ECMASCript in SharePoint 2013



Here we are getting some data from the custom list and show that data in the choice filed in the list form.
To Get the data from the custom list, we are using ECMAScript and then we store that data in some collection and then we append that data one by one to the Choice filed using javascript.

Here we accept that, we put the reference of the jquery file in the page.


<script language-="ecmascript" type="text/ecmascript">
       
       
        var siteUrl = '/';
       
        var ItemContainer = { ItemList: [] };
       
        function retrieveListItems(lookupItem) {
       
        //alert('Hi..RetriveListItems');
        ItemContainer = { ItemList: [] };
        var clientContext = SP.ClientContext.get_current();
        // Get the SharePoint list by giving the display name of the list.
        var oList = clientContext.get_web().get_lists().getByTitle('Process');
        // To retreive all items use the predefined createAllItemsQuery operation.
        //alert(oList);
       
       // var camlQuery = SP.CamlQuery.createAllItemsQuery();

        var camlQuery = new SP.CamlQuery();
        camlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='OfficeType'/><Value Type='Lookup'>"+lookupItem+"</Value></Eq></Where></Query></View>");
       
        this.collListItem = oList.getItems(camlQuery);
        clientContext.load(collListItem);
       
        //alert('Go to call Method');
        this.clientContext.executeQueryAsync(
            Function.createDelegate(this, this.onListDataLoadQuerySucceeded),
            Function.createDelegate(this, this.onListDataLoadQueryFailed));
    }
   
   
     // Callback function if the item retrieval Async call get successful.
    function onListDataLoadQuerySucceeded(sender, args) {
   
   
    //alert('On Success Method');
        var listItemInfo = "";
      var  listItemEnumerator="";
        var listItemEnumerator = collListItem.getEnumerator();
        while (listItemEnumerator.moveNext()) {
            var oListItem = listItemEnumerator.get_current();
            // Fill a json object with Id and Value properties.
            var tempItem = { Id: oListItem.get_id(), Value: oListItem.get_item('Title') };
            ItemContainer.ItemList.push(tempItem);
        }
       
       
        // Fill the drop down with retrieved data.
        fillDropDown();
    }
 
 
    // Fill  the drop down with the retrieved list item data.
    function fillDropDown() {
   
    //alert('in fill dropdown');
    //alert(ItemContainer.ItemList.length);
    $("Select[Title='Process']").empty();
        var ddlCategory = $("Select[Title='Process']");
       
       
       
        if (ddlCategory != null) {
       
       // alert('In If loop .. found the dropdown');
        var newOption="<option value='0'>Choose Process</option>";
        $("Select[Title='Process']").append(newOption);
       
       
      //  alert(newOption);
       
            for (var i = 0; i < ItemContainer.ItemList.length; i++) {
           
                var theOption = new Option;
               
               // alert(ItemContainer.ItemList.length);
                //alert(ItemContainer.ItemList[i].Id);
                theOption.value = ItemContainer.ItemList[i].Id;
               
               
                //alert(ItemContainer.ItemList[i].Value);
                theOption.text = ItemContainer.ItemList[i].Value;
               
                //alert(theOption.text);
               
              //alert(ddlCategory.Items.length);
             
              //alert(ddlCategory.options[i]);
               
               // ddlCategory.options[i] = theOption;
                                               
var newOption = "<option value='"+theOption.value+"'>"+theOption.text+"</option>";

// alert(newOption);


$("Select[Title='Process']").append(newOption);





               
               
                //alert('success for dropdown');
               
                //alert(ddlCategory.options[i]);
            }
        }
    }
   
   
  function   onListDataLoadQueryFailed(sender, args)
  {
 
  //alert('In Fail');
  }
       
       
        </script>

SPSerives : ForEach kind of condition using GetlistItems


We can create the For each kind of looping using SPServies as per the below code.



function GetAvabilityStateWise()
{

var Qstring="<table style='border-collapse: collapse;'><tr ><th style='border: 1px solid black;'><b>StateName</b></th><th style='border: 1px solid black;'><b> %Availability of Services </b></th> <tr>";
$().SPServices({
                    operation: "GetListItems",
                    async: false,
                    listName: "StateMaster",
                    CAMLViewFields: "<ViewFields><FieldRef Name='Title'/></ViewFields>",
                    CAMLQuery: "",
                    //CAMLRowLimit: 2,
                    completefunc: function (xData, Status) {
                                   $(xData.responseXML).SPFilterNode("z:row").each(function() {
                                     
  var t  =$(this).attr("ows_Title");                                              
                                     
                                       var total= GetTotalCountForState(t);

  var avlb = GetAvilableTotalCountForState(t);

var per;

if(avlb != 0 && total != 0)
per = (avlb/total)*100;
else
per=0;


 
//Qstring += t + "         " + per  + "%<br/>";
Qstring +=  "<tr><td style='border: 1px solid black;'>" + t + "</td><td style='border: 1px solid black;'>" + per  + "%</td>";
                                                                                                               
                                                });
                                }
                });
               
         // alert(Qstring);
       
        $("#lblReport1").html(Qstring);
       
//document.getElementById('myId').innerHTML                                                                      
       
       

}


function GetTotalCountForState(StateName)
{
    var itemCount=0;
 
    var queryText = "<Query><Where><Eq><FieldRef Name='State' /><Value Type='Lookup'>"+StateName+"</Value></Eq></Where></Query>";
 
    $().SPServices({
        operation: "GetListItems",
        listName: "FacilityStatus",
        async: false,
        CAMLQuery: queryText,
        completefunc: function (xData, status) {

            //alert(xData.responseXML);
            itemCount = $(xData.responseXML).SPFilterNode("rs:data").attr("ItemCount");
           // alert(itemCount);

          //  $(".TextBox3").val(itemCount);

        }
       
     
    });
   
    return itemCount ;
           }




function GetAvilableTotalCountForState(StateName)
{


 
    var itemCount=0;
 
//var queryText = "<Query><Where><And><Eq><FieldRef Name='State' /><Value Type='Lookup'>Rajasthan</Value></Eq><Eq><FieldRef Name='ServiceStage' /><Value Type='Lookup'>Services Available</Value></Eq></And></Where></Query>";
   
var queryText = "<Query><Where><And><Eq><FieldRef Name='State' /><Value Type='Lookup'>"+StateName+"</Value></Eq><Eq><FieldRef Name='ServiceStage' /><Value Type='Lookup'>Services Available</Value></Eq></And></Where></Query>";
 
    $().SPServices({
        operation: "GetListItems",
        listName: "FacilityStatus",
        async: false,

        CAMLQuery: queryText,

        completefunc: function (xData, status) {

           // alert(xData.responseXML);
            itemCount = $(xData.responseXML).SPFilterNode("rs:data").attr("ItemCount");
            //alert("Avilable total for OfficeType "+ OfficeType +"is : " +itemCount);

          //  $(".TextBox3").val(itemCount);

        }
       
     
    });
   
    return itemCount ;
           }

SPServices : GetListItmes : Get Total Count of the Items

To Get the Total Number of items from the custom list which satisfy our caml query, the code is as below :

var queryText = "<Query><Where><Eq><FieldRef Name='OfficeType' /><Value Type='Lookup'>"+OfficeType+"</Value></Eq></Where></Query>";

$().SPServices({
        operation: "GetListItems",
        listName: "FacilityStatus",
        async: false,
        CAMLQuery: queryText,
        completefunc: function (xData, status) {          
            itemCount = $(xData.responseXML).SPFilterNode("rs:data").attr("ItemCount");           
        }
     
   
    });
 
    return itemCount ;
           }

Cascading DropDown Using SPServices in SharePoint 2013


For Cascading Drop down, first of all we need to refer two scripts as shown in the code and also need to store that files at the proper path in Sharepoint Site content or in any other library.

If we need to put the cascading dropdown in the List forms, we need to put the below code at the relative NewForm.aspx and EditForm,aspx in the ListForms and put the below code at the "PlaceHolderAdditionalPageHead" .


<asp:Content ContentPlaceHolderId="PlaceHolderAdditionalPageHead" runat="server">


<script language="javascript" type="text/javascript" src="../../JSLibrary/jquery-1.7.2.min.js"></script>
<script language="javascript" type="text/javascript" src="../../JSLibrary/jquery.SPServices-0.7.1a.min.js"></script>



<script type="text/javascript">

$(document).ready(function() {
$().SPServices.SPCascadeDropdowns({
relationshipList: "Facilities",
relationshipListParentColumn: "Process",
relationshipListChildColumn: "Title",
parentColumn: "Process",
childColumn: "FacilityName",
promptText: "Choose Facility...",
debug: true

});

});
</script>

</asp:content>

Tuesday 24 February 2015

Custom Master Page Add an app Loading Page Issue

Add the below snippet at the proper place in your custom master page will solve you problem

 <div id="s4-workspace">
            <div id="s4-bodyContainer">
           
         
               <div class="ms-dialogHidden" style="display:none;">
                            <h1 id="pageTitle" class="ms-core-pageTitle">
                                <!-- ===== STARTER: Needed for Adding Apps from Site Contents ======================================================================================= -->
                                <!--SPM:<SharePoint:AjaxDelta id="DeltaPlaceHolderPageTitleInTitleArea" runat="server">-->
                                <!--SPM:<asp:ContentPlaceHolder id="PlaceHolderPageTitleInTitleArea" runat="server">-->
                                    <!--SPM:<SharePoint:SPTitleBreadcrumb runat="server" RenderCurrentNodeAsLink="true" SiteMapProvider="SPContentMapProvider" CentralAdminSiteMapProvider="SPXmlAdminContentMapProvider">-->
                                        <!--SPM:<PATHSEPARATORTEMPLATE>-->
                                            <!--SPM:<SharePoint:ClusteredDirectionalSeparatorArrow runat="server"/>-->
                                        <!--SPM:</PATHSEPARATORTEMPLATE>-->
                                    <!--SPM:</SharePoint:SPTitleBreadcrumb>-->
                                <!--SPM:</asp:ContentPlaceHolder>-->
                                <!--SPM:</SharePoint:AjaxDelta>-->   
                                <div class="ms-displayInlineBlock ms-normalWrap">
                                    <a href="javascript:;" id="ms-pageDescriptionDiv" style="display:none;">
                                        <span id="ms-pageDescriptionImage">&#160;</span>
                                    </a>
                                    <span class="ms-accessible" id="ms-pageDescription">
                                        <!--SPM:<asp:ContentPlaceHolder id="PlaceHolderPageDescription" runat="server"/>-->
                                    </span>
                                    <!--SPM:<SharePoint:ScriptBlock runat="server">-->
                                        <!--SPM:_spBodyOnLoadFunctionNames.push("setupPageDescriptionCallout");-->
                                    <!--SPM:</SharePoint:ScriptBlock>-->
                                </div>
                            </h1>
                        </div>
                       
           
            <div id="sideNavBox" class="ms-dialogHidden ms-forceWrap ms-noList" style="display:none;">
                        <div class="ms-core-navigation">
                            <!--SPM:<asp:ContentPlaceHolder ID="PlaceHolderLeftNavBar" runat="server">-->
                                <!--SPM:<asp:ContentPlaceHolder ID="PlaceHolderLeftNavBarTop" runat="server">-->
                                    <!-- ===== STARTER: hide the quick launch for any page the doesn't override the PlaceHolderLeftNavBar ============ -->
                                    <!-- ===== STARTER: if you want the navigation back you can add it from the collab master ============ -->
                                    <!--SPM:<style type="text/css">//<![CDATA[-->
                                        <!--SPM:#contentBox { margin-left: 0; }-->
                                        <!--SPM:#sideNavBox { display: none; }-->
                                    <!--SPM://]]></style>-->
                                <!--SPM:</asp:ContentPlaceHolder>-->
                                <!--SPM:<asp:ContentPlaceHolder ID="PlaceHolderQuickLaunchTop" runat="server"/>-->
                                <!--SPM:<asp:ContentPlaceHolder ID="PlaceHolderLeftNavBarDataSource" runat="server"/>-->
                                <!--SPM:<asp:ContentPlaceHolder ID="PlaceHolderCalendarNavigator" runat="server"/>-->
                                <!--SPM:<asp:ContentPlaceHolder ID="PlaceHolderLeftActions" runat="server"/>-->
                                <!--SPM:<asp:ContentPlaceHolder ID="PlaceHolderQuickLaunchBottom" runat="server"/>-->
                            <!--SPM:</asp:ContentPlaceHolder>-->
                        </div>
                    </div>

// other content

</div>
</div>