/// <summary> /// Get selecte user information from people editor control /// </summary> /// <param name="people"></param> /// <param name="currentWeb"></param> /// <returns></returns> public SPFieldUserValue GetSingleUserFromPeopleEditor(PeopleEditor people, SPWeb currentWeb) { SPFieldUserValue userValue = null; try { if (people.ResolvedEntities.Count <= 1) { PickerEntity user = (PickerEntity)people.ResolvedEntities[0]; switch ((string)user.EntityData["PrincipalType"]) { case "User": SPUser webUser = currentWeb.EnsureUser(user.Key); userValue = new SPFieldUserValue(currentWeb, webUser.ID, webUser.Name); break; case "SharePointGroup": SPGroup siteGroup = currentWeb.SiteGroups[user.EntityData["AccountName"].ToString()]; userValue = new SPFieldUserValue(currentWeb, siteGroup.ID, siteGroup.Name); break; } } } catch (Exception err) { LogErrorHelper objErr = new LogErrorHelper(LIST_SETTING_NAME, currentWeb); objErr.logSysErrorEmail(APP_NAME, err, "Error at GetSingleUserFromPeopleEditor function"); objErr = null; SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(APP_NAME, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, err.Message.ToString(), err.StackTrace); } return(userValue); }
/// <summary> /// Get multiple people information from people editor control /// </summary> /// <remarks> /// References: http://blog.bugrapostaci.com/tag/spfielduservalue/ /// </remarks> /// <param name="editor"></param> /// <returns></returns> public SPFieldUserValueCollection GetSelectedUsers(PeopleEditor editor, SPWeb currentWeb) { string selectedUsers = editor.CommaSeparatedAccounts; SPFieldUserValueCollection values = new SPFieldUserValueCollection(); try { // commaseparatedaccounts returns entries that are comma separated. we want to split those up char[] splitter = { ',' }; string[] splitPPData = selectedUsers.Split(splitter); // this collection will store the user values from the people editor which we'll eventually use // to populate the field in the list // for each item in our array, create a new sp user object given the loginname and add to our collection for (int i = 0; i < splitPPData.Length; i++) { string loginName = splitPPData[i]; if (!string.IsNullOrEmpty(loginName)) { SPUser user = currentWeb.SiteUsers[loginName]; SPFieldUserValue fuv = new SPFieldUserValue(currentWeb, user.ID, user.LoginName); values.Add(fuv); } } } catch (Exception err) { LogErrorHelper objErr = new LogErrorHelper(LIST_SETTING_NAME, currentWeb); objErr.logSysErrorEmail(APP_NAME, err, "Error at GetSelectedUsers function"); objErr = null; SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(APP_NAME, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, err.Message.ToString(), err.StackTrace); } return(values); }
/// <summary> /// Update a particular user profile property field /// </summary> /// <param name="acctName"></param> /// <param name="fieldName"></param> /// <param name="fieldValue"></param> public void updateProfileDetails(string acctName, string fieldName, string fieldValue, SPWeb currentWeb) { try { SPSite site = SPContext.Current.Site; SPServiceContext ospServerContext = SPServiceContext.GetContext(site); UserProfileManager ospUserProfileManager = new UserProfileManager(ospServerContext); UserProfile ospUserProfile = ospUserProfileManager.GetUserProfile(acctName); Microsoft.Office.Server.UserProfiles.PropertyCollection propColl = ospUserProfile.ProfileManager.PropertiesWithSection; if (ospUserProfile != null && propColl != null) { foreach (Property prop in propColl) { if (fieldName == prop.Name) { ospUserProfile[prop.Name].Value = fieldValue; } } ospUserProfile.Commit(); } } catch (Exception err) { LogErrorHelper objErr = new LogErrorHelper(LIST_SETTING_NAME, currentWeb); objErr.logSysErrorEmail(APP_NAME, err, "Error at getUserProfileDetails function"); objErr = null; SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(APP_NAME, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, err.Message.ToString(), err.StackTrace); } }
public bool Save(Cliente clie) { try { string error = ValidSave(clie); if (error != string.Empty) { throw new Exception("Ocurrio un error durante el Save: " + error); } if (clie.Id == 0) { _dbContext.Clientes.Add(clie); } _dbContext.SaveChanges(); return(true); } catch (Exception ex) { LogErrorHelper.LogError(ex); return(false); } }
public Task <HttpResponseMessage> Details() { HttpResponseMessage response = new HttpResponseMessage(); try { var user = _repository.Get(User.Identity.Name); var model = new DetailUserViewModel(); model.Email = user.Email; model.Id = user.Id; model.IsActive = user.IsActive; model.Name = user.Name; response = Request.CreateResponse(HttpStatusCode.OK, model); } catch (Exception ex) { response = Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message); LogErrorHelper.Register(ex); } var tsc = new TaskCompletionSource <HttpResponseMessage>(); tsc.SetResult(response); return(tsc.Task); }
public bool Delete(int id) { try { var ing = _dbContext.Ingredientes.Where(a => a.Id == id).FirstOrDefault(); if (ing != null) { var error = ValidDelete(ing); if (error != string.Empty) { throw new Exception("Error durante el Delete: " + error); } _dbContext.Ingredientes.Remove(ing); _dbContext.SaveChanges(); } return(true); } catch (Exception ex) { LogErrorHelper.LogError(ex); return(false); } }
public bool Save(CostoServicio domObj) { try { if (string.IsNullOrEmpty(domObj.Notas)) { domObj.Notas = ""; } string error = ValidSave(domObj); if (domObj.Id == 0) { _dbContext.CostoServicios.Add(domObj); } _dbContext.SaveChanges(); return(true); } catch (Exception ex) { LogErrorHelper.LogError(ex); return(false); } }
public bool Save(MateriaPrima mp) { try { string error = ValidSave(mp); if (error != string.Empty) { throw new Exception("Error durante el Save: " + error); } if (mp.Id == 0) { _dbContext.MateriasPrimas.Add(mp); } _dbContext.SaveChanges(); return(true); } catch (Exception ex) { LogErrorHelper.LogError(ex); return(false); } }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); try { using (IUserRepository _repository = new UserRepository(DataContextHelper.CurrentDataContext)) { var user = _repository.Get(context.UserName); if (user == null) { throw new Exception("Usuário ou senha inválidos"); } user.Authenticate(context.UserName, context.Password); GenericIdentity genericIdentity = new GenericIdentity(user.Email); var identity = new ClaimsIdentity(genericIdentity, null, context.Options.AuthenticationType, null, null); identity.AddClaim(new Claim("sub", context.UserName)); identity.AddClaim(new Claim("role", "user")); context.Validated(identity); } } catch (Exception ex) { context.SetError("invalid_grant", ex.Message); LogErrorHelper.Register(ex); return; } }
/// <summary> /// Get the localized label of User Profile Properties /// Option 1 => Get the specific property to find the label (much better performance) /// </summary> /// <param name="userProfilePropertyName"></param> /// <reference> /// 1. http://nikpatel.net/2013/12/26/code-snippet-programmatically-retrieve-localized-user-profile-properties-label/ /// </reference> /// <returns></returns> public string getLocalizedUserProfilePropertiesLabel(string userProfilePropertyName, SPWeb currentWeb) { string localizedLabel = string.Empty; try { //Get the handle of User Profile Service Application for current site (web application) SPSite site = SPContext.Current.Site; SPServiceContext context = SPServiceContext.GetContext(site); UserProfileConfigManager upcm = new UserProfileConfigManager(context); //Access the User Profile Property manager core properties ProfilePropertyManager ppm = upcm.ProfilePropertyManager; CorePropertyManager cpm = ppm.GetCoreProperties(); //Get the core property for user profile property and get the localized value CoreProperty cp = cpm.GetPropertyByName(userProfilePropertyName); if (cp != null) { localizedLabel = cp.DisplayNameLocalized[System.Globalization.CultureInfo.CurrentUICulture.LCID]; } } catch (Exception err) { LogErrorHelper objErr = new LogErrorHelper(LIST_SETTING_NAME, currentWeb); objErr.logSysErrorEmail(APP_NAME, err, "Error at getLocalizedUserProfilePropertiesLabel function"); objErr = null; SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(APP_NAME, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, err.Message.ToString(), err.StackTrace); return(string.Empty); } return(localizedLabel); }
/// <summary> /// Report any unmapped user profile property fields via email /// </summary> /// <param name="internalPropertyFieldName"></param> /// <param name="fieldValue"></param> private void reportUnManagedUserProfileProperties(SPWeb currentWeb) { LogErrorHelper objEmail = new LogErrorHelper(LIST_SETTING_NAME, currentWeb); try { StringBuilder sb = new StringBuilder(); for (int i = 0; i <= upFieldName.Count - 1; i++) { sb.AppendFormat("<b>{0}:</b> {1}<br>", upFieldName[i], upFieldValue[i]); } string emailMsg = "The following User Profile property fields below was not mapped to a custom list: <br>" + sb.ToString(); //Send email to admin user objEmail.sendUserEmail(APP_NAME, "User Profile Notification", emailMsg, false); } catch (Exception err) { objEmail.logSysErrorEmail(APP_NAME, err, "Error at reportUnManagedUserProfileProperties function"); SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(APP_NAME, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, err.Message.ToString(), err.StackTrace); } objEmail = null; }
public bool Save(Ingrediente ing) { try { string error = ValidSave(ing); if (error != string.Empty) { throw new Exception("Error durante el Save: " + error); } if (ing.Id == 0) { _dbContext.Ingredientes.Add(ing); } _dbContext.SaveChanges(); return(true); } catch (Exception ex) { LogErrorHelper.LogError(ex); return(false); } }
public bool Save(CostoMateriales domObj) { try { var error = ValidSave(domObj); if (error != string.Empty) { throw new Exception("Ocurrio un error durante el Save: " + error); } domObj.FechaCompra = domObj.FechaCompra.SacarHoras(); if (domObj.Id == 0) { _dbContext.CostoMateriales.Add(domObj); } _dbContext.SaveChanges(); return(true); } catch (Exception ex) { LogErrorHelper.LogError(ex); return(false); } }
public Task <HttpResponseMessage> Sync(IList <SyncTodoViewModel> model) { HttpResponseMessage response = new HttpResponseMessage(); try { var todos = new List <Todo>(); foreach (var item in model) { var todo = new Todo(item.Text); if (item.Done) { todo.MarkAsDone(); } todos.Add(todo); } _todoRepository.Sync(todos, User.Identity.Name); response = Request.CreateResponse(HttpStatusCode.OK, "Sincronia realizada com sucesso!"); } catch (Exception ex) { response = Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message); LogErrorHelper.Register(ex); } var tsc = new TaskCompletionSource <HttpResponseMessage>(); tsc.SetResult(response); return(tsc.Task); }
// Uncomment the method below to handle the event raised after a feature has been installed. //public override void FeatureInstalled(SPFeatureReceiverProperties properties) //{ //} // Uncomment the method below to handle the event raised before a feature is uninstalled. //public override void FeatureUninstalling(SPFeatureReceiverProperties properties) //{ //} // Uncomment the method below to handle the event raised when a feature is upgrading. //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters) //{ //} /// <summary> /// Send email to user /// </summary> /// <param name="subject"></param> /// <param name="body"></param> private void emailUser(string subject, string body, SPWeb currentWeb) { LogErrorHelper objEmail = new LogErrorHelper(LIST_SETTING, currentWeb); bool isEmailSent = objEmail.sendUserEmail(APP_NAME + " - EmailUser Function", subject, body, false); objEmail = null; }
public Task <HttpResponseMessage> Get() { HttpResponseMessage response = new HttpResponseMessage(); try { var todos = _todoRepository.Get(User.Identity.Name); response = Request.CreateResponse(HttpStatusCode.OK, todos.Select(x => new { id = x.Id, text = x.Title, done = x.Done })); } catch (Exception ex) { response = Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message); LogErrorHelper.Register(ex); } var tsc = new TaskCompletionSource <HttpResponseMessage>(); tsc.SetResult(response); return(tsc.Task); }
/// <summary> /// Method to insert a list item into a specific SharePoint list /// </summary> /// <param name="spSiteUrl"></param> /// <param name="listName"></param> /// <param name="colName"></param> /// <param name="itemValue"></param> public void AddListItem(string spSiteUrl, string listName, string colName, string itemValue) { try { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(spSiteUrl)) { using (SPWeb web = site.OpenWeb()) { web.AllowUnsafeUpdates = true; SPList list = web.Lists[listName]; SPListItem listItem = list.Items.Add(); listItem[colName] = itemValue; listItem.Update(); Thread.Sleep(1000); //Give SharePoint some time to update the changes web.Update(); Thread.Sleep(1000); //Give SharePoint some time to update the changes web.AllowUnsafeUpdates = false; } } }); } catch (Exception err) { LogErrorHelper objErr = new LogErrorHelper(); objErr.logErrorEmail(APP_NAME, err, "Error at AddListItem function"); objErr = null; SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(APP_NAME, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, err.Message.ToString(), err.StackTrace); } }
public bool Delete(int id) { try { var clie = _dbContext.Clientes.Where(a => a.Id == id).FirstOrDefault(); if (clie != null) { string error = ValidDelete(clie); if (error != string.Empty) { throw new Exception("Ocurrio un error en el Delete: " + error); } _dbContext.Clientes.Remove(clie); _dbContext.SaveChanges(); } return(true); } catch (Exception ex) { LogErrorHelper.LogError(ex); return(false); } }
public Task <HttpResponseMessage> Register(RegisterUserViewModel model) { HttpResponseMessage response = new HttpResponseMessage(); try { // Registra o usuário var user = new User(model.Name, model.Email, model.Password); _repository.SaveOrUpdate(user); response = Request.CreateResponse(HttpStatusCode.OK, "Usuário registrado com sucesso!"); } catch (DbUpdateException ex) { if (ex.InnerException.InnerException.Message.Contains("IX_USER_EMAIL")) { response = Request.CreateResponse(HttpStatusCode.BadRequest, "Este E-mail já está em uso no sistema."); } } catch (Exception ex) { response = Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message); LogErrorHelper.Register(ex); } var tsc = new TaskCompletionSource <HttpResponseMessage>(); tsc.SetResult(response); return(tsc.Task); }
/// <summary> /// Function to insert a log item into a SharePoint log list /// </summary> /// <param name="spSiteUrl"></param> /// <param name="listName"></param> /// <param name="errTitle"></param> /// <param name="errMsg"></param> public void AddLogListItem(string spSiteUrl, string errTitle, string errMsg, string docFileName, string pdfFileName, string itemID, bool convertStatus) { try { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(spSiteUrl)) { using (SPWeb web = site.OpenWeb()) { string listName = GetRCRSettingsItem("SPLogList"); SPFieldUserValue loginUser = GetCurrentUser(web); web.AllowUnsafeUpdates = true; SPList list = web.Lists[listName]; SPListItem listItem = list.Items.Add(); listItem["Title"] = errTitle; listItem["DescriptionLog"] = errMsg; listItem["DocFileName"] = docFileName; listItem["PdfFileName"] = pdfFileName; listItem["DocID"] = itemID; listItem["ConvertDate"] = DateTime.Now; if (convertStatus == true) { listItem["ConvertStatus"] = "Success"; } else { listItem["ConvertStatus"] = "Failed"; } if (loginUser != null) { listItem["Modified By"] = loginUser; } listItem.Update(); Thread.Sleep(1000); //Give SharePoint some time to update the changes web.Update(); Thread.Sleep(1000); //Give SharePoint some time to update the changes web.AllowUnsafeUpdates = false; } } }); } catch (Exception err) { LogErrorHelper objErr = new LogErrorHelper(); objErr.logErrorEmail(APP_NAME, err, "Error at AddLogListItem function"); objErr = null; SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(APP_NAME, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, err.Message.ToString(), err.StackTrace); } }
/// <summary> /// Workflow activity to send email /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void sendEmail_ExecuteCode(object sender, EventArgs e) { string docFileName = workflowProperties.WebUrl + "/" + workflowProperties.ItemUrl; string pdfFileName = ""; string itemID = workflowProperties.Item.ID.ToString(); string spSiteUrl = SPContext.Current.Site.Url; try { using (SPWeb spWeb = SPContext.Current.Site.OpenWeb(SPContext.Current.Web.ServerRelativeUrl)) { SharePointHelper objSPHelper = new SharePointHelper(PDF_SETTING_LIST, "EmailFrom", spWeb); SPFieldUserValue currentUser = objSPHelper.GetCurrentUser(spWeb); StringBuilder emailBody = new StringBuilder(); string Title = "PDF Conversion Notification"; string EmailTo = currentUser.User.Email; emailBody.Append("Dear " + currentUser.User.Name + ",<br>"); if (isDocWordFormat) { pdfFileName = Path.ChangeExtension(docFileName, "pdf"); emailBody.Append("<p>The document " + docFileName + " is in the process for PDF conversion. Please wait for the PDF file link below to be made availiable.</p><p><b>PDF file:</b> " + pdfFileName + "</p>"); } else { emailBody.Append("<p>The document " + docFileName + " is NOT a valid word document file type. Please select the correct word document (*.docx) format for PDF conversion."); } if (EmailTo.Length > 0) { //Send email to user SPUtility.SendEmail(SPContext.Current.Web, true, false, EmailTo, Title, emailBody.ToString()); WriteWFLog("PDF Notification Email", "Email has been successfully sent to " + EmailTo, spSiteUrl, docFileName, pdfFileName, itemID, true); } else { WriteWFLog("PDF Notification Email", "Email address is blank and has not been successfully sent", spSiteUrl, docFileName, pdfFileName, itemID, true); } objSPHelper = null; currentUser = null; } } catch (Exception err) { SPWeb spCurrentWeb = SPContext.Current.Site.OpenWeb(SPContext.Current.Web.ServerRelativeUrl); LogErrorHelper objErr = new LogErrorHelper(PDF_SETTING_LIST, spCurrentWeb); objErr.logSysErrorEmail(APP_NAME, err, "Error at sendEmail_ExecuteCode function"); objErr = null; spCurrentWeb = null; SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(APP_NAME, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, err.Message.ToString(), err.StackTrace); WriteWFLog("ERROR sending email to user!", err.Message.ToString(), spSiteUrl, docFileName, "", itemID, false); } }
/// <summary> /// Add a new choice column to a specific SharePoint list /// </summary> /// <param name="spSiteUrl"></param> /// <param name="listName"></param> /// <param name="displayColName"></param> /// <param name="arrChoices"></param> public void CreateNewColumnListChoiceType(string spSiteUrl, string listName, string displayColName, string[] arrChoices, string Description) { try { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(spSiteUrl)) { using (SPWeb web = site.OpenWeb()) { SPList list = web.Lists[listName]; //check if column exist if (list.Fields.ContainsField(displayColName) == false) { //Only add new column if one does not yet exist web.AllowUnsafeUpdates = true; list.Fields.Add(displayColName, SPFieldType.Choice, false); var fldChoice = list.Fields[displayColName] as SPFieldChoice; if (fldChoice != null) { string defaultChoiceValue = ""; for (int i = 0; i <= arrChoices.Length - 1; i++) { if (i == 0) { defaultChoiceValue = arrChoices[i]; } fldChoice.Choices.Add(arrChoices[i].ToString()); } fldChoice.DefaultValue = defaultChoiceValue; fldChoice.Description = Description; fldChoice.Update(); } list.Update(); web.Update(); web.AllowUnsafeUpdates = false; } } } }); } catch (Exception err) { LogErrorHelper objErr = new LogErrorHelper(); objErr.logErrorEmail(APP_NAME, err, "Error at CreateNewColumnListChoiceType function"); objErr = null; SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(APP_NAME, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, err.Message.ToString(), err.StackTrace); } }
/// <summary> /// Get value content of a specific list /// </summary> /// <param name="spListName"></param> /// <param name="spQueryStr"></param> /// <param name="spFieldName"></param> /// <returns></returns> public string GetSharePointListItem(string spListName, string spQueryStr, string spFieldName, bool displayTitle) { try { string spListContentItem = ""; using (SPWeb web = SPContext.Current.Web) { SPList spList = web.Lists[spListName]; SPQuery spQuery = new SPQuery(); spQuery.Query = spQueryStr; SPListItemCollection spListItems = spList.GetItems(spQuery); if (spListItems.Count >= 1) { foreach (SPListItem item in spListItems) { if (displayTitle) { string strDate = ""; string title = ""; if (spListName.ToString().ToLower() == "news") { DateTime dat = Convert.ToDateTime(item["PublishDate"].ToString()); strDate = "<div class='NewsDate'>" + dat.Day.ToString() + " " + getMonthName(dat.Month) + " " + dat.Year.ToString() + "</div><br>"; } title = strDate + "<div class='NewsItemTitle'>" + item["Title"].ToString() + "</div><br>"; spListContentItem = title + item[spFieldName].ToString(); } else { spListContentItem = item[spFieldName].ToString(); } } } } return(spListContentItem); } catch (Exception err) { LogErrorHelper objErr = new LogErrorHelper(); objErr.logErrorEmail(APP_NAME, err, "Error at GetSharePointListItem function"); objErr = null; SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(APP_NAME, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, err.Message.ToString(), err.StackTrace); return(string.Empty); } }
/// <summary> /// Method to retreive user profile by account name /// </summary> /// <param name="byPersonName"></param> public bool getUserProfileDetailsByAccountNameWithPrivileges(string byAccountName, SPWeb currentWeb, SPSite site) { try { bool isUserFound = false; SPSecurity.RunWithElevatedPrivileges(delegate() { //SPSite site = SPContext.Current.Site; ServerContext ospServerContext = ServerContext.GetContext(site); UserProfileManager ospUserProfileManager = new UserProfileManager(ospServerContext); if (ospUserProfileManager != null) { upFieldName = new List <string>(); upFieldValue = new List <string>(); //Search through all user profile property fields foreach (UserProfile user in ospUserProfileManager) { if (user.MultiloginAccounts[0].ToLower() == byAccountName.ToLower()) { foreach (ProfileSubtypeProperty prop in user.Properties) { if (prop.Name != null) { getUserProfilePropertyValue(prop, user, currentWeb); } } //Send email with any user profile fields not map to a custom list reportUnManagedUserProfileProperties(currentWeb); isUserFound = true; //Search user has been found } } } }); return(isUserFound); } catch (Exception err) { LogErrorHelper objErr = new LogErrorHelper(LIST_SETTING_NAME, currentWeb); objErr.logSysErrorEmail(APP_NAME, err, "Error at getUserProfileDetailsByAccountNameWithPrivileges function"); objErr = null; SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(APP_NAME, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, err.Message.ToString(), err.StackTrace); return(false); } }
/// <summary> /// Add a new Note column into a specific list /// </summary> /// <param name="spSiteUrl"></param> /// <param name="listName"></param> /// <param name="displayColName"></param> /// <param name="isMandatory"></param> /// <param name="isMultiLine"></param> public void CreateNewColumnListNoteType(string spSiteUrl, string listName, string displayColName, bool isMandatory, bool isMultiLine) { try { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(spSiteUrl)) { using (SPWeb web = site.OpenWeb()) { SPList list = web.Lists[listName]; //check if column exist if (list.Fields.ContainsField(displayColName) == false) {//Only add new column if one does not yet exist web.AllowUnsafeUpdates = true; list.Fields.Add(displayColName, SPFieldType.Note, isMandatory); if (isMultiLine) { var fldMultiLine = list.Fields[displayColName] as SPFieldMultiLineText; if (fldMultiLine != null) { fldMultiLine.NumberOfLines = 6; fldMultiLine.Update(); } } list.Update(); web.Update(); web.AllowUnsafeUpdates = false; } } } }); } catch (Exception err) { LogErrorHelper objErr = new LogErrorHelper(); objErr.logErrorEmail(APP_NAME, err, "Error at CreateNewColumnListNoteType function"); objErr = null; SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(APP_NAME, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, err.Message.ToString(), err.StackTrace); } }
private bool getUserProfileDetailsById_BUG(long byUserID, SPWeb currentWeb, SPSite site) { try { //SPSite site = SPContext.Current.Site; SPServiceContext ospServerContext = SPServiceContext.GetContext(site); UserProfileManager ospUserProfileManager = new UserProfileManager(ospServerContext); UserProfile ospUserProfile = ospUserProfileManager.GetUserProfile(byUserID); Microsoft.Office.Server.UserProfiles.PropertyCollection propColl = ospUserProfile.ProfileManager.PropertiesWithSection; if (ospUserProfile != null && propColl != null) { upFieldName = new List <string>(); upFieldValue = new List <string>(); //Search through all user profile property fields foreach (Property prop in propColl) { //Console.WriteLine("property Name : " + prop.Name); //Console.WriteLine("proerpty Value : " + ospUserProfile[prop.Name].Value); UserProfileValueCollection proValCol = ospUserProfile[prop.Name]; mapUserProfilePropertyValue(proValCol, prop, prop.Name, ospUserProfile[prop.Name].Value.ToString()); } //Send email with any user profile fields not map to a custom list reportUnManagedUserProfileProperties(currentWeb); return(true); } else { return(false); } } catch (Exception err) { LogErrorHelper objErr = new LogErrorHelper(LIST_SETTING_NAME, currentWeb); objErr.logSysErrorEmail(APP_NAME, err, "Error at getUserProfileDetailsById function"); objErr = null; SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(APP_NAME, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, err.Message.ToString(), err.StackTrace); return(false); } }
/// <summary> /// Function to get folder url /// </summary> /// <param name="folders"></param> /// <param name="folderUrl"></param> /// <returns></returns> private static SPFolder GetFolderByUrl(SPListItemCollection folders, string folderUrl) { SPFolder folder = null; try { if (folders == null) { throw new ArgumentNullException("folders"); } if (String.IsNullOrEmpty(folderUrl)) { throw new ArgumentNullException("folderUrl"); } SPListItem item = (from SPListItem i in folders where i.Url.Equals(folderUrl, StringComparison.InvariantCultureIgnoreCase) select i).FirstOrDefault(); if (item != null) { folder = item.Folder; } } catch (Exception err) { using (SPSite oSPSite = new SPSite(SPContext.Current.Site.Url)) { using (SPWeb oSPWeb = oSPSite.OpenWeb()) { LogErrorHelper logHelper = new LogErrorHelper(LIST_SETTING, oSPWeb); logHelper.logSysErrorEmail(APP_NAME, err, "GetFolderByUrl Error!"); logHelper = null; } } SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(APP_NAME, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, err.Message.ToString(), err.StackTrace); } return(folder); }
/// <summary> /// Get configuration settings from the list /// </summary> /// <param name="category"></param> /// <returns></returns> public string GetRCRSettingsItem(string category) { string description = string.Empty; try { if (category == string.Empty) { return(description); } using (SPWeb web = SPContext.Current.Web) { SPList spList = web.Lists["PDF Settings"]; SPQuery spQuery = new SPQuery(); spQuery.Query = @"<Where><Eq><FieldRef Name='SettingsCategory'/><Value Type='CHOICE'>" + category + "</Value></Eq></Where>"; spQuery.ViewFields = String.Concat("<FieldRef Name='SettingsValue'/>"); spQuery.ViewFieldsOnly = true; spQuery.RowLimit = 1; SPListItemCollection spListItems = spList.GetItems(spQuery); if (spListItems != null) { foreach (SPListItem spListItem in spListItems) { if (spListItem["SettingsValue"] != null) { description = spListItem["SettingsValue"].ToString(); } } } } return(description); } catch (Exception err) { LogErrorHelper objErr = new LogErrorHelper(); objErr.logErrorEmail(APP_NAME, err, "Error at GetRCRSettingsItem function"); objErr = null; SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(APP_NAME, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, err.Message.ToString(), err.StackTrace); return(string.Empty); } }
/// <summary> /// Function to publish all files inside folder /// </summary> /// <param name="folder"></param> /// <param name="featureId"></param> private static void PublishFiles(SPFolder folder, string featureId) { try { if (folder == null) { throw new ArgumentNullException("folder"); } if (String.IsNullOrEmpty(featureId)) { throw new ArgumentNullException("featureId"); } SPFileCollection files = folder.Files; var drafts = from SPFile f in files where String.Equals(f.Properties["FeatureId"] as string, featureId, StringComparison.InvariantCultureIgnoreCase) && f.Level == SPFileLevel.Draft select f; foreach (SPFile f in drafts) { f.Publish(""); f.Update(); } } catch (Exception err) { using (SPSite oSPSite = new SPSite(SPContext.Current.Site.Url)) { using (SPWeb oSPWeb = oSPSite.OpenWeb()) { LogErrorHelper logHelper = new LogErrorHelper(LIST_SETTING, oSPWeb); logHelper.logSysErrorEmail(APP_NAME, err, "PublishFiles Error!"); logHelper = null; } } SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(APP_NAME, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, err.Message.ToString(), err.StackTrace); } }
/// <summary> /// Function to activate the SAO feature /// </summary> /// <param name="properties"></param> public override void FeatureActivated(SPFeatureReceiverProperties properties) { try { SPSite site = properties.Feature.Parent as SPSite; if (site != null) { SPWeb rootWeb = site.RootWeb; SPList gallery = site.GetCatalog(SPListTemplateType.MasterPageCatalog); if (gallery != null) { SPListItemCollection folders = gallery.Folders; string featureId = properties.Feature.Definition.Id.ToString(); foreach (string folderUrl in folderUrls) { SPFolder folder = GetFolderByUrl(folders, folderUrl); if (folder != null) { PublishFiles(folder, featureId); } } } } } catch (Exception err) { using (SPSite oSPSite = new SPSite(SPContext.Current.Site.Url)) { using (SPWeb oSPWeb = oSPSite.OpenWeb()) { LogErrorHelper logHelper = new LogErrorHelper(LIST_SETTING, oSPWeb); logHelper.logSysErrorEmail(APP_NAME, err, "FeatureActivated Error!"); logHelper = null; } } SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(APP_NAME, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, err.Message.ToString(), err.StackTrace); } }