private void WriteExportStatus(SPWorkItem workItem, ExportStatus status) { lock (_writeLock) { if (workItem != null) { using (SPSite site = new SPSite(workItem.SiteId)) { using (SPWeb web = site.OpenWeb(workItem.WebId)) { try { SPList exportsList = web.Lists[workItem.ParentId]; SPListItem exportItem = exportsList.GetItemByUniqueId(workItem.ItemGuid); if (exportItem != null) { exportItem["ExportStatus"] = status.ToString(); exportItem.SystemUpdate(true); } } catch (Exception ex) { //failed to write ExportStatus } } } } } }
public static SurveyTemplateAdmin GetAdminTemplate(string pstrList, Guid pguidTemplate) { SurveyTemplateAdmin stThis = null; SPWeb web = SPContext.Current.Web; { try { SPList lst = web.Lists.TryGetList(pstrList); if (lst != null) { SPListItem lsi = lst.GetItemByUniqueId(pguidTemplate); return(new SurveyTemplateAdmin(lsi)); } } catch (Exception ex) { throw ex; } } return(stThis); }
public static SurveyTemplate GetTemplate(string pstrList, Guid pguidTemplate) { SurveyTemplate stThis = null; SPWeb web = SPContext.Current.Web; { try { SPList lst = web.Lists.TryGetList(pstrList); if (lst != null) { SPListItem lsi = lst.GetItemByUniqueId(pguidTemplate); JavaScriptSerializer ser = new JavaScriptSerializer(new SimpleTypeResolver()); stThis = new SurveyTemplate(); stThis.Title = lsi.Title; stThis.TemplateID = lsi.UniqueId; stThis = ser.Deserialize <SurveyTemplate>(lsi["QuestionData"].ToString()); } } catch (Exception ex) { throw ex; } } return(stThis); }
private void LogMessage(SPWorkItem workItem, string logMessage, params object[] formatTokens) { lock (_writeLock) { if (workItem != null) { using (SPSite site = new SPSite(workItem.SiteId)) { using (SPWeb web = site.OpenWeb(workItem.WebId)) { try { SPList exportsList = web.Lists[workItem.ParentId]; SPListItem exportItem = exportsList.GetItemByUniqueId(workItem.ItemGuid); if (exportItem != null) { exportItem["LogMessages"] = string.Format(logMessage, formatTokens); exportItem.Update(); } } catch (Exception ex) { //failed to write log message } } } } } }
public static SurveyScoreCard GetSurveyScoreCard(string pstrList, Guid pguidScoreCard) { SurveyScoreCard sscThis = null; SPWeb web = SPContext.Current.Web; { try { SPList lst = web.Lists.TryGetList(pstrList); if (lst != null) { SPListItem lsi = null; lsi = lst.GetItemByUniqueId(pguidScoreCard); JavaScriptSerializer ser = new JavaScriptSerializer(); sscThis = ser.Deserialize <SurveyScoreCard>(lsi["ScoreCardData"].ToString()); } } catch (Exception ex) { throw ex; } } return(sscThis); }
private SurveyResponse GetResponse(HttpContext context) { SurveyResponse rspReturn = new SurveyResponse(); if (context.Request["List"] != null && context.Request["ResponseID"] != null) { using (SPWeb web = SPContext.Current.Web) { try { SPList lst = web.Lists.TryGetList(context.Request["List"]); Guid guidResponse = new Guid(context.Request["ResponseID"]); if (lst != null) { SPListItem lsi = lst.GetItemByUniqueId(guidResponse); rspReturn = new SurveyResponse(lsi); } } catch (Exception ex) { context.Response.StatusCode = 500; context.Response.StatusDescription = "DWF Survey: " + ex.Message; } } } return(rspReturn); }
private void ExportMetadata(object sender, EventArgs e) { ControlHelper ch = (ControlHelper)lbItems.SelectedItem; SPListItem item = CurrentList.GetItemByUniqueId(ch.UniqueID); string filename = item.Name.Substring(0, item.Name.LastIndexOf(".")); string path = @"d:\" + filename + ".txt"; FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write); StreamWriter sw = new StreamWriter(file); sw.WriteLine("Metadata for: " + item.Name); sw.WriteLine("-----------"); foreach (SPField fld in item.Fields) { object value = null; if (item[fld.Title] == null) { value = "Not Set"; } else { value = item[fld.Title]; } sw.WriteLine("Feld: " + fld.Title); sw.WriteLine("Wert: " + value.ToString()); } sw.Close(); MessageBox.Show("Metadata written"); }
// Удаляем файл private void deleteFile() { // Получаем элемент из библиотеки документов по UniqueID и удаляем его SPWeb web = SPContext.Current.Site.RootWeb; SPList list = web.GetList(SPUrlUtility.CombineUrl(web.ServerRelativeUrl, libraryName)); SPListItem spFileItem = list.GetItemByUniqueId(currentFile.UniqueID); spFileItem.Delete(); }
private SurveyScoreCard SaveScoreCard(HttpContext context) { string strList = context.Request["List"] == null ? mcstrScoreCardList : context.Request["List"]; SurveyScoreCard sscReturn = new SurveyScoreCard(); try { if (context.Request["ScoreCardData"] != null) { JavaScriptSerializer ser = new JavaScriptSerializer(); sscReturn = ser.Deserialize <SurveyScoreCard>(context.Request["ScoreCardData"]); using (SPWeb web = SPContext.Current.Web) { SPList lst = web.Lists.TryGetList(strList); if (lst != null) { SPListItem lsi; if (sscReturn.ID == Guid.Empty) { lsi = lst.Items.Add(); } else { lsi = lst.GetItemByUniqueId(sscReturn.ID); } lsi["Title"] = sscReturn.Name; lsi["ScoreCardData"] = ser.Serialize(sscReturn); web.AllowUnsafeUpdates = true; lsi.Update(); web.AllowUnsafeUpdates = false; } else { context.Response.StatusCode = 500; context.Response.StatusDescription = "DWF Survey: Scorecard List not found"; } } } else { context.Response.StatusCode = 500; context.Response.StatusDescription = "DWF Survey: Scorecard data not found"; } } catch (Exception ex) { context.Response.StatusCode = 500; context.Response.StatusDescription = "DWF Survey: " + ex.Message; } return(sscReturn); }
public void ExportFile(ControlWrapper wrapper, string folder) { SPListItem item = List.GetItemByUniqueId(wrapper.UniqueID); if (item.FileSystemObjectType == SPFileSystemObjectType.File) { string destFile = folder + "\\" + item.File.Name; Stream input = item.File.OpenBinaryStream(); ExportStream(destFile, input); } }
private SurveyTemplate SaveTemplate(HttpContext context) { SurveyTemplate stThis = null; string strList = context.Request["List"] == null ? mcstrTemplateList : context.Request["List"]; try { if (context.Request.Form.Count > 0) { if (true) { JavaScriptSerializer ser = new JavaScriptSerializer(new SimpleTypeResolver()); stThis = ser.Deserialize <SurveyTemplate>(context.Request.Form[0].ToString()); using (SPWeb web = SPContext.Current.Web) { SPList lst = web.Lists.TryGetList(strList); if (lst != null) { SPListItem lsi; if (stThis.TemplateID == Guid.Empty) { lsi = lst.Items.Add(); } else { lsi = lst.GetItemByUniqueId(stThis.TemplateID); } lsi["Title"] = stThis.Title; lsi["QuestionData"] = ser.Serialize(stThis); web.AllowUnsafeUpdates = true; lsi.Update(); web.AllowUnsafeUpdates = false; } } } } else { context.Response.StatusCode = 500; context.Response.StatusDescription = "DWF Survey: Specified List Not Found"; } } catch (Exception ex) { context.Response.StatusCode = 500; context.Response.StatusDescription = ex.Message; } return(stThis); }
private double PublishTasksPubTypeOne( int projectId, int pubType, double taskCount, ProjectDataSet projectDataSet, SPList taskCenter, ref double taskDoneCount) { Guard.ArgumentIsNotNull(taskCenter, nameof(taskCenter)); Guard.ArgumentIsNotNull(projectDataSet, nameof(projectDataSet)); const string AssignmentId = "1"; if (pubType == PubTypeOne) { taskCount += projectDataSet.Assignment.Count; foreach (ProjectDataSet.AssignmentRow assignmentRow in projectDataSet.Assignment) { var currentTaskKey = $"{assignmentRow.TASK_UID.ToString().ToUpper()}.{assignmentRow.ASSN_UID.ToString().ToUpper()}"; if (!IsAssignedTaskSaved(assignmentRow.ASSN_UID)) { SPListItem listItem; if (hshCurTasks.Contains(currentTaskKey)) { var hshCurTask = (Guid)hshCurTasks[currentTaskKey]; listItem = taskCenter.GetItemByUniqueId(hshCurTask); hshCurTasks.Remove(currentTaskKey); } else { listItem = taskCenter.Items.Add(); } listItem[listItem.Fields.GetFieldByInternalName(IsAssignment).Id] = AssignmentId; listItem[ProjectText] = projectId; processAssignment(assignmentRow, projectDataSet, listItem); } else { hshCurTasks.Remove(currentTaskKey); } taskDoneCount++; setPubPercent(taskCount, taskDoneCount); } } return(taskCount); }
protected override bool ProcessWorkItem(SPContentDatabase contentDb, SPWorkItemCollection workItems, SPWorkItem workItem, SPJobState jobState) { if (workItem == null) { throw new ArgumentException("workItem is null"); } try { using (SPSite site = new SPSite(workItem.SiteId)) { using (SPWeb web = site.OpenWeb(workItem.WebId)) { try { //TODO CODE HERE SPList list = web.Lists[workItem.ParentId]; SPListItem listItem = list.GetItemByUniqueId(workItem.ItemGuid); SPList subList = web.Lists["SubscriberList"]; SPList elements = web.Lists["SubscribeElementList"]; //TODO Rewrite to caml for (int i = 0; i < subList.ItemCount; i++) { SPListItem item = subList.Items[i]; if (workItem.UserId == (int)item["User"]) { SPListItem newSubItem = elements.Items.Add(); newSubItem["User"] = workItem.UserId; newSubItem["NewsID"] = listItem["ID"]; newSubItem["Readed"] = false; newSubItem.Update(); } } } catch (Exception e) { throw e; } finally { workItems.SubCollection(site, web, 0, (uint)workItems.Count).DeleteWorkItem(workItem.Id); } } } } catch (Exception e) { throw e; } return(true); }
private SurveyTemplateAdmin GetCurrentTemplate(HttpContext context) { SurveyTemplateAdmin stThis = null; string strList = context.Request["List"] == null ? mcstrTemplateList : context.Request["List"]; using (SPWeb web = SPContext.Current.Web) { try { SPList lst = web.Lists.TryGetList(strList); if (lst != null) { SPListItem lsi = null; if (context.Request["TemplateID"] == null) { SPQuery qry = new SPQuery(); qry.RowLimit = 1; qry.Query = @"<OrderBy><FieldRef Name='Created' Ascending='False' /></OrderBy>"; SPListItemCollection lic = lst.GetItems(qry); if (lic.Count == 1) { lsi = lic[0]; } } else { lsi = lst.GetItemByUniqueId(new Guid(context.Request["TemplateID"])); } if (lsi != null) { stThis = new SurveyTemplateAdmin(lsi); } } else { context.Response.StatusCode = 500; context.Response.StatusDescription = "DWF Survey: Specified List Not Found"; } } catch (Exception ex) { context.Response.StatusCode = 500; context.Response.StatusDescription = "DWF Survey: " + ex.Message; } } return(stThis); }
private void ProcessProjectDataSetTask( int projectId, int pubType, Guid newTransUid, Guid lastTransUid, ProjectDataSet projectDataSet, SPList taskCenter, double taskDoneCount, double taskCount) { Guard.ArgumentIsNotNull(taskCenter, nameof(taskCenter)); Guard.ArgumentIsNotNull(projectDataSet, nameof(projectDataSet)); foreach (ProjectDataSet.TaskRow taskRow in projectDataSet.Task) { if (taskRow.TASK_ID != 0 && !taskRow.IsTASK_NAMENull() && !taskRow.TASK_IS_SUBPROJ) { try { SPListItem listItem; if (hshCurTasks.Contains(taskRow.TASK_UID.ToString().ToUpper())) { var hshCurTask = (Guid)hshCurTasks[taskRow.TASK_UID.ToString().ToUpper()]; listItem = taskCenter.GetItemByUniqueId(hshCurTask); hshCurTasks.Remove(taskRow.TASK_UID.ToString().ToUpper()); } else { listItem = taskCenter.Items.Add(); } listItem[ProjectText] = projectId; PopulateResources(pubType, projectDataSet, listItem, taskRow); PopulateListItem(pubType, newTransUid, lastTransUid, projectDataSet, taskCenter, listItem, taskRow); } catch (Exception exception) { myLog.WriteEntry( $"Error in publishTasks({taskRow.TASK_NAME}) updating list item: {exception.Message}{exception.StackTrace}{exception.InnerException}", EventLogEntryType.Error, 315); } } taskDoneCount++; setPubPercent(taskCount, taskDoneCount); } }
// Настраиваем контролы для отображения поля на форме отображения private void SetupDisplayTemplateControls() { if (currentFile != null) { // Получаем ссылку для загрузки файла SPWeb web = SPContext.Current.Site.RootWeb; SPList list = web.GetList(SPUrlUtility.CombineUrl(web.ServerRelativeUrl, libraryName)); SPListItem spFileItem = list.GetItemByUniqueId(currentFile.UniqueID); // Показываем ссылку на файл HyperLink aFile = (HyperLink)TemplateContainer.FindControl("aFile"); aFile.NavigateUrl = SPUrlUtility.CombineUrl(web.ServerRelativeUrl, spFileItem.Url); aFile.Text = currentFile.Name; } }
private void WriteProgress(SPWorkItem workItem, int percentageComplete) { lock (_writeLock) { if (workItem != null) { using (SPSite site = new SPSite(workItem.SiteId)) { using (SPWeb web = site.OpenWeb(workItem.WebId)) { try { SPList exportsList = web.Lists[workItem.ParentId]; SPListItem exportItem = exportsList.GetItemByUniqueId(workItem.ItemGuid); if (exportItem != null) { try { double currentValue = (double)exportItem["PercentageComplete"]; double newValue = (double)(percentageComplete / 100.0); //value between 0 and 1 if (newValue > currentValue) //ensure that the % can only go up { exportItem["PercentageComplete"] = newValue; exportItem.SystemUpdate(false); } } catch (Exception ex) { //error processing the percentage, this can be ignored. } } } catch (Exception ex) { //Failed to write progress } } } } } }
// Настраиваем контролы для отображения поля на форме редактирования private void SetupEditTemplateControls() { FileUpload fuDocument = (FileUpload)TemplateContainer.FindControl("fuDocument"); HyperLink aFile = (HyperLink)TemplateContainer.FindControl("aFile"); HiddenField hdFileName = (HiddenField)TemplateContainer.FindControl("hdFileName"); HtmlInputImage btnDelete = (HtmlInputImage)TemplateContainer.FindControl("btnDelete"); HtmlInputImage btnAdd = (HtmlInputImage)TemplateContainer.FindControl("btnAdd"); // В зависимости от того загружен ли файл отображаем контролы if (currentFile != null) { // Получаем ссылку для загрузки файла SPWeb web = SPContext.Current.Site.RootWeb; SPList list = web.GetList(SPUrlUtility.CombineUrl(web.ServerRelativeUrl, libraryName)); SPListItem spFileItem = list.GetItemByUniqueId(currentFile.UniqueID); // Показываем ссылку на файл aFile.NavigateUrl = SPUrlUtility.CombineUrl(web.ServerRelativeUrl, spFileItem.Url); aFile.Text = currentFile.Name; // А в скрытом поле сохраняем UniqueId файла hdFileName.Value = spFileItem.UniqueId.ToString(); } else { // Отображаем сообщение о том, что файл не задан aFile.Text = fileNotExist; hdFileName.Value = String.Empty; } btnDelete.Attributes.Add("onclick", String.Format(@"clearFileValue('{0}','{1}','{2}','{3}');return false;", aFile.ClientID, fuDocument.ClientID, hdFileName.ClientID, fileNotExist)); btnAdd.Attributes.Add("onclick", String.Format(@"changeDisplay('{0}');return false;", fuDocument.ClientID)); fuDocument.Attributes.Add("onchange", String.Format(@"changeFileName(this,'{0}');return false;", aFile.ClientID)); }
protected override bool ProcessWorkItem(SPContentDatabase contentDatabase, SPWorkItemCollection workItems, SPWorkItem workItem, SPJobState jobState) { Stopwatch sw = Stopwatch.StartNew(); //used to time how long the export took bool processingAlready = false; try { if (workItem != null) { //process the workItem using (SPSite site = new SPSite(workItem.SiteId)) { using (SPWeb web = site.OpenWeb(workItem.WebId)) { // processing logic // 1. SET GlymaExport list Item to ExportStatus.Processing // 2. START export based on type in GlymaExport list item // 3. STORE the export in the GlymaExport list against the item as an attachment // 4. SET GlymaExport list item to ExportStatus.Completed SPList exportsList = null; SPListItem exportItem = null; try { exportsList = web.Lists[workItem.ParentId]; exportItem = exportsList.GetItemByUniqueId(workItem.ItemGuid); if (exportItem != null) { string exportStatus = exportItem["ExportStatus"] as string; if (exportStatus == ExportStatus.Scheduled.ToString()) { // If the export was still marked as scheduled then set it to processing WriteExportStatus(workItem, ExportStatus.Processing); exportItem = exportsList.GetItemByUniqueId(workItem.ItemGuid); if (exportItem != null) { // read the type of export that we should produce ExportType exportType = (ExportType)Enum.Parse(typeof(ExportType), exportItem["ExportType"] as string); MapType mapType = (MapType)Enum.Parse(typeof(MapType), exportItem["MapType"] as string); Dictionary <string, string> exportProperties = null; string exportPropertiesStr = exportItem["ExportProperties"] as string; if (!string.IsNullOrEmpty(exportPropertiesStr) && exportPropertiesStr.Trim() != string.Empty) { try { ExportPropertiesDictionary exportDict = new ExportPropertiesDictionary(exportPropertiesStr); exportProperties = exportDict as Dictionary <string, string>; } catch (XmlSchemaValidationException) { exportProperties = null; } } bool useVerboseLogging = false; if (exportProperties != null) { if (exportProperties.ContainsKey("Verbose")) { if (exportProperties["Verbose"].ToLower() == "true") { useVerboseLogging = true; } } } if (useVerboseLogging) { LogMessage(workItem, "Creating Map Manager for the web: {0}.", web.Url); } // create the appropriate IExportUtility for the ExportType MapManagerFactory mapManagerFactory = new MapManagerFactory(); IMapManager mapManager = mapManagerFactory.GetMapManager(web); if (mapManager != null) { if (useVerboseLogging) { LogMessage(workItem, "Created Map Manager for the web: {0}.", web.Url); } ExportUtilityFactory exportUtilityFactory = new ExportUtilityFactory(mapManager); IExportUtility exportUtility = exportUtilityFactory.CreateExportUtility(mapType, exportType); if (exportUtility != null) { if (useVerboseLogging) { LogMessage(workItem, "Created Export Utility for {0} map type to {1}.", mapType.ToString(), exportType.ToString()); } exportItem = exportsList.GetItemByUniqueId(workItem.ItemGuid); if (exportItem != null) { Guid rootMapUid = Guid.Empty; Guid domainUid = Guid.Empty; try { string rootMapUidValue = exportItem["RootMapUid"] as string; string domainUidValue = exportItem["DomainUid"] as string; domainUid = new Guid(domainUidValue); rootMapUid = new Guid(rootMapUidValue); } catch (Exception ex) { //The GUIDs were not parsed correctly } if (rootMapUid != Guid.Empty && domainUid != Guid.Empty) { //The export utility will do the grunt work and provide a URL to the temp file created GlymaExportUserState userState = new GlymaExportUserState(workItem); userState.UseVerboseLogging = useVerboseLogging; //store the level of logging to use in the event handlers exportUtility.ExportCompleted += exportUtility_ExportCompleted; exportUtility.ProgressChanged += exportUtility_ProgressChanged; exportUtility.ExceptionRaised += exportUtility_ExceptionRaised; if (useVerboseLogging) { LogMessage(workItem, "Starting export."); } exportUtility.ExportMap(domainUid, rootMapUid, exportProperties, new List <Guid>(), userState); if (useVerboseLogging) { LogMessage(workItem, "Waiting for export to complete."); } // Wait for the export to complete (up to the timeout) bool signalled = userState.Completed.WaitOne(TIMEOUT_MS); if (!signalled) { if (useVerboseLogging) { LogMessage(workItem, "The export timed out after {0}ms", TIMEOUT_MS); } // The timeout occurred so don't process the completed or progress changed events exportUtility.ExportCompleted -= exportUtility_ExportCompleted; exportUtility.ProgressChanged -= exportUtility_ProgressChanged; exportUtility.ExceptionRaised -= exportUtility_ExceptionRaised; } } else { throw new Exception(string.Format("The DomainUid and/or RootMapUid were not valid Guid's. DomainUid: {0} RootMapUid: {1}.", domainUid.ToString(), rootMapUid.ToString())); } } } else { throw new Exception(string.Format("Unable to create export utility for the export type: {0}.", exportType.ToString())); } } else { throw new Exception(string.Format("Unable to build an IMapManager for the current SPWeb. {0}", mapManagerFactory.ErrorMessage)); } } } else if (exportStatus == ExportStatus.Processing.ToString()) { //shouldn't do anything unless it's scheduled. processingAlready = true; } } else { throw new Exception("The Export Job did not exist in the list."); } } catch (TargetInvocationException tiex) { if (workItem != null) { WriteExportStatus(workItem, ExportStatus.Error); LogMessage(workItem, "Error during export: {0}", tiex.Message); if (tiex.InnerException != null) { LogMessage(workItem, "Inner Exception({0}): {1}.\r\nStackTrace: {2}", tiex.InnerException.GetType().ToString(), tiex.InnerException.Message, tiex.InnerException.StackTrace); } } } catch (Exception ex) { //exception handling if (workItem != null) { WriteExportStatus(workItem, ExportStatus.Error); LogMessage(workItem, "Error during export: {0}.", ex.Message); } } finally { if (!processingAlready) { // delete the workItem after we've processed it workItems.SubCollection(site, web, 0, (uint)workItems.Count).DeleteWorkItem(workItem.Id); } //Update the progress of the timer job Progress += (100 / workItems.Count); //estimate only, some maps will export faster than others and different types may export faster if (Progress > 100) { Progress = 100; } this.UpdateProgress(Progress); //The base classes timer job's overall progress if (!processingAlready) //this is if the timer job ran and started processing the item that was already being processed { exportItem = exportsList.GetItemByUniqueId(workItem.ItemGuid); if (exportItem != null) { string exportStatus = exportItem["ExportStatus"] as string; if (exportStatus == ExportStatus.Processing.ToString()) { //if it's still processing and at this point then something has failed. WriteExportStatus(workItem, ExportStatus.Error); LogMessage(workItem, "The export failed as it was still in a processing state when it had apparently completed."); } LogMessage(workItem, "Completed in {0:0.000}s.", sw.Elapsed.TotalSeconds);//add in a metric for how long the export took (successful or failure) } } } } } } } catch (Exception ex) { //exception handling throw new Exception("Failed to while processing Glyma Export Work Item Timer Job.", ex); } return(true); }
private void exportUtility_ExportCompleted(object sender, ExportCompletedEventArgs e) { GlymaExportUserState userState = e.UserState as GlymaExportUserState; if (userState != null) { SPWorkItem workItem = userState.StateObject as SPWorkItem; if (workItem != null) { using (SPSite site = new SPSite(workItem.SiteId)) { using (SPWeb web = site.OpenWeb(workItem.WebId)) { try { if (e.Status == ExportStatus.Error) { WriteExportStatus(workItem, ExportStatus.Error); LogMessage(workItem, e.ErrorMessage); } else if (e.Status == ExportStatus.Completed) { SPList exportsList = web.Lists[workItem.ParentId]; SPListItem exportItem = exportsList.GetItemByUniqueId(workItem.ItemGuid); if (exportItem != null) { // Read the contents of the file byte[] fileContents = null; Stream fs = null; try { fs = File.OpenRead(e.FileLocation); fileContents = new byte[fs.Length]; fs.Read(fileContents, 0, (int)fs.Length); // Add the file to the ListItem SPAttachmentCollection attachments = exportItem.Attachments; string fileName = Path.GetFileName(e.FileLocation); string extention = fileName.Substring(fileName.LastIndexOf('.')); fileName = e.MapName + extention; attachments.Add(fileName, fileContents); exportItem.Update(); // Mark as completed WriteExportStatus(workItem, ExportStatus.Completed); WriteProgress(workItem, 1); if (userState.UseVerboseLogging) { LogMessage(workItem, "Export file copied to list successfully."); } } catch (Exception ex) { WriteExportStatus(workItem, ExportStatus.Error); LogMessage(workItem, "Failed reading the exported file: {0}. {1}", e.FileLocation, ex.Message); //this will append the log message } finally { if (fs != null) { fs.Close(); } } //Try delete the temporary file, don't change the status to Error if this fails but log it. try { DeleteTempFile(e.FileLocation); } catch (Exception ex) { if (workItem != null) { //the status will still be Completed but an error occurred that should be monitored. LogMessage(workItem, "Failed to delete temp export file: {0}. ", ex.Message); } } } } } finally { userState.Completed.Set(); //work item has completed } } } } } }
private DWFResponse SaveResponse(HttpContext context) { DWFResponse rspReturn = new DWFResponse(); string strList = context.Request["List"] == null ? mcstrResponseList : context.Request["List"]; rspReturn.IsError = true; if (context.Request["ResponseData"] != null) { JavaScriptSerializer ser = new JavaScriptSerializer(new SimpleTypeResolver()); SurveyResponse srThis = new SurveyResponse(); srThis.ResponseData = ser.Deserialize <List <SurveyAnswer> >(context.Request["ResponseData"]); srThis.ResponseName = context.Request["ResponseName"]; srThis.TemplateID = new Guid(context.Request["TemplateID"]); using (SPWeb web = SPContext.Current.Web) { try { SPList lst = web.Lists.TryGetList(strList); if (lst != null) { SPListItem lsi; if (context.Request["ID"] == "-1") { lsi = lst.Items.Add(); } else { lsi = lst.GetItemByUniqueId(new Guid(context.Request["ID"])); } lsi["Title"] = srThis.ResponseName; lsi["ResponseName"] = srThis.ResponseName; int intScore = srThis.Score(SurveyHandler.GetTemplate(context.Request["TemplateList"], srThis.TemplateID), SurveyHandler.GetScoreCard()); lsi["Score"] = intScore; lsi["TemplateID"] = srThis.TemplateID; lsi["ResponseData"] = context.Request["ResponseData"]; web.AllowUnsafeUpdates = true; SPSecurity.RunWithElevatedPrivileges(delegate() { lsi.Update(); }); web.AllowUnsafeUpdates = false; rspReturn.IsError = false; rspReturn.Message = "<h2>" + intScore + " out of 10</h2>"; rspReturn.Message += "<p>" + srThis.ScoreDescription + "</p>"; } } catch (Exception ex) { context.Response.StatusCode = 500; context.Response.StatusDescription = "DWF Survey: " + ex.Message; } } } else { context.Response.StatusCode = 500; context.Response.StatusDescription = "DWF Survey: Specified Responses List Not Found"; } return(rspReturn); }
protected void wzd_aanmelden_FinishButtonClick(object sender, WizardNavigationEventArgs e) { //using (SPLongOperation operation = new SPLongOperation(this.Page)) //{ // operation.Begin(); using (new SPMonitoredScope("Mailing SendMail")) { try { XDocument xmlInputData = new XDocument(new XElement("Properties")); XElement elements = new XElement("Elements", new object[] { new XElement("HEADER"), new XElement("FEATURED_AREA"), new XElement("VERENIGING"), new XElement("GEBRUIKER"), new XElement("OPMERKINGEN"), new XElement("BOTTOM_CALL_TO_ACTION"), new XElement("FOOTER") }); xmlInputData.Root.Add(elements); ClubCloud_Vereniging vereniging = new ClubCloud_Vereniging(); string verenigingsnummer = tbx_verenigingsnummer.Text; string number = string.Empty; int parsed = 0; if (verenigingsnummer.IndexOf('-') > 0) { number = verenigingsnummer.Split('-')[0].Trim(); } else { number = verenigingsnummer; } if (int.TryParse(number, out parsed)) { try { vereniging = Client.GetVerenigingByNummer("00000000", parsed.ToString(), false); } catch (Exception ex) { Logger.WriteLog(Logger.Category.Unexpected, ex.Source, ex.Message); } } if (vereniging == null) { vereniging = new ClubCloud_Vereniging(); } if (vereniging.Nummer != number) { vereniging.Nummer = number; } TextBox vereniging_naam = (TextBox)fvw_vereniging.FindControl("Naam"); string verenigingnaam = vereniging_naam.Text; if (vereniging.Naam != vereniging_naam.Text && !string.IsNullOrWhiteSpace(vereniging_naam.Text)) { vereniging.Naam = vereniging_naam.Text; } TextBox vereniging_KvKNummer = (TextBox)fvw_vereniging.FindControl("KvKNummer"); string verenigingkvknummer = vereniging_KvKNummer.Text; if (vereniging.KvKnummer != vereniging_KvKNummer.Text && !string.IsNullOrWhiteSpace(vereniging_KvKNummer.Text)) { vereniging.KvKnummer = vereniging_KvKNummer.Text; } TextBox vereniging_KvKPlaats = (TextBox)fvw_vereniging.FindControl("KvKPlaats"); string verenigingkvkplaats = vereniging_KvKPlaats.Text; if (vereniging.KvKplaats != vereniging_KvKPlaats.Text && !string.IsNullOrWhiteSpace(vereniging_KvKPlaats.Text)) { vereniging.KvKplaats = vereniging_KvKPlaats.Text; } TextBox vereniging_BankNummer = (TextBox)fvw_vereniging.FindControl("BankNummer"); string verenigingbanknummer = vereniging_BankNummer.Text; if (vereniging.BankNummer != vereniging_BankNummer.Text && !string.IsNullOrWhiteSpace(vereniging_BankNummer.Text)) { vereniging.BankNummer = vereniging_BankNummer.Text; } TextBox vereniging_BankIban = (TextBox)fvw_vereniging.FindControl("BankIban"); string verenigingbankiban = vereniging_BankIban.Text; if (vereniging.BankIban != vereniging_BankIban.Text && !string.IsNullOrWhiteSpace(vereniging_BankIban.Text)) { vereniging.BankIban = vereniging_BankIban.Text; } TextBox vereniging_BankPlaats = (TextBox)fvw_vereniging.FindControl("BankPlaats"); string verenigingbankplaats = vereniging_BankPlaats.Text; if (vereniging.BankPlaats != vereniging_BankPlaats.Text && !string.IsNullOrWhiteSpace(vereniging_BankPlaats.Text)) { vereniging.BankPlaats = vereniging_BankPlaats.Text; } TextBox vereniging_TelefoonOverdag = (TextBox)fvw_vereniging.FindControl("TelefoonOverdag"); string verenigingtelefoonoverdag = vereniging_TelefoonOverdag.Text; if (vereniging.TelefoonOverdag != vereniging_TelefoonOverdag.Text && !string.IsNullOrWhiteSpace(vereniging_TelefoonOverdag.Text)) { vereniging.TelefoonOverdag = vereniging_TelefoonOverdag.Text; } TextBox vereniging_TelefoonAvond = (TextBox)fvw_vereniging.FindControl("TelefoonAvond"); string verenigingtelefoonavond = vereniging_TelefoonAvond.Text; if (vereniging.TelefoonAvond != vereniging_TelefoonAvond.Text && !string.IsNullOrWhiteSpace(vereniging_TelefoonAvond.Text)) { vereniging.TelefoonAvond = vereniging_TelefoonAvond.Text; } TextBox vereniging_Email = (TextBox)fvw_vereniging.FindControl("Email"); string verenigingemail = vereniging_Email.Text; if (vereniging.EmailKNLTB != vereniging_Email.Text && !string.IsNullOrWhiteSpace(vereniging_Email.Text)) { vereniging.EmailKNLTB = vereniging_Email.Text; } xmlInputData.Root.Add(vereniging.ToXElement <ClubCloud_Vereniging>()); ClubCloud_Gebruiker gebruiker = new ClubCloud_Gebruiker(); TextBox persoon_knltb = (TextBox)fvw_persoon.FindControl("KNLTBNummer"); string persoonknltb = persoon_knltb.Text; string lm = string.Empty; parsed = 0; if (int.TryParse(persoonknltb, out parsed)) { lm = "luckyme"; } /* * { * try * { * gebruiker = Client.GetGebruikerByNummer("00000000", vereniging.Id, parsed.ToString(), false); * } * catch (Exception ex) * { * Logger.WriteLog(Logger.Category.Unexpected, ex.Source, ex.Message); * } * } */ if (gebruiker == null) { gebruiker = new ClubCloud_Gebruiker(); } if (gebruiker.Bondsnummer != parsed.ToString()) { gebruiker.Bondsnummer = parsed.ToString(); } TextBox persoon_naam = (TextBox)fvw_persoon.FindControl("Naam"); string persoonnaam = persoon_naam.Text; if (gebruiker.Volledigenaam != persoon_naam.Text && !string.IsNullOrWhiteSpace(persoon_naam.Text)) { gebruiker.Volledigenaam = persoon_naam.Text; } TextBox persoon_TelefoonOverdag = (TextBox)fvw_persoon.FindControl("TelefoonOverdag"); string persoontelefoonoverdag = persoon_TelefoonOverdag.Text; if (gebruiker.TelefoonOverdag != persoon_TelefoonOverdag.Text && !string.IsNullOrWhiteSpace(persoon_TelefoonOverdag.Text)) { gebruiker.TelefoonOverdag = persoon_TelefoonOverdag.Text; } TextBox persoon_TelefoonAvond = (TextBox)fvw_persoon.FindControl("TelefoonAvond"); string persoontelefoonavond = persoon_TelefoonAvond.Text; if (gebruiker.TelefoonAvond != persoon_TelefoonAvond.Text && !string.IsNullOrWhiteSpace(persoon_TelefoonAvond.Text)) { gebruiker.TelefoonAvond = persoon_TelefoonAvond.Text; } TextBox persoon_Email = (TextBox)fvw_persoon.FindControl("Email"); string persoonemail = persoon_Email.Text; if (gebruiker.EmailKNLTB != persoon_Email.Text && !string.IsNullOrWhiteSpace(persoon_Email.Text)) { gebruiker.EmailKNLTB = persoon_Email.Text; } xmlInputData.Root.Add(gebruiker.ToXElement <ClubCloud_Gebruiker>()); XElement aanmelden = new XElement("Aanmelden", new object[] { new XElement("Opmerkingen", opmerkingen.Text), new XElement("Akkoord", akkoord.Checked), new XElement("Datum", DateTime.Now.ToString()), new XElement("IP", GetIPAddress()) }); xmlInputData.Root.Add(aanmelden); EmailTracking tracking = new EmailTracking { CampaignName = "Aanmelden", CampaignSource = "WebSite", ClientId = vereniging.Id, RecipientId = vereniging.Nummer, TrackingId = "UA-9934149-20", CampagneContent = "aanmelden", CampagneMedium = "email", CampagneTerm = "aanmelden" }; xmlInputData.Root.Add(tracking.ToXElement <EmailTracking>()); XElement content = new XElement("Content", new XElement("Subject", string.Format("Aanmelden bij ClubCloud voor {0} ({1})", vereniging.Naam, vereniging.Nummer))); xmlInputData.Root.Add(content); SPSecurity.RunWithElevatedPrivileges(delegate() { try { using (SPSite currentSite = new SPSite(SPContext.Current.Site.ID, SPUrlZone.Internet)) { using (SPWeb web = currentSite.OpenWeb(SPContext.Current.Web.ID)) { SPDocumentLibrary SiteAssets = null; SPDocumentLibrary SitePages = null; SPFolder Templates = null; SPFolder Online = null; SPFile Aanmelden = null; SPFile Webversion = null; SPItem WebversionItem = null; XmlReader template = null; SPList assets = web.Lists.TryGetList("SiteAssets"); if (assets == null) { assets = web.Lists.TryGetList("Siteactiva"); } if (assets != null) { SiteAssets = (SPDocumentLibrary)assets; } if (SiteAssets != null) { Templates = SiteAssets.RootFolder.SubFolders["Templates"]; } SPList pages = web.Lists.TryGetList("SitePages"); if (pages == null) { pages = web.Lists.TryGetList("Sitepagina's"); } if (pages != null) { SitePages = (SPDocumentLibrary)pages; } if (SitePages != null) { Online = SitePages.RootFolder.SubFolders["Online"]; } if (Templates != null && Templates.Exists) { Aanmelden = Templates.Files["aanmelden.xsl"]; } if (Aanmelden != null && Aanmelden.Exists) { template = XmlReader.Create(Aanmelden.OpenBinaryStream()); } if (template == null) { throw new FileNotFoundException("Template not Found", Aanmelden.Url); } string body = GenerateEmailBody(template, xmlInputData); web.AllowUnsafeUpdates = true; if (Online != null && Online.Exists) { Webversion = Online.Files.Add(Guid.NewGuid() + ".aspx", System.Text.Encoding.UTF8.GetBytes(body), true); WebversionItem = pages.GetItemByUniqueId(Webversion.UniqueId); WebversionItem["Title"] = string.Format("Aanmelden bij ClubCloud voor {0} ({1})", vereniging.Naam, vereniging.Nummer); WebversionItem.Update(); } if (Webversion != null && Webversion.Exists) { XElement online = new XElement("Online", new object[] { new XElement("WebVersion", string.Format("{0}/{1}", currentSite.Url, Webversion.Url)) }); xmlInputData.Root.Add(online); } if (Aanmelden != null && Aanmelden.Exists) { template = XmlReader.Create(Aanmelden.OpenBinaryStream()); } body = GenerateEmailBody(template, xmlInputData); web.AllowUnsafeUpdates = false; MailMessage message = Email.CreateMailMessage(body); MailAddress tovereniging = new MailAddress(vereniging.EmailKNLTB, vereniging.Naam, Encoding.UTF8); message.To.Add(tovereniging); MailAddress topersoon = new MailAddress(gebruiker.EmailKNLTB, gebruiker.Volledigenaam, Encoding.UTF8); message.To.Add(topersoon); message.CC.Add(new MailAddress("*****@*****.**", "Aanmelden bij ClubCloud")); message.From = new MailAddress("*****@*****.**", "Aanmelden bij ClubCloud"); message.Subject = string.Format("Aanmelden bij ClubCloud voor {0}({1})", vereniging.Naam, vereniging.Nummer); message.Priority = MailPriority.Normal; message.ReplyToList.Add(new MailAddress("*****@*****.**", "Aanmelden bij ClubCloud")); message.Sender = new MailAddress("*****@*****.**", "Aanmelden bij ClubCloud"); SmtpClient client = new SmtpClient(ZimbraConfiguration.Server.SendMailHost, zimbraconfiguration.Server.SendMailPort); client.Credentials = new System.Net.NetworkCredential(ZimbraConfiguration.Server.SendMailUserName, ZimbraConfiguration.Server.SendMailPassword); client.DeliveryMethod = SmtpDeliveryMethod.Network; message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure | DeliveryNotificationOptions.OnSuccess | DeliveryNotificationOptions.Delay; Email.Send(message, client); } } } catch (Exception ex) { Logger.WriteLog(Logger.Category.Unexpected, ex.Source, ex.Message); } }); } catch (Exception ex) { Logger.WriteLog(Logger.Category.Unexpected, ex.Source, ex.Message); } } //operation.End("bedankt.aspx"); //} }
private MailMessage BuidMailMessage(ClubCloud_Vereniging vereniging) { MailMessage message = null; XDocument xmlInputData = new XDocument(new XElement("Properties")); XElement elements = new XElement("Elements", new object[] { new XElement("HEADER"), new XElement("FEATURED_AREA"), new XElement("FULL_WIDTH_COLUMN"), new XElement("INTRO"), new XElement("HALF_COLUMN_FEATURES"), new XElement("HALF_COLUMN_TOP_IMAGE"), new XElement("ONE_THIRD_TWO_THIRD_COLUMN_LEFT_IMAGE"), new XElement("TWO_THIRD_ONE_THIRD_COLUMN_RIGHT_IMAGE"), new XElement("CENTRECOURT"), new XElement("BOTTOM_CALL_TO_ACTION"), new XElement("FOOTER") }); xmlInputData.Root.Add(elements); xmlInputData.Root.Add(vereniging.ToXElement <ClubCloud_Vereniging>()); EmailTracking track = new EmailTracking { CampaignName = "Introductie", CampaignSource = "Nieuwsbrief", CampagneMedium = "email", ClientId = vereniging.Id, RecipientId = vereniging.Nummer, TrackingId = "UA-9934149-20", CampagneContent = "Introductie", CampagneTerm = "Introductie" }; xmlInputData.Root.Add(track.ToXElement <EmailTracking>()); XElement content = new XElement("Content", new XElement("Subject", string.Format("ClubCloud : De slimme keuze voor {0}", vereniging.Naam))); xmlInputData.Root.Add(content); SPSecurity.RunWithElevatedPrivileges(delegate() { try { using (SPSite currentSite = new SPSite(SPContext.Current.Site.ID, SPUrlZone.Internet)) { using (SPWeb web = currentSite.OpenWeb(SPContext.Current.Web.ID)) { SPDocumentLibrary SiteAssets = null; SPDocumentLibrary SitePages = null; SPFolder Templates = null; SPFolder Online = null; SPFile Aanmelden = null; SPFile Webversion = null; SPItem WebversionItem = null; XmlReader template = null; SPList assets = web.Lists.TryGetList("SiteAssets"); if (assets == null) { assets = web.Lists.TryGetList("Siteactiva"); } if (assets != null) { SiteAssets = (SPDocumentLibrary)assets; } if (SiteAssets != null) { Templates = SiteAssets.RootFolder.SubFolders["Templates"]; } SPList pages = web.Lists.TryGetList("SitePages"); if (pages == null) { pages = web.Lists.TryGetList("Sitepagina's"); } SPQuery query = new SPQuery(); query.Query = string.Format("<Where><Eq><FieldRef Name=\"Title\" /><Value Type=\"Text\">ClubCloud : De slimme keuze voor {0}</Value></Eq></Where>", vereniging.Naam); query.RowLimit = 1; query.ViewFields = @"<FieldRef Name=""Title"" />"; query.ViewAttributes = @"Scope=""Recursive"""; SPListItemCollection items = pages.GetItems(query); if (items.Count > 0) { throw new SPDuplicateObjectException("Club already mailed", new Exception("Club already mailed")); } if (pages != null) { SitePages = (SPDocumentLibrary)pages; } if (SitePages != null) { Online = SitePages.RootFolder.SubFolders["Online"]; } if (Templates != null && Templates.Exists) { Aanmelden = Templates.Files["template.xsl"]; } if (Aanmelden != null && Aanmelden.Exists) { template = XmlReader.Create(Aanmelden.OpenBinaryStream()); } if (template == null) { throw new FileNotFoundException("Template not Found", Aanmelden.Url); } string body = GenerateEmailBody(template, xmlInputData); web.AllowUnsafeUpdates = true; if (Online != null && Online.Exists) { Webversion = Online.Files.Add(Guid.NewGuid() + ".aspx", System.Text.Encoding.UTF8.GetBytes(body), true); WebversionItem = pages.GetItemByUniqueId(Webversion.UniqueId); WebversionItem["Title"] = string.Format("ClubCloud : De slimme keuze voor {0}", vereniging.Naam); WebversionItem.Update(); } if (Webversion != null && Webversion.Exists) { XElement online = new XElement("Online", new object[] { new XElement("WebVersion", string.Format("{0}/{1}", currentSite.Url, Webversion.Url)) }); xmlInputData.Root.Add(online); } if (Aanmelden != null && Aanmelden.Exists) { template = XmlReader.Create(Aanmelden.OpenBinaryStream()); } body = GenerateEmailBody(template, xmlInputData); web.AllowUnsafeUpdates = false; message = Email.CreateMailMessage(body); } } } catch (Exception ex) { Logger.WriteLog(Logger.Category.Unexpected, ex.Source, ex.Message); message = null; } }); return(message); }