Tuesday, 18 June 2013

SharePoint 2013 Apps: Accessing Data in the Host Web in a SharePoint-Hosted App

How to get the hosting  web title in sharepoint app ?


refer here

var context;
var web;
var user;
function sharePointReady() {
context = new SP.ClientContext.get_current();
web = context.get_web();
context.load(web,"Title");
context.executeQueryAsync(onGetWebSuccess, onGetWebFail)
}
function onGetWebSuccess() {
$('#message').text('The title of this App is ' + web.get_title());
}
function onGetWebFail(sender, args) {
alert('Failed to get user name. Error:' + args.get_message());
}
This code results in the following output:
This is the easy scenario. If I’m developing a SharePoint-hosted app, then I can easily get to the App Web through the clientcontext.get_current( )method which returns the current context that the user is running in.
However, if you want to access information in the Host Web, a different approach is required. You might think that you can just load the context of the app using SP.ClientContext and passing the string of the Host Web like so…
var web;
var hostcontext;
function sharePointReady() {
var hostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
hostcontext = new SP.ClientContext(hostUrl);
web = hostcontext.get_web();
hostcontext.load(web, "Title");
hostcontext.executeQueryAsync(onGetWebSuccess, onGetWebFail);
}
function onGetWebSuccess() {
$('#message').text("The title of the host web of this app is " + web.get_title());
}
function onGetWebFail(sender, args) {
alert('Failed to get lists. Error:' + args.get_message());
}
//this is just the sample function that's in all the MS samples
function getQueryStringParameter(paramToRetrieve) {
var params =
document.URL.split("?")[1].split("&");
var strParams = "";
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == paramToRetrieve)
return singleParam[1];
}
}
 …But nope. As soon as you try to execute a query against anything in that context, this is what you get:

So what is the right way? You need to use an object called the AppSiteContext. If you swap out the sharePointReady function from the previous example with this…
function sharePointReady() {
var hostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
currentcontext = new SP.ClientContext.get_current();
hostcontext = new SP.AppContextSite(currentcontext, hostUrl);
web = hostcontext.get_web();
currentcontext.load(web, "Title");
currentcontext.executeQueryAsync(onGetWebSuccess, onGetWebFail);
}
Additionally, you must give the app read access to the Host Site Collection through the App Manifest.
Once you configure this, then you get the output we’re expecting:
The AppContextSite uses the current context to load the Host Web Context. In the background, the SharePoint client object model is brokering all the tokens and fun Oauth security for you so that the App can act on your behalf when it accesses the Host Web.
For those of you who are REST purists, an example of doing the same thing is on the this Technet article [http://msdn.microsoft.com/en-us/library/fp179927.aspx]. But in my app, I’m using the Client Object Model and there really weren’t any examples out there that showed how to do this using CSOM.

Monday, 25 March 2013

Error occurred in deployment step 'Activate Features' Attempted to perform an unauthorized operation.


Having this error was so annoying since I tried to google it but no step-by-step instructions how to fix it. Anyway, I had this error while trying to deploy thevisual web part for Sharepoint 2010 within VS 2010. There are at least 2 reasons why you’re getting this error:
1.    Bear in mind that you can only deploy the solution of the visual web part at a farm level. You will get this error while trying to deploy the solution at a site level. This is related to the correct site url you enter while creating the project. It is recommended that you always click on “Validate”.
2.    It is so obvious from the message that your windows login does not have the right “site collection” permission.
What I’m going to talk about and step through is point #2 (not having the right permission). Reason being is whichever the windows login that you’re using to deploy the solution, Sharepoint will use it to check if you’re authorised to deploy any solutions or not (not just deploying actually).
Step 1
Fire up the Sharepoint 2010 Central Administration.
Step 2
Go to Application Management –> Change site collection administrations
Step 3
Select the correct site collection and type your windows account as the secondary site collection administrator
Now try to deploy the solution again and it should work! 


Number validation using javascript


<HTML>
   <HEAD>
   <SCRIPT language=Javascript>
      <!--
      function isNumberKey(evt)
      {
         var charCode = (evt.which) ? evt.which : event.keyCode
         if (charCode > 31 && (charCode < 48 || charCode > 57))
{alert("Enter Only Numbers");

            return false;
}

         return true;
      }
      //-->
   </SCRIPT>
   </HEAD>
   <BODY>
      <INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar">
   </BODY>
</HTML>

Use of caml query with datetime


 string[] dates;
      try
      {
          SPSecurity.RunWithElevatedPrivileges(delegate
          {

              using (SPSite oSite = new SPSite(SPContext.Current.Web.Url))
              {
                  using (SPWeb oWeb = oSite.OpenWeb())
                  {
                     
                      SPList list = SPContext.Current.Web.Lists["General Tasks"];
                      CustomListViewByQuery.List = list;
                      string query = null;
                      SPQuery qry = new SPQuery(list.DefaultView);
                      int iCnt = 0;
                      // Prepare start and end dates
                       DateTime startDate = new DateTime();
                       DateTime endDate = new DateTime();
                       if (ddlReports.SelectedValue == "Monthly")
                       {                        

                           dates = this.GetRange(FrequencyType.Monthly, DateTime.Today);
                           startDate = Convert.ToDateTime(dates[0]);
                           endDate= Convert.ToDateTime(dates[1]);
                           //startDate = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1);
                           //endDate = startDate.AddMonths(1).AddMinutes(-1);
                       }
                     
                       else if (ddlReports.SelectedValue == "Weekly")
                       {
                           dates = this.GetRange(FrequencyType.Weekly, DateTime.Today);
                           startDate = Convert.ToDateTime(dates[0]);
                           endDate = Convert.ToDateTime(dates[1]);
                       }
                   
                      Response.Write(startDate.ToString());
                       Response.Write(endDate.ToString());

                      // Format dates
                      string startDateFx = startDate.ToString("yyyy-MM-ddTHH:mm:ssZ");
                      string endDatFx = endDate.ToString("yyyy-MM-ddTHH:mm:ssZ");
                       Response.Write(startDateFx);
                       Response.Write(endDatFx);

                      try
                      {
//                         query = @" <Where>    
//         <Eq>
//            <FieldRef Name='Priority' />
//            <Value Type='Choice'>(1) High</Value>
//         </Eq>            
//   </Where>";
                          query = @"<Where><And><Leq><FieldRef Name='DueDate' /><Value Type='DateTime'   IncludeTimeValue='FALSE'>"+endDatFx+"</Value></Leq><Geq><FieldRef Name='DueDate' /><Value Type='DateTime'  IncludeTimeValue='FALSE'>"+startDateFx+"</Value> </Geq></And></Where>";

                          //query = @"<View>" +
                          //              "<Query>" +
                          //                  "<Where>" +
                          //                  "<And>"+
                          //                       "<Eq>"+
                          //                          "<FieldRef Name='Priority' />"+
                          //                          "<Value Type='Choice'>(1) High</Value>"+
                          //                       "</Eq>"+
                          //                       "<Eq>"+
                          //                              "<And>" +
                          //                                  "<Geq>" +
                          //                                      "<FieldRef Name='DueDate'/>" +
                          //                                      "<Value Type='DateTime' IncludeTimeValue='FALSE'>" + startDateFx + "</Value>" +
                          //                                  "</Geq>" +
                          //                                  "<Leq>" +
                          //                                      "<FieldRef Name='DueDate'/>" +
                          //                                      "<Value Type='DateTime' IncludeTimeValue='FALSE'>" + endDatFx + "</Value>" +
                          //                                  "</Leq>" +
                          //                              "</And>" +
                          //                      "</Eq>"+
                          //                  "</And>"+                                                      
                          //                  "</Where>" +
                          //              "</Query>" +
                          //       "</View>";
                          qry.Query = query;
                          CustomListViewByQuery.Query = qry;
                          CustomListViewByQuery.List = list;
                          CustomListViewByQuery.DisableFilter = true;
                          CustomListViewByQuery.DisableSort = true;
                          iCnt++;

                          if (iCnt > 0)
                          {

                              CustomListViewByQuery.Visible = true;

                          }
                      }
                      catch (Exception ex)
                      {
                      }
                  }
              }
          });
      }
      catch { }
   

Check browser in sharepoint pages


function BrowserCheck()
{

   if (navigator.appName == "Microsoft Internet Explorer") {        
    }
    else {      
        alert("Please login to Microsoft Internet Explorer for submitting PM's Weekly Status Sheet. You will be redirected to a blank page");
        window.location = "../../Redirect.aspx";
        //var date_WeekStartDate_1=document.getElementById('<%=WeekStartDate_1.Controls[0].ClientID%>');
//var date_WeekEndDate_1=document.getElementById('<%=WeekEndDate_1.Controls[0].ClientID%>');

        return false;
    }
}

Sharepoint multiline textbox validation


Sharepoint multiline textbox validation


function PreSaveAction()    {

var checkItem = $('#<%=lblTrueFalse.ClientID%>').val();  
         if (checkItem == "true")
         {
var value1=GetV3TextField('Approval Comments');
var Approvalvalue="";
if(navigator.appName == "Microsoft Internet Explorer")
{
Approvalvalue=$(value1).closest("span").find("iframe[Title='Rich Text Editor']").contents().find("body").text();

}
else
{
Approvalvalue=$(value1).val();
}
//var Approvalvalue=$(value1).val();

if(Approvalvalue =='' || Approvalvalue ==null)
{
alert('Please add some comments');
return false;
}
else
{

return true;
}

}
}

Export to pdf and export to excel in sharepoint webaparts using itextsharp


using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;

using System.Collections;
using System.Drawing.Imaging;
using System.Web;
using System.Text;  


protected void btnExportToPdf_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = (DataTable)ViewState["GeneralTask"];
                BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
                iTextSharp.text.Font font = new iTextSharp.text.Font(bfTimes, 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

                //Create a dummy GridView CssClass="grdStyle"
                GridView GridView1 = new GridView();
                GridView1.AllowPaging = false;
                GridView1.DataSource = dt;
                GridView1.DataBind();
                GridView1.CssClass = "grdStyle";


                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment;filename=ActivityExport.pdf");
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                using (StringWriter sw = new StringWriter())
                {
                    using (HtmlTextWriter hw = new HtmlTextWriter(sw))
                    {
                        GridView1.RenderControl(hw);
                        StringReader sr = new StringReader(sw.ToString());
                        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
                        pdfDoc.SetPageSize(PageSize.A4.Rotate());
                        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
                        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                        pdfDoc.Open();
                        htmlparser.Parse(sr);
                        pdfDoc.Close();
                        Response.Write(pdfDoc);
                        Response.End();
                    }
                }

            }
            catch { }
        }

        protected void btnExportToExcel_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = (DataTable)ViewState["GeneralTask"];
                GridView GridView1 = new GridView();
                GridView1.AllowPaging = false;
                GridView1.DataSource = dt;
                GridView1.DataBind();

                Response.Buffer = true;

                Response.AddHeader("content-disposition", string.Format("attachment;filename=ActivityReport.xls"));
                Response.Charset = "";

                Response.Cache.SetCacheability(HttpCacheability.NoCache);

                Response.ContentType = "application/vnd.xls";
                using (StringWriter stringWrite = new System.IO.StringWriter())
                {
                    using (HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite))
                    {
                        GridView1.RenderControl(htmlWrite);
                        Response.Write(stringWrite.ToString());

                        Response.Flush();
                        Response.Clear();
                        Response.End();
                    }
                }

            }
            catch { }
        }

Find the dll's here :---Itextsharp 5.3.0.0

Dropdown Unchanged event in share point for lookup exceeding value 20



http://social.technet.microsoft.com/Forums/en/sharepointadmin/thread/7003ef85-38bf-450b-91b4-4725733c5384


function getField(fieldType,fieldTitle) {
    var docTags = document.getElementsByTagName(fieldType);
    for (var i=0; i < docTags.length; i++) {
        if (docTags[i].title == fieldTitle) {
            return docTags[i]
        }
    }
}

2. I use the following lines of code to determine if the control is a lookup with < 19 options or one with > 19 options and accordingly set my function to be called either on "onchange" event or on "onblur" event

if(getField('select','Role') != null){   //incase of lookup having < 19 options
 if(getField('select','Role').type == 'select-one'){
  getField('select','Role').onchange = function() {syncDropDowns()};
 }
}else if(getField('input','Role') != null){  //incase of lookup having > 19 options
 if(getField('input','Role').type == 'text'){
  getField('input','Role').onblur = function() {syncDropDowns()};
 }
}




function getField(fieldType,fieldTitle) {
    var docTags = document.getElementsByTagName(fieldType);
    for (var i=0; i < docTags.length; i++) {
        if (docTags[i].title == fieldTitle) {
            return docTags[i]
        }
    }
}

2. I use the following lines of code to determine if the control is a lookup with < 19 options or one with > 19 options and accordingly set my function to be called either on "onchange" event or on "onblur" event

if(getField('select','Role') != null){   //incase of lookup having < 19 options
 if(getField('select','Role').type == 'select-one'){
  getField('select','Role').onchange = function() {syncDropDowns()};
 }
}else if(getField('input','Role') != null){  //incase of lookup having > 19 options
 if(getField('input','Role').type == 'text'){
  getField('input','Role').onblur = function() {syncDropDowns()};
 }
}


or simple call the spservices j query and use following method to convert the input field to select.

$().SPServices.SPComplexToSimpleDropdown({
 columnName: "State"
});

Get Lookupvalue in client context using ecma script


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

        var listItem;
        var list;
        var clientContext;

        function getLookUp() {
            this.clientContext = SP.ClientContext.get_current();
            if (this.clientContext != undefined && clientContext != null) {
                var webSite = clientContext.get_web();
                this.list = webSite.get_lists().getByTitle("Custom");
                this.listItem = list.getItemById(5);
                clientContext.load(this.listItem);
                this.clientContext.executeQueryAsync(Function.createDelegate(this, this.OnLoadSuccess), Function.createDelegate(this, this.OnLoadFailed));
            }
        }

        function OnLoadSuccess(sender, args) {
            var lookup = this.listItem.get_item("LookupSingleValue");
            alert("Lookup Id: " + lookup.get_lookupId() + "\n Lookup Value: " + lookup.get_lookupValue());


        }

        function OnLoadFailed(sender, args) {
            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
        }</script>
    <input id="btnGetLookUp" onclick="getLookUp()" type="button" value="Get Look Up" />

Build dynamic query string in sharepoint


public string BuildQueryString()
    {
        string url = HttpContext.Current.Request.Url.AbsoluteUri;
        string[] separateURL = url.Split('?');

        NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString("");
        if (ddlLegalAdvisor.SelectedIndex > 0)
        {
            queryString["LegalAdvisor"] = ddlLegalAdvisor.SelectedValue;
        }
        if (ddlAreaOfLaw.SelectedIndex > 0)
        {
            queryString["Areaoflaw"] = ddlAreaOfLaw.SelectedValue;
        }
        if (ddlFundingStream.SelectedIndex > 0)
        {
            queryString["FundingStream"] = ddlFundingStream.SelectedValue;
        }
        if (ddlInterviewRoom.SelectedIndex > 0)
        {
            queryString["InterviewRoom"] = ddlInterviewRoom.SelectedValue;
        }
        url = separateURL[0] + "?" + Convert.ToString(queryString);
        return url;

    }