Ejemplo n.º 1
0
        public ApiRajaOngkirTrackingDto Tracking(GetTrackingInputDto inputDto)
        {
            using (var client = new HttpClient())
            {
                var url    = AppSettingConfigurationHelper.GetSection("APIUrlRajaOngkir").Value;
                var apiKey = AppSettingConfigurationHelper.GetSection("APIKeyRajaOngkir").Value;
                client.BaseAddress = new Uri(url);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("key", apiKey);

                var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair <string, string>("waybill", inputDto.AirWayBill),
                    new KeyValuePair <string, string>("courier", inputDto.ExpeditionService.Expedition.RajaOngkirCode.ToLower())
                });

                HttpResponseMessage response = client.PostAsync("waybill", content).Result;

                var    resultString = AsyncHelper.RunSync(() => response.Content.ReadAsStringAsync());
                JToken token        = JObject.Parse(resultString);

                if ((string)token.SelectToken("rajaongkir").SelectToken("status").SelectToken("description") != HttpStatusCode.OK.ToString())
                {
                    throw new HozaruException((string)token.SelectToken("rajaongkir").SelectToken("status").SelectToken("description"));
                }

                var result = token.SelectToken("rajaongkir").SelectToken("result");
                return(result.ToObject <ApiRajaOngkirTrackingDto>());
            }
        }
Ejemplo n.º 2
0
        public static void SendMessage(string phone, string message)
        {
            if (Convert.ToBoolean(AppSettingConfigurationHelper.GetSection("SendWhatsapp").Value))
            {
                var domainAPI = AppSettingConfigurationHelper.GetSection("Wablas").GetSection("DomainAPI").Value;
                var token     = AppSettingConfigurationHelper.GetSection("Wablas").GetSection("Token").Value;

                using (var httpClient = new HttpClient())
                {
                    httpClient.BaseAddress = new Uri(domainAPI);
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token);

                    var data = new
                    {
                        phone   = phone,
                        message = message
                    };
                    var dataJson = Newtonsoft.Json.JsonConvert.SerializeObject(data);

                    var content = new StringContent(dataJson, Encoding.UTF8, "application/json");

                    var response = httpClient.PostAsync("/api/send-message", content).Result;
                    if (!response.IsSuccessStatusCode)
                    {
                        var logger = IocManager.Instance.Resolve <ILogger>();
                        logger.ErrorFormat("Failed send Whatstapp {0} with message: {1}. Error Message: {2}", phone, message, response.Content.ReadAsStringAsync().Result);
                    }
                }
            }
        }
Ejemplo n.º 3
0
        public async Task <RefreshTokenResponseDto> RefreshToken(RefreshTokenInputDto inputDto)
        {
            var signingKey     = AppSettingConfigurationHelper.GetSection("AuthSettings:SecretKey").Value;
            var claimPrincipal = _jwtTokenValidator.GetPrincipalFromToken(inputDto.AccessToken, signingKey);

            if (claimPrincipal != null)
            {
                var id   = claimPrincipal.Claims.First(c => c.Type == "id");
                var user = await _userManager.FindByIdAsync(Convert.ToInt64(id.Value));

                if (_refreshTokenService.HasValidRefreshToken(inputDto.RefreshToken))
                {
                    var jwtToken = await _jwtFactory.GenerateEncodedToken(user.Id.ToString(), user.UserName, user.TenantId);

                    _refreshTokenService.Remove(inputDto.RefreshToken);                   // delete the token we've exchanged
                    var refreshToken = _refreshTokenService.CreateRefreshToken(user, ""); // add the new one
                    return(new RefreshTokenResponseDto(jwtToken, refreshToken.Token, true));
                }
                else
                {
                    return(new RefreshTokenResponseDto(null, "", false, "Invalid Refresh Token"));
                }
            }
            return(new RefreshTokenResponseDto(null, "", false, "Invalid Access Token"));
        }
Ejemplo n.º 4
0
        private T collectToRajaOngkir <T>(string apiPath, Dictionary <string, string> query = null)
        {
            using (var client = new HttpClient())
            {
                var url    = AppSettingConfigurationHelper.GetSection("APIUrlRajaOngkir").Value;
                var apiKey = AppSettingConfigurationHelper.GetSection("APIKeyRajaOngkir").Value;
                client.BaseAddress = new Uri(url);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("key", apiKey);

                var urlQueryString = apiPath;

                if (query.IsNotNull())
                {
                    urlQueryString = QueryHelpers.AddQueryString(apiPath, query);
                }

                HttpResponseMessage response = client.GetAsync(urlQueryString).Result;

                var    resultString = AsyncHelper.RunSync(() => response.Content.ReadAsStringAsync());
                JToken token        = JObject.Parse(resultString);

                if ((string)token.SelectToken("rajaongkir").SelectToken("status").SelectToken("description") != HttpStatusCode.OK.ToString())
                {
                    throw new HozaruException((string)token.SelectToken("rajaongkir").SelectToken("status").SelectToken("description"));
                }

                var result = token.SelectToken("rajaongkir").SelectToken("results");
                return(result.ToObject <T>());
            }
        }
Ejemplo n.º 5
0
        public string SaveProductImage(Image image, string fileName, Product product, IImageFormat imageFormat)
        {
            var pathFileStorageDirectory = AppSettingConfigurationHelper.GetSection("PathFileStorageDirectory").Value;

            if (pathFileStorageDirectory == null || pathFileStorageDirectory.Equals(string.Empty))
            {
                throw new Exception("File configuration must have App Setting with key PathFileStorageDirectory");
            }

            var pathDirectoryProduct = Path.Combine(pathFileStorageDirectory, "Images", "Products", product.Id.ToString());

            var directoryProductInfo = new DirectoryInfo(pathDirectoryProduct);

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

            var resizedImage = ImageResizer.FixedSize(image, 600, 600);
            var filePath     = Path.Combine(directoryProductInfo.FullName, string.Format("{0}{1}", fileName, imageFormat.GetFileExtension()));

            var encoder = imageFormat.GetEncoder();

            resizedImage.Save(filePath, encoder);
            resizedImage.Dispose();
            return(Path.Combine("Images", "Products", product.Id.ToString(), fileName + imageFormat.GetFileExtension()));
        }
Ejemplo n.º 6
0
        public async Task InvokeAsync(HttpContext httpContext)
        {
            var filtered = new string[] { ".png", ".jpg", ".js", ".css", ".map", "sockjs-node" };

            foreach (var filter in filtered)
            {
                if (httpContext.Request.Path.Value.Contains(filter))
                {
                    await _next(httpContext);

                    return;
                }
            }

            var isFromProxtNginx = httpContext.Request.Headers["X-NginX-Proxy"].Any() ? Convert.ToBoolean(httpContext.Request.Headers["X-NginX-Proxy"]) : false;

            if (isFromProxtNginx)
            {
                var externalHostName = httpContext.Request.Headers["ExternalHost"].ToString().RemovePreFix("http://", "https://").RemovePostFix("/");
                var tenant           = await ApiClientHelper.GetTenantFromExternalDomain(externalHostName);

                if (tenant == null)
                {
                    await httpContext.Response.WriteAsync("Pastikan Anda memasukan Url Website yang benar.");
                }
                httpContext.Items.Add(HttpContextConstant.TENANCY_NAME, tenant.TenancyName);
            }
            else
            {
                var domainFormatConfiguration = AppSettingConfigurationHelper.GetSection("DomainFormat").Value;
                var hostName     = httpContext.Request.Headers["Host"].ToString().RemovePreFix("http://", "https://").RemovePostFix("/");
                var domainFormat = domainFormatConfiguration.RemovePreFix("http://", "https://").Split(':')[0].RemovePostFix("/");
                var result       = new FormattedStringValueExtracter().Extract(hostName, domainFormat, true, '/');

                var tenancyName = string.Empty;
                if (!result.IsMatch || !result.Matches.Any())
                {
                    await httpContext.Response.WriteAsync("Pastikan Anda memasukan Url Website yang benar.");
                }

                tenancyName = result.Matches[0].Value;
                if (string.Equals(tenancyName, "www", StringComparison.OrdinalIgnoreCase))
                {
                    await httpContext.Response.WriteAsync("Pastikan Anda memasukan Url Website yang benar.");
                }

                if (await ApiClientHelper.TenantIsExist(tenancyName) == false)
                {
                    await httpContext.Response.WriteAsync("Pastikan Anda memasukan Url Website yang benar.");
                }

                httpContext.Items.Add(HttpContextConstant.TENANCY_NAME, tenancyName);
            }

            await _next(httpContext);
        }
Ejemplo n.º 7
0
        public Stream GetImage(string code)
        {
            var bank = _bankRepository.FirstOrDefault(i => i.Code == code);

            Validate.Found(bank, "Tipe Pembayaran", code);

            var pathFileDirectory = AppSettingConfigurationHelper.GetSection("PathFileStorageDirectory").Value;
            var filePath          = Path.Combine(pathFileDirectory, bank.ImageUrl);

            return(File.OpenRead(filePath));
        }
Ejemplo n.º 8
0
        private static string generateOrderUrl(Order order, Tenant tenant)
        {
            var    httpProtocol = AppSettingConfigurationHelper.GetSection("MultiTenancyHttpProtocol").Value;
            var    domainName   = AppSettingConfigurationHelper.GetSection("MultiTenancyDomainName").Value;
            string orderUrl     = string.Format("{0}://{1}.{2}/order/{3}", httpProtocol, tenant.TenancyName, domainName, order.Id);

            if (!tenant.ExternalDomain.IsNullOrWhiteSpace())
            {
                orderUrl = string.Format("{0}://{1}/order/{2}", "http", tenant.ExternalDomain, order.Id);
            }

            return(orderUrl);
        }
Ejemplo n.º 9
0
        public Stream GetImage(Guid productId, Guid productImageId)
        {
            var product = _productRepo.Get(productId);

            Validate.Found(product, "Produk");
            var productImage = product.Images.FirstOrDefault(i => i.Id == productImageId);

            Validate.Found(product, "Gambar Produk");

            var pathFileDirectory = AppSettingConfigurationHelper.GetSection("PathFileStorageDirectory").Value;
            var filePath          = Path.Combine(pathFileDirectory, productImage.ImageUrl);

            return(File.OpenRead(filePath));
        }
Ejemplo n.º 10
0
        public Stream GetReceiptImage(Guid id, Guid paymentId)
        {
            var order = _orderRepository.Get(id);

            Validate.Found(order, "Orderan");

            var payment = order.Payment.PaymentHistories.FirstOrDefault(i => i.Id == paymentId);

            Validate.Found(payment, "Bukti Pembayaran");

            var pathFileDirectory = AppSettingConfigurationHelper.GetSection("PathFileStorageDirectory").Value;
            var filePath          = Path.Combine(pathFileDirectory, payment.ReceiptImageUrl);

            return(File.OpenRead(filePath));
        }
Ejemplo n.º 11
0
        public override void PreInitialize()
        {
            base.PreInitialize();
            var connectionString = AppSettingConfigurationHelper.GetConnectionString("DefaultConnection");

            Configuration.Modules.HozaruNHibernate()
            .FluentConfiguration
            .Database(FluentNHibernate.Cfg.Db.PostgreSQLConfiguration.Standard.ConnectionString(connectionString).Dialect("NHibernate.Dialect.PostgreSQL82Dialect"))
            .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()));

            if (Convert.ToBoolean(AppSettingConfigurationHelper.GetSection("ResetDatabase").Value))
            {
                Configuration.Modules.HozaruNHibernate().FluentConfiguration.ExposeConfiguration(cfg => new SchemaExport(cfg).Execute(true, true, false));
            }
        }
Ejemplo n.º 12
0
        public ProductImageDto Convert(ResolutionContext context)
        {
            if (context == null)
            {
                return(null);
            }

            var apiDomainName = AppSettingConfigurationHelper.GetSection("APIDomainName").Value;
            var productImage  = (ProductImage)context.SourceValue;

            return(new ProductImageDto()
            {
                Id = productImage.Id,
                Priority = productImage.Priority,
                Url = string.Format("{0}/api/products/image/{1}/{2}?v={3}", apiDomainName, productImage.Product.Id, productImage.Id, productImage.LastModificationTime.Value.ToString("ddMMyyyHHmmss"))
            });
        }
Ejemplo n.º 13
0
        public async Task <Stream> GetFaviconImage(string tenancyName)
        {
            var tenant = await _tenantManager.FindByTenancyNameAsync(tenancyName);

            Validate.Found(tenant, "Tenant");
            var pathFileDirectory = AppSettingConfigurationHelper.GetSection("PathFileStorageDirectory").Value;
            var imageFileUrl      = Path.Combine("Images", "Tenants", tenant.TenancyName, "favicon.png");
            var filePath          = Path.Combine(pathFileDirectory, imageFileUrl);

            if (File.Exists(filePath))
            {
                return(File.OpenRead(filePath));
            }
            else
            {
                var defaultFaviconImageUrl = Path.Combine("Images", "Tenants", "default-favicon.png");
                return(File.OpenRead(Path.Combine(pathFileDirectory, defaultFaviconImageUrl)));
            }
        }
        public OrderPaymentHistoryDto Convert(ResolutionContext context)
        {
            if (context == null)
            {
                return(null);
            }

            var orderPayment  = (OrderPaymentHistory)context.SourceValue;
            var apiDomainName = AppSettingConfigurationHelper.GetSection("APIDomainName").Value;

            return(new OrderPaymentHistoryDto()
            {
                Id = orderPayment.Id,
                PaymentAccountName = orderPayment.PaymentAccountName,
                PaymentAccountNumber = orderPayment.PaymentAccountNumber,
                PaymentBankName = orderPayment.PaymentBankName,
                PaymentDate = orderPayment.PaymentDate,
                Url = string.Format("{0}/api/orders/{1}/payments/image/{2}?v={3}", apiDomainName, orderPayment.Order.Id, orderPayment.Id, orderPayment.LastModificationTime.Value.ToString("ddMMyyyHHmmss"))
            });
        }
Ejemplo n.º 15
0
        public PaymentMethodDto Convert(ResolutionContext context)
        {
            if (context == null)
            {
                return(null);
            }

            var apiDomainName = AppSettingConfigurationHelper.GetSection("APIDomainName").Value;
            var paymentMethod = (PaymentMethod)context.SourceValue;

            return(new PaymentMethodDto()
            {
                Id = paymentMethod.Id,
                BankName = paymentMethod.Bank.BankName,
                Code = paymentMethod.Bank.Code,
                IsManualConfirmation = paymentMethod.Bank.IsManualConfirmation,
                Name = paymentMethod.Bank.Name,
                ImageUrl = string.Format("{0}/api/paymentmethods/image/{1}?v={2}", apiDomainName, paymentMethod.Bank.Code, paymentMethod.LastModificationTime.Value.ToString("ddMMyyyHHmmss"))
            });
        }
Ejemplo n.º 16
0
        public Guid Edit(EditProductInputDto inputDto)
        {
            var product = _productRepo.Get(inputDto.Id);

            Validate.Found(product, "Produk");

            if (product.SKU != inputDto.SKU && _productRepo.Count(i => i.SKU == inputDto.SKU) > 0)
            {
                throw new HozaruException(string.Format("Produk dengan SKU {0} sudah terdaftar.", inputDto.SKU));
            }

            product.Update(inputDto.Name, inputDto.Description, inputDto.Price, inputDto.Weight, inputDto.SKU);

            var pathFileDirectory = AppSettingConfigurationHelper.GetSection("PathFileStorageDirectory").Value;

            foreach (var priority in inputDto.DeletedImagesByPriority)
            {
                var productImage = product.Images.FirstOrDefault(i => i.Priority == priority);
                if (productImage.IsNotNull())
                {
                    var imagePath = Path.Combine(pathFileDirectory, productImage.ImageUrl);
                    File.Delete(imagePath);
                    product.RemoveImage(productImage);
                }
            }

            foreach (var image in inputDto.Images)
            {
                var fileName    = string.Format("{0}_{1}", product.Name, image.Priority);
                var imageStream = image.Image.OpenReadStream();
                var imageObj    = Image.Load(imageStream);
                var filePath    = _imageGenerator.SaveProductImage(imageObj, fileName, product, JpegFormat.Instance);
                product.AddImage(filePath, fileName, image.Priority);
            }
            _productRepo.Update(product);

            return(product.Id);
        }
Ejemplo n.º 17
0
        public OrderDto Convert(ResolutionContext context)
        {
            if (context == null)
            {
                return(null);
            }

            var order         = (Order)context.SourceValue;
            var tenantManager = IocManager.Instance.Resolve <TenantManager>();
            var apiDomainName = AppSettingConfigurationHelper.GetSection("APIDomainName").Value;
            var tenant        = tenantManager.FindByIdAsync(order.TenantId).Result;

            var    httpProtocol = AppSettingConfigurationHelper.GetSection("MultiTenancyHttpProtocol").Value;
            var    domainName   = AppSettingConfigurationHelper.GetSection("MultiTenancyDomainName").Value;
            string orderUrl     = string.Format("{0}://{1}.{2}/order/{3}", httpProtocol, tenant.TenancyName, domainName, order.Id);

            if (!tenant.ExternalDomain.IsNullOrWhiteSpace())
            {
                orderUrl = string.Format("{0}://{1}/order/{2}", "http", tenant.ExternalDomain, order.Id);
            }

            return(new OrderDto
            {
                Id = order.Id,
                OrderNumber = order.OrderNumber,
                TransactionDate = order.TransactionDate,
                DueDateConfirmation = order.DueDateConfirmation,
                Customer = Mapper.Map <OrderCustomerDto>(order.Customer),
                Shipment = Mapper.Map <OrderShipmentDto>(order.Shipment),
                Payment = Mapper.Map <OrderPaymentDto>(order.Payment),
                Note = order.Note,
                Status = order.Status,
                StatusText = ((OrderStatus)order.Status).ToString(),
                Summary = Mapper.Map <OrderSummaryDto>(order.Summary),
                Items = Mapper.Map <IList <OrderItemDto> >(order.Items),
                OrderUrl = orderUrl
            });
        }
Ejemplo n.º 18
0
        public TenantDto Convert(ResolutionContext context)
        {
            if (context == null)
            {
                return(null);
            }

            var apiDomainName = AppSettingConfigurationHelper.GetSection("APIDomainName").Value;
            var tenant        = (Tenant)context.SourceValue;

            return(new TenantDto()
            {
                Id = tenant.Id,
                Address = tenant.Address,
                BrandUrl = string.Format("{0}/api/tenants/brand/{1}?v={2}", apiDomainName, tenant.TenancyName, tenant.LastModificationTime.Value.ToString("ddMMyyyHHmmss")),
                District = Mapper.Map <DistrictDto>(tenant.District),
                ExternalDomain = tenant.ExternalDomain,
                Name = tenant.Name,
                TenancyName = tenant.TenancyName,
                Phone = tenant.Phone,
                WhatsappNumber = tenant.WhatsappNumber
            });
        }
Ejemplo n.º 19
0
        public IList <ApiRajaOngkirShippingCostResponseDto> GetShippingCost(GetShippingCostInputDto inputDto)
        {
            using (var client = new HttpClient())
            {
                var url    = AppSettingConfigurationHelper.GetSection("APIUrlRajaOngkir").Value;
                var apiKey = AppSettingConfigurationHelper.GetSection("APIKeyRajaOngkir").Value;
                client.BaseAddress = new Uri(url);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("key", apiKey);

                var couriers = inputDto.Expeditions.Select(i => i.Code.ToLower()).JoinAsString(":");

                var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair <string, string>("origin", inputDto.Origin.IdRajaOngkir.ToString()),
                    new KeyValuePair <string, string>("originType", "subdistrict"),
                    new KeyValuePair <string, string>("destination", inputDto.Destination.IdRajaOngkir.ToString()),
                    new KeyValuePair <string, string>("destinationType", "subdistrict"),
                    new KeyValuePair <string, string>("weight", (inputDto.Weight + 100).ToString()),
                    new KeyValuePair <string, string>("courier", couriers)
                });

                HttpResponseMessage response = client.PostAsync("cost", content).Result;

                var    resultString = AsyncHelper.RunSync(() => response.Content.ReadAsStringAsync());
                JToken token        = JObject.Parse(resultString);

                if ((string)token.SelectToken("rajaongkir").SelectToken("status").SelectToken("description") != HttpStatusCode.OK.ToString())
                {
                    throw new HozaruException("Ongkos Kirim tidak ditemukan.");
                }

                var result = token.SelectToken("rajaongkir").SelectToken("results");
                return(result.ToObject <IList <ApiRajaOngkirShippingCostResponseDto> >());
            }
        }