Example #1
0
        public async Task <OperationResultModel <ElectricMeterDto> > Add(ElectricMeterDto model)
        {
            var result = new OperationResultModel <ElectricMeterDto>();

            try
            {
                bool existAlready = await _electricMeterDao.GetBySerialNumber(model.SerialNumber) != null;

                if (existAlready)
                {
                    result.SetMessage("The electric meter is already registered");
                    return(result);
                }

                var device = await _electricMeterDao.Add(new ElectricMeter {
                    SerialNumber    = model.SerialNumber,
                    FirmwareVersion = model.FirmwareVersion,
                    State           = model.State
                });

                model.Id = device.Id;

                result
                .SetStatus(true)
                .SetMessage("Electric meter has been registered successfully")
                .SetData(model);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                result.SetMessage("Error creating an electric meter");
            }
            return(result);
        }
Example #2
0
        public ActionResult RDLExport(string exportFormat, string reportDirectory, string reportName)
        {
            OperationResultModel viewModel = new OperationResultModel();

            string exportPath = Path.Combine(Server.MapPath(ConfigurationHelper.AppSettings <string>("EasyLOB.Directory.Export")),
                                             reportName + String.Format(".{0:yyyyMMdd.HHmmss.fff}", DateTime.Now));

            IDictionary <string, string> reportParameters = new Dictionary <string, string>();

            if (System.Web.HttpContext.Current.Request.QueryString.Count > 3)
            {
                for (int q = 3; q < System.Web.HttpContext.Current.Request.QueryString.Count; q++)
                {
                    reportParameters.Add(System.Web.HttpContext.Current.Request.QueryString.AllKeys[q],
                                         System.Web.HttpContext.Current.Request.QueryString[q]);
                }
            }

            if (SyncfusionHelper.ExportRDL(viewModel.OperationResult, ref exportPath, exportFormat,
                                           reportDirectory, reportName, reportParameters))
            {
                byte[] file = System.IO.File.ReadAllBytes(exportPath);
                return(File(file,
                            LibraryHelper.GetContentType(LibraryHelper.GetFileType(Path.GetExtension(exportPath))),
                            Path.GetFileName(exportPath)));
            }

            return(ZViewOperationResult(viewModel.OperationResult));
        }
Example #3
0
        public ActionResult RDLC(string reportDirectory, string reportName)
        {
            OperationResultModel viewModel = new OperationResultModel();

            try
            {
                if (String.IsNullOrEmpty(reportName))
                {
                    viewModel.OperationResult.ErrorMessage = ErrorResources.RDL_Parameters;

                    return(ZViewOperationResult(viewModel.OperationResult));
                }
                else
                {
                    if (!IsReport(reportDirectory, reportName, viewModel.OperationResult))
                    {
                        return(ZViewOperationResult(viewModel.OperationResult));
                    }
                    else
                    {
                        ReportModelRDLC reportModel = new ReportModelRDLC();

                        reportModel.ReportDirectory = MultiTenantHelper.Tenant.Name +
                                                      (String.IsNullOrEmpty(reportDirectory) ? "" : "/" + reportDirectory);
                        reportModel.ReportName = reportName;

                        if (System.Web.HttpContext.Current.Request.QueryString.Count > 2)
                        {
                            for (int q = 2; q < System.Web.HttpContext.Current.Request.QueryString.Count; q++)
                            {
                                ReportParameter reportParameter = new ReportParameter()
                                {
                                    Name   = System.Web.HttpContext.Current.Request.QueryString.AllKeys[q],
                                    Labels = new List <string>()
                                    {
                                        ""
                                    },
                                    Prompt = "",
                                    Values = new List <string>()
                                    {
                                        System.Web.HttpContext.Current.Request.QueryString[q]
                                    },
                                    Nullable = true
                                };
                                reportModel.ReportParameters.Add(reportParameter);
                            }
                        }

                        return(ZView("RDLC", reportModel));
                    }
                }
            }
            catch (Exception exception)
            {
                viewModel.OperationResult.ParseException(exception);
            }

            return(ZViewOperationResult(viewModel.OperationResult));
        }
        public ActionResult ShopConnectorError(HttpStatusCode code, string message, string description = null)
        {
            Response.StatusCode = (int)code;

            var model = new OperationResultModel(message, true)
            {
                Description = description
            };

            return(Content(XmlHelper.Serialize(model)));
        }
Example #5
0
        public Task <string> ReportAsync(OperationResultModel operationResult)
        {
            var stringBuilder = new StringBuilder();

            foreach (var recognitionResult in operationResult.RecognitionResultCollection)
            {
                foreach (var line in recognitionResult.LineCollection)
                {
                    stringBuilder.AppendLine(line.Text);
                }
            }

            return(Task.FromResult(stringBuilder.ToString()));
        }
        public static OperationResultModel CreateAuthErrorModel(this ShopConnectorAuthResult result, ILocalizationService localize, HttpContextBase httpContext, string message = null)
        {
            var model = new OperationResultModel();

            string[] descriptions = localize.GetResource("Plugins.SmartStore.ShopConnector.ShopConnectorAuthResults").SplitSafe(";");
            var      description  = descriptions.SafeGet((int)result);

            model.HasError     = true;
            model.ShortMessage = "{0}: {1} ({2}).".FormatInvariant(localize.GetResource("Plugins.SmartStore.ShopConnector.UnauthorizedRequest"), description, result.ToString());

            if (message.HasValue())
            {
                model.ShortMessage = string.Concat(model.ShortMessage, " ", message);
            }

            model.Description = HttpUtility.UrlDecode(httpContext.Request.Headers.ToString().EmptyNull()).Replace("&", "\r\n");

            return(model);
        }
Example #7
0
        public override void ExecuteResult(ControllerContext context)
        {
            OperationResultModel model;

            if (_model != null)
            {
                model = _model;
            }
            else if (_context.ResponseModel != null)
            {
                model = _context.ResponseModel;
            }
            else
            {
                model = new OperationResultModel
                {
                    Description = _context.ToString()
                };

                if (_context.Status == HttpStatusCode.OK)
                {
                    model.ShortMessage = _context.Status.ToString();
                }
                else
                {
                    model.ShortMessage = string.Concat(_context.Status.ToString(), " ", EngineContext.Current.Resolve <ILocalizationService>().GetResource("Admin.Common.UnknownError"));
                }
            }

            var viewResult = new ViewResult
            {
                MasterName = "",
                ViewName   = "OperationResult",
                ViewData   = new ViewDataDictionary {
                    Model = model
                }
            };

            viewResult.ExecuteResult(context);
        }
Example #8
0
        public async Task <OperationResultModel <GatewayDto> > Add(GatewayDto model)
        {
            var result = new OperationResultModel <GatewayDto>();

            try
            {
                bool existAlready = await _gatewayDao.GetBySerialNumber(model.SerialNumber) != null;

                if (existAlready)
                {
                    result.SetMessage("The gateway is already registered");
                    return(result);
                }

                var device = await _gatewayDao.Add(new Gateway
                {
                    SerialNumber    = model.SerialNumber,
                    FirmwareVersion = model.FirmwareVersion,
                    State           = model.State,
                    IP   = model.IP,
                    Port = model.Port
                });

                model.Id = device.Id;

                result
                .SetStatus(true)
                .SetMessage("Gateway has been registered successfully")
                .SetData(model);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                result.SetMessage("Error creating a gateway");
            }
            return(result);
        }
        public async Task <IActionResult> Post(string id, IFormCollection form)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();

            _logger.LogDebug($"Postfile id={id}");
            string domainUrl = String.Empty;

            #region  基础请求内容的校验

            string strSubPath           = form["sub_dir_path"];             // 请求参数 -  子目录
            string strIsCreateSubPath   = form["is_create_sub_dir"];        //是创建子目录
            string strFile_exist_handle = form["file_exist_handle_option"]; // 请求参数,遇到重名文件时候的处理


            // 应用存储目录=存储+分配
            string strAppMainPath = "";

            // 应用存储目录+子目录
            string strFullDirectoryPath = "";

            //  判断 bse url
            if (!this._storageConfigModel.BaseUrl.EndsWith("/"))
            {
                return(new UnprocessableEntityObjectResult(new
                {
                    err_code = -101,
                    err_msg = $"基础域名 BaseUrl=[{this._storageConfigModel.BaseUrl}]配置不正确,名称需要以[/]结尾,请联系管理员"
                }));
            }

            //  判断 必填 strFile_exist_handle
            if (string.IsNullOrEmpty(strFile_exist_handle))
            {
                return(new BadRequestObjectResult(new
                {
                    err_code = -104,
                    err_msg = $"请求方的Post Form 必须包含属性[file_exist_handle_option],取值可选项有[Overwrite,Rename]"
                }));
            }

            // 判断 是否存在上传文件以及文件大小
            if (form.Files.Count < 1 || form.Files[0].Length < 1)
            {
                return(new BadRequestObjectResult(new
                {
                    err_code = -103,
                    err_msg = $"请求方的Post Form表单未设置文件对象,或者文件对象长度为0"
                }));
            }


            //判断根目录是否存在,不存则配置错误
            if (!Directory.Exists(this._storageConfigModel.StoragePath))
            {
                return(new UnprocessableEntityObjectResult(new
                {
                    err_code = -100,
                    err_msg = "根存储目录路径无法访问,根存储路径配置错误或没有权限,请联系管理员."
                }));
            }

            //判断 应用目录 长度
            if (id.Length > 127)
            {
                return(new BadRequestObjectResult(new
                {
                    err_code = -101,
                    err_msg = $"应用存储目录名称[{id}]不正确,目名不能以 / 开头结尾,不能使用除[-] [_] 之类特殊字符,最大长度128字符"
                }));
            }


            // 判断应用的存储目录,是否真实存在
            strAppMainPath = Path.Combine(this._storageConfigModel.StoragePath, id);
            if (!Directory.Exists(strAppMainPath))
            {
                return(new BadRequestObjectResult(new
                {
                    err_code = -102,
                    err_msg = $"应用存储目录路径{id}无法访问,可能未创建该目录或没权限,请联系管理员."
                }));
            }


            _logger.LogDebug($"Base Url={_storageConfigModel.BaseUrl}");

            // id合成域名
            domainUrl = String.Format(_storageConfigModel.BaseUrl, id);

            _logger.LogDebug($"合成域名 Url={domainUrl}");

            #endregion

            #region 处理目录路径 - 子目录

            // 获取子目录
            strIsCreateSubPath = string.IsNullOrEmpty(strIsCreateSubPath) ? "false" : strIsCreateSubPath.ToLowerInvariant();

            // 当子目录为空时, 不使用
            if (string.IsNullOrEmpty(strSubPath))
            {
                strSubPath           = "";
                strFullDirectoryPath = Path.Combine(strAppMainPath, strSubPath);
            }
            // 不为空的时候
            else
            {
                // 判断格式
                if (strSubPath.StartsWith("/"))
                {
                    return(new BadRequestObjectResult(new
                    {
                        err_code = -103,
                        err_msg = $"请求方的Post Form表单参数[sub_dir_path]=[{strSubPath}]设置错误,子目录路径不能以字符/开头"
                    }));
                }

                // 判断 实际的存储目录
                strFullDirectoryPath = Path.Combine(strAppMainPath, strSubPath);

                // 目标目录不存在
                if (!Directory.Exists(strFullDirectoryPath))
                {
                    if (strIsCreateSubPath.Equals("true"))
                    {
                        Directory.CreateDirectory(strFullDirectoryPath);
                        Console.WriteLine($"创建目录{strFullDirectoryPath}");
                    }
                    else
                    {
                        return(new BadRequestObjectResult(new
                        {
                            err_code = -104,
                            err_msg = $"请求方的Post Form 中的子目录[sub_dir_path]={strSubPath}不存在,如需创建,需指定is_create_sub_dir"
                        }));
                    }
                }
            }// end 子目录不为空时的处理

            #endregion

            #region 文件处理

            Console.WriteLine(strSubPath);

            string strRawfilename = form.Files[0].FileName;

            if (strRawfilename.Length > 127)
            {
                return(new BadRequestObjectResult(new
                {
                    err_code = -200,
                    err_msg = $"请求方的Post Form 的原始文件名不能超过128个字符"
                }));
            }

            // 获取扩展名
            string strFileExtension = Path.GetExtension(strRawfilename);
            string strFileGuid      = Guid.NewGuid().ToString();
            string strFileName      = strFileGuid + strFileExtension;

            // 最终带有Guid文件名
            string strTargetFileName = Path.Combine(strFullDirectoryPath, strFileName);

            using (var stream = new FileStream(strTargetFileName, FileMode.CreateNew))
            {
                await form.Files[0].CopyToAsync(stream);
            }

            sw.Stop();
            TimeSpan ts2 = sw.Elapsed;

            OperationResultModel operationResultModel = new OperationResultModel
            {
                WriteFileTimeSpanMs = ts2.TotalMilliseconds,
                AppDirectory        = id,
                SubPathFileName     = Path.Combine(strSubPath, strFileName),
                Msg = "写入新文件成功"
            };

            operationResultModel.FileInternalAccessUrl = $"{domainUrl}{operationResultModel.SubPathFileName}";
            _logger.LogDebug(operationResultModel.ToString());
            return(Ok(operationResultModel));


            #endregion
        }// end Controller
Example #10
0
 public ShopConnectorOperationResult(string message, bool hasError)
 {
     _context = null;
     _model   = new OperationResultModel(message, hasError);
 }