Esempio n. 1
0
        public static string GetName(MessageTarget type)
        {
            string result = String.Empty;

            switch (type)
            {
                case MessageTarget.Qtip:
                    result = "qtip";
                    break;
                case MessageTarget.Title:
                    result = "title";
                    break;
                case MessageTarget.Under:
                    result = "under";
                    break;
                case MessageTarget.Side:
                    result = "side";
                    break;
                case MessageTarget.None:
                    result = "none";
                    break;
            }

            return result;
        }
Esempio n. 2
0
 public override void DrawGUI(IntelligenceState parentState, Intelligence intelligence, CallbackCollection callbacks)
 {
     #if UNITY_EDITOR
     target = (MessageTarget)EditorGUILayout.EnumPopup("Target:",target);
     type = (NotificationType)EditorGUILayout.EnumPopup("Type:", type);
     EditorGUILayout.BeginHorizontal();
     GUILayout.Label("Position var:", GUILayout.Width(74));
     positionVariableName = EditorGUILayout.TextField(positionVariableName);
     EditorGUILayout.EndHorizontal();
     radius = EditorGUILayout.FloatField("Radius:", radius);
     #endif
 }
        public object ChangeOwner(Guid ownerId)
        {
            try
            {
                SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings);

                var curTenant = CoreContext.TenantManager.GetCurrentTenant();
                var owner     = CoreContext.UserManager.GetUsers(curTenant.OwnerId);
                var newOwner  = CoreContext.UserManager.GetUsers(ownerId);

                if (newOwner.IsVisitor())
                {
                    throw new System.Security.SecurityException("Collaborator can not be an owner");
                }

                if (!owner.ID.Equals(SecurityContext.CurrentAccount.ID) || Guid.Empty.Equals(newOwner.ID))
                {
                    return(new { Status = 0, Message = Resource.ErrorAccessDenied });
                }

                var confirmLink = CommonLinkUtility.GetConfirmationUrl(owner.Email, ConfirmType.PortalOwnerChange, newOwner.ID, newOwner.ID);
                StudioNotifyService.Instance.SendMsgConfirmChangeOwner(owner, newOwner, confirmLink);

                MessageService.Send(HttpContext.Current.Request, MessageAction.OwnerSentChangeOwnerInstructions, MessageTarget.Create(owner.ID), owner.DisplayUserName(false));

                var emailLink = string.Format("<a href=\"mailto:{0}\">{0}</a>", owner.Email);
                return(new { Status = 1, Message = Resource.ChangePortalOwnerMsg.Replace(":email", emailLink) });
            }
            catch (Exception e)
            {
                return(new { Status = 0, Message = e.Message.HtmlEncode() });
            }
        }
Esempio n. 4
0
        public void RunJob()
        {
            Status = (int)Operation.Success;
            CoreContext.TenantManager.SetCurrentTenant((int)Id);
            SecurityContext.AuthenticateMe(UserId);

            if (!SecurityContext.CheckPermissions(Constants.Action_AddRemoveUser))
            {
                Error       = Resource.ErrorAccessDenied;
                IsCompleted = true;
                return;
            }

            try
            {
                var     jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                var     ruleObj      = jsSerializer.Deserialize <List <UserData> >(userList);
                var     error        = 0;
                Address address;
                GetUserCounter = ruleObj.Count;

                foreach (var userData in ruleObj)
                {
                    var isValidEmail = Parser.TryParseAddress(userData.Email, out address);

                    if (!isValidEmail || String.IsNullOrEmpty(userData.FirstName) || String.IsNullOrEmpty(userData.LastName))
                    {
                        Data.Add(new UserResults
                        {
                            Email  = userData.Email,
                            Result = Resource.ImportContactsIncorrectFields,
                            Class  = !isValidEmail ? "error3" : "error1"
                        });
                        error++;
                        Percentage++;
                        continue;
                    }

                    var us = CoreContext.UserManager.GetUserByEmail(userData.Email);

                    if (us.ID != Constants.LostUser.ID)
                    {
                        Data.Add(new UserResults
                        {
                            Email  = userData.Email,
                            Result = CustomNamingPeople.Substitute <Resource>("ImportContactsAlreadyExists"),
                            Class  = "error2"
                        });
                        error++;
                        Percentage++;
                        continue;
                    }

                    if (!importUsersAsCollaborators && TenantStatisticsProvider.GetUsersCount() >= TenantExtra.GetTenantQuota().ActiveUsers)
                    {
                        importUsersAsCollaborators = true;
                    }

                    var userInfo = new UserInfo
                    {
                        Email     = userData.Email,
                        FirstName = userData.FirstName,
                        LastName  = userData.LastName
                    };

                    UserManagerWrapper.AddUser(userInfo, UserManagerWrapper.GeneratePassword(), false, true, importUsersAsCollaborators);

                    var messageAction = importUsersAsCollaborators ? MessageAction.GuestImported : MessageAction.UserImported;
                    MessageService.Send(httpHeaders, messageAction, MessageTarget.Create(userInfo.ID), userInfo.DisplayUserName(false));

                    Data.Add(new UserResults {
                        Email = userData.Email, Result = String.Empty
                    });
                    Percentage++;
                }
            }
            catch (Exception ex)
            {
                Status = (int)Operation.Error;
                Error  = ex.Message;
            }

            IsCompleted = true;
        }
        public TaskWrapperFull UpdateProjectTask(
            int taskid,
            string description,
            ApiDateTime deadline,
            ApiDateTime startDate,
            TaskPriority?priority,
            string title,
            int milestoneid,
            IEnumerable <Guid> responsibles,
            int?projectID,
            bool notify,
            TaskStatus?status,
            int?progress)
        {
            var taskEngine = EngineFactory.TaskEngine;
            var task       = taskEngine.GetByID(taskid).NotFoundIfNull();

            if (string.IsNullOrEmpty(title))
            {
                throw new ArgumentException(@"title can't be empty", "title");
            }

            if (!EngineFactory.MilestoneEngine.IsExists(milestoneid) && milestoneid > 0)
            {
                throw new ItemNotFoundException("Milestone not found");
            }

            task.Responsibles = new List <Guid>(responsibles.Distinct());

            task.Deadline    = Update.IfNotEquals(task.Deadline, deadline);
            task.Description = Update.IfNotEquals(task.Description, description);

            if (priority.HasValue)
            {
                task.Priority = Update.IfNotEquals(task.Priority, priority.Value);
            }

            task.Title     = Update.IfNotEmptyAndNotEquals(task.Title, title);
            task.Milestone = Update.IfNotEquals(task.Milestone, milestoneid);
            task.StartDate = Update.IfNotEquals(task.StartDate, startDate);

            if (projectID.HasValue)
            {
                var project = EngineFactory.ProjectEngine.GetByID((int)projectID).NotFoundIfNull();
                task.Project = project;
            }

            if (progress.HasValue)
            {
                task.Progress = progress.Value;
            }

            taskEngine.SaveOrUpdate(task, null, notify);

            if (status.HasValue)
            {
                taskEngine.ChangeStatus(task, status.Value);
            }

            MessageService.Send(Request, MessageAction.TaskUpdated, MessageTarget.Create(task.ID), task.Project.Title, task.Title);

            return(GetTask(taskid));
        }
Esempio n. 6
0
        /// <summary>
        /// The primary output interface for formatted output.
        /// </summary>
        /// <param name="format">Format string for output.</param>
        /// <param name="actor">The actor (or TargetType, depending on format string).</param>
        /// <param name="arg1">Argument Target, use varies based on format string.</param>
        /// <param name="arg2">Argument Target, use varies based on format string</param>
        /// <param name="type">Target of Act statement.</param>
        /// <param name="capitalize">If capitalize is set, the first word of the phrase will be capitalized (after variable substitution).</param>
        public static void Act( string format, CharData actor, Target arg1, Target arg2, MessageTarget type, bool capitalize )
        {
            Object obj1 = (Object)arg1;
            Object obj2 = (Object)arg2;
            CharData victimChar = (CharData)arg2;
            string[] himHer = new[] { "it", "him", "her" };
            string[] hisHer = new[] { "its", "his", "her" };
            string str;
            // Discard null and zero-length messages.
            if( format.Length == 0 )
            {
                return;
            }

            if( actor == null )
            {
                Log.Error( "Act: null actor!", 0 );
                return;
            }

            // To prevent crashes
            if( !actor.InRoom )
            {
                Log.Error( "Act: Actor CharData (" + actor.Name + ") is not in a room!" );
                return;
            }

            List<CharData> to = actor.InRoom.People;
            if( type == MessageTarget.victim || type == MessageTarget.room_vict )
            {
                if( !victimChar )
                {
                    Log.Error( "Act: null victim with Descriptor.MessageTarget.victim.", 0 );
                    Log.Error(String.Format("Bad act string: {0}", format));
                    return;
                }
                to = victimChar.InRoom.People;
            }

            string outputBuffer;

            foreach (CharData roomChar in to)
            {
                if( !roomChar.Socket && roomChar.IsNPC() || !roomChar.IsAwake() )
                    continue;
                if( type == MessageTarget.room_vict && victimChar.FlightLevel != roomChar.FlightLevel )
                    continue;
                if( ( type == MessageTarget.room_vict || type == MessageTarget.room || type == MessageTarget.everyone_but_victim ) && actor.FlightLevel != roomChar.FlightLevel )
                    continue;
                if( type == MessageTarget.room_vict && ( roomChar == actor || roomChar == victimChar ) )
                    continue;
                if( type == MessageTarget.character && roomChar != actor )
                    continue;
                if( type == MessageTarget.victim && ( roomChar != victimChar || roomChar == actor ) )
                    continue;
                if( type == MessageTarget.room && roomChar == actor )
                    continue;
                if( type == MessageTarget.everyone_but_victim && ( roomChar == victimChar ) )
                    continue;
                if( type == MessageTarget.room_above && ( roomChar.FlightLevel <= actor.FlightLevel ) )
                    continue;
                if( type == MessageTarget.room_below && ( roomChar.FlightLevel >= actor.FlightLevel ) )
                    continue;

                str = format;

                if (str.Contains("$t"))
                    str = str.Replace("$t", (String)arg1);
                if (str.Contains("$T"))
                    str = str.Replace("$T", (String)arg2);
                if (str.Contains("$n") && actor != null)
                    str = str.Replace("$n", actor.ShowNameTo(roomChar, false));
                if (str.Contains("$N") && victimChar != null)
                    str = str.Replace("$N", victimChar.ShowNameTo(roomChar, false));
                if (str.Contains("$e") && actor != null)
                    str = str.Replace("$e", actor.GetSexPronoun());
                if (str.Contains("$E") && victimChar != null)
                    str = str.Replace("$E", victimChar.GetSexPronoun());
                if (str.Contains("$m") && actor != null)
                    str = str.Replace("$m", himHer[Macros.Range(0, (int)actor.Gender, 2)]);
                if (str.Contains("$M") && victimChar != null)
                    str = str.Replace("$M", himHer[Macros.Range(0, (int)victimChar.Gender, 2)]);
                if (str.Contains("$s") && actor != null)
                    str = str.Replace("$s", hisHer[Macros.Range(0, (int)actor.Gender, 2)]);
                if (str.Contains("$S") && victimChar != null)
                    str = str.Replace("$S", hisHer[Macros.Range(0, (int)victimChar.Gender, 2)]);
                if (str.Contains("$p") && obj1 != null)
                    str = str.Replace("$p", CharData.CanSeeObj(roomChar, obj1) ? obj1.ShortDescription : "something");
                if (str.Contains("$P") && obj1 != null)
                    str = str.Replace("$P", CharData.CanSeeObj(roomChar, obj2) ? obj2.ShortDescription : "something");
                if (str.Contains("$d"))
                {
                    if (((string)arg2).Length == 0)
                    {
                        str = str.Replace("$d", "door");
                    }
                    else
                    {
                        str = str.Replace("$d", (string)arg2);
                    }
                }

                str += "\r\n";

                ColorConvert( out outputBuffer, str, roomChar );

                if (capitalize)
                {
                    outputBuffer = MUDString.CapitalizeANSIString(outputBuffer);
                }

                if (roomChar.Socket)
                {
                    roomChar.Socket.WriteToBuffer(outputBuffer);
                }
            }
            return;
        }
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                using (var scope = DIHelper.Resolve())
                {
                    var daoFactory = scope.Resolve <DaoFactory>();
                    _context = context;

                    SecurityContext.CurrentAccount = ASC.Core.Configuration.Constants.CoreSystem;

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

                    var productInfo = WebItemSecurity.GetSecurityInfo(ProductEntryPoint.ID.ToString());
                    if (!productInfo.Enabled)
                    {
                        throw new Exception(CRMCommonResource.CRMProductIsDisabled);
                    }

                    Contact contact;

                    var fieldCollector = new NameValueCollection();

                    var addressTemplate = new JObject();
                    foreach (String addressPartName in Enum.GetNames(typeof(AddressPart)))
                    {
                        addressTemplate.Add(addressPartName.ToLower(), "");
                    }
                    var addressTemplateStr = addressTemplate.ToString();

                    var isCompany = false;

                    var isCompanyString = GetValue("is_company");
                    var firstName       = GetValue("firstName");
                    var lastName        = GetValue("lastName");
                    var companyName     = GetValue("companyName");

                    if (!String.IsNullOrEmpty(isCompanyString))
                    {
                        if (!Boolean.TryParse(isCompanyString, out isCompany))
                        {
                            throw new ArgumentException();
                        }
                    }
                    else //old scheme
                    {
                        if (!String.IsNullOrEmpty(firstName))
                        {
                            isCompany = false;
                        }
                        else if (!String.IsNullOrEmpty(companyName))
                        {
                            isCompany = true;
                        }
                        else
                        {
                            throw new ArgumentException();
                        }
                    }


                    if (isCompany)
                    {
                        contact = new Company();

                        ((Company)contact).CompanyName = companyName;

                        fieldCollector.Add(CRMContactResource.CompanyName, companyName);
                    }
                    else
                    {
                        contact = new Person();

                        ((Person)contact).FirstName = firstName;
                        ((Person)contact).LastName  = lastName;
                        ((Person)contact).JobTitle  = GetValue("jobTitle");

                        fieldCollector.Add(CRMContactResource.FirstName, firstName);
                        fieldCollector.Add(CRMContactResource.LastName, lastName);

                        if (!String.IsNullOrEmpty(GetValue("jobTitle")))
                        {
                            fieldCollector.Add(CRMContactResource.JobTitle, ((Person)contact).JobTitle);
                        }
                    }

                    contact.About = GetValue("about");

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

                    if (!String.IsNullOrEmpty(GetValue("is_shared")))
                    {
                        contact.ShareType = Convert.ToBoolean(GetValue("is_shared"))
                            ? ShareType.ReadWrite
                            : ShareType.None;
                    }
                    else
                    {
                        contact.ShareType = (ShareType)(Convert.ToInt32(GetValue("share_type")));
                    }

                    contact.ID = daoFactory.ContactDao.SaveContact(contact);

                    var messageAction = contact is Company
                        ? MessageAction.CompanyCreatedWithWebForm
                        : MessageAction.PersonCreatedWithWebForm;
                    MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, messageAction,
                                        MessageTarget.Create(contact.ID), contact.GetTitle());

                    var contactInfos = new List <ContactInfo>();

                    foreach (var key in _context.Request.Form.AllKeys)
                    {
                        if (key.StartsWith("customField_"))
                        {
                            var    fieldID    = Convert.ToInt32(key.Split(new[] { '_' })[1]);
                            String fieldValue = GetValue(key);

                            if (String.IsNullOrEmpty(fieldValue))
                            {
                                continue;
                            }

                            var customField = daoFactory.CustomFieldDao.GetFieldDescription(fieldID);

                            if (customField == null ||
                                !(customField.EntityType == EntityType.Contact ||
                                  customField.EntityType == EntityType.Company && isCompany ||
                                  customField.EntityType == EntityType.Person && !isCompany))
                            {
                                continue;
                            }

                            if (customField.FieldType == CustomFieldType.CheckBox)
                            {
                                fieldValue = fieldValue == "on" || fieldValue == "true" ? "true" : "false";
                            }
                            fieldCollector.Add(customField.Label, fieldValue);

                            daoFactory.CustomFieldDao.SetFieldValue(isCompany ? EntityType.Company : EntityType.Person, contact.ID, fieldID, fieldValue);
                        }
                        else if (key.StartsWith("contactInfo_"))
                        {
                            var nameParts       = key.Split(new[] { '_' }).Skip(1).ToList();
                            var contactInfoType = (ContactInfoType)Enum.Parse(typeof(ContactInfoType), nameParts[0]);
                            var category        = Convert.ToInt32(nameParts[1]);

                            bool categoryIsExists = Enum.GetValues(ContactInfo.GetCategory(contactInfoType))
                                                    .Cast <object>()
                                                    .Any(categoryEnum => (int)categoryEnum == category);
                            if (!categoryIsExists)
                            {
                                throw new ArgumentException(String.Format("Category for {0} not found", nameParts[0]));
                            }

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

                                var findedAddress =
                                    contactInfos.Find(
                                        item =>
                                        (category == item.Category) && (item.InfoType == ContactInfoType.Address));

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

                                    contactInfos.Add(findedAddress);
                                }

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

                                addressParts[addressPart.ToString().ToLower()] = GetValue(key);

                                findedAddress.Data = addressParts.ToString();

                                continue;
                            }

                            var fieldValue = GetValue(key);

                            if (String.IsNullOrEmpty(fieldValue))
                            {
                                continue;
                            }

                            contactInfos.Add(new ContactInfo
                            {
                                Category  = category,
                                InfoType  = contactInfoType,
                                Data      = fieldValue,
                                ContactID = contact.ID,
                                IsPrimary = true
                            });
                        }
                        else if (String.Compare(key, "tag", true) == 0)
                        {
                            var tags = _context.Request.Form.GetValues("tag");

                            daoFactory.TagDao.SetTagToEntity(EntityType.Contact, contact.ID, tags);
                        }
                    }

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

                    daoFactory.ContactInfoDao.SaveList(contactInfos, contact);

                    var notifyList = GetValue("notify_list");

                    if (!String.IsNullOrEmpty(notifyList))
                    {
                        NotifyClient.Instance.SendAboutCreateNewContact(
                            notifyList
                            .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                            .Select(item => new Guid(item)).ToList(), contact.ID, contact.GetTitle(), fieldCollector);
                    }

                    var managersList = GetValue("managers_list");
                    SetPermission(contact, managersList);

                    if (contact is Person && !String.IsNullOrEmpty(companyName))
                    {
                        AssignPersonToCompany((Person)contact, companyName, managersList, daoFactory);
                    }

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

                    SecurityContext.Logout();

                    var newURL = new UriBuilder(GetValue("return_url")).Uri.AbsoluteUri;
                    context.Response.Buffer = true;
                    context.Response.Status = "302 Object moved";
                    context.Response.AddHeader("Location", newURL);
                    context.Response.Write("<HTML><Head>");
                    context.Response.Write(String.Format("<META HTTP-EQUIV=Refresh CONTENT=\"0;URL={0}\">", newURL));
                    context.Response.Write(String.Format("<Script>window.location='{0}';</Script>", newURL));
                    context.Response.Write("</Head>");
                    context.Response.Write("</HTML>");
                }
            }
            catch (Exception error)
            {
                LogManager.GetLogger("ASC.CRM").Error(error);
                context.Response.StatusCode = 400;
                context.Response.Write(HttpUtility.HtmlEncode(error.Message));
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Sends a text message a specified target. The type of the target is determined by targetmode while target
        /// specifies the ID of the recipient, whether it be a virtual server, a channel or a client.
        /// </summary>
        /// <param name="target">The target of the message</param>
        /// <param name="targetId">The id of the target</param>
        /// <param name="message">The message</param>
        /// <returns></returns>
        public SimpleResponse SendTextMessage(MessageTarget target, uint targetId, string message)
        {
            if (message.IsNullOrTrimmedEmpty())
                throw new ArgumentException("message is null or trimmed empty", "message");

            Command command = CommandName.SendTextMessage.CreateCommand();
            command.AddParameter("targetmode", (uint) target);
            command.AddParameter("msg", message);
            command.AddParameter("target", targetId);

            return ResponseBase<SimpleResponse>.Parse(SendCommand(command));
        }
        public async System.Threading.Tasks.Task Invoke(HttpContext context,
                                                        SetupInfo setupInfo,
                                                        CrmSecurity crmSecurity,
                                                        FileSizeComment fileSizeComment,
                                                        WebItemSecurity webItemSecurity,
                                                        MessageTarget messageTarget,
                                                        MessageService messageService,
                                                        DaoFactory daoFactory,
                                                        ContactPhotoManager contactPhotoManager)
        {
            if (!webItemSecurity.IsAvailableForMe(ProductEntryPoint.ID))
            {
                throw crmSecurity.CreateSecurityException();
            }

            context.Request.EnableBuffering();

            var contactId = Convert.ToInt32(context.Request.Form["contactID"]);

            Contact contact = null;

            if (contactId != 0)
            {
                contact = daoFactory.GetContactDao().GetByID(contactId);

                if (!crmSecurity.CanEdit(contact))
                {
                    throw crmSecurity.CreateSecurityException();
                }
            }

            var fileUploadResult = new FileUploadResult();

            if (context.Request.Form.Files.Count == 0)
            {
                await context.Response.WriteAsync(JsonSerializer.Serialize(fileUploadResult));
            }

            var fileName      = context.Request.Form.Files[0].FileName;
            var contentLength = context.Request.Form.Files[0].Length;

            if (String.IsNullOrEmpty(fileName) || contentLength == 0)
            {
                throw new InvalidOperationException(CRMErrorsResource.InvalidFile);
            }

            if (0 < setupInfo.MaxImageUploadSize && setupInfo.MaxImageUploadSize < contentLength)
            {
                fileUploadResult.Success = false;
                fileUploadResult.Message = fileSizeComment.GetFileImageSizeNote(CRMCommonResource.ErrorMessage_UploadFileSize, false).HtmlEncode();

                await context.Response.WriteAsync(JsonSerializer.Serialize(fileUploadResult));
            }

            if (FileUtility.GetFileTypeByFileName(fileName) != FileType.Image)
            {
                fileUploadResult.Success = false;
                fileUploadResult.Message = CRMJSResource.ErrorMessage_NotImageSupportFormat.HtmlEncode();

                await context.Response.WriteAsync(JsonSerializer.Serialize(fileUploadResult));
            }

            var uploadOnly = Convert.ToBoolean(context.Request.Form["uploadOnly"]);
            var tmpDirName = Convert.ToString(context.Request.Form["tmpDirName"]);

            try
            {
                ContactPhotoManager.PhotoData photoData;
                if (contactId != 0)
                {
                    photoData = contactPhotoManager.UploadPhoto(context.Request.Form.Files[0].OpenReadStream(), contactId, uploadOnly);
                }
                else
                {
                    if (String.IsNullOrEmpty(tmpDirName) || tmpDirName == "null")
                    {
                        tmpDirName = Guid.NewGuid().ToString();
                    }
                    photoData = contactPhotoManager.UploadPhotoToTemp(context.Request.Form.Files[0].OpenReadStream(), tmpDirName);
                }

                fileUploadResult.Success = true;
                fileUploadResult.Data    = photoData;
            }
            catch (Exception e)
            {
                fileUploadResult.Success = false;
                fileUploadResult.Message = e.Message.HtmlEncode();

                await context.Response.WriteAsync(JsonSerializer.Serialize(fileUploadResult));
            }

            if (contact != null)
            {
                var messageAction = contact is Company ? MessageAction.CompanyUpdatedPhoto : MessageAction.PersonUpdatedPhoto;

                messageService.Send(messageAction, messageTarget.Create(contact.ID), contact.GetTitle());
            }

            await context.Response.WriteAsync(JsonSerializer.Serialize(fileUploadResult));
        }
Esempio n. 10
0
        public ContactStatusWrapper UpdateContactStatus(int id, string title, string description, string color, int sortOrder)
        {
            if (!(CRMSecurity.IsAdmin))
            {
                throw CRMSecurity.CreateSecurityException();
            }

            if (id <= 0 || string.IsNullOrEmpty(title))
            {
                throw new ArgumentException();
            }

            var curListItemExist = DaoFactory.ListItemDao.IsExist(id);

            if (!curListItemExist)
            {
                throw new ItemNotFoundException();
            }

            var listItem = new ListItem
            {
                ID          = id,
                Title       = title,
                Description = description,
                Color       = color,
                SortOrder   = sortOrder
            };

            DaoFactory.ListItemDao.EditItem(ListType.ContactStatus, listItem);
            MessageService.Send(Request, MessageAction.ContactTemperatureLevelUpdated, MessageTarget.Create(listItem.ID), listItem.Title);

            return(ToContactStatusWrapper(listItem));
        }
Esempio n. 11
0
        public ContactStatusWrapper UpdateContactStatusColor(int id, string color)
        {
            if (!(CRMSecurity.IsAdmin))
            {
                throw CRMSecurity.CreateSecurityException();
            }

            if (id <= 0)
            {
                throw new ArgumentException();
            }

            var contactStatus = DaoFactory.ListItemDao.GetByID(id);

            if (contactStatus == null)
            {
                throw new ItemNotFoundException();
            }

            contactStatus.Color = color;

            DaoFactory.ListItemDao.ChangeColor(id, color);
            MessageService.Send(Request, MessageAction.ContactTemperatureLevelUpdatedColor, MessageTarget.Create(contactStatus.ID), contactStatus.Title);

            return(ToContactStatusWrapper(contactStatus));
        }
Esempio n. 12
0
        public HistoryCategoryWrapper UpdateHistoryCategoryIcon(int id, string imageName)
        {
            if (!(CRMSecurity.IsAdmin))
            {
                throw CRMSecurity.CreateSecurityException();
            }

            if (id <= 0)
            {
                throw new ArgumentException();
            }

            var historyCategory = DaoFactory.ListItemDao.GetByID(id);

            if (historyCategory == null)
            {
                throw new ItemNotFoundException();
            }

            historyCategory.AdditionalParams = imageName;

            DaoFactory.ListItemDao.ChangePicture(id, imageName);
            MessageService.Send(Request, MessageAction.HistoryEventCategoryUpdatedIcon, MessageTarget.Create(historyCategory.ID), historyCategory.Title);

            return(ToHistoryCategoryWrapper(historyCategory));
        }
Esempio n. 13
0
        public ContactStatusWrapper CreateContactStatus(string title, string description, string color, int sortOrder)
        {
            if (!(CRMSecurity.IsAdmin))
            {
                throw CRMSecurity.CreateSecurityException();
            }

            var listItem = new ListItem
            {
                Title       = title,
                Description = description,
                Color       = color,
                SortOrder   = sortOrder
            };

            listItem.ID = DaoFactory.ListItemDao.CreateItem(ListType.ContactStatus, listItem);
            MessageService.Send(Request, MessageAction.ContactTemperatureLevelCreated, MessageTarget.Create(listItem.ID), listItem.Title);

            return(ToContactStatusWrapper(listItem));
        }
Esempio n. 14
0
        public IEnumerable <DealMilestoneWrapper> UpdateDealMilestonesOrder(IEnumerable <int> ids)
        {
            if (!(CRMSecurity.IsAdmin))
            {
                throw CRMSecurity.CreateSecurityException();
            }

            if (ids == null)
            {
                throw new ArgumentException();
            }

            var idsList = ids.ToList();

            var result = idsList.Select(id => DaoFactory.DealMilestoneDao.GetByID(id)).ToList();

            DaoFactory.DealMilestoneDao.Reorder(idsList.ToArray());
            MessageService.Send(Request, MessageAction.OpportunityStagesUpdatedOrder, MessageTarget.Create(idsList), result.Select(x => x.Title));

            return(result.Select(ToDealMilestoneWrapper));
        }
        public RelationshipEventWrapper AddHistoryTo(
            string entityType,
            int entityId,
            int contactId,
            string content,
            int categoryId,
            ApiDateTime created,
            IEnumerable <int> fileId,
            IEnumerable <Guid> notifyUserList)
        {
            if (!string.IsNullOrEmpty(entityType) &&
                !(
                    string.Compare(entityType, "opportunity", StringComparison.OrdinalIgnoreCase) == 0 ||
                    string.Compare(entityType, "case", StringComparison.OrdinalIgnoreCase) == 0)
                )
            {
                throw new ArgumentException();
            }

            var entityTypeObj = ToEntityType(entityType);

            var entityTitle = "";

            if (contactId > 0)
            {
                var contact = DaoFactory.ContactDao.GetByID(contactId);
                if (contact == null || !CRMSecurity.CanAccessTo(contact))
                {
                    throw new ArgumentException();
                }
                entityTitle = contact.GetTitle();
            }

            if (entityTypeObj == EntityType.Case)
            {
                var cases = DaoFactory.CasesDao.GetByID(entityId);
                if (cases == null || !CRMSecurity.CanAccessTo(cases))
                {
                    throw new ArgumentException();
                }
                if (contactId <= 0)
                {
                    entityTitle = cases.Title;
                }
            }
            if (entityTypeObj == EntityType.Opportunity)
            {
                var deal = DaoFactory.DealDao.GetByID(entityId);
                if (deal == null || !CRMSecurity.CanAccessTo(deal))
                {
                    throw new ArgumentException();
                }
                if (contactId <= 0)
                {
                    entityTitle = deal.Title;
                }
            }

            var relationshipEvent = new RelationshipEvent
            {
                CategoryID = categoryId,
                EntityType = entityTypeObj,
                EntityID   = entityId,
                Content    = content,
                ContactID  = contactId,
                CreateOn   = created,
                CreateBy   = Core.SecurityContext.CurrentAccount.ID
            };

            var category = DaoFactory.ListItemDao.GetByID(categoryId);

            if (category == null)
            {
                throw new ArgumentException();
            }

            var item = DaoFactory.RelationshipEventDao.CreateItem(relationshipEvent);


            notifyUserList = notifyUserList != null?notifyUserList.ToList() : new List <Guid>();

            var needNotify = notifyUserList.Any();

            var fileListInfoHashtable = new Hashtable();

            if (fileId != null)
            {
                var fileIds = fileId.ToList();
                var files   = FilesDaoFactory.GetFileDao().GetFiles(fileIds.Cast <object>().ToArray());

                if (needNotify)
                {
                    foreach (var file in files)
                    {
                        var extension = Path.GetExtension(file.Title);
                        if (extension == null)
                        {
                            continue;
                        }

                        var fileInfo = string.Format("{0} ({1})", file.Title, extension.ToUpper());
                        if (!fileListInfoHashtable.ContainsKey(fileInfo))
                        {
                            fileListInfoHashtable.Add(fileInfo, file.DownloadUrl);
                        }
                        else
                        {
                            fileInfo = string.Format("{0} ({1}, {2})", file.Title, extension.ToUpper(), file.UniqID);
                            fileListInfoHashtable.Add(fileInfo, file.DownloadUrl);
                        }
                    }
                }

                DaoFactory.RelationshipEventDao.AttachFiles(item.ID, fileIds.ToArray());

                if (files.Any())
                {
                    var fileAttachAction = GetFilesAttachAction(entityTypeObj, contactId);
                    MessageService.Send(Request, fileAttachAction, MessageTarget.Create(item.ID), entityTitle, files.Select(x => x.Title));
                }
            }

            if (needNotify)
            {
                NotifyClient.Instance.SendAboutAddRelationshipEventAdd(item, fileListInfoHashtable, DaoFactory, notifyUserList.ToArray());
            }

            var wrapper = ToRelationshipEventWrapper(item);

            var historyCreatedAction = GetHistoryCreatedAction(entityTypeObj, contactId);

            MessageService.Send(Request, historyCreatedAction, MessageTarget.Create(item.ID), entityTitle, category.Title);

            return(wrapper);
        }
Esempio n. 16
0
        private bool CheckValidationKey()
        {
            var key      = Request["key"] ?? "";
            var emplType = Request["emplType"] ?? "";
            var social   = Request["social"] ?? "";

            var validInterval = SetupInfo.ValidEmailKeyInterval;
            var authInterval  = SetupInfo.ValidAuthKeyInterval;

            EmailValidationKeyProvider.ValidationResult checkKeyResult;
            switch (_type)
            {
            case ConfirmType.PortalContinue:
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type, key);
                break;

            case ConfirmType.PhoneActivation:
            case ConfirmType.PhoneAuth:
            case ConfirmType.TfaActivation:
            case ConfirmType.TfaAuth:
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type, key, authInterval);
                break;

            case ConfirmType.Auth:
            {
                var first      = Request["first"] ?? "";
                var module     = Request["module"] ?? "";
                var smsConfirm = Request["sms"] ?? "";

                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type + first + module + smsConfirm, key, authInterval);

                if (checkKeyResult == EmailValidationKeyProvider.ValidationResult.Ok)
                {
                    var user = _email.Contains("@")
                                       ? CoreContext.UserManager.GetUserByEmail(_email)
                                       : CoreContext.UserManager.GetUsers(new Guid(_email));

                    if (SecurityContext.IsAuthenticated && SecurityContext.CurrentAccount.ID != user.ID)
                    {
                        Auth.ProcessLogout();
                    }

                    if (!SecurityContext.IsAuthenticated)
                    {
                        if (!CoreContext.UserManager.UserExists(user.ID) || user.Status != EmployeeStatus.Active)
                        {
                            ShowError(Auth.MessageKey.ErrorUserNotFound);
                            return(false);
                        }

                        if (StudioSmsNotificationSettings.IsVisibleAndAvailableSettings && StudioSmsNotificationSettings.Enable && smsConfirm.ToLower() != "true")
                        {
                            //todo: think about 'first' & 'module'
                            Response.Redirect(SmsConfirmUrl(user), true);
                        }

                        if (TfaAppAuthSettings.IsVisibleSettings && TfaAppAuthSettings.Enable)
                        {
                            //todo: think about 'first' & 'module'
                            Response.Redirect(TfaConfirmUrl(user), true);
                        }

                        var messageAction = social == "true" ? MessageAction.LoginSuccessViaSocialAccount : MessageAction.LoginSuccess;
                        CookiesManager.AuthenticateMeAndSetCookies(user.Tenant, user.ID, messageAction);
                    }

                    SetDefaultModule(module);

                    AuthRedirect(first.ToLower() == "true");
                }
            }
            break;

            case ConfirmType.DnsChange:
            {
                var dnsChangeKey = string.Join(string.Empty, new[] { _email, _type.ToString(), Request["dns"], Request["alias"] });
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(dnsChangeKey, key, validInterval);
            }
            break;

            case ConfirmType.PortalOwnerChange:
            {
                Guid uid;
                try
                {
                    uid = new Guid(Request["uid"]);
                }
                catch
                {
                    uid = Guid.Empty;
                }
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type + uid, key, validInterval);
            }
            break;

            case ConfirmType.EmpInvite:
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type + emplType, key, validInterval);
                break;

            case ConfirmType.LinkInvite:
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_type + emplType, key, validInterval);
                break;

            case ConfirmType.EmailChange:
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type + SecurityContext.CurrentAccount.ID, key, validInterval);
                break;

            case ConfirmType.PasswordChange:
                var userInfo      = CoreContext.UserManager.GetUserByEmail(_email);
                var auditEvent    = AuditEventsRepository.GetByFilter(action: MessageAction.UserSentPasswordChangeInstructions, entry: EntryType.User, target: MessageTarget.Create(userInfo.ID).ToString(), limit: 1).FirstOrDefault();
                var passwordStamp = CoreContext.Authentication.GetUserPasswordStamp(userInfo.ID);

                string hash;

                if (auditEvent != null)
                {
                    var auditEventDate = TenantUtil.DateTimeToUtc(auditEvent.Date);

                    hash = (auditEventDate.CompareTo(passwordStamp) > 0 ? auditEventDate : passwordStamp).ToString("s");
                }
                else
                {
                    hash = passwordStamp.ToString("s");
                }

                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type + hash, key, validInterval);

                break;

            default:
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type, key, validInterval);
                break;
            }

            if (checkKeyResult == EmailValidationKeyProvider.ValidationResult.Expired)
            {
                ShowError(Auth.MessageKey.ErrorExpiredActivationLink);
                return(false);
            }

            if (checkKeyResult == EmailValidationKeyProvider.ValidationResult.Invalid)
            {
                ShowError(_type == ConfirmType.LinkInvite
                              ? Auth.MessageKey.ErrorInvalidActivationLink
                              : Auth.MessageKey.ErrorConfirmURLError);
                return(false);
            }

            if (!string.IsNullOrEmpty(_email) && !_email.TestEmailRegex())
            {
                ShowError(Auth.MessageKey.ErrorNotCorrectEmail);
                return(false);
            }

            return(true);
        }
Esempio n. 17
0
 /// <summary>
 /// The location where the error message text should display.
 /// </summary>
 public virtual TBuilder MsgTarget(MessageTarget msgTarget)
 {
     this.ToComponent().MsgTarget = msgTarget;
     return(this as TBuilder);
 }
Esempio n. 18
0
        public IEnumerable <ContactStatusWrapper> UpdateContactStatusesOrder(IEnumerable <string> titles)
        {
            if (!(CRMSecurity.IsAdmin))
            {
                throw CRMSecurity.CreateSecurityException();
            }

            if (titles == null)
            {
                throw new ArgumentException();
            }

            var result = titles.Select(title => DaoFactory.ListItemDao.GetByTitle(ListType.ContactStatus, title)).ToList();

            DaoFactory.ListItemDao.ReorderItems(ListType.ContactStatus, titles.ToArray());
            MessageService.Send(Request, MessageAction.ContactTemperatureLevelsUpdatedOrder, MessageTarget.Create(result.Select(x => x.ID)), result.Select(x => x.Title));

            return(result.ConvertAll(ToContactStatusWrapper));
        }
        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, MessageTarget.Create(contact.ID), 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, MessageTarget.Create(contact.ID), 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

                #region Link with mail message

                int result;
                var linkMessageId = int.TryParse(Request["linkMessageId"], out result) ? result : 0;

                if (linkMessageId > 0)
                {
                    try
                    {
                        LinkWithMessage(linkMessageId, contact.ID);
                    }
                    catch (Exception ex)
                    {
                        log4net.LogManager.GetLogger("ASC.CRM").Error(ex);
                    }
                }

                #endregion

                Response.Redirect(String.Compare(e.CommandArgument.ToString(), "0", true) == 0
                                      ? String.Format("default.aspx?id={0}{1}", contact.ID,
                                                      contact is Company
                                                          ? ""
                                                          : String.Format("&{0}=people", UrlConstant.Type))
                                      : String.Format("default.aspx?action=manage{0}",
                                                      contact is Company
                                                          ? ""
                                                          : String.Format("&{0}=people", UrlConstant.Type)), false);
                Context.ApplicationInstance.CompleteRequest();
            }
            catch (Exception ex)
            {
                log4net.LogManager.GetLogger("ASC.CRM").Error(ex);
                var cookie = HttpContext.Current.Request.Cookies.Get(ErrorCookieKey);
                if (cookie == null)
                {
                    cookie = new HttpCookie(ErrorCookieKey)
                    {
                        Value = ex.Message
                    };
                    HttpContext.Current.Response.Cookies.Add(cookie);
                }
            }
        }
Esempio n. 20
0
        public ContactStatusWrapper DeleteContactStatus(int contactStatusid)
        {
            if (!(CRMSecurity.IsAdmin))
            {
                throw CRMSecurity.CreateSecurityException();
            }

            if (contactStatusid <= 0)
            {
                throw new ArgumentException();
            }

            var dao      = DaoFactory.ListItemDao;
            var listItem = dao.GetByID(contactStatusid);

            if (listItem == null)
            {
                throw new ItemNotFoundException();
            }

            if (dao.GetItemsCount(ListType.ContactStatus) < 2)
            {
                throw new ArgumentException("The last contact status cannot be deleted");
            }

            var contactStatus = ToContactStatusWrapper(listItem);

            dao.DeleteItem(ListType.ContactStatus, contactStatusid, 0);
            MessageService.Send(Request, MessageAction.ContactTemperatureLevelDeleted, MessageTarget.Create(contactStatus.ID), contactStatus.Title);

            return(contactStatus);
        }
Esempio n. 21
0
 public ChatMessage(MessageTarget target, int targetId, string content)
 {
     this.Target = target;
       this.TargetId = targetId;
       this.Content = content;
 }
        private static void SendHeadersMessage(Dictionary <string, string> headers, MessageAction action, MessageTarget target, params string[] description)
        {
            if (headers == null)
            {
                log.Debug(string.Format("Empty Request Headers for \"{0}\" type of event", action));
                return;
            }

            MessageService.Send(headers, action, target, description);
        }
Esempio n. 23
0
 /// <summary>
 /// Forwards to Act with default argument of false. We don't use a default argument version that
 /// takes 5 or 6 parameters because the spell compiler doesn't like default arguments.
 /// </summary>
 /// <param name="format"></param>
 /// <param name="ch"></param>
 /// <param name="arg1"></param>
 /// <param name="arg2"></param>
 /// <param name="type"></param>
 public static void Act(string format, CharData ch, Target arg1, Target arg2, MessageTarget type)
 {
     Act(format, ch, arg1, arg2, type, false);
 }
        public FileUploadResult ProcessUpload(HttpContext context)
        {
            if (!WebItemSecurity.IsAvailableForMe(ProductEntryPoint.ID))
            {
                throw CRMSecurity.CreateSecurityException();
            }

            var     contactId = Convert.ToInt32(context.Request["contactID"]);
            Contact contact   = null;

            if (contactId != 0)
            {
                using (var scope = DIHelper.Resolve())
                {
                    contact = scope.Resolve <DaoFactory>().ContactDao.GetByID(contactId);
                    if (!CRMSecurity.CanEdit(contact))
                    {
                        throw CRMSecurity.CreateSecurityException();
                    }
                }
            }

            var fileUploadResult = new FileUploadResult();

            if (!FileToUpload.HasFilesToUpload(context))
            {
                return(fileUploadResult);
            }

            var file = new FileToUpload(context);

            if (String.IsNullOrEmpty(file.FileName) || file.ContentLength == 0)
            {
                throw new InvalidOperationException(CRMErrorsResource.InvalidFile);
            }

            if (0 < SetupInfo.MaxImageUploadSize && SetupInfo.MaxImageUploadSize < file.ContentLength)
            {
                fileUploadResult.Success = false;
                fileUploadResult.Message = FileSizeComment.GetFileImageSizeNote(CRMCommonResource.ErrorMessage_UploadFileSize, false).HtmlEncode();
                return(fileUploadResult);
            }

            if (FileUtility.GetFileTypeByFileName(file.FileName) != FileType.Image)
            {
                fileUploadResult.Success = false;
                fileUploadResult.Message = CRMJSResource.ErrorMessage_NotImageSupportFormat.HtmlEncode();
                return(fileUploadResult);
            }

            var uploadOnly = Convert.ToBoolean(context.Request["uploadOnly"]);
            var tmpDirName = Convert.ToString(context.Request["tmpDirName"]);

            try
            {
                ContactPhotoManager.PhotoData photoData;
                if (contactId != 0)
                {
                    photoData = ContactPhotoManager.UploadPhoto(file.InputStream, contactId, uploadOnly);
                }
                else
                {
                    if (String.IsNullOrEmpty(tmpDirName) || tmpDirName == "null")
                    {
                        tmpDirName = Guid.NewGuid().ToString();
                    }
                    photoData = ContactPhotoManager.UploadPhotoToTemp(file.InputStream, tmpDirName);
                }

                fileUploadResult.Success = true;
                fileUploadResult.Data    = photoData;
            }
            catch (Exception e)
            {
                fileUploadResult.Success = false;
                fileUploadResult.Message = e.Message.HtmlEncode();
                return(fileUploadResult);
            }

            if (contact != null)
            {
                var messageAction = contact is Company ? MessageAction.CompanyUpdatedPhoto : MessageAction.PersonUpdatedPhoto;
                MessageService.Send(context.Request, messageAction, MessageTarget.Create(contact.ID), contact.GetTitle());
            }

            return(fileUploadResult);
        }
        protected void SaveOrUpdateDeal(Object sender, CommandEventArgs e)
        {
            try
            {
                var dao = Global.DaoFactory;
                int dealID;

                var _isPrivate = false;
                var _selectedUsersWithoutCurUsr = new List <Guid>();

                #region BaseInfo

                var deal = new Deal
                {
                    Title           = Request["nameDeal"],
                    Description     = Request["descriptionDeal"],
                    DealMilestoneID = Convert.ToInt32(Request["dealMilestone"])
                };

                int contactID;
                if (int.TryParse(Request["selectedContactID"], out contactID))
                {
                    deal.ContactID = contactID;
                }

                int probability;
                if (int.TryParse(Request["probability"], out probability))
                {
                    deal.DealMilestoneProbability = probability;
                }

                if (deal.DealMilestoneProbability < 0)
                {
                    deal.DealMilestoneProbability = 0;
                }
                if (deal.DealMilestoneProbability > 100)
                {
                    deal.DealMilestoneProbability = 100;
                }

                deal.BidCurrency = Request["bidCurrency"];

                if (String.IsNullOrEmpty(deal.BidCurrency))
                {
                    deal.BidCurrency = Global.TenantSettings.DefaultCurrency.Abbreviation;
                }
                else
                {
                    deal.BidCurrency = deal.BidCurrency.ToUpper();
                }

                if (!String.IsNullOrEmpty(Request["bidValue"]))
                {
                    decimal bidValue;
                    if (!decimal.TryParse(Request["bidValue"], out bidValue))
                    {
                        bidValue = 0;
                    }

                    deal.BidValue = bidValue;
                    deal.BidType  = (BidType)Enum.Parse(typeof(BidType), Request["bidType"]);

                    if (deal.BidType != BidType.FixedBid)
                    {
                        int perPeriodValue;

                        if (int.TryParse(Request["perPeriodValue"], out perPeriodValue))
                        {
                            deal.PerPeriodValue = perPeriodValue;
                        }
                    }
                }
                else
                {
                    deal.BidValue = 0;
                    deal.BidType  = BidType.FixedBid;
                }

                DateTime expectedCloseDate;

                if (!DateTime.TryParse(Request["expectedCloseDate"], out expectedCloseDate))
                {
                    expectedCloseDate = DateTime.MinValue;
                }
                deal.ExpectedCloseDate = expectedCloseDate;

                deal.ResponsibleID = new Guid(Request["responsibleID"]);

                #endregion

                #region Validation

                CRMSecurity.DemandCreateOrUpdate(deal);

                if (HavePermission)
                {
                    var CurrentAccountID = SecurityContext.CurrentAccount.ID;

                    bool value;
                    if (bool.TryParse(Request.Form["isPrivateDeal"], out value))
                    {
                        _isPrivate = value;
                    }

                    if (_isPrivate)
                    {
                        _selectedUsersWithoutCurUsr = Request.Form["selectedPrivateUsers"]
                                                      .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                                      .Select(item => new Guid(item)).Where(i => i != CurrentAccountID).Distinct().ToList();

                        foreach (var uID in _selectedUsersWithoutCurUsr)
                        {
                            var usr = CoreContext.UserManager.GetUsers(uID);
                            if (usr.IsVisitor())
                            {
                                throw new ArgumentException();
                            }
                        }

                        if (deal.ResponsibleID != CurrentAccountID)
                        {
                            _selectedUsersWithoutCurUsr.Add(deal.ResponsibleID);

                            var responsible = CoreContext.UserManager.GetUsers(deal.ResponsibleID);
                            if (responsible.IsVisitor())
                            {
                                throw new ArgumentException(CRMErrorsResource.ResponsibleCannotBeVisitor);
                            }
                        }
                    }
                }


                #endregion

                var dealMilestone = dao.GetDealMilestoneDao().GetByID(deal.DealMilestoneID);
                if (TargetDeal == null)
                {
                    if (dealMilestone.Status != DealMilestoneStatus.Open)
                    {
                        deal.ActualCloseDate = TenantUtil.DateTimeNow();
                    }

                    dealID        = dao.GetDealDao().CreateNewDeal(deal);
                    deal.ID       = dealID;
                    deal.CreateBy = SecurityContext.CurrentAccount.ID;
                    deal.CreateOn = TenantUtil.DateTimeNow();
                    deal          = dao.GetDealDao().GetByID(dealID);

                    SetPermission(deal, _isPrivate, _selectedUsersWithoutCurUsr);

                    if (deal.ResponsibleID != Guid.Empty && deal.ResponsibleID != SecurityContext.CurrentAccount.ID)
                    {
                        NotifyClient.Instance.SendAboutResponsibleForOpportunity(deal);
                    }
                    MessageService.Send(HttpContext.Current.Request, MessageAction.OpportunityCreated, MessageTarget.Create(deal.ID), deal.Title);
                }
                else
                {
                    dealID  = TargetDeal.ID;
                    deal.ID = TargetDeal.ID;
                    deal.ActualCloseDate = TargetDeal.ActualCloseDate;

                    if (TargetDeal.ResponsibleID != Guid.Empty && TargetDeal.ResponsibleID != deal.ResponsibleID)
                    {
                        NotifyClient.Instance.SendAboutResponsibleForOpportunity(deal);
                    }


                    if (TargetDeal.DealMilestoneID != deal.DealMilestoneID)
                    {
                        deal.ActualCloseDate = dealMilestone.Status != DealMilestoneStatus.Open ? TenantUtil.DateTimeNow() : DateTime.MinValue;
                    }

                    dao.GetDealDao().EditDeal(deal);
                    deal = dao.GetDealDao().GetByID(dealID);
                    SetPermission(deal, _isPrivate, _selectedUsersWithoutCurUsr);
                    MessageService.Send(HttpContext.Current.Request, MessageAction.OpportunityUpdated, MessageTarget.Create(deal.ID), deal.Title);
                }

                #region Members

                var dealMembers = !String.IsNullOrEmpty(Request["selectedMembersID"])
                                      ? Request["selectedMembersID"].Split(new[] { ',' }).Select(
                    id => Convert.ToInt32(id)).Where(id => id != deal.ContactID).ToList()
                                      : new List <int>();

                var dealMembersContacts = dao.GetContactDao().GetContacts(dealMembers.ToArray()).Where(CRMSecurity.CanAccessTo).ToList();
                dealMembers = dealMembersContacts.Select(m => m.ID).ToList();

                if (deal.ContactID > 0)
                {
                    dealMembers.Add(deal.ContactID);
                }

                dao.GetDealDao().SetMembers(dealID, dealMembers.ToArray());

                #endregion

                #region CustomFields

                foreach (var customField in Request.Form.AllKeys)
                {
                    if (!customField.StartsWith("customField_"))
                    {
                        continue;
                    }

                    var fieldID = Convert.ToInt32(customField.Split('_')[1]);

                    var fieldValue = Request.Form[customField];

                    if (String.IsNullOrEmpty(fieldValue) && TargetDeal == null)
                    {
                        continue;
                    }

                    dao.GetCustomFieldDao().SetFieldValue(EntityType.Opportunity, dealID, fieldID, fieldValue);
                }

                #endregion

                string redirectUrl;
                if (TargetDeal == null && UrlParameters.ContactID != 0)
                {
                    redirectUrl = string.Format(e.CommandArgument.ToString() == "1" ? "deals.aspx?action=manage&contactID={0}" : "default.aspx?id={0}#deals", UrlParameters.ContactID);
                }
                else
                {
                    redirectUrl = e.CommandArgument.ToString() == "1" ? "deals.aspx?action=manage" : string.Format("deals.aspx?id={0}", dealID);
                }

                Response.Redirect(redirectUrl, false);
                Context.ApplicationInstance.CompleteRequest();
            }
            catch (Exception ex)
            {
                log4net.LogManager.GetLogger("ASC.CRM").Error(ex);
                var cookie = HttpContext.Current.Request.Cookies.Get(ErrorCookieKey);
                if (cookie == null)
                {
                    cookie = new HttpCookie(ErrorCookieKey)
                    {
                        Value = ex.Message
                    };
                    HttpContext.Current.Response.Cookies.Add(cookie);
                }
            }
        }
        public object SendDeactivateInstructions()
        {
            SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings);

            var tenant = CoreContext.TenantManager.GetCurrentTenant();
            var owner  = CoreContext.UserManager.GetUsers(tenant.OwnerId);

            var suspendUrl  = CommonLinkUtility.GetConfirmationUrl(owner.Email, ConfirmType.PortalSuspend);
            var continueUrl = CommonLinkUtility.GetConfirmationUrl(owner.Email, ConfirmType.PortalContinue);

            StudioNotifyService.Instance.SendMsgPortalDeactivation(tenant, suspendUrl, continueUrl);

            MessageService.Send(HttpContext.Current.Request, MessageAction.OwnerSentPortalDeactivationInstructions, MessageTarget.Create(owner.ID), owner.DisplayUserName(false));

            var emailLink = string.Format("<a href=\"mailto:{0}\">{0}</a>", owner.Email.HtmlEncode());

            return(Resource.AccountDeactivationMsg.Replace(":email", emailLink));
        }
Esempio n. 27
0
 public BotSession GetSession(MessageTarget target, ushort invokerId)
 {
     if (target == MessageTarget.Server)
         return DefaultSession;
     return openSessions.FirstOrDefault((bs) => bs.Client.ClientId == invokerId) ?? DefaultSession;
 }
        public string SendDeleteInstructions()
        {
            SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings);

            var tenant = CoreContext.TenantManager.GetCurrentTenant();
            var owner  = CoreContext.UserManager.GetUsers(tenant.OwnerId);

            var showAutoRenewText = !CoreContext.Configuration.Standalone &&
                                    CoreContext.PaymentManager.GetTariffPayments(TenantProvider.CurrentTenantID).Any() &&
                                    !TenantExtra.GetTenantQuota().Trial;

            StudioNotifyService.Instance.SendMsgPortalDeletion(tenant, CommonLinkUtility.GetConfirmationUrl(owner.Email, ConfirmType.PortalRemove), showAutoRenewText);

            MessageService.Send(HttpContext.Current.Request, MessageAction.OwnerSentPortalDeleteInstructions, MessageTarget.Create(owner.ID), owner.DisplayUserName(false));

            var emailLink = string.Format("<a href=\"mailto:{0}\">{0}</a>", owner.Email.HtmlEncode());

            return(Resource.AccountDeletionMsg.Replace(":email", emailLink));
        }
        public TaskWrapper CopyTask(int projectid, string description, ApiDateTime deadline,
                                    TaskPriority priority, string title, int milestoneid,
                                    IEnumerable <Guid> responsibles, bool notify, ApiDateTime startDate,
                                    int copyFrom, bool copySubtasks, bool copyFiles, bool removeOld)
        {
            if (string.IsNullOrEmpty(title))
            {
                throw new ArgumentException(@"title can't be empty", "title");
            }

            var projectEngine = EngineFactory.ProjectEngine;
            var taskEngine    = EngineFactory.TaskEngine;

            var copyFromTask = taskEngine.GetByID(copyFrom).NotFoundIfNull();
            var project      = projectEngine.GetByID(projectid).NotFoundIfNull();

            if (!EngineFactory.MilestoneEngine.IsExists(milestoneid) && milestoneid > 0)
            {
                throw new ItemNotFoundException("Milestone not found");
            }

            var team    = projectEngine.GetTeam(project.ID);
            var teamIds = team.Select(r => r.ID).ToList();

            if (responsibles.Any(responsible => !teamIds.Contains(responsible)))
            {
                throw new ArgumentException(@"responsibles", "responsibles");
            }

            var task = new Task
            {
                CreateBy     = CurrentUserId,
                CreateOn     = TenantUtil.DateTimeNow(),
                Deadline     = deadline,
                Description  = description ?? "",
                Priority     = priority,
                Status       = TaskStatus.Open,
                Title        = title,
                Project      = project,
                Milestone    = milestoneid,
                Responsibles = new List <Guid>(responsibles.Distinct()),
                StartDate    = startDate
            };

            taskEngine.SaveOrUpdate(task, null, notify);

            if (copySubtasks)
            {
                taskEngine.CopySubtasks(copyFromTask, task, team);
            }

            if (copyFiles)
            {
                taskEngine.CopyFiles(copyFromTask, task);
            }

            if (removeOld)
            {
                taskEngine.Delete(copyFromTask);
            }

            MessageService.Send(Request, MessageAction.TaskCreated, MessageTarget.Create(task.ID), project.Title, task.Title);

            return(GetTask(task));
        }
Esempio n. 30
0
        private OpportunityWrapper SetAccessToDeal(Deal deal, bool isPrivate, IEnumerable <Guid> accessList, bool isNotify, bool isMessageServicSende)
        {
            var accessListLocal = accessList != null?accessList.Distinct().ToList() : new List <Guid>();

            if (isPrivate && accessListLocal.Count > 0)
            {
                if (isNotify)
                {
                    accessListLocal = accessListLocal.Where(u => u != SecurityContext.CurrentAccount.ID).ToList();
                    ASC.Web.CRM.Services.NotifyService.NotifyClient.Instance.SendAboutSetAccess(EntityType.Opportunity, deal.ID, DaoFactory, accessListLocal.ToArray());
                }

                if (!accessListLocal.Contains(SecurityContext.CurrentAccount.ID))
                {
                    accessListLocal.Add(SecurityContext.CurrentAccount.ID);
                }

                CRMSecurity.SetAccessTo(deal, accessListLocal);

                if (isMessageServicSende)
                {
                    var users = GetUsersByIdList(accessListLocal);
                    MessageService.Send(Request, MessageAction.OpportunityRestrictedAccess, MessageTarget.Create(deal.ID), deal.Title, users.Select(x => x.DisplayUserName(false)));
                }
            }
            else
            {
                CRMSecurity.MakePublic(deal);
                if (isMessageServicSende)
                {
                    MessageService.Send(Request, MessageAction.OpportunityOpenedAccess, MessageTarget.Create(deal.ID), deal.Title);
                }
            }

            return(ToOpportunityWrapper(deal));
        }
        protected void SaveOrUpdateInvoice(Object sender, CommandEventArgs e)
        {
            try
            {
                using (var scope = DIHelper.Resolve())
                {
                    var dao = scope.Resolve <DaoFactory>();

                    var invoice = GetInvoice(dao);

                    var billingAddressID  = Convert.ToInt32(Request["billingAddressID"]);
                    var deliveryAddressID = Convert.ToInt32(Request["deliveryAddressID"]);

                    var messageAction = MessageAction.InvoiceCreated;

                    if (invoice.ID > 0)
                    {
                        messageAction = MessageAction.InvoiceUpdated;
                        RemoveInvoiceFile(invoice.FileID, dao);
                    }

                    invoice.ID = dao.InvoiceDao.SaveOrUpdateInvoice(invoice);
                    MessageService.Send(HttpContext.Current.Request, messageAction, MessageTarget.Create(invoice.ID),
                                        invoice.Number);

                    var invoiceLines = GetInvoiceLines(dao);

                    foreach (var line in invoiceLines)
                    {
                        line.InvoiceID = invoice.ID;
                        line.ID        = dao.InvoiceLineDao.SaveOrUpdateInvoiceLine(line);
                    }

                    RemoveUnusedLines(invoice.ID, invoiceLines, dao);

                    dao.InvoiceDao.UpdateInvoiceJsonData(invoice, billingAddressID, deliveryAddressID);

                    if (Global.CanDownloadInvoices)
                    {
                        PdfQueueWorker.StartTask(HttpContext.Current, TenantProvider.CurrentTenantID, SecurityContext.CurrentAccount.ID, invoice.ID);
                    }

                    string redirectUrl;
                    if (ActionType == InvoiceActionType.Create && UrlParameters.ContactID != 0)
                    {
                        redirectUrl =
                            string.Format(
                                e.CommandArgument.ToString() == "1"
                                    ? "invoices.aspx?action=create&contactID={0}"
                                    : "default.aspx?id={0}#invoices", UrlParameters.ContactID);
                    }
                    else
                    {
                        redirectUrl = e.CommandArgument.ToString() == "1"
                            ? "invoices.aspx?action=create"
                            : string.Format("invoices.aspx?id={0}", invoice.ID);
                    }

                    Response.Redirect(redirectUrl, false);
                    Context.ApplicationInstance.CompleteRequest();
                }
            }
            catch (Exception ex)
            {
                if (!(ex is InvoiceValidationException))
                {
                    LogManager.GetLogger("ASC.CRM").Error(ex);
                }

                var cookie = HttpContext.Current.Request.Cookies.Get(ErrorCookieKey);
                if (cookie == null)
                {
                    cookie = new HttpCookie(ErrorCookieKey)
                    {
                        Value = ex.Message
                    };
                    HttpContext.Current.Response.Cookies.Add(cookie);
                }
            }
        }
Esempio n. 32
0
        private void SendSuccessNotify(UserManager userManager, StudioNotifyService studioNotifyService, MessageService messageService, MessageTarget messageTarget, DisplayUserSettingsHelper displayUserSettingsHelper)
        {
            var fromUser = userManager.GetUsers(FromUser);
            var toUser   = userManager.GetUsers(ToUser);

            studioNotifyService.SendMsgReassignsCompleted(_currentUserId, fromUser, toUser);

            var fromUserName = fromUser.DisplayUserName(false, displayUserSettingsHelper);
            var toUserName   = toUser.DisplayUserName(false, displayUserSettingsHelper);

            if (_httpHeaders != null)
            {
                messageService.Send(_httpHeaders, MessageAction.UserDataReassigns, messageTarget.Create(FromUser), new[] { fromUserName, toUserName });
            }
            else
            {
                messageService.Send(MessageAction.UserDataReassigns, messageTarget.Create(FromUser), fromUserName, toUserName);
            }
        }
        public object AddAdmin(Guid id)
        {
            var isRetina = TenantLogoManager.IsRetina(HttpContext.Current.Request);

            SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings);

            var user = CoreContext.UserManager.GetUsers(id);

            if (user.IsVisitor())
            {
                throw new System.Security.SecurityException("Collaborator can not be an administrator");
            }

            WebItemSecurity.SetProductAdministrator(Guid.Empty, id, true);

            MessageService.Send(HttpContext.Current.Request, MessageAction.AdministratorAdded, MessageTarget.Create(user.ID), user.DisplayUserName(false));

            InitLdapRights();

            return(new
            {
                id = user.ID,
                smallFotoUrl = user.GetSmallPhotoURL(),
                bigFotoUrl = isRetina ? user.GetBigPhotoURL() : "",
                displayName = user.DisplayUserName(),
                title = user.Title.HtmlEncode(),
                userUrl = CommonLinkUtility.GetUserProfile(user.ID),
                accessList = GetAccessList(user.ID, true)
            });
        }
Esempio n. 34
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.ContactDao.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.ContactInfoDao.Save(contactInfo);

            var messageAction = contact is Company ? MessageAction.CompanyUpdatedPrincipalInfo : MessageAction.PersonUpdatedPrincipalInfo;

            MessageService.Send(Request, messageAction, MessageTarget.Create(contact.ID), contact.GetTitle());

            var contactInfoWrapper = ToContactInfoWrapper(contactInfo);

            contactInfoWrapper.ID = contactInfoID;
            return(contactInfoWrapper);
        }
Esempio n. 35
0
        private void SendSuccessNotify()
        {
            var fromUser = CoreContext.UserManager.GetUsers(_fromUserId);
            var toUser   = CoreContext.UserManager.GetUsers(_toUserId);

            StudioNotifyService.Instance.SendMsgReassignsCompleted(_currentUserId, fromUser, toUser);

            var fromUserName = fromUser.DisplayUserName(false);
            var toUserName   = toUser.DisplayUserName(false);

            if (_httpHeaders != null)
            {
                MessageService.Send(_httpHeaders, MessageAction.UserDataReassigns, MessageTarget.Create(_fromUserId),
                                    new[] { fromUserName, toUserName });
            }
            else
            {
                MessageService.Send(_context.Request, MessageAction.UserDataReassigns, MessageTarget.Create(_fromUserId),
                                    fromUserName, toUserName);
            }
        }
Esempio n. 36
0
File: Host.cs Progetto: sunoru/PBO
 void IRoomManager.Chat(int userId, MessageTarget target, int targetId, string content)
 {
 }
Esempio n. 37
0
        private void DeleteUserProfile(UserManager userManager, UserPhotoManager userPhotoManager, MessageService messageService, MessageTarget messageTarget, DisplayUserSettingsHelper displayUserSettingsHelper)
        {
            var user     = userManager.GetUsers(FromUser);
            var userName = user.DisplayUserName(false, displayUserSettingsHelper);

            userPhotoManager.RemovePhoto(user.ID);
            userManager.DeleteUser(user.ID);
            QueueWorkerRemove.Start(_tenantId, user, _currentUserId, false);

            if (_httpHeaders != null)
            {
                messageService.Send(_httpHeaders, MessageAction.UserDeleted, messageTarget.Create(FromUser), new[] { userName });
            }
            else
            {
                messageService.Send(MessageAction.UserDeleted, messageTarget.Create(FromUser), userName);
            }
        }
Esempio n. 38
0
 public ChatCommand(string content, MessageTarget target, int targetId)
 {
     Content = content;
       Target = target;
       TargetId = targetId;
 }
Esempio n. 39
0
File: Host.cs Progetto: sunoru/PBO
 void InformChat(int userId, MessageTarget target, string content)
 {
 }
Esempio n. 40
0
 public ChatInfo(int userId, MessageTarget target, string content)
 {
     this.UserId = userId;
       this.Target = target;
       this.Content = content;
 }
Esempio n. 41
0
        protected void ExecInvoicePdfView(ASC.CRM.Core.Entities.Invoice targetInvoice)
        {
            var pdfFile = Global.GetInvoicePdfExistingOrCreate(targetInvoice, DaoFactory);

            MessageService.Send(HttpContext.Current.Request, MessageAction.InvoiceDownloaded, MessageTarget.Create(targetInvoice.ID), targetInvoice.Number);

            Response.Redirect(CommonLinkUtility.GetFullAbsolutePath(pdfFile.DownloadUrl));
        }
Esempio n. 42
0
File: User.cs Progetto: sunoru/PBO
 public void Chat(string content, MessageTarget target = MessageTarget.All, int targetId = 0)
 {
   sendCommand(new ChatCommand(content, target, targetId));
 }