http://www.codeproject.com/Articles/581060/HowplustoplusGetplusSharePointplusClientplusContex

Introduction

The first step of app development is to correctly get access to SharePoint client context. I have struggled to develop a simple model to initialize the SharePoint Client context. Most of the App development includes ASP Master pages. So I need to figure out a working model for app development.

First, you need to know how SharePoint offers the contextString. contextString offers when SharePoint gets redirected from appredirect.aspx URL.

Example: https://rajee.sharepoint.com/_layouts/15/appredirect.aspx?instance_id={B0D5D768-303F-4AE7-A4D3-F94B687C6AB3

At that point, we need to capture the contextString and generate either AccessToken or RefreshToken and save it for accessing the SharePoint Client Context at a later time. Otherwise, it will result in generating the error The parameter 'token' cannot be a null or empty string (This is a nasty error which drove me crazy.).

Normally AccessToken is valid for 12 hours and RefreshToken is valid for 6 months.

In my approach, I used another key which is called as CacheKey to identify the user uniquely. Therefore I use this value to maintain a cookie based on the user.

Reference: Tips and FAQs: OAuth and remote apps for SharePoint 2013

The following shows my approach to do this. If you have a master page, you need to put the code in the onInit()rather than page load.

Collapse | Copy Code

protected void Page_Load(object sender, EventArgs e)
{
var key = Session["CashKey"]; // sharepoint url (app hosted url)
var hostWeb = Page.Request["SPHostUrl"]; // Sharepoint url with app Title (app deployed sp url)
Uri SharePointUri = new Uri(hostWeb + "/SharePointApp1/"); // This is first time the app is running
if (key == null)
{
// get the TokenString
var contextTokenString = TokenHelper.GetContextTokenFromRequest(Page.Request);
// Get the contexttoken by passing the token string
var contextToken = TokenHelper.ReadAndValidateContextToken
(contextTokenString, Request.Url.Authority); //Since some browsers does not support cookie name more than 40 chars
// Im taking first 40 chars
var cookieName = contextToken.CacheKey.Substring(0, 40); //Add User specific cookie name to the Session
Session.Add("CashKey", cookieName); // Get the Refresh Token
var refreshToken = contextToken.RefreshToken;
// Add the cookie value (refresh Token)
Response.Cookies.Add(new HttpCookie(cookieName, refreshToken)); }
else
{
// USER already in the application, means it is not getting redirect from the appRedirect
// So contextstring is null
}
}

This is code for button click.

Collapse | Copy Code

protected void Button1_Click(object sender, EventArgs e)
{
// sharepoint url (app hosted url)
var hostWeb = Page.Request["SPHostUrl"]; // Sharepoint url with app name (app deployed sp url)
Uri SharePointUri = new Uri(hostWeb + "/SharePointApp1/"); // Get the cookie name from the session
var key = Session["CashKey"] as string;
// Get the refresh token from the cookie
var refreshToken = Request.Cookies[key].Value; //Get the access Token By passing refreshToken
// 00000003-0000-0ff1-ce00-000000000000 is principal name for SP2013 it is unique
var accessToken = TokenHelper.GetAccessToken(refreshToken,
"00000003-0000-0ff1-ce00-000000000000",
SharePointUri.Authority, TokenHelper.GetRealmFromTargetUrl(SharePointUri)); // Access the Sharepoint Do your work
using (var clientContext = TokenHelper.GetClientContextWithAccessToken
("https://rajee.sharepoint.com/SharepointApp1", accessToken.AccessToken))
{
clientContext.Load(clientContext.Web, web => web.Title);
clientContext.ExecuteQuery();
Response.Write(clientContext.Web.Title);
}
}

Note: In the middle of the app, if the context is broken due to expiration or some other case you need to initialize the app from the AppRedirect, therefore you can:

Collapse | Copy Code

var hostWeb = Page.Request["SPHostUrl"];
var val = TokenHelper.GetAppContextTokenRequestUrl(hostWeb, Server.UrlEncode(Request.Url.ToString()));

How to Get SharePoint Client Context in SharePoint Apps (Provider Hosted / SharePoint Access ) in CSOM (Client Side Object Model)的更多相关文章

  1. 在C#开发中如何使用Client Object Model客户端代码获得SharePoint 网站、列表的权限情况

    自从人类学会了使用火,烤制的方式替代了人类的消化系统部分功能,从此人类的消化系统更加简单,加速了人脑的进化:自从SharePoint 2010开始有了Client Side Object Model ...

  2. SharePoint Client Object Model API 介绍以及工作原理解析

    CSOM和ServerAPI 的对比 SharePoint从2010开始引入了Client Object Model的API(后文中用CSOM来代替),从名字来看,我们可以简单的看出,该API是面向客 ...

  3. SharePoint 2010 匿名用户调用Client Object Model访问列表项

    最近有个小需求,在门户首页上加个通知公告的版块,新闻来源是列表项,需要有垂直滚动的效果. 第一个想法就是通过SharePoint的Client Object Model获取列表数据再加上JQuery来 ...

  4. c# sharepoint client object model 客户端如何创建中英文站点

    c# sharepoint client object model 客户端如何创建中英文站点 ClientContext ClientValidate = tools.GetContext(Onlin ...

  5. 关于SharePoint 的Client object model该何时load和execut query的一点自己的看法

    很多人在用client object model的时候,不知道何时或者该不该load,今天看到一个观点描述这个问题,觉得很有道理,和大家分享.那就是写client object model就像写sql ...

  6. SharePoint 2013中Office Web Apps的一次排错

    转自http://www.cnblogs.com/awpatp/archive/2013/06/06/3121420.html, 仅供自己查看 笔者尝试在自己的测试环境中为SharePoint 201 ...

  7. SharePoint安全 - 在Goolge和Bing中查找SharePoint相关内容

    博客地址 http://blog.csdn.net/foxdave 本篇提供两个查询串字典,分别对应Google和Bing的搜索,用来查询SharePoint网站的相关内容 Google ShareP ...

  8. SharePoint 2010 最佳实践学习总结------第1章 SharePoint Foundation开发基础

    ----前言 这段时间项目出在验收阶段,不是很忙,就潜心把SharePoint学一下,不求有多深刻,初衷只是先入门再说.后续会发布一系列的学习总结.主要学习的书籍为<SharePoint2010 ...

  9. 【Office Web Apps】在 SharePoint 中使用 Office Web Apps

    在 SharePoint 中使用 Office Web Apps 在安装并配置了 Microsoft Office Web Apps 的 SharePoint 网站上,通过 Office Web Ap ...

随机推荐

  1. linux_脚本应用

    linux下三个有用的 Python 脚本 2010年4月29日   import os, sys  def pyc_clean(dir):      findcmd = 'find %s -name ...

  2. 读书笔记_Effective_C++_条款四十三:学习处理模板化基类的名称

    背景是这样的,有两个不同的公司,然后想设计一个MessageSender,为这两个公司发送不同的消息,既支持明文发送SendClearText,也支持密文发送SendEncryptedText.一种思 ...

  3. NSString Byte NSData 字节(字符)字符串

    NSUTF8StringEncoding 3个字节(字符)一个中文字符 一个字节一个英文字符

  4. Sphinx(coreseek) 安装使用以及词库的扩展

    1.Sphinx(coreseek) 是啥 一般而言,Sphinx是一个独立的全文搜索引擎:而Coreseek是一个支持中文的全文搜索引擎,意图为其他应用提供高速.低空间占用.高结果相关度的中文全文搜 ...

  5. [CS231n-CNN] Backpropagation(反向传播算法)

    课程主页:http://cs231n.stanford.edu/ 上节讲到loss function: 引出了求导数使得loss function减小. -Back Propagation :梯度下降 ...

  6. mark:如何使用FileZilla连接虚拟机上的Fedora

    1. 下载FileZilla 2. 在虚拟机上安装SSH,http://linuxconfig.org/how-to-install-start-and-connect-to-ssh-server-o ...

  7. Java知多少(完结)

    系列文章: Java知多少(上) Java知多少(中) Java知多少(下)

  8. Linux下grep显示前后几行信息

    Linux下grep显示前后几行信息 标准unix/linux下的grep通过下面參数控制上下文 grep -C 5 foo file 显示file文件里匹配foo字串那行以及上下5行grep -B ...

  9. ArcGIS如何将表连接到空间数据上

    当我们有一些空间数据和一些业务数据(表),希望把业务数据和空间数据连接起来时,可以采用ArcGIS Desktop进行操作.本文将介绍如何在ArcGIS Destop中将表和空间数据关联起来. Arc ...

  10. Hadoop第7周练习—MapReduce进行数据查询和实现推简单荐系统

    1.1 1.2 :计算员工相关 2.1 内容 :求各个部门的总工资 :求各个部门的人数和平均工资 :求每个部门最早进入公司的员工姓名 :求各个城市的员工的总工资 :列出工资比上司高的员工姓名及其工资 ...