Пример #1
0
        public async Task FileDeleteLogicFail()
        {
            var data  = new FakeApiDataEntityHandler <VisibleFile>();
            var logic = new FakeApiLogicHandler();
            var cloud = new FakeCloudHandler();

            var model = VisibleData.GetFirst();

            cloud.Result.Setup(m => m.Execute(It.IsAny <DeleteCmd>()))
            .Returns(ActionConfirm.CreateFailure(("Delete Failed")));

            var command = new FileDelete
            {
                DataHandler  = data,
                File         = model,
                CloudHandler = cloud,
                LogicHandler = logic
            };

            await command.Execute();

            cloud.HasExecuted.Should().BeTrue();

            data.HasExecuted.Should().BeFalse();
            data.HasCommitted.Should().BeFalse();
            data.Result.Verify(s => s.Execute(It.IsAny <Delete <VisibleFile> >()), Times.Never());
        }
Пример #2
0
        public async Task SimpleNotifyLogicSignupMissingTemplate()
        {
            var data  = new FakeApiDataEntityHandler <NotifyTemplate>();
            var logic = new FakeApiLogicHandler();
            var cloud = new FakeCloudHandler();

            var template = NotifyTemplateData.GetFirst();
            var tenant   = TenantData.GetFirst();

            data.Result.Setup(m => m.Execute(It.IsAny <NotifyTemplateByName>())).Returns(null);

            var command = new SimpleNotify
            {
                DataHandler  = data,
                CurrentUser  = StandardUser,
                TemplateName = "signup",
                CloudHandler = cloud,
                LogicHandler = logic,
                Model        = tenant,
                Result       = ActionConfirm.CreateFailure("It failed")
            };

            await command.Execute();

            command.Result.Success.Should().BeFalse();

            cloud.HasExecuted.Should().BeFalse();

            data.HasExecuted.Should().BeTrue();
            data.HasCommitted.Should().BeFalse();
            data.Result.Verify(s => s.Execute(It.IsAny <NotifyTemplateByName>()), Times.Once());
            data.Result.Verify(s => s.Execute(It.IsAny <Loader <Tenant> >()), Times.Never());
        }
Пример #3
0
        public async Task VisibleControllerDeleteFailed()
        {
            var data  = new VisibleApiDataHandler();
            var logic = new CoreApiLogicHandler();
            var model = VisibleData.GetFirst();

            data.Result.Setup(m => m.Execute(It.IsAny <Loader <VisibleFile> >())).Returns(model);

            logic.Result.Setup(m => m.Execute(It.IsAny <FileDelete>()))
            .Returns(ActionConfirm.CreateFailure("It went wrong"));

            var controller = new VisibleController(data, Cloud, logic)
            {
                CurrentUser = StandardUser
            };
            var result = await controller.Delete(VisibleData.FirstId) as OkObjectResult;

            result.Should().NotBeNull();
            result.Should().BeOfType <OkObjectResult>();

            var check = result.Value as ConfirmViewModel;

            check.Success.Should().BeFalse();

            logic.Result.Verify(s => s.Execute(It.IsAny <FileDelete>()), Times.Once());

            data.HasExecuted.Should().BeTrue();
            data.HasCommitted.Should().BeFalse();
            data.Result.Verify(s => s.Execute(It.IsAny <Loader <VisibleFile> >()), Times.Once);
        }
Пример #4
0
        public async Task SignupUserLogicMissingEntry()
        {
            var data  = new LoginDataHandler();
            var logic = new CoreApiLogicHandler();
            var cloud = new FakeCloudHandler();

            var viewModel = LoginData.GetSignup();

            data.Result.Setup(m => m.Execute(It.IsAny <Loader <Tenant> >())).Returns(null);

            var command = new SignupUser
            {
                DataHandler  = data,
                CloudHandler = cloud,
                LogicHandler = logic,
                Input        = viewModel,
                Result       = ActionConfirm.CreateFailure("Failed")
            };

            await command.Execute();

            command.Result.Success.Should().BeFalse();

            logic.HasExecuted.Should().BeFalse();
            logic.Result.Verify(s => s.Execute(It.IsAny <SimpleNotify>()), Times.Never());

            data.HasExecuted.Should().BeTrue();
            data.HasCommitted.Should().BeFalse();
            data.Result.Verify(s => s.Execute(It.IsAny <Loader <Tenant> >()), Times.Once());
            data.Result.Verify(s => s.Execute(It.IsAny <UserSave>()), Times.Never());
        }
Пример #5
0
        public override async Task Execute()
        {
            if (string.IsNullOrEmpty(SenderEmail))
            {
                SenderEmail = "*****@*****.**";
                SenderName  = "Crux";
            }

            var from       = new EmailAddress(SenderEmail, SenderName);
            var to         = new EmailAddress(RecipientEmail);
            var email      = MailHelper.CreateSingleEmail(from, to, Subject, BodyText, BodyHtml);
            var mailClient = new SendGridClient(Settings.Value.SendGridMailKey, Settings.Value.SendGridEndpoint);

            var response = await mailClient.SendEmailAsync(email);

            if (response.StatusCode == HttpStatusCode.Created || response.StatusCode == HttpStatusCode.OK ||
                response.StatusCode == HttpStatusCode.Accepted)
            {
                Result = ActionConfirm.CreateSuccess(response.StatusCode);
            }
            else
            {
                Result = ActionConfirm.CreateFailure(response.StatusCode.ToString());
            }
        }
Пример #6
0
        public async Task ProcessFileLogicFail()
        {
            var file = new FakeFile();

            var data  = new FakeApiDataEntityHandler <VisibleFile>();
            var logic = new CoreApiLogicHandler();
            var cloud = new FakeCloudHandler();

            logic.Result.Setup(m => m.Execute(It.IsAny <ProcessImage>()))
            .Returns(ActionConfirm.CreateFailure("Failed to Process"));

            var command = new ProcessFile
            {
                DataHandler  = data,
                Source       = file,
                CloudHandler = cloud,
                LogicHandler = logic,
                CurrentUser  = StandardUser
            };

            await command.Execute();

            cloud.HasExecuted.Should().BeFalse();
            logic.HasExecuted.Should().BeTrue();

            data.HasExecuted.Should().BeFalse();
            data.HasCommitted.Should().BeFalse();
            logic.Result.Verify(s => s.Execute(It.IsAny <ProcessImage>()), Times.Once());
        }
Пример #7
0
        public void ActionConfirmTestFailure()
        {
            var msg = ActionConfirm.CreateFailure("Message");

            msg.Message.Should().Be("Message");

            msg.Success.Should().BeFalse();
        }
Пример #8
0
        public override async Task Execute()
        {
            try
            {
                await base.Execute();

                var blob = Container.GetBlockBlobReference(Key.ToLower());
                await blob.DeleteAsync();

                Confirm = ActionConfirm.CreateSuccess(Key);
            }
            catch (Exception exception)
            {
                Confirm = ActionConfirm.CreateFailure(exception.Message);
            }
        }
Пример #9
0
        public override async Task Execute()
        {
            try
            {
                using (WebClient webClient = new WebClient())
                {
                    Data = new MemoryStream(await webClient.DownloadDataTaskAsync(new Uri(Url)));
                }

                Result = ActionConfirm.CreateSuccess(Url);
            }
            catch (Exception exception)
            {
                Result = ActionConfirm.CreateFailure(exception.Message);
            }
        }
Пример #10
0
        public async Task LoaderControllerGiphyFail()
        {
            var cloud = new FakeCloudHandler();

            cloud.Result.Setup(m => m.Execute(It.IsAny <GiphyCmd>()))
            .Returns(ActionConfirm.CreateFailure("Something went wrong"));

            var controller = new LoaderController(Data, cloud, Logic)
            {
                CurrentUser = StandardUser
            };
            var result = await controller.Gif(UserData.FirstId) as NotFoundResult;

            result.Should().NotBeNull();
            result.Should().BeOfType <NotFoundResult>();

            cloud.HasExecuted.Should().BeTrue();
        }
Пример #11
0
        public override async Task Execute()
        {
            TwilioClient.Init(Settings.Value.TwilioAccountSid, Settings.Value.TwilioAuthToken);

            try
            {
                var message = await MessageResource.CreateAsync(
                    body : Message,
                    from : new Twilio.Types.PhoneNumber(SenderPhone),
                    to : new Twilio.Types.PhoneNumber(RecipientPhone)
                    );

                Result = ActionConfirm.CreateSuccess(message.Sid);
            }
            catch (Exception e)
            {
                Result = ActionConfirm.CreateFailure(e.Message);
            }
        }
Пример #12
0
        public override async Task Execute()
        {
            var deleteThumb = new DeleteCmd {
                Key = File.ThumbKey, ContainerName = "thb"
            };
            await CloudHandler.Execute(deleteThumb);

            if (!deleteThumb.Confirm.Success)
            {
                Result = ActionConfirm.CreateFailure("Thumb blob failed to delete -> " + File.Id);
                return;
            }

            var delete = new DeleteCmd {
                Key = File.UrlKey
            };

            if (File.IsImage)
            {
                delete.ContainerName = "ful";
            }

            if (File.IsVideo)
            {
                delete.ContainerName = "vid";
            }

            if (File.IsDocument)
            {
                delete.ContainerName = "doc";
            }

            await CloudHandler.Execute(delete);

            var persist = new Delete <VisibleFile> {
                Id = File.Id
            };
            await DataHandler.Execute(persist);

            Result = ActionConfirm.CreateSuccess("File deleted");
        }
Пример #13
0
        public override async Task Execute()
        {
            try
            {
                await SourceContainerCmd.Execute();

                await DestContainerCmd.Execute();

                var source = SourceContainerCmd.Container.GetBlockBlobReference(SourceKey.ToLower());
                var dest   = DestContainerCmd.Container.GetBlockBlobReference(DestKey.ToLower());

                dest.Properties.ContentType = source.Properties.ContentType;
                await dest.StartCopyAsync(source);

                Confirm = ActionConfirm.CreateSuccess(DestKey.ToLower());
            }
            catch (Exception exception)
            {
                Confirm = ActionConfirm.CreateFailure(exception.Message);
            }
        }
Пример #14
0
        public async Task LoaderControllerUploadNotFound()
        {
            var data  = new VisibleApiDataHandler();
            var logic = new CoreApiLogicHandler();
            var model = VisibleData.GetFirst();

            logic.Result.Setup(m => m.Execute(It.IsAny <ProcessFile>()))
            .Returns(ActionConfirm.CreateFailure("Something went wrong"));

            var controller = new LoaderController(data, Cloud, logic)
            {
                CurrentUser = StandardUser
            };
            var result = await controller.Upload(VisibleData.GetFile()) as NotFoundResult;

            result.Should().NotBeNull();
            result.Should().BeOfType <NotFoundResult>();

            data.HasExecuted.Should().BeFalse();
            logic.HasExecuted.Should().BeTrue();
        }
Пример #15
0
        public override async Task Execute()
        {
            IProcessCommand processor = null;

            if (IsImage())
            {
                processor = new ProcessImage
                {
                    Source      = Source, CurrentUser = CurrentUser, LoadType = "File Upload", CloudHandler = CloudHandler,
                    DataHandler = DataHandler
                };
            }

            else if (IsVideo())
            {
            }

            else if (IsDocument())
            {
            }

            if (processor != null)
            {
                await LogicHandler.Execute(processor);

                if (processor.Result != null && processor.Result.Success)
                {
                    Model  = processor.Result.Value as VisibleFile;
                    Result = processor.Result;
                }
                else
                {
                    Result = ActionConfirm.CreateFailure("File " + Source.FileName + " -> failed to load");
                }
            }
            else
            {
                Result = ActionConfirm.CreateFailure("File " + Source.FileName + " -> type not supported");
            }
        }
Пример #16
0
        public override async Task Execute()
        {
            try
            {
                await base.Execute();

                var blob = Container.GetBlockBlobReference(Key.ToLower());

                blob.Properties.ContentType = ContentType;
                Data.Position = 0;

                await blob.UploadFromStreamAsync(Data);

                Url     = blob.Uri;
                Length  = blob.Properties.Length;
                Confirm = ActionConfirm.CreateSuccess(Key.ToLower());
            }
            catch (Exception exception)
            {
                Confirm = ActionConfirm.CreateFailure(exception.Message);
            }
        }
Пример #17
0
        public override async Task Execute()
        {
            try
            {
                var thumbKey = Guid.NewGuid().ToString().Replace("-", string.Empty).ToLower() +
                               Path.GetExtension(Source.FileName).ToLower();
                var fullKey = Guid.NewGuid().ToString().Replace("-", string.Empty).ToLower() +
                              Path.GetExtension(Source.FileName).ToLower();

                Model = new ImageFile
                {
                    TenantId    = CurrentUser.TenantId,
                    TenantName  = CurrentUser.TenantName,
                    AuthorId    = CurrentUser.Id,
                    AuthorName  = CurrentUser.Name,
                    RegionKey   = CurrentUser.RegionKey,
                    ContentType = Source.ContentType,
                    LoadType    = LoadType,
                    Name        = Source.FileName,
                    Extension   = Path.GetExtension(Source.FileName).ToLower(),
                    FullUrl     = CloudHandler.Settings.Value.MediaRoot + "ful/" + fullKey,
                    ThumbUrl    = CloudHandler.Settings.Value.MediaRoot + "thb/" + thumbKey,
                    ThumbKey    = thumbKey,
                    UrlKey      = fullKey
                };

                if (!string.IsNullOrEmpty(ExistingId))
                {
                    var existing = new Loader <ImageFile> {
                        Id = ExistingId
                    };
                    await DataHandler.Execute(existing);

                    if (existing.Result != null)
                    {
                        Model = existing.Result;

                        if (!string.IsNullOrEmpty(Model.ThumbKey))
                        {
                            thumbKey = Model.ThumbKey;
                        }
                        else
                        {
                            Model.ThumbKey = new Uri(Model.ThumbUrl).Segments.Last();
                        }

                        if (!string.IsNullOrEmpty(Model.UrlKey))
                        {
                            fullKey = Model.UrlKey;
                        }
                        else
                        {
                            Model.UrlKey = new Uri(Model.ThumbUrl).Segments.Last();
                        }
                    }
                }

                var mainUpload = new UploadCmd {
                    Key = fullKey, ContainerName = "ful"
                };
                var thumbUpload = new UploadCmd {
                    Key = thumbKey, ContainerName = "thb"
                };

                using (var stream = Source.OpenReadStream())
                {
                    var format = Image.DetectFormat(stream);
                    var image  = Image.Load(stream, out format);

                    Model.Width    = image.Width;
                    Model.Height   = image.Height;
                    Model.MimeType = Source.ContentType;

                    if (image.Width > 1920)
                    {
                        image = ResizeImageToWidth(image, 1920);
                    }

                    if (image.Height > 1920)
                    {
                        image = ResizeImageToHeight(image, 1920);
                    }

                    image.Save(mainUpload.Data, format);
                    image = ResizeImageToWidth(image);
                    image.Save(thumbUpload.Data, format);

                    image.Dispose();
                }

                await CloudHandler.Execute(mainUpload);

                await CloudHandler.Execute(thumbUpload);

                Model.Length = mainUpload.Length;

                var persist = new Persist <ImageFile> {
                    Model = Model
                };
                await DataHandler.Execute(persist);

                Result       = ActionConfirm.CreateSuccess("File " + Model.Name + " Loaded");
                Result.Value = persist.Model;
            }
            catch (Exception exception)
            {
                Result = ActionConfirm.CreateFailure(exception.Message);
            }
        }
Пример #18
0
        public override async Task Execute()
        {
            var options = new PushCreateOptions
            {
                AppId   = new Guid(Settings.Value.OneSignalAppId),
                Filters = new List <IPushFilter>(),
                Data    = new Dictionary <string, string>()
            };

            options.Data.Add(new KeyValuePair <string, string>("Action", Action));

            if (IncludeUser)
            {
                options.Filters.Add(new PushFilterField
                {
                    Key = "userId", Value = UserId, Field = "tag", Relation = "="
                });
            }

            foreach (var clientExclude in IncludeClients)
            {
                if (options.Filters.Any())
                {
                    options.Filters.Add(new PushFilterOperator {
                        Operator = "OR"
                    });
                }

                options.Filters.Add(new PushFilterField
                {
                    Key = "tenantId", Value = clientExclude.TenantId, Field = "tag", Relation = "="
                });

                foreach (var userId in clientExclude.ExcludedUsers)
                {
                    options.Filters.Add(new PushFilterOperator {
                        Operator = "AND"
                    });
                    options.Filters.Add(new PushFilterField
                    {
                        Key = "userId", Value = userId, Field = "tag", Relation = "!="
                    });
                }

                if (ExcludeUser && TenantId == clientExclude.TenantId)
                {
                    options.Filters.Add(new PushFilterOperator {
                        Operator = "AND"
                    });
                    options.Filters.Add(new PushFilterField
                    {
                        Key = "userId", Value = UserId, Field = "tag", Relation = "!="
                    });
                }
            }

            foreach (var userId in IncludeUsers)
            {
                if (!ExcludeUser || UserId != userId)
                {
                    if (options.Filters.Any())
                    {
                        options.Filters.Add(new PushFilterOperator {
                            Operator = "OR"
                        });
                    }

                    options.Filters.Add(new PushFilterField
                    {
                        Key = "userId", Value = userId, Field = "tag", Relation = "="
                    });
                }
            }

            if (!string.IsNullOrEmpty(Identity))
            {
                options.Data.Add(new KeyValuePair <string, string>("Identity", Identity));
            }

            if (!string.IsNullOrEmpty(Message))
            {
                options.Contents.Add("en", Message);
            }

            if (!string.IsNullOrEmpty(Title))
            {
                options.Headings = new Dictionary <string, string>
                {
                    { "en", Title }
                };
            }

            if (!string.IsNullOrEmpty(Url))
            {
                options.Url = Url;
            }

            RestClient  RestClient  = new RestClient(Settings.Value.OneSignalEndpoint);
            RestRequest restRequest = new RestRequest("notifications", Method.POST);

            restRequest.AddHeader("Authorization", string.Format("Basic {0}", Settings.Value.OneSignalClientKey));
            restRequest.RequestFormat  = DataFormat.Json;
            restRequest.JsonSerializer = new SimpleSerializer();
            restRequest.AddJsonBody(options);

            var restResponse = RestClient.Execute <PushCreateResult>(restRequest);

            if (!(restResponse.StatusCode != HttpStatusCode.Created || restResponse.StatusCode != HttpStatusCode.OK))
            {
                if (restResponse.ErrorException != null)
                {
                    throw restResponse.ErrorException;
                }
                else if (restResponse.StatusCode != HttpStatusCode.OK && restResponse.Content != null)
                {
                    throw new Exception(restResponse.Content);
                }
            }

            var result = restResponse.Data;

            if (!string.IsNullOrEmpty(result.Id))
            {
                Result = ActionConfirm.CreateSuccess("Notification successful " + result.Id);
            }
            else
            {
                Result = ActionConfirm.CreateFailure("Notification failed " + Identity);
            }

            await Task.CompletedTask;
        }
Пример #19
0
        public override async Task Execute()
        {
            var template = new NotifyTemplateByName {
                Name = TemplateName
            };
            await DataHandler.Execute(template);

            if (template.Result != null)
            {
                var tenant = new Loader <Tenant> {
                    Id = CurrentUser.TenantId
                };
                await DataHandler.Execute(tenant);

                var config = new Loader <UserConfig> {
                    Id = CurrentUser.ConfigId
                };
                await DataHandler.Execute(config);

                var processor = new TemplaterCmd();

                processor.Models.Add(CurrentUser);

                if (tenant.Result != null)
                {
                    processor.Models.Add(tenant.Result);
                }

                if (Model != null)
                {
                    processor.Models.Add(Model);
                }

                if (config.Result.EmailNotify)
                {
                    var email = new EmailTemplateCmd
                    {
                        Template       = template.Result,
                        RecipientEmail = CurrentUser.Email,
                        Processor      = processor
                    };

                    await CloudHandler.Execute(email);

                    EmailResult = email.Result;
                }

                if (config.Result.PushNotify)
                {
                    var push = new PushTemplateCmd()
                    {
                        IncludeUser = true,
                        TenantId    = CurrentUser.TenantId,
                        UserId      = CurrentUser.Id,
                        Template    = template.Result,
                        Processor   = processor,
                        Url         = ReturnUrl,
                        Identity    = ReturnIdentity
                    };

                    await CloudHandler.Execute(push);

                    PushResult = push.Result;
                }

                if (config.Result.SmsNotify)
                {
                    var sms = new SmsTemplateCmd()
                    {
                        RecipientPhone = CurrentUser.EncryptedPhone,
                        SenderPhone    = CloudHandler.Settings.Value.TwilioSenderPhone,
                        Template       = template.Result,
                        Processor      = processor
                    };

                    await CloudHandler.Execute(sms);

                    SmsResult = sms.Result;
                }

                Result = ActionConfirm.CreateSuccess("Notification Completed");
            }
            else
            {
                ActionConfirm.CreateFailure("Template Missing -> " + TemplateName);
            }
        }
Пример #20
0
        public override async Task Execute()
        {
            var regionKey = "GLA";
            var tenant    = new Tenant()
            {
                Name       = Input.TenantName, TenantName = Input.TenantName, EntryKey = StringHelper.GenerateCode(16),
                AuthorName = Input.Name, RegionKey = regionKey
            };
            var isNew = true;

            if (string.IsNullOrEmpty(Input.TenantId))
            {
                var persistClient = new Persist <Tenant>()
                {
                    Model = tenant
                };
                await DataHandler.Execute(persistClient);

                tenant = persistClient.Model;
            }
            else
            {
                var loaderClient = new Loader <Tenant>()
                {
                    Id = Input.TenantId
                };
                await DataHandler.Execute(loaderClient);

                tenant = loaderClient.Result;
                isNew  = false;
            }

            if (tenant != null && !string.IsNullOrEmpty(tenant.Id))
            {
                var user = new User()
                {
                    TenantId     = tenant.Id, TenantName = Input.TenantName, Name = Input.Name, Email = Input.Email,
                    EncryptedPwd = EncryptHelper.Encrypt(Input.Pwd), AuthorName = Input.Name,
                    Right        = new UserRight()
                    {
                        CanAuth = isNew, CanAdmin = isNew, CanSuperuser = false
                    },
                    RegionKey = regionKey
                };

                var persistUser = new UserSave {
                    Model = user
                };
                await DataHandler.Execute(persistUser);

                if (persistUser.Confirm.Success)
                {
                    if (isNew)
                    {
                        tenant.AuthorId = persistUser.Model.Id;
                        tenant.TenantId = tenant.Id;

                        var persistClient = new Persist <Tenant>()
                        {
                            Model = tenant
                        };
                        await DataHandler.Execute(persistClient);

                        tenant = persistClient.Model;

                        var meetingType = new MeetingType()
                        {
                            TenantId = tenant.Id, TenantName = tenant.Name, Name = "Standard", IsRecur = false,
                            Pretext  = "Standard Meeting Type", RegionKey = regionKey, Prename = "Meeting",
                            AuthorId = persistUser.Model.Id, AuthorName = persistUser.Model.Name
                        };
                        var persistType = new Persist <MeetingType>()
                        {
                            Model = meetingType
                        };
                        await DataHandler.Execute(persistType);
                    }

                    persistUser.Model.AuthorId = persistUser.Model.Id;
                    await DataHandler.Execute(persistUser);

                    await DataHandler.Commit();

                    var signin = new SigninAuth()
                    {
                        Tenant      = tenant, Login = persistUser.Model, LogicHandler = LogicHandler,
                        DataHandler = DataHandler, Config = persistUser.ResultConfig, Settings = CloudHandler.Settings
                    };
                    await LogicHandler.Execute(signin);

                    ResultAuth = signin.Result;

                    Result = ActionConfirm.CreateSuccess(persistUser.Model);

                    var notify = new SimpleNotify
                    {
                        CloudHandler = CloudHandler, DataHandler = DataHandler, CurrentUser = persistUser.Model,
                        LogicHandler = LogicHandler, Model = persistUser.Model,
                        TemplateName = isNew ? "welcomeclient" : "welcomeuser"
                    };
                    await LogicHandler.Execute(notify);
                }
                else
                {
                    Result = ActionConfirm.CreateFailure(persistUser.Confirm.Message);
                }
            }
            else
            {
                Result = ActionConfirm.CreateFailure("Error connecting organisation");
            }
        }