Exemplo n.º 1
0
 public PersonWrapper(Person person)
     : base(person)
 {
     FirstName = person.FirstName;
     LastName = person.LastName;
     Title = person.JobTitle;
 }
Exemplo n.º 2
0
        public static PersonWrapper ToPersonWrapperQuick(Person person)
        {
            var result = new PersonWrapper(person.ID);

            result.DisplayName = person.GetTitle();
            result.IsPrivate = CRMSecurity.IsPrivate(person);
            result.IsShared = person.ShareType == ShareType.ReadWrite || person.ShareType == ShareType.Read;
            result.ShareType = person.ShareType;

            if (result.IsPrivate)
            {
                result.AccessList = CRMSecurity.GetAccessSubjectTo(person)
                                        .Select(item => EmployeeWraper.Get(item.Key));
            }
            result.Currency = !String.IsNullOrEmpty(person.Currency) ?
                new CurrencyInfoWrapper(CurrencyProvider.Get(person.Currency)) :
                null;

            result.SmallFotoUrl = String.Format("{0}HttpHandlers/filehandler.ashx?action=contactphotoulr&cid={1}&isc={2}&ps=1", PathProvider.BaseAbsolutePath, person.ID, false).ToLower();
            result.MediumFotoUrl = String.Format("{0}HttpHandlers/filehandler.ashx?action=contactphotoulr&cid={1}&isc={2}&ps=2", PathProvider.BaseAbsolutePath, person.ID, false).ToLower();
            result.IsCompany = false;
            result.CanEdit = CRMSecurity.CanEdit(person);
            //result.CanDelete = CRMSecurity.CanDelete(contact);

            result.CreateBy = EmployeeWraper.Get(person.CreateBy);
            result.Created = (ApiDateTime)person.CreateOn;
            result.About = person.About;
            result.Industry = person.Industry;


            result.FirstName = person.FirstName;
            result.LastName = person.LastName;
            result.Title = person.JobTitle;

            return result;
        }
Exemplo n.º 3
0
        protected static Contact ToContact(object[] row)
        {
            Contact contact;

            var isCompany = Convert.ToBoolean(row[6]);

            if (isCompany)
                contact = new Company
                           {
                               CompanyName = Convert.ToString(row[3])
                           };
            else
                contact = new Person
                       {
                           FirstName = Convert.ToString(row[1]),
                           LastName = Convert.ToString(row[2]),
                           JobTitle = Convert.ToString(row[4]),
                           CompanyID = Convert.ToInt32(row[9])
                       };

            contact.ID = Convert.ToInt32(row[0]);
            contact.About = Convert.ToString(row[5]);
            contact.Industry = Convert.ToString(row[7]);
            contact.StatusID = Convert.ToInt32(row[8]);
            contact.CreateOn = TenantUtil.DateTimeFromUtc(Convert.ToDateTime(row[10]));
            contact.CreateBy = ToGuid(row[11]);
            contact.ContactTypeID = Convert.ToInt32(row[14]);
            
            if (row[13] == null)
            {
                var accessSubjectToContact = CRMSecurity.GetAccessSubjectTo(contact);

                contact.IsShared = !accessSubjectToContact.Any();
            }
            else
                contact.IsShared = Convert.ToBoolean(row[13]); 

            return contact;
        }
Exemplo n.º 4
0
        protected static Contact ToContact(object[] row)
        {

            Contact contact;

            var isCompany = Convert.ToBoolean(row[6]);

            if (isCompany)
                contact = new Company
                           {
                               CompanyName = Convert.ToString(row[3])
                           };
            else
                contact = new Person
                       {
                           FirstName = Convert.ToString(row[1]),
                           LastName = Convert.ToString(row[2]),
                           JobTitle = Convert.ToString(row[4]),
                           CompanyID = Convert.ToInt32(row[9])
                       };

            contact.ID = Convert.ToInt32(row[0]);
            contact.About = Convert.ToString(row[5]);
            contact.Industry = Convert.ToString(row[7]);
            contact.StatusID = Convert.ToInt32(row[8]);
            contact.CreateOn = TenantUtil.DateTimeFromUtc(Convert.ToDateTime(row[10]));
            contact.CreateBy = ToGuid(row[11]);

            return contact;

        }
Exemplo n.º 5
0
        private bool _CommonData(int currentIndex, ref Contact contact, ref Dictionary<int, String> personFakeIdCompanyNameHash)
        {
            var firstName = GetPropertyValue("firstName");
            var lastName = GetPropertyValue("lastName");
            var companyName = GetPropertyValue("companyName");

            if (String.IsNullOrEmpty(firstName) && String.IsNullOrEmpty(lastName) && String.IsNullOrEmpty(companyName))
                return false;

            Percentage += 1.0 * 100 / (ImportFromCSV.MaxRoxCount * 2);

            var listItemDao = _daoFactory.GetListItemDao();


            if (!String.IsNullOrEmpty(firstName) || !String.IsNullOrEmpty(lastName))
            {
                var person = new Person
                {
                    ID = currentIndex,
                    FirstName = !String.IsNullOrEmpty(firstName) ? firstName : lastName,
                    LastName = !String.IsNullOrEmpty(firstName) ? lastName : String.Empty,
                    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 = ""
                    });
                }
            }

            return true;
        }
        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);
                }
            }
        }
Exemplo n.º 7
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();


            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)));
        }
Exemplo n.º 9
0
        public PersonWrapper CreatePerson(
            string firstName,
            string lastName,
            string jobTitle,
            int companyId,
            string about,
            ShareType shareType,
            IEnumerable<Guid> managerList,
            IEnumerable<ItemKeyValuePair<int, string>> customFieldList,
            IEnumerable<HttpPostedFileBase> photo)
        {
            if (companyId > 0) {
                var company = DaoFactory.GetContactDao().GetByID(companyId);
                if (company == null || !CRMSecurity.CanAccessTo(company)) throw new ItemNotFoundException();
            }

            var peopleInst = new Person
                {
                    FirstName = firstName,
                    LastName = lastName,
                    JobTitle = jobTitle,
                    CompanyID = companyId,
                    About = about,
                    ShareType = shareType
                };

            peopleInst.ID = DaoFactory.GetContactDao().SaveContact(peopleInst);
            peopleInst.CreateBy = Core.SecurityContext.CurrentAccount.ID;
            peopleInst.CreateOn = DateTime.UtcNow;

            var managerListLocal = managerList != null ? managerList.ToList() : new List<Guid>();
            if (managerListLocal.Any())
            {
                CRMSecurity.SetAccessTo(peopleInst, managerListLocal);
            }

            if (customFieldList != null)
            {
                foreach (var field in customFieldList)
                {
                    if (string.IsNullOrEmpty(field.Value)) continue;
                    DaoFactory.GetCustomFieldDao().SetFieldValue(EntityType.Person, peopleInst.ID, field.Key, field.Value);
                }
            }

            var wrapper = (PersonWrapper)ToContactWrapper(peopleInst);

            var photoList = photo != null ? photo.ToList() : new List<HttpPostedFileBase>();
            if (photoList.Any())
            {
                wrapper.SmallFotoUrl = ChangeContactPhoto(peopleInst.ID, photoList);
            }

            MessageService.Send(Request, MessageAction.PersonCreated, peopleInst.GetTitle());

            return wrapper;
        }
Exemplo n.º 10
0
        public String AddNewContact(bool isCompany, string companyName, string firstName, string lastName)
        {
            if (isCompany)
            {
                var company = new Company
                {
                    CompanyName = companyName.Trim()
                };

                company.ID = Global.DaoFactory.GetContactDao().SaveContact(company);
                CRMSecurity.MakePublic(company);

                return JsonConvert.SerializeObject(new
                {
                    id = company.ID,
                    title = company.GetTitle().HtmlEncode(),
                    img = ContactPhotoManager.GetSmallSizePhoto(company.ID, true)
                });
            }
            else
            {
                var contact = new Person
                {
                    FirstName = firstName.Trim(),
                    LastName = lastName.Trim()
                };

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

                return JsonConvert.SerializeObject(new
                {
                    id = contact.ID,
                    title = contact.GetTitle().HtmlEncode(),
                    img = ContactPhotoManager.GetSmallSizePhoto(contact.ID, false)
                });
            }

        }
        protected void AssignPersonToCompany(Person person, String companyName, String privateList)
        {
            Company company;

            var findedCompanies = Global.DaoFactory.GetContactDao().GetContactsByName(companyName)
                                  .Where(item => item is Company).ToList();

            if (findedCompanies.Count == 0)
            {
                company = new Company
                                     {
                                         CompanyName = companyName
                                     };

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

                SetPermission(company, privateList);

            }
            else
            {


                company = (Company)findedCompanies[0];
            }

            Global.DaoFactory.GetContactDao().AddMember(person.ID, company.ID);
        }
        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));
            }
        }
 protected void AssignCompanyToPerson(Company company, String firstName, String lastName, String privateList)
 {
     var person = new Person
                             {
                                 FirstName = firstName,
                                 LastName = lastName,
                                 CompanyID = company.ID
                             };
     person.ID = Global.DaoFactory.GetContactDao().SaveContact(person);
     SetPermission(person, privateList);
 }
        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;
            }
        }
Exemplo n.º 16
0
        private static Contact ToContact(object[] r)
        {
            Contact contact;
            var isCompany = Convert.ToBoolean(r[0]);

            if (isCompany)
            {
                contact = new Company
                    {
                        ID = Convert.ToInt32(r[1]),
                        About = Convert.ToString(r[2]),
                        CompanyName = Convert.ToString(r[5]),
                        IsShared = Convert.ToBoolean(r[8]),
                        CreateBy = new Guid(Convert.ToString(r[9])),
                        CreateOn = Convert.ToDateTime(r[10]),
                        LastModifedBy = new Guid(Convert.ToString(r[11])),
                        LastModifedOn = Convert.ToDateTime(r[12])
                    };
            }
            else
            {
                contact = new Person
                    {
                        ID = Convert.ToInt32(r[1]),
                        About = Convert.ToString(r[2]),
                        FirstName = Convert.ToString(r[3]),
                        LastName = Convert.ToString(r[4]),
                        CompanyID = Convert.ToInt32(r[6]),
                        JobTitle = Convert.ToString(r[7]),
                        IsShared = Convert.ToBoolean(r[8]),
                        CreateBy = new Guid(Convert.ToString(r[9])),
                        CreateOn = Convert.ToDateTime(r[10]),
                        LastModifedBy = new Guid(Convert.ToString(r[11])),
                        LastModifedOn = Convert.ToDateTime(r[12])
                    };
            }

            return contact;
        }
        public List<string> SearchCrmContacts(int tenant, string user, string searchText)
        {
            var contacts = new List<string>();

            if (!string.IsNullOrEmpty(searchText))
            {
                #region Set up connection to CRM sequrity
                try
                {
                    CoreContext.TenantManager.SetCurrentTenant(tenant);
                    SecurityContext.AuthenticateMe(CoreContext.Authentication.GetAccountByID(new Guid(user)));
                }
                catch (Exception e)
                {
                    _log.Error("Error connecting to CRM database", e);
                    return contacts;
                }
                #endregion

                //TODO: move to crm api

                const string cc_alias = "cc";
                const string cci_alias = "cci";

                using (var db = new DbManager("crm"))
                {
                    var query = new SqlQuery(CrmContactTable.name.Alias(cc_alias))
                        .Select(CrmContactTable.Columns.id.Prefix(cc_alias),
                                CrmContactTable.Columns.is_company.Prefix(cc_alias),
                                string.Format("trim(concat({0}, ' ', {1}, ' ', {2}))",
                                              CrmContactTable.Columns.first_name.Prefix(cc_alias),
                                              CrmContactTable.Columns.last_name.Prefix(cc_alias),
                                              CrmContactTable.Columns.company_name.Prefix(cc_alias)),
                                CrmContactTable.Columns.is_shared.Prefix(cc_alias),
                                CrmContactInfoTable.Columns.data.Prefix(cci_alias))
                        .InnerJoin(CrmContactInfoTable.name.Alias(cci_alias),
                                   Exp.EqColumns(CrmContactTable.Columns.tenant_id.Prefix(cc_alias),
                                                 CrmContactInfoTable.Columns.tenant_id.Prefix(cci_alias)) &
                                   Exp.EqColumns(CrmContactTable.Columns.id.Prefix(cc_alias),
                                                 CrmContactInfoTable.Columns.contact_id.Prefix(cci_alias)))
                        .Where(CrmContactInfoTable.Columns.type.Prefix(cci_alias), (int) ContactInfoType.Email);

                    if (FullTextSearch.SupportModule(FullTextSearch.CRMEmailsModule))
                    {
                        var ids = FullTextSearch.Search(FullTextSearch.CRMEmailsModule.Match(searchText.TrimEnd('*') + "*"));

                        if (!ids.Any())
                            return contacts;

                        query.Where(Exp.In(CrmContactInfoTable.Columns.id.Prefix(cci_alias),
                                           ids.Take(FULLTEXTSEARCH_IDS_COUNT).ToList()));

                    }
                    else
                    {
                        searchText = searchText.Replace("\"", "\\\"");
                        query
                            .Where(CrmContactTable.Columns.tenant_id.Prefix(cc_alias), tenant)
                            .Where(string.Format("(concat({0}, ' ', {1}) like '%{2}%')",
                                                 CrmContactTable.Columns.display_name.Prefix(cc_alias),
                                                 CrmContactInfoTable.Columns.data.Prefix(cci_alias),
                                                 searchText));
                    }

                    var result = db.ExecuteList(query)
                                    .ConvertAll(r => new
                                    {
                                        Id = Convert.ToInt32(r[0]),
                                        Company = Convert.ToBoolean(r[1]),
                                        DisplayName = Convert.ToString(r[2]),
                                        IsShared = r[3],
                                        Email = Convert.ToString(r[4])
                                    });

                    foreach (var r in result)
                    {
                        Contact contact;
                        if(r.Company)
                        {
                            contact = new Company();
                        }
                        else
                        {
                            contact = new Person();
                        }
                        contact.ID = r.Id;
                        contact.ShareType = GetContactShareType(contact, r.IsShared);
                        if (CRMSecurity.CanAccessTo(contact))
                        {
                            contacts.Add("\"" + r.DisplayName + "\" <" + r.Email + ">");
                        }
                    }
                }
            }
            return contacts;
        }
Exemplo n.º 18
0
        public PersonWrapper CreatePerson(String firstName,
                                          String lastName,
                                          String jobTitle,
                                          int companyId,
                                          String about,
                                          bool isShared,
                                          IEnumerable<Guid> managerList,
                                          IEnumerable<ItemKeyValuePair<int, String>> customFieldList,
                                          HttpPostedFileBase photo)
        {
            var peopleInst = new Person
                                 {
                                     FirstName = firstName,
                                     LastName = lastName,
                                     JobTitle = jobTitle,
                                     CompanyID = companyId,
                                     About = about,
                                     IsShared = isShared
                                 };

            peopleInst.ID = DaoFactory.GetContactDao().SaveContact(peopleInst);
            peopleInst.CreateBy = Core.SecurityContext.CurrentAccount.ID;
            peopleInst.CreateOn = DateTime.UtcNow;

            var managerListLocal = managerList.ToList();
            if (managerListLocal.Count != 0)
            {
                CRMSecurity.SetAccessTo(peopleInst, managerListLocal);
            }

            foreach (var field in customFieldList)
            {
                if (String.IsNullOrEmpty(field.Value)) continue;

                DaoFactory.GetCustomFieldDao().SetFieldValue(EntityType.Person, peopleInst.ID, field.Key, field.Value);
            }

            var result = (PersonWrapper)ToContactWrapper(peopleInst);

            if (photo != null)
                result.SmallFotoUrl = ChangeContactPhoto(peopleInst.ID, photo);

            return result;

        }
Exemplo n.º 19
0
 public static bool CanAccessTo(int contactID, EntityType entityType, ShareType? shareType, int companyID)
 {
     if (shareType.HasValue && (shareType.Value == ShareType.Read || shareType.Value == ShareType.ReadWrite) || IsAdmin)
     {
         return true;
     }
     if (entityType == EntityType.Company){
         var fakeContact = new Company() { ID = contactID };
         return GetAccessSubjectTo(fakeContact).ContainsKey(SecurityContext.CurrentAccount.ID);
     }
     else if (entityType == EntityType.Person)
     {
         var fakeContact = new Person() { ID = contactID, CompanyID = companyID };
         return GetAccessSubjectTo(fakeContact).ContainsKey(SecurityContext.CurrentAccount.ID);
     }
     return false;
 }
Exemplo n.º 20
0
        public PersonWrapper UpdatePerson(
            int personid,
            string firstName,
            string lastName,
            string jobTitle,
            int companyId,
            string about,
            ShareType shareType,
            IEnumerable<Guid> managerList,
            IEnumerable<ItemKeyValuePair<int, string>> customFieldList,
            IEnumerable<HttpPostedFileBase> photo)
        {
            if (personid <= 0 || string.IsNullOrEmpty(firstName) || string.IsNullOrEmpty(lastName)) throw new ArgumentException();

            var peopleInst = new Person
                {
                    ID = personid,
                    FirstName = firstName,
                    LastName = lastName,
                    JobTitle = jobTitle,
                    CompanyID = companyId,
                    About = about,
                    ShareType = shareType
                };

            DaoFactory.GetContactDao().UpdateContact(peopleInst);

            peopleInst = (Person)DaoFactory.GetContactDao().GetByID(peopleInst.ID);

            var managerListLocal = managerList != null ? managerList.ToList() : new List<Guid>();
            if (managerListLocal.Any())
            {
                CRMSecurity.SetAccessTo(peopleInst, managerListLocal);
            }

            if (customFieldList != null)
            {
                var existingCustomFieldList = DaoFactory.GetCustomFieldDao().GetFieldsDescription(EntityType.Person).Select(fd => fd.ID).ToList();
                foreach (var field in customFieldList)
                {
                    if (string.IsNullOrEmpty(field.Value) || !existingCustomFieldList.Contains(field.Key)) continue;
                    DaoFactory.GetCustomFieldDao().SetFieldValue(EntityType.Person, peopleInst.ID, field.Key, field.Value);
                }
            }

            var wrapper = (PersonWrapper)ToContactWrapper(peopleInst);

            var photoList = photo != null ? photo.ToList() : new List<HttpPostedFileBase>();
            if (photoList.Any())
            {
                wrapper.SmallFotoUrl = ChangeContactPhoto(peopleInst.ID, photoList);
            }

            MessageService.Send(Request, MessageAction.PersonUpdated, peopleInst.GetTitle());

            return wrapper;
        }
Exemplo n.º 21
0
        public PersonWrapper UpdatePerson(
                                          int personid,
                                          String firstName,
                                          String lastName,
                                          String jobTitle,
                                          int companyId,
                                          String about,
                                          bool isShared,
                                          IEnumerable<Guid> managerList,
                                          IEnumerable<ItemKeyValuePair<int, String>> customFieldList,
                                          HttpPostedFileBase photo)
        {

            if (personid == 0 || String.IsNullOrEmpty(firstName) || String.IsNullOrEmpty(lastName))
                throw new ArgumentException();

            var peopleInst = new Person
            {
                ID = personid,
                FirstName = firstName,
                LastName = lastName,
                JobTitle = jobTitle,
                CompanyID = companyId,
                About = about,
                IsShared = isShared
            };

            DaoFactory.GetContactDao().UpdateContact(peopleInst);

            peopleInst = (Person)DaoFactory.GetContactDao().GetByID(peopleInst.ID);

            var managerListLocal = managerList.ToList();
            if (managerListLocal.Count > 0)
                CRMSecurity.SetAccessTo(peopleInst, managerListLocal);

            foreach (var field in customFieldList)
                DaoFactory.GetCustomFieldDao().SetFieldValue(EntityType.Person, peopleInst.ID, field.Key, field.Value);

            var result = (PersonWrapper)ToContactWrapper(peopleInst);

            if (photo != null)
                result.SmallFotoUrl = ChangeContactPhoto(peopleInst.ID, photo);

            return result;
        }