Пример #1
0
        public IActionResult Edit(int id, [Bind("Id,ProjectName,SubCompanyId")] ProjectViewModel projectViewModel)
        {
            if (id != projectViewModel.Id)
            {
                return(NotFound());
            }


            if (ModelState.IsValid)
            {
                if (_IProject.Update(projectViewModel))
                {
                    return(RedirectToAction("Index"));
                }
                else
                {
                    ViewBag.Message = "Unable To Update.";
                }
            }

            ViewBag.SubCompanies = UtilityService.CreateSubCompanyListItem(_IProject.GetSubCompanies());
            return(View(projectViewModel));
        }
Пример #2
0
        /// <summary>
        /// Validate information value in grade logic.
        /// </summary>
        /// <param name="model">The grade information value.</param>
        /// <returns></returns>
        public ResultViewModel ValidateData(GradeViewModel model)
        {
            var result = new ResultViewModel();

            model.GradeItems = model.GradeItems.OrderBy(x => x.StartPoint).ToList();
            int oldEnd = int.MinValue;

            foreach (var item in model.GradeItems)
            {
                if (item.StartPoint >= item.EndPoint)
                {
                    result = UtilityService.InitialResultError(MessageValue.GradePointIncorrect, (int)HttpStatusCode.BadRequest);
                    break;
                }
                if (oldEnd >= item.StartPoint)
                {
                    result = UtilityService.InitialResultError(MessageValue.GradePointIncorrect, (int)HttpStatusCode.BadRequest);
                    break;
                }
                oldEnd = item.EndPoint.Value;
            }
            return(result);
        }
Пример #3
0
        /// <summary>
        /// Delete a  specific Time Entry
        /// </summary>
        /// <param name="dataAccessToken"></param>
        /// <param name="timeEntryId"></param>
        /// <returns>BaseBO</returns>
        public BaseBO DeleteTimeEntry(string dataAccessToken, string apiVersion, string timeEntryId)
        {
            BaseBO output = new BaseBO();

            try
            {
                // Calls DeleteTimeEntry of Integration layer to delete time entry for specific timeEntryId
                TimeEntryService integrationService = new TimeEntryService();
                integrationService.DeleteTimeEntry(Constants.CONSUMER_SECRET_TOKEN, UtilityService.DecryptedText(dataAccessToken), apiVersion, timeEntryId);
            }
            catch (DovicoException e)
            {
                logger.Log(LogLevel.Error, e);
                output.ErrorMessage = e.Message;
            }
            catch (Exception e)
            {
                logger.Log(LogLevel.Error, e);
                output.ErrorMessage = "Time Entry cannot be deleted.";
            }

            return(output);
        }
Пример #4
0
        public IActionResult Edit([FromBody] CriteriaViewModel model)
        {
            IActionResult response;

            if (_criteria.IsUse(model.Id))
            {
                response = BadRequest(UtilityService.InitialResultError(string.Format(MessageValue.IsUseMessageFormat, MessageValue.CriteriaMessage),
                                                                        (int)System.Net.HttpStatusCode.BadRequest));
            }
            else
            {
                var validate = _criteria.ValidateData(model);
                if (validate.IsError)
                {
                    response = BadRequest(validate);
                }
                else
                {
                    response = Ok(_criteria.Edit(model));
                }
            }
            return(response);
        }
Пример #5
0
        /// <summary>
        /// Forget password logic function.
        /// </summary>
        /// <param name="model">The forget password information.</param>
        /// <returns></returns>
        public ResultViewModel ForgetPassword(ForgetPasswordViewModel model)
        {
            var result = new ResultViewModel();

            if (this.ValidateInformation(model))
            {
                string newPassword = CodeGenerator.RandomString(8);
                using (TransactionScope scope = new TransactionScope())
                {
                    this.SavePassword(model.Email, newPassword);
                    this.UpdateFirstLogin(model.Email, true);
                    _unitOfWork.Complete(scope);
                }
                this.ReloadCache();
                result = this.SendEmailForgetPassword(model.Email, newPassword,
                                                      string.Format(ConstantValue.EmpTemplate, model.FirstNameEn, model.LastNameEn));
            }
            else
            {
                result = UtilityService.InitialResultError(MessageValue.ForgetPasswordAlert, 200);
            }
            return(result);
        }
        /// <summary>
        /// Validate evaluation save and edit before add data.
        /// </summary>
        /// <param name="model">The evaluation assign value.</param>
        /// <returns></returns>
        public ResultViewModel ValidateData(EvaluationAssignRequestViewModel model)
        {
            var result = new ResultViewModel();

            if (model.Id != 0)
            {
                var evaAssign = _unitOfWork.GetRepository <EvaluationAssign>().Get(x => x.EvaluationId == model.EvaluationId && x.Id != model.Id);
                if (evaAssign.Any(x => x.AdUser == model.ToAdUser))
                {
                    result = UtilityService.InitialResultError(MessageValue.DuplicateEvaluationAssign, (int)System.Net.HttpStatusCode.BadRequest);
                }
            }
            else
            {
                var evaAssign = _unitOfWork.GetRepository <EvaluationAssign>().Get(x => x.EvaluationId == model.EvaluationId);
                if (evaAssign.Any(x => x.AdUser == model.ToAdUser))
                {
                    result = UtilityService.InitialResultError(MessageValue.DuplicateEvaluationAssign, (int)System.Net.HttpStatusCode.BadRequest);
                }
            }

            return(result);
        }
Пример #7
0
    protected void btn_Modity_Click(object sender, EventArgs e)
    {
        if (txt_Name.Text.Trim() == "系统管理员" || txt_Name.Text.Trim() == "超级管理员")
        {
            UtilityService.Alert(this.Page, "该名称是非法名,请换一个角色名称!");
            return;
        }

        Model.Role r = new Model.Role();
        r.RoleCode = lab_Code.Text;
        r.RoleName = txt_Name.Text.Trim();

        bool re = new RoleBLL().Update(r);

        if (re)
        {
            UtilityService.AlertAndRedirect(this, "修改成功!", "RoleMgr.aspx");
        }
        else
        {
            UtilityService.Alert(this, "修改失败!");
        }
    }
Пример #8
0
    protected void btn_Add_Click(object sender, EventArgs e)
    {
        if (txt_Name.Text.Trim().ToLower() == "admin")
        {
            UtilityService.Alert(this.Page, "admin是非法用户名,请换一个用户名称!");
            return;
        }


        Model.User u = new Model.User();
        u.UserID   = txt_UM.Text.Trim();
        u.UserName = txt_Name.Text.Trim();
        //u.Password = txt_Pwd.Text.Trim();
        u.Status   = 1;
        u.OrganID  = int.Parse(ddl_Organ.SelectedValue.ToString());//(int)Session["OrganID"];
        u.OpenDate = DateTime.Parse(txt_OpenDate.Text);
        u.InputBy  = Session["UserID"].ToString();

        DataSet oldU = new UserBLL().GetList(" UserID = '" + u.UserID + "'");

        if (oldU != null && oldU.Tables[0].Rows.Count > 0)
        {
            UtilityService.Alert(this, "该用户名已存在!");
            return;
        }

        int re = new UserBLL().Add(u);

        if (re > 0)
        {
            UtilityService.AlertAndRedirect(this, "添加成功!", "UserMgr.aspx");
        }
        else
        {
            UtilityService.Alert(this, "添加失败!");
        }
    }
        /// <summary>
        /// Insert new holiday canlendar.
        /// </summary>
        /// <param name="model">The holiday calendar information value.</param>
        /// <returns></returns>
        public ResultViewModel Save(HolidayCalendarViewModel model)
        {
            var result = new ResultViewModel();

            using (TransactionScope scope = new TransactionScope())
            {
                var data = new List <HolidayCalendar>();
                foreach (var item in model.HolidayList)
                {
                    data.Add(new HolidayCalendar
                    {
                        Year        = model.Year,
                        HolidayDate = UtilityService.ConvertToDateTime(item.HolidayDateString, ConstantValue.DateTimeFormat),
                        Description = item.Description,
                        CreateBy    = _token.EmpNo,
                        CreateDate  = DateTime.Now
                    });
                }
                _unitOfWork.GetRepository <HolidayCalendar>().AddRange(data);
                _unitOfWork.Complete(scope);
            }
            this.ReloadCacheHolidayCalendar();
            return(result);
        }
Пример #10
0
    protected void btn_Add_Click(object sender, EventArgs e)
    {
        if (txt_Name.Text.Trim() == "系统管理员" || txt_Name.Text.Trim() == "超级管理员")
        {
            UtilityService.Alert(this.Page, "该名称是非法名,请换一个角色名称!");
            return;
        }

        Model.Role r = new Model.Role();
        r.RoleName = txt_Name.Text.Trim();
        r.OrganID  = (int)Session["OrganID"];
        r.InputBy  = Session["UserID"].ToString();

        int re = new RoleBLL().Add(r);

        if (re > 0)
        {
            UtilityService.AlertAndRedirect(this, "添加成功!", "RoleMgr.aspx");
        }
        else
        {
            UtilityService.Alert(this, "添加失败!");
        }
    }
        /// <summary>
        /// Insert TimeSheet to database.
        /// </summary>
        /// <param name="timeSheetList">The TimeSheet information.</param>
        /// <param name="email">The owner timesheet and tasklist.</param>
        private void SaveTimeSheet(List <TimeSheetModel> timeSheetList, string email, ref ResultViewModel result)
        {
            foreach (var item in timeSheetList)
            {
                var data = new TimeSheet.Data.Pocos.TimeSheet
                {
                    Email         = email,
                    DateTimeStamp = UtilityService.ConvertToDateTime(item.DateTimeStamp, ConstantValue.DATE_TIME_FORMAT)
                };

                if (!IsAlreadyDateTimeStamp(data.DateTimeStamp.Value))
                {
                    _unitOfWork.GetRepository <Data.Pocos.TimeSheet>().Add(data);
                    _unitOfWork.Complete();

                    item.TaskList = item.TaskList.Select(c => { c.TimeSheetId = data.Id; return(c); }).ToList();
                    SaveTaskList(item.TaskList);
                }
                else
                {
                    result = UtilityService.InitialResultError($"The {data.DateTimeStamp.Value.ToString("yyyy-MM-dd")} is already exits.");
                }
            }
        }
Пример #12
0
        public async Task <IBookParser> ParseAsync(string url = null, Action <IBookParser, long> onCompleted = null, Action <IBookParser, Exception> onError = null, CancellationToken cancellationToken = default)
        {
            try
            {
                // get HTML of the book
                var stopwatch = Stopwatch.StartNew();
                var html      = await this.SourceUrl.GetVnThuQuanHtmlAsync("GET", this.ReferUrl, null, cancellationToken).ConfigureAwait(false);

                // parse to get details
                await UtilityService.ExecuteTask(() => this.ParseBook(html), cancellationToken).ConfigureAwait(false);

                // permanent identity
                if (string.IsNullOrWhiteSpace(this.PermanentID) || !this.PermanentID.IsValidUUID())
                {
                    this.PermanentID = (this.Title + " - " + this.Author).Trim().ToLower().GetMD5();
                }

                // callback when done
                stopwatch.Stop();
                onCompleted?.Invoke(this, stopwatch.ElapsedMilliseconds);
                return(this);
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception ex)
            {
                onError?.Invoke(this, ex);
                if (onError == null)
                {
                    throw;
                }
                return(this);
            }
        }
Пример #13
0
        public async Task <IBookshelfParser> ParseAsync(Action <IBookshelfParser, long> onCompleted = null, Action <IBookshelfParser, Exception> onError = null, CancellationToken cancellationToken = default)
        {
            // prepare
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            // get HTML
            var url = this.UrlPattern;

            this.UrlParameters.ForEach((parameter, index) => url = url.Replace("{" + index + "}", parameter));

            var html = "";

            try
            {
                html = await UtilityService.GetWebPageAsync(url, this.ReferUrl, UtilityService.SpiderUserAgent, cancellationToken).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                onError?.Invoke(this, ex);
                if (onError == null)
                {
                    throw;
                }
                return(this);
            }

            // parse
            await this.ParseAsync(html, cancellationToken).ConfigureAwait(false);

            // callback when done
            stopwatch.Stop();
            onCompleted?.Invoke(this, stopwatch.ElapsedMilliseconds);
            return(this);
        }
Пример #14
0
        private void generateSaleTicketFooter()
        {
            this.setPrintFont(this.defaultTicketFontName, this.defaultTicketFontSize, FontStyle.Regular);
            this.drawCenterLine(" RECUERDE QUE ", 0, "=");
            // Imprimir factores de premio
            this.printPrizeFactors();
            // Imprimir leyendas finales
            line = "*** REVISE SU TIQUETE ***";
            this.drawCenterLine(line);
            line = "*** GRACIAS Y SUERTE ***";
            this.drawCenterLine(line);
            line = "NO SE PAGA SIN TIQUETE";
            this.drawCenterLine(line);
            line = "***";
            // Imprimir identificador del ticket
            this.drawCenterLine(line);
            this.setPrintFont(this.defaultTicketFontName, this.defaultTicketFontSize + 2, FontStyle.Regular);
            string globalId = this.fillString(UtilityService.getGlobalId(this.saleTicket.ticketId), 6, "0");

            line = "----< " + globalId + " >----";
            this.drawCenterLine(line);
            // Imprimir líneas de espacio finales
            this.printFinalLines();
        }
Пример #15
0
    protected void btn_Delete_Click(object sender, ImageClickEventArgs e)
    {
        string idList = string.Empty;

        foreach (GridViewRow dr in GridView1.Rows)
        {
            CheckBox chk = (CheckBox)dr.FindControl("chk");
            if (chk != null && chk.Checked)
            {
                string _id = "'" + dr.Cells[1].Text.Trim() + "'";

                string _name = dr.Cells[2].Text.Trim();

                if (_name == "admin")
                {
                    UtilityService.Alert(this.Page, "禁止删除系统管理员");
                    return;
                }

                idList += _id + ",";
            }
        }
        if (idList.Length > 0)
        {
            idList = idList.TrimEnd(',');
            bool re = new UserBLL().DeleteList(idList);
            if (re)
            {
                UtilityService.AlertAndRedirect(this.Page, "删除成功!", "UserMgr.aspx");
            }
            else
            {
                UtilityService.Alert(this.Page, "删除失败!");
            }
        }
    }
Пример #16
0
        private void aboutButton_Click(object sender, EventArgs e)
        {
            /*
            ServerConnectionService serverConnection = new ServerConnectionService();
            Object result = serverConnection.synchronizeDrawAssociation().result;
            Console.WriteLine(result);
            JObject jsonObject = JObject.FromObject(result);
            Console.WriteLine(jsonObject);
            string createDate = (string) jsonObject["createDate"];
            Console.WriteLine(createDate);
            JObject draw = (JObject) jsonObject["lotteryDraw"];
            Console.WriteLine(draw);
            */

            /*
            DisplayQRForm qrForm = new DisplayQRForm();
            qrForm.Show();
            */

            String version = UtilityService.getApplicationVersion();
            String serviceUrl = ServiceConectionConstants.getServiceApiEndPoint();
            MessageBox.Show($"SILO Application. Version: {version}\n\nServicio: {serviceUrl}");
            
        }
Пример #17
0
        /// <summary>
        /// Setup the logging.
        /// </summary>
        /// <param name="encodeQueueTask">
        /// The encode QueueTask.
        /// </param>
        private void SetupLogging(QueueTask encodeQueueTask)
        {
            string logDir   = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
            string logFile  = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", Init.InstanceId));
            string logFile2 = Path.Combine(logDir, string.Format("tmp_appReadable_log{0}.txt", Init.InstanceId));

            try
            {
                logBuffer = new StringBuilder();

                // Clear the current Encode Logs
                if (File.Exists(logFile))
                {
                    File.Delete(logFile);
                }
                if (File.Exists(logFile2))
                {
                    File.Delete(logFile2);
                }

                fileWriter = new StreamWriter(logFile)
                {
                    AutoFlush = true
                };
                fileWriter.WriteLine(UtilityService.CreateCliLogHeader(encodeQueueTask));
            }
            catch (Exception)
            {
                if (fileWriter != null)
                {
                    fileWriter.Close();
                    fileWriter.Dispose();
                }
                throw;
            }
        }
 protected void GetQueryString()
 {
     //初次加载一些参数设置成默认值
     ReportTitle   = "生命周期";
     AxisJsonStr   = "{}";
     SeriesJsonStr = "[]";
     if (HeadControl1.IsFirstLoad)
     {
         SoftID                  = CookieSoftid;
         PlatformID              = CookiePlatid;
         StartDateTime           = UtilityService.GetInstance().GetMaxTimeCache(net91com.Stat.Core.PeriodOptions.Daily, ReportType.UserLifecycle, CacheTimeOption.TenMinutes).AddMonths(-2);
         HeadControl1.SoftID     = SoftID.ToString();
         HeadControl1.PlatID     = PlatformID.ToString();
         HeadControl1.SingleTime = StartDateTime;
     }
     else  //用户选择模式
     {
         string beginstr = Request["inputtimestart"] == null ? "" : Request["inputtimestart"];
         StartDateTime = HeadControl1.SingleTime;
         PlatformID    = Convert.ToInt32(HeadControl1.PlatID);
         SoftID        = Convert.ToInt32(HeadControl1.SoftID);
         SetRequestCookie(SoftID, PlatformID);
     }
 }
        public ActionResult ImportExcel(string fileName)
        {
            List <InvoiceUploadItemViewModel> uploadInvoiceItemViewModel = new List <InvoiceUploadItemViewModel>();
            InvoiceUploadService service = new InvoiceUploadService();
            var result = service.ImportExcel(fileName);

            if (!result.ErrorFlag)
            {
                uploadInvoiceItemViewModel = result.ReturnResult;


                return(new JsonResult()
                {
                    Data = new
                    {
                        success = !result.ErrorFlag,
                        responseText = result.Message,
                        html = UtilityService.RenderPartialView(this, "~/Views/InvoiceUpload/InvoiceUploadItems.cshtml", uploadInvoiceItemViewModel)
                    },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    MaxJsonLength = Int32.MaxValue // Use this value to set your maximum size for all of your Requests
                });
            }
            else
            {
                return(Json(
                           new
                {
                    success = !result.ErrorFlag,
                    responseText = result.Message,
                    html = "",
                    errorList = result.ModelStateErrorList
                },
                           JsonRequestBehavior.AllowGet));
            }
        }
Пример #20
0
        public async Task Invoke(HttpContext httpContext)
        {
            string requestPath = httpContext.Request.Path.ToString().ToLower();

            //判断请求路径是否是不需要排除权限限制的
            if (AppHostDefaults.PublicUris.Contains(requestPath))
            {
                await _nextDelegate(httpContext);

                return;
            }
            //从request header中寻找authorization token
            string userToken = string.Empty;
            bool   hasValue  = httpContext.Request.Headers.TryGetValue(AppHostDefaults.INVOKER_TOKEN_HEADER, out StringValues token);

            if (!hasValue || token.Count == 0)
            {
                //从request cookie中找token
                userToken = httpContext.Request.Cookies[AppHostDefaults.INVOKER_TOKEN_HEADER];
                if (string.IsNullOrWhiteSpace(userToken))
                {
                    //未授权,跳转到授权入口
                    await UtilityService.CreateUnauthorizedResponse(httpContext);

                    return;
                }
            }
            else
            {
                userToken = token[0];
            }

            //TO DO: check that whether the token is valid

            await _nextDelegate(httpContext);
        }
Пример #21
0
 public Task SendUpdateMessagesAsync(List <BaseMessage> messages, string deviceID, string excludedDeviceID, CancellationToken cancellationToken = default)
 => UtilityService.ExecuteTask(() =>
 {
     using (var publisher = messages.Select(message => new UpdateMessage
     {
         Type = message.Type,
         Data = message.Data,
         DeviceID = deviceID,
         ExcludedDeviceID = excludedDeviceID
     }).ToObservable().Subscribe(
                message =>
     {
         this.GetUpdateMessagePublisher().OnNext(message);
         Global.OnSendRTUMessageSuccess?.Invoke(
             $"Publish an update message successful" + "\r\n" +
             $"- Device: {message.DeviceID}" + "\r\n" +
             $"- Excluded: {(string.IsNullOrWhiteSpace(message.ExcludedDeviceID) ? "None" : message.ExcludedDeviceID)}" + "\r\n" +
             $"- Type: {message.Type}" + "\r\n" +
             $"- Data: {message.Data.ToString(Formatting.None)}"
             );
     },
                exception => Global.OnSendRTUMessageFailure?.Invoke($"Error occurred while publishing an update message: {exception.Message}", exception)
                )) { }
 }, cancellationToken);
        /// <summary>
        /// Add produces response type to attribute filter.
        /// </summary>
        /// <param name="context">The context object for <see cref="IApplicationModelProvider" /></param>
        public void OnProvidersExecuting(ApplicationModelProviderContext context)
        {
            foreach (ControllerModel controller in context.Result.Controllers)
            {
                foreach (ActionModel action in controller.Actions)
                {
                    var genericReturnType = action.ActionMethod.ReturnType.GenericTypeArguments;
                    if (genericReturnType.Length > 0)
                    {
                        action.Filters.Add(new ProducesResponseTypeAttribute(genericReturnType[0],
                                                                             StatusCodes.Status200OK));
                    }

                    action.Filters.Add(new ProducesResponseTypeAttribute(UtilityService.InitialResultError("").GetType(),
                                                                         StatusCodes.Status400BadRequest));
                    action.Filters.Add(new ProducesResponseTypeAttribute(UtilityService.InitialResultError("").GetType(),
                                                                         StatusCodes.Status401Unauthorized));
                    action.Filters.Add(new ProducesResponseTypeAttribute(UtilityService.InitialResultError("").GetType(),
                                                                         StatusCodes.Status403Forbidden));
                    action.Filters.Add(new ProducesResponseTypeAttribute(UtilityService.InitialResultError("").GetType(),
                                                                         StatusCodes.Status500InternalServerError));
                }
            }
        }
        private bool isWritableDirectory(string pstrPath)
        {
            UtilityService util = new UtilityService();

            return(util.isWritableDirectory(pstrPath));
        }
Пример #24
0
        static void Main(string[] args)
        {
            // setup environment
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
            Program.Arguments = args;

            // prepare logging
            var loglevel = args?.FirstOrDefault(a => a.IsStartsWith("/loglevel:"))?.Replace(StringComparison.OrdinalIgnoreCase, "/loglevel:", "");

            if (string.IsNullOrWhiteSpace(loglevel))
#if DEBUG
            { loglevel = UtilityService.GetAppSetting("Logs:Level", "Debug"); }
#else
            { loglevel = UtilityService.GetAppSetting("Logs:Level", "Information"); }
#endif
            if (!loglevel.TryToEnum(out LogLevel logLevel))
#if DEBUG
            { logLevel = LogLevel.Debug; }
#else
            { logLevel = LogLevel.Information; }
#endif

            Components.Utility.Logger.AssignLoggerFactory(new ServiceCollection().AddLogging(builder => builder.SetMinimumLevel(logLevel)).BuildServiceProvider().GetService <ILoggerFactory>());

            var logPath = UtilityService.GetAppSetting("Path:Logs");
            if (logPath != null && Directory.Exists(logPath))
            {
                logPath = Path.Combine(logPath, "{Hour}_apigateway.controller.txt");
                Components.Utility.Logger.GetLoggerFactory().AddFile(logPath, logLevel);
            }
            else
            {
                logPath = null;
            }

            Program.Logger = Components.Utility.Logger.CreateLogger <Controller>();

            JsonConvert.DefaultSettings = () => new JsonSerializerSettings
            {
                Formatting            = Formatting.None,
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                DateTimeZoneHandling  = DateTimeZoneHandling.Local
            };

            // prepare outgoing proxy
            var proxy = UtilityService.GetAppSetting("Proxy:Host");
            if (!string.IsNullOrWhiteSpace(proxy))
            {
                try
                {
                    UtilityService.AssignWebProxy(proxy, UtilityService.GetAppSetting("Proxy:Port").CastAs <int>(), UtilityService.GetAppSetting("Proxy:User"), UtilityService.GetAppSetting("Proxy:UserPassword"), UtilityService.GetAppSetting("Proxy:Bypass")?.ToArray(";"));
                }
                catch (Exception ex)
                {
                    Program.Logger.LogError($"Error occurred while assigning web-proxy => {ex.Message}", ex);
                }
            }

            // setup event handlers
            Program.SetupEventHandlers();

            // run as a Windows desktop app
            if (Environment.UserInteractive)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Program.MainForm = new MainForm();
                Application.Run(Program.MainForm);
            }

            // run as a Windows service
            else
            {
                System.ServiceProcess.ServiceBase.Run(new ServiceRunner());
            }
        }
Пример #25
0
 internal static async Task <IPAddress> GetByIpifyAsync(CancellationToken cancellationToken = default)
 => IPAddress.Parse(Utility.PublicAddressRegex.Matches(await UtilityService.GetWebPageAsync("http://api.ipify.org/", null, null, cancellationToken).ConfigureAwait(false))[0].ToString());
Пример #26
0
        public static void Start(string[] args)
        {
            var stopwatch         = Stopwatch.StartNew();
            var isUserInteractive = Environment.UserInteractive && args?.FirstOrDefault(a => a.IsStartsWith("/daemon")) == null;

            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
            JsonConvert.DefaultSettings = () => new JsonSerializerSettings
            {
                Formatting            = Formatting.None,
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                DateTimeZoneHandling  = DateTimeZoneHandling.Local
            };
            if (isUserInteractive)
            {
                Console.OutputEncoding = System.Text.Encoding.UTF8;
            }

            // prepare logging
#if DEBUG
            var logLevel = LogLevel.Debug;
#else
            var logLevel = LogLevel.Information;
            try
            {
                logLevel = UtilityService.GetAppSetting("Logs:Level", "Information").ToEnum <LogLevel>();
            }
            catch { }
#endif

            Components.Utility.Logger.AssignLoggerFactory(new ServiceCollection().AddLogging(builder =>
            {
                builder.SetMinimumLevel(logLevel);
                if (isUserInteractive)
                {
                    builder.AddConsole();
                }
            }).BuildServiceProvider().GetService <ILoggerFactory>());

            var logPath = UtilityService.GetAppSetting("Path:Logs");
            if (logPath != null && Directory.Exists(logPath))
            {
                logPath = Path.Combine(logPath, "{Date}_apiwatcher.txt");
                Components.Utility.Logger.GetLoggerFactory().AddFile(logPath, logLevel);
            }
            else
            {
                logPath = null;
            }

            ServiceWatcher.Logger = Components.Utility.Logger.CreateLogger <Watcher>();

            var watchingProcessID = Process.GetCurrentProcess().Id;
            var watchingTime      = DateTime.Now.AddMinutes(-90);
            var watchingInterval  = UtilityService.GetAppSetting("TimerInterval:Watcher", "120").CastAs <int>();
            var watchingServices  = new Dictionary <string, Tuple <string, string> >(StringComparer.OrdinalIgnoreCase);

            if (System.Configuration.ConfigurationManager.GetSection(UtilityService.GetAppSetting("Section:Services", "net.vieapps.services")) is AppConfigurationSectionHandler config)
            {
                if (config.Section.SelectNodes("./service") is System.Xml.XmlNodeList services)
                {
                    services
                    .ToList()
                    .Where(service => !string.IsNullOrWhiteSpace(service.Attributes["name"]?.Value))
                    .ForEach(service => watchingServices[service.Attributes["name"].Value] = new Tuple <string, string>(service.Attributes["beKilledFirstProcesses"]?.Value, service.Attributes["executable"]?.Value));
                }
            }

            void kill(string processName)
            {
                Process.GetProcessesByName(processName).ForEach(process =>
                {
                    try
                    {
                        process.StandardInput.WriteLine("exit");
                        process.StandardInput.Close();
                        process.WaitForExit(789);
                        process.Refresh();
                        if (process.HasExited)
                        {
                            ServiceWatcher.Logger.LogInformation($"Process {process.ProcessName} ({process.StartInfo.FileName}{(string.IsNullOrWhiteSpace(process.StartInfo.Arguments) ? "" : $" {process.StartInfo.Arguments}")}) has been stopped");
                        }
 public string GetRandomString(int length, bool useNumber = true, bool useLower  = true, bool useUpper = true
                               , bool useSpecial          = false, string custom = "", string start    = "")
 {
     return(UtilityService.GetRandomString(length, useNumber, useLower, useUpper, useSpecial, custom, start));
 }
Пример #28
0
 public UtilityController(TemplateService templateService, UtilityService utilityService)
 {
     this._templateService = templateService;
     this._utilityService  = utilityService;
 }
Пример #29
0
        async Task ReceiveAsync(HttpContext context, CancellationToken cancellationToken)
        {
            // prepare
            var stopwatch   = Stopwatch.StartNew();
            var serviceName = context.GetParameter("x-service-name");
            var objectName  = context.GetParameter("x-object-name");
            var systemID    = context.GetParameter("x-system-id");
            var entityInfo  = context.GetParameter("x-entity");
            var objectID    = context.GetParameter("x-object-id");
            var isTemporary = "true".IsEquals(context.GetParameter("x-temporary"));

            if (string.IsNullOrWhiteSpace(objectID))
            {
                throw new InvalidRequestException("Invalid object identity");
            }

            // check permissions
            var gotRights = isTemporary
                                ? await context.CanContributeAsync(serviceName, objectName, systemID, entityInfo, "", cancellationToken).ConfigureAwait(false)
                                : await context.CanEditAsync(serviceName, objectName, systemID, entityInfo, objectID, cancellationToken).ConfigureAwait(false);

            if (!gotRights)
            {
                throw new AccessDeniedException();
            }

            // limit size - default is 512 KB
            if (!Int32.TryParse(UtilityService.GetAppSetting("Limits:Thumbnail"), out var limitSize))
            {
                limitSize = 512;
            }

            // read upload file
            var thumbnails = new List <byte[]>();
            var asBase64   = context.GetParameter("x-as-base64") != null;

            if (asBase64)
            {
                var base64Data = (await context.ReadTextAsync(cancellationToken).ConfigureAwait(false)).ToJson()["Data"];
                if (base64Data is JArray)
                {
                    (base64Data as JArray).Take(7).ForEach(data =>
                    {
                        var thumbnail = (data as JValue).Value.ToString().ToArray().Last().Base64ToBytes();
                        if (thumbnail != null && thumbnail.Length <= limitSize * 1024)
                        {
                            thumbnails.Add(thumbnail);
                        }
                        else
                        {
                            thumbnails.Add(null);
                        }
                    });
                }
                else
                {
                    thumbnails.Add((base64Data as JValue).Value.ToString().ToArray().Last().Base64ToBytes());
                }
            }
            else
            {
                for (var index = 0; index < context.Request.Form.Files.Count && index < 7; index++)
                {
                    thumbnails.Add(null);
                }
                await context.Request.Form.Files.Take(7).ForEachAsync(async(file, index, _) =>
                {
                    if (file != null && file.ContentType.IsStartsWith("image/") && file.Length > 0 && file.Length <= limitSize * 1024)
                    {
                        using (var stream = file.OpenReadStream())
                        {
                            var thumbnail = new byte[file.Length];
                            await stream.ReadAsync(thumbnail, 0, (int)file.Length, cancellationToken).ConfigureAwait(false);
                            thumbnails[index] = thumbnail;
                        }
                    }
                }, cancellationToken, true, false).ConfigureAwait(false);
            }

            // save uploaded files & create meta info
            var attachments = new List <AttachmentInfo>();
            var useCache    = "true".IsEquals(UtilityService.GetAppSetting("Files:Cache:Thumbnails", "true")) && Global.Cache != null;

            try
            {
                // save uploaded files into disc
                var title = "";
                try
                {
                    title = context.GetParameter("x-object-title")?.Url64Decode()?.GetANSIUri() ?? UtilityService.NewUUID;
                }
                catch
                {
                    title = UtilityService.NewUUID;
                }
                await thumbnails.ForEachAsync(async (thumbnail, index, _) =>
                {
                    if (thumbnail != null)
                    {
                        // prepare
                        var attachment = new AttachmentInfo
                        {
                            ID          = context.GetParameter("x-attachment-id") ?? UtilityService.NewUUID,
                            ServiceName = serviceName,
                            ObjectName  = objectName,
                            SystemID    = systemID,
                            EntityInfo  = entityInfo,
                            ObjectID    = objectID,
                            Size        = thumbnail.Length,
                            Filename    = $"{objectID}{(index > 0 ? $"-{index}" : "")}.jpg",
                            ContentType = "image/jpeg",
                            IsShared    = false,
                            IsTracked   = false,
                            IsTemporary = isTemporary,
                            Title       = title,
                            Description = "",
                            IsThumbnail = true
                        };

                        // save file into temporary directory
                        await UtilityService.WriteBinaryFileAsync(attachment.GetFilePath(true), thumbnail, false, cancellationToken).ConfigureAwait(false);

                        // update attachment info
                        attachments.Add(attachment);
                    }
                }, cancellationToken, true, false).ConfigureAwait(false);

                // create meta info
                var response  = new JArray();
                var cacheKeys = new List <string>();
                await attachments.ForEachAsync(async (attachment, token) =>
                {
                    response.Add(await context.CreateAsync(attachment, token).ConfigureAwait(false));
                    if (useCache)
                    {
                        var keys = await Global.Cache.GetSetMembersAsync($"{attachment.ObjectID}:Thumbnails", cancellationToken).ConfigureAwait(false);
                        if (keys != null && keys.Count > 0)
                        {
                            cacheKeys = cacheKeys.Concat(new[] { $"{attachment.ObjectID}:Thumbnails" }).Concat(keys).ToList();
                        }
                    }
                }, cancellationToken, true, false).ConfigureAwait(false);

                // clear cache
                if (useCache && cacheKeys.Count > 0)
                {
                    await Global.Cache.RemoveAsync(cacheKeys.Distinct(StringComparer.OrdinalIgnoreCase).ToList(), cancellationToken).ConfigureAwait(false);
                }

                // move files from temporary directory to official directory
                attachments.ForEach(attachment => attachment.PrepareDirectories().MoveFile(this.Logger, "Http.Uploads", true));

                // response
                await context.WriteAsync(response, cancellationToken).ConfigureAwait(false);

                stopwatch.Stop();
                if (Global.IsDebugLogEnabled)
                {
                    await context.WriteLogsAsync(this.Logger, "Http.Uploads", $"{thumbnails.Count(thumbnail => thumbnail != null)} thumbnail image(s) has been uploaded - Mode:  {(asBase64 ? "base64" : "file")} - Execution times: {stopwatch.GetElapsedTimes()}").ConfigureAwait(false);
                }
            }
            catch (Exception)
            {
                attachments.ForEach(attachment => attachment.DeleteFile(true, this.Logger, "Http.Uploads"));
                throw;
            }
        }
Пример #30
0
        async Task ShowAsync(HttpContext context, CancellationToken cancellationToken)
        {
            // check "If-Modified-Since" request to reduce traffict
            var requestUri   = context.GetRequestUri();
            var useCache     = "true".IsEquals(UtilityService.GetAppSetting("Files:Cache:Thumbnails", "true")) && Global.Cache != null;
            var cacheKey     = $"{requestUri}".ToLower().GenerateUUID();
            var lastModified = useCache ? await Global.Cache.GetAsync <string>($"{cacheKey}:time", cancellationToken).ConfigureAwait(false) : null;

            var eTag          = $"thumbnail#{cacheKey}";
            var noneMatch     = context.GetHeaderParameter("If-None-Match");
            var modifiedSince = context.GetHeaderParameter("If-Modified-Since") ?? context.GetHeaderParameter("If-Unmodified-Since");

            if (eTag.IsEquals(noneMatch) && modifiedSince != null && lastModified != null && modifiedSince.FromHttpDateTime() >= lastModified.FromHttpDateTime())
            {
                context.SetResponseHeaders((int)HttpStatusCode.NotModified, eTag, lastModified.FromHttpDateTime().ToUnixTimestamp(), "public", context.GetCorrelationID());
                if (Global.IsDebugLogEnabled)
                {
                    await context.WriteLogsAsync(this.Logger, "Http.Thumbnails", $"Response to request with status code 304 to reduce traffic ({requestUri})").ConfigureAwait(false);
                }
                return;
            }

            // prepare
            var requestUrl  = $"{requestUri}";
            var queryString = requestUri.ParseQuery();

            var isNoThumbnailImage = requestUri.PathAndQuery.IsStartsWith("/thumbnail") && (requestUri.PathAndQuery.IsEndsWith("/no-image.png") || requestUri.PathAndQuery.IsEndsWith("/no-image.jpg"));
            var pathSegments       = requestUri.GetRequestPathSegments();

            var serviceName = pathSegments.Length > 1 && !pathSegments[1].IsValidUUID() ? pathSegments[1] : "";
            var systemID    = pathSegments.Length > 1 && pathSegments[1].IsValidUUID() ? pathSegments[1].ToLower() : "";
            var identifier  = pathSegments.Length > 5 && pathSegments[5].IsValidUUID() ? pathSegments[5].ToLower() : "";

            if (!isNoThumbnailImage && (string.IsNullOrWhiteSpace(identifier) || (string.IsNullOrWhiteSpace(serviceName) && string.IsNullOrWhiteSpace(systemID))))
            {
                throw new InvalidRequestException();
            }

            var handlerName = pathSegments[0];
            var format      = handlerName.IsEndsWith("pngs") || (isNoThumbnailImage && Handler.NoThumbnailImageFilePath.IsEndsWith(".png")) || context.GetQueryParameter("asPng") != null || context.GetQueryParameter("transparent") != null
                                ? "PNG"
                                : handlerName.IsEndsWith("webps")
                                        ? "WEBP"
                                        : "JPG";
            var isBig       = handlerName.IsStartsWith("thumbnaibig");
            var isThumbnail = isNoThumbnailImage || (pathSegments.Length > 2 && Int32.TryParse(pathSegments[2], out var isAttachment) && isAttachment == 0);

            if (!Int32.TryParse(pathSegments.Length > 3 ? pathSegments[3] : "", out var width))
            {
                width = 0;
            }
            if (!Int32.TryParse(pathSegments.Length > 4 ? pathSegments[4] : "", out var height))
            {
                height = 0;
            }
            var isCropped       = requestUrl.IsContains("--crop") || queryString.ContainsKey("crop");
            var croppedPosition = requestUrl.IsContains("--crop-top") || "top".IsEquals(context.GetQueryParameter("cropPos")) ? "top" : requestUrl.IsContains("--crop-bottom") || "bottom".IsEquals(context.GetQueryParameter("cropPos")) ? "bottom" : "auto";
            //var isUseAdditionalWatermark = queryString.ContainsKey("nw") ? false : requestUrl.IsContains("--btwm");

            var attachment = new AttachmentInfo
            {
                ID          = identifier,
                ServiceName = serviceName,
                SystemID    = systemID,
                IsThumbnail = isThumbnail,
                Filename    = isThumbnail
                                        ? identifier + (pathSegments.Length > 6 && Int32.TryParse(pathSegments[6], out var index) && index > 0 ? $"-{index}" : "") + ".jpg"
                                        : pathSegments.Length > 6 ? pathSegments[6].UrlDecode() : "",
                IsTemporary = false,
                IsTracked   = false
            };

            if ("webp".IsEquals(format) && pathSegments[2].Equals("1") && attachment.Filename.IsEndsWith(".webp"))
            {
                attachment.Filename = attachment.Filename.Left(attachment.Filename.Length - 5);
            }

            // check existed
            var isCached  = false;
            var hasCached = useCache && await Global.Cache.ExistsAsync(cacheKey, cancellationToken).ConfigureAwait(false);

            FileInfo fileInfo = null;

            if (!hasCached)
            {
                fileInfo = new FileInfo(isNoThumbnailImage ? Handler.NoThumbnailImageFilePath : attachment.GetFilePath());
                if (!fileInfo.Exists)
                {
                    context.ShowHttpError((int)HttpStatusCode.NotFound, "Not Found", "FileNotFoundException", context.GetCorrelationID());
                    return;
                }
            }

            // check permission
            async Task <bool> gotRightsAsync()
            {
                if (!isThumbnail)
                {
                    attachment = await context.GetAsync(attachment.ID, cancellationToken).ConfigureAwait(false);

                    return(await context.CanDownloadAsync(attachment, cancellationToken).ConfigureAwait(false));
                }
                return(true);
            }

            // generate
            async Task <byte[]> getAsync()
            {
                var thumbnail = useCache ? await Global.Cache.GetAsync <byte[]>(cacheKey, cancellationToken).ConfigureAwait(false) : null;

                if (thumbnail != null)
                {
                    isCached = true;
                    if (Global.IsDebugLogEnabled)
                    {
                        await context.WriteLogsAsync(this.Logger, "Http.Thumbnails", $"Cached thumbnail was found ({requestUri})").ConfigureAwait(false);
                    }
                }
                return(thumbnail);
            }

            async Task <byte[]> generateAsync()
            {
                byte[] thumbnail;

                // generate
                try
                {
                    using (var stream = UtilityService.CreateMemoryStream())
                    {
                        using (var image = this.Generate(fileInfo.FullName, width, height, isBig, isCropped, croppedPosition))
                        {
                            // add watermark

                            // get thumbnail image
                            image.Save(stream, "png".IsEquals(format) ? ImageFormat.Png : ImageFormat.Jpeg);
                        }
                        thumbnail = stream.ToBytes();
                    }
                }

                // read the whole file when got error
                catch (Exception ex)
                {
                    await context.WriteLogsAsync(this.Logger, "Http.Thumbnails", $"Error occurred while generating thumbnail using Bitmap/Graphics => {ex.Message}", ex).ConfigureAwait(false);

                    thumbnail = await UtilityService.ReadBinaryFileAsync(fileInfo, cancellationToken).ConfigureAwait(false);
                }

                // update cache
                if (useCache)
                {
                    await Task.WhenAll
                    (
                        Global.Cache.AddSetMemberAsync($"{(attachment.SystemID.IsValidUUID() ? attachment.SystemID : attachment.ServiceName)}:Thumbnails", $"{attachment.ObjectID}:Thumbnails", cancellationToken),
                        Global.Cache.AddSetMemberAsync($"{attachment.ObjectID}:Thumbnails", cacheKey, cancellationToken),
                        Global.Cache.SetAsFragmentsAsync(cacheKey, thumbnail, 1440, cancellationToken),
                        Global.Cache.SetAsync($"{cacheKey}:time", fileInfo.LastWriteTime.ToHttpString(), 1440, cancellationToken),
                        Global.IsDebugLogEnabled?context.WriteLogsAsync(this.Logger, "Http.Thumbnails", $"Update a thumbnail image into cache successful [{requestUri} => {fileInfo.FullName}]") : Task.CompletedTask
                    ).ConfigureAwait(false);
                }

                return(thumbnail);
            }

            // prepare the thumbnail image
            var generateTask = hasCached ? getAsync() : generateAsync();

            if (!await gotRightsAsync().ConfigureAwait(false))
            {
                throw new AccessDeniedException();
            }

            // flush the thumbnail image to output stream, update counter & logs
            var bytes = await generateTask.ConfigureAwait(false);

            lastModified = lastModified ?? fileInfo.LastWriteTime.ToHttpString();
            var lastModifiedTime = lastModified.FromHttpDateTime().ToUnixTimestamp();

            if ("webp".IsEquals(format))
            {
                if (isCached)
                {
                    using (var stream = UtilityService.CreateMemoryStream(bytes))
                    {
                        await context.WriteAsync(stream, "image/webp", null, eTag, lastModifiedTime, "public", TimeSpan.FromDays(366), null, context.GetCorrelationID(), cancellationToken).ConfigureAwait(false);
                    }
                }
                else
                {
                    using (var imageFactory = new ImageFactory())
                        using (var stream = UtilityService.CreateMemoryStream())
                        {
                            imageFactory.Load(bytes);
                            imageFactory.Quality = 100;
                            imageFactory.Save(stream);
                            await context.WriteAsync(stream, "image/webp", null, eTag, lastModifiedTime, "public", TimeSpan.FromDays(366), null, context.GetCorrelationID(), cancellationToken).ConfigureAwait(false);

                            if (useCache)
                            {
                                await Task.WhenAll
                                (
                                    Global.Cache.SetAsFragmentsAsync(cacheKey, stream.ToBytes(), cancellationToken),
                                    Global.IsDebugLogEnabled?context.WriteLogsAsync(this.Logger, "Http.Thumbnails", $"Re-update a thumbnail image with WebP image format into cache successful ({requestUri})") : Task.CompletedTask
                                ).ConfigureAwait(false);
                            }
                        }
                }
            }
            else
            {
                using (var stream = UtilityService.CreateMemoryStream(bytes))
                {
                    await context.WriteAsync(stream, $"image/{("png".IsEquals(format) ? "png" : "jpeg")}", null, eTag, lastModifiedTime, "public", TimeSpan.FromDays(366), null, context.GetCorrelationID(), cancellationToken).ConfigureAwait(false);
                }
            }

            await Task.WhenAll
            (
                context.UpdateAsync(attachment, "Direct", cancellationToken),
                Global.IsDebugLogEnabled?context.WriteLogsAsync(this.Logger, "Http.Thumbnails", $"Successfully show a thumbnail image ({requestUri})") : Task.CompletedTask
            ).ConfigureAwait(false);
        }

        Bitmap Generate(string filePath, int width, int height, bool asBig, bool isCropped, string cropPosition)
        {
            using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, TextFileReader.BufferSize))
            {
                using (var image = Image.FromStream(stream) as Bitmap)
                {
                    // clone original image
                    if ((width < 1 && height < 1) || (width.Equals(image.Width) && height.Equals(image.Height)))
                    {
                        return(image.Clone() as Bitmap);
                    }

                    // calculate size depend on width
                    if (height < 1)
                    {
                        height = image.Height * width / image.Width;
                        if (height < 1)
                        {
                            height = image.Height;
                        }
                    }

                    // calculate size depend on height
                    else if (width < 1)
                    {
                        width = image.Width * height / image.Height;
                        if (width < 1)
                        {
                            width = image.Width;
                        }
                    }

                    // generate thumbnail
                    return(isCropped
                                                ? this.Generate(image, width, height, asBig, cropPosition)
                                                : this.Generate(image, width, height, asBig));
                }
            }
        }

        Bitmap Generate(Bitmap image, int width, int height, bool asBig, string cropPosition)
        {
            using (var thumbnail = this.Generate(image, width, (image.Height * width) / image.Width, asBig))
            {
                // if height is less than thumbnail image's height, then return thumbnail image
                if (thumbnail.Height <= height)
                {
                    return(thumbnail.Clone() as Bitmap);
                }

                // crop image
                int top = cropPosition.IsEquals("auto")
                                        ? (thumbnail.Height - height) / 2
                                        : cropPosition.IsEquals("bottom")
                                                ? thumbnail.Height - height
                                                : 0;
                using (var cropped = new Bitmap(width, height))
                {
                    using (var graphics = Graphics.FromImage(cropped))
                    {
                        graphics.DrawImage(thumbnail, new Rectangle(0, 0, width, height), new Rectangle(0, top, width, height), GraphicsUnit.Pixel);
                    }
                    return(cropped.Clone() as Bitmap);
                }
            }
        }

        Bitmap Generate(Bitmap image, int width, int height, bool asBig)
        {
            // get and return normal thumbnail
            if (!asBig)
            {
                return(image.GetThumbnailImage(width, height, null, IntPtr.Zero) as Bitmap);
            }

            // get and return big thumbnail (set resolution of original thumbnail)
            else
            {
                using (var thumbnail = new Bitmap(width, height))
                {
                    using (var graphics = Graphics.FromImage(thumbnail))
                    {
                        graphics.SmoothingMode     = SmoothingMode.HighQuality;
                        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        graphics.PixelOffsetMode   = PixelOffsetMode.HighQuality;
                        graphics.DrawImage(image, new Rectangle(0, 0, width, height));
                    }
                    return(thumbnail.Clone() as Bitmap);
                }
            }
        }