예제 #1
0
        public Address(ContactInfo contactInfo)
        {
            if (contactInfo.InfoType != ContactInfoType.Address)
                throw new ArgumentException();

            City = JObject.Parse(contactInfo.Data)["city"].Value<String>();
            Country = JObject.Parse(contactInfo.Data)["country"].Value<String>();
            State = JObject.Parse(contactInfo.Data)["state"].Value<String>();
            Street = JObject.Parse(contactInfo.Data)["street"].Value<String>();
            Zip = JObject.Parse(contactInfo.Data)["zip"].Value<String>();

        }
예제 #2
0
        public static bool TryParse(ContactInfo contactInfo, out Address res)
        {
            if (contactInfo.InfoType != ContactInfoType.Address)
            {
                res = null;
                return false;
            }

            try
            {
                res = Newtonsoft.Json.JsonConvert.DeserializeObject<Address>(contactInfo.Data);
                res.Category = contactInfo.Category;
                res.CategoryName = contactInfo.CategoryToString();
                res.IsPrimary = contactInfo.IsPrimary;
                return true;
            }
            catch (Exception)
            {
                res = null;
                return false;
            }
        }
        protected void SaveOrUpdateContact(object sender, CommandEventArgs e)
        {
            try
            {
                var dao = Global.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.GetContactDao().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.GetListItemDao().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.GetContactDao().UpdateContact(contact);

                    var messageAction = contact is Company ? MessageAction.CompanyUpdated : MessageAction.PersonUpdated;
                    MessageService.Send(HttpContext.Current.Request, messageAction, contact.GetTitle());

                    contact = dao.GetContactDao().GetByID(contact.ID);
                }
                else
                {
                    contact.ID = dao.GetContactDao().SaveContact(contact);

                    var messageAction = contact is Company ? MessageAction.CompanyCreated : MessageAction.PersonCreated;
                    MessageService.Send(HttpContext.Current.Request, messageAction, contact.GetTitle());

                    contact = dao.GetContactDao().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.GetContactDao().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.GetContactDao().GetRestrictedMembers(contact.ID);
                        assignedContactsIDs.AddRange(restrictedMembers.Select(m => m.ID).ToList());
                    }

                    dao.GetContactDao().SetMembers(contact.ID, assignedContactsIDs.ToArray());
                }

                #endregion

                #region tags

                var assignedTags = Request["baseInfo_assignedTags"];
                if (assignedTags != null)
                {
                    var oldTagList = dao.GetTagDao().GetEntityTags(EntityType.Contact, contact.ID);
                    foreach (var tag in oldTagList)
                    {
                        dao.GetTagDao().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.GetTagDao().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.GetCustomFieldDao().SetFieldValue(EntityType.Person, contact.ID, fieldID, "");
                            }
                            dao.GetCustomFieldDao().SetFieldValue(EntityType.Person, contact.ID, fieldID, fieldValue);
                        }
                        else
                        {
                            if (!String.IsNullOrEmpty(fieldValue))
                            {
                                dao.GetCustomFieldDao().SetFieldValue(EntityType.Company, contact.ID, fieldID, "");
                            }
                            dao.GetCustomFieldDao().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.GetContactInfoDao().DeleteByContact(contact.ID);
                dao.GetContactInfoDao().SaveList(contactInfos);

                #endregion

                #region Photo

                var photoPath = Request["uploadPhotoPath"];

                if (!String.IsNullOrEmpty(photoPath))
                {
                    if (photoPath != "null")
                    {
                        if (photoPath.StartsWith(PathProvider.BaseAbsolutePath))
                        {
                            var tmpDirName = photoPath.Substring(0, photoPath.LastIndexOf('/'));
                            ContactPhotoManager.TryUploadPhotoFromTmp(contact.ID, TargetContact == null, tmpDirName);
                        }
                        else
                        {
                            ContactPhotoManager.UploadPhoto(photoPath, contact.ID);
                        }
                    }
                }
                else if (TargetContact != null)
                {
                    ContactPhotoManager.DeletePhoto(TargetContact.ID);
                }
                #endregion


                #region Rights part #2

                SetContactManager(contactsForSetManager);

                #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);
                }
            }
        }
 private ContactInfoWrapper ToContactInfoWrapper(ContactInfo contactInfo)
 {
     return new ContactInfoWrapper(contactInfo);
 }
        public ContactInfoWrapper CreateContactInfo(int contactid,
                                                 ContactInfoType infoType,
                                                 String data,
                                                 bool isPrimary,
                                                 String category
                                             )
        {
            if (String.IsNullOrEmpty(data) || contactid == 0)
                throw new ArgumentException();

            var categoryType = ContactInfo.GetCategory(infoType);

            if (!Enum.IsDefined(categoryType, category))
                throw new ArgumentException();

            var contactInfo = new ContactInfo
                                  {
                                      Data = data,
                                      InfoType = infoType,
                                      ContactID = contactid,
                                      IsPrimary = isPrimary,
                                      Category = (int)Enum.Parse(categoryType, category)
                                  };

            var contactInfoID = DaoFactory.GetContactInfoDao().Save(contactInfo);

            if (contactInfo.InfoType == ContactInfoType.Email)
            {
                var contact = DaoFactory.GetContactDao().GetByID(contactInfo.ContactID);
                var userIds = CRMSecurity.GetAccessSubjectTo(contact).Keys.ToList();
                var emails = new[] { contactInfo.Data };
                DaoFactory.GetContactInfoDao().UpdateMailAggregator(emails, userIds);
            }

            var contactInfoWrapper = ToContactInfoWrapper(contactInfo);

            contactInfoWrapper.ID = contactInfoID;

            return contactInfoWrapper;
        }
예제 #6
0
 public ContactInfoWrapper(ContactInfo contactInfo)
     : base(contactInfo.ID)
 {
     InfoType = contactInfo.InfoType;
     Category = contactInfo.Category;
     CategoryName = contactInfo.CategoryToString();
     Data = contactInfo.Data;
     IsPrimary = contactInfo.IsPrimary;
     ID = contactInfo.ID;
 }
예제 #7
0
        public ContactInfoWrapper CreateContactInfo(int contactid, ContactInfoType infoType, string data, bool isPrimary, string category)
        {
            if (string.IsNullOrEmpty(data) || contactid <= 0) throw new ArgumentException();
            var contact = DaoFactory.GetContactDao().GetByID(contactid);
            if (contact == null) throw new ItemNotFoundException();

            if (infoType == ContactInfoType.Twitter)
            {
                if (!CRMSecurity.CanAccessTo(contact)) throw new ItemNotFoundException();
            }
            else
            {
                if (!CRMSecurity.CanEdit(contact)) throw new ItemNotFoundException();
            }

            var categoryType = ContactInfo.GetCategory(infoType);
            if (!Enum.IsDefined(categoryType, category)) throw new ArgumentException();


            var contactInfo = new ContactInfo
                {
                    Data = data,
                    InfoType = infoType,
                    ContactID = contactid,
                    IsPrimary = isPrimary,
                    Category = (int)Enum.Parse(categoryType, category)
                };

            if (contactInfo.InfoType == ContactInfoType.Address)
            {
                Address res;
                if (!Address.TryParse(contactInfo, out res))
                    throw new ArgumentException();
            }

            var contactInfoID = DaoFactory.GetContactInfoDao().Save(contactInfo);

            var messageAction = contact is Company ? MessageAction.CompanyUpdatedPrincipalInfo : MessageAction.PersonUpdatedPrincipalInfo;
            MessageService.Send(Request, messageAction, contact.GetTitle());

            var contactInfoWrapper = ToContactInfoWrapper(contactInfo);
            contactInfoWrapper.ID = contactInfoID;
            return contactInfoWrapper;
        }
예제 #8
0
        private void _ReadContactInfo(JProperty jToken, String propertyValue, Contact contact, ref List<ContactInfo> findedContactInfos, ref List<int> primaryFields, String addressTemplateStr)
        {
            var nameParts = jToken.Name.Split(new[] { '_' }).Skip(1).ToList();
            var contactInfoType =
                (ContactInfoType)Enum.Parse(typeof(ContactInfoType), nameParts[0]);

            var category = Convert.ToInt32(nameParts[1]);

            bool isPrimary = false;

            if ((contactInfoType == ContactInfoType.Email ||
                contactInfoType == ContactInfoType.Phone ||
                contactInfoType == ContactInfoType.Address) &&
                (!primaryFields.Contains((int)contactInfoType)))
            {
                isPrimary = true;

                primaryFields.Add((int)contactInfoType);
            }

            if (contactInfoType == ContactInfoType.Address)
            {
                var addressPart = (AddressPart)Enum.Parse(typeof(AddressPart), nameParts[2]);

                var findedAddress =
                    findedContactInfos.Find(
                        item =>
                        (category == item.Category) && (item.InfoType == ContactInfoType.Address) &&
                        (item.ContactID == contact.ID));

                if (findedAddress == null)
                {
                    findedAddress = new ContactInfo
                    {
                        Category = category,
                        InfoType = contactInfoType,
                        Data = addressTemplateStr,
                        ContactID = contact.ID,
                        IsPrimary = isPrimary
                    };

                    findedContactInfos.Add(findedAddress);
                }

                var addressParts = JObject.Parse(findedAddress.Data);

                addressParts[addressPart.ToString().ToLower()] = propertyValue;

                findedAddress.Data = addressParts.ToString();

                return;
            }

            findedContactInfos.Add(new ContactInfo
            {
                Category = category,
                InfoType = contactInfoType,
                Data = propertyValue,
                ContactID = contact.ID,
                IsPrimary = isPrimary
            });
        }
        protected void SaveOrUpdateContact(object sender, CommandEventArgs e)
        {
            Contact contact;

            var typeAddedContact = Request["typeAddedContact"];

            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()
                };

                peopleCompany.ID = Global.DaoFactory.GetContactDao().SaveContact(peopleCompany);

                CRMSecurity.MakePublic(peopleCompany);

                companyID = peopleCompany.ID;
            }

            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()
                              };


            if (!String.IsNullOrEmpty(Request["baseInfo_contactOverview"]))
                contact.About = Request["baseInfo_contactOverview"].Trim();


            if (TargetContact != null)
            {
                contact.ID = TargetContact.ID;
                contact.StatusID = TargetContact.StatusID;
                Global.DaoFactory.GetContactDao().UpdateContact(contact);
                contact = Global.DaoFactory.GetContactDao().GetByID(contact.ID);
                SetPermission(contact);
                TimeLinePublisher.Contact(contact,
                                          CRMCommonResource.ActionText_Update,
                                          UserActivityConstants.ActivityActionType,
                                          UserActivityConstants.ImportantActivity);
            }
            else
            {
                contact.ID = Global.DaoFactory.GetContactDao().SaveContact(contact);
                contact = Global.DaoFactory.GetContactDao().GetByID(contact.ID);
                SetPermission(contact);
                TimeLinePublisher.Contact(contact,
                                          CRMCommonResource.ActionText_Create,
                                          UserActivityConstants.ActivityActionType,
                                          UserActivityConstants.ImportantActivity);
            }

            if (contact is Company)
            {
                int[] assignedContactsIDs = null;

                if (!String.IsNullOrEmpty(Request["baseInfo_assignedContactsIDs"]))
                    assignedContactsIDs = Request["baseInfo_assignedContactsIDs"].Split(',').Select(item => Convert.ToInt32(item)).ToArray();

                Global.DaoFactory.GetContactDao().SetMembers(contact.ID, assignedContactsIDs);

            }

            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)
                       Global.DaoFactory.GetCustomFieldDao().SetFieldValue(EntityType.Person, contact.ID, fieldID,
                                                                        fieldValue);
                    else
                        Global.DaoFactory.GetCustomFieldDao().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());

            Global.DaoFactory.GetContactInfoDao().DeleteByContact(contact.ID);
            Global.DaoFactory.GetContactInfoDao().SaveList(contactInfos);


            if (!String.IsNullOrEmpty(Request["uploadPhotoPath"]))
            {
                ContactPhotoManager.UploadPhoto(Request["uploadPhotoPath"], contact.ID);
            }


            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)));
        }
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                _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) || String.IsNullOrEmpty(lastName))) {
                        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);

                contact.IsShared = Convert.ToBoolean(GetValue("is_shared"));

                contact.ID = Global.DaoFactory.GetContactDao().SaveContact(contact);

                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 = Global.DaoFactory.GetCustomFieldDao().GetFieldDescription(fieldID);

                        if (customField == null) continue;

                        fieldCollector.Add(customField.Label, fieldValue);

                        Global.DaoFactory.GetCustomFieldDao().SetFieldValue(EntityType.Contact, 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");

                        Global.DaoFactory.GetTagDao().SetTagToEntity(EntityType.Contact, contact.ID, tags);

                    }
                }

                contactInfos.ForEach(item => fieldCollector[item.InfoType.ToLocalizedString()] = PrepareteDataToView(item.InfoType, item.Data));

                Global.DaoFactory.GetContactInfoDao().SaveList(contactInfos);

                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);

                if (contact is Company && !String.IsNullOrEmpty(firstName) && !String.IsNullOrEmpty(lastName))
                    AssignCompanyToPerson((Company)contact, firstName, lastName, managersList);

                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));
            }
        }
예제 #11
0
        private void ImportContactsData()
        {
            using (var CSVFileStream = _dataStore.GetReadStream("temp", _CSVFileURI))
            using (CsvReader csv = ImportFromCSV.CreateCsvReaderInstance(CSVFileStream, _importSettings))
            {
                int currentIndex = 0;

                var countactCount = ImportFromCSV.MaxRoxCount;

                var addressTemplate = new JObject();

                foreach (String addressPartName in Enum.GetNames(typeof(AddressPart)))
                    addressTemplate.Add(addressPartName.ToLower(), "");

                var addressTemplateStr = addressTemplate.ToString();

                var personFakeIdCompanyNameHash = new Dictionary<int, String>();

                var contactDao = _daoFactory.GetContactDao();
                var contactInfoDao = _daoFactory.GetContactInfoDao();
                var customFieldDao = _daoFactory.GetCustomFieldDao();
                var tagDao = _daoFactory.GetTagDao();
                var listItemDao = _daoFactory.GetListItemDao();

                var findedContacts = new Dictionary<int, Contact>();
                var findedTags = new Dictionary<int, List<String>>();
                var findedCustomField = new List<CustomField>();
                var findedContactInfos = new List<ContactInfo>();

                while (csv.ReadNextRecord())
                {
                    _columns = csv.GetCurrentRowFields(false);

                    var firstName = GetPropertyValue("firstName");
                    var lastName = GetPropertyValue("lastName");
                    var companyName = GetPropertyValue("companyName");

                    if ((String.IsNullOrEmpty(firstName) || String.IsNullOrEmpty(lastName)) &&
                        String.IsNullOrEmpty(companyName))
                        continue;

                    Percentage += 1.0 * 100 / (countactCount * 2);

                    Contact contact;

                    if (!(String.IsNullOrEmpty(firstName) || String.IsNullOrEmpty(lastName)))
                    {
                        var person = new Person
                        {
                            ID = currentIndex,
                            FirstName = firstName,
                            LastName = lastName,
                            JobTitle = GetPropertyValue("title")
                        };

                        if (!(String.IsNullOrEmpty(companyName)))
                            personFakeIdCompanyNameHash.Add(person.ID, companyName);

                        contact = person;
                    }
                    else
                    {
                        contact = new Company
                        {
                            ID = currentIndex
                        };

                        ((Company)contact).CompanyName = companyName;
                    }

                    contact.About = GetPropertyValue("notes");
                    contact.ShareType = _importSettings.ShareType;

                    var contactStageName = GetPropertyValue("contactStage");
                    var contactTypeName = GetPropertyValue("contactType");
                    if (!String.IsNullOrEmpty(contactStageName))
                    {
                        var contactStage = listItemDao.GetByTitle(ListType.ContactStatus, contactStageName);
                        if (contactStage != null)
                        {
                            contact.StatusID = contactStage.ID;
                        }
                        else
                        {
                            contact.StatusID = listItemDao.CreateItem(ListType.ContactStatus, new ListItem(){
                                Title = contactStageName,
                                Color = "#77cf9a",
                                Description = ""
                            });
                        }
                    }

                    if (!String.IsNullOrEmpty(contactTypeName))
                    {
                        var contactType = listItemDao.GetByTitle(ListType.ContactType, contactTypeName);
                        if (contactType != null)
                        {
                            contact.ContactTypeID = contactType.ID;
                        }
                        else
                        {
                            contact.ContactTypeID = listItemDao.CreateItem(ListType.ContactType, new ListItem(){
                                Title = contactTypeName,
                                Description = ""
                            });
                        }
                    }


                    findedContacts.Add(contact.ID, contact);


                    var tag = GetPropertyValue("tag");

                    if (!String.IsNullOrEmpty(tag))
                        findedTags.Add(contact.ID, tag.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList());

                    var primaryFields = new List<int>();

                    foreach (JProperty jToken in _importSettings.ColumnMapping.Children())
                    {
                        var propertyValue = GetPropertyValue(jToken.Name);

                        if (String.IsNullOrEmpty(propertyValue)) continue;

                        if (jToken.Name.StartsWith("customField_"))
                        {
                            var fieldID = Convert.ToInt32(jToken.Name.Split(new[] { '_' })[1]);
                            var field = customFieldDao.GetFieldDescription(fieldID);

                            if (field != null)
                            {
                                findedCustomField.Add(new CustomField
                                {
                                    EntityID = contact.ID,
                                    EntityType = contact is Person ? EntityType.Person : EntityType.Company,
                                    ID = fieldID,
                                    Value = field.FieldType == CustomFieldType.CheckBox ? (propertyValue == "on" || propertyValue == "true" ? "true" : "false") : propertyValue
                                });
                            }
                        }
                        else if (jToken.Name.StartsWith("contactInfo_"))
                        {
                            var nameParts = jToken.Name.Split(new[] { '_' }).Skip(1).ToList();
                            var contactInfoType =
                                (ContactInfoType)Enum.Parse(typeof(ContactInfoType), nameParts[0]);

                            var category = Convert.ToInt32(nameParts[1]);

                            bool isPrimary = false;

                            if ((contactInfoType == ContactInfoType.Email ||
                                contactInfoType == ContactInfoType.Phone ||
                                contactInfoType == ContactInfoType.Address) &&
                                (!primaryFields.Contains((int)contactInfoType)))
                            {
                                isPrimary = true;

                                primaryFields.Add((int)contactInfoType);
                            }

                            if (contactInfoType == ContactInfoType.Address)
                            {
                                var addressPart = (AddressPart)Enum.Parse(typeof(AddressPart), nameParts[2]);

                                var findedAddress =
                                    findedContactInfos.Find(
                                        item =>
                                        (category == item.Category) && (item.InfoType == ContactInfoType.Address) &&
                                        (item.ContactID == contact.ID));

                                if (findedAddress == null)
                                {
                                    findedAddress = new ContactInfo
                                    {
                                        Category = category,
                                        InfoType = contactInfoType,
                                        Data = addressTemplateStr,
                                        ContactID = contact.ID,
                                        IsPrimary = isPrimary
                                    };

                                    findedContactInfos.Add(findedAddress);
                                }

                                var addressParts = JObject.Parse(findedAddress.Data);

                                addressParts[addressPart.ToString().ToLower()] = propertyValue;

                                findedAddress.Data = addressParts.ToString();

                                continue;
                            }

                            findedContactInfos.Add(new ContactInfo
                            {
                                Category = category,
                                InfoType = contactInfoType,
                                Data = propertyValue,
                                ContactID = contact.ID,
                                IsPrimary = isPrimary
                            });
                        }
                    }


                    if (currentIndex + 1 > ImportFromCSV.MaxRoxCount) break;

                    currentIndex++;

                }

                Percentage = 37.5;

                switch (_importSettings.DuplicateRecordRule)
                {
                    case 1:  // Skip  
                        {
                            var emails = findedContactInfos.Where(item => item.InfoType == ContactInfoType.Email).ToList();

                            var duplicateContactsID = contactDao.FindDuplicateByEmail(emails).Select(
                                   row => Convert.ToInt32(row[0])).Distinct().ToList();

                            if (duplicateContactsID.Count == 0) break;

                            findedContacts = findedContacts.Where(item => !duplicateContactsID.Contains(item.Key)).ToDictionary(x => x.Key, y => y.Value);

                            personFakeIdCompanyNameHash = personFakeIdCompanyNameHash.Where(item => !duplicateContactsID.Contains(item.Key)).ToDictionary(x => x.Key, y => y.Value);

                            if (findedContacts.Count == 0)
                            {
                                Complete();

                                return;
                            }

                            findedContactInfos = findedContactInfos.Where(item => !duplicateContactsID.Contains(item.ContactID)).ToList();
                            findedCustomField = findedCustomField.Where(item => !duplicateContactsID.Contains(item.EntityID)).ToList();

                            foreach (var exceptID in duplicateContactsID)
                            {
                                if (findedTags.ContainsKey(exceptID)) findedTags.Remove(exceptID);
                            }


                        }
                        break;
                    case 2:  // Overwrite  
                        {
                            var emailContactInfos = findedContactInfos.Where(item => item.InfoType == ContactInfoType.Email).ToList();

                            var duplicateContactsID = contactDao.FindDuplicateByEmail(emailContactInfos).Select(
                                 row => Convert.ToInt32(row[2])).Distinct().ToArray();

                            contactDao.DeleteBatchContact(duplicateContactsID);

                            break;
                        }
                    case 3: // Clone
                        break;
                    default:
                        break;
                }

                Percentage += 12.5;

                var findedCompanies = findedContacts.Where(x => x.Value is Company).ToDictionary(x => x.Key, y => y.Value);
                var findedPeoples = findedContacts.Where(x => x.Value is Person).ToDictionary(x => x.Key, y => y.Value);

                var fakeRealContactIdHash = contactDao.SaveContactList(findedCompanies.Values.ToList())
                                            .ToDictionary(item => item.Key, item => item.Value);

                var companyNameRealIdHash = new Dictionary<String, int>();

                foreach (Company item in findedCompanies.Values)
                {
                    if (companyNameRealIdHash.ContainsKey(item.CompanyName)) continue;

                    companyNameRealIdHash.Add(item.CompanyName, item.ID);

                }

                foreach (var item in personFakeIdCompanyNameHash)
                {

                    var person = (Person)findedPeoples[item.Key];


                    if (companyNameRealIdHash.ContainsKey(item.Value))
                    {
                        person.CompanyID = companyNameRealIdHash[item.Value];
                    }
                    else
                    {
                        var findedCompany = contactDao.GetContactsByName(item.Value).FirstOrDefault(x => x is Company);

                        // Why ???
                        if (findedCompany == null)
                        {
                            findedCompany = new Company
                            {
                                CompanyName = item.Value,
                                ShareType = _importSettings.ShareType
                            };
                            findedCompany.ID = contactDao.SaveContact(findedCompany);

                            person.CompanyID = findedCompany.ID;
                            CRMSecurity.SetAccessTo(findedCompany, _importSettings.ContactManagers);
                        }
                        else
                        {
                            person.CompanyID = findedCompany.ID;

                        }

                        companyNameRealIdHash.Add(item.Value, person.CompanyID);
                    }
                }

                fakeRealContactIdHash = fakeRealContactIdHash.Union(contactDao.SaveContactList(findedPeoples.Values.ToList())).ToDictionary(item => item.Key, item => item.Value);

                Percentage += 12.5;

                findedContactInfos.ForEach(item => item.ContactID = fakeRealContactIdHash[item.ContactID]);

                contactInfoDao.SaveList(findedContactInfos);

                Percentage += 12.5;

                findedCustomField.ForEach(item => item.EntityID = fakeRealContactIdHash[item.EntityID]);

                customFieldDao.SaveList(findedCustomField);

                Percentage += 12.5;

                foreach (var findedTagKey in findedTags.Keys)
                    tagDao.SetTagToEntity(EntityType.Contact, fakeRealContactIdHash[findedTagKey], findedTags[findedTagKey].ToArray());

                findedContacts.Values.ToList().ForEach(contact => CRMSecurity.SetAccessTo(contact, _importSettings.ContactManagers));

                Percentage += 12.5;
            }

            Complete();

        }
        protected void SaveOrUpdateContact(object sender, CommandEventArgs e)
        {
            Contact contact;

            var typeAddedContact = Request["typeAddedContact"];

            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()
                };

                peopleCompany.ID = Global.DaoFactory.GetContactDao().SaveContact(peopleCompany);

                CRMSecurity.MakePublic(peopleCompany);

                companyID = peopleCompany.ID;
            }

            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()
                              };
            }

            if (!String.IsNullOrEmpty(Request["baseInfo_contactOverview"]))
            {
                contact.About = Request["baseInfo_contactOverview"].Trim();
            }

            Boolean isSharedContact;
            if(bool.TryParse(Request["isPublicContact"], out isSharedContact))
            {
                contact.IsShared = isSharedContact;
            }

            contact.ContactTypeID = Convert.ToInt32(Request["baseInfo_contactType"]);

            if (TargetContact != null)
            {
                contact.ID = TargetContact.ID;
                contact.StatusID = TargetContact.StatusID;
                Global.DaoFactory.GetContactDao().UpdateContact(contact);
                contact = Global.DaoFactory.GetContactDao().GetByID(contact.ID);
            }
            else
            {
                contact.ID = Global.DaoFactory.GetContactDao().SaveContact(contact);
                contact = Global.DaoFactory.GetContactDao().GetByID(contact.ID);
            }

            SetContactManager(contact);

            if (contact is Company)
            {
                int[] assignedContactsIDs = null;

                if (!String.IsNullOrEmpty(Request["baseInfo_assignedContactsIDs"]))
                    assignedContactsIDs = Request["baseInfo_assignedContactsIDs"].Split(',').Select(item => Convert.ToInt32(item)).ToArray();

                Global.DaoFactory.GetContactDao().SetMembers(contact.ID, assignedContactsIDs);

            }

            var assignedTags = Request["baseInfo_assignedTags"];
            if (assignedTags != null)
            {
                var oldTagList = Global.DaoFactory.GetTagDao().GetEntityTags(EntityType.Contact, contact.ID);
                foreach (var tag in oldTagList)
                {
                    Global.DaoFactory.GetTagDao().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();
                    Global.DaoFactory.GetTagDao().SetTagToEntity(EntityType.Contact, contact.ID, newTagList);
                }
            }

            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)
                    {
                        Global.DaoFactory.GetCustomFieldDao().SetFieldValue(EntityType.Person, contact.ID, fieldID, fieldValue);
                    }
                    else
                    {
                        Global.DaoFactory.GetCustomFieldDao().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());

            Global.DaoFactory.GetContactInfoDao().DeleteByContact(contact.ID);
            Global.DaoFactory.GetContactInfoDao().SaveList(contactInfos);

            var emails = contactInfos
                .Where(item => item.InfoType == ContactInfoType.Email)
                .Select(item => item.Data)
                .ToList();
            if (emails.Count > 0)
            {
                var userIds = CRMSecurity.GetAccessSubjectTo(contact).Keys.ToList();
                Global.DaoFactory.GetContactInfoDao().UpdateMailAggregator(emails, userIds);
            }

            var photoPath = Request["uploadPhotoPath"];

            if (!String.IsNullOrEmpty(photoPath))
            {
                if (photoPath != "null")
                {
                    if (photoPath.StartsWith(PathProvider.BaseAbsolutePath))
                    {
                        var tmpDirName = photoPath.Substring(0, photoPath.LastIndexOf('/'));
                        ContactPhotoManager.TryUploadPhotoFromTmp(contact.ID, TargetContact == null, tmpDirName);
                    }
                    else
                    {
                        ContactPhotoManager.UploadPhoto(photoPath, contact.ID);
                    }
                }
            }
            else if (TargetContact != null)
            {
                ContactPhotoManager.DeletePhoto(TargetContact.ID);
            }

            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)));
        }
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                _context = context;

                SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);

                if (!CheckPermission())
                    throw new Exception(CRMSettingResource.WebToLeadsForm_InvalidKeyException);

                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 firstName = GetValue("firstName");
                var lastName = GetValue("lastName");
                var companyName = GetValue("companyName");

                if (!(String.IsNullOrEmpty(firstName) || String.IsNullOrEmpty(lastName)))
                {
                    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);

                }
                else if (!String.IsNullOrEmpty(companyName))
                {
                    contact = new Company();

                    ((Company)contact).CompanyName = companyName;

                    fieldCollector.Add(CRMContactResource.CompanyName, companyName);

                }
                else
                    throw new ArgumentException();

                contact.About = GetValue("about");

                if (!String.IsNullOrEmpty(contact.About))
                    fieldCollector.Add(CRMContactResource.About, contact.About);

                contact.ID = Global.DaoFactory.GetContactDao().SaveContact(contact);

                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 = Global.DaoFactory.GetCustomFieldDao().GetFieldDescription(fieldID);

                        if (customField == null) continue;

                        fieldCollector.Add(customField.Label, fieldValue);

                        Global.DaoFactory.GetCustomFieldDao().SetFieldValue(EntityType.Contact, 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]);

                        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");

                        Global.DaoFactory.GetTagDao().SetTagToEntity(EntityType.Contact, contact.ID, tags);

                    }
                }

                contactInfos.ForEach(item => fieldCollector.Add(item.InfoType.ToLocalizedString(), PrepareteDataToView(item.InfoType, item.Data)));

                Global.DaoFactory.GetContactInfoDao().SaveList(contactInfos);

                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);


                SetPermission(contact, GetValue("private_list"));

                if (contact is Person && !String.IsNullOrEmpty(companyName))
                    AssignPersonToCompany((Person)contact, companyName, GetValue("private_list"));

                SecurityContext.Logout();

                context.Response.Redirect(GetValue("return_url"));
            }
            catch (Exception error)
            {
                LogManager.GetLogger("ASC.CRM").Error(error);
                throw;
            }
        }
예제 #14
0
        public ContactInfoWrapper CreateContactInfo(int contactid,
                                                 ContactInfoType infoType,
                                                 String data,
                                                 bool isPrimary,
                                                 String category
                                             )
        {
            if (String.IsNullOrEmpty(data) || contactid == 0)
                throw new ArgumentException();

            var categoryType = ContactInfo.GetCategory(infoType);

            if (!Enum.IsDefined(categoryType, category))
                throw new ArgumentException();

            var contactInfo = new ContactInfo
                                  {
                                      Data = data,
                                      InfoType = infoType,
                                      ContactID = contactid,
                                      IsPrimary = isPrimary,
                                      Category = (int)Enum.Parse(categoryType, category)
                                  };

            var contactInfoID = DaoFactory.GetContactInfoDao().Save(contactInfo);

            var contactInfoWrapper = ToContactInfoWrapper(contactInfo);

            contactInfoWrapper.ID = contactInfoID;

            return contactInfoWrapper;
        }
예제 #15
0
        protected String RenderContactInfo(ContactInfo contactInfo)
        {

            switch (contactInfo.InfoType)
            {
                case ContactInfoType.Email:
                    return String.Format("<a class='crm-email linkMedium' href='mailto:{0}'>{0}</a><span class='textMediumDescribe'> ({1})</span>", contactInfo.Data.HtmlEncode(), contactInfo.CategoryToString());
                case ContactInfoType.Phone:
                    return String.Format("<div class='crm-phone'>{0}<span class='textMediumDescribe'> ({1})</span></div>", contactInfo.Data.HtmlEncode(), contactInfo.CategoryToString());
                //case ContactInfoType.Website:
                //    return String.Format("<a class='crm-website' href='${0}' target='_blank'>${0}</a><span class='textSmallDescribe'> ({1})</span>", contactInfo.Data, contactInfo.CategoryToString());
                //case ContactInfoType.Skype:
                //    return String.Format("<div class='crm-skype'>{0}<span class='textSmallDescribe'> ({1})</span></div>", contactInfo.Data, contactInfo.CategoryToString());
                //case ContactInfoType.Twitter:
                //    return String.Format("<a class='crm-twitter' href='http://twitter.com/{0}' target='_blank'>${0}</a><span class='textSmallDescribe'> ({1})</span>", contactInfo.Data, contactInfo.CategoryToString());
                //case ContactInfoType.LinkedIn:
                //    return String.Format("<a class='crm-linkedin' href='{0}' target='_blank'>${0}</a><span class='textSmallDescribe'> ({1})</span>", contactInfo.Data, contactInfo.CategoryToString());
                //case ContactInfoType.Facebook:
                //    return String.Format("<a class='crm-facebook' href='http://facebook.com/{0}' target='_blank'>${0}</a><span class='textSmallDescribe'> ({1})</span>", contactInfo.Data, contactInfo.CategoryToString());
                //case ContactInfoType.LiveJournal:
                //    return String.Format("<a class='rm-livejournal' href='{0}' target='_blank'>${0}</a><span class='textSmallDescribe'> ({1})</span>", contactInfo.Data, contactInfo.CategoryToString());
                //case ContactInfoType.MySpace:
                //    return String.Format("<a class='crm-myspace' href='{0}' target='_blank'>${0}</a><span class='textSmallDescribe'> ({1})</span>", contactInfo.Data, contactInfo.CategoryToString());
                //case ContactInfoType.GMail:
                //    return String.Format("<a class='crm-gmail' href='{0}' target='_blank'>${0}</a><span class='textSmallDescribe'> ({1})</span>", contactInfo.Data, contactInfo.CategoryToString());
                //case ContactInfoType.Blogger:
                //    return String.Format("<a class='crm-blogger' href='{0}' target='_blank'>${0}</a><span class='textSmallDescribe'> ({1})</span>", contactInfo.Data, contactInfo.CategoryToString());
                //case ContactInfoType.Yahoo:
                //    return String.Format("<a class='crm-yahoo' href='{0}' target='_blank'>${0}</a><span class='textSmallDescribe'> ({1})</span>", contactInfo.Data, contactInfo.CategoryToString());
                //case ContactInfoType.MSN:
                //    return String.Format("<a class='crm-msn' href='{0}' target='_blank'>${0}</a><span class='textSmallDescribe'> ({1})</span>", contactInfo.Data, contactInfo.CategoryToString());
                //case ContactInfoType.ICQ:
                //    return String.Format("<div class='crm-icq'>{0}<span class='textSmallDescribe'> ({1})</span></div>", contactInfo.Data, contactInfo.CategoryToString());
                //case ContactInfoType.Jabber:
                //    return String.Format("<div class='crm-jabber'>{0}<span class='textSmallDescribe'> ({1})</span></div>", contactInfo.Data, contactInfo.CategoryToString());
                //case ContactInfoType.AIM:
                //    return String.Format("<div class='crm-aim'>{0}<span class='textSmallDescribe'> ({1})</span></div>", contactInfo.Data, contactInfo.CategoryToString());
                case ContactInfoType.Address:
                    var address = JObject.Parse(contactInfo.Data);

                    var street = address[AddressPart.Street.ToString().ToLower()].ToString().HtmlEncode();
                    var city = address[AddressPart.City.ToString().ToLower()].ToString().HtmlEncode();
                    var state = address[AddressPart.State.ToString().ToLower()].ToString().HtmlEncode();
                    var country = address[AddressPart.Country.ToString().ToLower()].ToString().HtmlEncode();
                    var zip = address[AddressPart.Zip.ToString().ToLower()].ToString().HtmlEncode();

                    var text = street;
                    var tmp = String.IsNullOrEmpty(city) ? "" : city + ", ";

                    if (!String.IsNullOrEmpty(state)) { tmp += state + ", "; }
                    if (!String.IsNullOrEmpty(zip)) { tmp += zip; }
                    tmp = tmp.Trim().TrimEnd(',');
                    if (!String.IsNullOrEmpty(tmp)) { text = !String.IsNullOrEmpty(text) ? text + ",<br/>" + tmp : tmp; }
                    text = !String.IsNullOrEmpty(text) && !String.IsNullOrEmpty(country) ? text + ",<br/>" + country : text;
                    
                    var href = "";
                    if (!String.IsNullOrEmpty(street)) { href += street + ", "; }
                    if (!String.IsNullOrEmpty(city)) { href += city + ", "; }
                    if (!String.IsNullOrEmpty(state)) { href += state + ", "; }
                    if (!String.IsNullOrEmpty(zip)) { href += zip + ", "; }
                    if (!String.IsNullOrEmpty(country)) { href += country + ", "; }
                    href = href.Trim().TrimEnd(',');

                    return String.Format("<div class='crm-address'>{0}"
                        + "<span class='textMediumDescribe'> ({2})</span><br/>"
                        + "<a class='linkMedium' style='text-decoration: underline;' href='http://maps.google.com/maps?q={1}' target='_blank'>"
                        + CRMContactResource.ShowOnMap + "</a>"
                        + "</div>", text, href, contactInfo.CategoryToString());

                default:
                    return contactInfo.Data;
            }

        }
        public ContactInfoWrapper CreateContactInfo(int contactid, ContactInfoType infoType, string data, bool isPrimary, string category)
        {
            if (string.IsNullOrEmpty(data) || contactid <= 0) throw new ArgumentException();
            var contact = DaoFactory.GetContactDao().GetByID(contactid);
            if (contact == null || !CRMSecurity.CanEdit(contact)) throw new ItemNotFoundException();

            var categoryType = ContactInfo.GetCategory(infoType);
            if (!Enum.IsDefined(categoryType, category)) throw new ArgumentException();


            var contactInfo = new ContactInfo
                {
                    Data = data,
                    InfoType = infoType,
                    ContactID = contactid,
                    IsPrimary = isPrimary,
                    Category = (int)Enum.Parse(categoryType, category)
                };

            var contactInfoID = DaoFactory.GetContactInfoDao().Save(contactInfo);

            if (contactInfo.InfoType == ContactInfoType.Email)
            {
                var userIds = CRMSecurity.GetAccessSubjectTo(contact).Keys.ToList();
                var emails = new[] {contactInfo.Data};
                DaoFactory.GetContactInfoDao().UpdateMailAggregator(emails, userIds);
            }

            var messageAction = contact is Company ? MessageAction.CompanyUpdatedPrincipalInfo : MessageAction.PersonUpdatedPrincipalInfo;
            MessageService.Send(_context, messageAction, contact.GetTitle());

            var contactInfoWrapper = ToContactInfoWrapper(contactInfo);
            contactInfoWrapper.ID = contactInfoID;
            return contactInfoWrapper;
        }