Esempio n. 1
0
        public ActionResult Logging()
        {
            var logsData = new LoggingRepository().GetAll().ToList();
            var logs     = new List <LoggingViewModel>();

            foreach (var item in logsData)
            {
                var log = new LoggingViewModel();
                log.date            = item.actionDate.ToString();
                log.username        = item.userName;
                log.ip              = item.requestIP;
                log.controller      = item.controllerName;
                log.action          = item.actionName;
                log.httpRequestType = item.requestType;
                log.httpParameters  = item.requestParams;

                logs.Add(log);
            }

            LogHelper logHelper = new LogHelper();

            logHelper.getParams(this, 0);
            logHelper.logToDatabase(logHelper);

            return(View(logs));
        }
Esempio n. 2
0
        public ActionResult Upload(HttpPostedFileBase data)
        {
            try
            {
                var myStorageManager = StorageClient.Create();

                var guid     = Guid.NewGuid();
                var mynewobj = myStorageManager.UploadObject("programmingcloud", guid.ToString() + Path.GetExtension(data.FileName), data.ContentType, data.InputStream,
                                                             options: new Google.Cloud.Storage.V1.UploadObjectOptions()
                {
                    PredefinedAcl = PredefinedObjectAcl.PublicRead
                });

                //imgName = guid.ToString() + Path.GetExtension(data.FileName);

                ViewBag.Success = "Item uploaded successfully.";
            }
            catch (Exception ex)
            {
                LoggingRepository.ReportError(ex);
                ViewBag.Error = ex + " -(Item was not uploaded)";
            }

            return(RedirectToAction("Create", "Property"));
        }
Esempio n. 3
0
        private void attachUserToContext(HttpContext context, IUserService userService, string token)
        {
            string connStrings = _configuration.GetConnectionString("DevelopmentConnectionString");

            try
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var key          = Encoding.ASCII.GetBytes(_appSettings.Secret);
                tokenHandler.ValidateToken(token, new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    // set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later)
                    ClockSkew = TimeSpan.Zero
                }, out SecurityToken validatedToken);

                var jwtToken = (JwtSecurityToken)validatedToken;
                var username = jwtToken.Claims.First(x => x.Type == "username").Value;
                var password = jwtToken.Claims.First(x => x.Type == "password").Value;

                // attach user to context on successful jwt validation
                context.Items["UserLoginResponse"] = userService.GetById(username, password);
            }
            catch (Exception ex)
            {
                LoggingRepository.SaveException(ex);
            }
        }
Esempio n. 4
0
 public void LogMessage(string message)
 {
                 #if DEBUG
     Console.WriteLine(message);
                 #else
     LoggingRepository.Log(LoggingCategory.RepricingScript, message);
                 #endif
 }
Esempio n. 5
0
        public static void AddNpgLoggerScoped(this IServiceCollection services, string connectionString, LogLevel defaultLogLevel)
        {
            var optionsBuilder = new DbContextOptionsBuilder <LoggingDatabaseContext>();

            optionsBuilder.UseNpgsql(connectionString);
            var dbContext         = new LoggingDatabaseContext(optionsBuilder.Options);
            var loggingRepository = new LoggingRepository(dbContext);

            services.AddScoped <INpgLogger>(s => new NpgLogger(loggingRepository, defaultLogLevel));
        }
        public List <T> ConsumeMessages <T>(string queueUrl, bool deleteMessages = false, int?maxNumberOfMessages = null)
        {
            ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest
            {
                QueueUrl = queueUrl
            };

            if (maxNumberOfMessages.HasValue)
            {
                receiveMessageRequest.MaxNumberOfMessages = maxNumberOfMessages.Value;
            }

            ReceiveMessageResponse receiveMessageResponse = m_amazonSqsClient.ReceiveMessage(receiveMessageRequest);

            var messagesAndMd5 = receiveMessageResponse.Messages
                                 .Select(s => new { s.MessageId, s.Body, IsValidMD5 = Md5Utility.CompareMd5Sqs(s.Body, s.MD5OfBody), s.ReceiptHandle })
                                 .ToList();

            if (messagesAndMd5.Any(a => !a.IsValidMD5))
            {
                LoggingRepository.Log(LoggingCategory.RepricingScript, "MD5 on IMwsSubscriptionServiceApi was not valid.");
            }

            // Filter out messages with corrupted Body (Md5 didn't match).
            var messagesAndMd5Filtered = messagesAndMd5.Where(w => w.IsValidMD5)
                                         .ToDictionary(k => k.MessageId, v => v);

            if (deleteMessages && messagesAndMd5Filtered.Any())
            {
                List <DeleteMessageBatchRequestEntry> deleteMessageBatchRequestEntries = messagesAndMd5Filtered
                                                                                         .Select(s => s.Value)
                                                                                         .Select(s => new DeleteMessageBatchRequestEntry {
                    Id = s.MessageId, ReceiptHandle = s.ReceiptHandle
                })
                                                                                         .ToList();

                DeleteMessageBatchResponse deleteMessageBatchResponse = m_amazonSqsClient.DeleteMessageBatch(new DeleteMessageBatchRequest {
                    Entries = deleteMessageBatchRequestEntries, QueueUrl = queueUrl
                });

                // Don't return messages that we weren't able to delete.
                if (deleteMessageBatchResponse.Failed.Any())
                {
                    foreach (BatchResultErrorEntry batchResultErrorEntry in deleteMessageBatchResponse.Failed)
                    {
                        if (messagesAndMd5Filtered.ContainsKey(batchResultErrorEntry.Id))
                        {
                            messagesAndMd5Filtered.Remove(batchResultErrorEntry.Id);
                        }
                    }
                }
            }

            return(messagesAndMd5Filtered.Select(s => s.Value.Body.FromXml <T>()).ToList());
        }
Esempio n. 7
0
        public Dictionary <string, decimal> GetMyPriceForSKUs(IEnumerable <string> skus)
        {
            Dictionary <string, decimal> myPriceDictionary = new Dictionary <string, decimal>();

            GetMyPriceForSKURequest requestMyPriceForSku = new GetMyPriceForSKURequest
            {
                SellerId      = m_sellerId,
                MarketplaceId = m_marketPlaceId,
                SellerSKUList = new SellerSKUListType()
            };

            requestMyPriceForSku.SellerSKUList.SellerSKU.AddRange(skus);
            try
            {
                GetMyPriceForSKUResponse response = m_productClient.GetMyPriceForSKU(requestMyPriceForSku);

                List <GetMyPriceForSKUResult> getMyPriceForSkuResultList = response.GetMyPriceForSKUResult;
                foreach (GetMyPriceForSKUResult getMyPriceForSkuResult in getMyPriceForSkuResultList)
                {
                    if (getMyPriceForSkuResult.IsSetProduct())
                    {
                        MarketplaceWebServiceProducts.Model.Product product = getMyPriceForSkuResult.Product;

                        if (product.IsSetOffers())
                        {
                            OffersList       offers    = product.Offers;
                            List <OfferType> offerList = offers.Offer;
                            foreach (OfferType offer in offerList)
                            {
                                if (offer.IsSetBuyingPrice())
                                {
                                    PriceType buyingPrice = offer.BuyingPrice;
                                    if (buyingPrice.IsSetLandedPrice())
                                    {
                                        MoneyType landedPrice2 = buyingPrice.LandedPrice;

                                        if (landedPrice2.IsSetAmount())
                                        {
                                            decimal myPrice = landedPrice2.Amount;
                                            myPriceDictionary.Add(offer.SellerSKU, myPrice);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (MarketplaceWebServiceProductsException e)
            {
                LoggingRepository.Log(LoggingCategory.RepricingScript, string.Format("Exception in 'GetMyPriceForSKU': {0}", e.Message));
            }

            return(myPriceDictionary);
        }
 public DatenLoggerModelView()
 {
     LogEntries        = new List <IEntity>();
     CmdLoad           = new DelegateCommand(OnCmdLoad);
     CmdConfirm        = new DelegateCommand(OnCmdConfirm);
     CmdAddLog         = new DelegateCommand(OnCmdAddLog);
     CmdDublicateCheck = new DelegateCommand(OnCmdDublicateCheck);
     CmdHierarchie     = new DelegateCommand(OnCmdHierarchie);
     LogEntryView      = new LogEntryView();
     LoggingRepository = new LoggingRepository();
 }
Esempio n. 9
0
        public ActionResult DeleteItems(List <int> items)
        {
            if (items.Count > 0)
            {
                PropertyRepository pr     = new PropertyRepository();
                List <Property>    myList = new List <Property>();
                try
                {
                    if (pr.MyConnection.State == System.Data.ConnectionState.Closed)
                    {
                        pr.MyConnection.Open();
                        pr.MyTransaction = pr.MyConnection.BeginTransaction();
                    }

                    //delete all items
                    foreach (int id in items)
                    {
                        pr.DeleteProperty(id);
                    }

                    pr.MyTransaction.Commit();

                    if (items.Count == 1)
                    {
                        ViewBag.Success = "Property was deleted";
                    }
                    else
                    {
                        ViewBag.Success = "Properties were deleted";
                    }
                }
                catch (Exception ex)
                {
                    pr.MyTransaction.Rollback();

                    //log exception
                    LoggingRepository.ReportError(ex);
                    ViewBag.Error = "Error occurred. Nothing was deleted; Try again later";
                }
                finally
                {
                    myList = pr.GetProperty().ToList(); //to refresh the now updated list

                    if (pr.MyConnection.State == System.Data.ConnectionState.Open)
                    {
                        pr.MyConnection.Close();
                    }
                }

                return(View("Index", myList));
            }

            return(RedirectToAction("Index"));
        }
 public DatenLoggerAddModelView()
 {
     GetAddLogEntryModelView = this;
     CmdSave   = new DelegateCommand(OnCmdSave);
     CmdCancel = new DelegateCommand(OnCmdCancel);
     //LogEntryView = new LogEntryView();
     DeviceRepository   = new DeviceRepository();
     LoggingRepository  = new LoggingRepository();
     LocationRepository = new LocationRepository();
     Entity             = new LogEntry();
 }
Esempio n. 11
0
        public static void WriteDebugLog(string log)
        {
            ILoggingRepository logRepository = new LoggingRepository();

            logRepository.Add(new Logging()
            {
                CreatedDate = DateTime.Now,
                Message     = log,
                Type        = Convert.ToString((int)LogType.Debug)
            });
            logRepository.Save();
        }
Esempio n. 12
0
        public ActionResult Create(PropertyViewModel p)
        {
            PropertyRepository cc = new PropertyRepository();

            try
            {
                if (cc.MyConnection.State == System.Data.ConnectionState.Closed)
                {
                    cc.MyConnection.Open();
                }

                //save in bucket
                var myStorageManager = StorageClient.Create();
                var guid             = Guid.NewGuid();
                var mynewobj         = myStorageManager.UploadObject("programmingcloud", guid.ToString() + Path.GetExtension(p.File.FileName), p.File.ContentType, p.File.InputStream,
                                                                     options: new Google.Cloud.Storage.V1.UploadObjectOptions()
                {
                    PredefinedAcl = Google.Cloud.Storage.V1.PredefinedObjectAcl.PublicRead
                });

                string imgName = guid.ToString() + Path.GetExtension(p.File.FileName);
                string us      = User.Identity.Name;
                string u       = us.Substring(0, us.IndexOf("@"));
                p.Username = u;
                var prop = new Property()
                {
                    Username        = p.Username,
                    Location        = p.Location,
                    Name            = p.Name,
                    Description     = p.Description,
                    Price           = p.Price,
                    PropertyPicture = imgName
                };
                cc.AddProperty(prop);


                ViewBag.Success = "Property was created successfully";
                return(View());
            }
            catch (Exception ex)
            {
                LoggingRepository.ReportError(ex);
                ViewBag.Error = ex + " - (Error occurred. Property was not added)";
                return(View());
            }
            finally
            {
                if (cc.MyConnection.State == System.Data.ConnectionState.Open)
                {
                    cc.MyConnection.Close();
                }
            }
        }
Esempio n. 13
0
        public override void OnException(ExceptionContext actionExecutedContext)
        {
            string message = string.Format("Message: {0} StackTrace: {1}", actionExecutedContext.Exception.Message, actionExecutedContext.Exception.StackTrace);

            // Don't log if we are developing locally in Debug mode.
            // Make sure that when we deploy, the project was build in Release mode.
                        #if !DEBUG
            LoggingRepository.Log(LoggingCategory.WebApplication, message);
                        #endif

            base.OnException(actionExecutedContext);
        }
Esempio n. 14
0
        public IActionResult EditProvider([FromBody] ProviderModel model)
        {
            Response <ProviderModel> returnModel = new Response <ProviderModel>();
            string imageURL = string.Empty;
            string imgPath  = string.Empty;

            byte[] imageBytes;

            try
            {
                if (model == null)
                {
                    model = new ProviderModel();
                }

                if (!string.IsNullOrEmpty(model.image) && !string.IsNullOrEmpty(model.image_extension))
                {
                    if (model.image_extension.ToLower() != "jpg" && model.image_extension.ToLower() != "jpeg" && model.image_extension.ToLower() != "png")
                    {
                        returnModel.success = false;
                        returnModel.status  = (int)EnumClass.ResponseState.ResposityError;
                        returnModel.msg     = Resource_Kharban.SelectImageValidation;
                        return(Ok(returnModel));
                    }

                    var path = hostingEnvironment.WebRootPath + "/images/provider_profile"; //Path

                    //Check if directory exist
                    if (!System.IO.Directory.Exists(path))
                    {
                        System.IO.Directory.CreateDirectory(path); //Create directory if it doesn't exist
                    }

                    string imageName = DateTime.Now.ToString("yyyyMMddHHmmss") + "." + model.image_extension;

                    //set the image path
                    imgPath  = Path.Combine(path, imageName);
                    imageURL = "https://kharban.net:2096/images/provider_profile/" + imageName;
                    //imageURL = "http://localhost:59039/images/provider_profile/" + imageName;
                }
                returnModel = new ProviderRepository().UpdateProvider(model, imgPath, imageURL);
            }
            catch (Exception ex)
            {
                returnModel.msg    = ex.Message;
                returnModel.status = (int)EnumClass.ResponseState.ResposityError;
                LoggingRepository.SaveException(ex);
            }
            return(Ok(returnModel));
        }
Esempio n. 15
0
        public static void WriteExceptionLog(Exception ex)
        {
            ILoggingRepository logRepository = new LoggingRepository();

            logRepository.Add(new Logging()
            {
                CreatedDate           = DateTime.Now,
                ExceptionMessage      = ex.Message,
                InnerExceptionMessage = ex.InnerException.Message,
                LineNumber            = GetLineNumber(ex),
                MethodName            = GetMethodName(ex),
                Type = Convert.ToString((int)LogType.Debug)
            });
            logRepository.Save();
        }
Esempio n. 16
0
        public ActionResult Index()
        {
            PropertyRepository pr = new PropertyRepository();

            try
            {
                //1. Load items from cache
                RedisRepository rr    = new RedisRepository();
                var             items = rr.LoadItems();

                //2. hash the serialized value of items
                pr.MyConnection.Open();
                var itemsFromDb = pr.GetProperty();
                pr.MyConnection.Close();

                if (items == null)
                {
                    rr.StoreItems(itemsFromDb);
                    items = rr.LoadItems();
                }

                //3. compare the digest produced with the digest produced earlier while stored in application variable
                if (rr.HashValue(JsonConvert.SerializeObject(items)) != rr.HashValue(JsonConvert.SerializeObject(itemsFromDb)))
                {
                    //4. if they do not match
                    //storeincache method and re-produce a new hashcode
                    rr.StoreItems(itemsFromDb);
                    items = rr.LoadItems();
                }

                return(View(items));
            }
            catch (Exception ex)
            {
                LoggingRepository.ReportError(ex);
                ViewBag.Error = ex + " - (Error occurred while querying items)";
                return(View(new List <Property>()));
            }
            finally
            {
                if (pr.MyConnection.State == System.Data.ConnectionState.Open)
                {
                    pr.MyConnection.Close();
                }
            }
        }
Esempio n. 17
0
        public bool SendMail(string MailTO, string EmailSubject, string EmailBody, Stream stream = null, string attachmentName = null)
        {
            try
            {
                //MailTO = "*****@*****.**";
                string Website     = SiteKey.SiteUrl;
                string smtpAddress = _smtpserver;
                int    portNumber  = int.Parse(_Port);
                bool   enableSSL   = (_UseSSL.ToLower() == "true" ? true : false);
                string emailFrom   = _EmailFrom;
                string password    = _ePassword;
                string username    = _UserName;
                string emailTo     = MailTO;
                string subject     = EmailSubject;
                string body        = EmailBody;

                using (MailMessage mail = new MailMessage())
                {
                    mail.From = new MailAddress(emailFrom);
                    mail.To.Add(emailTo);
                    mail.Subject    = subject;
                    mail.Body       = body;
                    mail.IsBodyHtml = true;

                    if (stream != null)
                    {
                        mail.Attachments.Add(new Attachment(stream, attachmentName));
                    }

                    // Can set to false, if you are sending pure text.
                    using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
                    {
                        smtp.Credentials = new NetworkCredential(username, password);
                        smtp.EnableSsl   = enableSSL;
                        smtp.Send(mail);
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                LoggingRepository.SaveException(ex);
                return(false);
            }
        }
Esempio n. 18
0
        public void LogException(Exception ex)
        {
            try
            {
                string message        = ex.Message;
                bool   emailException = true;

                if (m_publishedExceptions.ContainsKey(message))
                {
                    DateTime lastSent = m_publishedExceptions[message];
                    if (lastSent.AddHours(c_emailMessageThrottleHours) >= DateTime.UtcNow)
                    {
                        emailException = false;
                    }
                }

                m_publishedExceptions.AddOrUpdate(
                    message,
                    DateTime.UtcNow,
                    (key, lastSent) => lastSent.AddHours(c_emailMessageThrottleHours) >= DateTime.UtcNow
                                                ? lastSent
                                                : DateTime.UtcNow);

                string messageToLog = string.Format("Repricing script Exception: {0} StackTrace: {1}", ex.Message, ex.StackTrace);

                if (emailException)
                {
                    string subject = string.Format("Repricing script Exception: {0}", message);
                    subject = subject.Substring(0, Math.Min(subject.Length, c_maxSubjectLength));

                    m_simpleNotificationService.PublishAlert(subject, messageToLog);
                }

                                #if DEBUG
                Console.WriteLine(message);
                                #else
                LoggingRepository.Log(LoggingCategory.RepricingScript, string.Format("Message: {0}, StackTrace: {1}", ex.Message, ex.StackTrace));
                                #endif
            }
            catch (Exception e)
            {
                LogMessage(string.Format("Failed to LogException. Message: {0}, StackTrace: {1}", e.Message, e.StackTrace));
            }
        }
Esempio n. 19
0
        public static void SendMsg(string mobile, string message)
        {
            string   username  = "******";
            string   password  = "******";
            string   sender_id = "DKRSMS";
            string   msg_token = "BSTqRa";
            string   restUrl   = "http://manage.sarvsms.com/api/send_transactional_sms.php?username="******"&msg_token=" + WebUtility.UrlEncode(msg_token) + "&sender_id=" + WebUtility.UrlEncode(sender_id) + "&message=" + WebUtility.UrlEncode(message) + "&mobile=" + WebUtility.UrlEncode(mobile);
            string   URldata;
            string   QueryData   = null;
            DateTime RequestDate = DateTime.Now;
            int      index       = restUrl.IndexOf("?");

            if (index > 0)
            {
                QueryData = restUrl.Substring(index + 1);
            }
            URldata = restUrl;
            try
            {
                using (WebClient Client = new WebClient())
                {
                    var http = (HttpWebRequest)WebRequest.Create(URldata);
                    http.Accept      = "application/json";
                    http.ContentType = "application/x-www-form-urlencoded"; //"application/json";
                    http.Method      = "GET";
                    UTF8Encoding encoding = new UTF8Encoding();
                    RequestDate = DateTime.Now;
                    var response = http.GetResponse();
                    var stream   = response.GetResponseStream();
                    var sr       = new StreamReader(stream);
                    var content  = sr.ReadToEnd();
                    if (!content.Contains("SUCCESS"))
                    {
                        Exception ex = new Exception();

                        LoggingRepository.SaveException(ex);
                    }
                }
            }
            catch (WebException ex)
            {
                //ExceptionList.SendErrorToText(ex, connString);
            }
        }
Esempio n. 20
0
 public MailSend(string Website)
 {
     try
     {
         string   myEmailCredentials = SiteKey.DKR_MAIL;
         string[] settings           = myEmailCredentials.Split(';');
         _smtpserver   = GetValue(settings, "smtpserver");
         _Port         = GetValue(settings, "Port");
         _Authenticate = GetValue(settings, "Authenticate");
         _UserName     = GetValue(settings, "UserName");
         _ePassword    = GetValue(settings, "ePassword");
         _UseSSL       = GetValue(settings, "UseSSL");
         _EmailFrom    = GetValue(settings, "EmailFrom");
     }
     catch (Exception ex)
     {
         LoggingRepository.SaveException(ex);
     }
 }
Esempio n. 21
0
        public static bool WriteFile(string filePath, string content)
        {
            bool isWritten = false;

            try
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
                File.WriteAllText(filePath, content);
                isWritten = true;
            }
            catch (Exception ex)
            {
                LoggingRepository.SaveException(ex);
            }
            return(isWritten);
        }
Esempio n. 22
0
        public bool SendMailAttachments(string MailTO, string EmailSubject, string EmailBody, Attachment atfile)
        {
            try
            {
                string smtpAddress = _smtpserver;
                int    portNumber  = int.Parse(_Port);
                bool   enableSSL   = (_UseSSL.ToLower() == "true" ? true : false);
                string emailFrom   = _UserName;
                string password    = _ePassword;
                string emailTo     = MailTO;
                string subject     = EmailSubject;
                string body        = EmailBody;
                using (MailMessage mail = new MailMessage())
                {
                    mail.From = new MailAddress(emailFrom);
                    mail.To.Add(emailTo);
                    mail.Subject    = subject;
                    mail.Body       = body;
                    mail.IsBodyHtml = true;
                    // Can set to false, if you are sending pure text.
                    if (atfile != null)
                    {
                        mail.Attachments.Add(atfile);
                    }
                    //mail.Attachments.Add(new Attachment("C:\\SomeFile.txt"));
                    //mail.Attachments.Add(new Attachment("C:\\SomeZip.zip"));

                    using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
                    {
                        smtp.Credentials = new NetworkCredential(emailFrom, password);
                        smtp.EnableSsl   = enableSSL;
                        smtp.Send(mail);
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                LoggingRepository.SaveException(ex);
                return(false);
            }
        }
Esempio n. 23
0
        static void Main()
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            IServiceLocator serviceLocator  = TypeRegistry.RegisterTypes();
            ReportRetrieval reportRetrieval = serviceLocator.GetInstance <ReportRetrieval>();

            Task <string> unsuppressedInventoryTask = Task.Factory.StartNew(() => reportRetrieval.GetUnsuppressedInventoryReport());
            Task <string> allOrdersTask             = Task.Factory.StartNew(() => reportRetrieval.GetAllOrdersReport());
            Task <string> feePreviewTask            = Task.Factory.StartNew(() => reportRetrieval.GetFeePreviewReport());
            Task <string> dailyInventoryTask        = Task.Factory.StartNew(() => reportRetrieval.GetDailyInventoryReport());

            Task <string>[] tasks =
            {
                unsuppressedInventoryTask,
                allOrdersTask,
                feePreviewTask,
                dailyInventoryTask
            };

            Task.WaitAll(tasks.Cast <Task>().ToArray());

            string result = tasks
                            .Select(s => s.Result)
                            .Aggregate((current, item) => string.Format("{0} \n\n {1}", current, item));

            stopwatch.Stop();

            TimeSpan elapsedTime = stopwatch.Elapsed;

            string loggingMessage = string.Format(
                "Report Upload has finished successfully. \n Took a total of {0} hours, {1} minutes, {2} seconds. \n\n {3}",
                elapsedTime.Hours,
                elapsedTime.Minutes,
                elapsedTime.Seconds,
                result);

            LoggingRepository.Log(LoggingCategory.ReportUpload, loggingMessage);
        }
Esempio n. 24
0
        private static async Task Main(string[] args)
        {
            var appSettings = AppSettings.LoadAppSettings();

            // Injections
            var logAnalyticsSecret = new LogAnalyticsSecret <LoggingRepository>(appSettings.LogAnalyticsCustomerId, appSettings.LogAnalyticsPrimarySharedKey, "JobScheduler");
            var loggingRepository  = new LoggingRepository(logAnalyticsSecret);
            var syncJobRepository  = new SyncJobRepository(appSettings.JobsStorageAccountConnectionString, appSettings.JobsTableName, loggingRepository);


            var telemetryConfiguration = new TelemetryConfiguration();

            telemetryConfiguration.InstrumentationKey = appSettings.APPINSIGHTS_INSTRUMENTATIONKEY;
            telemetryConfiguration.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer());

            IJobSchedulerConfig jobSchedulerConfig = new JobSchedulerConfig(
                appSettings.ResetJobs,
                appSettings.DaysToAddForReset,
                appSettings.DistributeJobs,
                appSettings.IncludeFutureJobs,
                appSettings.StartTimeDelayMinutes,
                appSettings.DelayBetweenSyncsSeconds,
                appSettings.DefaultRuntime);

            var runtimeRetrievalService = new DefaultRuntimeRetrievalService(jobSchedulerConfig.DefaultRuntimeSeconds);

            IJobSchedulingService jobSchedulingService = new JobSchedulingService(
                jobSchedulerConfig,
                syncJobRepository,
                runtimeRetrievalService,
                loggingRepository
                );

            IApplicationService applicationService = new ApplicationService(jobSchedulingService, jobSchedulerConfig, loggingRepository);

            // Call the JobScheduler ApplicationService
            await applicationService.RunAsync();
        }
Esempio n. 25
0
 public static void Save(string sender_id, string reciver_id, string reciver_mobile, string msg, string connStrings)
 {
     try
     {
         string guid      = Guid.NewGuid().ToString();
         var    perameter = new
         {
             id             = guid,
             reciver_id     = reciver_id,
             sender_id      = sender_id,
             reciver_mobile = reciver_mobile,
             msg            = msg,
             created        = DateTime.Now,
         };
         using (SqlConnection DB = new SqlConnection(connStrings))
         {
             DB.ExecuteSql(@"insert into sent_sms(id, reciver_id, sender_id, reciver_mobile, msg, created) Values(?id, ?reciver_id, ?sender_id, ?reciver_mobile, ?msg, ?created)", perameter);
         }
     }
     catch (Exception ex)
     {
         LoggingRepository.SaveException(ex);
     }
 }
Esempio n. 26
0
        public static async System.Threading.Tasks.Task <BaseResponse> PushNotificationAsync(string deviceid, string title, string message, string code = null, int Navi_Type = 0, string bookingId = null, int reject_count = 0)
        {
            BaseResponse model = new BaseResponse();

            try
            {
                WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
                tRequest.Method = "post";
                //serverKey - Key from Firebase cloud messaging server
                tRequest.Headers.Add(string.Format("Authorization: key={0}", SiteKey.PrivateKey));
                //Sender Id - From firebase project setting
                tRequest.Headers.Add(string.Format("Sender: id={0}", SiteKey.PublicKey));
                tRequest.ContentType = "application/json";
                var payload = new
                {
                    to                = deviceid,
                    priority          = "high",
                    content_available = true,

                    notification = new
                    {
                        body  = message,
                        title = title,
                        sound = "",
                        badge = Navi_Type
                    },
                    data = new
                    {
                        NotificationType     = code,
                        body                 = message,
                        title                = title,
                        sound                = "",
                        badge                = Navi_Type,
                        booking_id           = bookingId,
                        receipt_reject_count = reject_count
                    },
                };
                var    serializer = new JavaScriptSerializer();
                Byte[] byteArray  = Encoding.UTF8.GetBytes(serializer.Serialize(payload));
                tRequest.ContentLength = byteArray.Length;
                using (Stream dataStream = await tRequest.GetRequestStreamAsync())
                {
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    using (WebResponse tResponse = await tRequest.GetResponseAsync())
                    {
                        using (Stream dataStreamResponse = tResponse.GetResponseStream())

                        {
                            if (dataStreamResponse != null)
                            {
                                using (StreamReader tReader = new StreamReader(dataStreamResponse))
                                {
                                    String sResponseFromServer = await tReader.ReadToEndAsync();

                                    model.StatusMessage = sResponseFromServer;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LoggingRepository.SaveException(ex);
            }
            return(model);
        }
Esempio n. 27
0
 protected override void OnActionExecuting(ActionExecutingContext filterContext)
 {
     _coreDataRepository = new CoreDataRepository();
     _loggingRepository  = new LoggingRepository();
     base.OnActionExecuting(filterContext);
 }