public static Product GetProductDetails(SharePointContext spContext, int id) { using (var clientContext = spContext.CreateUserClientContextForSPAppWeb()) { if (clientContext != null) { List lstProducts = clientContext.Web.Lists.GetByTitle("Products"); ListItem selectedItem = lstProducts.GetItemById(id); clientContext.Load(selectedItem); clientContext.ExecuteQuery(); if (selectedItem != null) { return new Product { Id = selectedItem.Id, Title = selectedItem["Title"] as string, Description = selectedItem["ProductDescription"] as string, Price = selectedItem["Price"] as string }; } } } return null; }
public static bool AddProduct(SharePointContext spContext, Product product) { using (var clientContext = spContext.CreateUserClientContextForSPAppWeb()) { if (clientContext != null) { try { List lstProducts = clientContext.Web.Lists.GetByTitle("Products"); ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem newProduct = lstProducts.AddItem(itemCreateInfo); newProduct["Title"] = product.Title; newProduct["ProductDescription"] = product.Description; newProduct["Price"] = product.Price; newProduct.Update(); clientContext.ExecuteQuery(); return true; } catch (ServerException ex) { return false; } } } return false; }
public static List<Product> GetProducts(SharePointContext spContext, CamlQuery camlQuery) { List<Product> products = new List<Product>(); using (var clientContext = spContext.CreateUserClientContextForSPAppWeb()) { if (clientContext != null) { List lstProducts = clientContext.Web.Lists.GetByTitle("Products"); ListItemCollection lstProductItems = lstProducts.GetItems(camlQuery); clientContext.Load(lstProductItems); clientContext.ExecuteQuery(); if (lstProductItems != null) { foreach (var lstProductItem in lstProductItems) { products.Add( new Product { Id = lstProductItem.Id, Title = lstProductItem["Title"].ToString(), Description = lstProductItem["ProductDescription"].ToString(), Price = lstProductItem["Price"].ToString() }); } } } } return products; }
// public bool DeleteEvent(string sharepointUrl, string accessToken, string CalendarName) public bool DeleteEvent( string CalendarName, SharePointContext spContext) { Microsoft.SharePoint.Client.ListItemCollection listItems; // using (ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl, accessToken)) if(spContext==null) spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext.Current); using (var clientContext = spContext.CreateAppOnlyClientContextForSPHost()) { try { Web web = clientContext.Web; ListCollection lists = web.Lists; List selectedList = lists.GetByTitle(CalendarName); clientContext.Load<ListCollection>(lists); // this lists object is loaded successfully clientContext.Load<List>(selectedList); // this list object is loaded successfully clientContext.ExecuteQuery(); CamlQuery camlQuery = new CamlQuery(); StringBuilder camlwhere = new StringBuilder(); camlwhere.Append("<Where>"); camlwhere.Append("<And>"); camlwhere.Append("<Eq><FieldRef Name='Title' /><Value Type='Text'>" + this.Title + "</Value></Eq>"); camlwhere.Append("<Eq><FieldRef Name='EventDate' /><Value Type='Date'>" + this.EventTime.Year + "-" + this.EventTime.Month + "-" + this.EventTime.Day + "</Value></Eq>"); camlwhere.Append("</And>"); camlwhere.Append("</Where>"); camlQuery.ViewXml = @"<View><Query>" + camlwhere.ToString() + "</Query></View>"; listItems = selectedList.GetItems(camlQuery); clientContext.Load<Microsoft.SharePoint.Client.ListItemCollection>(listItems); clientContext.ExecuteQuery(); foreach (Microsoft.SharePoint.Client.ListItem oListItem in listItems) { if (oListItem["ID"] != null) { Microsoft.SharePoint.Client.ListItem listItem = selectedList.GetItemById(Convert.ToInt32(oListItem["ID"].ToString())); listItem.DeleteObject(); } } clientContext.ExecuteQuery(); return true; } catch (Exception ex) { Microsoft.SharePoint.Client.Utilities.Utility.LogCustomRemoteAppError(clientContext, Global.ProductId, ex.Message); clientContext.ExecuteQuery(); return false; } } }
protected void Page_Load(object sender, EventArgs e) { spContext = Session["SPContext"] as SharePointContext; listItemID = GetListItemIDFromQueryParameter(); // Read from SharePoint string employeeName = GetLocalEmployeeName(); // Write to remote database AddLocalEmployeeToCorpDB(employeeName); // Write to SharePoint SetLocalEmployeeSyncStatus(); // Go back to the Local Employees page Response.Redirect(spContext.SPHostUrl.ToString() + "Lists/Local%20Employees/AllItems.aspx", true); }
public static void DeleteProduct(SharePointContext spContext, Product product) { using (var clientContext = spContext.CreateUserClientContextForSPAppWeb()) { try { List productsList = clientContext.Web.Lists.GetByTitle("Products"); ListItem itemToDelete = productsList.GetItemById(product.Id); itemToDelete.DeleteObject(); clientContext.ExecuteQuery(); } catch (ServerException ex) { // TODO: Exception Handling } } }
private static string[] GetSiteMembersEmails(SharePointContext spContext) { List<string> siteMembersEmails = null; using (var clientContext = spContext.CreateAppOnlyClientContextForSPHost()) { Web web = clientContext.Web; clientContext.Load(web, w => w.AssociatedMemberGroup.Users.Include(u => u.Email)); clientContext.ExecuteQuery(); siteMembersEmails = new List<string>(web.AssociatedMemberGroup.Users.Count); foreach (User user in web.AssociatedMemberGroup.Users) { if (!String.IsNullOrEmpty(user.Email)) { siteMembersEmails.Add(user.Email); } } } return siteMembersEmails.ToArray(); }
public SPWebServiceNode() { this.IconUri = SharePointContext.GetImagePath("SETTINGS.GIF"); }
public override void OnResultExecuting(ResultExecutingContext filterContext) { filterContext.Controller.ViewBag.SPHostUrl = SharePointContext.GetSPHostUrl(filterContext.HttpContext.Request); filterContext.Controller.ViewBag.SPAppWebUrl = filterContext.HttpContext.Request[SharePointContext.SPAppWebUrlKey]; }
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SharePointKeys.SPContext.ToString()] = spContext as SharePointHighTrustContext; }
protected void Page_Load(object sender, EventArgs e) { // define initial script, needed to render the chrome control string script = @" function chromeLoaded() { $('#chromeControl_topheader_apptitle').text('Provisioning Demo'); $('body').show(); } //function callback to render chrome after SP.UI.Controls.js loads function renderSPChrome() { //Set the chrome options for launching Help, Account, and Contact pages var options = { 'appTitle': document.title, 'onCssLoaded': 'chromeLoaded()' }; //Load the Chrome Control in the divSPChrome element of the page var chromeNavigation = new SP.UI.Controls.Navigation('divSPChrome', options); chromeNavigation.setVisible(true); }"; //register script in page Page.ClientScript.RegisterClientScriptBlock(typeof(SubWeb), "BasePageScript", script, true); string currUrl = HttpContext.Current.Request.Url.OriginalString; currUrl = currUrl.Substring(0, currUrl.IndexOf("?")); SharePointContext spContext = SharePointContextProvider.Current.GetSharePointContext(Context); using (ClientContext ctx = spContext.CreateUserClientContextForSPHost()) { try { Web rootWeb = ctx.Site.RootWeb; ctx.Load(rootWeb); if (!rootWeb.AllProperties.IsPropertyAvailable("SubsiteOverrideUrl") || rootWeb.AllProperties["SubsiteOverrideUrl"] != currUrl) { rootWeb.AllProperties["SubsiteOverrideUrl"] = currUrl; rootWeb.Update(); ctx.Load(rootWeb); ctx.ExecuteQuery(); //new SubWeb().AddJsLink(ctx, rootWeb, this.Request); } } catch (Exception ex) { } //string[] approved = { "STS#0", "ENTERWIKI#0" }; //Web web = ctx.Web; //WebTemplateCollection templates = web.GetAvailableWebTemplates(1033, false); //ctx.Load(web); //ctx.Load(templates); //ctx.ExecuteQuery(); //foreach (var template in templates) //{ // if (Array.IndexOf(approved, template.Name) > -1){ // listSites.Items.Add(new System.Web.UI.WebControls.ListItem(template.Title, template.Name)); // } //} //listSites.SelectedIndex = 0; } lblBasePath.Text = Request["SPHostUrl"] + "/"; Dictionary <string, string> templates = new Dictionary <string, string>(); templates.Add("Team Site", "STS#0"); templates.Add("Custom Team Site", "STS#0"); //templates.Add("Discovery Center", "EDISC#0"); //templates.Add("Discovery Case", "EDISC#1"); //templates.Add("Records Center", "OFFILE#1"); //templates.Add("Shared Services Administration Site", "OSRV#0"); //templates.Add("PerformancePoint", "PPSMASite#0"); //templates.Add("Business Intelligence Center", "BICenterSite#0"); //templates.Add("SharePoint Portal Server Site", "SPS#0"); //templates.Add("Contents area Template", "SPSTOC#0"); //templates.Add("Topic area template", "SPSTOPIC#0"); templates.Add("News Site", "SPSNEWS#0"); //templates.Add("CMS Publishing Site", "CMSPUBLISHING#0"); //templates.Add("Publishing Site ", "BLANKINTERNET#0"); //templates.Add("Press Releases Site", "BLANKINTERNET#1"); //templates.Add("Publishing Site with Workflow", "BLANKINTERNET#2"); //templates.Add("News Site2", "SPSNHOME#0"); //templates.Add("Site Directory", "SPSSITES#0"); //templates.Add("Community area template", "SPSCOMMU#0"); //templates.Add("Report Center", "SPSREPORTCENTER#0"); //templates.Add("Collaboration Portal", "SPSPORTAL#0"); //templates.Add("Enterprise Search Center", "SRCHCEN#0"); //templates.Add("Profiles", "PROFILES#0"); //templates.Add("Publishing Portal", "BLANKINTERNETCONT"); //templates.Add("My Site Host", "SPSMSITEHOST#0"); //templates.Add("Enterprise Wiki", "ENTERWIKI#0"); //templates.Add("Project Site", "PROJECTSITE#0"); //templates.Add("Product Catalog ", "PRODUCTCATALOG#0"); templates.Add("Community Site", "COMMUNITY#0"); //templates.Add("Community Portal", "COMMUNITYPORTAL#0"); //templates.Add("Basic Search Center", "SRCHCENTERLITE#0"); //templates.Add("Basic Search Center2", "SRCHCENTERLITE#1"); //templates.Add("Visio Process Repository", "visprus#0"); foreach (var template in templates) { listSites.Items.Add(new System.Web.UI.WebControls.ListItem(template.Key, template.Value)); } listSites.SelectedIndex = 0; }
public static string GetUserName(SharePointContext spContext) { string strUserName = null; User spUser = null; using (var clientContext = spContext.CreateUserClientContextForSPHost()) { if (clientContext != null) { spUser = clientContext.Web.CurrentUser; clientContext.Load(spUser, user => user.Title); clientContext.ExecuteQuery(); strUserName = spUser.Title; } } return strUserName; }
public SpChiefExecutiveRepository(SharePointContext spContext) { _spContext = spContext; }
/* * The DeleteAttachmentItem method uses the Model classes to interact with data in the database. */ public ActionResult DeleteAttachmentItem(string eventID, string itemID) { Models.EventData eventData = new Models.EventData(); string saved = eventData.DeleteAttachmentItem(itemID); if (saved.StartsWith("Point8020.Error")) { return(RedirectToAction("TrappedError", "Home", new { ErrorMessage = "Item could not be deleted: Error Code is: " + saved, SPHostUrl = SharePointContext.GetSPHostUrl(HttpContext.Request).AbsoluteUri })); } else { return(RedirectToAction("Attachments", "Home", new { EventID = eventID, SPHostUrl = SharePointContext.GetSPHostUrl(HttpContext.Request).AbsoluteUri })); } }
public SpService(SharePointContext spContext) { _spContext = spContext; }
public ActionResult CreateAttendeeItem(string eventID, string name, string email) { Models.EventData eventData = new Models.EventData(); string saved = eventData.AddAttendeeItem(eventID, name, email); if (saved.StartsWith("Point8020.Error")) { return(RedirectToAction("TrappedError", "Home", new { ErrorMessage = "Item could not be saved: Error Code is: " + saved, SPHostUrl = SharePointContext.GetSPHostUrl(HttpContext.Request).AbsoluteUri })); } else { return(RedirectToAction("Attendees", "Home", new { EventID = eventID, SPHostUrl = SharePointContext.GetSPHostUrl(HttpContext.Request).AbsoluteUri })); } }
public ActionResult SaveCateringItem(string eventID, string itemID, string title, string description) { Models.EventData eventData = new Models.EventData(); string saved = eventData.UpdateCateringItem(eventID, itemID, title, description); if (saved.StartsWith("Point8020.Error")) { return(RedirectToAction("TrappedError", "Home", new { ErrorMessage = "Item could not be saved: Error Code is: " + saved, SPHostUrl = SharePointContext.GetSPHostUrl(HttpContext.Request).AbsoluteUri })); } else { return(RedirectToAction("Catering", "Home", new { EventID = eventID, SPHostUrl = SharePointContext.GetSPHostUrl(HttpContext.Request).AbsoluteUri })); } }
public ActionResult SaveEvent(string EventID, string EventTitle, string EventVenue, string EventAddress1, string EventAddress2, string EventCity, string EventState, string EventPostalCode, DateTime EventStartDateTime, DateTime EventEndDateTime, string EventDescription) { Models.EventData eventData = new Models.EventData(); string saved = eventData.UpdateEvent(EventID, EventTitle, EventVenue, EventAddress1, EventAddress2, EventCity, EventState, EventPostalCode, EventStartDateTime.ToUniversalTime(), EventEndDateTime.ToUniversalTime(), EventDescription); if (saved.StartsWith("Point8020.Error")) { return(RedirectToAction("TrappedError", "Home", new { ErrorMessage = "Event could not be saved: Error Code is: " + saved, SPHostUrl = SharePointContext.GetSPHostUrl(HttpContext.Request).AbsoluteUri })); } else { var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext); using (var clientContext = spContext.CreateUserClientContextForSPHost()) { if (clientContext != null) { hostWeb = clientContext.Web; clientContext.Load(hostWeb); ListCollection hostLists = hostWeb.Lists; clientContext.Load(hostLists); clientContext.ExecuteQuery(); bool calendarFound = false; foreach (List lst in hostLists) { if (lst.BaseTemplate == (int)ListTemplateType.Events) { if (lst.Title == "Contoso Events Calendar") { calendarFound = true; break; } } } eVentCalendarExists = calendarFound; if (calendarFound) { List calendar = hostWeb.Lists.GetByTitle("Contoso Events Calendar"); clientContext.Load(calendar); clientContext.ExecuteQuery(); CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = "<View><Query><Where><Eq><FieldRef Name='Category' /><Value Type='Text'>" + EventID + "</Value></Eq></Where></Query></View>"; ListItemCollection eventItems = calendar.GetItems(camlQuery); clientContext.Load(eventItems); clientContext.ExecuteQuery(); ListItem editEvent = eventItems[0]; editEvent["Title"] = EventTitle; editEvent["Location"] = EventCity; editEvent["EventDate"] = EventStartDateTime.ToUniversalTime(); editEvent["EndDate"] = EventEndDateTime.ToUniversalTime(); editEvent["Category"] = saved; editEvent.Update(); clientContext.ExecuteQuery(); } } return(RedirectToAction("Events", "Home", new { SPHostUrl = SharePointContext.GetSPHostUrl(HttpContext.Request).AbsoluteUri })); } } }
public ActionResult CreateEvent(string EventTitle, string EventVenue, string EventAddress1, string EventAddress2, string EventCity, string EventState, string EventPostalCode, DateTime EventStartDateTime, DateTime EventEndDateTime, string EventDescription) { Models.EventData eventData = new Models.EventData(); string saved = eventData.AddEvent(EventTitle, EventVenue, EventAddress1, EventAddress2, EventCity, EventState, EventPostalCode, EventStartDateTime.ToUniversalTime(), EventEndDateTime.ToUniversalTime(), EventDescription); if (saved.StartsWith("Point8020.Error")) { return(RedirectToAction("TrappedError", "Home", new { ErrorMessage = "Event could not be saved: Error Code is: " + saved, SPHostUrl = SharePointContext.GetSPHostUrl(HttpContext.Request).AbsoluteUri })); } else { var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext); using (var clientContext = spContext.CreateUserClientContextForSPHost()) { if (clientContext != null) { hostWeb = clientContext.Web; clientContext.Load(hostWeb); ListCollection hostLists = hostWeb.Lists; clientContext.Load(hostLists); clientContext.ExecuteQuery(); bool calendarFound = false; foreach (List lst in hostLists) { if (lst.BaseTemplate == (int)ListTemplateType.Events) { if (lst.Title == "Contoso Events Calendar") { calendarFound = true; break; } } } eVentCalendarExists = calendarFound; if (calendarFound) { List calendar = hostWeb.Lists.GetByTitle("Contoso Events Calendar"); clientContext.Load(calendar); clientContext.ExecuteQuery(); ListItemCreationInformation itemInfo = new ListItemCreationInformation(); ListItem newEvent = calendar.AddItem(itemInfo); newEvent["Title"] = EventTitle; newEvent["Location"] = EventCity; newEvent["EventDate"] = EventStartDateTime.ToUniversalTime(); newEvent["EndDate"] = EventEndDateTime.ToUniversalTime(); newEvent["Category"] = saved; newEvent.Update(); clientContext.ExecuteQuery(); } } } return(RedirectToAction("Events", "Home", new { SPHostUrl = SharePointContext.GetSPHostUrl(HttpContext.Request).AbsoluteUri })); } }
/* * The UploadFiles method coordinates saving a file to Azure BLOB storage with updating the database through a Model class. */ public ActionResult UploadFiles(string EventID) { bool isSaved = true; string savedStatus = string.Empty; for (int idx = 0; idx < Request.Files.Count; idx++) { HttpPostedFileBase file = (HttpPostedFileBase)Request.Files[idx]; Stream fileStream = file.InputStream; string fileName = getFileName(file.FileName); Models.EventData eventData = new Models.EventData(); savedStatus = eventData.AddAttachmentItem(EventID, EventID + "/" + fileName); if (savedStatus.StartsWith("Point8020.Success")) { savedStatus = SaveFileToAzure(fileStream, file.ContentType, EventID + "/" + fileName); if (savedStatus != "Point8020.Success") { isSaved = false; } } else { isSaved = false; } } if (isSaved == true) { return(RedirectToAction("Events", "Home", new { SPHostUrl = SharePointContext.GetSPHostUrl(HttpContext.Request).AbsoluteUri })); } else { return(RedirectToAction("TrappedError", "Home", new { ErrorMessage = "File could not be saved: Error Code is: " + savedStatus, SPHostUrl = SharePointContext.GetSPHostUrl(HttpContext.Request).AbsoluteUri })); } }
/// <summary> /// Constructor /// </summary> /// <param name="config"></param> /// <param name="context"></param> public SharePointController(IConfiguration config, SharePointContext context) { _username = config["Authentication:SharePoint:Username"]; _password = config["Authentication:SharePoint:Password"]; _context = context; }
protected void Page_Load(object sender, EventArgs e) { spContext = Session["SPContext"] as SharePointContext; }
// Grabs a document from a Sharepoint list and turns it into a "provided document", // i.e. a document which is to provided to Signicat in a web service request // and used as the original in a signing process private provideddocument GetDocumentForSigningFromSPList(SharePointContext spContext, string SPListId, string SPListItemId) { // Create a provided document, prepared for signing with basic properties var document = new provideddocument { externalreference = SPListItemId, id = "doc_1", mimetype = "application/pdf", signtextentry = "I have read and understood the document which has been presented to me, and I agree to its contents with my signature." }; // Now, let's get the name and data of the document from the Sharepoint list using (var clientContext = spContext.CreateUserClientContextForSPHost()) { if (clientContext != null) { // Get the list item representing the document List list = clientContext.Web.Lists.GetById(Guid.Parse(SPListId)); ListItem listItem = list.GetItemById(SPListItemId); clientContext.Load(listItem, li => li.DisplayName, li => li.File); clientContext.ExecuteQuery(); // Set the name of the document document.description = listItem.DisplayName; // Now get the binary contents Microsoft.SharePoint.Client.File itemFile = listItem.File; ClientResult<Stream> fileStream = listItem.File.OpenBinaryStream(); clientContext.Load(itemFile); clientContext.ExecuteQuery(); using (var memoryStream = new MemoryStream()) { fileStream.Value.CopyTo(memoryStream); document.data = memoryStream.ToArray(); } } } return document; }
/// <summary> /// Überprüft, ob der jeweilige SharePointContext im angegebenen HTTP-Kontext verwendet werden kann. /// </summary> /// <param name="spContext">Der SharePointContext.</param> /// <param name="httpContext">Der HTTP-Kontext.</param> /// <returns>True, wenn der jeweilige SharePointContext im angegebenen HTTP-Kontext verwendet werden kann.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; }
public static bool UpdateProduct(SharePointContext spContext, Product product) { using (var clientContext = spContext.CreateUserClientContextForSPAppWeb()) { if (clientContext != null) { try { List lstProducts = clientContext.Web.Lists.GetByTitle("Products"); ListItem selectedItem = lstProducts.GetItemById(product.Id); selectedItem["Title"] = product.Title; selectedItem["ProductDescription"] = product.Description; selectedItem["Price"] = product.Price; selectedItem.Update(); clientContext.ExecuteQuery(); return true; } catch (ServerException ex) { return false; } } } return false; }
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; }
/* * The SaveRoles method uses the Model classes to interact with data in the database. */ public ActionResult SaveRoles(string eventID, string items) { Models.EventData eventData = new Models.EventData(); string saved = eventData.SaveRoles(eventID, items); if (saved.StartsWith("Point8020.Error")) { return(RedirectToAction("TrappedError", "Home", new { ErrorMessage = "Security settings could not be saved: Error Code is: " + saved, SPHostUrl = SharePointContext.GetSPHostUrl(HttpContext.Request).AbsoluteUri })); } else { return(RedirectToAction("Events", "Home", new { SPHostUrl = SharePointContext.GetSPHostUrl(HttpContext.Request).AbsoluteUri })); } }
public Settings() { this.Header = "Settings"; this.Icon = ImageExtensions.LoadImage(SharePointContext.GetImagePath("icasax.png")); this.Click += new RoutedEventHandler(ClickHandler); }
public DataInitializer(SharePointContext context) { _spContext = context; }
public SPAlertCollectionNode() { this.IconUri = SharePointContext.GetImagePath("AIF16.GIF"); }
/// <summary> /// Speichert die dem angegebenen HTTP-Kontext zugeordnete SharePointContext-Instanz. /// <c>null</c> ist für das Löschen der dem HTTP-Kontext zugeordneten SharePointContext-Instanz zulässig. /// </summary> /// <param name="spContext">Die zu speichernde SharePointContext-Instanz oder <c>null</c>.</param> /// <param name="httpContext">Der HTTP-Kontext.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
public SharePointService(SharePointContext sharePointContext) { this.SharePointContext = sharePointContext; }
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; }
private static string UpdateSharePoint(IncomingMailboxViewModel model, SharePointContext spContext, CultureInfo currentCulture) { var result = new System.Text.StringBuilder(); if (model.DBModel.SiteUrl.ToLower() == spContext.SPHostUrl.AbsoluteUri.ToLower()) { using (var clientContext = spContext.CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { ListItem spItem = clientContext.Web.Lists.GetById(new Guid(model.DBModel.DocumentLibraryId)).GetItemById(model.DBModel.ListItemId); var formValues = new List <ListItemFormUpdateValue>(); formValues.Add(new ListItemFormUpdateValue() { FieldName = "Title", FieldValue = model.DBModel.DocumentTitle }); formValues.Add(new ListItemFormUpdateValue() { FieldName = "Subject", FieldValue = model.DBModel.DocumentSubject }); formValues.Add(new ListItemFormUpdateValue() { FieldName = "Observaciones", FieldValue = model.DBModel.DocumentSummary }); formValues.Add(new ListItemFormUpdateValue() { FieldName = "Remitente", FieldValue = model.DBModel.DocumentFrom }); formValues.Add(new ListItemFormUpdateValue() { FieldName = "FechaDoc", FieldValue = model.DBModel.DocumentDate.ToString("d", currentCulture) }); formValues.Add(new ListItemFormUpdateValue() { FieldName = "FechaVencimiento", FieldValue = model.DBModel.ResponseDate.ToString("d", currentCulture) }); formValues.Add(new ListItemFormUpdateValue() { FieldName = "EstadoDoc", FieldValue = model.DBModel.AssignmentStatus }); formValues.Add(new ListItemFormUpdateValue() { FieldName = "Destinatario", FieldValue = "[{'Key':'" + model.DBModel.AssignedToLogin + "'}]" }); var resUpdate = spItem.ValidateUpdateListItem(formValues, true, string.Empty); clientContext.ExecuteQuery(); foreach (ListItemFormUpdateValue updValue in resUpdate) { if (updValue.HasException) { result.AppendFormat("Campo: {0}, Mensaje: {1}; ", updValue.FieldName, updValue.ErrorMessage); } } } } } else { //generate destination context Uri destinationSiteUri = new Uri(model.DBModel.SiteUrl); //target realm of the tenant (This is constant per tenant) string targetRealm = TokenHelper.GetRealmFromTargetUrl(destinationSiteUri); //generate access token for destination site string accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, destinationSiteUri.Authority, targetRealm).AccessToken; using (var destinationContext = TokenHelper.GetClientContextWithAccessToken(model.DBModel.SiteUrl, accessToken)) { ListItem spItem = destinationContext.Web.Lists.GetById(new Guid(model.DBModel.DocumentLibraryId)).GetItemById(model.DBModel.ListItemId); var formValues = new List <ListItemFormUpdateValue>(); formValues.Add(new ListItemFormUpdateValue() { FieldName = "Title", FieldValue = model.DBModel.DocumentTitle }); formValues.Add(new ListItemFormUpdateValue() { FieldName = "Subject", FieldValue = model.DBModel.DocumentSubject }); formValues.Add(new ListItemFormUpdateValue() { FieldName = "Observaciones", FieldValue = model.DBModel.DocumentSummary }); formValues.Add(new ListItemFormUpdateValue() { FieldName = "Remitente", FieldValue = model.DBModel.DocumentFrom }); formValues.Add(new ListItemFormUpdateValue() { FieldName = "FechaDoc", FieldValue = model.DBModel.DocumentDate.ToString("d", currentCulture) }); formValues.Add(new ListItemFormUpdateValue() { FieldName = "FechaVencimiento", FieldValue = model.DBModel.ResponseDate.ToString("d", currentCulture) }); formValues.Add(new ListItemFormUpdateValue() { FieldName = "EstadoDoc", FieldValue = model.DBModel.AssignmentStatus }); formValues.Add(new ListItemFormUpdateValue() { FieldName = "Destinatario", FieldValue = "[{'Key':'" + model.DBModel.AssignedToLogin + "'}]" }); var resUpdate = spItem.ValidateUpdateListItem(formValues, true, string.Empty); destinationContext.ExecuteQuery(); foreach (ListItemFormUpdateValue updValue in resUpdate) { if (updValue.HasException) { result.AppendFormat("Campo: {0}, Mensaje: {1}; ", updValue.FieldName, updValue.ErrorMessage); } } } } return(result.ToString()); }
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; }
public string UploadSPFile(SharePointContext spContext, HttpPostedFileBase tempFile, string documentFolder, string siteUrl, string prefix) { log.Info("- OutboxDocs - UploadSPFile"); var result = string.Empty; using (var clientContext = spContext.CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { try { var relativeSite = clientContext.Url.Substring(clientContext.Url.IndexOf('/', 10)); var folder = clientContext.Web.GetFolderByServerRelativeUrl(documentFolder); clientContext.Load(folder); clientContext.ExecuteQuery(); FileCreationInformation fci = new FileCreationInformation(); if (tempFile.ContentLength < 1000000) // ~1MB { using (System.IO.Stream inputStream = tempFile.InputStream) { var memoryStream = inputStream as System.IO.MemoryStream; if (memoryStream == null) { memoryStream = new System.IO.MemoryStream(); inputStream.CopyTo(memoryStream); } fci.Content = memoryStream.ToArray(); } fci.Url = documentFolder + "/" + prefix + tempFile.FileName; fci.Overwrite = true; Microsoft.SharePoint.Client.File fileToUpload = folder.Files.Add(fci); clientContext.Load(fileToUpload); clientContext.ExecuteQuery(); Uri hostUrl = new Uri(siteUrl); result = "https://" + hostUrl.Host + fileToUpload.ServerRelativeUrl; } else if (tempFile.ContentLength < 5000000) // ~5MB { fci.ContentStream = tempFile.InputStream; fci.Url = documentFolder + "/" + prefix + tempFile.FileName; fci.Overwrite = true; Microsoft.SharePoint.Client.File fileToUpload = folder.Files.Add(fci); clientContext.Load(fileToUpload); clientContext.ExecuteQuery(); Uri hostUrl = new Uri(siteUrl); result = "https://" + hostUrl.Host + fileToUpload.ServerRelativeUrl; } if (tempFile.ContentLength >= 5000000) // > ~5MB { Guid uploadId = Guid.NewGuid(); Microsoft.SharePoint.Client.File uploadFile; int blockSize = 4 * 1024 * 1024; // 5MB blocks ClientResult <long> bytesUploaded = null; byte[] buffer = new byte[blockSize]; Byte[] lastBuffer = null; long fileoffset = 0; long totalBytesRead = 0; int bytesRead; bool first = true; bool last = false; using (BinaryReader br = new BinaryReader(tempFile.InputStream)) { while ((bytesRead = br.Read(buffer, 0, buffer.Length)) > 0) { totalBytesRead = totalBytesRead + bytesRead; // You've reached the end of the file. if (totalBytesRead == tempFile.ContentLength) { last = true; // Copy to a new buffer that has the correct size. lastBuffer = new byte[bytesRead]; Array.Copy(buffer, 0, lastBuffer, 0, bytesRead); } if (first) { using (MemoryStream contentStream = new MemoryStream()) { // Add an empty file. FileCreationInformation fileInfo = new FileCreationInformation(); fileInfo.ContentStream = contentStream; fileInfo.Url = prefix + tempFile.FileName; fileInfo.Overwrite = true; uploadFile = folder.Files.Add(fileInfo); // Start upload by uploading the first slice. using (MemoryStream s = new MemoryStream(buffer)) { // Call the start upload method on the first slice. bytesUploaded = uploadFile.StartUpload(uploadId, s); clientContext.ExecuteQuery(); // fileoffset is the pointer where the next slice will be added. fileoffset = bytesUploaded.Value; } // You can only start the upload once. first = false; } } else { // Get a reference to your file. uploadFile = clientContext.Web.GetFileByServerRelativeUrl(folder.ServerRelativeUrl + System.IO.Path.AltDirectorySeparatorChar + prefix + tempFile.FileName); if (last) { // Is this the last slice of data? using (MemoryStream s = new MemoryStream(lastBuffer)) { // End sliced upload by calling FinishUpload. uploadFile = uploadFile.FinishUpload(uploadId, fileoffset, s); clientContext.Load(uploadFile); clientContext.ExecuteQuery(); // Return the file object for the uploaded file. Uri hostUrl = new Uri(siteUrl); result = "https://" + hostUrl.Host + uploadFile.ServerRelativeUrl; } } else { using (MemoryStream s = new MemoryStream(buffer)) { // Continue sliced upload. bytesUploaded = uploadFile.ContinueUpload(uploadId, fileoffset, s); clientContext.ExecuteQuery(); // Update fileoffset for the next slice. fileoffset = bytesUploaded.Value; } } } } // while ((bytesRead = br.Read(buffer, 0, buffer.Length)) > 0) } } } catch (Exception ex) { log.Error(ex.ToString()); } } } return(result); }