예제 #1
0
 /// <summary>
 /// This method will store external requests information in Azure Table Storage
 /// </summary>
 /// <param name="externalSharingRequest"></param>
 /// <returns></returns>
 private void SaveExternalSharingRequest(MatterInformationVM matterInformation)
 {
     try
     {
         CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(generalSettings.CloudStorageConnectionString);
         CloudTableClient    tableClient         = cloudStorageAccount.CreateCloudTableClient();
         tableClient.DefaultRequestOptions = new TableRequestOptions
         {
             PayloadFormat = TablePayloadFormat.JsonNoMetadata
         };
         // Retrieve a reference to the table.
         CloudTable table = tableClient.GetTableReference(logTables.ExternalAccessRequests);
         // Create the table if it doesn't exist.
         table.CreateIfNotExists();
         //Insert the entity into Table Storage
         matterInformation.PartitionKey = matterInformation.Matter.Name;
         matterInformation.RowKey       = $"{Guid.NewGuid().ToString()}${matterInformation.Matter.Id}";
         matterInformation.Status       = "Pending";
         string matterInformationObject = Newtonsoft.Json.JsonConvert.SerializeObject(matterInformation);
         matterInformation.SerializeMatter = matterInformationObject;
         TableOperation insertOperation = TableOperation.Insert(matterInformation);
         table.Execute(insertOperation);
     }
     catch (Exception ex)
     {
         throw;
     }
 }
예제 #2
0
 /// <summary>
 /// Update the status in Azure Table Storage for the corresponding Parition and Row Key
 /// for which the user has accepted the invitation
 /// </summary>
 /// <param name="externalSharingRequest"></param>
 public static void UpdateTableStorageEntity(MatterInformationVM matterInformation, TextWriter log, string connection, string tableName, string status)
 {
     try
     {
         CloudStorageAccount cloudStorageAccount =
             CloudStorageAccount.Parse(connection);
         CloudTableClient tableClient = cloudStorageAccount.CreateCloudTableClient();
         // Create the CloudTable object that represents the "people" table.
         CloudTable table = tableClient.GetTableReference(tableName);
         // Create a retrieve operation that takes a entity.
         TableOperation retrieveOperation =
             TableOperation.Retrieve <MatterInformationVM>(matterInformation.PartitionKey, matterInformation.RowKey);
         // Execute the operation.
         TableResult retrievedResult = table.Execute(retrieveOperation);
         // Assign the result to a ExternalSharingRequest object.
         MatterInformationVM updateEntity = (MatterInformationVM)retrievedResult.Result;
         if (updateEntity != null)
         {
             updateEntity.Status = status;
             TableOperation updateOperation = TableOperation.Replace(updateEntity);
             table.Execute(updateOperation);
             log.WriteLine($"Updated the matter status to Accepted in Azure Table Storage");
         }
     }
     catch (Exception ex)
     {
         log.WriteLine($"Exception occured in the method UpdateTableStorageEntity. {ex}");
     }
 }
예제 #3
0
        public async void Check_Security_Group_Exists()
        {
            var blockedUserNames = new List <string>();

            blockedUserNames.Add("*****@*****.**");
            IList <IList <string> > assignUserNames = new List <IList <string> >();

            var userNames = new List <string>();

            userNames.Add("Venkat M");
            userNames.Add("");
            assignUserNames.Add(userNames);



            IList <IList <string> > assignUserEmails = new List <IList <string> >();
            var emails = new List <string>();

            emails.Add("*****@*****.**");
            emails.Add("");
            assignUserEmails.Add(emails);

            var userIds = new List <string>();

            userIds.Add("txtAssign1");

            var matterInformationVM = new MatterInformationVM()
            {
                Client = new Client()
                {
                    Url = "https://msmatter.sharepoint.com/sites/microsoft"
                },
                Matter = new Matter()
                {
                    Name             = "New Matter",
                    AssignUserNames  = assignUserNames,
                    AssignUserEmails = assignUserEmails,
                    Conflict         = new Conflict()
                    {
                        Identified = "True"
                    },
                    BlockUserNames = blockedUserNames,
                },
                UserIds = userIds
            };

            using (var testClient = testServer.CreateClient().AcceptJson())
            {
                var response = await testClient.PostAsJsonAsync("http://localhost:58775/api/v1/matter/checksecuritygroupexists", matterInformationVM);

                var result = response.Content.ReadAsJsonAsync <GenericResponseVM>().Result;
                Assert.NotNull(result);
            }
        }
예제 #4
0
        /// <summary>
        /// This method will send notifications to external users
        /// </summary>
        /// <param name="externalSharingRequest"></param>
        /// <returns></returns>
        private GenericResponseVM SendExternalNotification(MatterInformationVM matterInformation, string permission, string externalEmail)
        {
            var clientUrl = $"{matterInformation.Client.Url}";

            try
            {
                var users = new List <UserRoleAssignment>();
                UserRoleAssignment userRole = new UserRoleAssignment();
                userRole.UserId = externalEmail;
                switch (permission.ToLower())
                {
                case "full control":
                    userRole.Role = SharePoint.Client.Sharing.Role.Owner;
                    break;

                case "contribute":
                    userRole.Role = SharePoint.Client.Sharing.Role.Edit;
                    break;

                case "read":
                    userRole.Role = SharePoint.Client.Sharing.Role.View;
                    break;
                }
                users.Add(userRole);
                #region Doc Sharing API
                //Need to use MatterGuid instead of Id
                string matterLandingPageUrl        = $"{clientUrl}/sitepages/{matterInformation.Matter.MatterGuid + ServiceConstants.ASPX_EXTENSION}";
                string catalogSiteAssetsLibraryUrl = $"{generalSettings.CentralRepositoryUrl}/SitePages/home.aspx";
                using (var clientContext = spoAuthorization.GetClientContext(clientUrl))
                {
                    //Send notification to the matter landing page url with permission the user has selected
                    IList <UserSharingResult> matterLandingPageResult = DocumentSharingManager.UpdateDocumentSharingInfo(clientContext,
                                                                                                                         matterLandingPageUrl,
                                                                                                                         users, true, true, true, "The following matter page has been shared with you", true, true);
                    clientContext.ExecuteQuery();
                }
                return(null);

                #endregion
            }
            catch (Exception ex)
            {
                throw;
            }
        }
예제 #5
0
 /// <summary>
 /// This method will read external access requests azure table storage for all
 /// pending requests and update the matter related lists and libraries permissions for external users
 /// </summary>
 /// <param name="timerInfo"></param>
 /// <param name="matterInformationVM"></param>
 /// <param name="log"></param>
 public static void ReadExternalAccessRequests([TimerTrigger("00:00:05", RunOnStartup = true)] TimerInfo timerInfo,
                                               [Table("ExternalAccessRequests")] IQueryable <MatterInformationVM> matterInformationVM,
                                               TextWriter log)
 {
     try
     {
         var builder = new ConfigurationBuilder()
                       .SetBasePath(Directory.GetCurrentDirectory())
                       .AddJsonFile("appSettings.json")
                       .AddEnvironmentVariables();//appsettings.json will be overridden with azure web appsettings
         var            configuration = builder.Build();
         KeyVaultHelper kv            = new KeyVaultHelper(configuration);
         KeyVaultHelper.GetCert(configuration);
         kv.GetKeyVaultSecretsCerticate();
         //Read all rows from table storage which
         //Read all rows from table storage which are in pending state
         var query = from p in matterInformationVM select p;
         foreach (MatterInformationVM matterInformation in query)
         {
             if (matterInformation != null)
             {
                 if (matterInformation.Status.ToLower() == "pending")
                 {
                     string serializedMatter = matterInformation.SerializeMatter;
                     //De Serialize the matter information
                     MatterInformationVM originalMatter = Newtonsoft.Json.JsonConvert.DeserializeObject <MatterInformationVM>(serializedMatter);
                     log.WriteLine($"Checking the matter name {originalMatter.Matter.Name} has been acceped by the user or not");
                     //Read all external access requests records from azure table storge
                     GetExternalAccessRequestsFromSPO(originalMatter, log, configuration);
                 }
             }
         }
     }
     catch (Exception ex)
     {
         log.WriteLine($"Exception occured in the method ReadExternalAccessRequests. {ex}");
     }
 }
예제 #6
0
        /// <summary>
        /// This method will store the external sharing request in a list called "MatterCenterExternalRequests"
        /// and send notification to the external user regarding the information that is getting shared
        /// </summary>
        /// <param name="externalSharingRequest"></param>
        /// <returns></returns>
        public GenericResponseVM ShareMatter(MatterInformationVM matterInformation)
        {
            var tempMatterInformation = matterInformation;
            int index = 0;

            foreach (var assignUserEmails in matterInformation.Matter.AssignUserEmails)
            {
                foreach (string email in assignUserEmails)
                {
                    //First check whether the user exists in SharePoint or not
                    if (!string.IsNullOrWhiteSpace(email) && userDetails.CheckUserPresentInMatterCenter(generalSettings.SiteURL, email) == false)
                    {
                        //If not, store external request in a list
                        SaveExternalSharingRequest(matterInformation);
                        //Send notification to the user with appropriate information
                        SendExternalNotification(matterInformation,
                                                 matterInformation.Matter.Permissions[index],
                                                 matterInformation.Matter.AssignUserEmails[index][0]);
                    }
                }
                index = index + 1;
            }
            return(null);
        }
예제 #7
0
        private static void SentEmailNotificationForCreatedIsBackwardCompatibleMatters(MatterInformationVM matterInformation1, ExchangeService service, TextWriter log, IConfigurationRoot configuration)
        {
            string mailSubject                     = configuration.GetSection("Mail").GetSection("MatterMailSubject").Value;
            string defaultHtmlChunk                = configuration.GetSection("Mail").GetSection("MatterMailDefaultContentTypeHtmlChunk").Value;
            string oneNoteLibrarySuffix            = configuration.GetSection("Matter").GetSection("OneNoteLibrarySuffix").Value;
            string matterMailBodyMatterInformation = configuration.GetSection("Mail").GetSection("MatterMailBodyMatterInformation").Value;
            string matterMailBodyConflictCheck     = configuration.GetSection("Mail").GetSection("MatterMailBodyConflictCheck").Value;
            string matterCenterDateFormat          = configuration.GetSection("Mail").GetSection("MatterCenterDateFormat").Value;
            string matterMailBodyTeamMembers       = configuration.GetSection("Mail").GetSection("MatterMailBodyTeamMembers").Value;
            ///For isbackward compatability true
            MatterInformationVM originalMatter = JsonConvert.DeserializeObject <MatterInformationVM>(matterInformation1.SerializeMatter);
            Matter        matter                  = originalMatter.Matter;
            MatterDetails matterDetails           = originalMatter.MatterDetails;
            Client        client                  = originalMatter.Client;
            string        practiceGroupColumnName = configuration["ContentTypes:ManagedColumns:ColumnName1"].ToString();
            string        areaOfLawColumnName     = configuration["ContentTypes:ManagedColumns:ColumnName2"].ToString();
            string        matterMailBody;
            string        practiceGroupValue = originalMatter.MatterDetails.ManagedColumnTerms[practiceGroupColumnName].TermName;
            string        areaOfLawValue     = originalMatter.MatterDetails.ManagedColumnTerms[areaOfLawColumnName].TermName;

            // Generate Mail Subject
            string matterMailSubject = string.Format(CultureInfo.InvariantCulture, mailSubject,
                                                     matter.Id, matter.Name, originalMatter.MatterCreator);

            // Step 1: Create Matter Information
            string defaultContentType = string.Format(CultureInfo.InvariantCulture,
                                                      defaultHtmlChunk, matter.DefaultContentType);
            string matterType = string.Join(";", matter.ContentTypes.ToArray()).TrimEnd(';').Replace(matter.DefaultContentType, defaultContentType);

            if (matterType == string.Empty)
            {
                matterType = defaultContentType;
            }
            // Step 2: Create Team Information
            string secureMatter = ServiceConstants.FALSE.ToUpperInvariant() == matter.Conflict.SecureMatter.ToUpperInvariant() ?
                                  ServiceConstants.NO : ServiceConstants.YES;
            string mailBodyTeamInformation = string.Empty;

            mailBodyTeamInformation = TeamMembersPermissionInformation(matterDetails, mailBodyTeamInformation);

            string oneNotePath = string.Concat(client.Url, ServiceConstants.FORWARD_SLASH,
                                               matter.MatterGuid, oneNoteLibrarySuffix,
                                               ServiceConstants.FORWARD_SLASH, matter.Name, ServiceConstants.FORWARD_SLASH, matter.MatterGuid);
            string conflictIdentified = ServiceConstants.FALSE.ToUpperInvariant() == matter.Conflict.Identified.ToUpperInvariant() ?
                                        ServiceConstants.NO : ServiceConstants.YES;

            matterMailBody = string.Format(CultureInfo.InvariantCulture,
                                           matterMailBodyMatterInformation,
                                           practiceGroupValue,
                                           areaOfLawValue,
                                           matter.Name,
                                           matter.Description,
                                           matter.Name + " OneNote",
                                           matterType,
                                           originalMatter.MatterCreator,
                                           string.Format("{0:MMM dd, yyyy}", DateTime.Now),
                                           originalMatter.MatterLocation,
                                           client.Url, oneNotePath,
                                           configuration["General:SiteURL"].ToString());

            EmailMessage email = new EmailMessage(service);

            foreach (IList <string> userNames in matter.AssignUserEmails)
            {
                foreach (string userName in userNames)
                {
                    if (!string.IsNullOrWhiteSpace(userName))
                    {
                        using (var ctx = new ClientContext(originalMatter.Client.Url))
                        {
                            SecureString password = Utility.GetEncryptedPassword(configuration["General:AdminPassword"]);
                            ctx.Credentials = new SharePointOnlineCredentials(configuration["General:AdminUserName"], password);
                            if (CheckUserPresentInMatterCenter(ctx, originalMatter.Client.Url, userName, null, log))
                            {
                                email.ToRecipients.Add(userName);
                            }
                        }
                    }
                }
            }
            string adminUserName = configuration["General:AdminUserName"];

            email.From    = new EmailAddress(adminUserName);
            email.Subject = matterMailSubject;
            email.Body    = matterMailBody;
            email.Send();
            log.WriteLine($"connection string. {configuration["General:CloudStorageConnectionString"]}");
            Utility.UpdateTableStorageEntity(originalMatter, log, configuration["General:CloudStorageConnectionString"],
                                             configuration["Settings:MatterRequests"], "Accepted");
        }
예제 #8
0
        /// <summary>
        /// This method will get all list items from external access requests and process all
        /// requests which are in accpeted state
        /// </summary>
        /// <param name="originalMatter"></param>
        /// <param name="log"></param>
        /// <param name="configuration"></param>
        private static void GetExternalAccessRequestsFromSPO(MatterInformationVM originalMatter,
                                                             TextWriter log,
                                                             IConfigurationRoot configuration)
        {
            try
            {
                foreach (var assignUserEmails in originalMatter.Matter.AssignUserEmails)
                {
                    foreach (string email in assignUserEmails)
                    {
                        using (var ctx = new ClientContext(originalMatter.Client.Url))
                        {
                            SecureString password = Utility.GetEncryptedPassword(configuration["General:AdminPassword"]);
                            ctx.Credentials = new SharePointOnlineCredentials(configuration["General:AdminUserName"], password);
                            //First check whether the user exists in SharePoint or not
                            log.WriteLine($"Checking whether the user {email} has been present in the system or not");
                            if (CheckUserPresentInMatterCenter(ctx, originalMatter.Client.Url, email, configuration, log) == true)
                            {
                                string    requestedForPerson = email;
                                string    matterId           = originalMatter.Matter.MatterGuid;
                                var       listTitle          = configuration["Settings:ExternalAccessRequests"];
                                var       list      = ctx.Web.Lists.GetByTitle(listTitle);
                                CamlQuery camlQuery = CamlQuery.CreateAllItemsQuery();
                                camlQuery.ViewXml = "";
                                ListItemCollection listItemCollection = list.GetItems(camlQuery);
                                ctx.Load(listItemCollection);
                                ctx.ExecuteQuery();
                                log.WriteLine($"Looping all the records from {configuration["Settings:ExternalAccessRequests"]} lists");
                                foreach (ListItem listItem in listItemCollection)
                                {
                                    //The matter id for whom the request has been sent
                                    string requestedObjectTitle = listItem["RequestedObjectTitle"].ToString();
                                    //The person to whom the request has been sent
                                    string requestedFor = listItem["RequestedFor"].ToString();
                                    //The matter url for which the request has been sent
                                    string url = ((FieldUrlValue)listItem["RequestedObjectUrl"]).Url;
                                    //The status of the request whether it has been in pending=0, accepeted=2 or withdrawn=5
                                    string status = listItem["Status"].ToString();
                                    //If the status is accepted and the person and matter in table storage equals to item in Access Requests list
                                    if (requestedFor == requestedForPerson && matterId == requestedObjectTitle && status == "2")
                                    {
                                        log.WriteLine($"The user {email} has been present in the system and he has accepted the invitation and providing permssions to  matter {originalMatter.Matter.Name} from the user {email}");
                                        UpdateMatter umd = new UpdateMatter();
                                        //Update all matter related lists and libraries permissions for external users
                                        umd.UpdateUserPermissionsForMatter(originalMatter, configuration, password);

                                        //Update permissions for external users in Catalog Site Collection
                                        using (var catalogContext = new ClientContext(configuration["General:CentralRepositoryUrl"]))
                                        {
                                            catalogContext.Credentials =
                                                new SharePointOnlineCredentials(configuration["General:AdminUserName"], password);
                                            umd.AssignPermissionToCatalogLists(configuration["Catalog:SiteAssets"], catalogContext,
                                                                               email.Trim(), configuration["Catalog:SiteAssetsPermissions"], configuration);
                                        }
                                        log.WriteLine($"The matter permissions has been updated for the user {email}");
                                        log.WriteLine($"Updating the matter status to Accepted in Azure Table Storage");
                                        Utility.UpdateTableStorageEntity(originalMatter, log, configuration["General:CloudStorageConnectionString"],
                                                                         configuration["Settings:TableStorageForExternalRequests"], "Accepted");
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.WriteLine($"Exception occured in the method GetExternalAccessRequestsFromSPO. {ex}");
            }
        }
예제 #9
0
        private static void SentEmailNotificationForCreatedMatters(MatterInformationVM matterInformation1, ExchangeService service, TextWriter log, IConfigurationRoot configuration)
        {
            string mailSubject                     = configuration.GetSection("Mail").GetSection("MatterMailSubject").Value;
            string defaultHtmlChunk                = configuration.GetSection("Mail").GetSection("MatterMailDefaultContentTypeHtmlChunk").Value;
            string oneNoteLibrarySuffix            = configuration.GetSection("Matter").GetSection("OneNoteLibrarySuffix").Value;
            string matterMailBodyMatterInformation = configuration.GetSection("Mail").GetSection("MatterMailBodyMatterInformation").Value;
            string matterMailBodyConflictCheck     = configuration.GetSection("Mail").GetSection("MatterMailBodyConflictCheck").Value;
            string matterCenterDateFormat          = configuration.GetSection("Mail").GetSection("MatterCenterDateFormat").Value;
            string matterMailBodyTeamMembers       = configuration.GetSection("Mail").GetSection("MatterMailBodyTeamMembers").Value;
            //De Serialize the matter information
            MatterInformationVM originalMatter = JsonConvert.DeserializeObject <MatterInformationVM>(matterInformation1.SerializeMatter);
            Matter        matter        = originalMatter.Matter;
            MatterDetails matterDetails = originalMatter.MatterDetails;
            Client        client        = originalMatter.Client;

            string matterMailBody, blockUserNames;
            // Generate Mail Subject
            string matterMailSubject = string.Format(CultureInfo.InvariantCulture, mailSubject,
                                                     matter.Id, matter.Name, originalMatter.MatterCreator);

            // Step 1: Create Matter Information
            string defaultContentType = string.Format(CultureInfo.InvariantCulture,
                                                      defaultHtmlChunk, matter.DefaultContentType);
            string matterType = string.Join(";", matter.ContentTypes.ToArray()).TrimEnd(';').Replace(matter.DefaultContentType, defaultContentType);

            if (matterType == string.Empty)
            {
                matterType = defaultContentType;
            }
            // Step 2: Create Team Information
            string secureMatter = ServiceConstants.FALSE.ToUpperInvariant() == matter.Conflict.SecureMatter.ToUpperInvariant() ?
                                  ServiceConstants.NO : ServiceConstants.YES;
            string mailBodyTeamInformation = string.Empty;

            mailBodyTeamInformation = TeamMembersPermissionInformation(matterDetails, mailBodyTeamInformation);

            string oneNotePath = string.Concat(client.Url, ServiceConstants.FORWARD_SLASH,
                                               matter.MatterGuid, oneNoteLibrarySuffix,
                                               ServiceConstants.FORWARD_SLASH, matter.MatterGuid, ServiceConstants.FORWARD_SLASH, matter.MatterGuid);

            if (originalMatter.IsConflictCheck)
            {
                string conflictIdentified = ServiceConstants.FALSE.ToUpperInvariant() == matter.Conflict.Identified.ToUpperInvariant() ?
                                            ServiceConstants.NO : ServiceConstants.YES;
                blockUserNames = string.Join(";", matter.BlockUserNames.ToArray()).Trim().TrimEnd(';');

                blockUserNames = !String.IsNullOrEmpty(blockUserNames) ? string.Format(CultureInfo.InvariantCulture,
                                                                                       "<div>{0}: {1}</div>", "Conflicted User", blockUserNames) : string.Empty;
                matterMailBody = string.Format(CultureInfo.InvariantCulture,
                                               matterMailBodyMatterInformation, client.Name, client.Id,
                                               matter.Name, matter.Id, matter.Description, matterType) + string.Format(CultureInfo.InvariantCulture,
                                                                                                                       matterMailBodyConflictCheck, ServiceConstants.YES, matter.Conflict.CheckBy,
                                                                                                                       Convert.ToDateTime(matter.Conflict.CheckOn, CultureInfo.InvariantCulture).ToString(matterCenterDateFormat, CultureInfo.InvariantCulture),
                                                                                                                       conflictIdentified) + string.Format(CultureInfo.InvariantCulture,
                                                                                                                                                           matterMailBodyTeamMembers, secureMatter, mailBodyTeamInformation,
                                                                                                                                                           blockUserNames, client.Url, oneNotePath, matter.Name, originalMatter.MatterLocation, matter.Name);
            }
            else
            {
                blockUserNames = string.Empty;
                matterMailBody = string.Format(CultureInfo.InvariantCulture, matterMailBodyMatterInformation,
                                               client.Name, client.Id, matter.Name, matter.Id,
                                               matter.Description, matterType) + string.Format(CultureInfo.InvariantCulture, matterMailBodyTeamMembers, secureMatter,
                                                                                               mailBodyTeamInformation, blockUserNames, client.Url, oneNotePath, matter.Name, originalMatter.MatterLocation, matter.Name);
            }

            EmailMessage email = new EmailMessage(service);

            foreach (IList <string> userNames in matter.AssignUserEmails)
            {
                foreach (string userName in userNames)
                {
                    if (!string.IsNullOrWhiteSpace(userName))
                    {
                        using (var ctx = new ClientContext(originalMatter.Client.Url))
                        {
                            SecureString password = Utility.GetEncryptedPassword(configuration["General:AdminPassword"]);
                            ctx.Credentials = new SharePointOnlineCredentials(configuration["General:AdminUserName"], password);
                            if (CheckUserPresentInMatterCenter(ctx, originalMatter.Client.Url, userName, null, log))
                            {
                                email.ToRecipients.Add(userName);
                            }
                        }
                    }
                }
            }
            email.From    = new EmailAddress(configuration["General:AdminUserName"]);
            email.Subject = matterMailSubject;
            email.Body    = matterMailBody;
            email.Send();
            Utility.UpdateTableStorageEntity(originalMatter, log, configuration["General:CloudStorageConnectionString"],
                                             configuration["Settings:MatterRequests"], "Accepted");
        }
예제 #10
0
        public GenericResponseVM IsMatterValid(MatterInformationVM matterInformation, int methodNumber, MatterConfigurations matterConfigurations)
        {
            GenericResponseVM genericResponse = null;
            var matterDetails = matterInformation.MatterDetails;

            if (int.Parse(ServiceConstants.ProvisionMatterCreateMatter, CultureInfo.InvariantCulture) <= methodNumber &&
                int.Parse(ServiceConstants.EditMatterPermission, CultureInfo.InvariantCulture) >= methodNumber &&
                !spList.CheckPermissionOnList(matterSettings.ProvisionMatterAppURL, matterSettings.SendMailListName, PermissionKind.EditListItems))
            {
                genericResponse = new GenericResponseVM();
                //return string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, ServiceConstantStrings.IncorrectInputUserAccessCode, ServiceConstantStrings.IncorrectInputUserAccessMessage);
                genericResponse.Code  = errorSettings.IncorrectInputUserAccessCode;
                genericResponse.Value = errorSettings.IncorrectInputUserAccessMessage;
            }
            else
            {
                if (matterInformation.Client != null)
                {
                    genericResponse = new GenericResponseVM();
                    genericResponse = ValidateClientInformation(matterInformation.Client, methodNumber);
                    if (genericResponse != null)
                    {
                        return(genericResponse);
                    }
                }
                if (matterInformation.Matter != null)
                {
                    genericResponse = MatterMetadataValidation(matterInformation.Matter, matterInformation.Client,
                                                               methodNumber, matterConfigurations);
                    if (genericResponse != null)
                    {
                        return(genericResponse);
                    }
                    if (int.Parse(ServiceConstants.EditMatterPermission, CultureInfo.InvariantCulture) == methodNumber)
                    {
                        genericResponse = RoleCheck(matterInformation.Matter);
                        if (genericResponse != null)
                        {
                            return(genericResponse);
                        }
                    }
                    if (matterInformation.Matter.Permissions != null)
                    {
                        bool isFullControlPresent = ValidateFullControlPermission(matterInformation.Matter);
                        if (!isFullControlPresent)
                        {
                            return(GenericResponse(errorSettings.IncorrectInputUserAccessCode, errorSettings.ErrorEditMatterMandatoryPermission));
                        }
                    }
                }
                if (null != matterDetails && !(int.Parse(ServiceConstants.EditMatterPermission, CultureInfo.InvariantCulture) == methodNumber))
                {
                    if (string.IsNullOrWhiteSpace(matterDetails.PracticeGroup))
                    {
                        return(GenericResponse(errorSettings.IncorrectInputPracticeGroupCode, errorSettings.IncorrectInputPracticeGroupMessage));
                    }
                    if (string.IsNullOrWhiteSpace(matterDetails.AreaOfLaw))
                    {
                        return(GenericResponse(errorSettings.IncorrectInputAreaOfLawCode, errorSettings.IncorrectInputAreaOfLawMessage));
                    }
                    if (string.IsNullOrWhiteSpace(matterDetails.SubareaOfLaw))
                    {
                        return(GenericResponse(errorSettings.IncorrectInputSubareaOfLawCode, errorSettings.IncorrectInputSubareaOfLawMessage));
                    }
                    try
                    {
                        if (string.IsNullOrWhiteSpace(matterDetails.ResponsibleAttorney))
                        {
                            return(GenericResponse(errorSettings.IncorrectInputResponsibleAttorneyCode, errorSettings.IncorrectInputResponsibleAttorneyMessage));
                        }
                        else
                        {
                            IList <string> userNames = matterDetails.ResponsibleAttorney.Split(';').ToList <string>();
                            matterRespository.ResolveUserNames(matterInformation.Client, userNames).FirstOrDefault();
                        }
                    }
                    catch (Exception)
                    {
                        return(GenericResponse(errorSettings.IncorrectInputResponsibleAttorneyCode, errorSettings.IncorrectInputResponsibleAttorneyMessage));
                    }
                }
            }
            return(genericResponse);
        }
예제 #11
0
        /// <summary>
        /// This web job function will process matter that is there in azure table storage called MatterRequests.
        /// If there are any new matter is created, this web job function will get invoked for the time duration that has
        /// been specified and will preocess all new matters and will send notification for those respective users
        /// Once the matter has been processed, it will change the status of that matter to "Send" so that it will not
        /// be processed again
        /// </summary>
        /// <param name="timerInfo"></param>
        /// <param name="matterInformationVM"></param>
        public static void ProcessMatter([TimerTrigger("00:00:05", RunOnStartup = true)] TimerInfo timerInfo,
                                         [Table("MatterRequests")] IQueryable <MatterInformationVM> matterInformationVM, TextWriter log)
        {
            var query = from p in matterInformationVM select p;

            if (query.ToList().Count() > 0)
            {
                var builder = new ConfigurationBuilder()
                              .SetBasePath(Directory.GetCurrentDirectory())
                              .AddJsonFile("appSettings.json")
                              .AddInMemoryCollection()
                              .AddEnvironmentVariables();//appsettings.json will be overridden with azure web appsettings
                ExchangeService service       = new ExchangeService(ExchangeVersion.Exchange2013);
                var             configuration = builder.Build();
                KeyVaultHelper  kv            = new KeyVaultHelper(configuration);
                KeyVaultHelper.GetCert(configuration);
                kv.GetKeyVaultSecretsCerticate();
                //// can use on premise exchange server credentials with service.UseDefaultCredentials = true, or
                //explicitly specify the admin account (set default to false)
                string adminUserName = configuration.GetSection("General").GetSection("AdminUserName").Value;
                string adminPassword = configuration.GetSection("General").GetSection("AdminPassword").Value;
                service.Credentials = new WebCredentials(adminUserName, adminPassword);
                service.Url         = new Uri(configuration.GetSection("Settings").GetSection("ExchangeServiceURL").Value);
                string mailSubject                     = configuration.GetSection("Mail").GetSection("MatterMailSubject").Value;
                string defaultHtmlChunk                = configuration.GetSection("Mail").GetSection("MatterMailDefaultContentTypeHtmlChunk").Value;
                string oneNoteLibrarySuffix            = configuration.GetSection("Matter").GetSection("OneNoteLibrarySuffix").Value;
                string matterMailBodyMatterInformation = configuration.GetSection("Mail").GetSection("MatterMailBodyMatterInformation").Value;
                string matterMailBodyConflictCheck     = configuration.GetSection("Mail").GetSection("MatterMailBodyConflictCheck").Value;
                string matterCenterDateFormat          = configuration.GetSection("Mail").GetSection("MatterCenterDateFormat").Value;
                string matterMailBodyTeamMembers       = configuration.GetSection("Mail").GetSection("MatterMailBodyTeamMembers").Value;

                foreach (MatterInformationVM matterInformation1 in query)
                {
                    if (matterInformation1 != null)
                    {
                        if (matterInformation1.Status.ToLower() == "pending")
                        {
                            //De Serialize the matter information
                            MatterInformationVM originalMatter = JsonConvert.DeserializeObject <MatterInformationVM>(matterInformation1.SerializeMatter);
                            Matter        matter        = originalMatter.Matter;
                            MatterDetails matterDetails = originalMatter.MatterDetails;
                            Client        client        = originalMatter.Client;

                            string matterMailBody, blockUserNames;
                            // Generate Mail Subject
                            string matterMailSubject = string.Format(CultureInfo.InvariantCulture, mailSubject,
                                                                     matter.Id, matter.Name, originalMatter.MatterCreator);

                            // Step 1: Create Matter Information
                            string defaultContentType = string.Format(CultureInfo.InvariantCulture,
                                                                      defaultHtmlChunk, matter.DefaultContentType);
                            string matterType = string.Join(";", matter.ContentTypes.ToArray()).TrimEnd(';').Replace(matter.DefaultContentType, defaultContentType);
                            if (matterType == string.Empty)
                            {
                                matterType = defaultContentType;
                            }
                            // Step 2: Create Team Information
                            string secureMatter = ServiceConstants.FALSE.ToUpperInvariant() == matter.Conflict.SecureMatter.ToUpperInvariant() ?
                                                  ServiceConstants.NO : ServiceConstants.YES;
                            string mailBodyTeamInformation = string.Empty;
                            mailBodyTeamInformation = TeamMembersPermissionInformation(matterDetails, mailBodyTeamInformation);

                            string oneNotePath = string.Concat(client.Url, ServiceConstants.FORWARD_SLASH,
                                                               matter.MatterGuid, oneNoteLibrarySuffix,
                                                               ServiceConstants.FORWARD_SLASH, matter.MatterGuid, ServiceConstants.FORWARD_SLASH, matter.MatterGuid);

                            if (originalMatter.IsConflictCheck)
                            {
                                string conflictIdentified = ServiceConstants.FALSE.ToUpperInvariant() == matter.Conflict.Identified.ToUpperInvariant() ?
                                                            ServiceConstants.NO : ServiceConstants.YES;
                                blockUserNames = string.Join(";", matter.BlockUserNames.ToArray()).Trim().TrimEnd(';');

                                blockUserNames = !String.IsNullOrEmpty(blockUserNames) ? string.Format(CultureInfo.InvariantCulture,
                                                                                                       "<div>{0}: {1}</div>", "Conflicted User", blockUserNames) : string.Empty;
                                matterMailBody = string.Format(CultureInfo.InvariantCulture,
                                                               matterMailBodyMatterInformation, client.Name, client.Id,
                                                               matter.Name, matter.Id, matter.Description, matterType) + string.Format(CultureInfo.InvariantCulture,
                                                                                                                                       matterMailBodyConflictCheck, ServiceConstants.YES, matter.Conflict.CheckBy,
                                                                                                                                       Convert.ToDateTime(matter.Conflict.CheckOn, CultureInfo.InvariantCulture).ToString(matterCenterDateFormat, CultureInfo.InvariantCulture),
                                                                                                                                       conflictIdentified) + string.Format(CultureInfo.InvariantCulture,
                                                                                                                                                                           matterMailBodyTeamMembers, secureMatter, mailBodyTeamInformation,
                                                                                                                                                                           blockUserNames, client.Url, oneNotePath, matter.Name, originalMatter.MatterLocation, matter.Name);
                            }
                            else
                            {
                                blockUserNames = string.Empty;
                                matterMailBody = string.Format(CultureInfo.InvariantCulture, matterMailBodyMatterInformation,
                                                               client.Name, client.Id, matter.Name, matter.Id,
                                                               matter.Description, matterType) + string.Format(CultureInfo.InvariantCulture, matterMailBodyTeamMembers, secureMatter,
                                                                                                               mailBodyTeamInformation, blockUserNames, client.Url, oneNotePath, matter.Name, originalMatter.MatterLocation, matter.Name);
                            }

                            EmailMessage email = new EmailMessage(service);
                            foreach (IList <string> userNames  in matter.AssignUserEmails)
                            {
                                foreach (string userName in userNames)
                                {
                                    if (!string.IsNullOrWhiteSpace(userName))
                                    {
                                        using (var ctx = new ClientContext(originalMatter.Client.Url))
                                        {
                                            SecureString password = Utility.GetEncryptedPassword(configuration["General:AdminPassword"]);
                                            ctx.Credentials = new SharePointOnlineCredentials(configuration["General:AdminUserName"], password);
                                            if (CheckUserPresentInMatterCenter(ctx, originalMatter.Client.Url, userName, null, log))
                                            {
                                                email.ToRecipients.Add(userName);
                                            }
                                        }
                                    }
                                }
                            }
                            email.From    = new EmailAddress(adminUserName);
                            email.Subject = matterMailSubject;
                            email.Body    = matterMailBody;
                            email.Send();
                            Utility.UpdateTableStorageEntity(originalMatter, log, configuration["Data:DefaultConnection:AzureStorageConnectionString"],
                                                             configuration["Settings:MatterRequests"], "Accepted");
                        }
                    }
                }
            }
        }
예제 #12
0
        public void UpdateUserPermissionsForMatter(MatterInformationVM matterInformation,
                                                   IConfigurationRoot configuration, System.Security.SecureString securePassword)
        {
            var           matter           = matterInformation.Matter;
            var           matterDetails    = matterInformation.MatterDetails;
            var           client           = matterInformation.Client;
            int           listItemId       = -1;
            string        loggedInUserName = "";
            bool          isEditMode       = matterInformation.EditMode;
            ClientContext clientContext    = null;
            IEnumerable <RoleAssignment> userPermissionOnLibrary = null;

            //GenericResponseVM genericResponse = null;
            try
            {
                clientContext             = new ClientContext(matterInformation.Client.Url);
                clientContext.Credentials = new SharePointOnlineCredentials(configuration["General:AdminUserName"], securePassword);

                //if (null != matter.Conflict && !string.IsNullOrWhiteSpace(matter.Conflict.Identified))
                //{
                //    if (Convert.ToBoolean(matter.Conflict.Identified, System.Globalization.CultureInfo.InvariantCulture))
                //    {
                //        genericResponse = CheckSecurityGroupInTeamMembers(clientContext, matter, matterInformation.UserIds);
                //    }
                //}
                //else
                //{
                //    //genericResponse = string.Format(System.Globalization.CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputConflictIdentifiedCode, TextConstants.IncorrectInputConflictIdentifiedMessage);
                //    return;
                //}
                //if (genericResponse == null)
                //{
                PropertyValues matterStampedProperties = SPList.GetListProperties(clientContext, matter.Name);
                loggedInUserName = SPList.GetLoggedInUserDetails(clientContext).Name;
                // Get matter library current permissions
                userPermissionOnLibrary = SPList.FetchUserPermissionForLibrary(clientContext, matter.Name);
                string originalMatterName = SPList.GetMatterName(clientContext, matter.Name);
                listItemId = SPList.RetrieveItemId(clientContext, "Site Pages", originalMatterName);
                List <string> usersToRemove     = RetrieveMatterUsers(userPermissionOnLibrary);
                bool          hasFullPermission = CheckFullPermissionInAssignList(matter.AssignUserNames, matter.Permissions, loggedInUserName);
                List <string> listExists        = MatterAssociatedLists(clientContext, matter.Name);
                AssignRemoveFullControl(clientContext, matter, loggedInUserName, listItemId, listExists, true, hasFullPermission);
                bool result = false;
                if (listExists.Contains(matter.Name))
                {
                    result = UpdatePermission(clientContext, matter, usersToRemove, loggedInUserName, false, matter.Name, -1, isEditMode);
                }
                if (listExists.Contains(matter.Name + configuration["Matter:OneNoteLibrarySuffix"]))
                {
                    result = UpdatePermission(clientContext, matter, usersToRemove, loggedInUserName, false, matter.Name + configuration["Matter:OneNoteLibrarySuffix"], -1, isEditMode);
                }
                if (listExists.Contains(matter.Name + configuration["Matter:CalendarNameSuffix"]))
                {
                    result = UpdatePermission(clientContext, matter, usersToRemove, loggedInUserName, false, matter.Name + configuration["Matter:CalendarNameSuffix"], -1, isEditMode);
                }
                if (listExists.Contains(matter.Name + configuration["Matter:TaskNameSuffix"]))
                {
                    result = UpdatePermission(clientContext, matter, usersToRemove, loggedInUserName, false, matter.Name + configuration["Matter:TaskNameSuffix"], -1, isEditMode);
                }
                if (0 <= listItemId)
                {
                    result = UpdatePermission(clientContext, matter, usersToRemove, loggedInUserName, true, "Site Pages", listItemId, isEditMode);
                }
                // Update matter metadata
                result = UpdateMatterStampedProperties(clientContext, matterDetails, matter, matterStampedProperties, isEditMode, configuration);
                //}
            }
            catch (Exception ex)
            {
                MatterRevertList matterRevertListObject = new MatterRevertList()
                {
                    MatterLibrary        = matter.Name,
                    MatterOneNoteLibrary = matter.Name + configuration["Matter:OneNoteLibrarySuffix"],
                    MatterCalendar       = matter.Name + configuration["Matter:CalendarNameSuffix"],
                    MatterTask           = matter.Name + configuration["Matter:TaskNameSuffix"],
                    MatterSitePages      = "Site Pages"
                };
                RevertMatterUpdates(client, matter, clientContext, matterRevertListObject, loggedInUserName,
                                    userPermissionOnLibrary, listItemId, isEditMode);
            }
            //return ServiceUtility.GenericResponse("9999999", "Error in updating matter information");
        }
        public async Task <IActionResult> GetTaxonomy([FromBody] TermStoreViewModel termStoreViewModel)
        {
            try
            {
                #region Error Checking

                var matterInformation = new MatterInformationVM()
                {
                    Client = new Client()
                    {
                        Url = termStoreViewModel.Client.Url
                    }
                };
                var genericResponseVM = validationFunctions.IsMatterValid(matterInformation, 0, null);
                if (genericResponseVM != null)
                {
                    genericResponseVM.Description = $"Error occurred while getting the taxonomy data";
                    return(matterCenterServiceFunctions.ServiceResponse(genericResponseVM, (int)HttpStatusCode.BadRequest));
                }
                #endregion

                string cacheValue = string.Empty;
                string key        = string.Empty;
                var    details    = termStoreViewModel.TermStoreDetails;
                if (details.TermSetName == taxonomySettings.PracticeGroupTermSetName)
                {
                    key = ServiceConstants.CACHE_MATTER_TYPE;
                }
                else if (details.TermSetName == taxonomySettings.ClientTermSetName)
                {
                    key = ServiceConstants.CACHE_CLIENTS;
                }

                ServiceUtility.RedisCacheHostName = generalSettings.RedisCacheHostName;
                cacheValue = ServiceUtility.GetDataFromAzureRedisCache(key);
                cacheValue = "";
                TaxonomyResponseVM taxonomyRepositoryVM = null;
                if (String.IsNullOrEmpty(cacheValue))
                {
                    taxonomyRepositoryVM = await taxonomyRepository.GetTaxonomyHierarchyAsync(termStoreViewModel);

                    if (termStoreViewModel.TermStoreDetails.TermSetName == taxonomySettings.PracticeGroupTermSetName && taxonomyRepositoryVM.TermSets != null)
                    {
                        ServiceUtility.SetDataIntoAzureRedisCache <string>(key, taxonomyRepositoryVM.TermSets);
                        return(matterCenterServiceFunctions.ServiceResponse(taxonomyRepositoryVM.TermSets, (int)HttpStatusCode.OK));
                    }
                    if (termStoreViewModel.TermStoreDetails.TermSetName == taxonomySettings.ClientTermSetName && taxonomyRepositoryVM.ClientTermSets != null)
                    {
                        ServiceUtility.SetDataIntoAzureRedisCache <ClientTermSets>(key, taxonomyRepositoryVM.ClientTermSets);
                        return(matterCenterServiceFunctions.ServiceResponse(taxonomyRepositoryVM.ClientTermSets, (int)HttpStatusCode.OK));
                    }
                }
                else
                {
                    if (termStoreViewModel.TermStoreDetails.TermSetName == taxonomySettings.PracticeGroupTermSetName)
                    {
                        var pgTermSets = JsonConvert.DeserializeObject <string>(cacheValue);
                        if (pgTermSets == null)
                        {
                            genericResponseVM = new GenericResponseVM()
                            {
                                Value       = errorSettings.MessageNoResult,
                                Code        = "404",
                                Description = "No data is present for the given passed input"
                            };
                            return(matterCenterServiceFunctions.ServiceResponse(genericResponseVM, (int)HttpStatusCode.NotFound));
                        }
                        return(matterCenterServiceFunctions.ServiceResponse(pgTermSets, (int)HttpStatusCode.OK));
                    }
                    if (termStoreViewModel.TermStoreDetails.TermSetName == taxonomySettings.ClientTermSetName)
                    {
                        var clientTermSets = JsonConvert.DeserializeObject <ClientTermSets>(cacheValue);
                        if (clientTermSets == null)
                        {
                            genericResponseVM = new GenericResponseVM()
                            {
                                Value       = errorSettings.MessageNoResult,
                                Code        = HttpStatusCode.NotFound.ToString(),
                                Description = "No data is present for the given passed input"
                            };
                            return(matterCenterServiceFunctions.ServiceResponse(genericResponseVM, (int)HttpStatusCode.NotFound));
                        }
                        return(matterCenterServiceFunctions.ServiceResponse(clientTermSets, (int)HttpStatusCode.OK));
                    }
                }
                //If all the above condition fails, return validation error object
                genericResponseVM = new GenericResponseVM()
                {
                    Value       = errorSettings.MessageNoResult,
                    Code        = HttpStatusCode.NotFound.ToString(),
                    Description = "No data is present for the given passed input"
                };
                return(matterCenterServiceFunctions.ServiceResponse(genericResponseVM, (int)HttpStatusCode.BadRequest));
            }
            catch (Exception ex)
            {
                customLogger.LogError(ex, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, logTables.SPOLogTable);
                var errorResponse = customLogger.GenerateErrorResponse(ex);
                return(matterCenterServiceFunctions.ServiceResponse(errorResponse, (int)HttpStatusCode.InternalServerError));
            }
        }
        public async void Send_ExternalSharing_Notification()
        {
            var assignUserEmails = new List <IList <string> >();
            var userEmails       = new List <string>();

            userEmails.Add("*****@*****.**");
            assignUserEmails.Add(userEmails);

            userEmails = new List <string>();
            userEmails.Add("*****@*****.**");
            assignUserEmails.Add(userEmails);

            var assignUserNames = new List <IList <string> >();
            var userNames       = new List <string>();

            userNames.Add("Wilson Gajarla");
            userNames.Add("");
            assignUserNames.Add(userNames);

            userNames = new List <string>();
            userNames.Add("*****@*****.**");
            userNames.Add("");
            assignUserNames.Add(userNames);

            var permissions = new List <string>();

            permissions.Add("Full Control");
            permissions.Add("Full Control");

            var roles = new List <string>();

            roles.Add("Responsible Attorney");
            roles.Add("Legal Admin");

            var uploadBlockedUsers = new List <string>();

            uploadBlockedUsers.Add("*****@*****.**");
            var matterMetaInformation = new MatterInformationVM()
            {
                Client = new Client
                {
                    Url  = "https://msmatter.sharepoint.com/sites/microsoft",
                    Id   = "100001",
                    Name = "Microsoft"
                },
                Matter = new Matter
                {
                    Id             = "351085190a4ce42e2871e748b4e5d8ce",
                    Name           = "vTest4",
                    BlockUserNames = new List <string>()
                    {
                        "*****@*****.**"
                    },
                    AssignUserNames  = assignUserNames,
                    AssignUserEmails = assignUserEmails,
                    Permissions      = permissions,
                    Roles            = roles,
                    Conflict         = new Conflict()
                    {
                        Identified = "True"
                    }
                },
                MatterDetails = new MatterDetails
                {
                    ResponsibleAttorney      = "Wilson Gajarla;",
                    ResponsibleAttorneyEmail = "Wilson Gajarla;",
                    UploadBlockedUsers       = uploadBlockedUsers,
                    TeamMembers     = "Wilson Gajarla;[email protected]",
                    RoleInformation = "{\"Responsible Attorney\":\"Wilson Gajarla\",\"Legal Admin\":\"[email protected]\"}"
                },
                EditMode = true
            };

            using (var client = testServer.CreateClient().AcceptJson())
            {
                var response = await client.PostAsJsonAsync("http://localhost:44323/api/v1/matter/sharematter", matterMetaInformation);

                var result = response.Content.ReadAsJsonAsync <GenericResponseVM>().Result;
                Assert.NotNull(result);
            }
        }
예제 #15
0
        public GenericResponseVM UpdateMatter(MatterInformationVM matterInformation)
        {
            var           matter           = matterInformation.Matter;
            var           matterDetails    = matterInformation.MatterDetails;
            var           client           = matterInformation.Client;
            int           listItemId       = -1;
            string        loggedInUserName = "";
            bool          isEditMode       = matterInformation.EditMode;
            ClientContext clientContext    = null;
            IEnumerable <RoleAssignment> userPermissionOnLibrary = null;
            GenericResponseVM            genericResponse         = null;

            try
            {
                clientContext = spoAuthorization.GetClientContext(matterInformation.Client.Url);
                PropertyValues matterStampedProperties = matterRepositoy.GetStampedProperties(clientContext, matter.Name);
                loggedInUserName = matterRepositoy.GetLoggedInUserDetails(clientContext).Name;
                bool isFullControlPresent = editFunctions.ValidateFullControlPermission(matter);

                if (!isFullControlPresent)
                {
                    return(ServiceUtility.GenericResponse(errorSettings.IncorrectInputSelfPermissionRemoval, errorSettings.ErrorEditMatterMandatoryPermission));
                }

                // Get matter library current permissions
                userPermissionOnLibrary = matterRepositoy.FetchUserPermissionForLibrary(clientContext, matter.Name);
                string originalMatterName = matterRepositoy.GetMatterName(clientContext, matter.Name);
                listItemId = matterRepositoy.RetrieveItemId(clientContext, matterSettings.MatterLandingPageRepositoryName, originalMatterName);
                List <string> usersToRemove     = RetrieveMatterUsers(userPermissionOnLibrary);
                bool          hasFullPermission = CheckFullPermissionInAssignList(matter.AssignUserNames, matter.Permissions, loggedInUserName);
                List <string> listExists        = matterRepositoy.MatterAssociatedLists(clientContext, matter.Name);
                matterRepositoy.AssignRemoveFullControl(clientContext, matter, loggedInUserName, listItemId, listExists, true, hasFullPermission);
                bool result = false;
                if (listExists.Contains(matter.Name))
                {
                    result = matterRepositoy.UpdatePermission(clientContext, matter, usersToRemove, loggedInUserName, false, matter.Name, -1, isEditMode);
                }
                if (listExists.Contains(matter.Name + matterSettings.OneNoteLibrarySuffix))
                {
                    result = matterRepositoy.UpdatePermission(clientContext, matter, usersToRemove, loggedInUserName, false, matter.Name + matterSettings.OneNoteLibrarySuffix, -1, isEditMode);
                }
                if (listExists.Contains(matter.Name + matterSettings.CalendarNameSuffix))
                {
                    result = matterRepositoy.UpdatePermission(clientContext, matter, usersToRemove, loggedInUserName, false, matter.Name + matterSettings.CalendarNameSuffix, -1, isEditMode);
                }
                if (listExists.Contains(matter.Name + matterSettings.TaskNameSuffix))
                {
                    result = matterRepositoy.UpdatePermission(clientContext, matter, usersToRemove, loggedInUserName, false, matter.Name + matterSettings.TaskNameSuffix, -1, isEditMode);
                }
                if (0 <= listItemId)
                {
                    result = matterRepositoy.UpdatePermission(clientContext, matter, usersToRemove, loggedInUserName, true, matterSettings.MatterLandingPageRepositoryName, listItemId, isEditMode);
                }
                // Update matter metadata
                result = matterRepositoy.UpdateMatterStampedProperties(clientContext, matterDetails, matter, matterStampedProperties, isEditMode);
                if (result)
                {
                    return(genericResponse);
                }
            }
            catch (Exception ex)
            {
                MatterRevertList matterRevertListObject = new MatterRevertList()
                {
                    MatterLibrary        = matter.Name,
                    MatterOneNoteLibrary = matter.Name + matterSettings.OneNoteLibrarySuffix,
                    MatterCalendar       = matter.Name + matterSettings.CalendarNameSuffix,
                    MatterTask           = matter.Name + matterSettings.TaskNameSuffix,
                    MatterSitePages      = matterSettings.MatterLandingPageRepositoryName
                };
                matterRepositoy.RevertMatterUpdates(client, matter, clientContext, matterRevertListObject, loggedInUserName,
                                                    userPermissionOnLibrary, listItemId, isEditMode);
            }
            return(ServiceUtility.GenericResponse("9999999", "Error in updating matter information"));
        }
예제 #16
0
        /// <summary>
        /// This method will send notifications to external users
        /// </summary>
        /// <param name="externalSharingRequest"></param>
        /// <returns></returns>
        private GenericResponseVM SendExternalNotification(MatterInformationVM matterInformation, string permission, string externalEmail)
        {
            var clientUrl = $"{matterInformation.Client.Url}";

            try
            {
                string roleId = "";
                switch (permission.ToLower())
                {
                case "full control":
                    roleId = ((int)SPORoleIdMapping.FullControl).ToString();
                    break;

                case "contribute":
                    roleId = ((int)SPORoleIdMapping.Contribute).ToString();
                    break;

                case "read":
                    roleId = ((int)SPORoleIdMapping.Read).ToString();
                    break;
                }

                PeoplePickerUser peoplePickerUser = new PeoplePickerUser();
                peoplePickerUser.Key                 = externalEmail;
                peoplePickerUser.Description         = externalEmail;
                peoplePickerUser.DisplayText         = externalEmail;
                peoplePickerUser.EntityType          = "";
                peoplePickerUser.ProviderDisplayName = "";
                peoplePickerUser.ProviderName        = "";
                peoplePickerUser.IsResolved          = true;

                EntityData entityData = new EntityData();
                entityData.SPUserID         = externalEmail;
                entityData.Email            = externalEmail;
                entityData.IsBlocked        = "False";
                entityData.PrincipalType    = "UNVALIDATED_EMAIL_ADDRESS";
                entityData.AccountName      = externalEmail;
                entityData.SIPAddress       = externalEmail;
                peoplePickerUser.EntityData = entityData;

                string peoplePicker = Newtonsoft.Json.JsonConvert.SerializeObject(peoplePickerUser);
                peoplePicker = $"[{peoplePicker}]";
                string roleValue = $"role:{roleId}";

                bool sendEmail = true;

                bool   includeAnonymousLinkInEmail = false;
                bool   propagateAcl         = false;
                bool   useSimplifiedRoles   = true;
                string matterLandingPageUrl = $"{clientUrl}/sitepages/{matterInformation.Matter.MatterGuid + ServiceConstants.ASPX_EXTENSION}";
                string url          = matterLandingPageUrl;
                string emailBody    = $"The following information has been shared with you {matterInformation.Matter.Name}";
                string emailSubject = $"The following information has been shared with you {matterInformation.Matter.Name}";
                #region Doc Sharing API
                SharingResult sharingResult = null;
                using (var clientContext = spoAuthorization.GetClientContext(clientUrl))
                {
                    sharingResult = Microsoft.SharePoint.Client.Web.ShareObject(clientContext, url, peoplePicker, roleValue, 0, propagateAcl, sendEmail, includeAnonymousLinkInEmail, emailSubject, emailBody, useSimplifiedRoles);
                    clientContext.Load(sharingResult);
                    clientContext.ExecuteQuery();
                }
                return(null);

                #endregion
            }
            catch (Exception ex)
            {
                throw;
            }
        }
예제 #17
0
        /// <summary>
        /// Updates matter metadata - Stamps properties to the created matter.
        /// </summary>
        /// <param name="client">Client object containing Client data</param>
        /// <param name="details">Term Store object containing Term store data</param>
        /// <returns>Returns JSON object to the client</returns>        ///
        public IActionResult UpdateMetadata([FromBody] MatterMetdataVM matterMetdata)
        {
            string editMatterValidation = string.Empty;
            var    matter = matterMetdata.Matter;
            var    client = matterMetdata.Client;

            try
            {
                spoAuthorization.AccessToken = HttpContext.Request.Headers["Authorization"];
                #region Error Checking
                ErrorResponse errorResponse = null;
                if (matterMetdata.Client == null && matterMetdata.Matter == null &&
                    matterMetdata.MatterDetails == null && matterMetdata.MatterProvisionFlags == null)
                {
                    errorResponse = new ErrorResponse()
                    {
                        Message     = errorSettings.MessageNoInputs,
                        ErrorCode   = HttpStatusCode.BadRequest.ToString(),
                        Description = "No input data is passed"
                    };
                    return(matterCenterServiceFunctions.ServiceResponse(errorResponse, (int)HttpStatusCode.BadRequest));
                }
                #endregion

                #region Validations
                MatterInformationVM matterInfo = new MatterInformationVM()
                {
                    Client        = matterMetdata.Client,
                    Matter        = matterMetdata.Matter,
                    MatterDetails = matterMetdata.MatterDetails
                };
                GenericResponseVM genericResponse = validationFunctions.IsMatterValid(matterInfo,
                                                                                      int.Parse(ServiceConstants.ProvisionMatterUpdateMetadataForList),
                                                                                      matterMetdata.MatterConfigurations);
                if (genericResponse != null)
                {
                    matterProvision.DeleteMatter(client, matter);
                    errorResponse = new ErrorResponse()
                    {
                        Message   = genericResponse.Value,
                        ErrorCode = genericResponse.Code,
                    };
                    return(matterCenterServiceFunctions.ServiceResponse(errorResponse, (int)HttpStatusCode.BadRequest));
                }
                #endregion
                try
                {
                    genericResponse = matterProvision.UpdateMatterMetadata(matterMetdata);
                    if (genericResponse == null)
                    {
                        var result = new GenericResponseVM()
                        {
                            Code  = "200",
                            Value = "Update Success"
                        };
                        return(matterCenterServiceFunctions.ServiceResponse(result, (int)HttpStatusCode.OK));
                    }
                    return(matterCenterServiceFunctions.ServiceResponse(genericResponse, (int)HttpStatusCode.NotModified));
                }
                catch (Exception ex)
                {
                    matterProvision.DeleteMatter(client, matter);
                    customLogger.LogError(ex, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, logTables.SPOLogTable);
                    throw;
                }
            }
            catch (Exception ex)
            {
                customLogger.LogError(ex, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, logTables.SPOLogTable);
                throw;
            }
        }
예제 #18
0
        /// <summary>
        /// Updates matter
        /// </summary>
        /// <param name="client">Client object containing Client data</param>
        /// <param name="details">Term Store object containing Term store data</param>
        /// <returns>Returns JSON object to the client</returns>        ///
        public IActionResult Update([FromBody] MatterInformationVM matterInformation)
        {
            string editMatterValidation = string.Empty;
            var    matter = matterInformation.Matter;
            var    client = matterInformation.Client;
            var    userid = matterInformation.UserIds;

            try
            {
                spoAuthorization.AccessToken = HttpContext.Request.Headers["Authorization"];
                #region Error Checking
                ErrorResponse errorResponse = null;
                if (matterInformation.Client == null && matterInformation.Matter == null && matterInformation.MatterDetails == null)
                {
                    errorResponse = new ErrorResponse()
                    {
                        Message     = errorSettings.MessageNoInputs,
                        ErrorCode   = HttpStatusCode.BadRequest.ToString(),
                        Description = "No input data is passed"
                    };
                    return(matterCenterServiceFunctions.ServiceResponse(errorResponse, (int)HttpStatusCode.BadRequest));
                }
                #endregion

                #region Validations
                GenericResponseVM validationResponse = validationFunctions.IsMatterValid(matterInformation, int.Parse(ServiceConstants.EditMatterPermission), null);
                if (validationResponse != null)
                {
                    errorResponse = new ErrorResponse()
                    {
                        Message   = validationResponse.Value,
                        ErrorCode = validationResponse.Code,
                    };
                    return(matterCenterServiceFunctions.ServiceResponse(errorResponse, (int)HttpStatusCode.BadRequest));
                }

                if (null != matter.Conflict && !string.IsNullOrWhiteSpace(matter.Conflict.Identified))
                {
                    if (matter.AssignUserNames.Count == 0)
                    {
                        errorResponse = new ErrorResponse()
                        {
                            Message   = errorSettings.IncorrectInputUserNamesMessage,
                            ErrorCode = errorSettings.IncorrectInputUserNamesCode,
                        };
                        return(matterCenterServiceFunctions.ServiceResponse(errorResponse, (int)HttpStatusCode.BadRequest));
                    }
                    else
                    {
                        if (Convert.ToBoolean(matter.Conflict.Identified, CultureInfo.InvariantCulture))
                        {
                            validationResponse = editFunctions.CheckSecurityGroupInTeamMembers(client, matter, userid);
                            if (validationResponse != null)
                            {
                                errorResponse = new ErrorResponse()
                                {
                                    Message   = validationResponse.Value,
                                    ErrorCode = validationResponse.Code,
                                };
                                return(matterCenterServiceFunctions.ServiceResponse(errorResponse, (int)HttpStatusCode.BadRequest));
                            }
                        }
                    }
                }
                else
                {
                    errorResponse = new ErrorResponse()
                    {
                        Message   = errorSettings.IncorrectInputConflictIdentifiedMessage,
                        ErrorCode = errorSettings.IncorrectInputConflictIdentifiedCode,
                    };
                    return(matterCenterServiceFunctions.ServiceResponse(errorResponse, (int)HttpStatusCode.BadRequest));
                }
                #endregion

                #region Upadte Matter
                GenericResponseVM genericResponse = matterProvision.UpdateMatter(matterInformation);
                if (genericResponse == null)
                {
                    var result = new GenericResponseVM()
                    {
                        Code  = "200",
                        Value = "Update Success"
                    };
                    return(matterCenterServiceFunctions.ServiceResponse(result, (int)HttpStatusCode.OK));
                }
                else
                {
                    return(matterCenterServiceFunctions.ServiceResponse(genericResponse, (int)HttpStatusCode.NotModified));
                }

                #endregion
            }
            catch (Exception ex)
            {
                MatterRevertList matterRevertListObject = new MatterRevertList()
                {
                    MatterLibrary        = matterInformation.Matter.Name,
                    MatterOneNoteLibrary = matterInformation.Matter.Name + matterSettings.OneNoteLibrarySuffix,
                    MatterCalendar       = matterInformation.Matter.Name + matterSettings.CalendarNameSuffix,
                    MatterTask           = matterInformation.Matter.Name + matterSettings.TaskNameSuffix,
                    MatterSitePages      = matterSettings.MatterLandingPageRepositoryName
                };
                //editFunctions.RevertMatterUpdates(client, matter, matterRevertListObject, loggedInUserName, userPermissionOnLibrary, listItemId, isEditMode);
                customLogger.LogError(ex, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, logTables.SPOLogTable);
                throw;
            }
            finally
            {
            }
        }