protected void SaveOrUpdateDeal(Object sender, CommandEventArgs e) { try { using (var scope = DIHelper.Resolve()) { var dao = scope.Resolve <DaoFactory>(); int dealID; var _isPrivate = false; var _selectedUsersWithoutCurUsr = new List <Guid>(); #region BaseInfo var deal = new Deal { Title = Request["nameDeal"], Description = Request["descriptionDeal"], DealMilestoneID = Convert.ToInt32(Request["dealMilestone"]) }; int contactID; if (int.TryParse(Request["selectedContactID"], out contactID)) { deal.ContactID = contactID; } int probability; if (int.TryParse(Request["probability"], out probability)) { deal.DealMilestoneProbability = probability; } if (deal.DealMilestoneProbability < 0) { deal.DealMilestoneProbability = 0; } if (deal.DealMilestoneProbability > 100) { deal.DealMilestoneProbability = 100; } deal.BidCurrency = Request["bidCurrency"]; if (String.IsNullOrEmpty(deal.BidCurrency)) { deal.BidCurrency = Global.TenantSettings.DefaultCurrency.Abbreviation; } else { deal.BidCurrency = deal.BidCurrency.ToUpper(); } if (!String.IsNullOrEmpty(Request["bidValue"])) { decimal bidValue; if (!decimal.TryParse(Request["bidValue"], out bidValue)) { bidValue = 0; } deal.BidValue = bidValue; deal.BidType = (BidType)Enum.Parse(typeof(BidType), Request["bidType"]); if (deal.BidType != BidType.FixedBid) { int perPeriodValue; if (int.TryParse(Request["perPeriodValue"], out perPeriodValue)) { deal.PerPeriodValue = perPeriodValue; } } } else { deal.BidValue = 0; deal.BidType = BidType.FixedBid; } DateTime expectedCloseDate; if (!DateTime.TryParse(Request["expectedCloseDate"], out expectedCloseDate)) { expectedCloseDate = DateTime.MinValue; } deal.ExpectedCloseDate = expectedCloseDate; deal.ResponsibleID = new Guid(Request["responsibleID"]); #endregion #region Validation CRMSecurity.DemandCreateOrUpdate(deal); if (HavePermission) { var CurrentAccountID = SecurityContext.CurrentAccount.ID; bool value; if (bool.TryParse(Request.Form["isPrivateDeal"], out value)) { _isPrivate = value; } if (_isPrivate) { _selectedUsersWithoutCurUsr = Request.Form["selectedPrivateUsers"] .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(item => new Guid(item)).Where(i => i != CurrentAccountID).Distinct().ToList(); foreach (var uID in _selectedUsersWithoutCurUsr) { var usr = CoreContext.UserManager.GetUsers(uID); if (usr.IsVisitor()) { throw new ArgumentException(); } } if (deal.ResponsibleID != CurrentAccountID) { _selectedUsersWithoutCurUsr.Add(deal.ResponsibleID); var responsible = CoreContext.UserManager.GetUsers(deal.ResponsibleID); if (responsible.IsVisitor()) { throw new ArgumentException(CRMErrorsResource.ResponsibleCannotBeVisitor); } } } } #endregion var dealMilestone = dao.DealMilestoneDao.GetByID(deal.DealMilestoneID); if (TargetDeal == null) { if (dealMilestone.Status != DealMilestoneStatus.Open) { deal.ActualCloseDate = TenantUtil.DateTimeNow(); } dealID = dao.DealDao.CreateNewDeal(deal); deal.ID = dealID; deal.CreateBy = SecurityContext.CurrentAccount.ID; deal.CreateOn = TenantUtil.DateTimeNow(); deal = dao.DealDao.GetByID(dealID); SetPermission(deal, _isPrivate, _selectedUsersWithoutCurUsr); if (deal.ResponsibleID != Guid.Empty && deal.ResponsibleID != SecurityContext.CurrentAccount.ID) { NotifyClient.Instance.SendAboutResponsibleForOpportunity(deal); } MessageService.Send(HttpContext.Current.Request, MessageAction.OpportunityCreated, MessageTarget.Create(deal.ID), deal.Title); } else { dealID = TargetDeal.ID; deal.ID = TargetDeal.ID; deal.ActualCloseDate = TargetDeal.ActualCloseDate; if (TargetDeal.ResponsibleID != Guid.Empty && TargetDeal.ResponsibleID != deal.ResponsibleID) { NotifyClient.Instance.SendAboutResponsibleForOpportunity(deal); } if (TargetDeal.DealMilestoneID != deal.DealMilestoneID) { deal.ActualCloseDate = dealMilestone.Status != DealMilestoneStatus.Open ? TenantUtil.DateTimeNow() : DateTime.MinValue; } dao.DealDao.EditDeal(deal); deal = dao.DealDao.GetByID(dealID); SetPermission(deal, _isPrivate, _selectedUsersWithoutCurUsr); MessageService.Send(HttpContext.Current.Request, MessageAction.OpportunityUpdated, MessageTarget.Create(deal.ID), deal.Title); } #region Members var dealMembers = !String.IsNullOrEmpty(Request["selectedMembersID"]) ? Request["selectedMembersID"].Split(new[] { ',' }).Select( id => Convert.ToInt32(id)).Where(id => id != deal.ContactID).ToList() : new List <int>(); var dealMembersContacts = dao.ContactDao.GetContacts(dealMembers.ToArray()).Where(CRMSecurity.CanAccessTo).ToList(); dealMembers = dealMembersContacts.Select(m => m.ID).ToList(); if (deal.ContactID > 0) { dealMembers.Add(deal.ContactID); } dao.DealDao.SetMembers(dealID, dealMembers.ToArray()); #endregion #region CustomFields foreach (var customField in Request.Form.AllKeys) { if (!customField.StartsWith("customField_")) { continue; } var fieldID = Convert.ToInt32(customField.Split('_')[1]); var fieldValue = Request.Form[customField]; if (String.IsNullOrEmpty(fieldValue) && TargetDeal == null) { continue; } dao.CustomFieldDao.SetFieldValue(EntityType.Opportunity, dealID, fieldID, fieldValue); } #endregion string redirectUrl; if (TargetDeal == null && UrlParameters.ContactID != 0) { redirectUrl = string.Format( e.CommandArgument.ToString() == "1" ? "deals.aspx?action=manage&contactID={0}" : "default.aspx?id={0}#deals", UrlParameters.ContactID); } else { redirectUrl = e.CommandArgument.ToString() == "1" ? "deals.aspx?action=manage" : string.Format("deals.aspx?id={0}", dealID); } Response.Redirect(redirectUrl, false); Context.ApplicationInstance.CompleteRequest(); } } catch (Exception ex) { LogManager.GetLogger("ASC.CRM").Error(ex); var cookie = HttpContext.Current.Request.Cookies.Get(ErrorCookieKey); if (cookie == null) { cookie = new HttpCookie(ErrorCookieKey) { Value = ex.Message }; HttpContext.Current.Response.Cookies.Add(cookie); } } }
protected void Page_Load(object sender, EventArgs e) { if (UrlParameters.Action != "export") { InitPage(); } else { var contacts = GetContactsByFilter(); if (UrlParameters.View != "editor") { Response.Clear(); Response.ContentType = "text/csv; charset=utf-8"; Response.ContentEncoding = Encoding.UTF8; Response.Charset = Encoding.UTF8.WebName; const string fileName = "contacts.csv"; Response.AppendHeader("Content-Disposition", String.Format("attachment; filename={0}", fileName)); Response.Write(ExportToCSV.ExportContactsToCSV(contacts, false)); MessageService.Send(HttpContext.Current.Request, MessageAction.ContactsExportedToCsv, MessageTarget.Create(contacts.Select(x => x.ID)), contacts.Select(x => x.GetTitle())); Response.End(); } else { var fileUrl = ExportToCSV.ExportContactsToCSV(contacts, true); Response.Redirect(fileUrl); } } }
private OpportunityWrapper SetAccessToDeal(Deal deal, bool isPrivate, IEnumerable <Guid> accessList, bool isNotify, bool isMessageServicSende) { var accessListLocal = accessList != null?accessList.Distinct().ToList() : new List <Guid>(); if (isPrivate && accessListLocal.Count > 0) { if (isNotify) { accessListLocal = accessListLocal.Where(u => u != SecurityContext.CurrentAccount.ID).ToList(); ASC.Web.CRM.Services.NotifyService.NotifyClient.Instance.SendAboutSetAccess(EntityType.Opportunity, deal.ID, DaoFactory, accessListLocal.ToArray()); } if (!accessListLocal.Contains(SecurityContext.CurrentAccount.ID)) { accessListLocal.Add(SecurityContext.CurrentAccount.ID); } CRMSecurity.SetAccessTo(deal, accessListLocal); if (isMessageServicSende) { var users = GetUsersByIdList(accessListLocal); MessageService.Send(Request, MessageAction.OpportunityRestrictedAccess, MessageTarget.Create(deal.ID), deal.Title, users.Select(x => x.DisplayUserName(false))); } } else { CRMSecurity.MakePublic(deal); if (isMessageServicSende) { MessageService.Send(Request, MessageAction.OpportunityOpenedAccess, MessageTarget.Create(deal.ID), deal.Title); } } return(ToOpportunityWrapper(deal)); }
public object SaveMobilePhone(string query, string mobilePhone) { var user = GetUser(query); mobilePhone = SmsManager.SaveMobilePhone(user, mobilePhone); MessageService.Send(HttpContext.Current.Request, MessageAction.UserUpdatedMobileNumber, MessageTarget.Create(user.ID), user.DisplayUserName(false), mobilePhone); var mustConfirm = StudioSmsNotificationSettings.Enable; return (new { phoneNoise = SmsSender.BuildPhoneNoise(mobilePhone), confirm = mustConfirm, RefererURL = mustConfirm ? string.Empty : GetRefererURL() }); }
protected void Page_Load(object sender, EventArgs e) { if (SecurityContext.IsAuthenticated && User.ID != SecurityContext.CurrentAccount.ID) { Response.Redirect(GetRefererURL(), true); return; } if (!Activation && (!StudioSmsNotificationSettings.IsVisibleSettings || !StudioSmsNotificationSettings.Enable)) { Response.Redirect(GetRefererURL(), true); return; } if (IsPostBack && !Activation) { try { SmsManager.ValidateSmsCode(User, Request["phoneAuthcode"]); MessageService.Send(HttpContext.Current.Request, MessageAction.LoginSuccessViaSms); Response.Redirect(GetRefererURL(), true); } catch { MessageService.Send(HttpContext.Current.Request, User.DisplayUserName(false), MessageAction.LoginFailViaSms, MessageTarget.Create(User.ID)); } } var authCommunications = (AuthCommunications)LoadControl(AuthCommunications.Location); authCommunications.DisableJoin = true; _communitations.Controls.Add(authCommunications); AjaxPro.Utility.RegisterTypeForAjax(GetType()); Page.RegisterBodyScripts("~/UserControls/Management/SmsControls/js/confirmmobile.js") .RegisterStyle("~/UserControls/Management/SmsControls/css/confirmmobile.less"); if (string.IsNullOrEmpty(User.MobilePhone)) { Activation = true; } if (!Activation) { try { SmsManager.PutAuthCode(User, false); } catch (Exception) { Activation = true; } } if (Activation) { Country = new RegionInfo(Thread.CurrentThread.CurrentCulture.LCID).TwoLetterISORegionName; if (!CoreContext.Configuration.Standalone) { var ipGeolocationInfo = new GeolocationHelper("teamlabsite").GetIPGeolocationFromHttpContext(); if (ipGeolocationInfo != null) { Country = ipGeolocationInfo.Key; } } Page .RegisterClientScript(new CountriesResources()) .RegisterBodyScripts( "~/js/asc/plugins/countries.js", "~/js/asc/plugins/phonecontroller.js") .RegisterStyle("~/skins/default/phonecontroller.css"); } }
public DealMilestoneDto CreateDealMilestone([FromBody] CreateOrUpdateDealMilestoneRequestDto inDto) { var title = inDto.Title; var successProbability = inDto.SuccessProbability; var description = inDto.Description; var color = inDto.Color; var stageType = inDto.StageType; if (!(_crmSecurity.IsAdmin)) { throw _crmSecurity.CreateSecurityException(); } if (string.IsNullOrEmpty(title)) { throw new ArgumentException(); } if (successProbability < 0) { successProbability = 0; } var dealMilestone = new DealMilestone { Title = title, Color = color, Description = description, Probability = successProbability, Status = stageType }; dealMilestone.ID = _daoFactory.GetDealMilestoneDao().Create(dealMilestone); _messageService.Send(MessageAction.OpportunityStageCreated, _messageTarget.Create(dealMilestone.ID), dealMilestone.Title); return(ToDealMilestoneDto(dealMilestone)); }
protected void ExecInvoicePdfView(ASC.CRM.Core.Entities.Invoice targetInvoice) { var pdfFile = Global.GetInvoicePdfExistingOrCreate(targetInvoice); MessageService.Send(HttpContext.Current.Request, MessageAction.InvoiceDownloaded, MessageTarget.Create(targetInvoice.ID), targetInvoice.Number); Response.Redirect(CommonLinkUtility.GetFullAbsolutePath(pdfFile.FileDownloadUrl)); }
protected void SaveOrUpdateContact(object sender, CommandEventArgs e) { try { var dao = DaoFactory; Contact contact; List <Contact> contactsForSetManager = new List <Contact>(); var typeAddedContact = Request["typeAddedContact"]; #region Rights part #1 ShareType shareType = ShareType.None;// 0 - NotShared, 1 - ReadWriting, 2 - Reading if (!String.IsNullOrEmpty(Request["isPublicContact"])) { try { shareType = (ShareType)(Convert.ToInt32(Request["isPublicContact"])); } catch (Exception) { throw new ArgumentException(); } } #endregion #region BaseInfo var companyID = 0; if (!String.IsNullOrEmpty(Request["baseInfo_compID"])) { companyID = Convert.ToInt32(Request["baseInfo_compID"]); } else if (!String.IsNullOrEmpty(Request["baseInfo_compName"])) { var peopleCompany = new Company { CompanyName = Request["baseInfo_compName"].Trim(), ShareType = shareType }; peopleCompany.ID = dao.ContactDao.SaveContact(peopleCompany); companyID = peopleCompany.ID; contactsForSetManager.Add(peopleCompany); } if (typeAddedContact.Equals("people")) { contact = new Person { FirstName = Request["baseInfo_firstName"].Trim(), LastName = Request["baseInfo_lastName"].Trim(), JobTitle = Request["baseInfo_personPosition"].Trim(), CompanyID = companyID }; } else { contact = new Company { CompanyName = Request["baseInfo_companyName"].Trim() }; } contact.About = !String.IsNullOrEmpty(Request["baseInfo_contactOverview"]) ? Request["baseInfo_contactOverview"].Trim() : null; contact.ShareType = shareType; #endregion #region ContactType and Currency contact.ContactTypeID = Convert.ToInt32(Request["baseInfo_contactType"]); if (contact.ContactTypeID != 0) { var listItem = dao.ListItemDao.GetByID(contact.ContactTypeID); if (listItem == null) { throw new Exception(CRMErrorsResource.ContactTypeNotFound); } } contact.Currency = Convert.ToString(Request["baseInfo_currency"]); if (!String.IsNullOrEmpty(contact.Currency)) { var currency = CurrencyProvider.Get(contact.Currency); if (currency == null) { throw new Exception(CRMErrorsResource.CurrencyNotFound); } } #endregion #region Base Operation Of Save/Update if (TargetContact != null) { contact.ID = TargetContact.ID; contact.StatusID = TargetContact.StatusID; dao.ContactDao.UpdateContact(contact); var messageAction = contact is Company ? MessageAction.CompanyUpdated : MessageAction.PersonUpdated; MessageService.Send(HttpContext.Current.Request, messageAction, MessageTarget.Create(contact.ID), contact.GetTitle()); contact = dao.ContactDao.GetByID(contact.ID); } else { contact.ID = dao.ContactDao.SaveContact(contact); var messageAction = contact is Company ? MessageAction.CompanyCreated : MessageAction.PersonCreated; MessageService.Send(HttpContext.Current.Request, messageAction, MessageTarget.Create(contact.ID), contact.GetTitle()); contact = dao.ContactDao.GetByID(contact.ID); } contactsForSetManager.Add(contact); #endregion #region persons for company if (contact is Company) { var assignedContactsIDs = new List <int>(); if (!String.IsNullOrEmpty(Request["baseInfo_assignedNewContactsIDs"])) { try { var assignedContactsObjs = JArray.Parse(Request["baseInfo_assignedNewContactsIDs"]); var newAssignedContacts = new List <Contact>(); var recordIndex = 0; foreach (var assignedContactsObj in assignedContactsObjs) { newAssignedContacts.Add(new Person { ID = recordIndex, ShareType = shareType, CompanyID = contact.ID, FirstName = assignedContactsObj.Value <String>("FirstName"), LastName = assignedContactsObj.Value <String>("LastName") }); recordIndex++; } dao.ContactDao.SaveContactList(newAssignedContacts); if (newAssignedContacts.Count != 0) { contactsForSetManager.AddRange(newAssignedContacts); assignedContactsIDs.AddRange(newAssignedContacts.Select(c => c.ID).ToList()); } } catch (Exception ex) { log4net.LogManager.GetLogger("ASC.CRM").Error(ex); } } if (!String.IsNullOrEmpty(Request["baseInfo_assignedContactsIDs"])) { assignedContactsIDs.AddRange(Request["baseInfo_assignedContactsIDs"].Split(',').Select(item => Convert.ToInt32(item)).ToList()); } if (TargetContact != null && !CRMSecurity.IsAdmin) { var restrictedMembers = dao.ContactDao.GetRestrictedMembers(contact.ID); assignedContactsIDs.AddRange(restrictedMembers.Select(m => m.ID).ToList()); } dao.ContactDao.SetMembers(contact.ID, assignedContactsIDs.ToArray()); } #endregion #region tags var assignedTags = Request["baseInfo_assignedTags"]; if (assignedTags != null) { var oldTagList = dao.TagDao.GetEntityTags(EntityType.Contact, contact.ID); foreach (var tag in oldTagList) { dao.TagDao.DeleteTagFromEntity(EntityType.Contact, contact.ID, tag); } if (assignedTags != string.Empty) { var tagListInfo = JObject.Parse(assignedTags)["tagListInfo"].ToArray(); var newTagList = tagListInfo.Select(t => t.ToString()).ToArray(); dao.TagDao.SetTagToEntity(EntityType.Contact, contact.ID, newTagList); } } #endregion #region contact infos (addresses, mailes, phones etc.) var contactInfos = new List <ContactInfo>(); var addressList = new Dictionary <int, ContactInfo>(); var addressTemplate = new JObject(); foreach (String addressPartName in Enum.GetNames(typeof(AddressPart))) { addressTemplate.Add(addressPartName.ToLower(), ""); } var addressTemplateStr = addressTemplate.ToString(); foreach (var item in Request.Form.AllKeys) { if (item.StartsWith("customField_")) { int fieldID = Convert.ToInt32(item.Split('_')[1]); String fieldValue = Request.Form[item].Trim(); if (contact is Person) { if (!String.IsNullOrEmpty(fieldValue)) { dao.CustomFieldDao.SetFieldValue(EntityType.Person, contact.ID, fieldID, ""); } dao.CustomFieldDao.SetFieldValue(EntityType.Person, contact.ID, fieldID, fieldValue); } else { if (!String.IsNullOrEmpty(fieldValue)) { dao.CustomFieldDao.SetFieldValue(EntityType.Company, contact.ID, fieldID, ""); } dao.CustomFieldDao.SetFieldValue(EntityType.Company, contact.ID, fieldID, fieldValue); } } else if (item.StartsWith("contactInfo_")) { var nameParts = item.Split('_').Skip(1).ToList(); var contactInfoType = (ContactInfoType)Enum.Parse(typeof(ContactInfoType), nameParts[0]); var category = Convert.ToInt32(nameParts[2]); if (contactInfoType == ContactInfoType.Address) { var index = Convert.ToInt32(nameParts[1]); var addressPart = (AddressPart)Enum.Parse(typeof(AddressPart), nameParts[3]); var isPrimaryAddress = Convert.ToInt32(nameParts[4]) == 1; var dataValues = Request.Form.GetValues(item).Select(n => n.Trim()).ToList(); if (!addressList.ContainsKey(index)) { var newAddress = new ContactInfo { Category = category, InfoType = contactInfoType, Data = addressTemplateStr, IsPrimary = isPrimaryAddress, ContactID = contact.ID }; addressList.Add(index, newAddress); } foreach (var data in dataValues) { var addressParts = JObject.Parse(addressList[index].Data); addressParts[addressPart.ToString().ToLower()] = data; addressList[index].Data = addressParts.ToString(); } continue; } var isPrimary = Convert.ToInt32(nameParts[3]) == 1; if (Request.Form.GetValues(item) != null) { var dataValues = Request.Form.GetValues(item).Where(n => !string.IsNullOrEmpty(n.Trim())).ToList(); contactInfos.AddRange(dataValues.Select(dataValue => new ContactInfo { Category = category, InfoType = contactInfoType, Data = dataValue.Trim(), IsPrimary = isPrimary, ContactID = contact.ID })); } } } if (addressList.Count > 0) { contactInfos.AddRange(addressList.Values.ToList()); } dao.ContactInfoDao.DeleteByContact(contact.ID); dao.ContactInfoDao.SaveList(contactInfos); #endregion #region Photo var imagePath = Request["uploadPhotoPath"]; if (!String.IsNullOrEmpty(imagePath)) { ContactPhotoManager.TryUploadPhotoFromTmp(contact.ID, TargetContact == null, TargetContact == null ? imagePath : ""); } else if (TargetContact != null) { ContactPhotoManager.DeletePhoto(TargetContact.ID); } #endregion #region Rights part #2 SetContactManager(contactsForSetManager); #endregion #region Link with mail message int result; var linkMessageId = int.TryParse(Request["linkMessageId"], out result) ? result : 0; if (linkMessageId > 0) { try { LinkWithMessage(linkMessageId, contact.ID); } catch (Exception ex) { log4net.LogManager.GetLogger("ASC.CRM").Error(ex); } } #endregion Response.Redirect(String.Compare(e.CommandArgument.ToString(), "0", true) == 0 ? String.Format("default.aspx?id={0}{1}", contact.ID, contact is Company ? "" : String.Format("&{0}=people", UrlConstant.Type)) : String.Format("default.aspx?action=manage{0}", contact is Company ? "" : String.Format("&{0}=people", UrlConstant.Type)), false); Context.ApplicationInstance.CompleteRequest(); } catch (Exception ex) { log4net.LogManager.GetLogger("ASC.CRM").Error(ex); var cookie = HttpContext.Current.Request.Cookies.Get(ErrorCookieKey); if (cookie == null) { cookie = new HttpCookie(ErrorCookieKey) { Value = ex.Message }; HttpContext.Current.Response.Cookies.Add(cookie); } } }
public object ChangeOwner(Guid ownerId) { try { SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); var curTenant = CoreContext.TenantManager.GetCurrentTenant(); var owner = CoreContext.UserManager.GetUsers(curTenant.OwnerId); if (owner.IsVisitor()) { throw new System.Security.SecurityException("Collaborator can not be an owner"); } if (curTenant.OwnerId.Equals(SecurityContext.CurrentAccount.ID) && !Guid.Empty.Equals(ownerId)) { var confirmLink = CommonLinkUtility.GetConfirmationUrl(owner.Email, ConfirmType.PortalOwnerChange, ownerId, ownerId); StudioNotifyService.Instance.SendMsgConfirmChangeOwner(curTenant, CoreContext.UserManager.GetUsers(ownerId).DisplayUserName(), confirmLink); MessageService.Send(HttpContext.Current.Request, MessageAction.OwnerSentChangeOwnerInstructions, MessageTarget.Create(owner.ID), owner.DisplayUserName(false)); var emailLink = string.Format("<a href=\"mailto:{0}\">{0}</a>", owner.Email); return(new { Status = 1, Message = Resource.ChangePortalOwnerMsg.Replace(":email", emailLink) }); } return(new { Status = 0, Message = Resource.ErrorAccessDenied }); } catch (Exception e) { return(new { Status = 0, Message = e.Message.HtmlEncode() }); } }
public object Resend() { try { foreach (var user in new List <UserInfo>(CoreContext.UserManager.GetUsers()) .FindAll(u => u.ActivationStatus == EmployeeActivationStatus.Pending)) { if (user.IsVisitor()) { StudioNotifyService.Instance.GuestInfoActivation(user); } else { StudioNotifyService.Instance.UserInfoActivation(user); } MessageService.Send(HttpContext.Current.Request, MessageAction.UserSentActivationInstructions, MessageTarget.Create(user.ID), user.DisplayUserName(false)); } return(new { status = 1, message = Resources.Resource.SuccessResendInvitesText }); } catch (Exception e) { return(new { status = 0, message = e.Message.HtmlEncode() }); } }
private void SendSuccessNotify(long docsSpace, long crmSpace, long mailSpace, long talkSpace) { if (_notify) { StudioNotifyService.Instance.SendMsgRemoveUserDataCompleted(_currentUserId, _userId, _userName, docsSpace, crmSpace, mailSpace, talkSpace); } if (_httpHeaders != null) { MessageService.Send(_httpHeaders, MessageAction.UserDataRemoving, MessageTarget.Create(_userId), new[] { _userName }); } else { MessageService.Send(_context.Request, MessageAction.UserDataRemoving, MessageTarget.Create(_userId), _userName); } }
[Create(@"{code}", false, false)] //NOTE: this method doesn't requires auth!!! //NOTE: this method doesn't check payment!!! public AuthenticationTokenData AuthenticateMe(string userName, string password, string provider, string accessToken, string code) { bool viaEmail; var user = GetUser(userName, password, provider, accessToken, out viaEmail); try { SmsManager.ValidateSmsCode(user, code); var token = SecurityContext.AuthenticateMe(user.ID); MessageService.Send(Request, MessageAction.LoginSuccessViaApiSms); return(new AuthenticationTokenData { Token = token, Expires = new ApiDateTime(DateTime.UtcNow.AddYears(1)), Sms = true, PhoneNoise = SmsManager.BuildPhoneNoise(user.MobilePhone) }); } catch { MessageService.Send(Request, user.DisplayUserName(false), MessageAction.LoginFailViaApiSms, MessageTarget.Create(user.ID)); throw new AuthenticationException("User authentication failed"); } finally { SecurityContext.Logout(); } }
[Create(@"setphone", false, false)] //NOTE: this method doesn't requires auth!!! //NOTE: this method doesn't check payment!!! public AuthenticationTokenData SaveMobilePhone(string userName, string password, string provider, string accessToken, string mobilePhone) { bool viaEmail; var user = GetUser(userName, password, provider, accessToken, out viaEmail); mobilePhone = SmsManager.SaveMobilePhone(user, mobilePhone); MessageService.Send(HttpContext.Current.Request, MessageAction.UserUpdatedMobileNumber, MessageTarget.Create(user.ID), user.DisplayUserName(false), mobilePhone); return(new AuthenticationTokenData { Sms = true, PhoneNoise = SmsManager.BuildPhoneNoise(mobilePhone), Expires = new ApiDateTime(DateTime.UtcNow.Add(SmsKeyStorage.TrustInterval)) }); }
public void ProcessRequest(HttpContext context) { try { using (var scope = DIHelper.Resolve()) { var daoFactory = scope.Resolve <DaoFactory>(); _context = context; SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem); if (!CheckPermission()) { throw new Exception(CRMSettingResource.WebToLeadsForm_InvalidKeyException); } var productInfo = WebItemSecurity.GetSecurityInfo(ProductEntryPoint.ID.ToString()); if (!productInfo.Enabled) { throw new Exception(CRMCommonResource.CRMProductIsDisabled); } Contact contact; var fieldCollector = new NameValueCollection(); var addressTemplate = new JObject(); foreach (String addressPartName in Enum.GetNames(typeof(AddressPart))) { addressTemplate.Add(addressPartName.ToLower(), ""); } var addressTemplateStr = addressTemplate.ToString(); var isCompany = false; var isCompanyString = GetValue("is_company"); var firstName = GetValue("firstName"); var lastName = GetValue("lastName"); var companyName = GetValue("companyName"); if (!String.IsNullOrEmpty(isCompanyString)) { if (!Boolean.TryParse(isCompanyString, out isCompany)) { throw new ArgumentException(); } } else //old scheme { if (!String.IsNullOrEmpty(firstName)) { isCompany = false; } else if (!String.IsNullOrEmpty(companyName)) { isCompany = true; } else { throw new ArgumentException(); } } if (isCompany) { contact = new Company(); ((Company)contact).CompanyName = companyName; fieldCollector.Add(CRMContactResource.CompanyName, companyName); } else { contact = new Person(); ((Person)contact).FirstName = firstName; ((Person)contact).LastName = lastName; ((Person)contact).JobTitle = GetValue("jobTitle"); fieldCollector.Add(CRMContactResource.FirstName, firstName); fieldCollector.Add(CRMContactResource.LastName, lastName); if (!String.IsNullOrEmpty(GetValue("jobTitle"))) { fieldCollector.Add(CRMContactResource.JobTitle, ((Person)contact).JobTitle); } } contact.About = GetValue("about"); if (!String.IsNullOrEmpty(contact.About)) { fieldCollector.Add(CRMContactResource.About, contact.About); } if (!String.IsNullOrEmpty(GetValue("is_shared"))) { contact.ShareType = Convert.ToBoolean(GetValue("is_shared")) ? ShareType.ReadWrite : ShareType.None; } else { contact.ShareType = (ShareType)(Convert.ToInt32(GetValue("share_type"))); } contact.ID = daoFactory.ContactDao.SaveContact(contact); var messageAction = contact is Company ? MessageAction.CompanyCreatedWithWebForm : MessageAction.PersonCreatedWithWebForm; MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, messageAction, MessageTarget.Create(contact.ID), contact.GetTitle()); var contactInfos = new List <ContactInfo>(); foreach (var key in _context.Request.Form.AllKeys) { if (key.StartsWith("customField_")) { var fieldID = Convert.ToInt32(key.Split(new[] { '_' })[1]); String fieldValue = GetValue(key); if (String.IsNullOrEmpty(fieldValue)) { continue; } var customField = daoFactory.CustomFieldDao.GetFieldDescription(fieldID); if (customField == null || !(customField.EntityType == EntityType.Contact || customField.EntityType == EntityType.Company && isCompany || customField.EntityType == EntityType.Person && !isCompany)) { continue; } if (customField.FieldType == CustomFieldType.CheckBox) { fieldValue = fieldValue == "on" || fieldValue == "true" ? "true" : "false"; } fieldCollector.Add(customField.Label, fieldValue); daoFactory.CustomFieldDao.SetFieldValue(isCompany ? EntityType.Company : EntityType.Person, contact.ID, fieldID, fieldValue); } else if (key.StartsWith("contactInfo_")) { var nameParts = key.Split(new[] { '_' }).Skip(1).ToList(); var contactInfoType = (ContactInfoType)Enum.Parse(typeof(ContactInfoType), nameParts[0]); var category = Convert.ToInt32(nameParts[1]); bool categoryIsExists = Enum.GetValues(ContactInfo.GetCategory(contactInfoType)) .Cast <object>() .Any(categoryEnum => (int)categoryEnum == category); if (!categoryIsExists) { throw new ArgumentException(String.Format("Category for {0} not found", nameParts[0])); } if (contactInfoType == ContactInfoType.Address) { var addressPart = (AddressPart)Enum.Parse(typeof(AddressPart), nameParts[2]); var findedAddress = contactInfos.Find( item => (category == item.Category) && (item.InfoType == ContactInfoType.Address)); if (findedAddress == null) { findedAddress = new ContactInfo { Category = category, InfoType = contactInfoType, Data = addressTemplateStr, ContactID = contact.ID }; contactInfos.Add(findedAddress); } var addressParts = JObject.Parse(findedAddress.Data); addressParts[addressPart.ToString().ToLower()] = GetValue(key); findedAddress.Data = addressParts.ToString(); continue; } var fieldValue = GetValue(key); if (String.IsNullOrEmpty(fieldValue)) { continue; } contactInfos.Add(new ContactInfo { Category = category, InfoType = contactInfoType, Data = fieldValue, ContactID = contact.ID, IsPrimary = true }); } else if (String.Compare(key, "tag", true) == 0) { var tags = _context.Request.Form.GetValues("tag"); daoFactory.TagDao.SetTagToEntity(EntityType.Contact, contact.ID, tags); } } contactInfos.ForEach( item => fieldCollector[item.InfoType.ToLocalizedString()] = PrepareteDataToView(item.InfoType, item.Data)); daoFactory.ContactInfoDao.SaveList(contactInfos, contact); var notifyList = GetValue("notify_list"); if (!String.IsNullOrEmpty(notifyList)) { NotifyClient.Instance.SendAboutCreateNewContact( notifyList .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(item => new Guid(item)).ToList(), contact.ID, contact.GetTitle(), fieldCollector); } var managersList = GetValue("managers_list"); SetPermission(contact, managersList); if (contact is Person && !String.IsNullOrEmpty(companyName)) { AssignPersonToCompany((Person)contact, companyName, managersList, daoFactory); } if (contact is Company && !String.IsNullOrEmpty(firstName) && !String.IsNullOrEmpty(lastName)) { AssignCompanyToPerson((Company)contact, firstName, lastName, managersList, daoFactory); } SecurityContext.Logout(); var newURL = new UriBuilder(GetValue("return_url")).Uri.AbsoluteUri; context.Response.Buffer = true; context.Response.Status = "302 Object moved"; context.Response.AddHeader("Location", newURL); context.Response.Write("<HTML><Head>"); context.Response.Write(String.Format("<META HTTP-EQUIV=Refresh CONTENT=\"0;URL={0}\">", newURL)); context.Response.Write(String.Format("<Script>window.location='{0}';</Script>", newURL)); context.Response.Write("</Head>"); context.Response.Write("</HTML>"); } } catch (Exception error) { LogManager.GetLogger("ASC.CRM").Error(error); context.Response.StatusCode = 400; context.Response.Write(HttpUtility.HtmlEncode(error.Message)); } }
public IEnumerable <TaskWrapper> CreateTaskGroup( string title, string description, ApiDateTime deadline, Guid responsibleId, int categoryId, int[] contactId, string entityType, int entityId, bool isNotify, int alertValue) { var tasks = new List <Task>(); if ( !string.IsNullOrEmpty(entityType) && !(string.Compare(entityType, "opportunity", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(entityType, "case", StringComparison.OrdinalIgnoreCase) == 0) ) { throw new ArgumentException(); } foreach (var cid in contactId) { tasks.Add(new Task { Title = title, Description = description, ResponsibleID = responsibleId, CategoryID = categoryId, DeadLine = deadline, ContactID = cid, EntityType = ToEntityType(entityType), EntityID = entityId, IsClosed = false, AlertValue = alertValue }); } tasks = DaoFactory.GetTaskDao().SaveOrUpdateTaskList(tasks).ToList(); string taskCategory = null; if (isNotify) { if (categoryId > 0) { var listItem = DaoFactory.GetListItemDao().GetByID(categoryId); if (listItem == null) { throw new ItemNotFoundException(); } taskCategory = listItem.Title; } } for (var i = 0; i < tasks.Count; i++) { if (!isNotify) { continue; } Contact taskContact = null; Cases taskCase = null; Deal taskDeal = null; if (tasks[i].ContactID > 0) { taskContact = DaoFactory.GetContactDao().GetByID(tasks[i].ContactID); } if (tasks[i].EntityID > 0) { switch (tasks[i].EntityType) { case EntityType.Case: taskCase = DaoFactory.GetCasesDao().GetByID(tasks[i].EntityID); break; case EntityType.Opportunity: taskDeal = DaoFactory.GetDealDao().GetByID(tasks[i].EntityID); break; } } NotifyClient.Instance.SendAboutResponsibleByTask(tasks[i], taskCategory, taskContact, taskCase, taskDeal, null); } if (tasks.Any()) { var contacts = DaoFactory.GetContactDao().GetContacts(contactId); var task = tasks.First(); MessageService.Send(Request, MessageAction.ContactsCreatedCrmTasks, MessageTarget.Create(tasks.Select(x => x.ID)), contacts.Select(x => x.GetTitle()), task.Title); } return(ToTaskListWrapper(tasks)); }
public object AddAdmin(Guid id) { var isRetina = TenantLogoManager.IsRetina(HttpContext.Current.Request); SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings); var user = CoreContext.UserManager.GetUsers(id); if (user.IsVisitor()) { throw new System.Security.SecurityException("Collaborator can not be an administrator"); } WebItemSecurity.SetProductAdministrator(Guid.Empty, id, true); MessageService.Send(HttpContext.Current.Request, MessageAction.AdministratorAdded, MessageTarget.Create(user.ID), user.DisplayUserName(false)); InitLdapRights(); return(new { id = user.ID, smallFotoUrl = user.GetSmallPhotoURL(), bigFotoUrl = isRetina ? user.GetBigPhotoURL() : "", displayName = user.DisplayUserName(), title = user.Title.HtmlEncode(), userUrl = CommonLinkUtility.GetUserProfile(user.ID), accessList = GetAccessList(user.ID, true) }); }
public TaskWrapper UpdateTask( int taskid, string title, string description, ApiDateTime deadline, Guid responsibleid, int categoryid, int contactid, string entityType, int entityid, bool isNotify, int alertValue) { if (!string.IsNullOrEmpty(entityType) && !(string.Compare(entityType, "opportunity", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(entityType, "case", StringComparison.OrdinalIgnoreCase) == 0 ) || categoryid <= 0) { throw new ArgumentException(); } var listItem = DaoFactory.GetListItemDao().GetByID(categoryid); if (listItem == null) { throw new ItemNotFoundException(CRMErrorsResource.TaskCategoryNotFound); } var task = new Task { ID = taskid, Title = title, Description = description, DeadLine = deadline, AlertValue = alertValue, ResponsibleID = responsibleid, CategoryID = categoryid, ContactID = contactid, EntityID = entityid, EntityType = ToEntityType(entityType) }; task = DaoFactory.GetTaskDao().SaveOrUpdateTask(task); if (isNotify) { Contact taskContact = null; Cases taskCase = null; Deal taskDeal = null; if (task.ContactID > 0) { taskContact = DaoFactory.GetContactDao().GetByID(task.ContactID); } if (task.EntityID > 0) { switch (task.EntityType) { case EntityType.Case: taskCase = DaoFactory.GetCasesDao().GetByID(task.EntityID); break; case EntityType.Opportunity: taskDeal = DaoFactory.GetDealDao().GetByID(task.EntityID); break; } } NotifyClient.Instance.SendAboutResponsibleByTask(task, listItem.Title, taskContact, taskCase, taskDeal, null); } MessageService.Send(Request, MessageAction.CrmTaskUpdated, MessageTarget.Create(task.ID), task.Title); return(ToTaskWrapper(task)); }
public object ValidateTfaCode(string query, string code) { var user = GetUser(query); bool newBackupCodes; try { newBackupCodes = user.ValidateAuthCode(code, !Activation); MessageService.Send(HttpContext.Current.Request, MessageAction.LoginSuccesViaTfaApp); } catch (Authorize.BruteForceCredentialException) { MessageService.Send(HttpContext.Current.Request, user.DisplayUserName(false), MessageAction.LoginFailBruteForce); throw; } catch { MessageService.Send(HttpContext.Current.Request, user.DisplayUserName(false), MessageAction.LoginFailViaTfaApp, MessageTarget.Create(user.ID)); throw; } var refererUrl = GetRefererURL(); if (newBackupCodes) { MessageService.Send(HttpContext.Current.Request, MessageAction.UserConnectedTfaApp, MessageTarget.Create(user.ID)); refererUrl = CommonLinkUtility.GetUserProfile(user.ID) + "#codes"; } if (query.Contains("desktop=true")) { refererUrl = CommonLinkUtility.GetFullAbsolutePath(WebItemManager.Instance[WebItemManager.DocumentsProductID].StartURL + "?desktop=true"); } return(new { RefererURL = refererUrl }); }
public RelationshipEventWrapper AddHistoryTo( string entityType, int entityId, int contactId, string content, int categoryId, ApiDateTime created, IEnumerable <int> fileId, IEnumerable <Guid> notifyUserList) { if (!string.IsNullOrEmpty(entityType) && !( string.Compare(entityType, "opportunity", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(entityType, "case", StringComparison.OrdinalIgnoreCase) == 0) ) { throw new ArgumentException(); } var entityTypeObj = ToEntityType(entityType); var entityTitle = ""; if (contactId > 0) { var contact = DaoFactory.ContactDao.GetByID(contactId); if (contact == null || !CRMSecurity.CanAccessTo(contact)) { throw new ArgumentException(); } entityTitle = contact.GetTitle(); } if (entityTypeObj == EntityType.Case) { var cases = DaoFactory.CasesDao.GetByID(entityId); if (cases == null || !CRMSecurity.CanAccessTo(cases)) { throw new ArgumentException(); } if (contactId <= 0) { entityTitle = cases.Title; } } if (entityTypeObj == EntityType.Opportunity) { var deal = DaoFactory.DealDao.GetByID(entityId); if (deal == null || !CRMSecurity.CanAccessTo(deal)) { throw new ArgumentException(); } if (contactId <= 0) { entityTitle = deal.Title; } } var relationshipEvent = new RelationshipEvent { CategoryID = categoryId, EntityType = entityTypeObj, EntityID = entityId, Content = content, ContactID = contactId, CreateOn = created, CreateBy = Core.SecurityContext.CurrentAccount.ID }; var category = DaoFactory.ListItemDao.GetByID(categoryId); if (category == null) { throw new ArgumentException(); } var item = DaoFactory.RelationshipEventDao.CreateItem(relationshipEvent); notifyUserList = notifyUserList != null?notifyUserList.ToList() : new List <Guid>(); var needNotify = notifyUserList.Any(); var fileListInfoHashtable = new Hashtable(); if (fileId != null) { var fileIds = fileId.ToList(); var files = FilesDaoFactory.GetFileDao().GetFiles(fileIds.Cast <object>().ToArray()); if (needNotify) { foreach (var file in files) { var extension = Path.GetExtension(file.Title); if (extension == null) { continue; } var fileInfo = string.Format("{0} ({1})", file.Title, extension.ToUpper()); if (!fileListInfoHashtable.ContainsKey(fileInfo)) { fileListInfoHashtable.Add(fileInfo, file.DownloadUrl); } else { fileInfo = string.Format("{0} ({1}, {2})", file.Title, extension.ToUpper(), file.UniqID); fileListInfoHashtable.Add(fileInfo, file.DownloadUrl); } } } DaoFactory.RelationshipEventDao.AttachFiles(item.ID, fileIds.ToArray()); if (files.Any()) { var fileAttachAction = GetFilesAttachAction(entityTypeObj, contactId); MessageService.Send(Request, fileAttachAction, MessageTarget.Create(item.ID), entityTitle, files.Select(x => x.Title)); } } if (needNotify) { NotifyClient.Instance.SendAboutAddRelationshipEventAdd(item, fileListInfoHashtable, DaoFactory, notifyUserList.ToArray()); } var wrapper = ToRelationshipEventWrapper(item); var historyCreatedAction = GetHistoryCreatedAction(entityTypeObj, contactId); MessageService.Send(Request, historyCreatedAction, MessageTarget.Create(item.ID), entityTitle, category.Title); return(wrapper); }
public AjaxResponse SendEmailActivationInstructionsOnChange(string newEmail, string queryString) { const string StatusSuccess = "success"; const string StatusError = "error"; const string StatusFatalError = "fatalerror"; var response = new AjaxResponse { status = StatusSuccess }; if (String.IsNullOrEmpty(queryString)) { response.status = StatusFatalError; response.message = Resource.ErrorConfirmURLError; return(response); } if (String.IsNullOrEmpty(newEmail)) { response.status = StatusError; response.message = Resource.ErrorEmailEmpty; return(response); } try { var result = CheckValidationKey(queryString.Substring(1)); if (result != EmailValidationKeyProvider.ValidationResult.Ok) { response.status = StatusFatalError; switch (result) { case EmailValidationKeyProvider.ValidationResult.Invalid: response.message = Resource.ErrorInvalidActivationLink; break; case EmailValidationKeyProvider.ValidationResult.Expired: response.message = Resource.ErrorExpiredActivationLink; break; default: response.message = Resource.ErrorConfirmURLError; break; } return(response); } var user = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID); if (user == null) { response.status = StatusFatalError; response.message = Resource.ErrorUserNotFound; return(response); } var existentUser = CoreContext.UserManager.GetUserByEmail(newEmail); if (existentUser != null && existentUser.ID == user.ID) { response.status = StatusError; response.message = Resource.ErrorEmailsAreTheSame; return(response); } if (existentUser != null && existentUser.ID != Constants.LostUser.ID) { response.status = StatusError; response.message = CustomNamingPeople.Substitute <Resource>("ErrorEmailAlreadyExists"); return(response); } user.Email = newEmail; user.ActivationStatus = EmployeeActivationStatus.NotActivated; CoreContext.UserManager.SaveUserInfo(user); StudioNotifyService.Instance.SendEmailActivationInstructions(user, newEmail); MessageService.Send(Request, MessageAction.UserSentActivationInstructions, MessageTarget.Create(user.ID), user.DisplayUserName(false)); response.message = String.Format(Resource.MessageEmailActivationInstuctionsSentOnEmail, "<b>" + newEmail + "</b>"); return(response); } catch (Exception) { response.status = StatusFatalError; response.message = Resource.UnknownError; return(response); } }
public FileUploadResult ProcessUpload(HttpContext context) { if (!WebItemSecurity.IsAvailableForMe(ProductEntryPoint.ID)) { throw CRMSecurity.CreateSecurityException(); } var contactId = Convert.ToInt32(context.Request["contactID"]); Contact contact = null; if (contactId != 0) { using (var scope = DIHelper.Resolve()) { contact = scope.Resolve <DaoFactory>().ContactDao.GetByID(contactId); if (!CRMSecurity.CanEdit(contact)) { throw CRMSecurity.CreateSecurityException(); } } } var fileUploadResult = new FileUploadResult(); if (!FileToUpload.HasFilesToUpload(context)) { return(fileUploadResult); } var file = new FileToUpload(context); if (String.IsNullOrEmpty(file.FileName) || file.ContentLength == 0) { throw new InvalidOperationException(CRMErrorsResource.InvalidFile); } if (0 < SetupInfo.MaxImageUploadSize && SetupInfo.MaxImageUploadSize < file.ContentLength) { fileUploadResult.Success = false; fileUploadResult.Message = FileSizeComment.GetFileImageSizeNote(CRMCommonResource.ErrorMessage_UploadFileSize, false).HtmlEncode(); return(fileUploadResult); } if (FileUtility.GetFileTypeByFileName(file.FileName) != FileType.Image) { fileUploadResult.Success = false; fileUploadResult.Message = CRMJSResource.ErrorMessage_NotImageSupportFormat.HtmlEncode(); return(fileUploadResult); } var uploadOnly = Convert.ToBoolean(context.Request["uploadOnly"]); var tmpDirName = Convert.ToString(context.Request["tmpDirName"]); try { ContactPhotoManager.PhotoData photoData; if (contactId != 0) { photoData = ContactPhotoManager.UploadPhoto(file.InputStream, contactId, uploadOnly); } else { if (String.IsNullOrEmpty(tmpDirName) || tmpDirName == "null") { tmpDirName = Guid.NewGuid().ToString(); } photoData = ContactPhotoManager.UploadPhotoToTemp(file.InputStream, tmpDirName); } fileUploadResult.Success = true; fileUploadResult.Data = photoData; } catch (Exception e) { fileUploadResult.Success = false; fileUploadResult.Message = e.Message.HtmlEncode(); return(fileUploadResult); } if (contact != null) { var messageAction = contact is Company ? MessageAction.CompanyUpdatedPhoto : MessageAction.PersonUpdatedPhoto; MessageService.Send(context.Request, messageAction, MessageTarget.Create(contact.ID), contact.GetTitle()); } return(fileUploadResult); }
protected void DeleteProfile(object sender, EventArgs e) { try { SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem); var user = CoreContext.UserManager.GetUsers(UserId); user.Status = EmployeeStatus.Terminated; CoreContext.UserManager.SaveUserInfo(user); MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, MessageAction.UsersUpdatedStatus, MessageTarget.Create(user.ID), user.DisplayUserName(false)); if (CoreContext.Configuration.Personal) { UserPhotoManager.RemovePhoto(user.ID); CoreContext.UserManager.DeleteUser(user.ID); MessageService.Send(Request, MessageAction.UserDeleted, MessageTarget.Create(user.ID), user.DisplayUserName(false)); } operationBlock.Visible = false; result.Visible = true; errorBlock.Visible = false; } catch (Exception ex) { operationBlock.Visible = false; result.Visible = false; errorBlock.InnerHtml = ex.Message; errorBlock.Visible = true; } finally { Auth.ProcessLogout(); } }
public object ValidateSmsCode(string query, string code) { var user = GetUser(query); try { SmsManager.ValidateSmsCode(user, code); MessageService.Send(HttpContext.Current.Request, MessageAction.LoginSuccessViaSms); } catch (Authorize.BruteForceCredentialException) { MessageService.Send(Request, user.DisplayUserName(false), MessageAction.LoginFailBruteForce); throw; } catch { MessageService.Send(HttpContext.Current.Request, user.DisplayUserName(false), MessageAction.LoginFailViaSms, MessageTarget.Create(user.ID)); throw; } return(new { RefererURL = GetRefererURL() }); }
protected void SaveOrUpdateInvoice(Object sender, CommandEventArgs e) { try { using (var scope = DIHelper.Resolve()) { var dao = scope.Resolve <DaoFactory>(); var invoice = GetInvoice(dao); var billingAddressID = Convert.ToInt32(Request["billingAddressID"]); var deliveryAddressID = Convert.ToInt32(Request["deliveryAddressID"]); var messageAction = MessageAction.InvoiceCreated; if (invoice.ID > 0) { messageAction = MessageAction.InvoiceUpdated; RemoveInvoiceFile(invoice.FileID, dao); } invoice.ID = dao.InvoiceDao.SaveOrUpdateInvoice(invoice); MessageService.Send(HttpContext.Current.Request, messageAction, MessageTarget.Create(invoice.ID), invoice.Number); var invoiceLines = GetInvoiceLines(dao); foreach (var line in invoiceLines) { line.InvoiceID = invoice.ID; line.ID = dao.InvoiceLineDao.SaveOrUpdateInvoiceLine(line); } RemoveUnusedLines(invoice.ID, invoiceLines, dao); dao.InvoiceDao.UpdateInvoiceJsonData(invoice, billingAddressID, deliveryAddressID); if (Global.CanDownloadInvoices) { PdfQueueWorker.StartTask(HttpContext.Current, TenantProvider.CurrentTenantID, SecurityContext.CurrentAccount.ID, invoice.ID); } string redirectUrl; if (ActionType == InvoiceActionType.Create && UrlParameters.ContactID != 0) { redirectUrl = string.Format( e.CommandArgument.ToString() == "1" ? "Invoices.aspx?action=create&contactID={0}" : "Default.aspx?id={0}#invoices", UrlParameters.ContactID); } else { redirectUrl = e.CommandArgument.ToString() == "1" ? "Invoices.aspx?action=create" : string.Format("Invoices.aspx?id={0}", invoice.ID); } Response.Redirect(redirectUrl, false); Context.ApplicationInstance.CompleteRequest(); } } catch (Exception ex) { if (!(ex is InvoiceValidationException)) { LogManager.GetLogger("ASC.CRM").Error(ex); } var cookie = HttpContext.Current.Request.Cookies.Get(ErrorCookieKey); if (cookie == null) { cookie = new HttpCookie(ErrorCookieKey) { Value = ex.Message }; HttpContext.Current.Response.Cookies.Add(cookie); } } }
public string AddContactTagToGroup(string entityType, int entityid, string tagName) { if (entityid <= 0 || string.IsNullOrEmpty(tagName)) { throw new ArgumentException(); } var entityTypeObj = ToEntityType(entityType); if (entityTypeObj != EntityType.Company && entityTypeObj != EntityType.Person) { throw new ArgumentException(); } var contactInst = DaoFactory.ContactDao.GetByID(entityid); if (contactInst == null || !CRMSecurity.CanAccessTo(contactInst)) { throw new ItemNotFoundException(); } if (contactInst is Person && entityTypeObj == EntityType.Company) { throw new Exception(CRMErrorsResource.ContactIsNotCompany); } if (contactInst is Company && entityTypeObj == EntityType.Person) { throw new Exception(CRMErrorsResource.ContactIsNotPerson); } var contactIDsToAddTag = new List <int>(); if (contactInst is Company) { contactIDsToAddTag.Add(contactInst.ID); var members = DaoFactory.ContactDao.GetMembersIDsAndShareType(contactInst.ID); foreach (var m in members) { if (CRMSecurity.CanAccessTo(m.Key, EntityType.Person, m.Value, 0)) { contactIDsToAddTag.Add(m.Key); } } } else { var CompanyID = ((Person)contactInst).CompanyID; if (CompanyID != 0) { var cnt = DaoFactory.ContactDao.GetByID(CompanyID); if (cnt != null && cnt is Company && CRMSecurity.CanAccessTo(cnt)) { contactIDsToAddTag.Add(CompanyID); var members = DaoFactory.ContactDao.GetMembersIDsAndShareType(CompanyID); foreach (var m in members) { if (CRMSecurity.CanAccessTo(m.Key, EntityType.Person, m.Value, 0)) { contactIDsToAddTag.Add(m.Key); } } } else { contactIDsToAddTag.Add(contactInst.ID); } } else { contactIDsToAddTag.Add(contactInst.ID); } } DaoFactory.TagDao.AddTagToContacts(contactIDsToAddTag.ToArray(), tagName); var entityTitle = contactInst.GetTitle(); var messageActions = GetTagCreatedGroupAction(entityTypeObj); foreach (var messageAction in messageActions) { MessageService.Send(Request, messageAction, MessageTarget.Create(contactInst.ID), entityTitle, tagName); } return(tagName); }
protected void Page_Load(object sender, EventArgs e) { if (UrlParameters.Action != "export") { _phListBase.Controls.Add(LoadControl(ListBaseView.Location)); } else // export to csv { var tasks = GetTasksByFilter(); if (tasks.Count != 0) { if (UrlParameters.View != "editor") { Response.Clear(); Response.ContentType = "text/csv; charset=utf-8"; Response.ContentEncoding = Encoding.UTF8; Response.Charset = Encoding.UTF8.WebName; const string fileName = "tasks.csv"; Response.AppendHeader("Content-Disposition", String.Format("attachment; filename={0}", fileName)); Response.Write(ExportToCSV.ExportTasksToCSV(tasks, false)); MessageService.Send(HttpContext.Current.Request, MessageAction.CrmTasksExportedToCsv, MessageTarget.Create(tasks.Select(x => x.ID)), tasks.Select(x => x.Title)); Response.End(); } else { var fileUrl = ExportToCSV.ExportTasksToCSV(tasks, true); Response.Redirect(fileUrl); } } else { var cookie = HttpContext.Current.Request.Cookies.Get(ExportErrorCookieKey); if (cookie == null) { cookie = new HttpCookie(ExportErrorCookieKey) { Value = CRMTaskResource.ExportTaskListEmptyError }; HttpContext.Current.Response.Cookies.Add(cookie); } Response.Redirect(PathProvider.StartURL() + "tasks.aspx"); } } }
public List <string> SaveThumbnails(int x, int y, int width, int height, string saveFunctionType, Guid userID) { if (x < 0 || y < 0 || width <= 0 || height <= 0) { return(null); } var pointSelect = new Point(x, y); var sizeSelect = new Size(width, height); var saveClass = GetThumbnailsData(saveFunctionType, userID); var resaltBitmaps = new List <ThumbnailItem>(); System.Drawing.Image img = saveClass.MainImgBitmap; if (img == null) { return(null); } foreach (var thumbnail in saveClass.ThumbnailList) { var thumbnailBitmap = new Bitmap(thumbnail.size.Width, thumbnail.size.Height); var scaleX = thumbnail.size.Width / (1.0 * sizeSelect.Width); var scaleY = thumbnail.size.Height / (1.0 * sizeSelect.Height); var rect = new Rectangle(-(int)(scaleX * pointSelect.X), -(int)(scaleY * pointSelect.Y), (int)(scaleX * img.Width), (int)(scaleY * img.Height)); using (var graphic = Graphics.FromImage(thumbnailBitmap)) { graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; graphic.FillRectangle(new SolidBrush(Color.Black), 0, 0, thumbnail.size.Width, thumbnail.size.Height); graphic.DrawImage(img, rect); } thumbnail.bitmap = thumbnailBitmap; resaltBitmaps.Add(thumbnail); } saveClass.Save(resaltBitmaps); var user = CoreContext.UserManager.GetUsers(userID); MessageService.Send(HttpContext.Current.Request, MessageAction.UserUpdatedAvatarThumbnails, MessageTarget.Create(user.ID), user.DisplayUserName(false)); return(saveClass.ThumbnailList.Select(t => t.imgUrl).ToList()); }
protected void Page_Load(object sender, EventArgs e) { Page.RegisterBodyScripts("~/js/third-party/xregexp.js", "~/UserControls/Management/ConfirmInviteActivation/js/confirm_invite_activation.js") .RegisterStyle("~/UserControls/Management/ConfirmInviteActivation/css/confirm_invite_activation.less"); var uid = Guid.Empty; try { uid = new Guid(Request["uid"]); } catch { } var email = GetEmailAddress(); if (_type != ConfirmType.Activation && AccountLinkControl.IsNotEmpty && !CoreContext.Configuration.Personal) { var thrd = (AccountLinkControl)LoadControl(AccountLinkControl.Location); thrd.InviteView = true; thrd.ClientCallback = "loginJoinCallback"; thrdParty.Visible = true; thrdParty.Controls.Add(thrd); } Page.Title = HeaderStringHelper.GetPageTitle(Resource.Authorization); UserInfo user; try { SecurityContext.CurrentAccount = ASC.Core.Configuration.Constants.CoreSystem; user = CoreContext.UserManager.GetUserByEmail(email); var usr = CoreContext.UserManager.GetUsers(uid); if (usr.ID.Equals(Constants.LostUser.ID) || usr.ID.Equals(ASC.Core.Configuration.Constants.Guest.ID)) { usr = CoreContext.UserManager.GetUsers(CoreContext.TenantManager.GetCurrentTenant().OwnerId); } var photoData = UserPhotoManager.GetUserPhotoData(usr.ID, UserPhotoManager.MediumFotoSize); _userAvatar = photoData == null?usr.GetMediumPhotoURL() : "data:image/png;base64," + Convert.ToBase64String(photoData); _userName = usr.DisplayUserName(true); _userPost = (usr.Title ?? "").HtmlEncode(); } finally { SecurityContext.Logout(); } if (_type == ConfirmType.LinkInvite || _type == ConfirmType.EmpInvite) { if (!CoreContext.Configuration.Personal) { if (_employeeType == EmployeeType.User && TenantStatisticsProvider.GetUsersCount() >= TenantExtra.GetTenantQuota().ActiveUsers) { ShowError(UserControlsCommonResource.TariffUserLimitReason); return; } if (_employeeType == EmployeeType.Visitor && !(CoreContext.Configuration.Standalone || TenantStatisticsProvider.GetVisitorsCount() < TenantExtra.GetTenantQuota().ActiveUsers *Constants.CoefficientOfVisitors)) { ShowError(UserControlsCommonResource.TariffVisitorLimitReason); return; } } if (!user.ID.Equals(Constants.LostUser.ID)) { ShowError(CustomNamingPeople.Substitute <Resource>("ErrorEmailAlreadyExists")); return; } } else if (_type == ConfirmType.Activation) { if (user.IsActive) { Response.Redirect(CommonLinkUtility.GetDefault()); return; } if (user.ID.Equals(Constants.LostUser.ID) || user.Status == EmployeeStatus.Terminated) { ShowError(string.Format(Resource.ErrorUserNotFoundByEmail, email)); return; } } var tenant = CoreContext.TenantManager.GetCurrentTenant(); if (tenant != null) { var settings = IPRestrictionsSettings.Load(); if (settings.Enable && !IPSecurity.IPSecurity.Verify(tenant)) { ShowError(Resource.ErrorAccessRestricted); return; } } if (!IsPostBack) { return; } var firstName = GetFirstName(); var lastName = GetLastName(); var passwordHash = (Request["passwordHash"] ?? "").Trim(); var mustChangePassword = false; LoginProfile thirdPartyProfile; //thirdPartyLogin confirmInvite if (Request["__EVENTTARGET"] == "thirdPartyLogin") { var valueRequest = Request["__EVENTARGUMENT"]; thirdPartyProfile = new LoginProfile(valueRequest); if (!string.IsNullOrEmpty(thirdPartyProfile.AuthorizationError)) { // ignore cancellation if (thirdPartyProfile.AuthorizationError != "Canceled at provider") { ShowError(HttpUtility.HtmlEncode(thirdPartyProfile.AuthorizationError)); } return; } if (string.IsNullOrEmpty(thirdPartyProfile.EMail)) { ShowError(HttpUtility.HtmlEncode(Resource.ErrorNotCorrectEmail)); return; } } if (Request["__EVENTTARGET"] == "confirmInvite") { if (String.IsNullOrEmpty(email)) { _errorMessage = Resource.ErrorEmptyUserEmail; return; } if (!email.TestEmailRegex()) { _errorMessage = Resource.ErrorNotCorrectEmail; return; } if (String.IsNullOrEmpty(firstName)) { _errorMessage = Resource.ErrorEmptyUserFirstName; return; } if (String.IsNullOrEmpty(lastName)) { _errorMessage = Resource.ErrorEmptyUserLastName; return; } if (String.IsNullOrEmpty(passwordHash)) { _errorMessage = Resource.ErrorPasswordEmpty; return; } } var userID = Guid.Empty; try { SecurityContext.CurrentAccount = ASC.Core.Configuration.Constants.CoreSystem; if (_type == ConfirmType.EmpInvite || _type == ConfirmType.LinkInvite) { if (!CoreContext.Configuration.Personal && TenantStatisticsProvider.GetUsersCount() >= TenantExtra.GetTenantQuota().ActiveUsers&& _employeeType == EmployeeType.User) { ShowError(UserControlsCommonResource.TariffUserLimitReason); return; } UserInfo newUser; if (Request["__EVENTTARGET"] == "confirmInvite") { var fromInviteLink = _type == ConfirmType.LinkInvite; newUser = CreateNewUser(firstName, lastName, email, passwordHash, _employeeType, fromInviteLink); var messageAction = _employeeType == EmployeeType.User ? MessageAction.UserCreatedViaInvite : MessageAction.GuestCreatedViaInvite; MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, messageAction, MessageTarget.Create(newUser.ID), newUser.DisplayUserName(false)); userID = newUser.ID; } if (Request["__EVENTTARGET"] == "thirdPartyLogin") { if (String.IsNullOrEmpty(passwordHash)) { passwordHash = UserManagerWrapper.GeneratePassword(); mustChangePassword = true; } var valueRequest = Request["__EVENTARGUMENT"]; thirdPartyProfile = new LoginProfile(valueRequest); newUser = CreateNewUser(GetFirstName(thirdPartyProfile), GetLastName(thirdPartyProfile), GetEmailAddress(thirdPartyProfile), passwordHash, _employeeType, false); var messageAction = _employeeType == EmployeeType.User ? MessageAction.UserCreatedViaInvite : MessageAction.GuestCreatedViaInvite; MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, messageAction, MessageTarget.Create(newUser.ID), newUser.DisplayUserName(false)); userID = newUser.ID; if (!String.IsNullOrEmpty(thirdPartyProfile.Avatar)) { SaveContactImage(userID, thirdPartyProfile.Avatar); } var linker = new AccountLinker("webstudio"); linker.AddLink(userID.ToString(), thirdPartyProfile); } } else if (_type == ConfirmType.Activation) { if (!UserFormatter.IsValidUserName(firstName, lastName)) { throw new Exception(Resource.ErrorIncorrectUserName); } SecurityContext.SetUserPasswordHash(user.ID, passwordHash); user.ActivationStatus = EmployeeActivationStatus.Activated; user.FirstName = firstName; user.LastName = lastName; CoreContext.UserManager.SaveUserInfo(user); userID = user.ID; //notify if (user.IsVisitor()) { StudioNotifyService.Instance.GuestInfoAddedAfterInvite(user); MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, MessageAction.GuestActivated, MessageTarget.Create(user.ID), user.DisplayUserName(false)); } else { StudioNotifyService.Instance.UserInfoAddedAfterInvite(user); MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, MessageAction.UserActivated, MessageTarget.Create(user.ID), user.DisplayUserName(false)); } } } catch (SecurityContext.PasswordException) { _errorMessage = HttpUtility.HtmlEncode(Resource.ErrorPasswordRechange); return; } catch (Exception exception) { _errorMessage = HttpUtility.HtmlEncode(exception.Message); return; } finally { SecurityContext.Logout(); } user = CoreContext.UserManager.GetUsers(userID); try { CookiesManager.AuthenticateMeAndSetCookies(user.Email, passwordHash, MessageAction.LoginSuccess); StudioNotifyService.Instance.UserHasJoin(); if (mustChangePassword) { StudioNotifyService.Instance.UserPasswordChange(user); } } catch (Exception exception) { (Page as Confirm).ErrorMessage = HttpUtility.HtmlEncode(exception.Message); return; } UserHelpTourHelper.IsNewUser = true; if (CoreContext.Configuration.Personal) { PersonalSettings.IsNewUser = true; } Response.Redirect(CommonLinkUtility.GetDefault()); }
public void RunJob() { Status = (int)Operation.Success; CoreContext.TenantManager.SetCurrentTenant((int)Id); SecurityContext.AuthenticateMe(UserId); if (!SecurityContext.CheckPermissions(Constants.Action_AddRemoveUser)) { Error = Resource.ErrorAccessDenied; IsCompleted = true; return; } try { var jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); var ruleObj = jsSerializer.Deserialize <List <UserData> >(userList); var error = 0; var percentStep = 100.0 / ruleObj.Count; foreach (var userData in ruleObj) { var validateEmail = UserManagerWrapper.ValidateEmail(userData.Email); if (!validateEmail || String.IsNullOrEmpty(userData.FirstName) || String.IsNullOrEmpty(userData.LastName)) { Data.Add(new UserResults { Email = userData.Email, Result = Resource.ImportContactsIncorrectFields, Class = !validateEmail ? "error3" : "error1" }); error++; Percentage += percentStep; continue; } var us = CoreContext.UserManager.GetUserByEmail(userData.Email); if (us.ID != Constants.LostUser.ID) { Data.Add(new UserResults { Email = userData.Email, Result = CustomNamingPeople.Substitute <Resource>("ImportContactsAlreadyExists"), Class = "error2" }); error++; Percentage += percentStep; continue; } if (!importUsersAsCollaborators && TenantStatisticsProvider.GetUsersCount() >= TenantExtra.GetTenantQuota().ActiveUsers) { importUsersAsCollaborators = true; } var userInfo = new UserInfo { Email = userData.Email, FirstName = userData.FirstName, LastName = userData.LastName }; UserManagerWrapper.AddUser(userInfo, UserManagerWrapper.GeneratePassword(), false, true, importUsersAsCollaborators); var messageAction = importUsersAsCollaborators ? MessageAction.GuestImported : MessageAction.UserImported; MessageService.Send(httpHeaders, messageAction, MessageTarget.Create(userInfo.ID), userInfo.DisplayUserName(false)); Data.Add(new UserResults { Email = userData.Email, Result = String.Empty }); Percentage += percentStep; } } catch (Exception ex) { Status = (int)Operation.Error; Error = ex.Message; } IsCompleted = true; }
protected void SaveOrUpdateCase(object sender, CommandEventArgs e) { try { using (var scope = DIHelper.Resolve()) { var daoFactory = scope.Resolve <DaoFactory>(); int caseID; if (TargetCase != null) { caseID = TargetCase.ID; TargetCase.Title = Request["caseTitle"]; daoFactory.CasesDao.UpdateCases(TargetCase); FactoryIndexer <CasesWrapper> .UpdateAsync(TargetCase); MessageService.Send(HttpContext.Current.Request, MessageAction.CaseUpdated, MessageTarget.Create(TargetCase.ID), TargetCase.Title); SetPermission(TargetCase); } else { caseID = daoFactory.CasesDao.CreateCases(Request["caseTitle"]); var newCase = daoFactory.CasesDao.GetByID(caseID); FactoryIndexer <CasesWrapper> .IndexAsync(newCase); MessageService.Send(HttpContext.Current.Request, MessageAction.CaseCreated, MessageTarget.Create(newCase.ID), newCase.Title); SetPermission(newCase); } daoFactory.CasesDao.SetMembers(caseID, !String.IsNullOrEmpty(Request["memberID"]) ? Request["memberID"].Split(',').Select( id => Convert.ToInt32(id)).ToArray() : new List <int>().ToArray()); var assignedTags = Request["baseInfo_assignedTags"]; if (assignedTags != null) { var oldTagList = daoFactory.TagDao.GetEntityTags(EntityType.Case, caseID); foreach (var tag in oldTagList) { daoFactory.TagDao.DeleteTagFromEntity(EntityType.Case, caseID, tag); } if (assignedTags != string.Empty) { var tagListInfo = JObject.Parse(assignedTags)["tagListInfo"].ToArray(); var newTagList = tagListInfo.Select(t => t.ToString()).ToArray(); daoFactory.TagDao.SetTagToEntity(EntityType.Case, caseID, newTagList); } } foreach (var customField in Request.Form.AllKeys) { if (!customField.StartsWith("customField_")) { continue; } int fieldID = Convert.ToInt32(customField.Split('_')[1]); string fieldValue = Request.Form[customField]; if (String.IsNullOrEmpty(fieldValue) && TargetCase == null) { continue; } daoFactory.CustomFieldDao.SetFieldValue(EntityType.Case, caseID, fieldID, fieldValue); } Response.Redirect( string.Compare(e.CommandArgument.ToString(), "0", StringComparison.OrdinalIgnoreCase) == 0 ? string.Format("Cases.aspx?id={0}", caseID) : "Cases.aspx?action=manage", false); Context.ApplicationInstance.CompleteRequest(); } } catch (Exception ex) { LogManager.GetLogger("ASC.CRM").Error(ex); var cookie = HttpContext.Current.Request.Cookies.Get(ErrorCookieKey); if (cookie == null) { cookie = new HttpCookie(ErrorCookieKey) { Value = ex.Message }; HttpContext.Current.Response.Cookies.Add(cookie); } } }