public static RibbonProperties GetRibbonProps(SPList list) { RibbonProperties rp = new RibbonProperties(); SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(SPContext.Current.Web.Url)) { using (SPWeb web = site.OpenWeb()) { GridGanttSettings gSettings = GetGridGanttSettings(list); string pubPC = EPMLiveCore.CoreFunctions.getLockConfigSetting(web, "EPMLivePublisherProjectCenter", false); string pubTC = EPMLiveCore.CoreFunctions.getLockConfigSetting(web, "EPMLivePublisherTaskCenter", false); bool foundmpp = false; try { SPDocumentLibrary lib = (SPDocumentLibrary)web.Lists["Project Schedules"]; if (lib != null) { if (lib.ContentTypesEnabled) { foreach (SPContentType ct in lib.ContentTypes) { string template = ct.DocumentTemplateUrl; if (template.Substring(template.Length - 3, 3) == "mpp") { foundmpp = true; break; } } } else { string template = lib.DocumentTemplateUrl; if (template.Substring(template.Length - 3, 3) == "mpp") { foundmpp = true; } } } } catch { } if (gSettings.BuildTeam && list.Fields.GetFieldByInternalName("AssignedTo") != null) { if (list.DoesUserHavePermissions(SPBasePermissions.EditListItems)) { rp.bBuildTeam = true; } } bool.TryParse(EPMLiveCore.CoreFunctions.getConfigSetting(web, "EPMLiveDisablePublishing"), out rp.bDisableProject); bool.TryParse(EPMLiveCore.CoreFunctions.getConfigSetting(web, "EPMLiveDisablePlanners"), out rp.bDisablePlan); if (site.Features[new Guid("158c5682-d839-4248-b780-82b4710ee152")] != null) { ArrayList arr = new ArrayList(EPMLiveCore.CoreFunctions.getConfigSetting(site.RootWeb, "EPKLists").ToLower().Split(',')); if (arr.Contains(list.Title.ToLower())) { string menus = ""; menus = EPMLiveCore.CoreFunctions.getConfigSetting(site.RootWeb, "EPK" + list.Title.Replace(" ", "") + "_menus"); if (menus == "") { menus = EPMLiveCore.CoreFunctions.getConfigSetting(site.RootWeb, "EPKMenus"); } rp.aEPKButtons = new ArrayList(menus.Split('|')); string noactivex = ""; noactivex = EPMLiveCore.CoreFunctions.getConfigSetting(site.RootWeb, "EPK" + list.Title.Replace(" ", "") + "_nonactivexs"); if (noactivex == "") { noactivex = EPMLiveCore.CoreFunctions.getConfigSetting(site.RootWeb, "epknonactivexs"); } rp.aEPKActivex = new ArrayList(noactivex.Split('|')); } } } } }); return(rp); }
protected void Button2_Click(object sender, EventArgs e) { try { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(SPContext.Current.Web.Url)) { using (SPWeb web = site.OpenWeb()) { SPList list = web.Lists.TryGetList("Candidates"); if (list != null) { SPListItem NewItem = list.Items.Add(); { SPDocumentLibrary documentLib = web.Lists["Resumes"] as SPDocumentLibrary; Stream fStream = FileUpload1.PostedFile.InputStream; byte[] _byteArray = new byte[fStream.Length]; fStream.Read(_byteArray, 0, (int)fStream.Length); fStream.Close(); web.AllowUnsafeUpdates = true; string filepath = FileUpload1.FileName.Split(',')[0]; string _fileUrl = documentLib.RootFolder.Url + "/" + FileUpload1.FileName; string candidateResumeLink = documentLib.RootFolder.ServerRelativeUrl + "/" + FileUpload1.FileName; bool IsOverwriteFile = true; SPFile file = documentLib.RootFolder.Files.Add(_fileUrl, _byteArray, IsOverwriteFile); SPListItem item = file.Item; item["Title"] = FileUpload1.FileName.Split('.')[0]; item["Name"] = FileUpload1.FileName; item.Update(); file.Update(); string clientname = lookup(DropDownList1.SelectedValue); NewItem["VacancyName"] = new SPFieldLookupValue(Convert.ToInt32(clientname), DropDownList1.SelectedValue.ToString()); NewItem["CandidateName"] = txtname.Text; NewItem["Domain"] = drpdomain.SelectedItem.ToString(); NewItem["Experience"] = txtexperience.Text; NewItem["SkillSets"] = txtskillset.Text; NewItem["CurrentCTC"] = txtcrtctc.Text; NewItem["ExpectedCTC"] = txtexctc.Text; NewItem["Email"] = txtemail.Text; NewItem["ContactNo"] = txtcontact.Text; NewItem["UploadedResume"] = FileUpload1.FileName; NewItem["Source"] = txtSource.Text; NewItem["NoticePeriod"] = txtNotice.Text; NewItem.Update(); web.AllowUnsafeUpdates = false; Page.Response.Redirect(SPContext.Current.Site.Url + MainSite, false); } } } } }); } catch (Exception ex) { //Alert.Text = ex.Message.ToString(); } }
public int SelectOnlineVersions() { int result = -1; 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"); } SPQuery query = new SPQuery(); query.Query = @"<Where><IsNotNull><FieldRef Name=""Title"" /></IsNotNull></Where>"; query.ViewFields = @"<FieldRef Name=""Title"" />"; query.ViewAttributes = @"Scope=""Recursive"""; result = pages.GetItems(query).Count; } } } catch (Exception ex) { Logger.WriteLog(Logger.Category.Unexpected, ex.Source, ex.Message); result = -1; } }); return(result); }
public static void Main(string[] args) { string webApplicationUrl = args[0]; bool isSyntaxOk = true; for (int i = 1; i < args.Length; i++) { if (!Languages.Instance.AllLanguages.Contains(args[i])) { isSyntaxOk = false; break; } } if (isSyntaxOk) { try { using (var currentSite = new SPSite(webApplicationUrl)) using (SPWeb web = currentSite.OpenWeb()) { SPList pagesToParseUrlList = web.GetList("/Lists/PagesToUpdateForTranslation"); SPList extractorTranslationsList = web.GetList("/Lists/ExtractorTranslations"); if (pagesToParseUrlList.Fields.ContainsField("Pages")) { if (pagesToParseUrlList.Items.Count > 0) { int initExtractorTranslationsCount = extractorTranslationsList.Items.Count; Console.Write("Alphamosaik Translations Extractor process begins..."); string defaultLang = args[1]; var languageDisplayed = new List <string>(); for (int i = 2; i < args.Length; i++) { languageDisplayed.Add(args[i]); } SPSecurity.RunWithElevatedPrivileges(delegate { foreach (SPListItem currentUrl in pagesToParseUrlList.Items) { foreach (string languageCode in languageDisplayed) { if (defaultLang != languageCode) { try { int beforeThisAddCount = extractorTranslationsList.Items.Count; Console.WriteLine(); Console.WriteLine(currentUrl["Pages"] + " is being parsed for language: \"" + languageCode + "\" ..."); WebRequest request = WebRequest.Create(currentUrl["Pages"] + "?SPS_Trans_Code=Translation_Extractor&SPS_Extractor_Status=" + currentUrl.ID + "&SPSLanguage=" + languageCode); request.UseDefaultCredentials = true; request.Timeout = 300000; Console.WriteLine(currentUrl["Pages"] + "(language:\"" + languageCode + "\") is treated : " + (extractorTranslationsList.Items.Count - beforeThisAddCount) + " phrases added."); } catch { Console.WriteLine(currentUrl["Pages"] + " is not available."); } } } } }); Console.WriteLine(); Console.WriteLine("Process completed : " + pagesToParseUrlList.Items.Count + " pages treated."); Console.WriteLine((extractorTranslationsList.Items.Count - initExtractorTranslationsCount) + " phrases added to the \"ExtractorTranslations\" list."); } } } } catch (Exception) { Console.WriteLine("Error : please verify the url or the language codes in parameters."); Console.WriteLine("Syntax : TranslationsExtractor.exe <SiteCollectionRootAbsoluteUrl> <DefaultLanguageCode> <Language1Code> [<Language2Code>] [<Language3Code>]"); } } else { Console.WriteLine("Syntax error : please verify the language codes in parameters."); Console.WriteLine("Syntax : TranslationsExtractor.exe <SiteCollectionRootAbsoluteUrl> <DefaultLanguageCode> <Language1Code> [<Language2Code>] [<Language3Code>]"); } }
public static string UpdateFiles(SPWeb web, string folderName, List <SPFieldValue> fields, List <Attachment> addFiles, List <Attachment> deleteFiles) { string message = "ok"; try { Guid siteId = web.Site.ID; SPSecurity.RunWithElevatedPrivileges(delegate { using (SPSite site = new SPSite(siteId)) { using (SPWeb Web = site.OpenWeb()) { SPList list; foreach (Attachment attachment in deleteFiles) { list = Web.Lists[new Guid(attachment.LookupList)]; Web.AllowUnsafeUpdates = true; SPFolder folder = Web.GetFolder(list.RootFolder + folderName); if (!folder.Exists) { list.RootFolder.Files[attachment.FileName].Delete(); } else { folder.Files[attachment.FileName].Delete(); } list.RootFolder.Update(); Web.AllowUnsafeUpdates = false; } foreach (Attachment attachment in addFiles) { list = web.Lists[new Guid(attachment.LookupList)]; byte[] buffer = Convert.FromBase64String(attachment.Content); if (!string.IsNullOrEmpty(attachment.FileName)) { web.AllowUnsafeUpdates = true; SPFile file = null; if (folderName == "") { file = list.RootFolder.Files.Add(attachment.FileName, buffer, false); } else { SPFolder folderWithName = web.GetFolder(list.RootFolder + "/" + folderName); if (!folderWithName.Exists) { SPListItem item = list.Folders.Add(list.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, folderName); item.Update(); file = item.Folder.Files.Add(attachment.FileName, buffer, false); } else { file = folderWithName.Files.Add(attachment.FileName, buffer, false); } } file.Item["Title"] = attachment.Title; file.Item.Update(); web.AllowUnsafeUpdates = false; SPFieldValue fileFieldValue = new SPFieldValue { InternalName = attachment.InternalName, Type = "File", LookupList = attachment.LookupList, value = file.Item.ID.ToString() }; fields.Add(fileFieldValue); } } } } }); } catch (Exception exception) { message = exception.Message; } return(message); }
public override bool Perform() { Guid webAppId = Web.Site.WebApplication.Id; try { SPSecurity.RunWithElevatedPrivileges(() => { LogMessage("Connecting to the database . . .", 2); string epmLiveCnStr = CoreFunctions.getConnectionString(webAppId); using (var epmLiveCn = new SqlConnection(epmLiveCnStr)) { epmLiveCn.Open(); #region ViewCode epmLiveCn.ExecuteNonQuery($@"ALTER VIEW [dbo].[vwMeta] AS SELECT dbo.TSTIMESHEET.USERNAME AS Username, dbo.TSTIMESHEET.RESOURCENAME AS [Resource Name], dbo.TSUSER.USER_ID AS SharePointAccountID, dbo.TSITEM.LIST_UID, dbo.TSITEM.ITEM_ID, dbo.TSITEM.TS_ITEM_UID AS [Item UID], dbo.TSITEM.TITLE AS [Item Name], dbo.TSITEM.PROJECT AS Project, dbo.TSITEM.PROJECT_ID AS ProjectID, COALESCE (dbo.TSMETA.ListName + '_' + dbo.TSMETA.ColumnName, 'TempColumn') AS ColumnName, dbo.TSMETA.DisplayName, dbo.TSMETA.ColumnValue, dbo.TSITEM.ITEM_TYPE AS [Item Type], dbo.TSITEM.TS_UID AS [Timesheet UID], dbo.TSPERIOD.PERIOD_ID AS [Period Id], dbo.TSPERIOD.SITE_ID, dbo.TSITEM.LIST AS List, dbo.TSITEMHOURS.TS_ITEM_DATE AS Date, dbo.TSITEMHOURS.TS_ITEM_HOURS AS Hours, dbo.TSITEMHOURS.TS_ITEM_TYPE_ID AS [Type Id], dbo.TSTYPE.TSTYPE_NAME AS [Type Name], dbo.TSPERIOD.PERIOD_START AS [Period Start], dbo.TSPERIOD.PERIOD_END AS [Period End], CASE dbo.TSTIMESHEET.SUBMITTED WHEN 0 THEN 'No' WHEN 1 THEN 'Yes' END AS Submitted, CASE dbo.TSTIMESHEET.APPROVAL_STATUS WHEN 0 THEN 'Pending' WHEN 1 THEN 'Approved' WHEN 2 THEN 'Rejected' END AS [Approval Status], CASE dbo.TSITEM.APPROVAL_STATUS WHEN 0 THEN 'Pending' WHEN 1 THEN 'Approved' WHEN 2 THEN 'Rejected' END AS [PM Approval Status], CONVERT(varchar(8000), COALESCE (dbo.TSTIMESHEET.APPROVAL_NOTES, '')) AS [Approval Notes], dbo.TSTIMESHEET.LASTMODIFIEDBYN, CONVERT(varchar(MAX), dbo.TSNOTES.TS_ITEM_NOTES) AS TS_ITEM_NOTES, dbo.TSTIMESHEET.APPROVAL_DATE, COALESCE (dbo.TSTIMESHEET.LastSubmittedByName, dbo.TSTIMESHEET.LASTMODIFIEDBYN) AS LastSubmittedByName, COALESCE (dbo.TSTIMESHEET.LastSubmittedByUser, dbo.TSTIMESHEET.LASTMODIFIEDBYU) AS LastSubmittedByUser FROM dbo.TSITEM INNER JOIN dbo.TSTIMESHEET ON dbo.TSITEM.TS_UID = dbo.TSTIMESHEET.TS_UID INNER JOIN dbo.TSPERIOD ON dbo.TSTIMESHEET.PERIOD_ID = dbo.TSPERIOD.PERIOD_ID AND dbo.TSTIMESHEET.SITE_UID = dbo.TSPERIOD.SITE_ID INNER JOIN dbo.TSITEMHOURS ON dbo.TSITEM.TS_ITEM_UID = dbo.TSITEMHOURS.TS_ITEM_UID LEFT OUTER JOIN dbo.TSNOTES ON dbo.TSITEM.TS_ITEM_UID = dbo.TSNOTES.TS_ITEM_UID AND dbo.TSITEMHOURS.TS_ITEM_DATE = dbo.TSNOTES.TS_ITEM_DATE LEFT OUTER JOIN dbo.TSMETA ON dbo.TSITEM.TS_ITEM_UID = dbo.TSMETA.TS_ITEM_UID LEFT OUTER JOIN dbo.TSTYPE ON dbo.TSTIMESHEET.SITE_UID = dbo.TSTYPE.SITE_UID AND dbo.TSITEMHOURS.TS_ITEM_TYPE_ID = dbo.TSTYPE.TSTYPE_ID LEFT OUTER JOIN dbo.TSUSER ON dbo.TSTIMESHEET.TSUSER_UID = dbo.TSUSER.TSUSERUID UNION SELECT dbo.TSTIMESHEET.USERNAME AS Username, dbo.TSTIMESHEET.RESOURCENAME AS [Resource Name], dbo.TSUSER.USER_ID AS SharePointAccountID, dbo.TSITEM.LIST_UID, dbo.TSITEM.ITEM_ID, dbo.TSITEM.TS_ITEM_UID AS [Item UID], dbo.TSITEM.TITLE AS [Item Name], dbo.TSITEM.PROJECT AS Project, dbo.TSITEM.PROJECT_ID AS ProjectID, COALESCE (dbo.TSMETA.ColumnName, 'TempColumn') AS ColumnName, dbo.TSMETA.DisplayName, dbo.TSMETA.ColumnValue, dbo.TSITEM.ITEM_TYPE AS [Item Type], dbo.TSITEM.TS_UID AS [Timesheet UID], dbo.TSPERIOD.PERIOD_ID AS [Period Id], dbo.TSPERIOD.SITE_ID, dbo.TSITEM.LIST AS List, dbo.TSITEMHOURS.TS_ITEM_DATE AS Date, dbo.TSITEMHOURS.TS_ITEM_HOURS AS Hours, dbo.TSITEMHOURS.TS_ITEM_TYPE_ID AS [Type Id], dbo.TSTYPE.TSTYPE_NAME AS [Type Name], dbo.TSPERIOD.PERIOD_START AS [Period Start], dbo.TSPERIOD.PERIOD_END AS [Period End], CASE dbo.TSTIMESHEET.SUBMITTED WHEN 0 THEN 'No' WHEN 1 THEN 'Yes' END AS Submitted, CASE dbo.TSTIMESHEET.APPROVAL_STATUS WHEN 0 THEN 'Pending' WHEN 1 THEN 'Approved' WHEN 2 THEN 'Rejected' END AS [Approval Status], CASE dbo.TSITEM.APPROVAL_STATUS WHEN 0 THEN 'Pending' WHEN 1 THEN 'Approved' WHEN 2 THEN 'Rejected' END AS [PM Approval Status], CONVERT(varchar(8000), COALESCE (dbo.TSTIMESHEET.APPROVAL_NOTES, '')) AS [Approval Notes], dbo.TSTIMESHEET.LASTMODIFIEDBYN, CONVERT(varchar(MAX), dbo.TSNOTES.TS_ITEM_NOTES) AS Expr1, dbo.TSTIMESHEET.APPROVAL_DATE, COALESCE (dbo.TSTIMESHEET.LastSubmittedByName, dbo.TSTIMESHEET.LASTMODIFIEDBYN) AS LastSubmittedByName, COALESCE (dbo.TSTIMESHEET.LastSubmittedByUser, dbo.TSTIMESHEET.LASTMODIFIEDBYU) AS LastSubmittedByUser FROM dbo.TSITEM INNER JOIN dbo.TSTIMESHEET ON dbo.TSITEM.TS_UID = dbo.TSTIMESHEET.TS_UID INNER JOIN dbo.TSPERIOD ON dbo.TSTIMESHEET.PERIOD_ID = dbo.TSPERIOD.PERIOD_ID AND dbo.TSTIMESHEET.SITE_UID = dbo.TSPERIOD.SITE_ID INNER JOIN dbo.TSITEMHOURS ON dbo.TSITEM.TS_ITEM_UID = dbo.TSITEMHOURS.TS_ITEM_UID LEFT OUTER JOIN dbo.TSNOTES ON dbo.TSITEMHOURS.TS_ITEM_DATE = dbo.TSNOTES.TS_ITEM_DATE AND dbo.TSITEM.TS_ITEM_UID = dbo.TSNOTES.TS_ITEM_UID LEFT OUTER JOIN dbo.TSMETA ON dbo.TSITEM.TS_ITEM_UID = dbo.TSMETA.TS_ITEM_UID AND dbo.TSITEM.LIST = dbo.TSMETA.ListName LEFT OUTER JOIN dbo.TSTYPE ON dbo.TSTIMESHEET.SITE_UID = dbo.TSTYPE.SITE_UID AND dbo.TSITEMHOURS.TS_ITEM_TYPE_ID = dbo.TSTYPE.TSTYPE_ID LEFT OUTER JOIN dbo.TSUSER ON dbo.TSTIMESHEET.TSUSER_UID = dbo.TSUSER.TSUSERUID UNION SELECT TSTIMESHEET_1.USERNAME, TSTIMESHEET_1.RESOURCENAME AS [Resource Name], TSUSER_1.USER_ID AS SharePointAccountID, TSITEM_1.LIST_UID, TSITEM_1.ITEM_ID, TSITEM_1.TS_ITEM_UID, TSITEM_1.TITLE, TSITEM_1.PROJECT, TSITEM_1.PROJECT_ID, 'Resource_' + dbo.TSRESMETA.ColumnName AS listcolumnname, dbo.TSRESMETA.DisplayName, CASE dbo.TSRESMETA.ColumnName WHEN 'StandardRate' THEN (CASE TSITEM_1.Rate WHEN null THEN dbo.TSRESMETA.ColumnValue ELSE TSITEM_1.Rate END) ELSE dbo.TSRESMETA.columnvalue END AS ColumnValue, TSITEM_1.ITEM_TYPE, TSITEM_1.TS_UID,TSTIMESHEET_1.PERIOD_ID, TSTIMESHEET_1.SITE_UID, TSITEM_1.LIST, TSITEMHOURS_1.TS_ITEM_DATE, TSITEMHOURS_1.TS_ITEM_HOURS, TSITEMHOURS_1.TS_ITEM_TYPE_ID, TSTYPE_1.TSTYPE_NAME, TSPERIOD_1.PERIOD_START AS Start, TSPERIOD_1.PERIOD_END AS [End], CASE TSTIMESHEET_1.SUBMITTED WHEN 0 THEN 'No' WHEN 1 THEN 'Yes' END AS Submitted, CASE TSTIMESHEET_1.APPROVAL_STATUS WHEN 0 THEN 'Pending' WHEN 1 THEN 'Approved' WHEN 2 THEN 'Rejected' END AS [Approval Status], CASE TSITEM_1.APPROVAL_STATUS WHEN 0 THEN 'Pending' WHEN 1 THEN 'Approved' WHEN 2 THEN 'Rejected' END AS [PM Approval Status], CONVERT(varchar(8000), COALESCE (TSTIMESHEET_1.APPROVAL_NOTES, '')) AS [Approval Notes], TSTIMESHEET_1.LASTMODIFIEDBYN, CONVERT(varchar(MAX), dbo.TSNOTES.TS_ITEM_NOTES) AS TS_ITEM_NOTES, TSTIMESHEET_1.APPROVAL_DATE, COALESCE (TSTIMESHEET_1.LastSubmittedByName, TSTIMESHEET_1.LASTMODIFIEDBYN) AS LastSubmittedByName, COALESCE (TSTIMESHEET_1.LastSubmittedByUser, TSTIMESHEET_1.LASTMODIFIEDBYU) AS LastSubmittedByUser FROM dbo.TSTIMESHEET AS TSTIMESHEET_1 INNER JOIN dbo.TSRESMETA ON TSTIMESHEET_1.TS_UID = dbo.TSRESMETA.TS_UID INNER JOIN dbo.TSITEM AS TSITEM_1 ON TSTIMESHEET_1.TS_UID = TSITEM_1.TS_UID INNER JOIN dbo.TSITEMHOURS AS TSITEMHOURS_1 ON TSITEM_1.TS_ITEM_UID = TSITEMHOURS_1.TS_ITEM_UID INNER JOIN dbo.TSPERIOD AS TSPERIOD_1 ON TSTIMESHEET_1.PERIOD_ID = TSPERIOD_1.PERIOD_ID AND TSTIMESHEET_1.SITE_UID = TSPERIOD_1.SITE_ID LEFT OUTER JOIN dbo.TSNOTES ON TSITEMHOURS_1.TS_ITEM_DATE = dbo.TSNOTES.TS_ITEM_DATE AND TSITEM_1.TS_ITEM_UID = dbo.TSNOTES.TS_ITEM_UID LEFT OUTER JOIN dbo.TSTYPE AS TSTYPE_1 ON TSTIMESHEET_1.SITE_UID = TSTYPE_1.SITE_UID AND TSITEMHOURS_1.TS_ITEM_TYPE_ID = TSTYPE_1.TSTYPE_ID LEFT OUTER JOIN dbo.TSUSER AS TSUSER_1 ON TSTIMESHEET_1.TSUSER_UID = TSUSER_1.TSUSERUID" ); #endregion LogMessage("TSItem.Rate, Updated the vwMeta view", MessageKind.SUCCESS, 4); } }); return(true); } catch (Exception exception) { string message = exception.InnerException != null ? exception.InnerException.Message : exception.Message; LogMessage(message, MessageKind.FAILURE, 4); return(false); } }
protected void Button2_Click(object sender, EventArgs e) { try { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(SPContext.Current.Web.Url)) { using (SPWeb web = site.OpenWeb()) { SPList list = web.Lists.TryGetList("CandidateDetails"); if (list != null) { SPListItem NewItem = list.Items.Add(); { SPDocumentLibrary documentLib = web.Lists["Resumes"] as SPDocumentLibrary; Stream fStream = FileUpload1.PostedFile.InputStream; byte[] _byteArray = new byte[fStream.Length]; fStream.Read(_byteArray, 0, (int)fStream.Length); fStream.Close(); web.AllowUnsafeUpdates = true; string filepath = FileUpload1.FileName.Split(',')[0]; string _fileUrl = documentLib.RootFolder.Url + "/" + FileUpload1.FileName; string candidateResumeLink = documentLib.RootFolder.ServerRelativeUrl + "/" + FileUpload1.FileName; bool IsOverwriteFile = true; SPFile file = documentLib.RootFolder.Files.Add(_fileUrl, _byteArray, IsOverwriteFile); SPListItem item = file.Item; item["Title"] = FileUpload1.FileName.Split('.')[0]; item["Name"] = FileUpload1.FileName; item.Update(); file.Update(); NewItem["Name"] = txtname.Text; NewItem["Domain"] = drpdomain.SelectedItem.ToString(); NewItem["Experience"] = txtexperience.Text; NewItem["SkillSets"] = txtskillset.Text; NewItem["CurrentCTC"] = txtcrtctc.Text; NewItem["ExpectedCTC"] = txtexctc.Text; //People Picker int Interviewer = spPeoplePickerUserName.ResolvedEntities.Count; for (int i = 0; i < Interviewer; i++) { PickerEntity peEntity = spPeoplePickerUserName.ResolvedEntities[i] as PickerEntity; SPUser user = SPContext.Current.Web.EnsureUser(peEntity.Key); NewItem["Interviewer"] = user; } //NewItem["Interviewer"] = user.Name; // Datetime Control if (!DateTimeControl1.IsDateEmpty) { NewItem["InterviewDate"] = Convert.ToDateTime(DateTimeControl1.SelectedDate); } else { NewItem["InterviewDate"] = DateTime.Now; } NewItem["Remarks"] = txtremark.Text; NewItem["Email"] = txtemail.Text; NewItem["ContactNo"] = txtcontact.Text; NewItem["UploadedResume"] = FileUpload1.FileName; NewItem["Status"] = drpStatus.SelectedItem.ToString(); NewItem.Update(); web.AllowUnsafeUpdates = false; Page.Response.Redirect(SPContext.Current.Site.Url + MainSite, false); // } //} //else //{ // Alert.Text = "List not found"; //} } } } } }); } catch (Exception ex) { //Alert.Text = ex.Message.ToString(); } }
private void UpdateStatisticsList(SPWeb currentWeb, HttpContext ctx) { var cLoginName = string.Empty; var cDate = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now); var cURL = ctx.Request.Url.AbsoluteUri.ToString(); if (currentWeb.CurrentUser == null || string.IsNullOrEmpty(currentWeb.CurrentUser.LoginName)) { cLoginName = "Annonymous"; } else { cLoginName = currentWeb.CurrentUser.LoginName; } var cIP = ctx.Request.UserHostAddress; var cBrowser = ctx.Request.Browser.Browser; var camlQuery = "<Where><And><Eq>" + "<FieldRef Name='Url' />" + "<Value Type='Text'>" + cURL + "</Value></Eq>" + "<And><Eq><FieldRef Name='Title' />" + "<Value Type='Text'>" + cLoginName + "</Value></Eq>" + "<And><Eq><FieldRef Name='DateHit' /><Value Type='DateTime' IncludeTime='FALSE'>" + cDate + "</Value></Eq>" + "<And><Eq><FieldRef Name='Browser' /><Value Type='Text'>" + cBrowser + "</Value></Eq><Eq><FieldRef Name='IP' /><Value Type='Text'>" + cIP + "</Value></Eq>" + "</And></And></And></And></Where>"; SPSecurity.RunWithElevatedPrivileges(() => { using (var site = new SPSite(currentWeb.Site.ID)) { using (var web = site.OpenWeb(currentWeb.ID)) { try { SPQuery spQuery = new SPQuery { Query = camlQuery, RowLimit = 1 }; SPList list = Utilities.GetListFromUrl(web, ListsName.English.StatisticsList); if (list != null) { SPListItemCollection items = list.GetItems(spQuery); if (items == null || items.Count <= 0) { var item = list.Items.Add(); item["Title"] = cLoginName; item["Url"] = cURL; item["IP"] = cIP; item["DateHit"] = DateTime.Now; item["Browser"] = cBrowser; web.AllowUnsafeUpdates = true; item.Update(); } } } catch (Exception ex) { } } } }); }
protected void exportcsv_Click(object sender, EventArgs e) { string _stdate = _hiddenstdate.Value; string _enddate = _hiddenenddate.Value; DateTime _enddateformatted = Convert.ToDateTime(_enddate); string siteurl = HttpContext.Current.Request.UrlReferrer.ToString(); #region sqlqry string gridqry = @" SELECT t_res.ResourceUID AS ResUID, t_proj.ProjectUID AS ProjUID, t_res.ResourceName AS ResName, CASE WHEN t_class.Type <> 0 THEN t_class.ClassNAME ELSE t_proj.ProjectName END AS ProjName, t_act.TimeByDay AS t_date, t_act.TimeByDay_DayOfWeek AS t_wkday, t_class.Type AS t_type, CASE WHEN ((t_act.TimeByDay_DayOfWeek = 1 OR t_act.TimeByDay_DayOfWeek = 7) AND (t_class.Type = 1)) THEN '0' WHEN (t_class.Type = 1 AND (t_act.ActualWorkBillable + t_act.ActualWorkNonBillable + t_act.ActualOvertimeWorkBillable + t_act.ActualOvertimeWorkNonBillable <= 4)) THEN '4' WHEN (t_class.Type = 1 AND (t_act.ActualWorkBillable + t_act.ActualWorkNonBillable + t_act.ActualOvertimeWorkBillable + t_act.ActualOvertimeWorkNonBillable > 4)) THEN '8' ELSE t_act.ActualWorkBillable + t_act.ActualWorkNonBillable + t_act.ActualOvertimeWorkBillable + t_act.ActualOvertimeWorkNonBillable END AS totaltime INTO [#t1] FROM MSP_TimesheetActual AS t_act INNER JOIN MSP_TimesheetResource AS t_res ON t_act.LastChangedResourceNameUID = t_res.ResourceNameUID INNER JOIN MSP_TimesheetLine AS t_line ON t_act.TimesheetLineUID = t_line.TimesheetLineUID INNER JOIN MSP_TimesheetClass AS t_class ON t_line.ClassUID = t_class.ClassUID INNER JOIN MSP_TimesheetProject AS t_proj ON t_line.ProjectNameUID = t_proj.ProjectNameUID WHERE (t_act.TimeByDay BETWEEN '" + _stdate + @"' AND '" + _enddate + @"') ORDER BY ResUID, t_date, t_type SELECT #t1.ResUID, #t1.ProjUID, #t1.ResName, #t1.ProjName, #t1.t_date, #t1.t_wkday, #t1.t_type, #t1.totaltime, ISNULL(dummyt1_nkwking.nonwktotal,0) AS nwktotal, ISNULL(dummyt1.daytotal,0) AS daytotal, CASE WHEN #t1.t_type <> 1 AND ((dummyt1_nkwking.nonwktotal = 4 AND dummyt1.daytotal >4)or (ISNULL(dummyt1_nkwking.nonwktotal,0) =8) or (ISNULL(dummyt1_nkwking.nonwktotal,0) = 0 AND dummyt1.daytotal > 8)) THEN (8-ISNULL(dummyt1_nkwking.nonwktotal,0))*#t1.totaltime/(CASE WHEN dummyt1.daytotal=0 THEN 1 ELSE ISNULL(dummyt1.daytotal,1) END) ELSE #t1.totaltime END AS normalizedtime into #t2 FROM #t1 LEFT OUTER JOIN( SELECT dummyt1_nwking.ResUID, dummyt1_nwking.t_date, SUM(dummyt1_nwking.totaltime) AS nonwktotal FROM [#t1] AS dummyt1_nwking WHERE (dummyt1_nwking.t_type = 1) GROUP BY dummyt1_nwking.ResUID, dummyt1_nwking.t_date --ORDER BY dummyt1_nwking.ResUID, dummyt1_nwking.t_date ) AS dummyt1_nkwking ON #t1.ResUID = dummyt1_nkwking.ResUID AND #t1.t_date = dummyt1_nkwking.t_date LEFT OUTER JOIN ( SELECT dummyt1.ResUID, dummyt1.t_date, SUM(dummyt1.totaltime) AS daytotal FROM [#t1] AS dummyt1 WHERE (dummyt1.t_type <> 1) GROUP BY dummyt1.ResUID, dummyt1.t_date --ORDER BY dummyt1.ResUID, dummyt1.t_date ) AS dummyt1 ON #t1.ResUID = dummyt1.ResUID AND #t1.t_date = dummyt1.t_date ORDER BY #t1.ResUID, #t1.t_date, #t1.t_type drop table #t1 SELECT distinct TimeByDay AS missing_date,TimeDayOfTheWeek AS missing_wkday, t_Resources.ResUID AS missing_ResUID, t_Resources.ResName INTO #t3 FROM MSP_TimeByDay CROSS JOIN (SELECT distinct [#t2].ResUID, #t2.ResName FROM [#t2]) AS t_Resources WHERE (TimeByDay BETWEEN '" + _stdate + @"' AND '" + _enddate + @"') AND (NOT EXISTS (SELECT * FROM [#t2] WHERE MSP_TimeByDay.TimeByDay = [#t2].t_date AND t_Resources.ResUID = [#t2].ResUID)) INSERT INTO #t2 SELECT #t3.missing_ResUID, 'E38038FA-F8CA-47D1-BFD4-6B45B8462972',#t3.ResName,'NotClocked',#t3.missing_date, #t3.missing_wkday, 1, 8, 8,0,8 FROM #t3 WHERE #t3.missing_wkday <> '1' AND #t3.missing_wkday <> '7' drop table #t3 SELECT #t2.ResUID, SUM(#t2.normalizedtime) AS total_paid_leave INTO #t4 FROM #t2 WHERE #t2.t_type = 1 AND #t2.ProjName = 'Paid Leave-Public Holiday' GROUP By #t2.ResUID SELECT #t2.ResUID,#t2.ProjUID, SUM( (CONVERT(NUMERIC(18,14),#t2.normalizedtime) /(CASE WHEN nortotal.total_Proj = 0 THEN 1.0 ELSE CONVERT(NUMERIC(18,14),nortotal.total_Proj) END) )*CONVERT(NUMERIC(18,14),ISNULL(#t4.total_paid_leave,0)) + CONVERT(NUMERIC(18,14),#t2.normalizedtime) ) AS normalized_proj_time INTO #t5 FROM #t2 INNER JOIN (select #t2.ResUID, SUM(#t2.normalizedtime) AS total_Proj FROM #t2 WHERE t_type = 0 GROUP BY #t2.ResUID) AS nortotal ON #t2.ResUID = nortotal.ResUID LEFT OUTER JOIN #t4 ON #t2.ResUID = #t4.ResUID WHERE #t2.t_type = 0 GROUP BY #t2.ResUID, #t2.ProjUID, #t2.ProjName, #t2.t_type --select * from #t2 drop table #t4 SELECT #t2.ResUID, #t2.ProjUID, #t2.ProjName, #t2.t_type, SUM (convert(numeric(18,14),#t2.normalizedtime)) AS nor_time INTO #t6 FROM #t2 GROUP By #t2.ResUID, #t2.ProjUID, #t2.ProjName,#t2.t_type drop table #t2 select #t6.ResUID, #t6.ProjUID, #t6.ProjName, CASE WHEN #t6.t_type = 0 THEN #t5.normalized_proj_time ELSE #t6.nor_time END AS total_time, CASE WHEN #t6.t_type = 0 THEN (convert (float,#t5.normalized_proj_time)/res_total.res_total_time)*100 ELSE (convert(float,#t6.nor_time) /res_total.res_total_time)*100 END AS pct_total_time, #t6.t_type INTO #t7 from #t6 LEFT OUTER JOIN #t5 on #t6.ResUID = #t5.ResUID and #t6.ProjUID = #t5.ProjUID LEFT OUTER JOIN (select #t6.ResUID, SUM (#t6.nor_time) AS res_total_time FROM #t6 GROUP BY #t6.ResUID) AS res_total ON #t6.ResUID = res_total.ResUID where #t6.ProjName <> 'Paid Leave-Public Holiday' order by #t6.ResUID drop table #t5 drop table #t6 select #t7.ResUID, #t7.ProjUID, #t7.ProjName, #t7.total_time, #t7.pct_total_time,uv_res.ResourceName, ISNULL (uv_proj.Project_RC_Code, #t7.ProjName) AS costcode, ISNULL(uv_res.ResourceEmailAddress,'NoEmail') AS res_email FROM #t7 left outer join dbo.MSP_EpmResource_UserView as uv_res on #t7.ResUID = uv_res.ResourceUID left outer join dbo.MSP_EpmProject_UserView as uv_proj on #t7.ProjUID = uv_proj.ProjectUID order by #t7.resuid, #t7.t_type drop table #t7 "; string rc_code_qry = @" SELECT MemberFullValue FROM MSPLT_Project_RC_Code_UserView WHERE (ParentLookupMemberUID IS NOT NULL) ORDER BY CAST(MemberFullValue AS varchar(500)) "; #endregion sqlqry WindowsImpersonationContext wik = null; wik = WindowsIdentity.Impersonate(IntPtr.Zero); SPSecurity.RunWithElevatedPrivileges(delegate() { SqlConnection con = new SqlConnection(MyConfiguration.GetDataBaseConnectionString(siteurl)); con.Open(); DataSet dt = new DataSet(); DataSet rc_code_dt = new DataSet(); SqlDataAdapter adapter = new SqlDataAdapter(new SqlCommand(gridqry, con)); adapter.Fill(dt); DataTable maintbl = dt.Tables[0]; adapter = new SqlDataAdapter(new SqlCommand(rc_code_qry, con)); adapter.Fill(rc_code_dt); DataTable rc_code_table = rc_code_dt.Tables[0]; maintbl.Columns.Add("HRISID"); maintbl.Columns.Add("OLDEMPID"); maintbl.Columns.Add("PayRolStDate"); maintbl.Columns.Add("PayRolEntity"); maintbl.Columns.Add("staftype"); string pctcolumntype = maintbl.Columns["pct_total_time"].DataType.ToString(); DataView view = new DataView(dt.Tables[0]); DataTable resourcelist = view.ToTable(true, "ResourceName", "res_email"); string resname = string.Empty; string resemail = string.Empty; try { using (SPSite site = new SPSite(MyConfiguration.frm_siteurl_GetSiteURL(siteurl))) { foreach (DataRow row in resourcelist.Rows) { SPWeb hrWeb = site.AllWebs["HRMV02"]; SPList res_detail = hrWeb.Lists["Resource Details"]; SPList seconded = hrWeb.Lists["Resource Secondment"]; SPQuery qry = new SPQuery(); qry.Query = @"<Where> <Eq> <FieldRef Name='EMail'/> <Value Type='Text'>" + row[1].ToString() + @"</Value> </Eq> </Where>"; SPListItemCollection items = res_detail.GetItems(qry); #region secondment and resource data from HR Manipulation if (items.Count > 0) { foreach (SPListItem itm in items) { #region secondment query SPQuery secondedqry = new SPQuery(); secondedqry.Query = @" <ViewFields> <FieldRef Name='Department' /> <FieldRef Name='From_x0020_Date' /> <FieldRef Name='To_x0020_Date' /> </ViewFields> <Where> <And> <Eq> <FieldRef Name='Resource_x0020_Name' /> <Value Type='Lookup'>" + itm["Resource Name"].ToString() + @"</Value> </Eq> <Leq> <FieldRef Name='From_x0020_Date' /> <Value Type='DateTime'>" + string.Format("{0:yyyy-MM-dd}", _enddateformatted) + @"</Value> </Leq> </And> </Where> <OrderBy> <FieldRef Name='ID' Ascending='False' /> </OrderBy> <RowLimit>1</RowLimit> "; #endregion secondment query //MyConfiguration.ErrorLog("List Resource Name : " + itm["Resource Name"].ToString(), EventLogEntryType.SuccessAudit); //MyConfiguration.ErrorLog("List Department Name : " + itm["Department"].ToString(), EventLogEntryType.SuccessAudit); foreach (DataRow ro in maintbl.Select("res_email = '" + row[1].ToString() + "'")) { ro["ResourceName"] = itm["Resource Name"].ToString(); if ((itm.Fields.ContainsField("HRIS_x0020_ID")) && (itm["HRIS_x0020_ID"] != null)) { ro["HRISID"] = itm["HRIS_x0020_ID"].ToString(); } else { ro["HRISID"] = "-"; } if ((itm.Fields.ContainsField("Old_x0020_Emp_x0020_Num")) && (itm["Old_x0020_Emp_x0020_Num"] != null)) { ro["OLDEMPID"] = itm["Old_x0020_Emp_x0020_Num"].ToString(); } else { ro["OLDEMPID"] = "-"; } if ((itm.Fields.ContainsField("Date_x0020_On_x0020_Board")) && (itm["Date_x0020_On_x0020_Board"] != null)) { ro["PayRolStDate"] = itm["Date_x0020_On_x0020_Board"].ToString(); } else { ro["PayRolStDate"] = "01-01-1900"; } if ((itm.Fields.ContainsField("Department")) && (itm["Department"] != null)) { string[] deptname = itm["Department"].ToString().Split(new char[] { ';', '#' }, StringSplitOptions.RemoveEmptyEntries); SPList deptlist = hrWeb.Lists["Department"]; SPListItem deptitem = deptlist.GetItemById(Convert.ToInt32(deptname[0].ToString())); string[] entityname = deptitem["Entity"].ToString().Split(new char[] { ';', '#' }, StringSplitOptions.RemoveEmptyEntries); ro["PayRolEntity"] = entityname[1].ToString(); if (ro["ProjName"].ToString() != string.Empty && ro["ProjName"].ToString() == "Orignal Department") { ro["ProjName"] = deptname[1].ToString(); if ((deptitem.Fields.ContainsField("Cost_x0020_Code")) && (deptitem["Cost_x0020_Code"] != null)) { ro["costcode"] = deptitem["Cost_x0020_Code"].ToString(); } else { ro["costcode"] = deptname[1].ToString(); } } } else { ro["PayRolEntity"] = "-"; } if ((itm.Fields.ContainsField("Resource_x0020_Type")) && (itm["Resource_x0020_Type"] != null)) { ro["staftype"] = itm["Resource_x0020_Type"].ToString(); } else { ro["staftype"] = "-"; } SPListItemCollection secondeditems = seconded.GetItems(secondedqry); if (secondeditems.Count > 0) { foreach (SPListItem secondeditem in secondeditems) { if ((secondeditem.Fields.ContainsField("Department")) && (secondeditem["Department"] != null)) { string[] deptname = secondeditem["Department"].ToString().Split(new char[] { ';', '#' }, StringSplitOptions.RemoveEmptyEntries); SPList deptlist = hrWeb.Lists["Department"]; SPListItem deptitem = deptlist.GetItemById(Convert.ToInt32(deptname[0].ToString())); string[] entityname = deptitem["Entity"].ToString().Split(new char[] { ';', '#' }, StringSplitOptions.RemoveEmptyEntries); ro["PayRolEntity"] = entityname[1].ToString(); if (ro["ProjName"].ToString() != string.Empty && ro["ProjName"].ToString() == "TO BAU") { ro["ProjName"] = deptname[1].ToString(); if ((deptitem.Fields.ContainsField("Cost_x0020_Code")) && (deptitem["Cost_x0020_Code"] != null)) { ro["costcode"] = deptitem["Cost_x0020_Code"].ToString(); } else { ro["costcode"] = deptname[1].ToString(); } } //MyConfiguration.ErrorLog("Resource Name: " + ro["ResourceName"].ToString(), EventLogEntryType.SuccessAudit); //MyConfiguration.ErrorLog("Deptment: " + ro["ProjName"].ToString(), EventLogEntryType.SuccessAudit); //MyConfiguration.ErrorLog("Code: " + ro["costcode"].ToString(), EventLogEntryType.SuccessAudit); } } } } } } else { foreach (DataRow ro in maintbl.Select("res_email = '" + row[1].ToString() + "'")) { ro["HRISID"] = "NA in HRM"; ro["OLDEMPID"] = "NA in HRM"; ro["PayRolStDate"] = "01-01-1900"; ro["PayRolEntity"] = "NA in HRM"; ro["staftype"] = "Internal"; } } #endregion secondment and resource data from HR Manipulation } } } catch (Exception ex) { MyConfiguration.ErrorLog("Error in accessing SPSite" + ex.Message, EventLogEntryType.Error); } maintbl.DefaultView.Sort = "staftype DESC"; DataView pivotview = new DataView(maintbl); DataTable pivotviewtable = pivotview.ToTable(false, "ResUID", "costcode", "total_time"); var qyery = (from c in maintbl.AsEnumerable() group c by new { cost_code = c.Field <string>("costcode"), res_uid = c.Field <Guid>("ResUID") } into grp orderby grp.Key.res_uid, grp.Key.cost_code select new { ResUID = grp.Key.res_uid, costcode = grp.Key.cost_code, total_time = grp.Sum(r => r.Field <decimal>("total_time")) / 8 }); DataTable pvtable = qyery.CopyToDataTable(); DataTable resulttbl = new DataTable(); resulttbl = Pivot(pvtable, "ResUID", "costcode", "total_time"); resulttbl.Columns.Add("ResourceName"); resulttbl.Columns.Add("HRISID"); resulttbl.Columns.Add("OLDEMPID"); resulttbl.Columns.Add("PayRolStDate"); resulttbl.Columns.Add("PayRolEntity"); resulttbl.Columns.Add("staftype"); resulttbl.Columns["ResourceName"].SetOrdinal(1); resulttbl.Columns["HRISID"].SetOrdinal(2); resulttbl.Columns["OLDEMPID"].SetOrdinal(3); resulttbl.Columns["PayRolStDate"].SetOrdinal(4); resulttbl.Columns["PayRolEntity"].SetOrdinal(5); resulttbl.Columns["staftype"].SetOrdinal(6); if (rc_code_table.Rows.Count > 0) { int columnindex = 7; foreach (DataRow ro in rc_code_table.Rows) { bool found = false; foreach (DataColumn resultcolumn in resulttbl.Columns) { if (ro[0].ToString() == resultcolumn.ColumnName) { found = true; } } if (found == false) { resulttbl.Columns.Add(ro[0].ToString()); } resulttbl.Columns[ro[0].ToString()].SetOrdinal(columnindex++); } } DataView resdetailview = new DataView(maintbl); DataTable resdetailtable = resdetailview.ToTable(true, "ResUID", "ResourceName", "HRISID", "OLDEMPID", "PayRolStDate", "PayRolEntity", "staftype"); foreach (DataRow ro in resulttbl.Rows) { foreach (DataRow mtlrow in resdetailtable.Select("ResUID = '" + ro["ResUID"] + "'")) { ro["ResourceName"] = mtlrow["ResourceName"]; ro["HRISID"] = mtlrow["HRISID"].ToString(); ro["OLDEMPID"] = mtlrow["OLDEMPID"]; if (mtlrow["PayRolStDate"].ToString() != "00-00-000") { ro["PayRolStDate"] = Convert.ToDateTime(mtlrow["PayRolStDate"]).ToString("dd-MM-yyyy"); } else { ro["PayRolStDate"] = mtlrow["PayRolStDate"]; } ro["PayRolEntity"] = mtlrow["PayRolEntity"]; ro["staftype"] = mtlrow["staftype"]; } } #region export function WindowsImpersonationContext wic = null; try { try { wic = WindowsIdentity.Impersonate(IntPtr.Zero); } catch (Exception) { } // You should be very carefull with sharepoint layout folder, we have to specify full control permission to everybody. string FolderPath = Server.MapPath("/_layouts/CIMB_TimeSheet/CSVFiles/"); if (Directory.Exists(FolderPath)) { foreach (string file in Directory.GetFiles(FolderPath)) { try { File.Delete(file); } catch (Exception ex) { } } } else { Directory.CreateDirectory(FolderPath); } string clientfilename = DateTime.Now.ToString("ddMMyyhhmmss") + DateTime.Now.Millisecond.ToString(); string filename = FolderPath + clientfilename + ".csv"; var writer = new StreamWriter(filename); //Writing column name at first row string columnheaderline = string.Empty; for (int i = 1; i < resulttbl.Columns.Count; i++) { if (i > 6) { columnheaderline = columnheaderline + resulttbl.Columns[i].ColumnName + "(days),"; } else { columnheaderline = columnheaderline + resulttbl.Columns[i].ColumnName + ","; } } writer.WriteLine(columnheaderline); // Writing row values foreach (DataRow row in resulttbl.Rows) { string columnvalue = string.Empty; for (int i = 1; i < resulttbl.Columns.Count; i++) { if (i > 6) { if (row[i].ToString() != string.Empty) { columnvalue = columnvalue + row[i] + ","; } else { columnvalue = columnvalue + "0,"; } } else { columnvalue = columnvalue + row[i] + ","; } } writer.WriteLine(columnvalue); } writer.Flush(); writer.Close(); writer.Dispose(); // Sending files here Response.ContentType = "application/CSV"; Response.AddHeader("content-disposition", "attachment; filename=ManDayByProject" + clientfilename + ".csv"); Response.TransmitFile(filename); Response.Flush(); Response.End(); } catch (Exception) { } #endregion export function }); }
public override void Execute(Guid contentDbId) { string filePath = "<FILEPATH TO>\\sitemap.xml"; string sharePointSite = "<SHAREPOINT SITELINK>"; var sb = new StringBuilder(); string xmltext = sb.AppendLine("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>") .AppendLine("<!--Generated:" + XmlConvert.ToString(DateTime.Now) + "-->") .AppendLine("<urlset xmlns=\"<SITEMAP LINK URLSET>\">") .ToString(); try { xmltext = sb.AppendLine(ReturnPagesLibraryListElements("<PAGES LIST>")) .AppendLine(ReturnDLListElements("<DOCUMENT LIBRARY 1>")) .AppendLine(ReturnDLListElements("<DOCUMENT LIBRARY 2>")) .AppendLine(ReturnDLListElements("<DOCUMENT LIBRARY 3>")) .AppendLine("</urlset>").ToString(); System.IO.File.WriteAllText(@filePath, xmltext); //By colleague string fileToUpload = @filePath; string documentLibraryName = "Sitemap"; Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(delegate { using (SPSite oSite = new SPSite(this.WebApplication.Sites[0].Url)) { using (SPWeb oWeb = oSite.OpenWeb()) { if (!System.IO.File.Exists(fileToUpload)) { throw new FileNotFoundException("File not found.", fileToUpload); } SPFolder myLibrary = oWeb.Folders[documentLibraryName]; // Prepare to upload Boolean replaceExistingFiles = true; String fileName = System.IO.Path.GetFileName(fileToUpload); FileStream fileStream = File.OpenRead(fileToUpload); // Upload document SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles); // Commit myLibrary.Update(); } } }); // End -By colleague } catch (Exception ex) { SPSecurity.RunWithElevatedPrivileges(delegate() { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("Sitemap-Logging", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message + " URL== " + this.WebApplication.Sites[0].Url, ex.StackTrace); }); } }
/// <summary> /// An item was updated. /// </summary> public override void ItemUpdated(SPItemEventProperties properties) { base.ItemUpdated(properties); //Ausführen des folgenden Codes nur, wenn ein PDF vorhanden ist if (properties.ListItem.Name.Contains(".pdf")) { //Durch folgende Zeile wird der enthaltene Code als SHAREPOINT\System ausgeführt und nicht unter dem Kontext des Benutzers, der den Auftrag unterschrieben hat SPSecurity.RunWithElevatedPrivileges(delegate() { //Laden des aktuellen Webs; das ist nötig, um alle möglichen Operationen mit Bibliotheken und Elementen auszuführen //dieses wird wieder geschlossen bzw. freigegeben, wenn die geschweifte Klammer von "using" geschlossen wird using (SPSite site = new SPSite(properties.WebUrl)) { using (SPWeb web = site.OpenWeb()) { //Festlegen von Variablen //Initialisieren der "Helper"-Klasse. Diese enthält selbst geschriebene Methoden, die hier aufgerufen werden. Helper helper = new Helper(); //Laden des aktuell geänderten bzw. unterschrieben Elements SPListItem _currentItem = web.Lists[properties.ListId].GetItemById(properties.ListItemId); //Abspeichern von Spaltenwerten des Elements in Variablen; der String in den eckigen Klammern ist der Spaltenname string auftragsnummer = _currentItem["Auftragsnummer"].ToString(); string bestellmethode = _currentItem["Bestellmethode"].ToString(); SPFieldBoolean DrittlandBoolField = _currentItem.Fields["Drittland"] as SPFieldBoolean; bool Drittland = (bool)DrittlandBoolField.GetFieldValue(_currentItem["Drittland"].ToString()); string DocID = _currentItem.Properties["_dlc_DocId"].ToString(); //Die Summe muss in ein double-Wert umgewandelt werden, damit er später richtig verwendet werden kann double summe = Convert.ToDouble(_currentItem["Summe"]); //Laden der Bibliothek "Temp" und des Unterordners, welcher als Namen die Auftragsnummer hat SPList tempbibliothek = web.Lists["Temp"]; var tempfolder = web.GetFolder(String.Format("{0}/Temp/" + auftragsnummer, web.Url)); //Angabe des Namens der Bibliothek, in der die Begründungen gespeichert werden, und des Dateinamens der Begründungen //string begruendungbibliothek = "Begruendungen"; string begruendungbibliothek = "Begründungen"; string begruendungdateiname = auftragsnummer + "_InterneBegruendung.pdf"; string auftragdesturl = tempbibliothek.RootFolder.SubFolders[auftragsnummer].Url + "/" + auftragsnummer + ".pdf"; string begruendungdesturl = tempbibliothek.RootFolder.SubFolders[auftragsnummer].Url + "/" + begruendungdateiname; //Angabe des Namens der Bibliothek der Auftragsformulare und deren Dateinamen string formularbibliothek = "Auftragsformular"; string formulardateiname = auftragsnummer + ".xml"; string xanhang = "my:Anhang"; string xweitergabe = "my:Weitergabe"; //Angeben des Pfades zum Ablegen des zusammengefassten PDFs für den Druck für die VW //Bei Pfadangaben mit Backslashes muss entweder vor dem Anführungszeichen ein @ geschrieben werden ODER doppelte Backslashes verwendet werden (z.B. "C:\\ipm-int\\Bestellungen\\") string pdfpath = @"C:\Bestellung\PrintTemp\PDF\"; //Angeben des Druckers über den gedruckt wird; hier ist einfach der Freigabename anzugeben //string printer = @"\\ipm-int\Bestellungen\"; string printer = @"\\printserver\A-3-31-SW-Buero\"; //Definieren einer vorerst leeren String-Variable string davorsigniert = ""; //Wenn die Spalte "SignaturePreviousSigned" nicht leer ist, wird der enthaltene Wert der Variable "davorsigniert" zugwiesen if (_currentItem["SignaturePreviousSigned"] != null) { davorsigniert = _currentItem["SignaturePreviousSigned"].ToString(); } //Auslesen der Empfänger-Adressen aus den SharePoint-Gruppen string rcptFaxPostalOrders = ""; string spGroupRcptFaxPostalFiles = "Empfänger der Fax - und Postbestellungen"; foreach (SPUser user in web.SiteGroups[spGroupRcptFaxPostalFiles].Users) { rcptFaxPostalOrders += user.Email.ToString() + ";"; } Console.WriteLine(rcptFaxPostalOrders); //Die Drittlands-Mail inkl. Anlagen soll seit 13.02.2019 laut Verwaltung nur noch an das Einkaufs-Postfach gehen. string rcptThirdCountryOrders = ""; string spGroupRcptCustomFiles = "Empfänger der Drittlandsbestellungen"; foreach (SPUser user in web.SiteGroups[spGroupRcptCustomFiles].Users) { rcptThirdCountryOrders += user.Email.ToString() + ";"; } string rcptBbc = ""; string spGroupRcptBbc = "E-Mails der Ereignisempfänger (BBC) "; foreach (SPUser user in web.SiteGroups[spGroupRcptBbc].Users) { rcptBbc += user.Email.ToString() + ";"; } //Erstellen der byte-Arrays für die PDF-Dateien die durch Mergen/Zusammenfügen erstellt werden; eins für den Empfang zum faxen, das andere für den Ausdruck für die Verwaltung byte[] mergeresultbyte = new byte[0]; byte[] mergeresultbytevw = new byte[0]; //Festlegen des Dateinamens unter dem das PDF für den Ausdurck für die Verwaltung im lokalen Dateisystem abgespeichert wird. string mergefilenamevw = auftragsnummer + "_vw.pdf"; //Laden des gerade signierten PDFs; zuerst wird es als SharePoint-Datei (SPFile) geladen, dann als Byte-Array. SPFile auftragszettel = _currentItem.File; byte[] auftragszettelbyte = auftragszettel.OpenBinary(); //Initialisieren eines PDFReaders (von itextsharp) mit Verweis auf das eben geöffnete Byte-Array; der PDF-Reader kann PDF-Dateien nur lesen using (PdfReader pdfreader = new PdfReader(auftragszettelbyte)) { //Laden der vorhandenen PDF-Formularfelder AcroFields fields = pdfreader.AcroFields; //Speichern der Namen aller signierten Felder in disem PDF in Liste "signatures". Die zu signierenden Felder heißen "Projektleiter" und "Verwaltung"; demnach kann dieser Wert leer, "Projektleiter" oder "ProjektleiterVerwaltung" sein List <string> signatures = pdfreader.AcroFields.GetSignatureNames(); //Die gerade gespeicherten Feldnamen werden mit Komma getrennt (wenn mehrere vorhanden sind) und in eine neue String-Variable gespeichert. Somit wird aus "ProjektleiterVerwaltung" > "Projektleiter,Verwaltung" string signiert = string.Join(",", signatures.ToArray()); //Anhand dieser IF-Abfrage wird geprüft ob der Auftag überhaupt signiert wurde. Es wird der Spaltenwert ("SignaturePreviousSigned") mit den im PDF tatsächlich signierten Feldern verglichen if (signiert != davorsigniert) { //Starten des SharePoint-Designer-Workflows "Unterschriftenlauf" mit Parameter "signedfields". Mit diesem Parameter werden die Namen der Signierten Felder direkt als String mitgegeben. SPWorkflowAssociationCollection associationCollection = _currentItem.ParentList.WorkflowAssociations; foreach (SPWorkflowAssociation association in associationCollection) { if (association.Name == "Unterschriftenlauf") { association.AutoStartChange = true; association.AutoStartCreate = false; association.AssociationData = "<Data><Signiert>" + signiert + "</Signiert></Data>"; //web.Site.WorkflowManager.StartWorkflow(_currentItem, association, association.AssociationData); site.WorkflowManager.StartWorkflow(_currentItem, association, association.AssociationData); } } //Der SharePoint-Designer-Workflow geht nun alle vorhandenen Fälle durch und versendet die nötigen Benachrichtigungen und ändert das Status-Feld des Auftrags //Im Code muss nun nur noch der Fall beachtet werden, wenn Projektleiter und Verwaltung unterschrieben haben //In diesem Fall muss ein PDF für die Verwaltung und eins (nur wenn nötig) für den Empfang erstellt werden. Letzteres wird benötigt, um dem Empfang dieses per Mail zu versenden, damit es gefaxt oder per Post versendet werden kann. //Das ist nur nötig, wenn die Bestellmethode NICHT "online" oder "Abholung" ist //Zu aller erst wird überprüft ob der beschriebene Fall eintritt: Die Variable "signiert" enthält alle Namen der Signaturfelder aus dem PDf, die unterschrieben sind. if ((signiert == "Projektleiter,Verwaltung") || (signiert == "Verwaltung,Projektleiter")) { string tempuploadurl = helper.TempOrdner(tempbibliothek, tempfolder, auftragsnummer); //Laden des Auftragsformulars byte[] xmlfile = helper.GetFileFromWeb(formularbibliothek, formulardateiname, web); Stream xmlmemstr = new MemoryStream(xmlfile); XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(xmlmemstr); XPathNavigator root = xmldoc.CreateNavigator(); XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable()); //Angeben des NameSpaces: Die Werte werden direkt aus einem beispiel Formular entnommen (stehen am Anfang der XML-Datei) nsmgr.AddNamespace("my", "http://schemas.microsoft.com/office/infopath/2003/myXSD/2016-04-22T15:49:19"); helper.AnlagenHochladen(root.Select("/my:meineFelder/my:Anlagen/my:Anlage", nsmgr), xanhang, xweitergabe, nsmgr, DocID, tempfolder, tempuploadurl, web); //Hochladen der Begründung und des aktuellen Auftragzettels in den Temp-Ordner //Begründung if (root.SelectSingleNode("/my:meineFelder/my:Begruendung", nsmgr).ToString() != "") { byte[] fattenedBegruendung = helper.flattenPdfForm(helper.GetFileFromWeb(begruendungbibliothek, begruendungdateiname, web)); SPFile copybegruendung = tempfolder.Files.Add(begruendungdesturl, fattenedBegruendung, true); SPListItem copybegruendungitem = copybegruendung.Item; copybegruendungitem["Auftragsnummer"] = auftragsnummer; //Übernehmen der Änderung. Durch "SystemUpdate" wird diese Änderung nicht in SharePoint selbst dokumentiert (in Spalten "geändert von" und "geändert"). copybegruendungitem.SystemUpdate(); } //Auftragszettel byte[] flattendAuftrag = helper.flattenPdfForm(auftragszettelbyte); SPFile copyauftrag = tempfolder.Files.Add(auftragdesturl, flattendAuftrag, true); //Setzen des Spaltenwerts "Weitergabe" auf true, da der Lieferant den Auftragszettel immer erhalten muss. Wäre dieser WErt auf "false" würde Auftragszettel beim PDf für Fax oder Post fehlen. Der Wert ist in der SharePoint-Bibliothek "Temp" standardmäßig auf "false" gesetzt. SPListItem copyauftragitem = copyauftrag.Item; copyauftragitem["Weitergabe"] = true; copyauftragitem.SystemUpdate(); //diese IF-Abfrage ist nur reine Sicherheitsmaßnahme: Es wird geprüft ob im Temp-Ordner auch Dateien vorhanden sind. Da der Auftrag direkt davor in diesen Ordner kopiert wird sollte diese Bedingung immer zutreffen. if (tempfolder.ItemCount > 0) { //Zusammenführen aller PDF-Dokumente für die Verwaltung //SPListItemCollection ist eine Sammlung von SharePoint-Elementen. Welche Elemente ausgewählt werden, ist in der Helper-Methode (ganz unten) nach zu lesen. Mit dem Übergabewert "false" wird bewirkt, dass nicht beachtet wird, welche Anlagen zur Weitergabe an den Lieferanten gewählt sind - es wird alles einfach gedruckt. SPListItemCollection pdfcollection = helper.CollectPDF(tempfolder, tempbibliothek, false); //Die zuvor erstellte Sammlung von Elementen ("pdfcollection") wird nun in einer weiteren Helper-Methode verwendet, um die PDf-Dateien zu kombinieren. Mit dem Übergabewert "false" wird bewirkt, dass die AEB's NICHT mit ausgedruckt werden. mergeresultbytevw = helper.Merge(pdfcollection, false, auftragsnummer); //Zusammenführen der PDf-Dokumente für den Lieferanten //Gemerged wird nur, wenn über Fax oder Post bestellt wird, damit die Zentrale eine Datei hat, die sie versenden/ausdrucken können. Wenn "online" oder per "Abholung" bestellt wird, oder wenn es sich um ein Drittland handelt, findet dieser Vorgang nicht statt. if ((bestellmethode.Contains("online") == false) && (bestellmethode.Contains("Abholung") == false) && Drittland == false) { //Sammeln der Elemente; diesmal mit dem Übergabewert "true", damit nur Anlagen berücksichtigt werden, die auch zur Weitergabe für den Lieferanten ausgewählt sind pdfcollection = helper.CollectPDF(tempfolder, tempbibliothek, true); //Zusammenführen der gerade gesammelten Elemente; diesmal mit dem Übergabewert "true", damit die AEBs erhalten bleiben mergeresultbyte = helper.Merge(pdfcollection, true, auftragsnummer); //Kopieren des PDF in einen lokalen Ordner auf dem SharePoint-Server File.WriteAllBytes(pdfpath + auftragsnummer + "_Kopie.pdf", mergeresultbyte); string faxnummer = "<br>"; if ((bestellmethode == "Fax") && (_currentItem["Fax"] != null)) { faxnummer = "Fax: " + _currentItem["Fax"].ToString() + "<br><br>"; } string zentraletext = "<div style='font-family: Frutiger LT COM 45 Light; font-size: 11pt;'>Guten Tag,<br><br>" + "der Auftrag #" + auftragsnummer + " wurde vom Projektleiter und der Verwaltung signiert. Als Bestellmethode wurde " + bestellmethode + " gewählt. " + "Der Auftrag ist im Anhang enthalten. Hierbei handelt es sich nur um eine Kopie für den Lieferanten.<br><br>" + "Name Besteller: " + helper.Anzeigename(_currentItem, "Profil:NameBesteller") + "<br>" + "Projektleiter: " + helper.Anzeigename(_currentItem, "Profil:Projektleiter") + "<br>" + "Firma: " + _currentItem["Firma"].ToString() + "<br>" + faxnummer + "Dies ist eine automatische Benachrichtigung. Bitte antworten Sie nicht auf diese E-Mail."; helper.Mail("Bestellung", rcptFaxPostalOrders, rcptBbc, "Auftrag #" + auftragsnummer + " - Signaturvorgang abgeschlossen", zentraletext, mergeresultbyte, auftragsnummer, site); } } else { mergeresultbytevw = auftragszettelbyte; //Auch Dieser Else-Block ist nur reine Sicherheitsmaßnahme. } //Kopieren des PDFs für VW in einen lokalen Ordner (siehe Variable "printpath") auf dem SharePoint-Server. File.WriteAllBytes(pdfpath + mergefilenamevw, mergeresultbytevw); //Hochladen des PDFs für VW in Ordner "Print" in Bibliothek "Temp" //desturl = tempbibliothek.RootFolder.SubFolders["Merged"].Url + "/" + mergefilenamevw; //SPFile uploadmerged = tempfolder.Files.Add(desturl, File.ReadAllBytes(pdfpath + mergefilenamevw), true); //Schicken der PDF-Datei für VW an den Drucker (siehe Variable "printer") if (Drittland == false) { File.Copy(pdfpath + mergefilenamevw, printer + mergefilenamevw); } else { string drittlandtext = "<div style='font-family: Frutiger LT COM 45 Light; font-size: 11pt;'>Guten Tag,<br><br>" + "der Signaturvorang für den Auftrag (#" + auftragsnummer + ") wurde abgeschlossen. Da es sich um eine Bestellung aus dem <b>Drittland</b> handelt, wird der Auftrag <b>ohne automatischen Ausdruck</b> an den Einkauf weitergeleitet. " + "Der Auftrag ist im Anhang enthalten.<br><br>" + "Name Besteller: " + helper.Anzeigename(_currentItem, "Profil:NameBesteller") + "<br>" + "Projektleiter: " + helper.Anzeigename(_currentItem, "Profil:Projektleiter") + "<br>" + "Firma: " + _currentItem["Firma"].ToString() + "<br>" + "Bestellmethode: " + bestellmethode + "<br><br>" + "Dies ist eine automatische Benachrichtigung. Bitte antworten Sie nicht auf diese E-Mail."; helper.Mail("Bestellung", rcptThirdCountryOrders, rcptBbc, "Drittland: Auftrag #" + auftragsnummer + " - Signaturvorgang abgeschlossen", drittlandtext, mergeresultbytevw, auftragsnummer, site); } //Löschen des PDFs für VW aus lokalem Ordner - NICHT MEHR NÖTIG, da der Temp-Ordner wöchentlich aufgeräumt wird. Deßhalb können beide Dateien aus Troubleshooting-Gründen aufgehoben werden. //File.Delete(pdfpath + mergefilenamevw); //Löschen des temporären Ordners in Bibliothek "Temp" tempfolder.Delete(); } } } } } }); } }
private void DeleteOldData(string listName, List <string> moduleIds, int departmentId) { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(_webUrl)) { using (SPWeb web = site.OpenWeb()) { try { web.AllowUnsafeUpdates = true; var firstCondition = $@"<Eq> <FieldRef Name='DataSourceID' /> <Value Type='Number'>{1}</Value> </Eq>"; if (departmentId > 0) { firstCondition = $@"<And> <Eq> <FieldRef Name='DataSourceID' /> <Value Type='Number'>{1}</Value> </Eq> <Eq> <FieldRef Name='DepartmentEN' LookupId='TRUE'/> <Value Type='Lookup'>{departmentId}</Value> </Eq> </And>"; } var query = $@" <Where> {firstCondition} </Where>"; if (moduleIds != null && moduleIds.Any()) // Delete by modules + department { StringBuilder sbItem = new StringBuilder(); foreach (var moduleId in moduleIds) { sbItem.Append($@"<Value Type='Number'>{moduleId}</Value>"); } query = $@"<Where> <And> {firstCondition} <In> <FieldRef Name='ModuleNameEN' LookupId='TRUE'/> <Values> {sbItem.ToString()} </Values> </In> </And> </Where>"; } var spQuery = new SPQuery { ViewFields = "<FieldRef Name='ID'/>", Query = query, ViewAttributes = "Scope=\"RecursiveAll\"", ViewFieldsOnly = true, }; SPList list = web.GetList($"{web.Url}/Lists/{listName}"); var itemCollection = list.GetItems(spQuery); if (itemCollection != null && itemCollection.Count > 0) { // Delete StringBuilder sbDelete = new StringBuilder(); sbDelete.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>"); string stringcommand = "<Method><SetList Scope=\"Request\">" + list.ID + "</SetList><SetVar Name=\"ID\">{0}</SetVar><SetVar Name=\"Cmd\">Delete</SetVar></Method>"; foreach (SPListItem item in itemCollection) { //result.Add(item.ID); sbDelete.Append(string.Format(stringcommand, item.ID)); } sbDelete.Append("</Batch>"); web.ProcessBatchData(sbDelete.ToString()); } } catch { } finally { web.AllowUnsafeUpdates = false; } } } }); }
protected void btnAtualizar_Click(object sender, EventArgs e) { try { string strLogin = SPContext.Current.Web.CurrentUser.LoginName; SPSecurity.RunWithElevatedPrivileges(delegate() { lblErro.Text = string.Empty; lblErro.ForeColor = Color.Red; #region PrivilegeCode if (Request.Files.Count == 0) { lblErro.Text = "Favor selecionar um arquivo válido"; return; } var arquivo = Request.Files[0]; //verificar se a imagem está dentro dos padrões if (!ArquivosValidos.Contains(arquivo.ContentType)) { lblErro.Text = "Tipo de arquivo inválido! Favor selecionar uma imagem JPG válida."; return; } //verifica o tamanho da foto if (arquivo.ContentLength > (1024 * 50)) { lblErro.Text = "O arquivo não pode ser maior que 50KB, tente novamente com um arquivo menor"; return; } Stream srArq = arquivo.InputStream; srArq.Position = 0; byte[] bArq = new byte[srArq.Length]; srArq.Read(bArq, 0, arquivo.ContentLength); //Carregar matricula do usuário if (SiteDataSourceUrl == "/") { SiteDataSourceUrl = Page.Request.Url.Scheme + "://" + Page.Request.Url.Host + ":" + Page.Request.Url.Port; } SPList listaPessoas = SPContext.Current.Web.Lists.TryGetList("Pessoas"); SPQuery objQuery = new SPQuery { Query = "<Where><Contains><FieldRef Name='USERNAME' /><Value Type='Text'>" + strLogin + "</Value></Contains></Where>" }; var eu = listaPessoas.GetItems(objQuery); if (eu == null || eu.Count == 0) { lblErro.Text = "Usuário não encontrado, não foi possível salvar a imagem"; return; } using (SPSite site = new SPSite(SiteDataSourceUrl)) { using (SPWeb web = site.RootWeb) { SPList listaFotos = web.Lists.TryGetList("Fotos"); var matricula = (String)eu[0]["Matrícula"]; //Adiciona o novo arquivo. string strDestino = string.Format("/Fotos/{0}.JPG", matricula); web.Files.Add(strDestino, bArq, true); lblErro.Text = "Imagem atualizada com sucesso!"; lblErro.ForeColor = Color.Green; } } });//delegate #endregion } catch { lblErro.Text = "Erro ao gravar a foto do usuário"; } }
public static void EnableFancyForms(SPList list) { SPSecurity.RunWithElevatedPrivileges(() => { SPWeb web = list.ParentWeb; //No dispose required web.AllowUnsafeUpdates = true; bool isFancyFormWpExist = false; var rootFolder = list.RootFolder; var dispFormUrl = string.Format("{0}/{1}/DispForm.aspx", web.ServerRelativeUrl, rootFolder.Url); var dispForm = web.GetFile(dispFormUrl); if (dispForm != null) { //Delete webparts from existing list using (SPLimitedWebPartManager wpm = dispForm.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared)) { try { if (wpm.WebParts != null) { for (int i = 0; i < wpm.WebParts.Count; i++) { try { if ((!string.IsNullOrEmpty(wpm.WebParts[i].Title)) && (wpm.WebParts[i].Title.Equals("Fancy Display Form", StringComparison.InvariantCultureIgnoreCase)) && !isFancyFormWpExist) { isFancyFormWpExist = true; wpm.WebParts[i].AllowHide = false; wpm.WebParts[i].Hidden = false; wpm.SaveChanges(wpm.WebParts[i]); } else if (wpm.WebParts[i].ToString() == "Microsoft.SharePoint.WebPartPages.XsltListViewWebPart" || wpm.WebParts[i].ToString() == "Microsoft.SharePoint.WebPartPages.ListFormWebPart" || wpm.WebParts[i].ToString() == "Microsoft.SharePoint.WebPartPages.ListViewWebPart" || wpm.WebParts[i].ToString() == "Microsoft.SharePoint.WebPartPages.DataFormWebPart") { wpm.WebParts[i].AllowHide = true; wpm.WebParts[i].Hidden = true; wpm.SaveChanges(wpm.WebParts[i]); } } catch (Exception ex) { LoggingService.WriteTrace(Area.EPMLiveCore, Categories.EPMLiveCore.Event, TraceSeverity.Medium, ex.ToString()); } } } } catch (Exception ex) { LoggingService.WriteTrace(Area.EPMLiveCore, Categories.EPMLiveCore.Event, TraceSeverity.Medium, ex.ToString()); } finally { if (wpm != null) { wpm.Web.Dispose(); } } } } else { dispForm = rootFolder.Files.Add(dispFormUrl, SPTemplateFileType.FormPage); } if (isFancyFormWpExist) { return; } using (SPLimitedWebPartManager wpm = dispForm.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared)) { try { //var fancyDispFormWebPart = new EPMLiveWebParts.FancyDisplayForm(); var fancyDispFormWebPart = WebPartsHelper.WebPartsReflector.CreateFancyDisplayFormWebPart(); fancyDispFormWebPart.Title = "Fancy Display Form"; fancyDispFormWebPart.ChromeState = System.Web.UI.WebControls.WebParts.PartChromeState.Normal; fancyDispFormWebPart.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.None; fancyDispFormWebPart.AllowHide = false; fancyDispFormWebPart.Hidden = false; fancyDispFormWebPart.Visible = true; wpm.AddWebPart(fancyDispFormWebPart, "Main", 0); } catch (Exception ex) { LoggingService.WriteTrace(Area.EPMLiveCore, Categories.EPMLiveCore.Event, TraceSeverity.Medium, ex.ToString()); } finally { if (wpm != null) { wpm.Web.Dispose(); } } } }); }
//public string GetLatestMessageNews(DateTime beforetime, out string nextBeforeTime, bool publicmessage) public static string GetLatestMessageNews(DateTime beforetime, bool publicmessage) { using (new SPMonitoredScope("Weixin.GetLatestMessageNews", 5000)) { //Guid siteid = SPContext.Current.Site.ID; //Guid webid = SPContext.Current.Web.ID; Guid siteid = new Guid("fbf5935b-6717-4036-8bfc-856c1ef075a7"); Guid webid = new Guid("3acebb12-b9c8-4a00-94f7-4d779743e805"); SPUserToken t = null; SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite s = new SPSite(siteid)) { using (SPWeb w = s.OpenWeb(webid)) { t = w.GetUserToken("i:0#.f|fbamember|233173287"); } } }); StringBuilder ret = new StringBuilder(); //using (SPSite site = new SPSite(siteid, SPFBAUser.usertoken)) using (SPSite site = new SPSite(siteid, t)) { using (SPWeb web = site.OpenWeb(webid)) { SPSiteDataQuery query = new SPSiteDataQuery(); //query.Lists = string.Concat("<Lists><List ID = '", web.GetList(publicmessage ? PublicMessageListUrl : PrivateMessageListUrl).ID.ToString(), "' /><List ID = '", web.GetList(ImageLibUrl).ID.ToString(), "' /></Lists>"); //query.Webs = "<Webs Scope=\"SiteCollection\"/>"; query.Lists = string.Concat("<Lists><List ID = '", web.GetList(publicmessage ? "/sites/public/lists/list/" : "/sites/public/lists/Private%20Message/").ID.ToString(), "' /><List ID = '", web.GetList("/sites/public/Images1/").ID.ToString(), "' /></Lists>"); query.ViewFields = @"<FieldRef Name=""Author"" Nullable=""TRUE"" /><FieldRef Name=""ItemChildCount"" Nullable=""TRUE"" /><FieldRef Name=""Modified""/><FieldRef Name=""Title"" Nullable=""TRUE"" />"; query.ViewFields += @"<FieldRef Name=""WeChat61"" Nullable=""TRUE""/>"; query.RowLimit = 5; query.Query = "<OrderBy><FieldRef Name=\"Modified\" Ascending=\"FALSE\" /></OrderBy><Where>" + "<And>" + "<Or>" // + "<And><IsNotNull><FieldRef Name=\"WeChatPicUrl\" Nullable=\"TRUE\"/></IsNotNull>" + "<IsNotNull><FieldRef Name=\"WeChat61\" Nullable=\"TRUE\"/></IsNotNull>" // + (publicmessage? string.Concat("<Eq>< FieldRef Name = \"FileDirRef\" ></FieldRef ><Value Type = \"Text\" >",ImageLibUrl,"</Value></Eq>"): string.Concat("<Contains>< FieldRef Name = \"FileDirRef\" ></FieldRef ><Value Type = \"Text\" >", SPFBAUserName, "</Value><Contains>")) // + (publicmessage ? string.Concat("<Eq><FieldRef Name = \"FileDirRef\" /><Value Type = \"Text\" >", "/sites/public/Images1/", "</Value></Eq>") : string.Concat("<Contains>< FieldRef Name = \"FileDirRef\" /><Value Type = \"Text\" >", "233173287", "</Value></Contains>")) // + "</And>" + "<BeginsWith><FieldRef Name = \"ContentTypeId\" /><Value Type = \"ContentTypeId\" >0x012002</Value></BeginsWith>" + "</Or>" + "<Lt><FieldRef Name='Created'/><Value IncludeTimeValue ='TRUE' Type ='DateTime'>" + SPUtility.CreateISO8601DateTimeFromSystemDateTime(beforetime) + "</Value></Lt>" + "</And></Where>"; DataTable results = web.GetSiteData(query); if (results != null && results.Rows.Count > 0) { //var responseMessageNews = CreateResponseMessage<ResponseMessageNews>(); //Article a = new Article(); ////string prevAuthor = string.Empty; //int i = 0; //StringBuilder ret = new StringBuilder(); //foreach (DataRow r in results.Rows) //{ // string author = r["Author"] == null ? string.Empty : r["Author"].ToString().Trim(); // //SPFieldUserValue au = author.Equals(string.Empty) ? null : // // (item.Fields.GetFieldByInternalName("Author").GetFieldValue(item["Author"].ToString()) as SPFieldUserValue); // //string u = au == null ? string.Empty // // : (au.User == null ? string.Empty : au.User.Name); // if (string.IsNullOrEmpty((r["WeChatPicUrl"] ?? string.Empty).ToString())) // { // ret.AppendLine(string.Concat(author, ":", r["Title"])); // ret.AppendLine(string.Concat(" 修改时间", r["Modified"].ToString())); // } //} //responseMessageNews.Articles.Add(a); string lastTime = string.Empty; foreach (DataRow item in results.Rows) { string author = item["Author"] == null ? string.Empty : item["Author"].ToString().Trim(); //SPFieldUserValue au = author.Equals(string.Empty) ? null : // (item.Fields.GetFieldByInternalName("Author").GetFieldValue(item["Author"].ToString()) as SPFieldUserValue); //string u = au == null ? string.Empty // : (au.User == null ? string.Empty : au.User.Name); if (item["WeChat61"] == null) { ret.AppendLine(string.Concat("主题:", item["Title"])); ret.AppendLine(string.Concat("作者:", author)); ret.AppendLine(string.Concat("修改时间", item["Modified"].ToString())); ret.AppendLine(string.Concat("回复数:", item["ItemChildCount"])); } else { ret.AppendLine(string.Concat("作者:", author)); ret.AppendLine(string.Concat("修改时间", item["Modified"].ToString())); ret.AppendLine(string.Concat("PicUrl", item["WeChat61"].ToString())); } ret.AppendLine(); lastTime = item["Modified"].ToString(); } //nextBeforeTime = lastTime; return(ret.ToString()); } else { //nextBeforeTime = string.Empty; return("已无更早留言"); } //SPList ImageLib = web.GetList(ImageLibUrl); //SPQuery qry = new SPQuery(); //qry.RowLimit = 1; //qry.Query = "<OrderBy Override=\"TRUE\"><FieldRef Name=\"Modified\" Ascending=\"FALSE\" /></OrderBy><Where>" // + "<Lt><FieldRef Name='Created'/><Value IncludeTimeValue='TRUE' Type='DateTime'>" // + SPUtility.CreateISO8601DateTimeFromSystemDateTime(beforetime) // + "</Value></Lt></Where>"; //qry.ViewFields = @"<FieldRef Name=""Author"" /><FieldRef Name=""Modified"" /><FieldRef Name=""WeChatPicUrl"" />"; } } } }
private void CopyNews(SPWeb web, string catID, string catName, string source) { var descValue = source.Split(new string[] { "<div class=\"new-desc\">" }, 2, StringSplitOptions.None)[1]; descValue = descValue.Split(new string[] { "</div>" }, 2, StringSplitOptions.None)[0]; var remainValue = source.Split(new string[] { "<div class=\"new-desc\">" }, 2, StringSplitOptions.None)[0]; var linkValue = remainValue.Split(new string[] { "href=" }, 2, StringSplitOptions.None)[1]; var imgValue = remainValue.Split(new string[] { "href=" }, 2, StringSplitOptions.None)[0]; var linkTitle = linkValue.Split(new string[] { ">" }, 2, StringSplitOptions.None)[1]; linkTitle = linkTitle.Split(new string[] { "</a>" }, 2, StringSplitOptions.None)[0]; linkValue = linkValue.Split(new string[] { ">" }, 2, StringSplitOptions.None)[0]; linkValue = linkValue.Replace("\"", "").Replace("'", ""); imgValue = imgValue.Split(new string[] { "src=" }, 2, StringSplitOptions.None)[1]; imgValue = imgValue.Split(new string[] { ">" }, 2, StringSplitOptions.None)[0]; imgValue = imgValue.Replace("\"", "").Replace("'", "").Replace("../", ""); imgValue = txtUrl.Text + "/" + imgValue; var newsID = linkValue.Split(new string[] { "&new=" }, 2, StringSplitOptions.None)[1]; linkValue = txtUrl.Text + "/sovp/news/new" + newsID + "/xxx"; var imgExt = imgValue.Split(new string[] { "." }, StringSplitOptions.None)[imgValue.Split('.').Length - 1]; var fileName = newsID + "." + imgExt; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(imgValue); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream receiveStream = response.GetResponseStream(); SPSecurity.RunWithElevatedPrivileges(() => { using (var site = new SPSite(web.Site.ID)) { using (var adminWeb = site.OpenWeb(web.ID)) { var imgUrl = string.Empty; using (MemoryStream stream = new MemoryStream()) { // Create a 4K buffer to chunk the file byte[] MyBuffer = new byte[4096]; int BytesRead; // Read the chunk of the web response into the buffer while (0 < (BytesRead = receiveStream.Read(MyBuffer, 0, MyBuffer.Length))) { // Write the chunk from the buffer to the file stream.Write(MyBuffer, 0, BytesRead); } var fuThumbName = string.Format(CultureInfo.InvariantCulture, "{0}_{1}", Utilities.GetPreByTime(DateTime.Now), fileName); SPFile file = Utilities.UploadFileToDocumentLibrary(web, stream, string.Format(CultureInfo.InvariantCulture, "{0}/{1}/{2}", WebUrl, ListsName.InternalName.NewsImagesList, fuThumbName)); imgUrl = file.Url; } var list = Utilities.GetCustomListByUrl(adminWeb, ListsName.InternalName.NewsList); var item = list.AddItem(); item[FieldsName.NewsList.InternalName.Title] = linkTitle; item[FieldsName.NewsList.InternalName.NewsGroup] = catID; item[FieldsName.NewsList.InternalName.NewsGroupName] = catName; item[FieldsName.NewsList.InternalName.Description] = descValue; item[FieldsName.NewsList.InternalName.ImageThumb] = imgUrl; if (!string.IsNullOrEmpty(imgUrl)) { SPFieldUrlValue imgDsp = new SPFieldUrlValue(); imgDsp.Description = item.Title; var webUrl = web.ServerRelativeUrl; if (webUrl.Equals("/")) { webUrl = ""; } imgDsp.Url = webUrl + "/" + imgUrl; item[FieldsName.NewsList.InternalName.ImageDsp] = imgDsp; } WebClient webClient = new WebClient(); byte[] reqHTML; reqHTML = webClient.DownloadData(linkValue); UTF8Encoding objUTF8 = new UTF8Encoding(); string detail = objUTF8.GetString(reqHTML); detail = detail.Split(new string[] { "<div class=\"new-detail-content\">" }, 2, StringSplitOptions.None)[1]; detail = detail.Split(new string[] { "<div id=\"new-reference\">" }, 2, StringSplitOptions.None)[0]; detail = detail.Substring(0, detail.Length - 6); item[FieldsName.NewsList.InternalName.Content] = detail; adminWeb.AllowUnsafeUpdates = true; item.Update(); } } }); }
/// <summary> /// 从文件直接读取文本,支持格式:rtf,txt,doc,docx /// </summary> /// <param name="filePath">文件路径</param> /// <returns></returns> public static string FileRead(string filePath) { string line = string.Empty; string tempDataStr = string.Empty; //try //{ //{ //FileStream aFile = new FileStream(filePath, FileMode.Open); //StreamReader sr = new StreamReader(aFile); //string str = sr.ReadToEnd(); //sr.Close(); SPSecurity.RunWithElevatedPrivileges(delegate() { if (filePath.Length > filePath.LastIndexOf(".", System.StringComparison.Ordinal)) { string fileTypeStr = filePath.Substring(filePath.LastIndexOf(".", System.StringComparison.Ordinal)); if (fileTypeStr == ".txt")//txt文件 { foreach (string lines in File.ReadLines(filePath, Encoding.Default)) { tempDataStr = tempDataStr + lines; //按行依次读取文件中数据 } } //else if (fileTypeStr == ".rtf")//rtf文件 //{ // tempDataStr = File.ReadAllText(filePath, Encoding.Default); //} //else if (fileTypeStr == ".doc" || fileTypeStr == ".docx")//word文件 //{ // try // { // Word.Application wApp = new Word.Application(); // Word.Document doc = null; // object unknow = Type.Missing; // wApp.Visible = false; // object file = filePath; // doc = wApp.Documents.Open(ref file, // ref unknow, ref unknow, ref unknow, ref unknow, // ref unknow, ref unknow, ref unknow, ref unknow, // ref unknow, ref unknow, ref unknow, ref unknow, // ref unknow, ref unknow, ref unknow); // for (int i = 0; i < doc.Paragraphs.Count; i++) // { // tempDataStr = tempDataStr + doc.Paragraphs[i].Range.Text.Trim(); // } // CloseFile(wApp); // QuitApp(wApp); // } // catch (Exception ex) // { // } //} else { tempDataStr = "你选择导入的文件格式不正确,仅支持导入.txt文件!"; } } else { tempDataStr = "文件路径格式不正确!"; } //} //} //catch //{ //} }); return(tempDataStr); }
protected void LoadTabSettings() { SPSecurity.RunWithElevatedPrivileges(delegate { using (SPSite objSite = new SPSite(SPContext.Current.Web.Url)) { using (SPWeb objWeb = objSite.OpenWeb()) { SPList list = objWeb.Lists[new Guid(Request.QueryString["List"])]; Tabs allTabs = Tabs.LoadTabs(Helper.GetConfigFile(list, Constants.ConfigFile.TabSettingFile)); if (allTabs != null) { DataTable tabsDataTable = createTabDataTable(); DataTable permissionDataTable = createPermissionDataTable(); DataTable permissionConditionDataTable = createConditionDataTable(); foreach (Tab tab in allTabs) { DataRow drTab = tabsDataTable.NewRow(); drTab[Constants.TabField.Index] = tab.Index; drTab[Constants.TabField.Title] = tab.Title; drTab[Constants.TabField.IsDefault] = tab.IsSelected; drTab[Constants.TabField.Description] = tab.Description; drTab[Constants.TabField.FieldToString] = tab.CommaSeperatedFields; drTab[Constants.TabField.FieldDisplayNameToString] = Helper.GetFieldDisplayNames(list, tab.CommaSeperatedFields); drTab[Constants.TabField.HasPermission] = (tab.Permissions.Count > 0); tabsDataTable.Rows.Add(drTab); foreach (TabPermission tabPermission in tab.Permissions) { DataRow drPermission = permissionDataTable.NewRow(); // Adding the tab row id for reference drPermission[Constants.PermissionField.TabRowID] = drTab[Constants.RowID]; drPermission[Constants.PermissionField.IsDefault] = tabPermission.IsDefault; drPermission[Constants.PermissionField.PermissionID] = (int)tabPermission.Level; drPermission[Constants.PermissionField.PermissionName] = Enums.DisplayString(tabPermission.Level); drPermission[Constants.PermissionField.SPPrinciples] = tabPermission.ForSPPrinciples; drPermission[Constants.PermissionField.SPPrinciplesOperatorID] = (int)tabPermission.BySPPrinciplesOperator; drPermission[Constants.PermissionField.SPPrinciplesOperatorName] = Enums.DisplayString(tabPermission.BySPPrinciplesOperator); drPermission[Constants.PermissionField.OnFormIDs] = tabPermission.FormsIdToString(); drPermission[Constants.PermissionField.OnFormNames] = tabPermission.FormsToString(); drPermission[Constants.PermissionField.HasCondition] = tabPermission.Conditions.ConditionsToString(list); permissionDataTable.Rows.Add(drPermission); foreach (Condition permCondition in tabPermission.Conditions) { if (!list.Fields.ContainsField(permCondition.OnField.SPName)) { continue; } DataRow drCondition = permissionConditionDataTable.NewRow(); drCondition[Constants.ConditionField.PermissionRowID] = drPermission[Constants.RowID]; drCondition[Constants.ConditionField.SPFieldName] = permCondition.OnField.SPName; drCondition[Constants.ConditionField.SPFieldDisplayName] = list.Fields.GetFieldByInternalName(permCondition.OnField.SPName).Title; drCondition[Constants.ConditionField.SPFieldOperatorID] = (int)permCondition.ByFieldOperator; drCondition[Constants.ConditionField.SPFieldOperatorName] = Enums.DisplayString(permCondition.ByFieldOperator); drCondition[Constants.ConditionField.Value] = permCondition.Value; permissionConditionDataTable.Rows.Add(drCondition); } PermissionConditionDataTable = permissionConditionDataTable; } TabPermissionDataTable = permissionDataTable; } TabDataTable = tabsDataTable; grdTabView.DataSource = tabsDataTable; grdTabView.DataBind(); } } } }); }
protected override void OnPagePreLoad(object sender, EventArgs e) { base.OnPagePreLoad(sender, e); this.DataBindings.Add(new TreeNodeBinding() { DataMember = "System.Data.DataRowView", TextField = "Text", ValueField = "Url" }); List <KlasifikacijaItem> _postavke = new List <KlasifikacijaItem>(); string cUrl = SPContext.Current.Web.Url; SPSecurity.RunWithElevatedPrivileges(() => { try { using (var site = new SPSite(cUrl)) { using (var web = site.OpenWeb()) { list = web.FindListByName(ListName ?? "Drevo"); if (list != null) { SPQuery query = new SPQuery() { ViewXml = "<View><Query><Where><Eq><FieldRef Name='Z' /><Value Type='Boolean'>0</Value></Eq></Where></Query></View>" }; var lic = list.GetItems(query); foreach (SPListItem li in lic) { var postavka = new KlasifikacijaItem() { ID = li.ID, Text = li["Title"].ToString() }; try { postavka.Url = new SPFieldUrlValue(li["Dokument"].ToString()).Url; } catch { } if (li["Nadrejeni"] != null) { var lID = new SPFieldLookupValue(li["Nadrejeni"].ToString()).LookupId; postavka.ParentID = lID; } _postavke.Add(postavka); } var sortedDataSet = _postavke.OrderBy(c => c.ParentID).ThenBy(c => c.Text).ToList().ToDataSet(); this.DataSource = new HierarchicalDataSet(sortedDataSet, "ID", "ParentID"); this.DataBind(); this.CollapseAll(); // expandanje specifičnega noda if (Page.Request.Cookies["XnetWikiNavigationExpNodes"] != null) { try { var currExpanded = Page.Request.Cookies["XnetWikiNavigationExpNodes"].Value.ToString(); var currExpNodes = currExpanded.Split('|'); if (currExpNodes.Length > 0) { var allNodes = this.Nodes.Cast <TreeNode>().SelectMany(GetNodeBranch).ToList(); foreach (var currExpNode in currExpNodes) { try { int currIndx = Int32.Parse(currExpNode); allNodes[currIndx].Expand(); } catch { } } } } catch { } } } } } } catch (Exception ex) { Logger.ToLog(ex, "Error WikiNavigation"); } }); }
protected void createTabXML() { bool isDefault = false; Tabs allTabs = new Tabs(); DataTable tabsDataTable = TabDataTable; DataTable permissionDataTable = TabPermissionDataTable; DataTable permissionConditionDataTable = PermissionConditionDataTable; foreach (DataRow drTab in tabsDataTable.Rows) { ushort index = Convert.ToUInt16(drTab[Constants.TabField.Index]); string title = drTab[Constants.TabField.Title].ToString(); string desc = drTab[Constants.TabField.Description].ToString(); bool isTabDefault = Helper.ConvertToBool(drTab[Constants.TabField.IsDefault].ToString()); int tabID = Convert.ToInt32(drTab[Constants.RowID]); Tab t1 = new Tab(index, title, desc); t1.CommaSeperatedFields = drTab[Constants.TabField.FieldToString].ToString(); t1.IsSelected = isTabDefault; DataTable permissionOfSelectedTab = Helper.GetViewFromDataTable(permissionDataTable, tabID, Constants.PermissionField.TabRowID).ToTable(); if (permissionOfSelectedTab != null && permissionOfSelectedTab.Rows.Count > 0) { foreach (DataRow drPermission in permissionOfSelectedTab.Rows) { bool IsDefault = Helper.ConvertToBool(drPermission[Constants.PermissionField.IsDefault].ToString()); Enums.PermissionLevel permissionLevel = (Enums.PermissionLevel)(Convert.ToInt32(drPermission[Constants.PermissionField.PermissionID].ToString())); string OnForms = drPermission[Constants.PermissionField.OnFormIDs].ToString(); string ForSPPrinciples = drPermission[Constants.PermissionField.SPPrinciples].ToString(); Enums.Operator BySPPrinciplesOperator = (Enums.Operator)(Convert.ToInt32(drPermission[Constants.PermissionField.SPPrinciplesOperatorID].ToString())); int permissionID = Convert.ToInt32(drPermission[Constants.RowID]); TabPermission perm1 = new TabPermission(isDefault, permissionLevel, TabPermission.ParseForms(OnForms), ForSPPrinciples, BySPPrinciplesOperator); DataTable conditionOfSelectedPermission = Helper.GetViewFromDataTable(permissionConditionDataTable, permissionID, Constants.ConditionField.PermissionRowID).ToTable(); if (conditionOfSelectedPermission != null && conditionOfSelectedPermission.Rows.Count > 0) { foreach (DataRow drCondition in conditionOfSelectedPermission.Rows) { string OnField = drCondition[Constants.ConditionField.SPFieldName].ToString(); Enums.Operator ByFieldOperator = (Enums.Operator)Convert.ToInt32(drCondition[Constants.ConditionField.SPFieldOperatorID].ToString()); object Value = drCondition[Constants.ConditionField.Value].ToString(); perm1.Conditions.Add(new Condition(new Field(OnField), ByFieldOperator, Value)); } } t1.Permissions.Add(perm1); } } allTabs.Add(t1); } SPSecurity.RunWithElevatedPrivileges(delegate { using (SPSite objSite = new SPSite(SPContext.Current.Web.Url.ToString())) { using (SPWeb objWeb = objSite.OpenWeb()) { SPList list = objWeb.Lists[new Guid(Request.QueryString["List"])]; objWeb.AllowUnsafeUpdates = true; string xml = allTabs.ToString(); if (allTabs.Count > 0 && Helper.IsValidXml(xml)) { Helper.CreateConfigFile(list, Constants.ConfigFile.TabSettingFile, xml); } else { Helper.DeleteConfigFile(list, Constants.ConfigFile.TabSettingFile, xml); } objWeb.AllowUnsafeUpdates = false; } } }); }
protected void Page_Load(object sender, EventArgs e) { Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Expires = -1; Response.ContentType = "text/xml"; Response.ContentEncoding = System.Text.Encoding.UTF8; using (SPWeb web = SPContext.Current.Web) { docXml = new XmlDocument(); docXml.LoadXml("<rows></rows>"); addHeader(); SPSecurity.RunWithElevatedPrivileges(delegate() { cn = new SqlConnection(EPMLiveCore.CoreFunctions.getConnectionString(web.Site.WebApplication.Id)); cn.Open(); }); SqlCommand cmd = new SqlCommand("spTSGetPeriodsInfo", cn); cmd.Parameters.AddWithValue("@siteid", SPContext.Current.Site.ID); cmd.CommandType = CommandType.StoredProcedure; SqlDataReader dr = cmd.ExecuteReader(); int lastperiodid = 1; bool lastperiodclosed = false; while (dr.Read()) { XmlNode ndRow = docXml.CreateNode(XmlNodeType.Element, "row", docXml.NamespaceURI); XmlAttribute attrId = docXml.CreateAttribute("id"); attrId.Value = dr.GetInt32(0).ToString(); ndRow.Attributes.Append(attrId); lastperiodclosed = dr.GetBoolean(3); lastperiodid = dr.GetInt32(0); XmlNode ndCell = docXml.CreateNode(XmlNodeType.Element, "cell", docXml.NamespaceURI); ndCell.InnerText = dr.GetDateTime(1).ToShortDateString(); ndRow.AppendChild(ndCell); ndCell = docXml.CreateNode(XmlNodeType.Element, "cell", docXml.NamespaceURI); ndCell.InnerText = dr.GetDateTime(2).ToShortDateString(); ndRow.AppendChild(ndCell); if (dr.GetBoolean(3)) { ndCell = docXml.CreateNode(XmlNodeType.Element, "cell", docXml.NamespaceURI); ndCell.InnerText = "Closed"; ndRow.AppendChild(ndCell); ndCell = docXml.CreateNode(XmlNodeType.Element, "cell", docXml.NamespaceURI); ndCell.InnerText = ""; ndRow.AppendChild(ndCell); ndCell = docXml.CreateNode(XmlNodeType.Element, "cell", docXml.NamespaceURI); ndCell.InnerText = "<a href=\"javascript:void(0);\" onclick=\"javascript:openPeriod('" + dr.GetInt32(0).ToString() + "');\">open</a>"; ndRow.AppendChild(ndCell); } else { ndCell = docXml.CreateNode(XmlNodeType.Element, "cell", docXml.NamespaceURI); ndCell.InnerText = "Open"; ndRow.AppendChild(ndCell); ndCell = docXml.CreateNode(XmlNodeType.Element, "cell", docXml.NamespaceURI); attrId = docXml.CreateAttribute("id"); attrId.Value = "del"; ndCell.Attributes.Append(attrId); ndRow.AppendChild(ndCell); ndCell = docXml.CreateNode(XmlNodeType.Element, "cell", docXml.NamespaceURI); ndCell.InnerText = "<a href=\"javascript:void(0);\" onclick=\"javascript:closePeriod('" + dr.GetInt32(0).ToString() + "');\">close</a>"; ndRow.AppendChild(ndCell); } ndCell = docXml.CreateNode(XmlNodeType.Element, "cell", docXml.NamespaceURI); ndCell.InnerText = dr.GetInt32(5) + " / " + dr.GetInt32(4); ndRow.AppendChild(ndCell); if (dr.GetInt32(4) > 0) { lastperiodclosed = true; } ndCell = docXml.CreateNode(XmlNodeType.Element, "cell", docXml.NamespaceURI); ndCell.InnerXml = "<![CDATA[<a href=\"" + web.Url + "/_layouts/epmlive/viewts.aspx?period_id=" + dr.GetInt32(0).ToString() + "\">view</a>]]>"; ndRow.AppendChild(ndCell); docXml.FirstChild.AppendChild(ndRow); } if (!lastperiodclosed) { XmlNode nd = docXml.SelectSingleNode("//row[@id='" + lastperiodid + "']/cell[@id='del']"); if (nd != null) { nd.InnerText = "<a href=\"javascript:void(0);\" onclick=\"deletePeriod('" + lastperiodid + "');\">delete</a>"; } } cn.Close(); outputXml(); } }
protected void Page_Load(object sender, EventArgs e) { //==================================Integration Menu================================= MenuTemplate propertyNameListMenu = new MenuTemplate(); propertyNameListMenu.ID = "IntegrationMenu"; MenuItemTemplate testMenu = new MenuItemTemplate("Edit Connection", "/_layouts/epmlive/images/integration/editcon.png"); testMenu.ClientOnClickNavigateUrl = "connection.aspx?intlistid=%INTLISTID%&LIST=%LISTID%&ret=Manage"; propertyNameListMenu.Controls.Add(testMenu); MenuItemTemplate testMenu2 = new MenuItemTemplate("Edit Properties", "/_layouts/images/edit.gif"); testMenu2.ClientOnClickNavigateUrl = "properties.aspx?intlistid=%INTLISTID%&LIST=%LISTID%&ret=Manage"; propertyNameListMenu.Controls.Add(testMenu2); MenuItemTemplate testMenu3 = new MenuItemTemplate("Edit Columns", "/_layouts/epmlive/images/integration/editcols.png"); testMenu3.ClientOnClickNavigateUrl = "columns.aspx?intlistid=%INTLISTID%&LIST=%LISTID%&ret=Manage"; propertyNameListMenu.Controls.Add(testMenu3); MenuItemTemplate testMenu4 = new MenuItemTemplate("View Log", "/_layouts/epmlive/images/integration/log.png"); testMenu4.ClientOnClickNavigateUrl = "log.aspx?intlistid=%INTLISTID%&LIST=%LISTID%&ret=Manage"; propertyNameListMenu.Controls.Add(testMenu4); MenuItemTemplate testMenu5 = new MenuItemTemplate("Delete Integration", "/_layouts/images/delete.gif"); testMenu5.ClientOnClickScript = "DeleteIntegration('%INTLISTID%');"; propertyNameListMenu.Controls.Add(testMenu5); this.Controls.Add(propertyNameListMenu); //=================================================================================== MenuTemplate propertyNameListMenu2 = new MenuTemplate(); propertyNameListMenu2.ID = "IntegrationGroupMenu"; MenuItemTemplate testMenu6 = new MenuItemTemplate("Add Integration", "/_layouts/images/add.gif"); testMenu6.ClientOnClickNavigateUrl = "Add.aspx?LIST=%LISTID%&ret=Manage"; propertyNameListMenu2.Controls.Add(testMenu6); MenuItemTemplate testMenu7 = new MenuItemTemplate("Edit Fields", "/_layouts/images/edit.gif"); testMenu7.ClientOnClickScript = "EditFields('%LISTID%')"; propertyNameListMenu2.Controls.Add(testMenu7); this.Controls.Add(propertyNameListMenu2); //=================================================================================== SPMenuField colMenu = new SPMenuField(); colMenu.HeaderText = ""; colMenu.TextFields = "ListName"; // GroupName field, bind to a List column colMenu.MenuTemplateId = "IntegrationGroupMenu"; colMenu.TokenNameAndValueFields = "LISTID=LIST_ID"; colMenu.SortExpression = "ListName"; colMenu.MenuFormat = MenuFormat.ArrowAlwaysVisible; gvIntegrations.GroupMenu = colMenu; SPSecurity.RunWithElevatedPrivileges(delegate() { var dataSet = new DataSet(); using (var connection = new SqlConnection(CoreFunctions.getConnectionString(Web.Site.WebApplication.Id))) { connection.Open(); using (var sqlCommand = new SqlCommand( @"SELECT dbo.INT_MODULES.Title, dbo.INT_MODULES.Description, dbo.INT_MODULES.Icon, dbo.INT_LISTS.INT_LIST_ID, dbo.INT_LISTS.LIST_ID, dbo.INT_LISTS.ACTIVE FROM dbo.INT_MODULES INNER JOIN dbo.INT_LISTS ON dbo.INT_MODULES.MODULE_ID = dbo.INT_LISTS.MODULE_ID where SITE_ID=@siteid", connection)) { sqlCommand.Parameters.AddWithValue("@siteid", Web.Site.ID); using (var sqlDataAdapter = new SqlDataAdapter(sqlCommand)) { sqlDataAdapter.Fill(dataSet); } } } DataTable dt = dataSet.Tables[0]; dt.Columns.Add("ListName"); Hashtable hshLists = new Hashtable(); ArrayList arrExists = new ArrayList(); ArrayList arrIgnore = new ArrayList(); foreach (SPList list in Web.Lists) { if (!list.Hidden) { hshLists.Add(list.ID, list.Title); } if (bIsSystemList(list.Title) || list.BaseType == SPBaseType.DocumentLibrary) { arrIgnore.Add(list.ID); } } foreach (DataRow dr in dt.Rows) { try { Guid ListId = new Guid(dr["LIST_ID"].ToString()); if (hshLists.Contains(ListId)) { dr["ListName"] = hshLists[ListId].ToString(); arrExists.Add(ListId); } } catch { } } foreach (DictionaryEntry de in hshLists) { if (!arrExists.Contains(de.Key) && !arrIgnore.Contains(de.Key)) { DataRow dr = dt.NewRow(); dr["List_Id"] = de.Key; dr["ListName"] = de.Value; dr["Title"] = "No Integrations"; dt.Rows.Add(dr); } } gvIntegrations.DataSource = dataSet; gvIntegrations.DataBind(); }); }
//заполнение компонентов вариантами для выбора или настройка для связи с источником данных protected override void OnLoad(EventArgs e) { EnsureChildControls(); if (ControlMode == SPControlMode.Display) { return; } if (_pickerEntityMode) { //настройка свойств EntityPicker'а для подключения к внешнему источнику данных var editorData = new CustomExternalLookupData { ConnectionString = _connString, QueryString = string.IsNullOrEmpty(QueryString) ? _queryString : QueryString }; _entityEditor.PickerData = editorData; _entityEditor.Enabled = ExecuteQuery; } else { if (ExecuteQuery) { if (!Page.IsPostBack || _queryStringChanged) { var dm = new DataManager(_connString, string.IsNullOrEmpty(QueryString) ? _queryString : QueryString); DataTable records = null; SPSecurity.RunWithElevatedPrivileges(() => records = dm.GetRecords()); if (MultiSelectMode) { _leftListBox.Items.Clear(); foreach (DataRow rec in records.Rows) { var newListItem = new ListItem { Value = rec["ID"].ToString(), Text = rec["Value"].ToString() }; _leftListBox.Items.Add(newListItem); } _leftListBox.Enabled = _rightListBox.Enabled = true; } else { _dropDownList.Items.Clear(); foreach (DataRow row in records.Rows) { _dropDownList.Items.Add(new ListItem(row["Value"].ToString(), row["ID"].ToString())); } if (!Field.Required) { _dropDownList.Items.Insert(0, new ListItem("(нет)", string.Empty)); } _dropDownList.Enabled = true; } } } else { if (MultiSelectMode) { _leftListBox.Items.Clear(); _rightListBox.Items.Clear(); _rightListBoxValues.Value = ""; _leftListBox.Enabled = _rightListBox.Enabled = false; } else { _dropDownList.Items.Clear(); _dropDownList.Enabled = false; } } } if (MultiSelectMode && !_pickerEntityMode) { //проверка того, что в поле множественного выбора выбраны только допустимые значения string[] valuesSplit = _rightListBoxValues.Value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (valuesSplit.Any(val => _leftListBox.Items.FindByValue(val) == null)) { throw new SPException("Выбрано недопустимое значение"); } //обновление атрибутов title для options select'а AddTitlesToListBoxItems(_leftListBox.Items); } base.OnLoad(e); }
private void StatisticList(SPUser logUser) { string[] lstName = ListName.Split(';'); SPQuery oQuery; SPList sList; int[] itmCounts = new int[4]; SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(SPContext.Current.Site.ID)) { using (SPWeb web = site.AllWebs[SPContext.Current.Web.ID]) { //设置sharepoint时间格式 SPTimeZone timeZone = web.RegionalSettings.TimeZone; foreach (string mList in lstName) { try { sList = web.Lists.TryGetList(mList); 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 qDate = currentDate.AddDays(-1); DateTime cDate = timeZone.LocalTimeToUTC(currentDate); string dt = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Parse(cDate.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'>" + dt + "</Value></Geq><And/></Where>"; lstItems = sList.GetItems(oQuery); itmCounts[2] = lstItems.Count;//当日更新 qDate = currentDate.AddDays(-7); cDate = timeZone.LocalTimeToUTC(currentDate); dt = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Parse(cDate.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'>" + dt + "</Value></Geq><And/></Where>"; lstItems = sList.GetItems(oQuery); itmCounts[3] = lstItems.Count;//本周更新 this.Controls.Add(new LiteralControl(mList + "<br/>")); this.Controls.Add(new LiteralControl("个人总数 : " + itmCounts[0].ToString() + "<br/>")); this.Controls.Add(new LiteralControl("团队总数 : " + itmCounts[1].ToString() + "<br/>")); this.Controls.Add(new LiteralControl("当日更新 : " + itmCounts[2].ToString() + "<br/>")); this.Controls.Add(new LiteralControl("本周总数 : " + itmCounts[3].ToString() + "<br/>")); } catch { } } } } } ); }
protected void Page_Load(object sender, EventArgs e) { SqlConnection cn = null; SPSecurity.RunWithElevatedPrivileges(delegate() { cn = new SqlConnection(EPMLiveCore.CoreFunctions.getConnectionString(SPContext.Current.Site.WebApplication.Id)); cn.Open(); }); if (cn != null) { SPWeb web = SPContext.Current.Web; string resUrl = EPMLiveCore.CoreFunctions.getConfigSetting(web, "EPMLiveResourceURL", true, false); if (resUrl != "") { SPWeb resWeb = null; try { if (resUrl.ToLower() != web.Url.ToLower()) { using (SPSite tempSite = new SPSite(resUrl)) { resWeb = tempSite.OpenWeb(); if (resWeb.Url.ToLower() != resUrl.ToLower()) { resWeb = null; } } } else { resWeb = web; } } catch { } if (resWeb != null) { switch (Request["Report"]) { case "1": try { SPList list = resWeb.Lists["Resources"]; SPQuery query = new SPQuery(); query.Query = "<Where><Eq><FieldRef Name='TimesheetManager'/><Value Type='User'><UserID/></Value></Eq></Where>"; SPListItemCollection lic = list.GetItems(query); foreach (SPListItem li in lic) { string username = ""; string name = ""; try { string user = li["SharePointAccount"].ToString(); SPFieldUserValue uv = new SPFieldUserValue(resWeb, user); username = uv.User.LoginName; name = uv.User.Name; } catch { } if (username != "") { SqlCommand cmd = new SqlCommand("spTSData", cn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@siteuid", web.Site.ID); cmd.Parameters.AddWithValue("@username", username); cmd.Parameters.AddWithValue("@start", Request["start"]); cmd.Parameters.AddWithValue("@end", Request["end"]); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dttemp = new DataTable(); da.Fill(dttemp); dtRollup.Merge(dttemp, false, MissingSchemaAction.Add); } } } catch { } break; case "2": try { SPList list = resWeb.Lists["Resources"]; SPQuery query = new SPQuery(); query.Query = "<Where><Eq><FieldRef Name='SharePointAccount'/><Value Type='User'><UserID/></Value></Eq></Where>"; SPListItemCollection lic = list.GetItems(query); if (lic.Count > 0) { try { if (lic[0]["TimesheetAdministrator"].ToString().ToLower() == "true") { foreach (SPListItem li in list.Items) { string username = ""; string name = ""; try { string user = li["SharePointAccount"].ToString(); SPFieldUserValue uv = new SPFieldUserValue(resWeb, user); username = uv.User.LoginName; name = uv.User.Name; } catch { } if (username != "") { SqlCommand cmd = new SqlCommand("spTSData", cn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@siteuid", web.Site.ID); cmd.Parameters.AddWithValue("@username", username); cmd.Parameters.AddWithValue("@start", Request["start"]); cmd.Parameters.AddWithValue("@end", Request["end"]); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dttemp = new DataTable(); da.Fill(dttemp); dtRollup.Merge(dttemp, false, MissingSchemaAction.Add); } } } } catch { } } } catch { } break; case "3": try { SPList list = resWeb.Lists["Resources"]; SPQuery query = new SPQuery(); query.Query = "<Where><Eq><FieldRef Name='SharePointAccount'/><Value Type='User'><UserID/></Value></Eq></Where>"; SPListItemCollection lic = list.GetItems(query); if (lic.Count > 0) { try { foreach (SPListItem li in lic) { string username = ""; string name = ""; try { string user = li["SharePointAccount"].ToString(); SPFieldUserValue uv = new SPFieldUserValue(resWeb, user); username = uv.User.LoginName; name = uv.User.Name; } catch { } if (username != "") { SqlCommand cmd = new SqlCommand("spTSData", cn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@siteuid", web.Site.ID); cmd.Parameters.AddWithValue("@username", username); cmd.Parameters.AddWithValue("@start", Request["start"]); cmd.Parameters.AddWithValue("@end", Request["end"]); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dttemp = new DataTable(); da.Fill(dttemp); dtRollup.Merge(dttemp, false, MissingSchemaAction.Add); } } } catch { } } } catch { } break; } ; if (resWeb.ID != SPContext.Current.Web.ID) { resWeb.Close(); } } } cn.Close(); listGrid.DataSource = dtRollup; listGrid.DataBind(); } }
public void StartRefresh(Guid timerjobguid, out DataTable dtResults, bool refreshAll) { DataTable dt = InitializeResultsDT(_sListNames, refreshAll); string _errorListName = string.Empty; try { SPList spList = null; string sSiteIdListName = string.Empty; SPSecurity.RunWithElevatedPrivileges(delegate { using (_web) { if (refreshAll) { // we need to refresh work hours // and resources first because // SPProcessAssignments depends on data in LSTWorkHours and LSTResources #region refresh work hours list SPList lworkhours = _web.Lists.TryGetList("Work Hours"); //if (lworkhours == null) //{ // _DAO.LogStatus( // string.Empty, // string.Empty, // "Work Hours list does not exist at web: " + _web.ID + ".", // "Work Hours list does not exist at web: " + _web.ID + ".", // 2, // 3, // timerjobguid.ToString()); //} // if a reporting list if (lworkhours != null && IsReportingList("Work Hours")) { try { _errorListName = "Work Hours"; //Clear out dataset _dsLists = new DataSet(); _dsMyWorkLists = new DataSet(); spList = null; _sTableName = _DAO.GetTableName(lworkhours.ID); _siteID = _web.ID; //Add sSiteIdListName string to array, that will be used to create dyn. sql to do a batch delete _ArrayListTableNames.Add(_sTableName); //throw new System.InvalidOperationException("exeception handling test"); bool error; string sErrMsg; AddItems(timerjobguid, lworkhours.Title, out error, out sErrMsg); //Add all current list items to the database (from the corresponding sharepoint list) if (error) { DataRow[] dr = dt.Select("ListName='" + lworkhours.Title + "'"); if (sErrMsg.ToLower().Contains("does not exist at site with url")) { if (dr[0]["ResultText"] == null) { dr[0]["ResultText"] = " " + "List not present."; } else { dr[0]["ResultText"] = dr[0]["ResultText"] + " " + "List not present."; } } else { if (dr[0]["ResultText"] == null) { dr[0]["ResultText"] = " " + sErrMsg; } else { dr[0]["ResultText"] = dr[0]["ResultText"] + " " + sErrMsg; } } } } catch (Exception ex) { DataRow[] dr = dt.Select("ListName='" + lworkhours.Title + "'"); if (ex.Message.ToLower().Contains("does not exist at site with url")) { } else { if (dr[0]["ResultText"] == null) { dr[0]["ResultText"] = " " + ex.Message; } else { dr[0]["ResultText"] = dr[0]["ResultText"] + " " + ex.Message; } } } if (_dsLists.Tables.Count > 0) { _DAO.InsertAllItemsDB(_dsLists, timerjobguid); } } #endregion // refresh work hours list #region refresh resources list SPList lResource = _web.Lists.TryGetList("Resources"); //if (lResource == null) //{ // _DAO.LogStatus( // string.Empty, // string.Empty, // "Resources list does not exist at web: " + _web.ID + ".", // "Resources list does not exist at web: " + _web.ID + ".", // 2, // 3, // timerjobguid.ToString()); //} // if a reporting list if (lResource != null && IsReportingList("Resources")) { try { _errorListName = "Resources"; //Clear out dataset _dsLists = new DataSet(); _dsMyWorkLists = new DataSet(); spList = null; _sTableName = _DAO.GetTableName(lResource.Title); _siteID = _web.ID; //Add sSiteIdListName string to array, that will be used to create dyn. sql to do a batch delete _ArrayListTableNames.Add(_sTableName); //throw new System.InvalidOperationException("exeception handling test"); bool error; string sErrMsg; AddItems(timerjobguid, lResource.Title, out error, out sErrMsg); //Add all current list items to the database (from the corresponding sharepoint list) if (error) { DataRow[] dr = dt.Select("ListName='" + lResource.Title + "'"); if (sErrMsg.ToLower().Contains("does not exist at site with url")) { if (dr[0]["ResultText"] == null) { dr[0]["ResultText"] = " " + "List not present."; } else { dr[0]["ResultText"] = dr[0]["ResultText"] + " " + "List not present."; } } else { if (dr[0]["ResultText"] == null) { dr[0]["ResultText"] = " " + sErrMsg; } else { dr[0]["ResultText"] = dr[0]["ResultText"] + " " + sErrMsg; } } } } catch (Exception ex) { DataRow[] dr = dt.Select("ListName='" + lResource.Title + "'"); if (ex.Message.ToLower().Contains("does not exist at site with url")) { } else { if (dr[0]["ResultText"] == null) { dr[0]["ResultText"] = " " + ex.Message; } else { dr[0]["ResultText"] = dr[0]["ResultText"] + " " + ex.Message; } } } if (_dsLists.Tables.Count > 0) { _DAO.InsertAllItemsDB(_dsLists, timerjobguid); } } #endregion // refresh work hours list #region refresh all var allLists = new List <string>(_sListNames.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)); var allSpLists = new List <SPList>(); foreach (string l in allLists) { SPList list = _web.Lists.TryGetList(l); if (list != null) { allSpLists.Add(list); } if (list == null || list.Title == "Work Hours" || list.Title == "Resources") { continue; } _errorListName = list.Title; //Clear out dataset _dsLists = new DataSet(); _dsMyWorkLists = new DataSet(); // if a mywork list var settings = new GridGanttSettings(list); if (settings.EnableWorkList) { try { _sTableName = "LSTMyWork"; _siteID = _web.ID; bool error; string sErrMsg; AddItems_MyWork(timerjobguid, list.Title, list.ID, out error, out sErrMsg); HandleError(error, dt, list, sErrMsg); } catch (Exception ex) { DataRow[] dr = dt.Select("ListName='" + list.Title + "'"); if (ex.Message.ToLower().Contains("does not exist at site with url")) { } else { if (dr[0]["ResultText"] == null) { dr[0]["ResultText"] = " " + ex.Message; } else { dr[0]["ResultText"] = dr[0]["ResultText"] + " " + ex.Message; } } } if (_dsMyWorkLists.Tables.Count > 0) { _DAO.InsertAllItemsDB(_dsMyWorkLists, timerjobguid); } } // if a reporting list if (IsReportingList(list.Title)) { try { spList = null; _sTableName = _DAO.GetTableName(list.ID); _siteID = _web.ID; //Add sSiteIdListName string to array, that will be used to create dyn. sql to do a batch delete _ArrayListTableNames.Add(_sTableName); //throw new System.InvalidOperationException("exeception handling test"); bool error; string sErrMsg; AddItems(timerjobguid, list.Title, out error, out sErrMsg); //Add all current list items to the database (from the corresponding sharepoint list) HandleError(error, dt, list, sErrMsg); } catch (Exception ex) { DataRow[] dr = dt.Select("ListName='" + list.Title + "'"); if (ex.Message.ToLower().Contains("does not exist at site with url")) { } else { if (dr[0]["ResultText"] == null) { dr[0]["ResultText"] = " " + ex.Message; } else { dr[0]["ResultText"] = dr[0]["ResultText"] + " " + ex.Message; } } } if (_dsLists.Tables.Count > 0) { _DAO.InsertAllItemsDB(_dsLists, timerjobguid); } } } #endregion // refresh all lists #region refresh security groups for all lists try { ProcessSecurity.ProcessSecurityOnRefreshAll(_web, allSpLists, _DAO.GetClientReportingConnection()); _DAO.LogStatus( string.Empty, string.Empty, "ProcessSecurity processed successfully on refresh all for web: " + _web.Title, "ProcessSecurity processed successfully on refresh all for web: " + _web.Title, 0, 1, timerjobguid.ToString()); } catch (Exception ex) { _DAO.LogStatus( string.Empty, string.Empty, "ProcessSecurity failed on refresh all.", ex.Message, 2, 3, timerjobguid.ToString()); } #endregion } else { #region refreshing individual lists //loop thru all lists foreach (string sListName in _ArrayListNames) { try { _errorListName = sListName; //set to null spList = null; //Init. list spList = _web.Lists[sListName]; //Init. list sqltable name _sTableName = _DAO.GetTableName(spList.ID);//_DAO.GetTableName(sListName); //Init. web id _siteID = _web.ID; //Add sSiteIdListName string to array, that will be used to create dyn. sql to do a batch delete _ArrayListTableNames.Add(_sTableName); //Delete items in LSTMyWork associated to this list, then re-add var settings = new GridGanttSettings(spList); if (settings.EnableWorkList) { _DAO.DeleteMyWork(spList.ID); try { _sTableName = "LSTMyWork"; _siteID = _web.ID; bool bError; string sErr; AddItems_MyWork(timerjobguid, spList.Title, spList.ID, out bError, out sErr); if (bError) { DataRow[] dr = dt.Select("ListName='" + spList.Title + "'"); if (sErr.ToLower().Contains("does not exist at site with url")) { if (dr[0]["ResultText"] == null) { dr[0]["ResultText"] = " " + "List not present."; } else { dr[0]["ResultText"] = dr[0]["ResultText"] + " " + "List not present."; } } else { if (dr[0]["ResultText"] == null) { dr[0]["ResultText"] = " " + sErr; } else { dr[0]["ResultText"] = dr[0]["ResultText"] + " " + sErr; } } } } catch (Exception ex) { DataRow[] dr = dt.Select("ListName='" + spList.Title + "'"); if (ex.Message.ToLower().Contains("does not exist at site with url")) { } else { if (dr[0]["ResultText"] == null) { dr[0]["ResultText"] = " " + ex.Message; } else { dr[0]["ResultText"] = dr[0]["ResultText"] + " " + ex.Message; } } } if (_dsMyWorkLists.Tables.Count > 0) { _DAO.InsertAllItemsDB(_dsMyWorkLists, timerjobguid); } } //throw new System.InvalidOperationException("exeception handling test"); bool error; string sErrMsg; _sTableName = _DAO.GetTableName(spList.ID); AddItems(timerjobguid, sListName, out error, out sErrMsg); //Add all current list items to the database (from the corresponding sharepoint list) //AddItems(timerjobguid,sListName); if (error) { DataRow[] dr = dt.Select("ListName='" + sListName + "'"); if (sErrMsg.ToLower().Contains("does not exist at site with url")) { if (dr[0]["ResultText"] == null) { dr[0]["ResultText"] = " " + "List not present."; } else { dr[0]["ResultText"] = dr[0]["ResultText"] + " " + "List not present."; } } else { if (dr[0]["ResultText"] == null) { dr[0]["ResultText"] = " " + sErrMsg; } else { dr[0]["ResultText"] = dr[0]["ResultText"] + " " + sErrMsg; } } } } catch (Exception ex) { DataRow[] dr = dt.Select("ListName='" + sListName + "'"); if (ex.Message.ToLower().Contains("does not exist at site with url")) { //DO NOTHING... //if (dr[0]["ResultText"] == null) //{ // dr[0]["ResultText"] = " " + "List not present."; //} //else //{ // dr[0]["ResultText"] = dr[0]["ResultText"] + " " + "List not present."; //} } else { if (dr[0]["ResultText"] == null) { dr[0]["ResultText"] = " " + ex.Message; } else { dr[0]["ResultText"] = dr[0]["ResultText"] + " " + ex.Message; } } } #region refresh security groups for list try { if (spList != null) { ProcessSecurity.ProcessSecurityOnListRefresh(_web, spList, _DAO.GetClientReportingConnection()); _DAO.LogStatus( string.Empty, string.Empty, "ProcessSecurity processed successfully on list: " + spList.Title + " in web: " + _web.Title, "ProcessSecurity processed successfully on list: " + spList.Title + " in web: " + _web.Title, 0, 1, timerjobguid.ToString()); } } catch (Exception ex) { DataRow[] dr = dt.Select("ListName='" + sListName + "'"); if (dr[0]["ResultText"] == null) { dr[0]["ResultText"] = " " + ex.Message; } else { dr[0]["ResultText"] = dr[0]["ResultText"] + " " + ex.Message; } } #endregion } if (_dsLists.Tables.Count > 0) { _DAO.InsertAllItemsDB(_dsLists, timerjobguid); } #endregion } } }); } catch (Exception ex) { _DAO.LogStatus(string.Empty, string.Empty, "Refresh not completed due to error. Web: " + _web.Title + ". List: " + _errorListName + ". Error: " + ex.Message, ex.StackTrace, 2, 3, timerjobguid.ToString()); } _DAO.Dispose(); dtResults = dt; }
/// <summary> /// Get activated features from farm and build up SharePointParentHierarchy /// </summary> private void LoadAllActivatedFeaturesAndHierarchy() { SPSecurity.RunWithElevatedPrivileges(delegate() { var farm = FarmRead.GetFarm(); // Get Farm features var farmFeatures = farm.Features; var parent = FeatureParent.GetFeatureParent(farm); FarmId = parent.Id; SharePointParentHierarchy.Add(FarmId, new List <FeatureParent>()); Parents.Add(parent); if (farmFeatures != null) { var activatedFarmFeatures = ActivatedFeature.MapSpFeatureToActivatedFeature(farmFeatures, parent); ActivatedFeatures.AddRange(activatedFarmFeatures); } // Get Web App features var adminWebApps = FarmRead.GetWebApplicationsAdmin(); // Central Admin var caIndex = 1; foreach (SPWebApplication adminApp in adminWebApps) { if (adminApp != null) { var index = (adminApp.Features.Count == 1 && caIndex == 1) ? string.Empty : " " + caIndex.ToString(); var caParent = FeatureParent.GetFeatureParent(adminApp, "Central Admin" + index); AddParentToHierarchyAndParentsList(FarmId, caParent, true); var adminFeatures = adminApp.Features; if (adminFeatures != null && adminFeatures.Count > 0) { var activatedCaWebAppFeatures = ActivatedFeature.MapSpFeatureToActivatedFeature(adminFeatures, caParent); ActivatedFeatures.AddRange(activatedCaWebAppFeatures); } var sites = adminApp.Sites; if (sites != null && sites.Count > 0) { foreach (SPSite s in sites) { GetSiteFeatuesAndBelow(s, caParent.Id); s.Dispose(); } } } } // Content Web Apps var contentWebApps = FarmRead.GetWebApplicationsContent(); foreach (SPWebApplication webApp in contentWebApps) { if (webApp != null) { var waAsParent = FeatureParent.GetFeatureParent(webApp); AddParentToHierarchyAndParentsList(FarmId, waAsParent, true); var waFeatures = webApp.Features; if (waFeatures != null && waFeatures.Count > 0) { var activatedWebAppFeatures = ActivatedFeature.MapSpFeatureToActivatedFeature(waFeatures, waAsParent); ActivatedFeatures.AddRange(activatedWebAppFeatures); } var sites = webApp.Sites; if (sites != null && sites.Count > 0) { foreach (SPSite s in sites) { GetSiteFeatuesAndBelow(s, waAsParent.Id); s.Dispose(); } } } } }); }
protected override void Render(HtmlTextWriter writer) { try { int LCID = HttpContext.Current.Request.Url.Segments.Contains("fra/") ? 1036 : 1033;// System.Threading.Thread.CurrentThread.CurrentUICulture.LCID; System.Text.StringBuilder sb = new StringBuilder(); SPSecurity.RunWithElevatedPrivileges(delegate() { SPListItemCollection collListItems; SPList footerList = SPContext.Current.Site.RootWeb.Lists.TryGetList("LACFooterLinks"); SPQuery oQuery = new SPQuery(); if (LCID == 1036) { oQuery.Query = "<Where><IsNotNull><FieldRef Name='ID'/></IsNotNull></Where>" + "<OrderBy><FieldRef Name='EnglishOrder' /></OrderBy>"; } else { oQuery.Query = "<Where><IsNotNull><FieldRef Name='ID'/></IsNotNull></Where>" + "<OrderBy><FieldRef Name='FrenchOrder' /></OrderBy>"; } if (footerList != null) { collListItems = footerList.GetItems(oQuery); if (collListItems != null) { int i = 1; sb.Append("<ul class=\"float-right\">"); foreach (SPListItem item in collListItems) { sb.Append("<li>"); if (LCID == 1033) { sb.Append("<a class=\"footerFontClass\" href=\"" + item["English Url"] + "\">" + item["English Link Text"] + "</a>"); } else { sb.Append("<a class=\"footerFontClass\" href=\"" + item["French Url"] + "\">" + item["French Link Text"] + "</a>"); } if (i != collListItems.Count) { sb.Append(" "); } sb.Append("</li>"); } sb.Append("</ul>"); } writer.Write(sb.ToString()); } }); } catch (Exception ex) { writer.Write("oTech.Lac.Intranet.WebControls: FooterLinks exception message: " + ex.ToString()); } }
public IQueryable <DictionaryEntry> SelectTemplates() { List <DictionaryEntry> result = new List <DictionaryEntry>(); using (new SPMonitoredScope("Mailing SelectTemplates")) { if (SPContext.Current.Web.CurrentUser != null) { 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; SPFolder Templates = null; SPFile Aanmelden = null; XElement 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"]; } if (Templates != null && Templates.Exists) { Aanmelden = Templates.Files["template.xsl"]; } if (Aanmelden != null && Aanmelden.Exists) { template = XElement.Load(Aanmelden.OpenBinaryStream()); } if (template == null) { throw new FileNotFoundException("Template not Found", Aanmelden.Url); } IQueryable <string> names = template.Elements("{http://www.w3.org/1999/XSL/Transform}template").Where(temp => temp.Attribute("match") != null && temp.Attribute("match").Value != "/").Select(temp => temp.Attribute("match").Value).AsQueryable(); foreach (string name in names) { result.Add(new DictionaryEntry(name, name)); } } } } catch (Exception ex) { Logger.WriteLog(Logger.Category.Unexpected, ex.Source, ex.Message); } }); return(result.AsQueryable <DictionaryEntry>()); } } return(null); }
public static void ListOpElevated(string webUrl, string listName, Action <SPList> listOp) { SPSecurity.RunWithElevatedPrivileges(() => ListOp(webUrl, listName, listOp)); }