public static void BatchDeleteItems(SPList splTask, SPQuery query,SPWeb web) { // Set up the variables to be used. StringBuilder methodBuilder = new StringBuilder(); string batch = string.Empty; string batchFormat = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<Batch onError=\"Return\">{0}</Batch>"; string methodFormat = "<Method ID=\"{0}\">" + "<SetList Scope=\"Request\">{1}</SetList>" + "<SetVar Name=\"ID\">{2}</SetVar>" + "<SetVar Name=\"Cmd\">Delete</SetVar>" + "</Method>"; // Get the list containing the items to update. //PList list = WorkFlowUtil.GetWorkflowList(listName); // Query to get the unprocessed items. SPListItemCollection unprocessedItems = splTask.GetItems(query); // Build the CAML delete commands. foreach (SPListItem item in unprocessedItems) { methodBuilder.AppendFormat(methodFormat, "1", item.ParentList.ID, item.ID.ToString()); } // Put the pieces together. batch = string.Format(batchFormat, methodBuilder.ToString()); // Process the batch of commands. string batchReturn = web.ProcessBatchData(batch.ToString()); }
public void ActivateFeaturesInWeb(SPWeb web) { foreach (Feature feature in _featureset.WebFeatures) { PerformAction(web, web.Features, feature); } }
/// <summary> /// This method returns all publication locations /// </summary> /// <returns>SPListItemCollection</returns> public SPListItem GetProjectDetails(string PID,SPWeb Web) { SPList ObjList = Web.Lists["Project Documents"]; SPQuery _query=new SPQuery(); _query.Query="<Where><Eq><FieldRef Name=\"Persistent_x0020_ID\" /><Value Type=\"Text\">" + PID + "</Value></Eq></Where>"; return ObjList.GetItems(_query)[0]; }
/// <summary> /// Bind workflow /// </summary> /// <param name="web"></param> /// <param name="contentTypeName"></param> /// <param name="workflowName"></param> public static void BindWorkflow(SPWeb web, string contentTypeName, string workflowName) { SPContentType siteContentType = web.ContentTypes[contentTypeName]; string taskListTitle = ApplicationConfig.TaskListName; string historyListTitle = ApplicationConfig.HistoryListName; SPWorkflowAssociation wfAssoc = null; // Get a template. SPWorkflowTemplate workflowTemplate = web.WorkflowTemplates.Cast<SPWorkflowTemplate>().FirstOrDefault(wft => wft.Name == workflowName); // Add the association to the content type or update it if it already exists. if ((wfAssoc = siteContentType.WorkflowAssociations.GetAssociationByName(workflowName, web.Locale)) == null) { wfAssoc = SPWorkflowAssociation.CreateWebContentTypeAssociation(workflowTemplate, workflowName, taskListTitle, historyListTitle); siteContentType.WorkflowAssociations.Add(wfAssoc); } else { siteContentType.WorkflowAssociations.Update(wfAssoc); } // Propagate to children of this content type. siteContentType.UpdateWorkflowAssociationsOnChildren(false, // Do not generate full change list true, // Push down to derived content types true, // Push down to list content types false); // Do not throw exception if sealed or readonly }
public static void Get_ZUS_ZD(SPWeb web, int okresId, bool isChorobowa, bool isPracownicy, out double skladkaZD, out DateTime terminPlatnosci, out DateTime terminPrzekazania) { skladkaZD = -1; terminPlatnosci = new DateTime(); terminPrzekazania = new DateTime(); SPList list = web.Lists.TryGetList(targetList); //if (list != null) //{ SPListItem item = list.GetItemById(okresId); if (item != null) { Get_ZUS_Terminy(isPracownicy, ref terminPlatnosci, ref terminPrzekazania, item); //składka zdrowotna skladkaZD = Double.Parse(item["colZUS_D_ZD_Skladka"].ToString()); } //} }
public void Send(SPWeb web, IEnumerable<string> emailTo, string senderDisplayName, string subject, string body) { if (web == null) throw new ArgumentNullException("web"); if (emailTo == null || !emailTo.Any()) throw new ArgumentNullException("emailTo"); var webApplication = web.Site.WebApplication; var from = new MailAddress(webApplication.OutboundMailSenderAddress, senderDisplayName); var message = new MailMessage { IsBodyHtml = true, Body = body, From = from }; var smtpServer = webApplication.OutboundMailServiceInstance; var smtp = new SmtpClient(smtpServer.Server.Address); foreach (var email in emailTo) { message.To.Add(email); } message.Subject = subject; smtp.Send(message); }
public static void AddList(SPWeb web) { if (web.Lists.TryGetList(ListName) == null) { web.AllowUnsafeUpdates = true; var listGuid = web.Lists.Add(ListName, "A list of the most recent files and documents that have changed on this site and subsites.", SPListTemplateType.GenericList); var list = web.Lists[listGuid]; list.Hidden = true; list.EnableAttachments = false; list.EnableSyndication = true; list.NoCrawl = true; list.Update(); list.Fields.Add(web.Fields.GetFieldByInternalName("URL")); list.Update(); var createdField = list.Fields["Created"]; createdField.Indexed = true; createdField.Update(); var view = list.DefaultView; view.ViewFields.Add("URL"); view.ViewFields.Add("Created"); const string viewQuery = @"<OrderBy><FieldRef Name='Created' Ascending='FALSE' /></OrderBy>"; view.Query = viewQuery; view.Update(); list.Update(); ULSLog.LogMessage(string.Format("Successfully added {0} list to site. Direct URL = {1}/{2}", ListName, list.ParentWeb.Url, list.RootFolder.Url)); } }
public void AddNiemUploadEventReceiver(SPWeb sysWeb, string spListTitle) { SPList spListCustom = null; spListCustom = sysWeb.Lists.TryGetList(spListTitle); if (spListCustom != null) { // add the TitleFieldUpdateListEventReceiver to specific lists string assemblyName = "Niem.CaseUpload, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6f7c7006f477a0a5"; string className = "Niem.CaseUpload.NiemUploadCaseHandler.NiemUploadCaseEventHandler"; // When the user is tyring //SPEventReceiverDefinition erAdding = spListCustom.EventReceivers.Add(); //erAdding.Assembly = assemblyName; //erAdding.Class = className; //erAdding.Type = SPEventReceiverType.ItemAdding; //erAdding.Name = "NiemUploadCaseHandlerEventReceiverItemAdding"; //erAdding.Update(); SPEventReceiverDefinition erUpdating = spListCustom.EventReceivers.Add(); erUpdating.Assembly = assemblyName; erUpdating.Class = className; erUpdating.Type = SPEventReceiverType.ItemUpdating; erUpdating.Name = "NiemUploadCaseHandlerEventReceiverItemUpdating"; erUpdating.Update(); spListCustom.Update(); } }
protected void Page_Load(object sender, EventArgs e) { web = SPContext.Current.Web; if (!IsPostBack) { SPListCollection lists = web.GetListsOfType(SPBaseType.DocumentLibrary); ddDocLibs.DataSource = lists; ddDocLibs.DataTextField = "Title"; ddDocLibs.DataValueField = "Title"; ddDocLibs.DataBind(); SPUserCollection users = web.SiteUsers; ddUsers.DataSource = users; ddUsers.DataTextField = "Name"; ddUsers.DataValueField = "LoginName"; ddUsers.DataBind(); SPRoleDefinitionCollection roleDefinitions = web.RoleDefinitions; ddPermissionsLevels.DataSource = roleDefinitions; ddPermissionsLevels.DataTextField = "Name"; ddPermissionsLevels.DataValueField = "Name"; ddPermissionsLevels.DataBind(); } }
public static void ImportSecurity(XmlDocument xmlDoc, bool includeItemSecurity, SPWeb web) { Logger.Write("Start Time: {0}.", DateTime.Now.ToString()); foreach (XmlElement listElement in xmlDoc.SelectNodes("//List")) { SPList list = null; try { list = web.GetList(web.ServerRelativeUrl.TrimEnd('/') + "/" + listElement.GetAttribute("Url")); } catch (ArgumentException) { } catch (FileNotFoundException) { } if (list == null) { Console.WriteLine("WARNING: List was not found - skipping."); continue; } ImportSecurity(list, web, includeItemSecurity, listElement); } Logger.Write("Finish Time: {0}.\r\n", DateTime.Now.ToString()); }
public static void CreateListStructure(SPWeb web) { var helper = new ListHelper(web) { Title = ListsName.DisplayName.StatisticsList, Name = ListsName.InternalName.StatisticsList, OnQuickLaunch = false, EnableAttachments = false }; helper.AddField(new SingleLineTextFieldCreator(FieldsName.StatisticsList.InternalName.UserBrowser, FieldsName.StatisticsList.DisplayName.UserBrowser)); helper.AddField(new SingleLineTextFieldCreator(FieldsName.StatisticsList.InternalName.UserIP, FieldsName.StatisticsList.DisplayName.UserIP)); helper.AddField(new SingleLineTextFieldCreator(FieldsName.StatisticsList.InternalName.UserUrl, FieldsName.StatisticsList.DisplayName.UserUrl)); SPList list = helper.Apply(); SPField fieldTitle = list.Fields.GetField(FieldsName.StatisticsList.InternalName.Title); if (fieldTitle!=null) { fieldTitle.Title = FieldsName.StatisticsList.DisplayName.Title; fieldTitle.Update(); } list.Update(); var defaultView = list.DefaultView; defaultView.ViewFields.DeleteAll(); defaultView.RowLimit = 100; defaultView.Query = "<OrderBy><FieldRef Name='ID' Ascending='FALSE' /></OrderBy>"; defaultView.ViewFields.Add(Constants.FieldTitleLinkToItem); defaultView.ViewFields.Add(FieldsName.StatisticsList.InternalName.UserBrowser); defaultView.ViewFields.Add(FieldsName.StatisticsList.InternalName.UserIP); defaultView.ViewFields.Add(FieldsName.StatisticsList.InternalName.UserUrl); defaultView.Update(); }
internal static void Create(SPWeb web, int klientId, int okresId) { SPListItem item = tabKlienci.Get_KlientById(web, klientId); if (item != null) { SPFieldLookupValueCollection kody; switch (item.ContentType.Name) { case "Osoba fizyczna": case "Firma": kody = new SPFieldLookupValueCollection(item["selSerwisyWspolnicy"].ToString()); break; default: kody = new SPFieldLookupValueCollection(item["selSewisy"].ToString()); break; } foreach (SPFieldLookupValue kod in kody) { switch (kod.LookupValue) { case @"PD-M": Create_PD_M_Form(web, item.ID, okresId); break; case @"PD-KW": Create_PD_KW_Form(web, item.ID, okresId); break; default: break; } } } }
internal static void WriteToLog(SPWeb web, string message) { ASCIIEncoding enc = new ASCIIEncoding(); UnicodeEncoding uniEncoding = new UnicodeEncoding(); string errors = message; SPFile files = web.GetFile("/" + DocumentLibraryName + "/" + LogFileName); if (files.Exists) { byte[] fileContents = files.OpenBinary(); string newContents = enc.GetString(fileContents) + Environment.NewLine + errors; files.SaveBinary(enc.GetBytes(newContents)); } else { using (MemoryStream ms = new MemoryStream()) { using (StreamWriter sw = new StreamWriter(ms, uniEncoding)) { sw.Write(errors); } SPFolder LogLibraryFolder = web.Folders[DocumentLibraryName]; LogLibraryFolder.Files.Add(LogFileName, ms.ToArray(), false); } } web.Update(); }
public SPList GetSitePagesLibrary(SPWeb web) { SPList wikiList; try { string serverRelativeUrl = web.ServerRelativeUrl; if (serverRelativeUrl == "/") { serverRelativeUrl = "/SitePages"; } else { serverRelativeUrl = serverRelativeUrl + "/SitePages"; } wikiList = web.GetList(serverRelativeUrl); } catch { wikiList = null; } if ((wikiList != null) && (wikiList.BaseTemplate != SPListTemplateType.WebPageLibrary)) { wikiList = null; } return wikiList; }
/// <summary> /// Method to ensure a file in a document library. Will create if not exist. /// </summary> /// <param name="web">The web where the list or library is</param> /// <param name="listTitle">The list title where to ensure the file</param> /// <param name="file">The fileinfo containing all the information needed to create the file</param> /// <returns>The file</returns> public SPFile EnsureFile(SPWeb web, string listTitle, FileInfo file) { if (file == null) { throw new ArgumentNullException("file"); } SPFile sharePointFile = null; // Locate the list/library var list = this.listLocator.TryGetList(web, listTitle); // Go get the file if its url is not null if (file.Url != null) { sharePointFile = web.GetFile(file.Url.ToString()); } // If the file is not found, create it. if (sharePointFile == null || file.Overwrite) { sharePointFile = list.RootFolder.Files.Add(file.FileName, file.Data, file.Overwrite); } return sharePointFile; }
protected void assign_roles(SPWeb web, SPListItem item, SPListItem project, string field_name, string field_guid, SPRoleDefinition definition) { try { string value = project[field_name].ToString(); SPFieldUserValueCollection field_user_value = (SPFieldUserValueCollection)project.Fields[new Guid(field_guid)].GetFieldValue(value); foreach (SPFieldUserValue user_value in field_user_value) { if (user_value.User == null) { SPGroup group = web.SiteGroups.GetByID(user_value.LookupId); bind_role(item, group, definition); } else { bind_role(item, user_value.User, definition); } } } catch (Exception ex) { log(web.Site, "为项目【" + project["Title"] + "】的【" + field_name + "】的文档授权时发生错误", "错误", ex.ToString()); } }
const string targetList = "Procedury"; //"tabProcedury"; #endregion Fields #region Methods public static bool AddNew(SPWeb web, string nazwaProcedury) { bool result = false; SPList list = web.Lists.TryGetList(targetList); //if (list!=null) //{ SPListItem item = list.AddItem(); item["Title"] = nazwaProcedury; try { item.SystemUpdate(); } catch (Exception) { } finally { result = true; } //} return result; }
/// <summary> /// Na podstawie wprowadzonego tematu zadania sprawdza czy istnieje taka procedura, jeżeli nie istnieje to ją dodaje w statusie nowy, /// jeżeli istnieje i jest zatwierdzona to zwraca jej ID. W pozostałych przypadkach zwraca 0; /// </summary> /// <param name="web"></param> /// <param name="procName"></param> /// <returns></returns> public static int Ensure(SPWeb web, string procName, bool ignorujStatusProcedury) { SPList list = web.Lists.TryGetList(targetList); SPListItem item = list.Items.Cast<SPListItem>() .Where(i => i.Title.Equals(procName)) .FirstOrDefault(); if (item == null) { SPListItem newItem = list.AddItem(); newItem["Title"] = procName; newItem["enumStatusProcedury"] = "Nowa"; newItem.Update(); return newItem.ID; } else { if (BLL.Tools.Get_Text(item, "enumStatusProcedury").Equals("Zatwierdzona") || ignorujStatusProcedury) { return item.ID; } else return 0; } }
public static void Create(SPWeb web, int klientId, int okresId, bool createKK) { Debug.WriteLine("Create RBR Form"); SPListItem item = tabKlienci.Get_KlientById(web, klientId); SPFieldLookupValueCollection kody; switch (item.ContentType.Name) { case "Osoba fizyczna": case "Firma": kody = new SPFieldLookupValueCollection(item["selSerwisyWspolnicy"].ToString()); break; default: kody = new SPFieldLookupValueCollection(item["selSewisy"].ToString()); break; } foreach (SPFieldLookupValue kod in kody) { switch (kod.LookupValue) { case @"RBR": if (createKK) BLL.tabKartyKontrolne.Create_KartaKontrolna(web, item.ID, okresId); Create_BR_Form(web, item.ID, okresId); break; default: break; } } }
protected SPGroup ResolveSecurityGroup(SPWeb web, SecurityGroupLinkDefinition securityGroupLinkModel) { SPGroup securityGroup = null; if (securityGroupLinkModel.IsAssociatedMemberGroup) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "IsAssociatedMemberGroup = true. Resolving AssociatedMemberGroup"); securityGroup = web.AssociatedMemberGroup; } else if (securityGroupLinkModel.IsAssociatedOwnerGroup) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "IsAssociatedOwnerGroup = true. Resolving IsAssociatedOwnerGroup"); securityGroup = web.AssociatedOwnerGroup; } else if (securityGroupLinkModel.IsAssociatedVisitorGroup) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "IsAssociatedVisitorGroup = true. Resolving IsAssociatedVisitorGroup"); securityGroup = web.AssociatedVisitorGroup; } else if (!string.IsNullOrEmpty(securityGroupLinkModel.SecurityGroupName)) { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Resolving group by name: [{0}]", securityGroupLinkModel.SecurityGroupName); securityGroup = web.SiteGroups[securityGroupLinkModel.SecurityGroupName]; } else { TraceService.Error((int)LogEventId.ModelProvisionCoreCall, "IsAssociatedMemberGroup/IsAssociatedOwnerGroup/IsAssociatedVisitorGroup/SecurityGroupName should be defined. Throwing SPMeta2Exception"); throw new SPMeta2Exception("securityGroupLinkModel"); } return securityGroup; }
/// <summary> /// Adds a new permission level to the web. /// </summary> /// <param name = "web"></param> /// <param name = "name"></param> /// <param name = "description"></param> /// <param name = "permissions"></param> public static void CreatePermissionLevel(SPWeb web, string name, string description, SPBasePermissions permissions) { if (!web.IsRootWeb && !web.HasUniqueRoleDefinitions) { throw new NotSupportedException("This web must be broken permission before adding new permission level."); } var roleDefinition = GetRoleDefinition(web, name); if (roleDefinition != null) { if (roleDefinition.BasePermissions != permissions || roleDefinition.Description != description) { roleDefinition.BasePermissions = permissions; roleDefinition.Description = description; roleDefinition.Update(); } } else { roleDefinition = new SPRoleDefinition { Name = name, Description = description, BasePermissions = permissions }; web.RoleDefinitions.Add(roleDefinition); } }
public static void CreateListStructure(SPWeb web) { var helper = new ListHelper(web) { Title = ListsName.DisplayName.SignaturePerson, Name = ListsName.InternalName.SignaturePerson, OnQuickLaunch = false, EnableAttachments = true }; SPList list = helper.Apply(); SPField fieldTitle = list.Fields.GetField(FieldsName.SignaturePerson.InternalName.Title); if (fieldTitle!=null) { fieldTitle.Title = FieldsName.SignaturePerson.DisplayName.Title; fieldTitle.Update(); } list.Update(); var defaultView = list.DefaultView; defaultView.ViewFields.DeleteAll(); defaultView.RowLimit = 100; defaultView.ViewFields.Add(Constants.EditColumn); defaultView.ViewFields.Add(Constants.FieldTitleLinkToItem); defaultView.Update(); }
public Operator(SPWeb web, int operatorId) { SPListItem item = BLL.dicOperatorzy.GetItemById(web, operatorId); this.Email = Get_Text(item, "colEmail"); this.Telefon = Get_Text(item, "colTelefon"); this.Name = item.Title; }
private static void UpdateCurrentComposedLookItem(SPWeb web, ComposedLook composedLook) { var catalog = web.GetCatalog(SPListTemplateType.DesignCatalog); var items = catalog.GetItems(new SPQuery { RowLimit = 1u, Query = "<Where><Eq><FieldRef Name='DisplayOrder'/><Value Type='Number'>0</Value></Eq></Where>", ViewFields = "<FieldRef Name='DisplayOrder'/>", ViewFieldsOnly = true }); // Delete current composed look item if (items.Count == 1) { items[0].Delete(); } // Create the new composed look item var item = catalog.AddItem(); item[BuiltInFields.DisplayOrderName] = 0; item[SPBuiltInFieldId.Name] = SPResource.GetString(web.UICulture, "DesignGalleryCurrentItemName"); item[SPBuiltInFieldId.Title] = SPResource.GetString(web.UICulture, "DesignGalleryCurrentItemName"); item[BuiltInFields.MasterPageUrlName] = HttpUtility.UrlDecode(new Uri(composedLook.MasterPagePath.Url).AbsolutePath); item[BuiltInFields.ThemeUrlName] = HttpUtility.UrlDecode(new Uri(composedLook.ThemePath.Url).AbsolutePath); item[BuiltInFields.ImageUrlName] = composedLook.ImagePath == null ? string.Empty : HttpUtility.UrlDecode(new Uri(composedLook.ImagePath.Url).AbsolutePath); item[BuiltInFields.FontSchemeUrlName] = HttpUtility.UrlDecode(new Uri(composedLook.FontSchemePath.Url).AbsolutePath); item.Update(); }
private SiteMapNode BuildFullMenuStructure(SPWeb currentWeb) { Clear(); SiteMapNode root = null; SPWeb webSite = SPContext.Current.Site.RootWeb; string relativeUrl = webSite.ServerRelativeUrl.ToString(); SPSecurity.RunWithElevatedPrivileges(delegate() { SPSite currentsite = new SPSite(webSite.Site.Url); SPWeb rootweb = currentsite.OpenWeb(relativeUrl); root = new SiteMapNode(this, rootweb.ID.ToString(), rootweb.ServerRelativeUrl, rootweb.Title); if (rootweb == currentWeb) { SiteMapNode root2 = new SiteMapNode(this, "Root", "/", null); AddNode(root2); string cacheKey = rootweb.ID.ToString(); AddMenuToCache(cacheKey, root2); } foreach (SPWeb web in rootweb.Webs) { SiteMapNode node = BuildNodeTree(web); AddNode(node, root); } }); return root; }
/// <summary> /// попытка получения пользователя по логину /// </summary> /// <param name="loginName"></param> /// <returns></returns> public static SPUser GetUserByLoginName(SPWeb web, string loginName) { SPUser ret = null; try { PortalSecurity.RunWithElevatedPrivileges(web, (elSite, elWeb) => { ret = elWeb.AllUsers[loginName]; }); } catch { // скорее всего не удалось найти юзвера по логину или логин был без домена, попробуем иначе try { PortalSecurity.RunWithElevatedPrivileges(web, (elSite, elWeb) => { SPPrincipalInfo pinfo = SPUtility.ResolvePrincipal(elWeb, loginName, SPPrincipalType.User, SPPrincipalSource.All, elWeb.AllUsers, false); if (pinfo != null && !string.IsNullOrEmpty(pinfo.LoginName)) ret = elWeb.AllUsers[pinfo.LoginName]; }); } catch { } } return ret; }
private int GetCurrentWebSiteLevel(SPWeb currentWeb) { //We can't really work out the level from the URL because the URL //might contain managed path that is not part of the site collection //(e.g. http://server/ or http://server/sites/). int level = 0; var tempWeb = currentWeb; while (!tempWeb.IsRootWeb) { level++; tempWeb = tempWeb.ParentWeb; //Official guidance from MS is that we do not need to call Dispose on SPWeb.ParentWeb. } return level; }
public static bool SendMail( SPWeb web, MailMessage message, Models.MailServiceProviders provider = Models.MailServiceProviders.Default) { bool result = false; try { switch (provider) { case MailServiceProviders.MailGun: result = Models.MailGun.SendMail(message); break; case MailServiceProviders.ElasticEmail: break; case MailServiceProviders.SendGrid: break; case MailServiceProviders.TurboSMTP: break; default: //wysyłka przez SharePoint result = Models.LocalSMTP.SendMail(web, message); break; } return result; } catch (Exception ex) { Logger.LogEvent_Exception(web.Name, ex.ToString()); return false; } }
public void InitializeWebDefaultRegionalSettings(SPWeb web) { // Web regional settings should en-CA or fr-CA, depending on web default language var settings = web.Language == (uint)Language.English.Culture.LCID ? this.EnglishCanadianSettings(web, false) : this.FrenchCanadianSettings(web, false); web.RegionalSettings = settings; web.Update(); }
internal static bool SendMail(SPWeb web, System.Net.Mail.MailMessage message) { bool result = false; SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPWeb web1 = web.Site.OpenWeb()) { SmtpClient client = new SmtpClient(); client.Host = web1.Site.WebApplication.OutboundMailServiceInstance.Server.Address; try { client.Send(message); result = true; } catch (Exception ex) { Logger.LogEvent_Exception(web.Name, ex.ToString()); } } }); return result; }
private bool InitializeMSARecommendationControls(int recommendationId) { try { using (SPSite oSPsite = new SPSite(SPContext.Current.Web.Url)) { using (SPWeb oSPWeb = oSPsite.OpenWeb()) { string listName = "MSARecommendation"; // Fetch the List SPList spListMSAR = oSPWeb.GetList(string.Format("{0}/Lists/{1}/AllItems.aspx", oSPWeb.Url, listName)); if (spListMSAR != null) { SPListItem spListItemMSAR = spListMSAR.GetItemById(recommendationId); if (spListItemMSAR != null) { bool isAllowed = true; bool isCompleted = false; SPUser responsiblePerson = null; //Check Permissions if (spListItemMSAR["Assignee"] != null) { string assignee = Convert.ToString(spListItemMSAR["Assignee"]); SPUser currentUser = oSPWeb.CurrentUser; if (currentUser != null && !Utility.CompareUsername(currentUser.LoginName, assignee)) { isAllowed = false; } if (isAllowed == false) { if (CheckPermission()) { DisableControls(); } else { string accessDeniedUrl = Utility.GetRedirectUrl("Access_Denied"); if (!String.IsNullOrEmpty(accessDeniedUrl)) { DisableControls(); Page.Response.Redirect(accessDeniedUrl, false); } return(false); } } } if (spListItemMSAR["Status"] != null) { string status = Convert.ToString(spListItemMSAR["Status"]); if (status.Equals("Completed", StringComparison.OrdinalIgnoreCase)) { isCompleted = true; this.approvedBy_div.Visible = true; DisableControls(); } } if (spListItemMSAR["TargetDate"] != null) { DateTime targetDate; bool bValid = DateTime.TryParse(Convert.ToString(spListItemMSAR["TargetDate"]), new CultureInfo("en-GB"), DateTimeStyles.AssumeLocal, out targetDate); if (!bValid) { targetDate = Convert.ToDateTime(spListItemMSAR["TargetDate"]); } this.targetDate_tf.Value = targetDate.ToShortDateString(); } if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["RecommendationNo"]))) { this.recommendationNo_tf.Value = Convert.ToString(spListItemMSAR["RecommendationNo"]); } if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["Status"]))) { this.status_ddl.Value = Convert.ToString(spListItemMSAR["Status"]); } if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["MSARecommendationDescription"]))) { this.description_ta.Value = Convert.ToString(spListItemMSAR["MSARecommendationDescription"]); } if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["ResponsibleDepartment"]))) { this.responsibleDepartment_tf.Value = Convert.ToString(spListItemMSAR["ResponsibleDepartment"]); } if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["ResponsibleSection"]))) { this.responsibleSection_tf.Value = Convert.ToString(spListItemMSAR["ResponsibleSection"]); } if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["InjuryClass"]))) { this.injuryClassification_tf.Value = Convert.ToString(spListItemMSAR["InjuryClass"]); } if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["TypeOfVoilation"]))) { this.typeOfVoilation_tf.Value = Convert.ToString(spListItemMSAR["TypeOfVoilation"]); } if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["ObservationCategory"]))) { this.observationCategoryA_tf.Value = Convert.ToString(spListItemMSAR["ObservationCategory"]); } if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["ObservationCategory"]))) { this.observationCategoryA_tf.Value = Convert.ToString(spListItemMSAR["ObservationCategory"]); } if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["LastStatement"]))) { this.lastStatement_ta.Value = Convert.ToString(spListItemMSAR["LastStatement"]); } if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["ClosureJustification"]))) { string guessMePattern = "*|~^|^~|*"; string justifications = Convert.ToString(spListItemMSAR["ClosureJustification"]); this.history_div.InnerHtml = Utility.GetFormattedData(justifications, guessMePattern, true); } else { this.history_div.InnerHtml = "<p class='dataItem'>There is no history available.</p>"; } if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["ApprovedBy"]))) { this.approvedBy_tf.Value = Convert.ToString(spListItemMSAR["ApprovedBy"]); } foreach (String attachmentname in spListItemMSAR.Attachments) { String attachmentAbsoluteURL = spListItemMSAR.Attachments.UrlPrefix // gets the containing directory URL + attachmentname; // To get the SPSile reference to the attachment just use this code SPFile attachmentFile = oSPWeb.GetFile(attachmentAbsoluteURL); StringBuilder sb = new StringBuilder(); HtmlTableRow tRow = new HtmlTableRow(); HtmlTableCell removeLink = new HtmlTableCell(); HtmlTableCell fileLink = new HtmlTableCell(); sb.Append(String.Format("<a href='{0}/{1}' target='_blank'>{2}</a>", oSPWeb.Url, attachmentFile.Url, attachmentname)); removeLink.InnerHtml = "<span class='btn-danger removeLink' style='padding:3px; margin-right:3px; border-radius:2px;'><i class='glyphicon glyphicon-remove'></i></span><span class='fileName' style='display:none;'>" + attachmentFile.Name + "</span>"; fileLink.InnerHtml = sb.ToString(); tRow.Cells.Add(removeLink); tRow.Cells.Add(fileLink); this.grdAttachments.Rows.Add(tRow); } //Responsible Person if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["ResponsiblePerson"]))) { string username = Convert.ToString(spListItemMSAR["ResponsiblePerson"]); responsiblePerson = Utility.GetUser(oSPWeb, username); if (responsiblePerson == null) { if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["Assignee"]))) { string tempUsername = Convert.ToString(spListItemMSAR["Assignee"]); responsiblePerson = Utility.GetUser(oSPWeb, tempUsername); } } if (responsiblePerson != null) { // Clear existing users from control this.responsiblePerson_PeopleEditor.Entities.Clear(); // PickerEntity object is used by People Picker Control PickerEntity UserEntity = new PickerEntity(); // CurrentUser is SPUser object UserEntity.DisplayText = responsiblePerson.Name; UserEntity.Key = responsiblePerson.LoginName; // Add PickerEntity to People Picker control this.responsiblePerson_PeopleEditor.Entities.Add(this.responsiblePerson_PeopleEditor.ValidateEntity(UserEntity)); } } //Status if (!String.IsNullOrEmpty(Convert.ToString(spListItemMSAR["Status"]))) { //Write some code here } //ResponsibleSection if (spListItemMSAR["ResponsibleSection"] != null) { int sectionId = Convert.ToInt32(spListItemMSAR["ResponsibleSection"]); listName = "Section"; // Fetch the List SPList spList = oSPWeb.GetList(string.Format("{0}/Lists/{1}/AllItems.aspx", oSPWeb.Url, listName)); if (spList != null && sectionId > 0) { SPListItem spListItem = spList.GetItemById(sectionId); if (spListItem != null) { this.responsibleSection_tf.Value = Convert.ToString(spListItem["Title"]); } } } //ResponsibleDepartment if (spListItemMSAR["ResponsibleDepartment"] != null) { int id = Convert.ToInt32(spListItemMSAR["ResponsibleDepartment"]); listName = "Department"; // Fetch the List SPList spList = oSPWeb.GetList(string.Format("{0}/Lists/{1}/AllItems.aspx", oSPWeb.Url, listName)); if (spList != null && id > 0) { SPListItem spListItem = spList.GetItemById(id); if (spListItem != null) { string departmentName = Convert.ToString(spListItem["Title"]); this.responsibleDepartment_tf.Value = departmentName; if (String.IsNullOrEmpty(this.approvedBy_tf.Value)) { var hodLI = FillApprovalAuthority(oSPWeb, departmentName); var currentUser = oSPWeb.CurrentUser; if (currentUser != null && hodLI != null && currentUser.Email.Equals(hodLI.Value, StringComparison.OrdinalIgnoreCase)) { this.approvalAuthority_ddl.SelectedValue = hodLI.Value; this.approvalAuthority_ddl.Enabled = false; this.approvalAuthority_ddl.Attributes.Add("class", "formcontrol disableControl"); } } else { var user = Utility.GetUser(oSPWeb, null, this.approvedBy_tf.Value); if (user != null) { this.approvalAuthority_ddl.Items.Add(new ListItem(user.Name, user.Email)); this.approvalAuthority_ddl.Enabled = false; this.approvalAuthority_ddl.Attributes.Add("class", "formcontrol disableControl"); this.approvedBy_tf.Value = user.Name; this.approvalAuthority_ddl.Items.Insert(0, new ListItem("Please Select", "0")); this.approvalAuthority_ddl.DataBind(); this.approvalAuthority_ddl.SelectedValue = user.Email; } } } } } //Initiated By if (spListItemMSAR["MSAID"] != null) { int id = Convert.ToInt32(spListItemMSAR["MSAID"]); //Department listName = "MSA"; // Fetch the List SPList spList = oSPWeb.GetList(string.Format("{0}/Lists/{1}/AllItems.aspx", oSPWeb.Url, listName)); if (spList != null) { SPListItem spListItem = spList.GetItemById(id); if (spListItem != null) { if (!String.IsNullOrEmpty(Convert.ToString(spListItem["AuditedBy"]))) { string auditedBy = Convert.ToString(spListItem["AuditedBy"]); var spUser = Utility.GetUser(oSPWeb, auditedBy); if (spUser != null) { this.initiatedBy_tf.Value = spUser.Name; } else { this.initiatedBy_tf.Value = Convert.ToString(spListItem["AuditedBy"]); } } } } } //Update Control on the basis of current operation SPUser spCurrentUser = oSPWeb.CurrentUser; string approvingAuthorityEmail = null; if (this.approvalAuthority_ddl != null && this.approvalAuthority_ddl.Items.Count > 0) { approvingAuthorityEmail = this.approvalAuthority_ddl.SelectedValue; } //Case: Responsible Person is also Approving Authority if (isAllowed == true && isCompleted == false && responsiblePerson != null && !String.IsNullOrEmpty(responsiblePerson.Email) && responsiblePerson.Email.Equals(approvingAuthorityEmail, StringComparison.OrdinalIgnoreCase)) { this.btnReject.Visible = false; this.btnApprove.Visible = true; this.btnSend.Visible = false; this.approvedBy_div.Visible = true; this.approvedBy_tf.Value = responsiblePerson.Name; } else if (isAllowed == true && isCompleted == false && spCurrentUser != null && !String.IsNullOrEmpty(approvingAuthorityEmail)) { if (spCurrentUser.Email.Equals(approvingAuthorityEmail, StringComparison.OrdinalIgnoreCase)) { this.btnApprove.Visible = true; this.btnReject.Visible = true; this.btnSend.Visible = false; //this.btnSave.Visible = true; this.approvedBy_div.Visible = true; } else { this.btnApprove.Visible = false; this.btnReject.Visible = false; this.btnSend.Visible = true; //this.btnSave.Visible = true; this.approvedBy_div.Visible = false; } } else { DisableControls(); } bool isSavedAsDraft = Convert.ToBoolean(spListItemMSAR["IsSavedAsDraft"]); if (isSavedAsDraft == true) { DisableControls(); } } } return(true); } } } catch (Exception ex) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("SL.FG.FFL(MSARecommendation->InitializeMSARecommendationControls)", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace); message_div.InnerHtml = "Something went wrong!!! Please Contact the administrator."; DisableControls(); } return(false); }
/// <summary> /// Gets the ExportJobs for the particular map schema type for a domain and root map. /// </summary> /// <param name="mapType">OPTIONALLY: The map schema type</param> /// <param name="domainUid">The DomainUid for the exports</param> /// <param name="rootMapUid">The RootMapUid for the exports</param> /// <returns>A list of all the ExportJobs that match the criteria supplied as arguments</returns> private ExportJobsResponse GetExportJobsImp(MapType?mapType, Guid domainUid, Guid rootMapUid) { ExportJobsResponse response = new ExportJobsResponse(); response.ExportJobs = new Dictionary <Guid, ExportJob>(); try { Guid webID = SPContext.Current.Web.ID; Guid siteID = SPContext.Current.Site.ID; SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(siteID)) { using (SPWeb web = site.OpenWeb(webID)) { if (web != null) { SPList exportsList = web.TryGetList(web.GetServerRelativeListUrlPrefix() + "GlymaExports"); //TODO get the name from a constant if (exportsList != null) { SPQuery query = new SPQuery(); if (mapType.HasValue) { query.Query = "<Where><And><And>" + "<Eq><FieldRef Name='DomainUid' /><Value Type='Text'>" + domainUid.ToString() + "</Value></Eq>" + "<Eq><FieldRef Name='RootMapUid' /><Value Type='Text'>" + rootMapUid.ToString() + "</Value></Eq>" + "</And><Eq><FieldRef Name='MapType' /><Value Type='Text'>" + mapType.ToString() + "</Value></Eq></And></Where>" + "<OrderBy><FieldRef Name='Created' Ascending='TRUE'></FieldRef></OrderBy>"; } else { query.Query = "<Where><And>" + "<Eq><FieldRef Name='DomainUid' /><Value Type='Text'>" + domainUid.ToString() + "</Value></Eq>" + "<Eq><FieldRef Name='RootMapUid' /><Value Type='Text'>" + rootMapUid.ToString() + "</Value></Eq>" + "</And></Where>" + "<OrderBy><FieldRef Name='Created' Ascending='TRUE'></FieldRef></OrderBy>"; } //get the exports for this domain/rootmap in ascending order SPListItemCollection exports = exportsList.GetItems(query); foreach (SPListItem export in exports) { ExportJob exportJob = GetExportJob(export); response.ExportJobs.Add(exportJob.Id, exportJob); if (exportJob.Status == ExportStatus.Error) { //maintenance task if the export job had an error clear the TimerJobWorkItem if it was left behind CleanupErrorWorkItems(exportJob, site, web); } } } else { throw new Exception("Failed to find the Glyma Exports list."); } } else { throw new Exception("The SPWeb was not found."); } } } }); } catch (Exception ex) { ExportError error = new ExportError() { ErrorMessage = "Failed to get the export jobs for the site." }; throw new FaultException <ExportError>(error, ex.ToString()); } return(response); }
/// <summary> /// GetSiteDataUsingSPSiteDataQuery - RUN WITH ELEVATED PRIVILEDGES /// </summary> /// <param name="web"></param> private void GetSiteDataUsingSPSiteDataQuery(SPWeb web) { SPSite s = SPContext.Current.Site; SPWeb w = SPContext.Current.Web; try { string dbCon = s.ContentDatabase.DatabaseConnectionString; var cn = new SqlConnection(dbCon); cn.Open(); string siteurl = w.ServerRelativeUrl.Substring(1); string[] rolluplists = PropChartRollupLists.ToArray(); //TODO: This little section is for when they didn't elect to have rollup lists. This will stick the one selected list into the array to use. Refactor this. bool hasRollupLists = true; var selectedList = w.Lists[PropChartSelectedList]; if (rolluplists[0] == "") { hasRollupLists = false; rolluplists[0] = selectedList.Title; } string lists = ""; foreach (string list in rolluplists) { if (hasRollupLists) { string query = ""; if (siteurl == "") { query = "SELECT dbo.AllLists.tp_ID FROM dbo.Webs INNER JOIN dbo.AllLists ON dbo.Webs.Id = dbo.AllLists.tp_WebId WHERE webs.siteid='" + web.Site.ID + "' AND (dbo.AllLists.tp_Title like '" + list.Replace("'", "''") + "')"; } else { query = "SELECT dbo.AllLists.tp_ID FROM dbo.Webs INNER JOIN dbo.AllLists ON dbo.Webs.Id = dbo.AllLists.tp_WebId WHERE (dbo.Webs.FullUrl LIKE '" + siteurl + "/%' OR dbo.Webs.FullUrl = '" + siteurl + "') AND (dbo.AllLists.tp_Title like '" + list.Replace("'", "''") + "')"; } var cmd = new SqlCommand(query, cn); cmd.Parameters.AddWithValue("@list", list); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { lists += "<List ID='" + dr.GetGuid(0) + "'/>"; } dr.Close(); } else { lists = "<List ID='" + selectedList.ID + "'/>"; } var dq = new SPSiteDataQuery(); dq.Lists = "<Lists>" + lists + "</Lists>"; dq.Query = oTopQuery.Query.Replace("<Query>", "").Replace("</Query>", ""); //get from current view dq.Webs = "<Webs Scope='Recursive'/>"; string sYFields = ""; for (int iSeries = 0; iSeries < GetYFields().Length; iSeries++) { string sSeriesName = GetYFields()[iSeries]; sYFields += "<FieldRef Name='" + sSeriesName + "' Nullable='TRUE'/>"; } if (IsBubbleChart()) { dq.ViewFields = "<FieldRef Name='" + PropChartXaxisField + "' Nullable='TRUE'/>" + sYFields + "<FieldRef Name='" + PropChartZaxisField + "' Nullable='TRUE'/>" + "<FieldRef Name='" + PropBubbleChartColorField + "' Nullable='TRUE'/>" + "<FieldRef Name='Title' Nullable='TRUE'/>"; } else { if (!PropChartZaxisField.Contains("None Selected")) { dq.ViewFields = "<FieldRef Name='" + PropChartXaxisField + "' Nullable='TRUE'/>" + "<FieldRef Name='" + PropChartZaxisField + "' Nullable='TRUE'/>" + sYFields; } else { dq.ViewFields = "<FieldRef Name='" + PropChartXaxisField + "' Nullable='TRUE'/>" + sYFields; } } dtSPSiteDataQueryData = new DataTable("SiteDataQueryData"); AppendLookupQueryIfApplicable(dq); dtSPSiteDataQueryData = web.GetSiteData(dq); ConvertEmptySiteQueryDataToNoValue(); ProcessSiteQueryData(list); } cn.Close(); } catch (Exception ex) { HandleException(ex); } }
public void LoadChartDataUsingSPSiteDataQuery() { try { if (ChartDataTable == null) { ChartDataTable = new DataTable("Series"); } DataColumn dcSeriesName = ChartDataTable.Columns["SeriesName"]; if (dcSeriesName == null) { ChartDataTable.Columns.Add("SeriesName"); } _numberOfColumnsInChartDataTable = 0; _numberOfRowsInChartDataTable = 0; SPView oView = null; try { oTopList = SPContext.Current.Web.Lists[PropChartSelectedList]; oView = oTopList.Views[PropChartSelectedView]; } catch (Exception ex) { HandleException(ex); } if (oView != null) { var docQuery = new XmlDocument(); docQuery.LoadXml("<Query>" + oView.Query + "</Query>"); try { XmlNode ndGroupBy = docQuery.SelectSingleNode("//GroupBy"); if (ndGroupBy != null) { docQuery.FirstChild.RemoveChild(ndGroupBy); } } catch (Exception ex) { HandleException(ex); } // node doesn't exist try { XmlNode ndOrderBy = docQuery.SelectSingleNode("//OrderBy"); if (ndOrderBy != null) { docQuery.FirstChild.RemoveChild(ndOrderBy); } } catch (Exception ex) { HandleException(ex); } // node doesn't exist oTopQuery = new SPQuery(); oTopQuery.Query = GetFilterQuery(oTopList, docQuery); // oView.Query; } // process this site SPSecurity.RunWithElevatedPrivileges( delegate { using (SPWeb web = SPContext.Current.Site.OpenWeb()) { GetSiteDataUsingSPSiteDataQuery(web); } }); // process any sites configured in the chart web part settings if (PropChartRollupSites.Length > 0) { string[] arSites = PropChartRollupSites.ToArray(); foreach (string sSite in arSites) { if (sSite.Trim().Length > 0) { try { SPSecurity.RunWithElevatedPrivileges( delegate { using (var site = new SPSite(sSite)) { using (SPWeb webCurr = site.OpenWeb()) { if (webCurr.Url.ToLower() == sSite) { GetSiteDataUsingSPSiteDataQuery(webCurr); } } } }); } catch (Exception ex) { HandleException(ex); } } } } } catch (Exception ex) { HandleException(ex); } }
private void CreateDetailNewsPage(SPWeb web, SPList list) { var rootFolder = list.RootFolder; var dispFormUrl = string.Format("{0}/{1}/{2}.aspx", web.ServerRelativeUrl.TrimEnd('/'), rootFolder.Url, Constants.NEWS_DISPLAYPAGE); var dispForm = web.GetFile(dispFormUrl); if (dispForm != null && dispForm.Exists) { dispForm.Delete(); // delete & recreate our display form } // create a new DispForm dispForm = rootFolder.Files.Add(dispFormUrl, SPTemplateFileType.FormPage); WebPartHelper.ProvisionWebpart(web, new WebpartPageDefinitionCollection() { new WebpartPageDefinition() { PageUrl = dispForm.Url, Title = list.Title, Webparts = new System.Collections.Generic.List <WebpartDefinition>() { new DefaultWP() { Index = 0, ZoneId = "Main", WebpartName = "NewsDetailView.webpart", Properties = new System.Collections.Generic.List <Property>() { new Property() { Name = "Title", Value = list.Title }, new Property() { Name = "ChromeType", Type = "chrometype", Value = "2" } } } } }, new WebpartPageDefinition() { PageUrl = dispForm.Url, Title = "Other news", Webparts = new System.Collections.Generic.List <WebpartDefinition>() { new DefaultWP() { Index = 2, ZoneId = "Main", WebpartName = "OtherNewsListView.webpart", Properties = new System.Collections.Generic.List <Property>() { new Property() { Name = "Title", Value = "Other news" } } } } } }); dispForm.Update(); //list.Update(); }
public static string GetWebTemplate(this SPWeb web) { return(string.Format("{0}#{1}", web.WebTemplate, web.Configuration)); }
public static uint GetLCID(this SPWeb web) { return((uint)web.Locale.LCID); }
/// <summary> /// Creates an ExportJob and schedules the WorkItem for the timer job that processes the exports. /// </summary> /// <param name="domainUid">The DominUid for the map being exported</param> /// <param name="rootMapUid">The RootMapUid for the map being exported</param> /// <param name="exportProperties">The export properties for the export</param> /// <param name="mapType">The map type (schema) for the map being exported</param> /// <param name="exportType">The output format for the export</param> /// <returns>The ExportJob that was created</returns> public ExportJobResponse CreateExportJob(Guid domainUid, Guid rootMapUid, IDictionary <string, string> exportProperties, MapType mapType, ExportType exportType) { ExportJobResponse response = new ExportJobResponse(); try { Guid webID = SPContext.Current.Web.ID; Guid siteID = SPContext.Current.Site.ID; SPUser currentUser = null; using (SPSite site = new SPSite(siteID)) { using (SPWeb web = site.OpenWeb(webID)) { if (web != null) { currentUser = web.CurrentUser; } } } SPSecurity.RunWithElevatedPrivileges(delegate() { int userId = -1; SPList exportsList = null; int listItemIdNum = -1; using (SPSite site = new SPSite(siteID)) { using (SPWeb web = site.OpenWeb(webID)) { if (web != null) { if (currentUser == null) { //The current user shouldn't be null, it should have been resolved outside of this RunWithElevatedPrivileges delegate currentUser = web.CurrentUser; } if (currentUser != null) { userId = currentUser.ID; exportsList = web.TryGetList(web.GetServerRelativeListUrlPrefix() + "GlymaExports"); //TODO get the name from a constant if (exportsList != null) { //the text payload will contain the properties serialized into a simple XML format ExportPropertiesDictionary serializableDict = new ExportPropertiesDictionary(exportProperties); string textPayload = serializableDict.ConvertToXml(); Guid workItemId = Guid.NewGuid(); // Create a unique id for the work item and export job listItemIdNum = CreateExportJobListEntry(exportsList, domainUid, rootMapUid, mapType, exportType, workItemId, textPayload, userId); // if the list item was created then create the export job, if it wasn't it was because an export // for this particular root map of this type was already scheduled (changing the properties doesn't have effect) if (listItemIdNum != -1) { site.AddWorkItem(workItemId, //gWorkItemId - A Guid that identifies the work item DateTime.Now.ToUniversalTime(), //schdDateTime - represents a time in universal time for when the work item should take place GlymaExportWorkItemTimerJob.WorkItemTypeId, //gWorkItemType - this must be the GUID used in the GlymaExportWorkItemTimerJob web.ID, //gWebId - The identifier of the web containing the list exportsList.ID, //gParentId - The list ID listItemIdNum, //nItemId - The list item ID number true, //fSetWebId - true to set the Web identifier exportsList.Items.GetItemById(listItemIdNum).UniqueId, //gItemGuid - The unique identifier of the list item domainUid, //gBatchId - A Guid context identifier for the work item engine userId, //nUserId - SPUser ID number null, //rgbBinaryPayload - not used textPayload, //strTextPayload Guid.Empty); //gProcessingId - needs to be Guid.Empty ExportJob scheduledJob = new ExportJob(); scheduledJob.Created = (DateTime)exportsList.Items.GetItemById(listItemIdNum)[SPBuiltInFieldId.Created]; scheduledJob.CreatedBy = new GlymaUser() { Name = currentUser.Name }; scheduledJob.Id = workItemId; scheduledJob.IsCurrent = true; scheduledJob.Status = ExportStatus.Scheduled; scheduledJob.Type = exportType; scheduledJob.MapType = mapType; scheduledJob.ExportProperties = exportProperties; scheduledJob.PercentageComplete = 0; response.ExportJob = scheduledJob; } else { //already scheduled so throw an exception to be handled with an error throw new Exception(string.Format("A scheduled export job already exists for the Glyma map: DomainUid: {0}, RootMapUid: {1}, Export Type: {2}, Map Type: {3}", domainUid.ToString(), rootMapUid.ToString(), exportType.ToString(), mapType.ToString())); } } else { throw new Exception("Failed to find the Glyma Exports list."); } } else { throw new Exception("The current user was not able to be determined."); } } else { throw new Exception("The SPSite and/or the SPWeb were null."); } } } }); } catch (Exception ex) { ExportError error = new ExportError() { ErrorMessage = "Failed to create the Glyma map export job." }; throw new FaultException <ExportError>(error, ex.ToString()); } return(response); }
protected void wzd_aanmelden_FinishButtonClick(object sender, WizardNavigationEventArgs e) { //using (SPLongOperation operation = new SPLongOperation(this.Page)) //{ // operation.Begin(); using (new SPMonitoredScope("Mailing SendMail")) { try { XDocument xmlInputData = new XDocument(new XElement("Properties")); XElement elements = new XElement("Elements", new object[] { new XElement("HEADER"), new XElement("FEATURED_AREA"), new XElement("VERENIGING"), new XElement("GEBRUIKER"), new XElement("OPMERKINGEN"), new XElement("BOTTOM_CALL_TO_ACTION"), new XElement("FOOTER") }); xmlInputData.Root.Add(elements); ClubCloud_Vereniging vereniging = new ClubCloud_Vereniging(); string verenigingsnummer = tbx_verenigingsnummer.Text; string number = string.Empty; int parsed = 0; if (verenigingsnummer.IndexOf('-') > 0) { number = verenigingsnummer.Split('-')[0].Trim(); } else { number = verenigingsnummer; } if (int.TryParse(number, out parsed)) { try { vereniging = Client.GetVerenigingByNummer("00000000", parsed.ToString(), false); } catch (Exception ex) { Logger.WriteLog(Logger.Category.Unexpected, ex.Source, ex.Message); } } if (vereniging == null) { vereniging = new ClubCloud_Vereniging(); } if (vereniging.Nummer != number) { vereniging.Nummer = number; } TextBox vereniging_naam = (TextBox)fvw_vereniging.FindControl("Naam"); string verenigingnaam = vereniging_naam.Text; if (vereniging.Naam != vereniging_naam.Text && !string.IsNullOrWhiteSpace(vereniging_naam.Text)) { vereniging.Naam = vereniging_naam.Text; } TextBox vereniging_KvKNummer = (TextBox)fvw_vereniging.FindControl("KvKNummer"); string verenigingkvknummer = vereniging_KvKNummer.Text; if (vereniging.KvKnummer != vereniging_KvKNummer.Text && !string.IsNullOrWhiteSpace(vereniging_KvKNummer.Text)) { vereniging.KvKnummer = vereniging_KvKNummer.Text; } TextBox vereniging_KvKPlaats = (TextBox)fvw_vereniging.FindControl("KvKPlaats"); string verenigingkvkplaats = vereniging_KvKPlaats.Text; if (vereniging.KvKplaats != vereniging_KvKPlaats.Text && !string.IsNullOrWhiteSpace(vereniging_KvKPlaats.Text)) { vereniging.KvKplaats = vereniging_KvKPlaats.Text; } TextBox vereniging_BankNummer = (TextBox)fvw_vereniging.FindControl("BankNummer"); string verenigingbanknummer = vereniging_BankNummer.Text; if (vereniging.BankNummer != vereniging_BankNummer.Text && !string.IsNullOrWhiteSpace(vereniging_BankNummer.Text)) { vereniging.BankNummer = vereniging_BankNummer.Text; } TextBox vereniging_BankIban = (TextBox)fvw_vereniging.FindControl("BankIban"); string verenigingbankiban = vereniging_BankIban.Text; if (vereniging.BankIban != vereniging_BankIban.Text && !string.IsNullOrWhiteSpace(vereniging_BankIban.Text)) { vereniging.BankIban = vereniging_BankIban.Text; } TextBox vereniging_BankPlaats = (TextBox)fvw_vereniging.FindControl("BankPlaats"); string verenigingbankplaats = vereniging_BankPlaats.Text; if (vereniging.BankPlaats != vereniging_BankPlaats.Text && !string.IsNullOrWhiteSpace(vereniging_BankPlaats.Text)) { vereniging.BankPlaats = vereniging_BankPlaats.Text; } TextBox vereniging_TelefoonOverdag = (TextBox)fvw_vereniging.FindControl("TelefoonOverdag"); string verenigingtelefoonoverdag = vereniging_TelefoonOverdag.Text; if (vereniging.TelefoonOverdag != vereniging_TelefoonOverdag.Text && !string.IsNullOrWhiteSpace(vereniging_TelefoonOverdag.Text)) { vereniging.TelefoonOverdag = vereniging_TelefoonOverdag.Text; } TextBox vereniging_TelefoonAvond = (TextBox)fvw_vereniging.FindControl("TelefoonAvond"); string verenigingtelefoonavond = vereniging_TelefoonAvond.Text; if (vereniging.TelefoonAvond != vereniging_TelefoonAvond.Text && !string.IsNullOrWhiteSpace(vereniging_TelefoonAvond.Text)) { vereniging.TelefoonAvond = vereniging_TelefoonAvond.Text; } TextBox vereniging_Email = (TextBox)fvw_vereniging.FindControl("Email"); string verenigingemail = vereniging_Email.Text; if (vereniging.EmailKNLTB != vereniging_Email.Text && !string.IsNullOrWhiteSpace(vereniging_Email.Text)) { vereniging.EmailKNLTB = vereniging_Email.Text; } xmlInputData.Root.Add(vereniging.ToXElement <ClubCloud_Vereniging>()); ClubCloud_Gebruiker gebruiker = new ClubCloud_Gebruiker(); TextBox persoon_knltb = (TextBox)fvw_persoon.FindControl("KNLTBNummer"); string persoonknltb = persoon_knltb.Text; string lm = string.Empty; parsed = 0; if (int.TryParse(persoonknltb, out parsed)) { lm = "luckyme"; } /* * { * try * { * gebruiker = Client.GetGebruikerByNummer("00000000", vereniging.Id, parsed.ToString(), false); * } * catch (Exception ex) * { * Logger.WriteLog(Logger.Category.Unexpected, ex.Source, ex.Message); * } * } */ if (gebruiker == null) { gebruiker = new ClubCloud_Gebruiker(); } if (gebruiker.Bondsnummer != parsed.ToString()) { gebruiker.Bondsnummer = parsed.ToString(); } TextBox persoon_naam = (TextBox)fvw_persoon.FindControl("Naam"); string persoonnaam = persoon_naam.Text; if (gebruiker.Volledigenaam != persoon_naam.Text && !string.IsNullOrWhiteSpace(persoon_naam.Text)) { gebruiker.Volledigenaam = persoon_naam.Text; } TextBox persoon_TelefoonOverdag = (TextBox)fvw_persoon.FindControl("TelefoonOverdag"); string persoontelefoonoverdag = persoon_TelefoonOverdag.Text; if (gebruiker.TelefoonOverdag != persoon_TelefoonOverdag.Text && !string.IsNullOrWhiteSpace(persoon_TelefoonOverdag.Text)) { gebruiker.TelefoonOverdag = persoon_TelefoonOverdag.Text; } TextBox persoon_TelefoonAvond = (TextBox)fvw_persoon.FindControl("TelefoonAvond"); string persoontelefoonavond = persoon_TelefoonAvond.Text; if (gebruiker.TelefoonAvond != persoon_TelefoonAvond.Text && !string.IsNullOrWhiteSpace(persoon_TelefoonAvond.Text)) { gebruiker.TelefoonAvond = persoon_TelefoonAvond.Text; } TextBox persoon_Email = (TextBox)fvw_persoon.FindControl("Email"); string persoonemail = persoon_Email.Text; if (gebruiker.EmailKNLTB != persoon_Email.Text && !string.IsNullOrWhiteSpace(persoon_Email.Text)) { gebruiker.EmailKNLTB = persoon_Email.Text; } xmlInputData.Root.Add(gebruiker.ToXElement <ClubCloud_Gebruiker>()); XElement aanmelden = new XElement("Aanmelden", new object[] { new XElement("Opmerkingen", opmerkingen.Text), new XElement("Akkoord", akkoord.Checked), new XElement("Datum", DateTime.Now.ToString()), new XElement("IP", GetIPAddress()) }); xmlInputData.Root.Add(aanmelden); EmailTracking tracking = new EmailTracking { CampaignName = "Aanmelden", CampaignSource = "WebSite", ClientId = vereniging.Id, RecipientId = vereniging.Nummer, TrackingId = "UA-9934149-20", CampagneContent = "aanmelden", CampagneMedium = "email", CampagneTerm = "aanmelden" }; xmlInputData.Root.Add(tracking.ToXElement <EmailTracking>()); XElement content = new XElement("Content", new XElement("Subject", string.Format("Aanmelden bij ClubCloud voor {0} ({1})", vereniging.Naam, vereniging.Nummer))); xmlInputData.Root.Add(content); SPSecurity.RunWithElevatedPrivileges(delegate() { try { using (SPSite currentSite = new SPSite(SPContext.Current.Site.ID, SPUrlZone.Internet)) { using (SPWeb web = currentSite.OpenWeb(SPContext.Current.Web.ID)) { SPDocumentLibrary SiteAssets = null; SPDocumentLibrary SitePages = null; SPFolder Templates = null; SPFolder Online = null; SPFile Aanmelden = null; SPFile Webversion = null; SPItem WebversionItem = null; XmlReader template = null; SPList assets = web.Lists.TryGetList("SiteAssets"); if (assets == null) { assets = web.Lists.TryGetList("Siteactiva"); } if (assets != null) { SiteAssets = (SPDocumentLibrary)assets; } if (SiteAssets != null) { Templates = SiteAssets.RootFolder.SubFolders["Templates"]; } SPList pages = web.Lists.TryGetList("SitePages"); if (pages == null) { pages = web.Lists.TryGetList("Sitepagina's"); } if (pages != null) { SitePages = (SPDocumentLibrary)pages; } if (SitePages != null) { Online = SitePages.RootFolder.SubFolders["Online"]; } if (Templates != null && Templates.Exists) { Aanmelden = Templates.Files["aanmelden.xsl"]; } if (Aanmelden != null && Aanmelden.Exists) { template = XmlReader.Create(Aanmelden.OpenBinaryStream()); } if (template == null) { throw new FileNotFoundException("Template not Found", Aanmelden.Url); } string body = GenerateEmailBody(template, xmlInputData); web.AllowUnsafeUpdates = true; if (Online != null && Online.Exists) { Webversion = Online.Files.Add(Guid.NewGuid() + ".aspx", System.Text.Encoding.UTF8.GetBytes(body), true); WebversionItem = pages.GetItemByUniqueId(Webversion.UniqueId); WebversionItem["Title"] = string.Format("Aanmelden bij ClubCloud voor {0} ({1})", vereniging.Naam, vereniging.Nummer); WebversionItem.Update(); } if (Webversion != null && Webversion.Exists) { XElement online = new XElement("Online", new object[] { new XElement("WebVersion", string.Format("{0}/{1}", currentSite.Url, Webversion.Url)) }); xmlInputData.Root.Add(online); } if (Aanmelden != null && Aanmelden.Exists) { template = XmlReader.Create(Aanmelden.OpenBinaryStream()); } body = GenerateEmailBody(template, xmlInputData); web.AllowUnsafeUpdates = false; MailMessage message = Email.CreateMailMessage(body); MailAddress tovereniging = new MailAddress(vereniging.EmailKNLTB, vereniging.Naam, Encoding.UTF8); message.To.Add(tovereniging); MailAddress topersoon = new MailAddress(gebruiker.EmailKNLTB, gebruiker.Volledigenaam, Encoding.UTF8); message.To.Add(topersoon); message.CC.Add(new MailAddress("*****@*****.**", "Aanmelden bij ClubCloud")); message.From = new MailAddress("*****@*****.**", "Aanmelden bij ClubCloud"); message.Subject = string.Format("Aanmelden bij ClubCloud voor {0}({1})", vereniging.Naam, vereniging.Nummer); message.Priority = MailPriority.Normal; message.ReplyToList.Add(new MailAddress("*****@*****.**", "Aanmelden bij ClubCloud")); message.Sender = new MailAddress("*****@*****.**", "Aanmelden bij ClubCloud"); SmtpClient client = new SmtpClient(ZimbraConfiguration.Server.SendMailHost, zimbraconfiguration.Server.SendMailPort); client.Credentials = new System.Net.NetworkCredential(ZimbraConfiguration.Server.SendMailUserName, ZimbraConfiguration.Server.SendMailPassword); client.DeliveryMethod = SmtpDeliveryMethod.Network; message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure | DeliveryNotificationOptions.OnSuccess | DeliveryNotificationOptions.Delay; Email.Send(message, client); } } } catch (Exception ex) { Logger.WriteLog(Logger.Category.Unexpected, ex.Source, ex.Message); } }); } catch (Exception ex) { Logger.WriteLog(Logger.Category.Unexpected, ex.Source, ex.Message); } } //operation.End("bedankt.aspx"); //} }
/// <summary> /// Deletes an ExportJob if it's in the Scheduled, Completed, or Error ExportStates. /// </summary> /// <param name="job">The ExportJob to delete</param> /// <returns>The ExportJob that was deleted</returns> public ExportJobResponse DeleteExportJob(ExportJob job) { ExportJobResponse response = new ExportJobResponse(); try { Guid webID = SPContext.Current.Web.ID; Guid siteID = SPContext.Current.Site.ID; SPSecurity.RunWithElevatedPrivileges(delegate() { SPList exportsList = null; using (SPSite site = new SPSite(siteID)) { using (SPWeb web = site.OpenWeb(webID)) { if (web != null && site != null) { exportsList = web.TryGetList(web.GetServerRelativeListUrlPrefix() + "GlymaExports"); if (exportsList != null) { SPQuery query = new SPQuery(); query.Query = "<Where>" + "<Eq><FieldRef Name='Title' /><Value Type='Text'>" + job.Id.ToString() + "</Value></Eq>" + "</Where>"; SPListItemCollection exports = exportsList.GetItems(query); // There can only be one ExportJob with the job ID (unique values enforced in SP list for Title column) if (exports.Count > 0) { SPListItem exportItem = exports[0]; if (exportItem != null) { string exportStatusStr = exportItem["ExportStatus"] as string; ExportStatus exportStatus = (ExportStatus)Enum.Parse(typeof(ExportStatus), exportStatusStr, true); if (exportStatus == ExportStatus.Scheduled) { SPWorkItemCollection workItemsCollection = new SPWorkItemCollection(site, GlymaExportWorkItemTimerJob.WorkItemTypeId); uint colCount, rowCount = 0; object workItems = null; site.GetWorkItems(workItemsCollection, out colCount, out rowCount, out workItems); //gets all work items for this site of the type GlymaExportWorkItemTimerJob if (workItemsCollection.Count > 0) { // Delete the work item that this export job created SPWorkItemCollection subCollection = workItemsCollection.SubCollection(site, web, 0, (uint)workItemsCollection.Count); subCollection.DeleteWorkItem(job.Id); } } if (exportStatus == ExportStatus.Scheduled || exportStatus == ExportStatus.Completed || exportStatus == ExportStatus.Error) { exportItem.Delete(); //delete the item after it has been cancelled } else if (exportStatus == ExportStatus.Processing) { throw new Exception("The export job is currently processing and cannot be deleted."); } } response.ExportJob = job; } } else { throw new Exception("Failed to find the Glyma Exports list."); } } else { throw new Exception("The SPSite and/or the SPWeb were null."); } } } }); } catch (Exception ex) { ExportError error = new ExportError() { ErrorMessage = "Failed to cancel the Glyma map export job." }; throw new FaultException <ExportError>(error, ex.ToString()); } return(response); }
public SPWebLookupKey(SPWeb web) : this(web.ID) { }
public ErrorAdapter(SPWeb web) : base(web) { }
/// <summary> /// Fixes the pages page layout url so that it points to the page layout in the container site collections master page gallery. /// </summary> /// <param name="publishingWeb">The target publishing web.</param> /// <param name="pageName">Name of the page.</param> /// <param name="pageLayoutUrl">The page layout URL.</param> /// <param name="searchRegex">The search regex.</param> /// <param name="replaceString">The replace string.</param> /// <param name="fixContact">if set to <c>true</c> [fix contact].</param> /// <param name="test">if set to <c>true</c> [test].</param> public static void FixPages(PublishingWeb publishingWeb, string pageName, string pageLayoutUrl, Regex searchRegex, string replaceString, bool fixContact, bool test) { if (!PublishingWeb.IsPublishingWeb(publishingWeb.Web)) { return; } PublishingPageCollection pages; int tryCount = 0; while (true) { try { tryCount++; pages = publishingWeb.GetPublishingPages(); break; } catch (InvalidPublishingWebException) { // The following is meant to deal with a timing issue when using this method in conjuction with other commands. When // used independently this should be unnecessary. if (tryCount > 4) { throw; } Thread.Sleep(10000); SPWeb web = publishingWeb.Web; SPSite site = web.Site; string url = site.MakeFullUrl(web.ServerRelativeUrl); site.Close(); site.Dispose(); web.Close(); web.Dispose(); publishingWeb.Close(); site = new SPSite(url); web = site.OpenWeb(Utilities.GetServerRelUrlFromFullUrl(url)); publishingWeb = PublishingWeb.GetPublishingWeb(web); } } foreach (PublishingPage page in pages) { if (!(string.IsNullOrEmpty(pageName) || page.Name.ToLower() == pageName.ToLower())) { continue; } if (page.ListItem[FieldId.PageLayout] == null) { continue; } Logger.Write("Progress: Begin processing {0}.", page.Url); Logger.Write("Progress: Current layout set to {0}.", page.ListItem[FieldId.PageLayout].ToString()); // Can't edit items that are checked out. if (Utilities.IsCheckedOut(page.ListItem) && !Utilities.IsCheckedOutByCurrentUser(page.ListItem)) { Logger.WriteWarning("WARNING: Page is already checked out by another user - skipping."); continue; } SPFieldUrlValue url; if (string.IsNullOrEmpty(pageLayoutUrl)) { if (searchRegex == null) { if (page.ListItem[FieldId.PageLayout] == null || string.IsNullOrEmpty(page.ListItem[FieldId.PageLayout].ToString().Trim())) { Logger.WriteWarning("WARNING: Current page layout is empty - skipping. Use the 'pagelayout' parameter to set a page layout."); continue; } // We didn't get a layout url passed in or a regular expression so try and fix the existing url url = new SPFieldUrlValue(page.ListItem[FieldId.PageLayout].ToString()); if (string.IsNullOrEmpty(url.Url) || url.Url.IndexOf("/_catalogs/") < 0) { Logger.WriteWarning("WARNING: Current page layout does not point to a _catalogs folder or is empty - skipping. Use the 'pagelayout' parameter to set a page layout Layout Url: {0}", url.ToString()); continue; } string newUrl = publishingWeb.Web.Site.ServerRelativeUrl.TrimEnd('/') + url.Url.Substring(url.Url.IndexOf("/_catalogs/")); string newDesc = publishingWeb.Web.Site.MakeFullUrl(newUrl); if (url.Url.ToLowerInvariant() == newUrl.ToLowerInvariant()) { Logger.Write("Progress: Current layout matches new evaluated layout - skipping."); continue; } url.Url = newUrl; url.Description = newDesc; } else { if (page.ListItem[FieldId.PageLayout] == null || string.IsNullOrEmpty(page.ListItem[FieldId.PageLayout].ToString().Trim())) { Logger.Write("Progress: Current page layout is empty - skipping. Use the pagelayout parameter to set a page layout."); } // A regular expression was passed in so use it to fix the page layout url if we find a match. if (searchRegex.IsMatch((string)page.ListItem[FieldId.PageLayout])) { url = new SPFieldUrlValue(page.ListItem[FieldId.PageLayout].ToString()); string newUrl = searchRegex.Replace((string)page.ListItem[FieldId.PageLayout], replaceString); if (url.ToString().ToLowerInvariant() == newUrl.ToLowerInvariant()) { Logger.Write("Progress: Current layout matches new evaluated layout - skipping."); continue; } url = new SPFieldUrlValue(newUrl); } else { Logger.Write("Progress: Existing page layout url does not match provided regular expression - skipping."); continue; } } } else { // The user passed in an url string so use it. if (pageLayoutUrl.ToLowerInvariant() == (string)page.ListItem[FieldId.PageLayout]) { Logger.Write("Progress: Current layout matches provided layout - skipping."); continue; } url = new SPFieldUrlValue(pageLayoutUrl); } string fileName = url.Url.Substring(url.Url.LastIndexOf('/')); // Make sure that the URLs are server relative instead of absolute. //if (url.Description.ToLowerInvariant().StartsWith("http")) // url.Description = Utilities.GetServerRelUrlFromFullUrl(url.Description) + fileName; //if (url.Url.ToLowerInvariant().StartsWith("http")) // url.Url = Utilities.GetServerRelUrlFromFullUrl(url.Url) + fileName; if (page.ListItem[FieldId.PageLayout] != null && url.ToString().ToLowerInvariant() == page.ListItem[FieldId.PageLayout].ToString().ToLowerInvariant()) { continue; // No difference detected so move on. } Logger.Write("Progress: Changing layout url from \"{0}\" to \"{1}\"", page.ListItem[FieldId.PageLayout].ToString(), url.ToString()); if (fixContact) { SPUser contact = null; try { contact = page.Contact; } catch (SPException) { } if (contact == null) { Logger.Write("Progress: Page contact ('{0}') does not exist - assigning current user as contact.", page.ListItem[FieldId.Contact].ToString()); page.Contact = publishingWeb.Web.CurrentUser; if (!test) { page.ListItem.SystemUpdate(); } } } if (test) { continue; } try { bool publish = false; if (!Utilities.IsCheckedOut(page.ListItem)) { page.CheckOut(); publish = true; } page.ListItem[FieldId.PageLayout] = url; page.ListItem.UpdateOverwriteVersion(); if (publish) { Common.Lists.PublishItems itemPublisher = new Common.Lists.PublishItems(); itemPublisher.PublishListItem(page.ListItem, page.ListItem.ParentList, false, "Automated fix of publishing pages page layout URL.", null, null); } } catch (Exception ex) { Logger.WriteException(new ErrorRecord(ex, null, ErrorCategory.NotSpecified, page)); } } }
public TranslationUserAccount LoadUserAccount(SPWeb spWeb, string sourceLanguage) { string login = string.Empty; string password = string.Empty; string url = string.Empty; List <string> userProfileList = new List <string>(); TranslationUserAccount translationUserAccount = new TranslationUserAccount(); SPUser currentUser = spWeb.CurrentUser; string lang = string.Empty; if (string.IsNullOrEmpty(sourceLanguage)) { if (HttpContext.Current != null) { lang = Utilities.GetLanguageCode(HttpContext.Current); } else { lang = sourceLanguage; } } if (HttpRuntime.Cache.Get("OceanikTranslationAccount " + spWeb.ID.ToString() + currentUser.LoginName + "-" + lang) == null) { try { SPUser rootSiteCurrentUser = spWeb.SiteUsers.GetByID(currentUser.ID); string systranAccount = string.Empty; //if (HttpRuntime.Cache.Get("OceanikTranslationAccount " + currentUser.LoginName) == null) //{ if (spWeb.Lists["Translation Accounts"] != null) { SPList accountsSystranList = spWeb.Lists["Translation Accounts"]; if (HttpRuntime.Cache.Get("OceanikTranslationAccountId " + spWeb.ID.ToString() + currentUser.LoginName) == null) { foreach (SPItem account in accountsSystranList.Items) { if (account["Groups"] != null) { var o = account["Groups"]; SPFieldUserValueCollection groupsForThisAccount = (SPFieldUserValueCollection)account["Groups"]; foreach (SPFieldUserValue groupForThisAccount in groupsForThisAccount) { try { foreach (SPGroup groupForTheRootSiteCurrentUser in rootSiteCurrentUser.Groups) { if (groupForTheRootSiteCurrentUser.Name == groupForThisAccount.LookupValue) { if (accountsSystranList.Fields.ContainsField("Account")) { systranAccount = account["Account"].ToString(); HttpRuntime.Cache.Remove("OceanikTranslationAccountId " + spWeb.ID.ToString() + currentUser.LoginName); HttpRuntime.Cache.Add("OceanikTranslationAccountId " + spWeb.ID.ToString() + currentUser.LoginName, account.ID, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.High, null); //if (accountsSystranList.Fields.ContainsField("Profiles")) //{ // string profilesFieldValue = account["Profiles"].ToString(); // if (profilesFieldValue != string.Empty) // { // Regex lookupRegex = new Regex("[0-9]+;#(?<value>([^;]+))"); // foreach (Match profileName in lookupRegex.Matches(profilesFieldValue)) // { // userProfileArrayList.Add(profileName.Groups["value"].Value); // } // } //} } break; } } if (userProfileList.Count > 0) { break; } } catch { } } if (userProfileList.Count > 0) { break; } } } } if (accountsSystranList.Fields.ContainsField("Account") && accountsSystranList.Fields.ContainsField("Password") && accountsSystranList.Fields.ContainsField("Url")) { string accountId = Convert.ToString(HttpRuntime.Cache.Get("OceanikTranslationAccountId " + spWeb.ID.ToString() + currentUser.LoginName)); SPListItem accountItem = accountsSystranList.Items.Cast <SPListItem>().First(sPListItemTmp => sPListItemTmp.ID.ToString() == accountId); if (accountItem["Account"] != null && accountItem["Password"] != null && accountItem["Url"] != null) { login = accountItem["Account"].ToString(); password = EncryptionUtility.Encrypt(accountItem["Password"].ToString()); url = accountItem["Url"].ToString(); string languageItemSource = string.Empty; if (string.IsNullOrEmpty(sourceLanguage)) { if (HttpContext.Current != null) { languageItemSource = Utilities.GetLanguageCode(HttpContext.Current); } else { languageItemSource = sourceLanguage; } } //foreach (LanguageItem languageItemSource in Dictionaries.Instance.VisibleLanguages) { foreach (LanguageItem languageItemDestination in Dictionaries.Instance.VisibleLanguages) { if (languageItemSource != languageItemDestination.LanguageDestination) { List <string> userProfileListTmp = GetTemplates(ConvertLanguageCode2LettersTo3Letters(languageItemSource), ConvertLanguageCode2LettersTo3Letters(languageItemDestination.LanguageDestination), url, login, password); foreach (string languageItemName in userProfileListTmp) { if (!userProfileList.Contains(languageItemName)) { userProfileList.Add(languageItemName); } } } } } //userProfileList = GetTemplates("eng", "fra", url, login, password); } } } //} } catch { } translationUserAccount.Login = login; translationUserAccount.Password = password; translationUserAccount.Url = url; translationUserAccount.Profiles = userProfileList; HttpRuntime.Cache.Remove("OceanikTranslationAccount " + spWeb.ID.ToString() + currentUser.LoginName + "-" + lang); HttpRuntime.Cache.Add("OceanikTranslationAccount " + spWeb.ID.ToString() + currentUser.LoginName + "-" + lang, translationUserAccount, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.High, null); } else { translationUserAccount = (TranslationUserAccount)(HttpRuntime.Cache.Get("OceanikTranslationAccount " + spWeb.ID.ToString() + currentUser.LoginName + "-" + lang)); } return(translationUserAccount); }
public DisableTaskCenterThrolling(SPWeb web, bool isPfeSite) : base(web, isPfeSite) { }
protected override void OnPreRender(System.EventArgs e) { SPWeb Web = SPContext.Current.Web; SPList List = SPContext.Current.List; SPListItem ListItem = SPContext.Current.ListItem; CssRegistration.Register("/_layouts/epmlive/modal/modal.css"); ScriptLink.Register(Page, "/_layouts/epmlive/modal/modal.js", false); SPRibbon ribbon = SPRibbon.GetCurrent(this.Page); RegisterArchiveRestoreFormButtons(Web, List, ListItem, ribbon); ribbon.TrimById("Ribbon.ListForm.Display.Manage.EditItem"); XmlDocument ribbonExtensions = new XmlDocument(); if (NavigationService.LPPFEPermissionCheck(List, SPBasePermissions.EditListItems)) { ribbonExtensions.LoadXml(@"<Button Id=""Ribbon.ListForm.Display.Manage.EditItem2"" Sequence=""10"" Command=""Ribbon.ListForm.Display.Manage.EditItem2"" Image16by16=""/_layouts/" + Web.Language + @"/images/formatmap16x16.png"" Image16by16Top=""-128"" Image16by16Left=""-224"" Image32by32=""/_layouts/" + Web.Language + @"/images/formatmap32x32.png"" Image32by32Top=""-128"" Image32by32Left=""-96"" LabelText=""Edit Item"" TemplateAlias=""o1""/>"); ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.ListForm.Display.Manage.Controls._children"); } if (!NavigationService.LPPFEPermissionCheck(List, SPBasePermissions.DeleteListItems)) { ribbon.TrimById("Ribbon.ListForm.Display.Manage.DeleteItem"); } EPMLiveCore.GridGanttSettings gSettings = API.ListCommands.GetGridGanttSettings(List); ArrayList arrAssoc = API.ListCommands.GetAssociatedLists(List); if (gSettings.AssociatedItems) { StringBuilder sbLists = new StringBuilder(); foreach (EPMLiveCore.API.AssociatedListInfo ali in arrAssoc) { //sbLists.Append("<Button Id=\"Ribbon.ListForm.Display.Manage.LinkedItemsButton\" Sequence=\"20\" Command=\""); sbLists.Append("<Button Sequence=\"20\" Command=\""); sbLists.Append("Ribbon.ListForm.Display.Associated.LinkedItemsButton"); sbLists.Append("\" Id=\"Ribbon.ListForm.Display.Associated."); sbLists.Append(HttpUtility.HtmlEncode(ali.Title)); sbLists.Append("."); sbLists.Append(ali.LinkedField); sbLists.Append("\" LabelText=\""); sbLists.Append(HttpUtility.HtmlEncode(ali.Title)); sbLists.Append("\" TemplateAlias=\"o1\" Image16by16=\""); sbLists.Append(ali.icon); sbLists.Append("\"/>"); } if (sbLists.Length > 0) { StringBuilder sbLinkedItems = new StringBuilder(); sbLinkedItems.Append("<Group Id=\"Ribbon.ListForm.Display.Associated\" Sequence=\"41\" Command=\"Ribbon.ListForm.Display.Associated.LinkedItems\" Description=\"\" Title=\"Associated Items\" Template=\"Ribbon.Templates.Flexible2\">"); sbLinkedItems.Append("<Controls Id=\"Ribbon.ListForm.Display.Associated.Controls\">"); sbLinkedItems.Append(sbLists); sbLinkedItems.Append("</Controls>"); sbLinkedItems.Append("</Group>"); ribbonExtensions = new XmlDocument(); ribbonExtensions.LoadXml(sbLinkedItems.ToString()); ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.ListForm.Display.Groups._children"); ribbonExtensions = new XmlDocument(); ribbonExtensions.LoadXml("<MaxSize Id=\"Ribbon.ListForm.Display.Associated.MaxSize\" Sequence=\"10\" GroupId=\"Ribbon.ListForm.Display.Associated\" Size=\"MediumMedium\" />"); ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.ListForm.Display.Scaling._children"); //StringBuilder sbLinkedItems = new StringBuilder(); //sbLinkedItems.Append("<FlyoutAnchor Id=\"Ribbon.ListForm.Display.Manage.LinkedItems\" Sequence=\"39\" Command=\""); //sbLinkedItems.Append("Ribbon.ListForm.Display.Manage.LinkedItems"); //sbLinkedItems.Append("\" Image32by32=\"/_layouts/epmlive/images/linkeditems.gif\" LabelText=\"Associated Items\" TemplateAlias=\"o1\">"); //sbLinkedItems.Append("<Menu Id=\"Ribbon.List.EPMLive.LinkedItems.Menu\">"); //sbLinkedItems.Append("<MenuSection Id=\"Ribbon.List.EPMLive.LinkedItems.Menu.Scope\" Sequence=\"10\" DisplayMode=\"Menu16\">"); //sbLinkedItems.Append("<Controls Id=\"Ribbon.List.EPMLive.LinkedItems.Menu.Scope.Controls\">"); //sbLinkedItems.Append(sbLists); //sbLinkedItems.Append("</Controls>"); //sbLinkedItems.Append("</MenuSection>"); //sbLinkedItems.Append("</Menu>"); //sbLinkedItems.Append("</FlyoutAnchor>"); //ribbonExtensions.LoadXml(sbLinkedItems.ToString()); //ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, //"Ribbon.ListForm.Display.Manage.Controls._children"); } } //======================Planner================== API.ListPlannerProps p = API.ListCommands.GetListPlannerInfo(List); if (p.PlannerV2Menu != "") { ribbonExtensions.LoadXml(p.PlannerV2Menu.Replace("EPMLivePlanner", "Ribbon.ListForm.Display.Manage.EPMLivePlanner").Replace("TaskPlanner", "Ribbon.ListForm.Display.Manage.TaskPlanner")); ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.ListForm.Display.Manage.Controls._children"); //if(bPlanner == 1) //{ // EPMLiveWorkPlanner.WorkPlannerAPI.PlannerProps props = EPMLiveWorkPlanner.WorkPlannerAPI.getSettings(Web, sPlannerID); // bUseTeam = props.bUseTeam; // ribbonExtensions.LoadXml("<Button Id=\"Ribbon.ListItem.EPMLive.BuildTeam\" Sequence=\"41\" Command=\"Ribbon.ListForm.Display.Manage.BuildTeam\" LabelText=\"Build Team\" TemplateAlias=\"o1\" Image32by32=\"/_layouts/epmlive/images/editteam32.gif\"/>"); // ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.ListForm.Display.Manage.Controls._children"); //} } //=====================Create Workspace=========== if (gSettings.EnableRequests) { string childitem = ""; try { childitem = ListItem["WorkspaceUrl"].ToString(); } catch { } if ((ListItem.ModerationInformation == null || ListItem.ModerationInformation.Status == SPModerationStatusType.Approved) && childitem == "") { ribbonExtensions = new XmlDocument(); ribbonExtensions.LoadXml("<Button Id=\"Ribbon.ListItem.EPMLive.CreateWorkspace\" Sequence=\"50\" Command=\"Ribbon.ListForm.Display.Manage.CreateWorkspace\" LabelText=\"Create Workspace\" TemplateAlias=\"o2\" Image16by16=\"_layouts/images/epmlivelogosmall.gif\"/>"); ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.ListForm.Display.Manage.Controls._children"); } } //=====================Favorite if (Web.Features[new Guid("046f0200-30e5-4545-b00f-c8c73aef9f0e")] != null) { ribbonExtensions = new XmlDocument(); ribbonExtensions.LoadXml("<Button Id=\"Ribbon.ListItem.EPMLive.FavoriteStatus\" Sequence=\"100\" Command=\"Ribbon.ListForm.Display.Actions.Favorite\" LabelText=\"Favorite\" TemplateAlias=\"o1\" Image32by32=\"_layouts/epmlive/images/star32.png\" Image16by16=\"_layouts/epmlive/images/star16.png\"/>"); ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.ListForm.Display.Actions.Controls._children"); ribbonExtensions = new XmlDocument(); ribbonExtensions.LoadXml("<Button Id=\"Ribbon.ListItem.EPMLive.FavoriteStatus\" Sequence=\"100\" Command=\"Ribbon.ListForm.Display.Actions.Favorite\" LabelText=\"Favorite\" TemplateAlias=\"o1\" Image32by32=\"_layouts/epmlive/images/star32.png\" Image16by16=\"_layouts/epmlive/images/star16.png\"/>"); ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.ListForm.Edit.Actions.Controls._children"); ribbonExtensions = new XmlDocument(); ribbonExtensions.LoadXml("<Button Id=\"Ribbon.ListItem.EPMLive.FavoriteStatus\" Sequence=\"100\" Command=\"Ribbon.ListForm.Display.Actions.Favorite\" LabelText=\"Favorite\" TemplateAlias=\"o1\" Image32by32=\"_layouts/epmlive/images/star32.png\" Image16by16=\"_layouts/epmlive/images/star16.png\"/>"); ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.DocLibListForm.Edit.Actions.Controls._children"); } EPMLiveCore.API.RibbonProperties rp = (EPMLiveCore.API.RibbonProperties)EPMLiveCore.Infrastructure.CacheStore.Current.Get("GR-" + Web.CurrentUser.ID, "GridSettings-" + List.ID, () => { return(EPMLiveCore.API.ListCommands.GetRibbonProps(List)); }).Value; //=====================Build Team=========== try { if (rp.bBuildTeam) { ribbonExtensions = new XmlDocument(); ribbonExtensions.LoadXml("<Button Id=\"Ribbon.ListItem.EPMLive.BuildTeam\" Sequence=\"50\" Command=\"Ribbon.ListForm.Display.Manage.BuildTeam\" LabelText=\"Edit Team\" TemplateAlias=\"o2\" Image16by16=\"_layouts/epmlive/images/buildteam16.gif\"/>"); ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.ListForm.Display.Manage.Controls._children"); } } catch { } //==========Go To Workspace================= string workspaceurl = ""; try { workspaceurl = ListItem["WorkspaceUrl"].ToString(); } catch { } if (workspaceurl != "") { ribbonExtensions = new XmlDocument(); ribbonExtensions.LoadXml("<Button Id=\"Ribbon.ListItem.EPMLive.GoToWorkspace\" Sequence=\"55\" Command=\"Ribbon.ListForm.Display.Manage.GoToWorkspace\" LabelText=\"Go To Workspace\" TemplateAlias=\"o1\" Image32by32=\"_layouts/images/spgraphic.gif\" Image32by32Top=\"7\" Image32by32Left=\"4\"/>"); ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.ListForm.Display.Manage.Controls._children"); } //================EPK=================== if (rp.aEPKButtons.Contains("costs")) { ribbonExtensions = new XmlDocument(); ribbonExtensions.LoadXml(@"<Button Id=""Ribbon.ListItem.Manage.EPKCosts"" Sequence=""101"" Command=""Ribbon.ListForm.Display.Manage.EPKCost"" Image32by32=""/_layouts/epmlive/images/editcosts.png"" LabelText=""Edit Costs"" TemplateAlias=""o1"" />"); ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.ListForm.Display.Manage.Controls._children"); } if (rp.aEPKButtons.Contains("resplan")) { if (rp.aEPKActivex.Contains("resplan")) { ribbonExtensions = new XmlDocument(); ribbonExtensions.LoadXml(@"<Button Id=""Ribbon.ListItem.Manage.EPKResourcePlanner"" Sequence=""103"" Command=""Ribbon.ListForm.Display.Manage.EPKRP"" Image32by32=""/_layouts/epmlive/images/ribbon32.png"" Image32by32Top=""-65"" LabelText=""Edit Resource Plan"" TemplateAlias=""o1"" />"); ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.ListForm.Display.Manage.Controls._children"); } else { ribbonExtensions = new XmlDocument(); ribbonExtensions.LoadXml(@"<Button Id=""Ribbon.ListItem.Manage.EPKResourcePlanner"" Sequence=""103"" Command=""Ribbon.ListForm.Display.Manage.EPKRPM"" Image16by16=""/_layouts/1033/images/formatmap16x16.png"" Image16by16Top=""-64"" Image16by16Left=""-128"" LabelText=""Resource Planner"" TemplateAlias=""o2"" />"); ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.ListForm.Display.Manage.Controls._children"); } } API.Integration.IntegrationCore core = new API.Integration.IntegrationCore(Web.Site.ID, Web.ID); string Errors = ""; int seq = 130; var commands = new List <IRibbonCommand>(); List <EPMLiveIntegration.IntegrationControl> ics = core.GetItemButtons(ListItem.ParentList.ID, ListItem, out Errors); foreach (EPMLiveIntegration.IntegrationControl ic in ics) { ribbonExtensions = new XmlDocument(); ribbonExtensions.LoadXml(@"<Button Id=""EPMINT." + ic.Control + @"." + (int)ic.Window + @""" Sequence=""" + (seq++).ToString() + @""" Command=""Ribbon.ListForm.Display.Manage.EPMINT"" Image32by32=""/_layouts/15/images/" + ic.Image + @""" LabelText=""" + ic.Title + @""" TemplateAlias=""o1"" />"); ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.ListForm.Display.Manage.Controls._children"); } //=============================================== // register the command at the ribbon. Include the callback to the server // to generate the xml //commands.Add(new SPRibbonCommand("Ribbon.ListForm.Display.Manage.EditItem2", "alert('test');", "true")); var manager = new SPRibbonScriptManager(); var methodInfo = typeof(SPRibbonScriptManager).GetMethod("RegisterInitializeFunction", BindingFlags.Instance | BindingFlags.NonPublic); methodInfo.Invoke(manager, new object[] { Page, "InitPageComponent", "/_layouts/epmlive/WEDispFormPageComponent.js", false, "WEDispFormPageComponent.PageComponent.initialize()" }); manager.RegisterGetCommandsFunction(Page, "getGlobalCommands", commands); manager.RegisterCommandEnabledFunction(Page, "commandEnabled", commands); manager.RegisterHandleCommandFunction(Page, "handleCommand", commands); }
public AddRPTWEBGROUPSUniqueContraints_710(SPWeb spWeb, bool isPfeSite) : base(spWeb, isPfeSite) { }
private static void WriteTableToServer(SPSite spSite, SPWeb spWeb, SqlConnection con) { using (var cmd = new SqlCommand(WorkspaceQueries.EnsureRptWebScript) { Connection = con }) { cmd.ExecuteNonQuery(); } using (var table = new DataTable()) { var column = new DataColumn("RPTWEBGROUPS") { DataType = Type.GetType("System.Guid") }; table.Columns.Add(column); column = new DataColumn("SITEID") { DataType = Type.GetType("System.Guid") }; table.Columns.Add(column); column = new DataColumn("WEBID") { DataType = Type.GetType("System.Guid") }; table.Columns.Add(column); column = new DataColumn("GROUPID") { DataType = Type.GetType("System.Int32") }; table.Columns.Add(column); column = new DataColumn("SECTYPE") { DataType = Type.GetType("System.Int32") }; table.Columns.Add(column); foreach (SPRoleAssignment roleAssignment in spWeb.RoleAssignments) { var type = roleAssignment.Member is SPGroup ? 1 : 0; var found = roleAssignment.RoleDefinitionBindings.Cast <SPRoleDefinition>() .Any(def => (def.BasePermissions & SPBasePermissions.ViewListItems) == SPBasePermissions.ViewListItems); if (found) { table.Rows.Add(new object[] { Guid.NewGuid(), spSite.ID, spWeb.ID, roleAssignment.Member.ID, type }); } } table.Rows.Add(new object[] { Guid.NewGuid(), spSite.ID, spWeb.ID, 999999, 1 }); using (var bulkCopy = new SqlBulkCopy(con)) { bulkCopy.DestinationTableName = "dbo.RPTWEBGROUPS"; bulkCopy.WriteToServer(table); } } }
public AddUpdateMyWorkColumn(SPWeb spWeb, bool isPfeSite) : base(spWeb, isPfeSite) { }
public UnregisterEPMLiveRegitery(SPWeb spWeb, bool isPfeSite) : base(spWeb, isPfeSite) { }
/// <summary> /// Actualiza la relacion automática hacia la lista Correspondencia de Entrada /// </summary> /// <param name="properties"></param> private void EventoActualizarAsociarCorrespondenciaEntrante(SPItemEventProperties properties) { object enRespuestaAAntes = properties.ListItem["En_x0020_respuesta_x0020_a"]; object enRespuestaADespues = properties.AfterProperties["En_x0020_respuesta_x0020_a"]; if (((SPFieldLookupValueCollection)enRespuestaAAntes).Count == 0 && string.IsNullOrEmpty(enRespuestaADespues.ToString())) //Si el campo "En respuesta a" esta vacio { return; } SPSite sitioAdm = null; SPWeb webAdm = null; try { string UrlFPC = ConfigurationManager.AppSettings["UrlFPC"]; SPSecurity.RunWithElevatedPrivileges(delegate() {//Como usuario administrador sitioAdm = new SPSite(UrlFPC); webAdm = sitioAdm.OpenWeb(); }); SPFieldLookupValueCollection enlacesSalidaAntes = (SPFieldLookupValueCollection)enRespuestaAAntes; SPFieldLookupValueCollection enlacesSalidaDespues = new SPFieldLookupValueCollection(enRespuestaADespues.ToString()); SPListItem itemEntrada; SPFieldLookupValueCollection enlacesEntrada; SPFieldLookupValueCollection enlacesEntrada2; #region Definir la lista usada string listaCorreoUsada = ""; if (string.Equals(webAdm.Lists[properties.ListId].Title.Trim(), CORREO_SALIDA_FUNDAPRO, StringComparison.CurrentCultureIgnoreCase)) { listaCorreoUsada = CORREO_ENTRADA_FUNDAPRO; } else if (string.Equals(webAdm.Lists[properties.ListId].Title.Trim(), CORREO_SALIDA_EDUCAPRO, StringComparison.CurrentCultureIgnoreCase)) { listaCorreoUsada = CORREO_ENTRADA_EDUCAPRO; } else if (string.Equals(webAdm.Lists[properties.ListId].Title.Trim(), CORREO_SALIDA_EDUCAPRO_CB, StringComparison.CurrentCultureIgnoreCase)) { listaCorreoUsada = CORREO_ENTRADA_EDUCAPRO_CB; } else if (string.Equals(webAdm.Lists[properties.ListId].Title.Trim(), CORREO_SALIDA_EDUCAPRO_SC, StringComparison.CurrentCultureIgnoreCase)) { listaCorreoUsada = CORREO_ENTRADA_EDUCAPRO_SC; } #endregion #region Eliminar relacion existente sobre este elemento foreach (SPFieldLookupValue enlaceSalidaAntes in enlacesSalidaAntes) { itemEntrada = webAdm.Lists[listaCorreoUsada].Items.GetItemById( enlaceSalidaAntes.LookupId); enlacesEntrada = (SPFieldLookupValueCollection)itemEntrada["Respuesta"]; enlacesEntrada2 = (SPFieldLookupValueCollection)itemEntrada["Respuesta"]; for (int i = 0; i < enlacesEntrada.Count; i++) { if (enlacesEntrada[i].LookupId == properties.ListItemId) { enlacesEntrada2.RemoveAt(i); break; } } itemEntrada["Respuesta"] = enlacesEntrada2; using (DisabledItemEventsScope scope = new DisabledItemEventsScope()) { itemEntrada.SystemUpdate(); } } #endregion #region Crear relacion sobre este elemento foreach (SPFieldLookupValue enlaceSalidaDespues in enlacesSalidaDespues) { itemEntrada = webAdm.Lists[listaCorreoUsada].Items.GetItemById( enlaceSalidaDespues.LookupId); enlacesEntrada = (SPFieldLookupValueCollection)itemEntrada["Respuesta"]; SPFieldLookupValue enlaceEntrada = new SPFieldLookupValue(properties.ListItemId, properties.ListItem["CITE"].ToString()); if (!enlacesEntrada.Contains(enlaceEntrada)) { enlacesEntrada.Add(enlaceEntrada); } itemEntrada["Respuesta"] = enlacesEntrada; using (DisabledItemEventsScope scope = new DisabledItemEventsScope()) { itemEntrada.SystemUpdate(); } } #endregion } finally { if (webAdm != null) { webAdm.Dispose(); } if (sitioAdm != null) { sitioAdm.Dispose(); } } }
public EmailNotificationsUpdateTemplates(SPWeb spWeb, bool isPfeSite) : base(spWeb, isPfeSite) { }
/// <summary> ///统计不同时间的个人用户和团队的新闻源 /// </summary> /// MaxThreadCount最大值是100,即最多只能返回100,默认值是20, /// <returns>返回一维数组,0-个人总数,1-团队总数,2-当日更新,3-本周更新</returns> private int[] GetPublishdNews() { SPSocialFeedOptions socialOptions = new SPSocialFeedOptions(); socialOptions.MaxThreadCount = int.MaxValue; int i = 0; int j = 0; int[] totalTimes = new int[6]; try { string acountName = GetAccountName(); SPSecurity.RunWithElevatedPrivileges(delegate { using (SPSite site = new SPSite(SPContext.Current.Site.ID)) { //this.Controls.Add(new LiteralControl("site:" + site.Url + "<br/>")); using (SPWeb web = site.AllWebs[SPContext.Current.Web.ID]) { //this.Controls.Add(new LiteralControl("web:"+web.Url + "<br/>")); SPServiceContext serviceContext = SPServiceContext.GetContext(site); UserProfileManager upm = new UserProfileManager(serviceContext); string accountName = GetAccountName(); //this.Controls.Add(new LiteralControl("name:" + accountName + "<br/>")); UserProfile u = upm.GetUserProfile(accountName); SPSocialFeedManager feedManager = new SPSocialFeedManager(u, serviceContext); SPSocialFeed feed = feedManager.GetFeedFor(web.Url, socialOptions); SPSocialThread[] threads = feed.Threads; //this.Controls.Add(new LiteralControl("count:" + threads.Length + "<br/>")); foreach (SPSocialThread thread in threads) { //只统计用户发布的新闻源,thread.Attributes.ToString() == "None"表示用户关注了哪些内容,这部分没有统计 if (thread.Attributes.ToString() != "None") { string actorAccount; if (thread.Actors.Length == 1) { actorAccount = thread.Actors[0].AccountName; } else { actorAccount = thread.Actors[1].AccountName; } //string temp = ""; //for (int k = 0; k < thread.Actors.Length; k++) //{ // temp += thread.Actors[k].AccountName+" 、 "; //} //this.Controls.Add(new LiteralControl("actorlength:" + thread.Actors.Length + ";actorAccount:" + temp + "<br/>")); //当前用户 if (actorAccount.ToLower() == accountName.ToLower()) { i = i + 1; } j = j + 1; } } totalTimes[0] = i; //个人总数 //this.Controls.Add(new LiteralControl("my:" + i + "<br/>")); totalTimes[1] = j; //团队总数 //this.Controls.Add(new LiteralControl("all:" + j + "<br/>")); socialOptions = new SPSocialFeedOptions(); socialOptions.MaxThreadCount = int.MaxValue; //this.Controls.Add(new LiteralControl("Now:" + DateTime.Now + "<br/>24小时前:" + DateTime.Now.AddHours(-24) + "<br/>一天前:" + DateTime.Now.AddDays(-1))); socialOptions.NewerThan = DateTime.Now.AddHours(-32);//.Date.AddDays(-1).AddHours(8); feed = feedManager.GetFeedFor(web.Url, socialOptions); threads = feed.Threads; totalTimes[3] = threads.Length;//团队当日更新 i = 0; j = 0; foreach (SPSocialThread thread in threads) { //只统计用户发布的新闻源,thread.Attributes.ToString() == "None"表示用户关注了哪些内容,这部分没有统计 if (thread.Attributes.ToString() != "None") { string actorAccount; if (thread.Actors.Length == 1) { actorAccount = thread.Actors[0].AccountName; } else { actorAccount = thread.Actors[1].AccountName; } //string temp = ""; //for (int k = 0; k < thread.Actors.Length; k++) //{ // temp += thread.Actors[k].AccountName+" 、 "; //} //this.Controls.Add(new LiteralControl("actorlength:" + thread.Actors.Length + ";actorAccount:" + temp + "<br/>")); //当前用户 if (actorAccount.ToLower() == accountName.ToLower()) { i = i + 1; } j = j + 1; } } totalTimes[2] = i;//个人当日更新 socialOptions = new SPSocialFeedOptions(); socialOptions.MaxThreadCount = int.MaxValue; socialOptions.NewerThan = DateTime.Now.Date.AddDays(-6).AddHours(-8);//.AddHours(8); feed = feedManager.GetFeedFor(web.Url, socialOptions); threads = feed.Threads; totalTimes[5] = threads.Length;//团队本周更新 i = 0; j = 0; foreach (SPSocialThread thread in threads) { //只统计用户发布的新闻源,thread.Attributes.ToString() == "None"表示用户关注了哪些内容,这部分没有统计 if (thread.Attributes.ToString() != "None") { string actorAccount; if (thread.Actors.Length == 1) { actorAccount = thread.Actors[0].AccountName; } else { actorAccount = thread.Actors[1].AccountName; } //string temp = ""; //for (int k = 0; k < thread.Actors.Length; k++) //{ // temp += thread.Actors[k].AccountName+" 、 "; //} //this.Controls.Add(new LiteralControl("actorlength:" + thread.Actors.Length + ";actorAccount:" + temp + "<br/>")); //当前用户 if (actorAccount.ToLower() == accountName.ToLower()) { i = i + 1; } j = j + 1; } } totalTimes[4] = i; } } }); } catch (Exception ex) { this.Controls.Add(new LiteralControl(ex.Message)); } return(totalTimes); }
/// <summary> /// Handles the OnRowDataBound event of the gvMyPub control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="GridViewRowEventArgs"/> instance containing the event data.</param> protected void gvMyPub_OnRowDataBound(object sender, GridViewRowEventArgs e) { const string listTitle = "项目文档"; if (e.Row.RowType == DataControlRowType.DataRow)//数据行 { string strIsMatch = DataBinder.Eval(e.Row.DataItem, "IsMatch").ToString(); int proIsMatch = 0; if (strIsMatch != "") { proIsMatch = Convert.ToInt32(strIsMatch); } if (ViewState["gvPubEdit"] != null) { if (e.Row.RowIndex == (int)ViewState["gvPubEdit"]) { var list = (DropDownList)e.Row.Cells[8].Controls[1]; //FindControl("ddProIsMach"); list.SelectedValue = proIsMatch.ToString(); } else { var lbIsMach = (Label)e.Row.Cells[8].Controls[1];// e.Row.FindControl("lbIsMach"); switch (proIsMatch) { case 0: lbIsMach.Text = "拒绝对接"; break; case 1: lbIsMach.Text = "等待对接"; break; default: lbIsMach.Text = "对接完成"; break; } } } else { var lbIsMach = (Label)e.Row.Cells[8].Controls[1];// e.Row.FindControl("lbIsMach"); switch (proIsMatch) { case 0: lbIsMach.Text = "拒绝对接"; break; case 1: lbIsMach.Text = "等待对接"; break; default: lbIsMach.Text = "对接完成"; break; } } e.Row.Attributes.Add("onmouseover", "currentcolor=this.style.backgroundColor;this.style.backgroundColor='#C6E2FF'"); e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=currentcolor;"); //string projName = e.Row.Cells[1].Text;//项目名即子网站名称 string webTitle = DataBinder.Eval(e.Row.DataItem, "PName").ToString(); //int flag = 0; var elink = (HyperLink)e.Row.FindControl("DocManagement"); if (!SPContext.Current.Web.Webs[webTitle].Exists) { elink.Text = "项目未审批"; elink.Enabled = false; } else { SPWeb childweb = SPContext.Current.Web.Webs[webTitle]; if (childweb.Lists.Cast <SPList>().Any(list => list.Title == listTitle)) { string url = SPContext.Current.Web.Webs[webTitle].Lists[listTitle].DefaultViewUrl; elink.NavigateUrl = String.Format(url); } } //保持列不变形 for (int i = 0; i < e.Row.Cells.Count; i++) { //方法一: //e.Row.Cells[i].Text = " " + e.Row.Cells[i].Text + " "; e.Row.Cells[i].Wrap = false; //方法二: //e.Row.Cells[i].Text = "<nobr> " + e.Row.Cells[i].Text + " </nobr>"; } } }
static void Track(string url, string SPListURLDir, string SPListItemId, string Folder, HttpContext context) { SPUserToken userToken = null; SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(url)) { using (SPWeb web = site.OpenWeb()) { string body; using (var reader = new StreamReader(context.Request.InputStream)) body = reader.ReadToEnd(); var fileData = new JavaScriptSerializer().Deserialize <Dictionary <string, object> >(body); try { var userList = (System.Collections.ArrayList)fileData["users"]; var userID = Int32.Parse(userList[0].ToString()); var users = web.AllUsers; for (int i = 0; i < users.Count; i++) { if (users[i].ID == userID) { userToken = users[i].UserToken; break; } } if (userToken == null) { userToken = web.AllUsers[0].UserToken; } } catch (Exception ex) { Log.LogError(ex.Message); userToken = web.AllUsers[0].UserToken; } try { SPSite s = new SPSite(url, userToken); SPWeb w = s.OpenWeb(); SPList list = w.GetList(SPListURLDir); SPListItem item = list.GetItemById(Int32.Parse(SPListItemId)); //save file to SharePoint if ((int)fileData["status"] == 2) { var req = (string)fileData["url"]; var replaceExistingFiles = true; var fileName = item.File.Name; w.AllowUnsafeUpdates = true; //for list update in SharePoint necessary AllowUnsafeUpdates = true w.Update(); byte[] fileDataArr = null; using (var wc = new WebClient()) fileDataArr = wc.DownloadData(req); if (Folder != "") { SPFolder folder = w.GetFolder(Folder); folder.Files.Add(fileName, fileDataArr, replaceExistingFiles); folder.Update(); } else { list.RootFolder.Files.Add(fileName, fileDataArr, replaceExistingFiles); list.Update(); } w.AllowUnsafeUpdates = false; w.Update(); } context.Response.Write("{\"error\":0}"); } catch (Exception ex) { Log.LogError(ex.Message); } } } }); }
/// <summary> /// Crea una relacion automática hacia la lista Correspondencia de Entrada /// </summary> /// <param name="properties"></param> private void EventoAsociarCorrespondenciaEntrante(SPItemEventProperties properties) { SPSite sitioAdm = null; SPWeb webAdm = null; try { string UrlFPC = ConfigurationManager.AppSettings["UrlFPC"]; SPSecurity.RunWithElevatedPrivileges(delegate() {//Como usuario administrador sitioAdm = new SPSite(UrlFPC); webAdm = sitioAdm.OpenWeb(); }); SPListItem itemSalida = properties.ListItem; SPListItem itemEntrada; SPFieldLookupValueCollection enlacesSalida = (SPFieldLookupValueCollection)itemSalida["En respuesta a"]; SPFieldLookupValueCollection enlacesEntrada; #region Definir la lista usada string listaCorreoUsada = ""; if (string.Equals(webAdm.Lists[properties.ListId].Title.Trim(), CORREO_SALIDA_FUNDAPRO, StringComparison.CurrentCultureIgnoreCase)) { listaCorreoUsada = CORREO_ENTRADA_FUNDAPRO; } else if (string.Equals(webAdm.Lists[properties.ListId].Title.Trim(), CORREO_SALIDA_EDUCAPRO, StringComparison.CurrentCultureIgnoreCase)) { listaCorreoUsada = CORREO_ENTRADA_EDUCAPRO; } else if (string.Equals(webAdm.Lists[properties.ListId].Title.Trim(), CORREO_SALIDA_EDUCAPRO_CB, StringComparison.CurrentCultureIgnoreCase)) { listaCorreoUsada = CORREO_ENTRADA_EDUCAPRO_CB; } else if (string.Equals(webAdm.Lists[properties.ListId].Title.Trim(), CORREO_SALIDA_EDUCAPRO_SC, StringComparison.CurrentCultureIgnoreCase)) { listaCorreoUsada = CORREO_ENTRADA_EDUCAPRO_SC; } #endregion #region Crear relacion sobre este elemento foreach (SPFieldLookupValue enlaceSalida in enlacesSalida) { itemEntrada = webAdm.Lists[listaCorreoUsada].Items.GetItemById( enlaceSalida.LookupId); enlacesEntrada = (SPFieldLookupValueCollection)itemEntrada["Respuesta"]; SPFieldLookupValue enlaceEntrada = new SPFieldLookupValue(itemSalida.ID, itemSalida["CITE"].ToString()); if (!enlacesEntrada.Contains(enlaceEntrada)) { enlacesEntrada.Add(enlaceEntrada); } itemEntrada["Respuesta"] = enlacesEntrada; using (DisabledItemEventsScope scope = new DisabledItemEventsScope()) { itemEntrada.SystemUpdate(); } } #endregion } finally { if (webAdm != null) { webAdm.Dispose(); } if (sitioAdm != null) { sitioAdm.Dispose(); } } }
private ListItem FillApprovalAuthority(SPWeb oSPWeb, string departmentName) { ListItem hodLI = null; try { var currentUser = oSPWeb.CurrentUser; string currentUserEmail = null; string currentUserRole = null; if (currentUser != null) { currentUserEmail = currentUser.Email; } string listName = "Department"; // Fetch the List SPList spList = oSPWeb.GetList(string.Format("{0}/Lists/{1}/AllItems.aspx", oSPWeb.Url, listName)); SPQuery query = new SPQuery(); SPListItemCollection spListItems; // Include only the fields you will use. query.ViewFields = "<FieldRef Name='HOD'/><FieldRef Name='HODEmail'/><FieldRef Name='DepartmentDescription'/>"; query.ViewFieldsOnly = true; StringBuilder sb = new StringBuilder(); sb.Append("<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + departmentName + "</Value></Eq></Where>"); query.Query = sb.ToString(); spListItems = spList.GetItems(query); List <ListItem> lstItems = new List <ListItem>(); foreach (SPListItem spListItem in spListItems) { string email = Convert.ToString(spListItem["HODEmail"]); string name = Convert.ToString(spListItem["HOD"]); string description = Convert.ToString(spListItem["DepartmentDescription"]); if (currentUserEmail.Equals(email, StringComparison.OrdinalIgnoreCase)) { currentUserRole = description; } //string title = name + " (" + description + ") "; string title = name; if (!String.IsNullOrEmpty(title) && !String.IsNullOrEmpty(email)) { lstItems.Add(new ListItem(title, email)); if (description.Equals("HOD", StringComparison.OrdinalIgnoreCase)) { hodLI = new ListItem(); hodLI.Text = title; hodLI.Value = email; } } } if (currentUserRole != null && (currentUserRole.Equals("Unit Manager", StringComparison.OrdinalIgnoreCase) || currentUserRole.Equals("HOD", StringComparison.OrdinalIgnoreCase))) { this.approvalAuthority_ddl.Items.Add(hodLI); } else { foreach (var item in lstItems) { this.approvalAuthority_ddl.Items.Add(new ListItem(item.Text, item.Value)); } } this.approvalAuthority_ddl.Items.Insert(0, new ListItem("Please Select", "0")); return(hodLI); } catch (Exception ex) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("SL.FG.FFL(MSARecommendationForm->FillApprovalAuthority)", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace); } return(hodLI); }
private void StatisticList(SPUser logUser) { string lstNames = WebPartObj.ListName; if (lstNames == "") { kpiDiv.InnerHtml = "尚未指定任何列表名称进行数据统计!"; } else { string[] lstName = WebPartObj.ListName.Split(';'); SPQuery oQuery; SPList sList; int[] itmCounts = new int[6]; DataTable datatable = newTable(); SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(SPContext.Current.Site.ID)) { using (SPWeb web = site.AllWebs[SPContext.Current.Web.ID]) { string myac = ""; string lName = ""; //设置sharepoint时间格式 SPTimeZone timeZone = web.RegionalSettings.TimeZone; string listsHtml = "<fieldset style='border: 1px dotted #ff4500; padding: 5px;'><legend style='text-align:center;background-color: #ff4500; color:#f5fffa;padding:5px'>活动量化明细表</legend><table class='mytable'>"; listsHtml += "<tr><th rowspan='2'>KPI</th><th rowspan='2'>由我发布</th><th colspan='2'>今日更新</th><th colspan='2'>本周更新</th><th rowspan='2'>站内总数</th></tr>"; listsHtml += "<tr><td>本人</td><td>本站</td><td>本人</td><td>本站</td></tr>"; itmCounts = NewsCount;//微博 listsHtml += "<tr>"; listsHtml += "<th><a href='" + web.Url + "/newsfeed.aspx' target='_blank'>微 博</a></th>"; listsHtml += "<td>" + itmCounts[0].ToString() + "</td>"; listsHtml += "<td>" + itmCounts[2].ToString() + "</td>"; listsHtml += "<td>" + itmCounts[3].ToString() + "</td>"; listsHtml += "<td>" + itmCounts[4].ToString() + "</td>"; listsHtml += "<td>" + itmCounts[5].ToString() + "</td>"; listsHtml += "<td>" + itmCounts[1].ToString() + "</td>"; listsHtml += "</tr>"; datatable.Rows.Add("微 博", itmCounts[0], itmCounts[1]); if (itmCounts[4] == 0) { if (myac != "") { myac += "、"; } myac += "“<b><a href='" + SPContext.Current.Web.Url + "/newsfeed.aspx' target='_blank'>微 博</a></b>”"; } foreach (string mList in lstName) { try { if (mList == "Posts" && WebPartObj.SubWebUrl != "")//统计备忘录 { SPWeb subWeb = web.Webs[WebPartObj.SubWebUrl]; sList = subWeb.Lists.TryGetList(mList); } else { sList = web.Lists.TryGetList(mList); } lName = "<a href='" + sList.DefaultViewUrl + "' target='_blank'>" + mList + "</a>"; if (mList == "Posts") { lName = "<a href='" + sList.DefaultViewUrl + "' target='_blank'>备忘录</a>"; } if (mList == "讨论列表") { lName = "<a href='" + sList.DefaultViewUrl + "' target='_blank'>讨 论</a>"; } if (mList == "文档") { lName = "<a href='" + sList.DefaultViewUrl + "' target='_blank'>文 档</a>"; } oQuery = new SPQuery(); oQuery.ViewAttributes = "Scope='RecursiveAll'"; oQuery.Query = "<Where><Eq><FieldRef Name='Author'/><Value Type='Text'>" + logUser.Name + "</Value></Eq></Where>"; SPListItemCollection lstItems = sList.GetItems(oQuery); itmCounts[0] = lstItems.Count; //个人 itmCounts[1] = sList.ItemCount; //全部 /***********今日更新******************/ oQuery = new SPQuery(); DateTime currentDate = DateTime.Now; DateTime yesterdayDate = currentDate.AddDays(-1); DateTime yesterdayUTCDate = timeZone.LocalTimeToUTC(yesterdayDate); string yesterdayUTCDateString = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Parse(yesterdayUTCDate.ToString())); oQuery.ViewAttributes = "Scope='RecursiveAll'"; oQuery.Query = "<Where><And><Eq><FieldRef Name='Author'/><Value Type='Text'>" + logUser.Name + "</Value></Eq><Geq><FieldRef Name='Created'/><Value Type='DateTime'>" + yesterdayUTCDateString + "</Value></Geq></And></Where>"; lstItems = sList.GetItems(oQuery); itmCounts[2] = lstItems.Count;//个人当日更新 oQuery = new SPQuery(); oQuery.ViewAttributes = "Scope='RecursiveAll'"; oQuery.Query = "<Where><Geq><FieldRef Name='Created'/><Value Type='DateTime'>" + yesterdayUTCDateString + "</Value></Geq></Where>"; lstItems = sList.GetItems(oQuery); itmCounts[3] = lstItems.Count;//站内当日更新 /***********本周更新******************/ DateTime lastWeekDate = currentDate.AddDays(-7); DateTime lastWeekUTCDate = timeZone.LocalTimeToUTC(lastWeekDate); string lastWeekUTCDateString = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Parse(lastWeekUTCDate.ToString())); oQuery = new SPQuery(); oQuery.ViewAttributes = "Scope='RecursiveAll'"; oQuery.Query = "<Where><And><Eq><FieldRef Name='Author'/><Value Type='Text'>" + logUser.Name + "</Value></Eq><Geq><FieldRef Name='Created'/><Value Type='DateTime'>" + lastWeekUTCDateString + "</Value></Geq></And></Where>"; lstItems = sList.GetItems(oQuery); itmCounts[4] = lstItems.Count;//个人本周更新 oQuery = new SPQuery(); oQuery.ViewAttributes = "Scope='RecursiveAll'"; oQuery.Query = "<Where><Geq><FieldRef Name='Created'/><Value Type='DateTime'>" + lastWeekUTCDateString + "</Value></Geq></Where>"; lstItems = sList.GetItems(oQuery); itmCounts[5] = lstItems.Count;//站内本周更新 listsHtml += "<tr>"; listsHtml += "<th>" + lName + "</th>"; listsHtml += "<td>" + itmCounts[0].ToString() + "</td>"; listsHtml += "<td>" + itmCounts[2].ToString() + "</td>"; listsHtml += "<td>" + itmCounts[3].ToString() + "</td>"; listsHtml += "<td>" + itmCounts[4].ToString() + "</td>"; listsHtml += "<td>" + itmCounts[5].ToString() + "</td>"; listsHtml += "<td>" + itmCounts[1].ToString() + "</td>"; listsHtml += "</tr>"; datatable.Rows.Add(lName, itmCounts[0], itmCounts[1]); if (itmCounts[4] == 0) { if (myac != "") { myac += "、"; } myac += "“<b>" + lName + "</b>”"; } } catch { } } listsHtml += "</table></fieldset>"; if (myac != "") { listsHtml = "<div class='kpidiv'>亲,你好。<br/>系统发现你近一周都没有参与发布过:" + myac + ",<br/>快快参与站内活动赢取积分赶超其它小伙伴吧!</div>" + listsHtml; } kpiDiv.InnerHtml = listsHtml; if (datatable.Rows.Count > 0) { } } } }); } }
static void Main(string[] args) { SPSite sitio = null; SPWeb web = null; try { string UrlFPC = ConfigurationManager.AppSettings["UrlFPC"]; int contador = 0; sitio = new SPSite(UrlFPC); web = sitio.OpenWeb(); SPList listaFundapro = web.Lists["Correspondencia de Entrada Funda-Pro"]; SPList listaEducapro = web.Lists["Correspondencia de Entrada Educa-Pro"]; SPList listaEducaproCB = web.Lists["Correspondencia de Entrada Educa-Pro (CB)"]; SPList listaEducaproSC = web.Lists["Correspondencia de Entrada Educa-Pro (SC)"]; SPList listaParametros = web.Lists["Parámetros Globales"]; #region Recuperar parametro global SPListItemCollection itemsParametros = listaParametros.Items; foreach (SPListItem item in itemsParametros) { if (string.Equals(item.Title.Trim(), PARAMETRO, StringComparison.CurrentCultureIgnoreCase)) { tiempoObsoleto = Convert.ToInt32(item["Valor parámetro"].ToString()); break; } } #endregion #region Consulta SP (Query) SPQuery consulta = new SPQuery(); consulta.Query = "<Where><Or><Eq><FieldRef Name='Estado_x0020_corr_x002e_' />" + "<Value Type='Text'>ACTIVA</Value></Eq><Eq>" + "<FieldRef Name='Estado_x0020_corr_x002e_' />" + "<Value Type='Text'>PASIVA</Value>" + "</Eq></Or></Where>"; #endregion #region Fundapro SPListItemCollection itemsFundapro = listaFundapro.GetItems(consulta); foreach (SPListItem item in itemsFundapro) { if (EsItemObsoleto(item)) { item["Estado corr."] = ESTADO; using (DisabledItemEventsScope scope = new DisabledItemEventsScope()) { item.SystemUpdate(); } contador++; } } Console.WriteLine(contador.ToString() + " item(s) obsoleto(s) FUNDAPRO."); contador = 0; #endregion #region Educapro La Paz SPListItemCollection itemsEducapro = listaEducapro.GetItems(consulta); foreach (SPListItem item in itemsEducapro) //La Paz { if (EsItemObsoleto(item)) { item["Estado corr."] = ESTADO; using (DisabledItemEventsScope scope = new DisabledItemEventsScope()) { item.SystemUpdate(); } } } Console.WriteLine(contador.ToString() + " item(s) obsoleto(s) EDUCAPRO LA PAZ."); contador = 0; #endregion #region Educapro Cochabamba SPListItemCollection itemsEducaproCB = listaEducaproCB.GetItems(consulta); foreach (SPListItem item in itemsEducaproCB) //Cochabamba { if (EsItemObsoleto(item)) { item["Estado corr."] = ESTADO; using (DisabledItemEventsScope scope = new DisabledItemEventsScope()) { item.SystemUpdate(); } } } Console.WriteLine(contador.ToString() + " item(s) obsoleto(s) EDUCAPRO COCHABAMBA."); contador = 0; #endregion #region Educapro Santa Cruz SPListItemCollection itemsEducaproSC = listaEducaproSC.GetItems(consulta); foreach (SPListItem item in itemsEducaproSC) //Santa Cruz { if (EsItemObsoleto(item)) { item["Estado corr."] = ESTADO; using (DisabledItemEventsScope scope = new DisabledItemEventsScope()) { item.SystemUpdate(); } } } Console.WriteLine(contador.ToString() + " item(s) obsoleto(s) EDUCAPRO SANTA CRUZ."); contador = 0; #endregion } catch (Exception ex) { Console.WriteLine("ERROR: " + ex.Message); } finally { if (web != null) { web.Dispose(); } if (sitio != null) { sitio.Dispose(); } } }
private bool SaveRecommendation(string currentOperation) { bool isSaved = false; try { using (SPSite oSPsite = new SPSite(SPContext.Current.Web.Url)) { using (SPWeb oSPWeb = oSPsite.OpenWeb()) { if (!String.IsNullOrEmpty(this.hdnRecommendationId.Value)) { int recommendationId = Convert.ToInt32(this.hdnRecommendationId.Value); string listName = "MSARecommendation"; // Fetch the List SPList spList = oSPWeb.GetList(string.Format("{0}/Lists/{1}/AllItems.aspx", oSPWeb.Url, listName)); SPListItem spListItem = spList.GetItemById(recommendationId); if (spListItem != null) { string closureJustification = this.closureJustification_ta.Value; string closureDateStr = this.closureDate_dtc.SelectedDate != null?Convert.ToString(this.closureDate_dtc.SelectedDate) : null; string approvedBy = null; if (approvalAuthority_ddl != null && approvalAuthority_ddl.SelectedIndex > 0) { approvedBy = approvalAuthority_ddl.SelectedValue; } if (!String.IsNullOrEmpty(closureJustification)) { spListItem["LastStatement"] = closureJustification; StringBuilder sb = new StringBuilder(); if (!String.IsNullOrEmpty(closureDateStr)) { DateTime date; bool bValid = DateTime.TryParse(closureDateStr, new CultureInfo("en-GB"), DateTimeStyles.AssumeLocal, out date); if (bValid) { closureDateStr = Convert.ToString(date); } } string previousCJ = Convert.ToString(spListItem["ClosureJustification"]); SPUser spUser = oSPWeb.CurrentUser; if (spUser != null) { string responsiblePerson = spUser.Name; string guessMePattern = "*|~^|^~|*"; sb.Append("<p class='dataItem_by'>") .Append(responsiblePerson) .Append("<span class='dataItem_by_date'>") .Append(" (") .Append(closureDateStr) .Append(") ") .Append("</span>") .Append("</p>") .Append("<p class='dataItem'>") .Append(Convert.ToString(closureJustification)) .Append("</p>") .Append(guessMePattern) .Append(previousCJ); spListItem["ClosureJustification"] = sb.ToString(); } } if (!String.IsNullOrEmpty(closureDateStr)) { DateTime date; bool bValid = DateTime.TryParse(closureDateStr, new CultureInfo("en-GB"), DateTimeStyles.AssumeLocal, out date); if (bValid) { spListItem["ClosureDate"] = date; } else { spListItem["ClosureDate"] = Convert.ToDateTime(closureDateStr); } } if (!String.IsNullOrEmpty(approvedBy)) { spListItem["ApprovedBy"] = approvedBy; } else { message_div.InnerHtml = "Approving Authority not available!!! Please Contact the administrator."; return(false); } if (!String.IsNullOrEmpty(this.hdnFilesNames.Value)) { var fileNames = hdnFilesNames.Value.Split('~'); foreach (var item in fileNames) { if (!String.IsNullOrEmpty(item)) { spListItem.Attachments.Delete(item); } } } if (this.fileUploadControl.HasFiles) { foreach (var uploadedFile in fileUploadControl.PostedFiles) { int maxFileLimit = 20971520; if (uploadedFile.ContentLength > maxFileLimit) { message_div.InnerHtml = "Attachment file size limit is 20MB. Please reattach files."; isSaved = false; return(isSaved); } } foreach (var uploadedFile in fileUploadControl.PostedFiles) { Stream fs = uploadedFile.InputStream; byte[] _bytes = new byte[fs.Length]; fs.Position = 0; fs.Read(_bytes, 0, (int)fs.Length); fs.Close(); fs.Dispose(); spListItem.Attachments.Add(uploadedFile.FileName, _bytes); } } //Decide values on the basis of operation string recommendationLink = Utility.GetRedirectUrl("MSARecommendationFormLink"); StringBuilder linkSB = new StringBuilder(); linkSB.Append(recommendationLink) .Append("?MSARID=") .Append(spListItem.ID); string subject = ""; string body = ""; if (currentOperation.Equals("Send", StringComparison.OrdinalIgnoreCase)) { subject = Utility.GetValueByKey("From_ResponsiblePerson_To_HOD_RE_Subject"); body = Utility.GetValueByKey("From_ResponsiblePerson_To_HOD_RE"); body = body.Replace("~|~", linkSB.ToString()); spListItem["Status"] = "In Progress"; } else if (currentOperation.Equals("Approve", StringComparison.OrdinalIgnoreCase)) { subject = Utility.GetValueByKey("From_HOD_To_ResponsiblePerson_Approve_RE_Subject"); body = Utility.GetValueByKey("From_HOD_To_ResponsiblePerson_Approve_RE"); body = body.Replace("~|~", linkSB.ToString()); spListItem["Status"] = "Completed"; } else if (currentOperation.Equals("Reject", StringComparison.OrdinalIgnoreCase)) { subject = Utility.GetValueByKey("From_HOD_To_ResponsiblePerson_Reject_RE_Subject"); body = Utility.GetValueByKey("From_HOD_To_ResponsiblePerson_Reject_RE"); body = body.Replace("~|~", linkSB.ToString()); } if (!currentOperation.Equals("Save", StringComparison.OrdinalIgnoreCase)) { if (String.IsNullOrEmpty(body)) { body = linkSB.ToString(); } Message message = new Message(); SPUser spCurrentUser = oSPWeb.CurrentUser; string approvingAuthorityEmail = Convert.ToString(spListItem["ApprovedBy"]); SPUser approvingAuthority = null; if (!String.IsNullOrEmpty(approvingAuthorityEmail)) { approvingAuthority = Utility.GetUser(oSPWeb, null, approvingAuthorityEmail); if (approvingAuthority != null) { if (spCurrentUser.Email.Equals(approvingAuthorityEmail, StringComparison.OrdinalIgnoreCase)) { SPUser responsiblePerson = Utility.GetUser(oSPWeb, Convert.ToString(spListItem["ResponsiblePerson"])); if (responsiblePerson != null) { spListItem["Assignee"] = Convert.ToString(spListItem["ResponsiblePerson"]); spListItem["AssigneeEmail"] = responsiblePerson.Email; message.To = responsiblePerson.Email; message.From = approvingAuthorityEmail; message.Subject = subject; message.Body = body; } } else { spListItem["Assignee"] = approvingAuthority.LoginName; spListItem["AssigneeEmail"] = approvingAuthority.Email; message.To = approvingAuthority.Email; message.From = spCurrentUser.Email; message.Subject = subject; message.Body = body; } oSPWeb.AllowUnsafeUpdates = true; spListItem.Update(); oSPWeb.AllowUnsafeUpdates = false; isSaved = Email.SendEmail(message); if (!isSaved) { message_div.InnerHtml = "MSA Recommendation Saved Successfully but Email Sending Failed, Please Contact your Administrator."; } } } if (approvingAuthority == null) { message_div.InnerHtml = "Information of Approving Authoirty is incomplete or needs more permission. Please Contact the Administrator!"; isSaved = false; } } else { oSPWeb.AllowUnsafeUpdates = true; spListItem.Update(); oSPWeb.AllowUnsafeUpdates = false; isSaved = true; } } } } } } catch (Exception ex) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("SL.FG.FFL(MSARecommendation->SaveRecommendation)", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace); message_div.InnerHtml = "Something went wrong!!! Please Contact the administrator."; DisableControls(); } return(isSaved); }