Exemple #1
0
        public async Task CompleteAddImageNote_ReturnsImageTooLarge()
        {
            // arrange
            var fakeBlobRepository = new FakeBlobRepository();
            var largeImageStream   = new MemoryStream();

            Fill(largeImageStream, 0, ImagesService.MaximumImageSize + 1);

            fakeBlobRepository.AddFakeBlob(ImagesService.FullImagesBlobContainerName, "fakeuserid/fakeid", largeImageStream);
            var mockImageValidatorService = new Mock <IImageValidatorService>();

            mockImageValidatorService
            .Setup(m => m.ValidateImage(It.IsAny <Stream>()))
            .Returns(new ValueTuple <bool, string>(true, ""));
            var service = new ImagesService(fakeBlobRepository, mockImageValidatorService.Object, new Mock <IImagePreviewService>().Object, new Mock <IImageCaptionService>().Object, new Mock <IEventGridPublisherService>().Object);

            // act
            var output = await service.CompleteAddImageNoteAsync("fakeid", "fakeuserid", "fakecategory");

            // assert
            Assert.Equal(CompleteAddImageNoteResult.ImageTooLarge, output.result);
        }
Exemple #2
0
        public async Task UpdateImageCaption_UpdatesImageCaption()
        {
            // arrange
            var fakeBlobRepository = new FakeBlobRepository();
            var fullImageBlob      = new CloudBlockBlob(new Uri("https://fakeblobrepository/fullimages/fakeuserid/fakeid"));

            fullImageBlob.Metadata[ImagesService.CaptionMetadataName] = "oldcaption";
            fakeBlobRepository.AddFakeBlob(ImagesService.FullImagesBlobContainerName, "fakeuserid/fakeid", fullImageBlob);
            fakeBlobRepository.AddFakeBlob(ImagesService.PreviewImagesBlobContainerName, "fakeuserid/fakeid");
            var mockImageCaptionService = new Mock <IImageCaptionService>();

            mockImageCaptionService
            .Setup(m => m.GetImageCaptionAsync(It.IsAny <byte[]>()))
            .ReturnsAsync("newcaption");
            var service = new ImagesService(fakeBlobRepository, new Mock <ImageValidatorService>().Object, new Mock <IImagePreviewService>().Object, mockImageCaptionService.Object, new Mock <IEventGridPublisherService>().Object);

            // act
            await service.UpdateImageNoteCaptionAsync("fakeid", "fakeuserid");

            // assert
            Assert.Equal("newcaption", fakeBlobRepository.Blobs.Single(b => b.ContainerName == ImagesService.FullImagesBlobContainerName).Blob.Metadata[ImagesService.CaptionMetadataName]);
        }
Exemple #3
0
        public async Task CompleteAddImageNote_UpdatesBlobMetadata()
        {
            // arrange
            var fakeBlobRepository = new FakeBlobRepository();

            fakeBlobRepository.AddFakeBlob(ImagesService.FullImagesBlobContainerName, "fakeuserid/fakeid");
            var mockImageValidatorService = new Mock <IImageValidatorService>();

            mockImageValidatorService
            .Setup(m => m.ValidateImage(It.IsAny <Stream>()))
            .Returns(new ValueTuple <bool, string>(true, ""));
            var service = new ImagesService(fakeBlobRepository, mockImageValidatorService.Object, new Mock <IImagePreviewService>().Object, new Mock <IImageCaptionService>().Object, new Mock <IEventGridPublisherService>().Object);

            // act
            await service.CompleteAddImageNoteAsync("fakeid", "fakeuserid", "fakecategory");

            // assert
            Assert.Equal("fakecategory",
                         fakeBlobRepository.Blobs.Single(b => b.ContainerName == ImagesService.FullImagesBlobContainerName).Blob.Metadata[ImagesService.CategoryIdMetadataName]);
            Assert.Equal("fakeuserid",
                         fakeBlobRepository.Blobs.Single(b => b.ContainerName == ImagesService.FullImagesBlobContainerName).Blob.Metadata[ImagesService.UserIdMetadataName]);
        }
Exemple #4
0
 protected void Page_Load(object sender, EventArgs e)
 {
     try
     {
         if (Page.RouteData.Values["GroupId"] != null)
         {
             GroupId = Page.RouteData.Values["GroupId"] as string;
         }
         if (!IsPostBack)
         {
             List <GroupImages> listGrp;
             if (GroupId != null)
             {
                 listGrp = GroupImagesService.GroupImages_GetByTop("", "Active=1", "Ord");
             }
             else
             {
                 listGrp = GroupImagesService.GroupImages_GetById(GroupId);
             }
             if (listGrp.Count > 0)
             {
                 groupName = listGrp[0].Name;
                 List <Data.Images> listImages = ImagesService.Images_GetByTop("", "Active = 1 AND GroupId = '" + listGrp[0].Id + "'", "Ord");
                 for (int i = 0; i < listImages.Count; i++)
                 {
                     ltrImages.Text += "<a href=#>\n";
                     ltrImages.Text += "<img alt='" + groupName + "'\n";
                     ltrImages.Text += "src='" + StringClass.ThumbImage(listImages[i].Image) + "'\n";
                     ltrImages.Text += "data-image='" + listImages[i].Image + "'\n";
                     ltrImages.Text += "style='display:none'></a>";
                 }
             }
         }
     }
     catch (Exception ex)
     {
         MailSender.SendMail("", "", "Error System", ex.Message + "\n" + ex.StackTrace);
     }
 }
        public void UpdateImage_ShouldReturn_Success()
        {
            // Arrange
            ImagesModel image = new ImagesModel
            {
                FileName     = "somefile.png",
                ProductId    = 1,
                LinkWebStore = "some weblink",
                LinkSupplier = "some suppliers link",
                LocalPath    = "some local path"
            };

            fakeImagesRepository.Setup(a => a.Update(image));
            imagesService = new ImagesService(fakeImagesRepository.Object, new Mock <ICommonRepository>().Object);

            ImagesDtoModel imageDto = new ImagesDtoModel
            {
                FileName     = image.FileName,
                ProductId    = image.ProductId,
                ProductName  = "Product name",
                LinkWebStore = image.LinkWebStore,
                LinkSupplier = image.LinkSupplier,
                LocalPath    = image.LocalPath
            };

            try
            {
                // Act
                imagesService.UpdateImage(imageDto);
                operationSucceeded = true;
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message + " | " + ex.StackTrace;
            }

            // Assert
            Assert.IsTrue(operationSucceeded, errorMessage);
        }
Exemple #6
0
        protected void grdImages_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            string strCA = e.CommandArgument.ToString();

            switch (e.CommandName)
            {
            case "Edit":
                Insert = false;
                Id     = strCA;
                List <Data.Images> listE = ImagesService.Images_GetById(Id);
                ddlGroupImage.SelectedValue = listE[0].GroupId;
                LoadDropDownListGroupImage();
                //PageHelper.LoadDropProPriority(ddlPriority);
                txtImage.Text     = listE[0].Image;
                imgImage.ImageUrl = listE[0].Image.Length > 0 ? listE[0].Image : "";
                PageHelper.LoadDropDownListLanguage(ddlLanguage);
                ddlLanguage.SelectedValue = listE[0].Language;
                txtOrd.Text       = listE[0].Ord;
                chkActive.Checked = listE[0].Active == "1" || listE[0].Active == "True";
                pnView.Visible    = false;
                pnUpdate.Visible  = true;
                break;

            case "Active":
                string strA = "";
                string str  = e.Item.Cells[2].Text;
                strA = str == "1" ? "0" : "1";
                SqlDataProvider sql = new SqlDataProvider();
                sql.ExecuteNonQuery("Update [Images] set Active=" + strA + "  Where Id='" + strCA + "'");
                BindGrid();
                break;

            case "Delete":
                ImagesService.Images_Delete(strCA);
                BindGrid();
                break;
            }
        }
Exemple #7
0
        public async Task CompleteAddImageNote_CreatesAndUploadsPreviewBlob()
        {
            // arrange
            var fakeBlobRepository = new FakeBlobRepository();

            fakeBlobRepository.AddFakeBlob(ImagesService.FullImagesBlobContainerName, "fakeuserid/fakeid");
            var mockImagePreviewService   = new Mock <IImagePreviewService>();
            var mockImageValidatorService = new Mock <IImageValidatorService>();

            mockImageValidatorService
            .Setup(m => m.ValidateImage(It.IsAny <Stream>()))
            .Returns(new ValueTuple <bool, string>(true, ""));
            var service = new ImagesService(fakeBlobRepository, mockImageValidatorService.Object, mockImagePreviewService.Object, new Mock <IImageCaptionService>().Object, new Mock <IEventGridPublisherService>().Object);

            // act
            await service.CompleteAddImageNoteAsync("fakeid", "fakeuserid", "fakecategory");

            // assert
            mockImagePreviewService.Verify(m =>
                                           m.CreatePreviewImage(It.IsAny <Stream>()),
                                           Times.Once);
            Assert.Contains(fakeBlobRepository.Blobs, f => f.ContainerName == ImagesService.PreviewImagesBlobContainerName);
            Assert.Equal("image/jpeg", fakeBlobRepository.Blobs.Single(b => b.ContainerName == ImagesService.PreviewImagesBlobContainerName).ContentType);
        }
Exemple #8
0
        public async Task CompleteAddImageNote_ReturnsImageAlreadyCreated()
        {
            // arrange
            var blob = new CloudBlockBlob(new Uri("https://fakeblobrepository/fullimages/fakeuserid/fakeid"));

            blob.Metadata.Add(ImagesService.CategoryIdMetadataName, "fakecategory");
            blob.Metadata.Add(ImagesService.UserIdMetadataName, "fakeuserid");
            var fakeBlobRepository = new FakeBlobRepository();

            fakeBlobRepository.AddFakeBlob(ImagesService.FullImagesBlobContainerName, "fakeuserid/fakeid", blob);
            var mockImagePreviewService   = new Mock <IImagePreviewService>();
            var mockImageValidatorService = new Mock <IImageValidatorService>();

            mockImageValidatorService
            .Setup(m => m.ValidateImage(It.IsAny <Stream>()))
            .Returns(new ValueTuple <bool, string>(true, ""));
            var service = new ImagesService(fakeBlobRepository, mockImageValidatorService.Object, mockImagePreviewService.Object, new Mock <IImageCaptionService>().Object, new Mock <IEventGridPublisherService>().Object);

            // act
            var output = await service.CompleteAddImageNoteAsync("fakeid", "fakeuserid", "fakecategory");

            // assert
            Assert.Equal(CompleteAddImageNoteResult.ImageAlreadyCreated, output.result);
        }
Exemple #9
0
        public async Task CompleteAddImageNote_PublishesImageCreatedEventToEventGrid()
        {
            // arrange
            var fakeBlobRepository = new FakeBlobRepository();

            fakeBlobRepository.AddFakeBlob(ImagesService.FullImagesBlobContainerName, "fakeuserid/fakeid");
            var mockImageValidatorService = new Mock <IImageValidatorService>();

            mockImageValidatorService
            .Setup(m => m.ValidateImage(It.IsAny <Stream>()))
            .Returns(new ValueTuple <bool, string>(true, ""));
            var mockEventGridPublisherService = new Mock <IEventGridPublisherService>();
            var service = new ImagesService(fakeBlobRepository, mockImageValidatorService.Object, new Mock <IImagePreviewService>().Object, new Mock <IImageCaptionService>().Object, mockEventGridPublisherService.Object);

            // act
            await service.CompleteAddImageNoteAsync("fakeid", "fakeuserid", "fakecategory");

            // assert
            mockEventGridPublisherService.Verify(m =>
                                                 m.PostEventGridEventAsync(EventTypes.Images.ImageCreated,
                                                                           "fakeuserid/fakeid",
                                                                           It.Is <ImageCreatedEventData>(d => d.Category == "fakecategory")),
                                                 Times.Once);
        }
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
            {
                byte[]         imageSize     = new byte [FileUpload1.PostedFile.ContentLength];
                HttpPostedFile uploadedImage = FileUpload1.PostedFile;
                uploadedImage.InputStream.Read
                    (imageSize, 0, (int)FileUpload1.PostedFile.ContentLength);

                int result = ImagesService.addNewImage((Guid)Membership.GetUser(User.Identity.Name, false).ProviderUserKey, imageSize);
                if (result > 0)
                {
                    photoAlert.Attributes.Add("class", "alert alert-success");
                    photoAlertText.InnerText = "Votre nouvelle photo de profil a bien été envoyée !";
                    ObjectDataSourceImage.Update();
                }
                else
                {
                    photoAlert.Attributes.Add("class", "alert alert-error");
                    photoAlertText.InnerText = "Une erreur s'est produite, le transfert à échoué.";
                }
                photoAlert.Visible = true;
            }
        }
Exemple #11
0
 public TeamsController(PlayersService playersService, ImagesService imagesService)
 {
     _playersService = playersService;
     _imagesService  = imagesService;
 }
 public ImagesController(ImagesService imagesService)
 {
     _imagesService = imagesService ?? throw new ArgumentNullException(nameof(imagesService));
 }
 public BooksController(AppDbContext dbContext, UserManager <User> userManager, ImagesService imagesService)
 {
     this.dbContext     = dbContext;
     this.userManager   = userManager;
     this.imagesService = imagesService;
 }
Exemple #14
0
 public ReactionImagesModule(IConfiguration config, UsersService usersService, ImagesService imagesService)
 {
     Config        = config;
     UsersService  = usersService;
     ImagesService = imagesService;
 }
 public Edit(IWebHostEnvironment env, Storage storage, ImagesService imagesService)
 {
     _env           = env;
     _storage       = storage;
     _imagesService = imagesService;
 }
Exemple #16
0
 public void TestGetImagesWithInvalidUrl(string url)
 {
     Assert.Throws <ArgumentNullException>(() => ImagesService.GetImages(url));
 }
Exemple #17
0
        public async Task RunAsync(params string[] args)
        {
            _log = LogManager.GetCurrentClassLogger();

            _log.Info("Starting NadekoBot v" + StatsService.BotVersion);

            //create client
            Client = new DiscordShardedClient(new DiscordSocketConfig
            {
                AudioMode         = Discord.Audio.AudioMode.Outgoing,
                MessageCacheSize  = 10,
                LogLevel          = LogSeverity.Warning,
                TotalShards       = Credentials.TotalShards,
                ConnectionTimeout = int.MaxValue,
#if !GLOBAL_NADEKO
                //AlwaysDownloadUsers = true,
#endif
            });

#if GLOBAL_NADEKO
            Client.Log += Client_Log;
#endif

            //initialize Services
            Localization   = new Localization(NadekoBot.BotConfig.Locale, NadekoBot.AllGuildConfigs.ToDictionary(x => x.GuildId, x => x.Locale));
            CommandService = new CommandService(new CommandServiceConfig()
            {
                CaseSensitiveCommands = false,
                DefaultRunMode        = RunMode.Sync
            });
            Google         = new GoogleApiService();
            CommandHandler = new CommandHandler(Client, CommandService);
            Stats          = new StatsService(Client, CommandHandler);
            Images         = await ImagesService.Create().ConfigureAwait(false);

            ////setup DI
            //var depMap = new DependencyMap();
            //depMap.Add<ILocalization>(Localizer);
            //depMap.Add<ShardedDiscordClient>(Client);
            //depMap.Add<CommandService>(CommandService);
            //depMap.Add<IGoogleApiService>(Google);


            //setup typereaders
            CommandService.AddTypeReader <PermissionAction>(new PermissionActionTypeReader());
            CommandService.AddTypeReader <CommandInfo>(new CommandTypeReader());
            CommandService.AddTypeReader <CommandOrCrInfo>(new CommandOrCrTypeReader());
            CommandService.AddTypeReader <ModuleInfo>(new ModuleTypeReader());
            CommandService.AddTypeReader <IGuild>(new GuildTypeReader());


            var sw = Stopwatch.StartNew();
            //connect
            await Client.LoginAsync(TokenType.Bot, Credentials.Token).ConfigureAwait(false);

            await Client.ConnectAsync().ConfigureAwait(false);

            //await Client.DownloadAllUsersAsync().ConfigureAwait(false);
            Stats.Initialize();

            sw.Stop();
            _log.Info("Connected in " + sw.Elapsed.TotalSeconds.ToString("F2"));

            //load commands and prefixes

            ModulePrefixes = new ConcurrentDictionary <string, string>(NadekoBot.BotConfig.ModulePrefixes.OrderByDescending(mp => mp.Prefix.Length).ToDictionary(m => m.ModuleName, m => m.Prefix));

            // start handling messages received in commandhandler

            await CommandHandler.StartHandling().ConfigureAwait(false);

            var _ = await Task.Run(() => CommandService.AddModulesAsync(this.GetType().GetTypeInfo().Assembly)).ConfigureAwait(false);

#if !GLOBAL_NADEKO
            await CommandService.AddModuleAsync <Music>().ConfigureAwait(false);
#endif
            Ready = true;
            Console.WriteLine(await Stats.Print().ConfigureAwait(false));
        }
        public async Task <CustomerProfileModel> GetCustomerProfile(string business_id, string id)
        {
            try
            {
                List <System.Threading.Tasks.Task> tasks = new List <System.Threading.Tasks.Task>();
                CustomerProfileModel model = new CustomerProfileModel();
                //var key = "GetCustomerProfile" + business_id + id;
                //var lst = await CacheBase.cacheManagerGet<CustomerProfileModel>(key);
                //if (lst != null)
                //    return lst;
                Customer            c       = null;
                FacebookUserProfile profile = null;
                var    date1  = DateTime.UtcNow;
                Thread thread = null;
                //tasks.Add(System.Threading.Tasks.Task.Factory.StartNew(() =>
                //{
                c = _customerService.GetById(business_id, id);
                if (c == null)
                {
                    thread = _threadService.GetById(business_id, id);
                    if (thread != null)
                    {
                        c = _customerService.GetById(business_id, thread.customer_id);
                    }
                }
                //}));

                //System.Threading.Tasks.Task.WaitAll(tasks.ToArray());

                if (c == null)
                {
                    return(model);
                }
                if (c != null)
                {
                    if (c.active_thread == null)
                    {
                        thread = _threadService.GetByIdFromCustomerId(business_id, c.id);
                        if (thread != null)
                        {
                            c.active_thread = JsonConvert.SerializeObject(thread);
                            System.Threading.Tasks.Task.Factory.StartNew(() =>
                            {
                                _customerService.CreateCustomer(c, false);
                            });
                        }
                    }
                }

                var sp             = c.channel_id.Split('_');
                var channel_ext_id = sp[sp.Length - 1];

                #region lay ten that neu da tao don hang
                if (string.IsNullOrWhiteSpace(c.real_name))
                {
                    c.real_name = c.name;
                    _customerService.UpdateRealName(c.business_id, c.id, c.name);
                }
                if (c.real_name == c.name && !string.IsNullOrWhiteSpace(c.phone))
                {
                    try
                    {
                        System.Threading.Tasks.Task.Factory.StartNew(() =>
                        {
                            var uri    = _appSettings.Value.BaseUrls.ApiOrder + "api/order/list?logonId=" + c.phone + "&imei=&token=@bazavietnam";
                            var orders = Core.Helpers.WebHelper.HttpGetAsyncSting(uri).Result;
                            if (orders.Length > 10)
                            {
                                var orderBs   = JsonConvert.DeserializeObject(orders);
                                var array     = (JArray)orderBs;
                                var orderItem = array[array.Count - 1];
                                {
                                    if (orderItem["OrderId"].ToString() != "")
                                    {
                                        var urlDetail   = _appSettings.Value.BaseUrls.ApiOrder + "api/order/detail2?id=" + orderItem["OrderId"] + "&logonId=" + c.phone + "&imei=&token=@bazavietnam";
                                        var orderDetail = Core.Helpers.WebHelper.HttpGetAsyncSting(urlDetail).Result;

                                        var obj = JsonConvert.DeserializeObject <JToken>(orderDetail);
                                        if (obj != null)
                                        {
                                            var real_name = (string)obj["Fullname"];
                                            if (!string.IsNullOrWhiteSpace(real_name))
                                            {
                                                _customerService.UpdateRealName(c.business_id, c.id, real_name);
                                            }
                                        }
                                    }
                                }
                            }
                        });
                    }
                    catch (Exception ex) { }
                }
                #endregion

                var customer = new CustomerModel(c);

                var customer_id1 = "";
                var customer_id2 = customer.id;
                model.id          = customer.id;
                model.customer_id = customer.id;

                if (string.IsNullOrWhiteSpace(customer.sex) || (!string.IsNullOrWhiteSpace(customer.avatar) && customer.avatar.IndexOf(_appSettings.Value.BaseUrls.ApiSaveImage) < 0))
                {
                    tasks.Add(System.Threading.Tasks.Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            var channel = _channelService.GetById(business_id, customer.channel_id);
                            profile     = _facebookConversationService.GetProfile(customer.active_thread.ext_id, channel.token);
                            if (profile != null && !string.IsNullOrWhiteSpace(profile.sex))
                            {
                                c.sex = profile.sex;
                                if (string.IsNullOrWhiteSpace(customer.avatar) || (!string.IsNullOrWhiteSpace(customer.avatar) && customer.avatar.IndexOf(_appSettings.Value.BaseUrls.ApiSaveImage) < 0))
                                {
                                    c.avatar = ImagesService.UpsertImageStore(profile.avatar, _appSettings.Value).Result;
                                }
                                _customerService.CreateCustomer(c, false);
                            }
                        }
                        catch { }
                    }));
                }

                tasks.Add(System.Threading.Tasks.Task.Factory.StartNew(() =>
                {
                    model.referrals = new List <ReferralModel>();
                    if (!string.IsNullOrWhiteSpace(customer_id1))
                    {
                        foreach (var item in _referralService.GetReferralsByCustomer(business_id, customer_id1, new Paging {
                            Limit = 5
                        }).Result)
                        {
                            model.referrals.Add(new ReferralModel(item));
                        }
                    }
                    if (customer_id2 != customer_id1 && !string.IsNullOrWhiteSpace(customer_id2))
                    {
                        foreach (var item in _referralService.GetReferralsByCustomer(business_id, customer_id2, new Paging {
                            Limit = 5
                        }).Result)
                        {
                            model.referrals.Add(new ReferralModel(item));
                        }
                        model.referrals = model.referrals.OrderByDescending(r => r.created_time).Take(5).ToList();
                    }
                }));
                tasks.Add(System.Threading.Tasks.Task.Factory.StartNew(() =>
                {
                    model.id                   = id;
                    model.name                 = customer.name;
                    model.blocked              = customer.blocked;
                    model.phone                = !string.IsNullOrWhiteSpace(customer.phone) ? customer.phone : "";
                    model.avatar               = customer.avatar != null && customer.avatar.IndexOf("http://") < 0 && customer.avatar.IndexOf("https://") < 0 ? _appSettings.Value.BaseUrls.Api + customer.avatar : customer.avatar;
                    model.profile_ext_url      = "/customers/openprofile/" + business_id + "/" + id;
                    model.openlink             = "/" + business_id + "/messages/openlink/?thread_id=" + customer.active_thread.id;
                    model.last_contacted_since = Core.Helpers.CommonHelper.UnixTimestampToDateTime(customer.timestamp).ToLocalTime().ToString("dd/MM/yyyy");
                    model.last_visits          = customer.active_thread.last_visits;
                    model.sex                  = !string.IsNullOrWhiteSpace(customer.sex) ? customer.sex : "";
                    model.weight               = customer.weight;
                    model.height               = customer.height;
                    model.address              = !string.IsNullOrWhiteSpace(customer.address) ? customer.address : "";
                    model.phone_list           = c.phone_list;
                }));

                tasks.Add(System.Threading.Tasks.Task.Factory.StartNew(() =>
                {
                    model.notes = new List <NoteModel>();
                    if (!string.IsNullOrWhiteSpace(customer_id1))
                    {
                        foreach (var item in _noteService.GetCustomerNotes(business_id, customer_id1, new Paging {
                            Limit = 10
                        }))
                        {
                            model.notes.Add(new NoteModel(item));
                        }
                    }
                    if (customer_id2 != customer_id1 && !string.IsNullOrWhiteSpace(customer_id2))
                    {
                        foreach (var item in _noteService.GetCustomerNotes(business_id, customer_id2, new Paging {
                            Limit = 10
                        }))
                        {
                            model.notes.Add(new NoteModel(item));
                        }
                        model.notes = model.notes.OrderByDescending(n => n.created_time).Take(10).ToList();
                    }
                }));

                tasks.Add(System.Threading.Tasks.Task.Factory.StartNew(() =>
                {
                    model.tickets = new List <TicketModel>();
                    if (!string.IsNullOrWhiteSpace(customer_id1))
                    {
                        foreach (var item in _ticketService.GetCustomerTickets(business_id, customer_id1, new Paging {
                            Limit = 10
                        }))
                        {
                            model.tickets.Add(new TicketModel(item));
                        }
                    }
                    if (customer_id2 != customer_id1 && !string.IsNullOrWhiteSpace(customer_id2))
                    {
                        foreach (var item in _ticketService.GetCustomerTickets(business_id, customer_id2, new Paging {
                            Limit = 10
                        }))
                        {
                            model.tickets.Add(new TicketModel(item));
                        }
                        model.tickets = model.tickets.OrderByDescending(t => t.created_time).Take(10).ToList();
                    }
                }));

                tasks.Add(System.Threading.Tasks.Task.Factory.StartNew(() =>
                {
                    model.starred_messages = new List <MessageModel>();
                    if (!string.IsNullOrWhiteSpace(customer_id1))
                    {
                        foreach (var item in _messageService.GetStarredMesagesByCustomer(business_id, new Paging {
                            Limit = 10
                        }, customer_id1).Result)
                        {
                            model.starred_messages.Add(new MessageModel(item));
                        }
                    }

                    if (customer_id2 != customer_id1 && !string.IsNullOrWhiteSpace(customer_id2))
                    {
                        foreach (var item in _messageService.GetStarredMesagesByCustomer(business_id, new Paging {
                            Limit = 10
                        }, customer_id2).Result)
                        {
                            model.starred_messages.Add(new MessageModel(item));
                        }
                        model.starred_messages = model.starred_messages.OrderByDescending(m => m.timestamp).Take(10).ToList();
                    }
                }));


                tasks.Add(System.Threading.Tasks.Task.Factory.StartNew(() =>
                {
                    model.last_messages = new List <MessageModel>();
                    if (!string.IsNullOrWhiteSpace(customer_id1))
                    {
                        foreach (var item in _messageService.GetByCustomerExcludeCurrentThread(business_id, customer_id1, channel_ext_id, new Paging {
                            Limit = 10, Next = "9999999999"
                        }).Result)
                        {
                            item.sender_name = item.sender_ext_id == item.channel_ext_id ? item.sender_name : customer.name;
                            model.last_messages.Add(new MessageModel(item));
                        }
                    }

                    if (customer_id2 != customer_id1 && !string.IsNullOrWhiteSpace(customer_id2))
                    {
                        foreach (var item in _messageService.GetByCustomerExcludeCurrentThread(business_id, customer_id2, channel_ext_id, new Paging {
                            Limit = 10, Next = "9999999999"
                        }).Result)
                        {
                            item.sender_name = item.sender_ext_id == item.channel_ext_id ? item.sender_name : customer.name;
                            model.last_messages.Add(new MessageModel(item));
                        }
                        model.last_messages = model.last_messages.OrderByDescending(m => m.timestamp).Take(10).ToList();
                    }
                }));

                System.Threading.Tasks.Task.WaitAll(tasks.ToArray());
                model.sex    = string.IsNullOrWhiteSpace(model.sex) && profile != null && !string.IsNullOrWhiteSpace(profile.sex) ? profile.sex : model.sex;
                model.avatar = string.IsNullOrWhiteSpace(model.avatar) && profile != null && !string.IsNullOrWhiteSpace(profile.avatar) ? profile.avatar : model.avatar;

                //  CacheBase.cacheManagerSetForProceduce(key, model, DateTime.Now.AddMinutes(10), null, null, false);
                return(model);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Exemple #19
0
 public UselessController(MessagesServiceFactory messagesServiceFactory, ImagesService imageService)
 {
     this._messagesServiceFactory = messagesServiceFactory;
     this._imagesService          = imageService;
 }
 public ProductosController(LicoreriaService repo, ImagesService imagesService)
 {
     this.repo          = repo;
     this.ImagesService = imagesService;
 }
        private static IImagesService InitializeService(EfDeletableEntityRepository <Image> imageRepo, EfDeletableEntityRepository <ImageType> imageTypeRepo)
        {
            var service = new ImagesService(imageRepo, imageTypeRepo);

            return(service);
        }
Exemple #22
0
 public ImagesServiceTest()
 {
     _imageService = new ImagesService();
 }
Exemple #23
0
 public ImagesController(IRepository <Picture> pictures, IRepository <CategoryPictures> categories)
 {
     this.pictures   = pictures;
     this.categories = categories;
     this.service    = new ImagesService();
 }
 public KerykeionImagesService(EntitiesService service,
                               ImagesService imagesService) : base(service)
 {
     _imagesService = imagesService;
 }
Exemple #25
0
 public void TestSaveImagesWithInvaledDto()
 {
     Assert.Throws <ArgumentNullException>(() => ImagesService.SaveImages(null));
     Assert.Throws <ArgumentNullException>(() => ImagesService.SaveImages(new ImageDto[] { }));
 }
        public async Task PostsSeederShouldWork()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "PostsSeederShouldWork").Options;
            var dbContext = new ApplicationDbContext(options);

            // Repos
            var postsRepository             = new EfDeletableEntityRepository <Post>(dbContext);
            var categoriesRepository        = new EfDeletableEntityRepository <Category>(dbContext);
            var vehicleCategoriesRepository = new EfDeletableEntityRepository <VehicleCategory>(dbContext);
            var colorsRepository            = new EfDeletableEntityRepository <Color>(dbContext);
            var makesRepository             = new EfDeletableEntityRepository <Make>(dbContext);
            var modelsRepository            = new EfDeletableEntityRepository <Model>(dbContext);
            var citiesRepository            = new EfDeletableEntityRepository <City>(dbContext);
            var imagesRepository            = new EfDeletableEntityRepository <Image>(dbContext);

            // Setups
            var serviceProvider = new Mock <IServiceProvider>();
            var makesService    = new MakesService(makesRepository);
            var imagesService   = new ImagesService(imagesRepository);

            var userManager = this.GetUserManager(dbContext);

            Account cloudinaryCredentials = new Account(
                this.Configuration["Cloudinary:CloudName"],
                this.Configuration["Cloudinary:ApiKey"],
                this.Configuration["Cloudinary:ApiSecret"]);
            Cloudinary cloudinary = new Cloudinary(cloudinaryCredentials);

            await userManager.CreateAsync(new ApplicationUser()
            {
                UserName = "******"
            });

            serviceProvider
            .Setup(x => x.GetService(typeof(ICloudinaryService)))
            .Returns(new CloudinaryService(cloudinary, imagesService));
            serviceProvider
            .Setup(x => x.GetService(typeof(IPostsService)))
            .Returns(new PostsService(postsRepository, makesService));
            serviceProvider
            .Setup(x => x.GetService(typeof(ICategoriesService)))
            .Returns(new CategoriesService(categoriesRepository));
            serviceProvider
            .Setup(x => x.GetService(typeof(IVehicleCategoriesService)))
            .Returns(new VehicleCategoriesService(vehicleCategoriesRepository));
            serviceProvider
            .Setup(x => x.GetService(typeof(IColorService)))
            .Returns(new ColorService(colorsRepository));
            serviceProvider
            .Setup(x => x.GetService(typeof(ICategoriesService)))
            .Returns(new CategoriesService(categoriesRepository));
            serviceProvider
            .Setup(x => x.GetService(typeof(IMakesService)))
            .Returns(makesService);
            serviceProvider
            .Setup(x => x.GetService(typeof(IModelsService)))
            .Returns(new ModelsService(modelsRepository));
            serviceProvider
            .Setup(x => x.GetService(typeof(ICitiesService)))
            .Returns(new CitiesService(citiesRepository));
            serviceProvider
            .Setup(x => x.GetService(typeof(IImagesService)))
            .Returns(imagesService);
            serviceProvider
            .Setup(x => x.GetService(typeof(UserManager <ApplicationUser>)))
            .Returns(userManager);

            // Categories
            var categoriesSeeder = new CategorySeeder();
            await categoriesSeeder.SeedAsync(dbContext, serviceProvider.Object);

            // Vehicle cateogories
            var vehicleCategoriesSeeder = new VehicleCategorySeeder();
            await vehicleCategoriesSeeder.SeedAsync(dbContext, serviceProvider.Object);

            // Colors
            var colorsSeeder = new ColorSeeder();
            await colorsSeeder.SeedAsync(dbContext, serviceProvider.Object);

            // Makes
            var makesSeeder = new MakesSeeder();
            await makesSeeder.SeedAsync(dbContext, serviceProvider.Object);

            // Models
            var modelsSeeder = new ModelsSeeder();
            await modelsSeeder.SeedAsync(dbContext, serviceProvider.Object);

            // Cities
            var citiesSeeder = new CitiesSeeder();
            await citiesSeeder.SeedAsync(dbContext, serviceProvider.Object);

            // Posts
            var postsSeeder = new PostsSeeder();
            await postsSeeder.SeedAsync(dbContext, serviceProvider.Object);

            Assert.NotEmpty(dbContext.Posts);
        }
Exemple #27
0
        public async Task <ApiResponse> Send([FromForm] MessageFormData form)
        {
            Hibaza.CCP.Data.Common _cm = new Hibaza.CCP.Data.Common();
            var para    = JsonConvert.DeserializeObject <dynamic>(form.para);
            var channel = _channelService.GetById(form.business_id, form.channel_id);

            #region luu hinh anh den server rieng
            try
            {
                if (form.channel_format == "image-text" || form.channel_format == "image" || form.channel_format == "receipt")
                {
                    if (para.message != null && para.message.attachment != null && para.message.attachment.payload != null && para.message.attachment.payload.elements != null)
                    {
                        List <payloadFb> elements = JsonConvert.DeserializeObject <List <payloadFb> >(JsonConvert.SerializeObject(para.message.attachment.payload.elements));
                        for (var i = 0; i < elements.Count; i++)
                        {
                            try
                            {
                                if (!string.IsNullOrWhiteSpace(elements[i].image_url))
                                {
                                    var newImageUrl = await ImagesService.UpsertImageStore(elements[i].image_url, _appSettings.Value);

                                    para.message.attachment.payload.elements[i].image_url          = newImageUrl;
                                    para.message.attachment.payload.elements[i].default_action.url = newImageUrl;
                                }
                            }
                            catch (Exception ex) { }
                        }
                    }

                    #region file attachment
                    // var data = new MessageData { images = new List<MessageFile>() };
                    var files = Request.Form.Files;
                    var j     = 0;
                    if (files.Count > 0)
                    {
                        foreach (var file in files)
                        {
                            if (file.Length > 0)
                            {
                                var fileName = ContentDispositionHeaderValue
                                               .Parse(file.ContentDisposition)
                                               .FileName.ToString();
                                fileName = Core.Helpers.CommonHelper.removeSpecialFile(fileName);

                                var fileId = "";
                                if ((form.thread_id + fileName).Length < 100)
                                {
                                    fileId = form.thread_id + "_" + Core.Helpers.CommonHelper.GenerateDigitUniqueNumber() + "_" + fileName;
                                }
                                else
                                {
                                    fileId = form.thread_id + "_" + fileName;
                                }
                                // var path = Path.Combine(Directory.GetCurrentDirectory(), @"Documents", "Attachments", fileId);
                                var dir      = Path.Combine(Directory.GetCurrentDirectory(), _appSettings.Value.PathToFileDocuments);
                                var fullName = Path.Combine(dir, fileId);

                                if (!Directory.Exists(dir))
                                {
                                    Directory.CreateDirectory(dir);
                                }

                                using (FileStream fs = System.IO.File.Create(fullName))
                                {
                                    file.CopyTo(fs);
                                    fs.Flush();
                                }
                                var bytes  = _cm.ConvertToBytes(file);
                                var newUrl = await _cm.HtmlPostBytesAsync <string>(_appSettings.Value.BaseUrls.ApiSaveImage
                                                                                   + "api/UploadFile", form.thread_id + "_" + file.FileName, bytes);

                                var elements = JsonConvert.DeserializeObject <List <payloadFb> >(JsonConvert.SerializeObject(para.message.attachment.payload.elements));

                                para.message.attachment.payload.elements[j].image_url = newUrl;
                                para.message.attachment.payload.elements[j].title     = para.message.attachment.payload.elements[j].title == "" ?
                                                                                        channel.name : para.message.attachment.payload.elements[j].title;
                                para.message.attachment.payload.elements[j].default_action.url = newUrl;
                                j++;

                                //var bytes = _cm.ConvertToBytes(file);
                                //var newUrl = await _cm.HtmlPostBytesAsync<string>(_appSettings.Value.BaseUrls.ApiSaveImage
                                //    + "File_DocumentsView/UploadFile", thread.id + "_" + file.FileName, bytes);

                                //var elements = JsonConvert.DeserializeObject<List<payloadFb>>(JsonConvert.SerializeObject(para.message.attachment.payload.elements));

                                //para.message.attachment.payload.elements[j].image_url = newUrl;
                                //para.message.attachment.payload.elements[j].default_action.url = newUrl;
                                //para.message.attachment.payload.elements[j].title = para.message.attachment.payload.elements[j].title == "" ?
                                //    channel.name : para.message.attachment.payload.elements[j].title;
                                //j++;
                            }
                        }
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            #endregion
            // _logService.Create(new Log { name = "send zalo ", message = "", details = JsonConvert.SerializeObject(para).ToString() });
            return(await _zaloService.SendMessage(para, channel, form));
        }
Exemple #28
0
 public ImagesController(mini_unsplash_cloneContext context, ImagesService imagesService)
 {
     _context           = context;
     this.imagesService = imagesService;
 }
 public Add(Storage storage, ImagesService imagesService)
 {
     _storage       = storage;
     _imagesService = imagesService;
 }
Exemple #30
0
        public ApiResponse RegisterAdmin([FromForm] Agent agent)
        {
            ApiResponse response = new ApiResponse();

            if (string.IsNullOrWhiteSpace(agent.password))
            {
                response.msg = "Password not provided";
                return(response);
            }

            if (agent.password != agent.password_confirmation)
            {
                response.msg = "Passwords are mismatched";
                return(response);
            }
            agent.name          = string.IsNullOrWhiteSpace(agent.name) ? agent.last_name + " " + agent.first_name : agent.name;
            agent.business_name = agent.business_name ?? "";
            agent.business_name = agent.business_name.Trim();
            if (string.IsNullOrWhiteSpace(agent.business_name))
            {
                response.msg = "Business name required";
                return(response);
            }

            agent.email = agent.email ?? "";
            agent.email = agent.email.Trim().ToLower();
            if (string.IsNullOrWhiteSpace(agent.email) || !agent.email.Contains("@"))
            {
                response.msg = "Invalid email address";
                return(response);
            }
            if (!string.IsNullOrWhiteSpace(agent.facebook_access_token))
            {
                try
                {
                    var uri = "https://graph.facebook.com/v2.10/me?fields=id,name,email,age_range,first_name,gender,last_name,picture{url},birthday,address&access_token=" + agent.facebook_access_token;
                    var c   = Core.Helpers.WebHelper.HttpGetAsync <JObject>(uri).Result;
                    if (c != null && c["id"] != null)
                    {
                        agent.ext_id = (string)c["id"];
                        if (c["picture"] != null && c["picture"]["data"] != null && c["picture"]["data"]["url"] != null)
                        {
                            var imageUrl = ImagesService.UpsertImageStore((string)c["picture"]["data"]["url"], _appSettings.Value).Result;
                            agent.avatar = imageUrl;
                        }
                    }
                }
                catch (Exception ex) { }
            }
            var business = new Business
            {
                name   = agent.business_name,
                type   = "company",
                active = true,
                logo   = agent.avatar,
                email  = agent.email,
                ext_id = agent.ext_id,
                token  = agent.facebook_access_token
            };

            var businessCheck = _businessService.GetByEmail(agent.email);

            if (businessCheck == null || businessCheck.id == null)
            {
                agent.business_id = _businessService.Create(business);
            }
            else
            {
                agent.business_id = businessCheck.id;
            }
            agent.username     = agent.email;
            agent.login_status = "offline";
            agent.active       = true;
            agent.status       = "offline";
            agent.role         = "admin";

            //add hotline demo
            try
            {
                var uri  = _appSettings.Value.BaseUrls.ApiHotline + "api/PhoneAccounts/PhoneAccountNotUsingDemo";
                var obj  = Core.Helpers.WebHelper.HttpGetAsync <dynamic>(uri).Result;
                var bson = Core.Helpers.CommonHelper.JsonToBsonDocument((string)obj);
                foreach (var item in bson)
                {
                    agent.phone_account_id = item.Name;
                    break;
                }
            }
            catch (Exception ex) { }

            response.ok  = true;
            response.msg = agent.business_id;
            try
            {
                var current = _agentService.GetSingleOrDefaultByUserName(agent.username);
                if (current == null)
                {
                    response.data = _agentService.Create(agent);
                }
            }
            catch (Exception ex)
            {
                response.msg = ex.Message;
                throw ex;
            }

            return(response);
        }