bool checkItem(SPItemEventProperties properties) { string jobTitle = properties.AfterProperties["Title"].ToString(); bool allowed = false; SPWeb jobDefWeb = null; SPList jobDefList; SPUser privilegedAccount = properties.Web.AllUsers[@"SHAREPOINT\SYSTEM"]; SPUserToken privilegedToken = privilegedAccount.UserToken; try { using (SPSite elevatedSite = new SPSite(properties.Web.Url, privilegedToken)) { using (SPWeb elevatedWeb = elevatedSite.OpenWeb()) { jobDefWeb = elevatedWeb.Webs["JobDefinitions"]; jobDefList = jobDefWeb.Lists["Job Definitions"]; foreach (SPListItem item in jobDefList.Items) { if (item["Title"].ToString() == jobTitle) { allowed = true; break; } } } } return(allowed); } finally { jobDefWeb.Dispose(); } }
internal static void CheckSend(Guid SiteId, SPUserToken UserToken, Guid WebId, string ListTitle, int ListItemId) { using (SPSite s = new SPSite(SiteId, UserToken)) { using (SPWeb w = s.OpenWeb(WebId)) { try { SPList newList = w.Lists.TryGetList(ListTitle); SPListItem currentItem = newList.GetItemById(ListItemId); //Проверяем помечено ли для рассылки if ((bool)currentItem[Constants.NewsFileds.WITH_EMAIL] == true) { BeginSend(w, currentItem); } else { return; } } catch (Exception ex) { } } } }
public SPSiteInstance CreateFromGuid(object id, object userToken) { var guidId = GuidInstance.ConvertFromJsObjectToGuid(id); SPUserToken spUserToken = null; if (userToken != Undefined.Value) { if (userToken is Base64EncodedByteArrayInstance) { spUserToken = new SPUserToken((userToken as Base64EncodedByteArrayInstance).Data); } else if (userToken is SPUserTokenInstance) { spUserToken = (userToken as SPUserTokenInstance).SPUserToken; } else { spUserToken = new SPUserToken(Encoding.UTF8.GetBytes(TypeConverter.ToString(userToken))); } } var site = spUserToken == null ? new SPSite(guidId) : new SPSite(guidId, spUserToken); return(new SPSiteInstance(Engine.Object.InstancePrototype, site)); }
SPListItemCollection GetWorkflowCenterConfigByDept(string department) { SPUserToken userToken = SPContext.Current.Web.CurrentUser.UserToken; string rootUrl = SPContext.Current.Site.RootWeb.Url; using (SPSite site = new SPSite(rootUrl, userToken)) using (SPWeb web = site.OpenWeb()) { SPList oList = web.Lists["WorkflowCenterConfig"]; SPQuery oQuery = new SPQuery(); string strQuery = @" <Where> <And> <Eq> <FieldRef Name='Title' /> <Value Type='Text'>{0}</Value> </Eq> <Eq> <FieldRef Name='Active' /> <Value Type='Boolean'>1</Value> </Eq> </And> </Where>"; oQuery.Query = string.Format(strQuery, department); SPListItemCollection col = oList.GetItems(oQuery); return(col); } }
public static void CopyFile(string sourceFileUrl, string targetFolderUrl, bool overwrite = false, bool includeHistory = false, bool runAsSystem = false) { SPUserToken userToken = runAsSystem ? SPUserToken.SystemAccount : SPContext.Current.Web.CurrentUser.UserToken; using (SPSite sourceSite = new SPSite(sourceFileUrl, userToken)) using (SPWeb sourceWeb = sourceSite.OpenWeb()) using (SPSite targetSite = new SPSite(targetFolderUrl, userToken)) using (SPWeb targetWeb = targetSite.OpenWeb()) { using (new Unsafe(sourceWeb)) { using (new Unsafe(targetWeb)) { SPFile sourceFile = sourceWeb.GetFile(sourceFileUrl); SPFolder targetFolder = targetWeb.GetFolder(targetFolderUrl); if (includeHistory) { CopyFileAndHistory(sourceFile, targetFolder, overwrite); } else { CopyFile(sourceFile, targetFolder, overwrite); } } } } }
private void FindWebApplication(SPFeatureReceiverProperties properties) { SPFeatureScope scope = properties.Feature.Definition.Scope; if (scope == SPFeatureScope.Web) { SPWeb web = properties.Feature.Parent as SPWeb; SPUserToken oSysToken = GetSysToken(web.Site.ID); using (SPSite centralSite = new SPSite(web.Site.ID, oSysToken)) { webApp = centralSite.WebApplication; } } if (scope == SPFeatureScope.Site) { SPSite site = properties.Feature.Parent as SPSite; SPUserToken oSysToken = GetSysToken(site.ID); using (SPSite centralSite = new SPSite(site.ID, oSysToken)) { webApp = centralSite.WebApplication; } } if (scope == SPFeatureScope.WebApplication) { webApp = properties.Feature.Parent as SPWebApplication; } }
public static SPUserToken GetSystemToken(this SPSite site) { SPUserToken token = null; bool tempCADE = site.CatchAccessDeniedException; try { site.CatchAccessDeniedException = false; token = site.SystemAccount.UserToken; } catch (UnauthorizedAccessException) { //token = SPUserToken.SystemAccount; SPSecurity.RunWithElevatedPrivileges(() => { using (SPSite elevSite = new SPSite(site.ID, site.Zone)) token = elevSite.SystemAccount.UserToken; }); } finally { site.CatchAccessDeniedException = tempCADE; } return(token); }
public void UploadFile(String targetLibraryName, String fileName, byte[] file, Boolean overwrite) { SPList targetLibrary = web.Lists[targetLibraryName]; String destUrl = SPUtility.ConcatUrls(web.Url, targetLibrary.RootFolder.Url) + "/" + fileName; SPFile newFile = web.GetFile(destUrl); if (newFile.Exists) { if (newFile.CheckOutType != SPFile.SPCheckOutType.None) { newFile.CheckIn(checkInComment); } using (EventReceiverManager eventReceiverManager = new EventReceiverManager(true)) { newFile.Delete(); } } SPFieldUserValue userValue = new SPFieldUserValue(web, listItemForm[SPBuiltInFieldId.Author].ToString()); SPUser author = userValue.User; SPUserToken userToken = author.UserToken; using (SPSite impSite = new SPSite(web.Site.ID, userToken)) { using (SPWeb impWeb = impSite.OpenWeb()) { SPList impTargetLibrary = impWeb.Lists[targetLibraryName]; String impDestUrl = SPUtility.ConcatUrls(impWeb.Url, impTargetLibrary.RootFolder.Url) + "/" + fileName; SPFile upload = impTargetLibrary.RootFolder.Files.Add(impDestUrl, file, overwrite); } } }
public static SPBasePermissions GetPermissionsForUser(SPUser user, SPWeb web) { SPUserToken userToken = user.UserToken; #if SP2007 MethodInfo getPermissions = typeof(SPUtility).GetMethod("GetPermissions", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.Static, null, new[] { typeof(SPUserToken), typeof(ISecurableObject) }, null); #else MethodInfo getPermissions = typeof(SPUtility).GetMethod( "GetPermissions", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.Static, null, new[] { typeof(SPUserToken), typeof(SPSecurableObject) }, null); #endif var perms = (SPBasePermissions)getPermissions.Invoke(null, new object[] { userToken, web }); return(perms); }
/// <summary> /// This is an internal helper function. This function will bring back an SLKStore Object. /// </summary> /// <returns>SLKStore Object stamped with the currently logged user</returns> private SlkStore GetSLKStore() { try { //Getting User Object using (SPSite siteForUser = new SPSite(classesUrl)) { using (SPWeb webForUser = siteForUser.RootWeb) { //TODO: Does not handle invalid users gracefully. SPUserToken token = webForUser.AllUsers[Username].UserToken; using (SPSite site = new SPSite(classesUrl, token)) { using (SPWeb web = site.OpenWeb()) { return(SlkStore.GetStore(web)); } } } } } catch (Exception exception) { hasError = true; errorDesc = exception.Message; return(null); } }
internal static SPUserToken GetSystemToken(SPSite site) { if (site == null) { return(null); } site.CatchAccessDeniedException = false; try { return(site.SystemAccount.UserToken); } catch (UnauthorizedAccessException) { SPUserToken sysToken = null; SPSecurity.RunWithElevatedPrivileges( () => { using (var superSite = new SPSite(site.ID)) { sysToken = superSite.SystemAccount.UserToken; } } ); return(sysToken); } }
private SPList GetDocumentLibraryFromUrl(string documentLibraryUrl, string username) { SPWeb oWeb = null; Uri webUrl = new Uri(new Uri(Context.Request.Url.ToString()), documentLibraryUrl); oWeb = new SPSite(webUrl.OriginalString).OpenWeb(); if (!String.IsNullOrEmpty(username)) { SPUserToken userToken = oWeb.SiteUsers[username].UserToken; oWeb.Dispose(); SPSite site = new SPSite(webUrl.OriginalString, userToken); oWeb = site.OpenWeb(); } SPList documentLibrary = oWeb.GetList(webUrl.OriginalString); if (documentLibrary.BaseType == SPBaseType.DocumentLibrary) { return(documentLibrary); } else { return(null); } }
private static SPUserToken GetSiteAdminUserToken(Guid siteId, SPUrlZone urlZone) { SPUserToken siteAdminUserToken = null; RunWithElevatedPrivileges(delegate { using (SPSite site = new SPSite(siteId, urlZone)) { using (SPSite site2 = new SPSite(siteId, urlZone, site.SystemAccount.UserToken)) { IEnumerator enumerator = site2.RootWeb.SiteUsers.GetEnumerator(); SPUser current; while (enumerator.MoveNext()) { current = (SPUser)enumerator.Current; if (current.IsSiteAdmin) { goto Label_0061; } } return; Label_0061: siteAdminUserToken = current.UserToken; } } }); return(siteAdminUserToken); }
/// <summary> /// Gets the collection of all the sites in the site collection. /// </summary> /// <param name="site">A SharePoint site collection</param> /// <returns>The collection of all the sites in the site collection</returns> public static SPWebCollection GetSPWebCollectionFromSite(SPSite site) { SPUserToken token = site.SystemAccount.UserToken; SPSite elevatedSiteCollection = new SPSite(site.ID, token); return(elevatedSiteCollection.AllWebs); }
public override void ItemAdded(SPItemEventProperties properties) { /*Reactivate Feature for Syncronization Update*/ try { SPFile file = properties.ListItem.File; //this checks for a File type //Only set Folders and DocSets, Files Inherit Permissions from DocSet if (file == null) //check for folders and file types and check out file { /*Impersonate System Account*/ SPSite tempSite = properties.Web.Site; SPUserToken systoken = tempSite.SystemAccount.UserToken; //Use System Account using (SPSite sysSite = new SPSite(tempSite.Url, systoken)) { using (SPWeb sysWeb = sysSite.OpenWeb(properties.Web.ServerRelativeUrl)) { SPQuery query = new SPQuery(); query.ViewXml = "<View Scope='RecursiveAll'/>"; SPWeb sysParentWeb = sysSite.RootWeb; SPList syslist = sysWeb.Lists.TryGetList(properties.List.Title); SPListItemCollection coll = syslist.GetItems(query); SPListItem sysItem = coll.GetItemById(properties.ListItem.ID); SPList ccpList = sysParentWeb.Lists.TryGetList("Permissions List"); //get CCPList ItemPermissions.SetItem(sysWeb, ccpList, sysItem); //set item permissions } } } else if (file != null) { properties.ListItem["Permission Status"] = "Inherit from Parent"; properties.ListItem.Update(); } } catch (Exception e) { /*UPDATE LOGGING TO INCLUDE SITE*/ //Log SPSite site = properties.Web.Site; SPWeb parentWeb = site.RootWeb; SPList eventLog = parentWeb.Lists.TryGetList("CCPEventFeatureLog");//get log list SPListItem item = eventLog.AddItem(); item["ListEvents"] = e.Message; item["Site"] = properties.Web.Url; if (properties.List.Title == "Contracts") { item["Contracts"] = properties.Web.Title; } else if (properties.List.Title == "Proposals") { item["Proposals"] = properties.Web.Title; } item.Update(); } }
public static void RunWithAccountSystem(SPSite currentSite, Action <SPSite> action) { SPUserToken systoken = currentSite.SystemAccount.UserToken; using (SPSite site = new SPSite(currentSite.Url, systoken)) { action(site); } }
private static void switchUser(SPWeb web, string siteStr, string user) { //impersonate somebody else SPUserToken userToken = web.AllUsers[user].UserToken; SPSite s = new SPSite(siteStr, userToken); SPWeb w = s.OpenWeb(); Console.WriteLine("Currently logged in as: " + w.CurrentUser.ToString() + "(" + w.CurrentUser.Name + ")"); }
/// <summary> /// An item was added. /// </summary> public override void ItemAdded(SPItemEventProperties properties) { //test {0} and test {1} //base.ItemAdded(properties); string webUrl = properties.WebUrl; SPUserToken sysAdminToken = properties.Site.SystemAccount.UserToken; using (SPSite site = new SPSite(webUrl, sysAdminToken)) { using (SPWeb web = site.OpenWeb()) { SPList list = web.GetList("/Lists/eventListTest"); SPQuery query = new SPQuery() { Query = string.Format(@"<Where><Eq><FieldRef Name='ListId' /><Value Type='Text'>{0}</Value></Eq></Where>", properties.ListId.ToString().ToUpper()) }; SPListItemCollection items = list.GetItems(query); foreach (SPListItem item in items) { if (item["Params"].ToString().Length > 0) { string[] pNames = item["Params"].ToString().Split(','); object[] param = new object[pNames.Length]; for (int i = 0; i < pNames.Length; i++) { if (pNames[i].ToUpper().Contains(".LOOKUPID")) { string[] s = pNames[i].Split('.'); param[i] = new SPFieldLookupValue(properties.ListItem[s[0]].ToString()).LookupId; } else if (pNames[i].ToUpper().Contains(".LOOKUPVALUE")) { string[] s = pNames[i].Split('.'); param[i] = new SPFieldLookupValue(properties.ListItem[s[0]].ToString()).LookupValue; } else { param[i] = properties.ListItem[pNames[i]].ToString(); } } properties.ListItem[item["Field"].ToString()] = string.Format(item["Value"].ToString(), param); } else { properties.ListItem[item["Field"].ToString()] = string.Format(item["Value"].ToString()); } } if (items.Count > 0) { properties.ListItem.SystemUpdate(false); } } } }
public SPUserTokenInstance(ObjectInstance prototype, SPUserToken userToken) : this(prototype) { if (userToken == null) { throw new ArgumentNullException("userToken"); } m_userToken = userToken; }
public static SPList GetSPListFromURL(string url, SPUserToken userToken) { using (SPSite site = new SPSite(url, userToken)) { using (SPWeb web = site.OpenWeb()) { return(web.GetList(url)); } } }
public static void RunWithAccountSystem(Action <SPSite> action) { var currentSite = SPContext.Current.Site; SPUserToken systoken = currentSite.SystemAccount.UserToken; using (SPSite site = new SPSite(currentSite.Url, systoken)) { action(site); } }
public static void RunWithAccountSystem(SPSite currentSite, Action <SPWeb> action) { SPUserToken systoken = currentSite.SystemAccount.UserToken; using (SPSite site = new SPSite(currentSite.Url, systoken)) { using (SPWeb web = site.OpenWeb()) { action(web); } } }
private static SPUserToken GetSystemAccountUserToken(Guid siteId, SPUrlZone urlZone) { SPUserToken systemAccountUserToken = null; RunWithElevatedPrivileges(delegate { using (SPSite site = new SPSite(siteId, urlZone)) { systemAccountUserToken = site.SystemAccount.UserToken; } }); return(systemAccountUserToken); }
public static SPUserToken GetUserToken(string url, string userName) { SPSite site = new SPSite(url); SPUserToken token = site.SystemAccount.UserToken; try { token = site.OpenWeb().Users[userName].UserToken; } catch (Exception ex) { SquadronContext.Errr(ex.ToString()); } return(token); }
static void Download(string url, string SPListURLDir, string SPListItemId, HttpContext context) { SPUserToken userToken = null; SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(url)) using (SPWeb web = site.OpenWeb()) { try { userToken = web.AllUsers[0].UserToken; SPSite s = new SPSite(url, userToken); //hack for SP2019. try to access by user, else access by admin var type = web.GetList(SPListURLDir).Title.ToString(); var logList = s.RootWeb.Lists.TryGetList(type); SPList list = logList != null ? logList : web.GetList(SPListURLDir); SPWeb w = logList != null ? s.OpenWeb() : site.OpenWeb(); SPListItem item = list.GetItemById(Int32.Parse(SPListItemId)); //get and send file SPFile file = item.File; var ContentType = MimeMapping.GetMimeMapping(file.Name); if (file != null) { byte[] bArray = file.OpenBinary(); context.Response.Clear(); context.Response.Charset = Encoding.Unicode.EncodingName; context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", file.Name)); context.Response.AddHeader("Content-Length", file.Length.ToString()); context.Response.BinaryWrite(bArray); context.Response.ContentType = ContentType; context.Response.Flush(); context.Response.Close(); context.Response.End(); } } catch (Exception ex) { Log.LogError(ex.Message); } } }); }
public static void RunWithCurrentRequestAndElevatedPrivilegesAndAccountSystem(Action <SPSite> action) { var request = HttpContext.Current.Request; var rootUrl = $"{request.Url.Scheme}://{request.Url.Authority}"; SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite currentSite = new SPSite(rootUrl)) { SPUserToken systoken = currentSite.SystemAccount.UserToken; using (SPSite site = new SPSite(currentSite.Url, systoken)) { action(site); } } }); }
private SPBasePermissions GetPermissionsForUser(ref SPUser user, ref SPWeb web) { SPBasePermissions perms = SPBasePermissions.EmptyMask; try { SPUserToken userToken = user.UserToken; System.Reflection.MethodInfo getPermissions = typeof(Microsoft.SharePoint.Utilities.SPUtility).GetMethod("GetPermissions", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Static); perms = (SPBasePermissions)getPermissions.Invoke(null, new object[] { userToken, web }); } catch { } return(perms); }
string GetRemainingTasks(string relativePath) { string remainingTasks = string.Empty; SPUserToken userToken = SPContext.Current.Web.CurrentUser.UserToken; string rootUrl = SPContext.Current.Site.RootWeb.Url; //Bankpayment using (SPSite site = new SPSite(rootUrl + relativePath, userToken)) using (SPWeb web = site.OpenWeb()) { SPListItemCollection col = GetCollection(web); if (col != null && col.Count > 0) { remainingTasks = "(" + col.Count + ")"; } } return(remainingTasks); }
public static SPUserToken GetSystemToken(this SPSite site) { SPUserToken token = null; bool tempCADE = site.CatchAccessDeniedException; bool siteIsUnlocked = true; try { //site.CatchAccessDeniedException = false; token = site.SystemAccount.UserToken; } catch (SPException spEx) { if (site.IsReadLocked) { // in this case SiteCollection is locked // not possible to get system account token, continue with a "normal" token siteIsUnlocked = false; token = site.UserToken; } else { throw spEx; } } catch (UnauthorizedAccessException) { SPSecurity.RunWithElevatedPrivileges(() => { using (SPSite elevSite = new SPSite(site.ID)) token = elevSite.SystemAccount.UserToken; }); } finally { if (siteIsUnlocked) { site.CatchAccessDeniedException = tempCADE; } } return(token); }
public static SPWeb Elevate(this SPWeb web) { SPWeb _Web = null; if (web != null) { SPUserToken token = null; SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(web.Site.ID)) token = site.SystemAccount.UserToken; }); using (SPSite site = new SPSite(web.Site.ID, token)) _Web = site.OpenWeb(web.ID); } return(_Web); }
private static void ImpersonateAndCheckIn(SPSite spSite, Guid webId, string documentLibraryName, Guid itemId, SPUserToken token) { using (var site = new SPSite(spSite.Url, token)) { try { SPListItem item = site.AllWebs[webId].Lists[documentLibraryName].Items[itemId]; item.File.CheckIn("Automated checkin", SPCheckinType.MajorCheckIn); item.Update(); } catch (Exception) { return; } } }