Ejemplo n.º 1
0
        public ActionResult LogIn(Default model)
        {
            if (string.IsNullOrEmpty(model.UserAccount).Equals(true) || string.IsNullOrEmpty(model.UserPassWord).Equals(true))
                return View(model);

            ReturnResult ReturnResult = new ReturnResult();
            ReturnResult = CheckUserAccount(model.UserAccount.Trim().ToUpper(), model.UserPassWord.Trim().ToUpper());
            if (ReturnResult.ReturnMsgNo == "1")
            {
                Session["UserAccount"] = model.UserAccount.Trim();
                return RedirectToAction("Index");
            }
            ViewBag.Error = ReturnResult.ReturnMsgNo + "|" + ReturnResult.ReturnMsg;
            return RedirectToAction("Error",new {ErrMsg = ReturnResult.ReturnMsgNo + "|" + ReturnResult.ReturnMsg}); 
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 获取一条数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ReturnResult <ApiToken> GetOne(ApiToken model)
        {
            var rst = new ReturnResult <ApiToken>();

            try
            {
                StringBuilder strSql = new StringBuilder();
                strSql.Append(@"select Id,AppId,AccessToken,RefreshToken,AccessTokenExpiresIn,AccessTokenCreateTime,RefreshTokenExpiresTime from api_token ");
                strSql.Append("where 1=1 ");

                if (model != null)
                {
                    if (model.Id != 0)
                    {
                        strSql.Append("and Id = @Id ");
                    }
                    if (model.AppId > 0)
                    {
                        strSql.Append("and AppId = @AppId ");
                    }
                }

                var query = conn.Query <ApiToken>(strSql.ToString(), model).FirstOrDefault();
                if (query == null)
                {
                    rst.Message = "数据不存在";
                }
                else
                {
                    rst.Result  = true;
                    rst.Data    = query;
                    rst.Message = "查询成功";
                }
            }
            catch (Exception ex)
            {
                rst.Message = "查询失败:" + ex.Message;
                Log4netUtil.Error("ApiTokenDal/GetOne", ex);
            }

            return(rst);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 新增标签到微信并在此标签下新增用户
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="tagName"></param>
        /// <returns></returns>
        public ActionResult AddTagAndUse(string AppId, string tagName, string OpenId)
        {
            WX_App     app  = new WX_AppManager().GetByPK(AppId);
            TagService ser  = new TagService(app.AppId, app.AppSecret);
            string     json = ser.Create(tagName);
            JObject    jo   = (JObject)JsonConvert.DeserializeObject(json);
            WX_UserTag tag  = new WX_UserTag()
            {
                AppId   = AppId,
                TagId   = (int)jo["tag"]["id"],
                TagName = jo["tag"]["name"].ToString(),
            };
            ReturnResult result = new ReturnResult()
            {
                Result = true
            };

            if (!new WX_UserTagManager().Add(tag))
            {
                result.Result   = false;
                result.ErrorMsg = "新增失败!";
            }
            else
            {
                List <string> openIdList = JsonConvert.DeserializeObject <List <string> >(OpenId);
                JObject       job        = JObject.Parse(new UserService(app.AppId, app.AppSecret).AddTag(openIdList, tag.TagId));
                var           Adresult   = new
                {
                    errcode = job["errcode"].ToString(),
                    errmsg  = job["errmsg"].ToString()
                };
                if (Adresult.errcode.Equals("0"))
                {
                    WX_UserManager manager = new WX_UserManager();
                    foreach (var id in openIdList)
                    {
                        manager.AddTag(manager.GetByPK(id), tag.TagId);
                    }
                }
            }
            return(Json(result, JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 4
0
        public InterfacePrototype GetSharedClass <InterfacePrototype>(string name, params object[] RemoteArgs)
        {
            lock (InitializedClasses)
            {
                SyncObject syncObject = null;
                lock (Requests)
                {
                    int RequestId = 0;

                    RequestId = GetNextRandomInteger();
                    while (Requests.ContainsKey(RequestId))
                    {
                        RequestId = GetNextRandomInteger();
                    }

                    syncObject = new SyncObject(this);
                    Requests.Add(RequestId, syncObject);
                    Send(new MsgGetSharedClass(name, RemoteArgs, RequestId));
                }

                ReturnResult result = syncObject.Wait <ReturnResult>(null, 30000); //wait for response
                if (result == null)
                {
                    throw new Exception("A timeout occured");
                }
                if (result.ExceptionOccured)
                {
                    throw new Exception(result.exceptionMessage);
                }
                if (result.ReturnValue == null)
                {
                    throw new Exception("The shared class \"" + name + "\" could not be found in the remote client");
                }

                SharedClass c = (SharedClass)result.ReturnValue;
                c.Client = this;
                InterfacePrototype tmp = DynClassCreator.CreateDynamicClass <InterfacePrototype>(c);

                InitializedClasses.Add(c.SharedId, c);
                return(tmp);
            }
        }
        public HttpResponseMessage GetCityUserFromID([FromUri] int CityUserID)
        {
            //System.Diagnostics.EventLog.WriteEntry("Application", "LoginCust started");
            AccountManagementService         accService  = new AccountManagementService();
            HttpStatusCode                   ReturnCode  = HttpStatusCode.OK;
            TranInfo <CityUserAccount_M>     transaction = new TranInfo <CityUserAccount_M>();
            ReturnResult <CityUserAccount_M> result      = new ReturnResult <CityUserAccount_M>();

            try
            {
                result = accService.GetCityUserFromID(CityUserID);
                if (result.status.Status == StatusEnum.Success)
                {
                    transaction.data   = result.result;
                    transaction.status = true;
                }
                else
                {
                    // transaction.warnings.Add(result.status.StatusMessage);

                    transaction.status = false;
                    transaction.AddException(result.status.StatusMessage);

                    //_commonService.LogError(result.status.StatusCode, result.status.StatusMessage, result.status.StatusDetails, 0, "LoginCust");
                }
            }
            catch (Exception ex)
            {
                transaction.status = false;
                transaction.AddException(ex.Message);
                ReturnCode    = HttpStatusCode.InternalServerError;
                result.status = _eHandler.HandleException(ex);
                _commonService.LogError(result.status);
                // transaction.AddException(ex.Message);
                //ReturnCode = HttpStatusCode.InternalServerError;

                //if (ex.InnerException != null) { InnerExceptionMessage = ex.InnerException.Message; }
                //LogHelper.Instance.Error(CorrelationID, Username, Request.GetRequestContext().VirtualPathRoot, ex.Message, InnerExceptionMessage, 0, ex);
            }

            return(Request.CreateResponse <TranInfo <CityUserAccount_M> >(ReturnCode, transaction));
        }
Ejemplo n.º 6
0
        public ReturnResult <Log> InsertLog(Log Log)
        {
            DbProvider provider     = new DbProvider();
            var        result       = new ReturnResult <Log>();
            string     outCode      = String.Empty;
            string     outMessage   = String.Empty;
            string     totalRecords = String.Empty;

            try
            {
                provider.SetQuery("LOG_CREATE", CommandType.StoredProcedure)
                .SetParameter("VanBanId", SqlDbType.Int, Log.VanBanId, ParameterDirection.Input)
                .SetParameter("Action", SqlDbType.NVarChar, Log.Action, 64, ParameterDirection.Input)
                .SetParameter("CreatedDate", SqlDbType.DateTime, Log.CreatedDate, ParameterDirection.Input)
                .SetParameter("CreatedBy", SqlDbType.Int, Log.CreatedBy, ParameterDirection.Input)
                .SetParameter("IsDeleted", SqlDbType.Bit, Log.IsDeleted, ParameterDirection.Input)
                .SetParameter("ErrorCode", SqlDbType.NVarChar, DBNull.Value, 100, ParameterDirection.Output)
                .SetParameter("ErrorMessage", SqlDbType.NVarChar, DBNull.Value, 4000, ParameterDirection.Output)
                .GetSingle <Log>(out Log).Complete();

                provider.GetOutValue("ErrorCode", out outCode)
                .GetOutValue("ErrorMessage", out outMessage);

                if (outCode != "0" || outCode == "")
                {
                    result.ErrorCode    = outCode;
                    result.ErrorMessage = outMessage;
                }
                else
                {
                    result.Item         = Log;
                    result.ErrorCode    = outCode;
                    result.ErrorMessage = outMessage;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(result);
        }
Ejemplo n.º 7
0
        public ReturnResult <Font> UpdateFont(Font font)
        {
            ReturnResult <Font> result;
            DbProvider          db;

            try
            {
                result = new ReturnResult <Font>();
                db     = new DbProvider();
                db.SetQuery("FONT_EDIT", CommandType.StoredProcedure)
                .SetParameter("PhongID", SqlDbType.Int, font.FontID, ParameterDirection.Input)
                .SetParameter("PhongSo", SqlDbType.NChar, font.FontNumber, 50, ParameterDirection.Input)
                .SetParameter("CoQuanID", SqlDbType.Int, font.OrganID, ParameterDirection.Input)
                .SetParameter("NgonNguID", SqlDbType.Int, font.LanguageId, ParameterDirection.Input)
                .SetParameter("TenPhong", SqlDbType.NVarChar, font.FontName, 50, ParameterDirection.Input)
                .SetParameter("CongCu", SqlDbType.NVarChar, font.LookupTools, 50, ParameterDirection.Input)
                .SetParameter("LichSu", SqlDbType.NVarChar, font.History, 500, ParameterDirection.Input)
                .SetParameter("NgonNgu", SqlDbType.NVarChar, font.Lang, 50, ParameterDirection.Input)
                .SetParameter("NgayCapNhat", SqlDbType.NVarChar, font.UpdateTime.ToString(), 50, ParameterDirection.Input)
                .SetParameter("GhiChu", SqlDbType.NVarChar, font.Note, 300, ParameterDirection.Input)
                .SetParameter("ErrorCode", SqlDbType.NVarChar, DBNull.Value, 100, ParameterDirection.Output)
                .SetParameter("ErrorMessage", SqlDbType.NVarChar, DBNull.Value, 4000, ParameterDirection.Output)
                .ExcuteNonQuery()
                .Complete();
                db.GetOutValue("ErrorCode", out string errorCode)
                .GetOutValue("ErrorMessage", out string errorMessage);
                if (errorCode.ToString() == "0")
                {
                    result.ErrorCode    = "0";
                    result.ErrorMessage = "";
                }
                else
                {
                    result.Failed(errorCode, errorMessage);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(result);
        }
Ejemplo n.º 8
0
        //检查是否是vip用户
        public object Get(string cookie)
        {
            if (string.IsNullOrWhiteSpace(cookie))
            {
                return(ReturnResult.Return("1", "cookie错误", null, null));
            }
            else
            {
                ObjSessionModel obj = handle.AnalyzeCookie.Analyze(cookie);

                if (obj == null)
                {
                    return(ReturnResult.Return("1", "cookie错误", null, null));
                }
                else
                {
                    return(handle.CheckAuthorization.Check(obj.userId));
                }
            }
        }
Ejemplo n.º 9
0
        public ReturnResult CancelMeeting(string meetingId)
        {
            ReturnResult returnResult = new ReturnResult();

            try
            {
                Meeting meeting = _context.Meetings.Find(new Guid(meetingId));
                meeting.IsCanceled = true;
                _context.SaveChanges();
            }
            catch (Exception e)
            {
                returnResult.Result  = false;
                returnResult.Message = e.Message;
                _logger.Error("Faild to cancel a Meeting", e);
                return(returnResult);
            }
            returnResult.Result = true;
            return(returnResult);
        }
Ejemplo n.º 10
0
        public ReturnResult <Account> EditPassword(Account account)
        {
            var            result         = new ReturnResult <Account>();
            AccountService accountService = new AccountService();

            if (accountService.IsAuthenticate(account))
            {
                var hasedPassword = accountService.CreateHashedPassword(account.Password);

                // Assign a new hashed password to account
                account.Password = hasedPassword;
                result           = AccountDAL.EditPassword(account);
            }
            else
            {
                result.ErrorCode    = "1";
                result.ErrorMessage = "Nhập sai mật khẩu hiện tại";
            }
            return(AccountDAL.EditPassword(account));
        }
Ejemplo n.º 11
0
        public ActionResult OnPublicKey(string data)
        {
            ReturnResult result = new ReturnResult();

            try
            {
                string path  = Server.MapPath("~/Upload");
                byte[] token = Assembly.LoadFile(data)
                               .GetName()
                               .GetPublicKeyToken();
                string content = BitConverter.ToString(token).Replace("-", "").ToLower();
                result.data = content;
            }
            catch (Exception ex)
            {
                result.code = -1;
                result.msg  = ex.Message;
            }
            return(Json(result));
        }
Ejemplo n.º 12
0
 public async Task <ReturnResult <bool> > SaveUserInfo(UsersModel userInfo)
 {
     return(await Aspect.Task(async() =>
     {
         ReturnResult <bool> result = new ReturnResult <bool>();
         result.data = await this.Update(userInfo);
         if (result.data)
         {
             result.code = 1;
         }
         else
         {
             result.code = -103;
             result.message = "用户信息更新失败!";
         }
         return result;
     })
            .WithLog("更新用户信息.")
            .Execute());
 }
Ejemplo n.º 13
0
        public IActionResult Add(Client model)
        {
            var rst = new ReturnResult <bool>();

            var bll = new ClientBll();

            if (model.id == 0)
            {
                model.secret      = Guid.NewGuid().ToString("N");
                model.is_online   = false;
                model.create_time = DateTime.Now;
                rst = bll.Add(model);
            }
            else
            {
                rst = bll.Update(model);
            }

            return(Json(rst));
        }
Ejemplo n.º 14
0
        public async Task <ReturnResult> AddArticleStock(List <ArticleStock> articleStocks)
        {
            ReturnResult result = new ReturnResult();

            try
            {
                await _context.ArticleStocks.AddRangeAsync(articleStocks);

                await _context.SaveChangesAsync();

                result.StatusMessage = "New articles add successfully to the inventory";
                return(result);
            }
            catch (Exception)
            {
                //statusMessage = e.Message;
                //addedCustomer = null;
                throw;
            }
        }
Ejemplo n.º 15
0
        public ActionResult ErrorGuide(int ErrCode = -1)
        {
            ReturnResult result = new ReturnResult();

            switch (ErrCode)
            {
                case 4901:
                case 4902:
                case 4903:
                    result.Error("인증토큰이 유효하지 않습니다.");
                    break;
                default:
                    result.Error("알수없는 오류가 발생했습니다.");
                    break;
            }

            ViewBag.result = result;

            return View(this);
        }
Ejemplo n.º 16
0
        public IActionResult GetAllCoQuan()
        {
            ReturnResult <CoQuan> result;

            try
            {
                result = new ReturnResult <CoQuan>();
                result = coQuanBUS.GetAllCoQuan();
                return(Ok(new OrganList()
                {
                    OrganTypes = result.ItemList.Select(item => item.OrganType).Distinct().ToList(),
                    OrganName = result.ItemList.Select(item => item.TenCoQuan).Distinct().ToList(),
                    OrganAddress = result.ItemList.Select(item => item.AddressDetail).Distinct().ToList()
                }));
            }
            catch (Exception ex)
            {
                return(Unauthorized());
            }
        }
Ejemplo n.º 17
0
 public async Task <ReturnResult <AdvertisementsModel> > GetAdvertisement(string key)
 {
     return(await Aspect.Task(async() =>
     {
         ReturnResult <AdvertisementsModel> result = new ReturnResult <AdvertisementsModel>();
         Expression <Func <Advertisements, bool> > exp = x => x.key == key;
         var adTemp = await this.FindOneAsync <AdvertisementsModel, Advertisements>(repository, exp);
         if (adTemp == null || string.IsNullOrEmpty(adTemp.ID))
         {
             result.code = -104;
             result.message = "未查询到广告数据。";
             return result;
         }
         result.code = 1;
         result.data = adTemp;
         return result;
     })
            .WithLog("获取广告信息.")
            .Execute());
 }
Ejemplo n.º 18
0
        public async Task <ReturnResult> AddKey([FromBody] CreateKey request)
        {
            if (int.Parse(request.SectionID) <= 0)
            {
                throw new AppException("栏目不能为空");
            }
            if (string.IsNullOrWhiteSpace(request.Name))
            {
                throw new AppException("名称不能为空");
            }

            int        iUID       = LoginManager.GetUserID();
            var        mapper     = new MapperConfiguration(x => x.CreateMap <CreateKey, KeyContent>()).CreateMapper();
            KeyContent keyContent = mapper.Map <KeyContent>(request);

            keyContent.CreateUserID = iUID;
            keyContent = await KeyManager.EncryptKey(keyContent);

            return(ReturnResult.ResultCalculation(() => KeyContentManager.Insert(keyContent)));
        }
Ejemplo n.º 19
0
        public static ReturnResult <List <ModelField> > InsertBulk(IDatabase db, List <ModelField> modelFields)
        {
            var results = new ReturnResult <List <ModelField> >();

            try
            {
                db.InsertBulk(modelFields);

                results.Success = true;
                results.Item    = modelFields;
            }
            catch (Exception e)
            {
                results.Success      = false;
                results.ErrorMessage = "There was an error saving the model.";
                results.Exception    = e;
            }

            return(results);
        }
        public ReturnResult <bool> ResendPin(CustomerInfo message)
        {
            ReturnResult <string> result      = new ReturnResult <string>();
            ReturnResult <bool>   resultFinal = new ReturnResult <bool>();

            result = accDBHandler.ResendPin(message);
            if (result != null)
            {
                EmailM emailMessage = new EmailM();
                emailMessage.Subject     = "RAP Security PIN";
                emailMessage.MessageBody = NotificationMessage.ResourceManager.GetString("ResendPinMsg").Replace("PIN", result.result);
                if (message.email != null)
                {
                    emailMessage.RecipientAddress.Add(message.email);
                }
                EmailService emailservice = new EmailService();
                resultFinal = emailservice.SendEmail(emailMessage);
            }
            return(resultFinal);
        }
Ejemplo n.º 21
0
        ReturnResult InsertLanguage(XmlNode lanNode)
        {
            List <string> lstParams = new List <string>();

            lstParams.Add(App.GCurrentDBServer.DbType.ToString());
            lstParams.Add(App.GCurrentDBServer.Host);
            lstParams.Add(App.GCurrentDBServer.Port);
            lstParams.Add(App.GCurrentDBServer.ServiceName);
            lstParams.Add(App.GCurrentDBServer.LoginName);
            lstParams.Add(App.GCurrentDBServer.Password);
            //lstParams.Add(strImportLanguageType);
            //从i=1开始 因为第一个childnode值是rownum 不需要导入数据库
            for (int i = 1; i < lanNode.ChildNodes.Count; i++)
            {
                if (lanNode.ChildNodes[i].Name.ToUpper() == "DISPLAYMESSAGE" || lanNode.ChildNodes[i].Name.ToUpper() == "TIPMESSAGE")
                {
                    if (lanNode.ChildNodes[i].InnerText.Length > 2048)
                    {
                        continue;
                    }
                    if (lanNode.ChildNodes[i].InnerText.Length > 1024)
                    {
                        lstParams.Add(lanNode.ChildNodes[i].InnerText.Substring(0, 1024));
                        lstParams.Add(lanNode.ChildNodes[i].InnerText.Substring(1025));
                    }
                    else
                    {
                        lstParams.Add(lanNode.ChildNodes[i].InnerText);
                        lstParams.Add("");
                    }
                }
                else
                {
                    lstParams.Add(lanNode.ChildNodes[i].InnerText);
                }
            }
            lstParams.Add("");  //InObject字段值 目前为空
            ReturnResult Result = AboutLanguagesInServer.WCFOperationMthodA("HTTP", App.GCurrentUmpServer.Host, App.GCurrentUmpServer.Port, 5, lstParams);

            return(Result);
        }
Ejemplo n.º 22
0
        void InstanceBackgroundWorkerImportOnlyRefresh_DoWork(object sender, DoWorkEventArgs e)
        {
            //删除一种类型的语言
            List <string> lstParams = new List <string>();

            lstParams.Add(App.GCurrentDBServer.DbType.ToString());
            lstParams.Add(App.GCurrentDBServer.Host);
            lstParams.Add(App.GCurrentDBServer.Port);
            lstParams.Add(App.GCurrentDBServer.ServiceName);
            lstParams.Add(App.GCurrentDBServer.LoginName);
            lstParams.Add(App.GCurrentDBServer.Password);
            lstParams.Add(strImportLanguageType);
            RRemoveLanResult = AboutLanguagesInServer.WCFOperationMthodA("HTTP", App.GCurrentUmpServer.Host, App.GCurrentUmpServer.Port, 4, lstParams);
            if (RRemoveLanResult.BoolReturn)
            {
                //开始写入数据库
                ReturnResult InsertResult = null;
                foreach (XmlNode node in IXMLNodeTableDataRowsList.ChildNodes)
                {
                    if (node.ChildNodes.Count > 0)
                    {
                        InsertResult = InsertLanguage(node);
                        if (!InsertResult.BoolReturn)
                        {
                            bIsImportSuccess = false;
                            string        strError  = DateTime.Now + " | " + string.Format(this.TryFindResource("Error006").ToString(), node["C002"]);
                            List <string> lstErrors = new List <string>();
                            lstErrors.Add(strError);
                            strError = DateTime.Now + " | " + string.Format(this.TryFindResource("Error006").ToString(), InsertResult.StringReturn);
                            Logger.WriteLog(lstErrors);
                        }
                    }
                }
            }
            else
            {
                InstanceBackgroundWorkerImportOnlyRefresh.Dispose(); InstanceBackgroundWorkerImportOnlyRefresh = null;
                MessageBox.Show(RRemoveLanResult.StringReturn,
                                this.TryFindResource("ErrorMsgTitle").ToString(), MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// 获取一条数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ReturnResult <Admin> GetOne(Admin model)
        {
            var rst = new ReturnResult <Admin>();

            try
            {
                StringBuilder strSql = new StringBuilder();
                strSql.Append(@"select t1.*,t2.Token from admin t1 ");
                strSql.Append(@"inner join admin_token t2 on t1.Id = t2.AdminId ");
                strSql.Append("where 1=1 ");
                if (model != null)
                {
                    if (model.Id != 0)
                    {
                        strSql.Append("and t1.Id = @Id ");
                    }
                    if (!string.IsNullOrEmpty(model.Token))
                    {
                        strSql.Append("and t2.Token = @Token ");
                    }
                }
                var query = conn.Query <Admin>(strSql.ToString(), model).FirstOrDefault();
                if (query == null)
                {
                    rst.Message = "数据不存在";
                }
                else
                {
                    rst.Result  = true;
                    rst.Data    = query;
                    rst.Message = "查询成功";
                }
            }
            catch (Exception ex)
            {
                rst.Message = "查询失败:" + ex.Message;
                Log4netUtil.Error("AdminDal/GetOne", ex);
            }

            return(rst);
        }
Ejemplo n.º 24
0
        /// <summary>
        ///  执行ExecuteNonQuery
        /// </summary>
        /// <param name="transaction">transaction</param>
        /// <param name="commandType">Command type</param>
        /// <param name="commandText">Command text</param>
        /// <param name="oraParamsCollection">键值对的参数列表</param>
        /// <returns>ID</returns>
        public ReturnResult ExecuteNonQuery(OracleTransaction transaction, CommandType commandType, string commandText, List <OracleParameter> oraParamsCollection)
        {
            ReturnResult    result = new ReturnResult();
            OracleParameter orcleOutputParameter = null;
            OracleCommand   cmd = new OracleCommand();

            try
            {
                PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText);
                if (oraParamsCollection != null)
                {
                    foreach (OracleParameter current in oraParamsCollection)
                    {
                        cmd.Parameters.Add(current);
                        if (current.Direction.Equals(ParameterDirection.Output))
                        {
                            orcleOutputParameter = current;
                        }
                    }
                }
                cmd.ExecuteNonQuery();
                if (orcleOutputParameter == null)
                {
                    result.Message  = "OK";
                    result.Anything = "OK";
                }
                else
                {
                    result.Message  = "OK";
                    result.Anything = orcleOutputParameter.Value.ToString();
                }
                result.Status = true;
            }
            catch (Exception ex)
            {
                result.Message = "Execute:ExecuteNonQuery," + ex.Message;
                result.Status  = false;
                logHandler.Error(MethodBase.GetCurrentMethod().Name + "Call ExecuteNonQuery Fail:" + ex.Message);
            }
            return(result);
        }
Ejemplo n.º 25
0
        // viết lại api cho profile từ đây
        public ReturnResult <Profiles> ProfilesGetSearchWithPaging(BaseCondition <Profiles> condition)
        {
            ReturnResult <Profiles> result = new ReturnResult <Profiles>();
            DbProvider      db;
            List <Profiles> lstResult;

            try
            {
                db        = new DbProvider();
                lstResult = new List <Profiles>();
                db.SetQuery("PROFILES_GET_SEARCH_WITH_PAGING", CommandType.StoredProcedure);
                db.SetParameter("PageIndex", SqlDbType.Int, condition.PageIndex);
                db.SetParameter("PageSize", SqlDbType.Int, condition.PageSize);
                db.SetParameter("InWhere", SqlDbType.NVarChar, condition.IN_WHERE, 500);
                db.SetParameter("InSort", SqlDbType.NVarChar, condition.IN_SORT, 200);
                db.SetParameter("TotalRecords", SqlDbType.Int, DBNull.Value, ParameterDirection.Output);
                db.SetParameter("ErrorCode", SqlDbType.Int, DBNull.Value, ParameterDirection.Output);
                db.SetParameter("ErrorMessage", SqlDbType.NVarChar, DBNull.Value, 2000, ParameterDirection.Output);
                db.GetList <Profiles>(out lstResult);
                db.Complete();
                db.GetOutValue("ErrorCode", out int errorCode)
                .GetOutValue("ErrorMessage", out string errorMessage)
                .GetOutValue("TotalRecords", out int totalRecords);
                if (errorCode.ToString() != "0")
                {
                    result.Failed(errorCode.ToString(), errorMessage);
                }
                else
                {
                    result.ItemList     = lstResult;
                    result.TotalRows    = totalRecords;
                    result.ErrorCode    = "0";
                    result.ErrorMessage = "";
                }
            }
            catch (Exception ex)
            {
                result.Failed("-1", ex.Message);
            }
            return(result);
        }
Ejemplo n.º 26
0
        public ReturnResult <Skills> AddNewSkills(Skills Skills)
        {
            var        result       = new ReturnResult <Skills>();
            DbProvider db           = new DbProvider();
            string     outCode      = String.Empty;
            string     outMessage   = String.Empty;
            string     totalRecords = String.Empty;

            try
            {
                // Set tên stored procedure
                db.SetQuery("Skills_AddNew", CommandType.StoredProcedure)
                .SetParameter("SkillName", SqlDbType.NVarChar, Skills.SkillName)
                .SetParameter("Description", SqlDbType.NVarChar, Skills.Description)
                .SetParameter("CreatedUser", SqlDbType.NVarChar, Skills.CreatedUser)
                .SetParameter("Status", SqlDbType.TinyInt, Skills.Status)
                .SetParameter("ErrorCode", SqlDbType.NVarChar, DBNull.Value, 100, ParameterDirection.Output)
                .SetParameter("ErrorMessage", SqlDbType.NVarChar, DBNull.Value, 4000, ParameterDirection.Output)
                .ExcuteNonQuery()
                .Complete();


                db.GetOutValue("ErrorCode", out outCode)
                .GetOutValue("ErrorMessage", out outMessage);
                if (outCode != "0" || outCode == "")
                {
                    result.Failed(outCode, outMessage);
                }
                else
                {
                    result.Item         = Skills;
                    result.ErrorCode    = "0";
                    result.ErrorMessage = "";
                }
            }
            catch (Exception ex)
            {
                result.Failed("-1", ex.Message);
            }
            return(result);
        }
Ejemplo n.º 27
0
        public ReturnResult <User> Login(User model, Trans t = null)
        {
            var rst = new ReturnResult <User>()
            {
                Message = "用户名或密码错误"
            };

            try
            {
                conn           = CreateMySqlConnection(t);
                model.password = EncryptHelper.MD5Encrypt(model.password);
                var sql = new StringBuilder("select * from user where password=@password ");
                if (!string.IsNullOrEmpty(model.user_id))
                {
                    sql.Append("and user_id=@user_id");
                }
                else if (!string.IsNullOrEmpty(model.user_name))
                {
                    sql.Append("and user_name=@user_name");
                }
                else
                {
                    rst.Status  = 10005;
                    rst.Message = "信息已失效请刷新界面重新登录!";
                    return(rst);
                }
                rst.Data = conn.QueryFirstOrDefault <User>(sql.ToString(), model, t?.DbTrans);
                if (rst.Data != null)
                {
                    rst.Result  = true;
                    rst.Message = "登录成功";
                }
            }
            catch (Exception ex)
            {
                rst.Message = $"服务异常:{ex.InnerException ?? ex}";
                Log4netUtil.Error($"{ex.InnerException ?? ex}");
            }

            return(rst);
        }
        /// <summary>
        /// Lot重新生成时记录到ISSUE表
        /// </summary>
        /// <param name="lotEntityList"></param>
        /// <returns></returns>
        public ReturnResult InsertBatch_R_ISSUE_DESC_T(List<LotMoEntity> lotEntityList)
        {
            ReturnResult result = new ReturnResult();

            List<KeyValuePair<string, List<OracleParameter>>> strSqlList = new List<KeyValuePair<string, List<OracleParameter>>>();
            string strInsert = string.Format(@"INSERT INTO  SFISM4.R_ISSUE_DESC_T 
                (CUSTOMER,
                ISSUE_TYPE,
                PN,
                OCCUR_DESC)
                VALUES
                (:CUSTOMER,
                :ISSUE_TYPE,
                :PN,
                :OCCUR_DESC)");

            foreach (var entity in lotEntityList)
            {
                DBParameter dbParameter = new DBParameter();
                dbParameter.Clear();
                dbParameter.Add(":CUSTOMER", OracleDbType.Varchar2, "PPM_LOT");
                dbParameter.Add(":ISSUE_TYPE", OracleDbType.Varchar2, "LOTREBUILDER");
                dbParameter.Add(":PN", OracleDbType.Varchar2, entity.MO_ORDER);
                dbParameter.Add(":OCCUR_DESC", OracleDbType.Varchar2, entity.LOT_NO);

                strSqlList.Add(new KeyValuePair<string, List<OracleParameter>>(strInsert, dbParameter.GetParameters()));
            }
            try
            {
                result = dbHander.ExecuteNonQueryBatchSql(strSqlList);
                result.Status = true;
            }
            catch (Exception ex)
            {
                result.Status = false;
                result.Message = ex.Message;
                this.logHandler.Error(MethodBase.GetCurrentMethod().Name, "Call InsertBatch_R_ISSUE_DESC_T Fail: " + ex.Message);
            }

            return result;
        }
Ejemplo n.º 29
0
        /// <summary>
        /// 添加客户请求处理接口
        /// </summary>
        /// <returns></returns>
        public async Task <ReturnResult> AddCustomerAsync(CustomerParamater parameter)
        {
            ReturnResult result   = new ReturnResult();
            var          customer = Mapper.Map <Customer>(parameter);
            //根据openId验证客户是否存在
            var oldCustomer = await GetCustomerEntityByOpenIdAsync(customer.Openid);

            if (oldCustomer != null)
            {
                customer.Id = oldCustomer.Id;
                context.Customers.Update(oldCustomer);
            }
            else
            {
                await context.Customers.AddAsync(customer);
            }
            await context.SaveChangesAsync();

            result.Id = customer.Id;
            return(result);
        }
Ejemplo n.º 30
0
        public async Task <IActionResult> Register(string Username, string Password, string Email)
        {
            ReturnResult <object> model = new ReturnResult <object>();

            if (string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password) || string.IsNullOrEmpty(Email))
            {
                model.Status    = "ok";
                model.ReturnMsg = "输入的信息不能为空";
            }
            User user = new User();

            user.Email    = Email;
            user.Password = Password;
            user.UserName = Username;

            await userService.Save(user);

            model.Status  = "ok";
            model.Message = "注册成功";
            return(Json(model));
        }
Ejemplo n.º 31
0
        public async Task <ReturnResult> DeleteCar(Guid id)
        {
            ReturnResult ReturnResult = new ReturnResult();

            ReturnResult.Action = "Delete car";

            Car Car = await CarRepository.ReadAsync(id);

            if (Car == null)
            {
                ReturnResult.Inconsistencies.Add(
                    "Carro não encontrado");
            }
            else
            {
                await CarRepository.DeleteAsync(id);

                await CarRepository.SaveChangesAsync();
            }
            return(ReturnResult);
        }
Ejemplo n.º 32
0
        /// <summary>
        /// 检查Excel文件的字段是否包含了必须的字段
        /// </summary>
        /// <param name="guid">附件的GUID</param>
        /// <returns></returns>
        public ActionResult CheckExcelColumns(string guid)
        {
            ReturnResult result = new ReturnResult();

            try
            {
                DataTable dt = ConvertExcelFileToTable(guid);
                if (dt != null)
                {
                    //检查列表是否包含必须的字段
                    result.ErrorCode = DataTableHelper.ContainAllColumns(dt, columnString)?0:1;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(LogLevel.LOG_LEVEL_CRIT, ex, typeof(LoginLogController));
                result.ErrorMessage = ex.Message;
            }

            return(ToJsonContent(result));
        }
Ejemplo n.º 33
0
        public JsonResult RemoveChannel(int ChannelID)
        {
            ReturnResult result = new ReturnResult();

            this.LoginCheck();

            using (var context = new SharedPlayerContext())
            {
                Channel channel = context.Channels.Where(x => x.ChannelID == ChannelID).FirstOrDefault();
                if (channel != null && channel.ChannelID > 0)
                {
                    if (channel.CreateMemberID == this.LoginMember.MemberID)
                    {
                        List<Music> music = context.Musics.Where(x => x.ChannelID == ChannelID).ToList();
                        if (music != null && music.Count > 0)
                        {
                            foreach (Music item in music)
                            {
                                context.Musics.Remove(item);
                            }
                        }
                        context.Channels.Remove(channel);
                        context.SaveChanges();
                        result.Success();
                    }
                    else
                    {
                        result.Error("채널을 삭제할 권한이 없습니다.");
                    }
                }
                else
                {
                    result.Error("채널이 존재하지 않습니다.");
                }
            }
            
            return Json(result);
        }
Ejemplo n.º 34
0
        //查詢VIEW欄位
        public JsonResult ChangeTableDataJson(string select, string view, string where, string orderby, string iseasyquery, string strquery)
        {
            ReturnResult ReturnResult = new ReturnResult();
            ReturnDBResult ReturnDBResult = new ReturnDBResult();
            ReturnDBResult = ViewQueryLog(select, view, where, orderby, iseasyquery, strquery);

            ReturnResult.ReturnMsgNo = Convert.ToString(ReturnDBResult.ReturnMsgNo);
            ReturnResult.ReturnMsg = ReturnDBResult.ReturnMsg;
            //描述
            ReturnDBResult ReturnDBResultNote = new ReturnDBResult();
            ReturnDBResultNote = ViewQueryNote(view); 

            //string ColumnName = "";
            StringBuilder JsonString = new StringBuilder();

            if (ReturnDBResult.ReturnDS.Tables.Count > 0)
            {
                if (ReturnDBResult.ReturnDS.Tables[0].Columns.Count > 0)
                { 
                    JsonString.Append("[");
                    for (int i = 0; i < ReturnDBResult.ReturnDS.Tables[0].Columns.Count; i++)
                    {
                        if (i == 0)
                            JsonString.Append("{");//JsonString.Append("{");
                        else
                            JsonString.Append(",{");//JsonString.Append(",{");
                        string Temp = "";
                        if (ReturnDBResultNote.ReturnDS.Tables.Count > 0 )
                        {
                            if (ReturnDBResultNote.ReturnDS.Tables[0].Rows.Count > 0 )
                            {
                                for (int j = 0; j < ReturnDBResultNote.ReturnDS.Tables[0].Rows.Count; j++)
                                {
                                    if (Convert.ToString(ReturnDBResultNote.ReturnDS.Tables[0].Rows[j]["objname"]) == Convert.ToString(ReturnDBResult.ReturnDS.Tables[0].Columns[i].ColumnName))
                                    {
                                        Temp = Convert.ToString(ReturnDBResultNote.ReturnDS.Tables[0].Rows[j]["value"]);
                                        break;
                                    }
                                }
                            }
                        }
                        JsonString.Append("\"ColumnName\":\"" + ReturnDBResult.ReturnDS.Tables[0].Columns[i].ColumnName + "\",\"ColumnNameNote\":\"" + Temp + "\""); //'ColumnName':
                        JsonString.Append("}");
                    }
                    JsonString.Append("]");
                }
            }
            ReturnResult.ReturnTB = JsonString.ToString();
            return Json(ReturnResult, JsonRequestBehavior.AllowGet);
        }
Ejemplo n.º 35
0
        public JsonResult RemoveMusic(long MusicID)
        {
            ReturnResult result = new ReturnResult();

            this.LoginCheck();

            using (var context = new SharedPlayerContext())
            {
                Music music = context.Musics.Where(x => x.MusicID == MusicID).FirstOrDefault();
                if (music != null && music.MusicID > 0)
                {
                    Channel channel = context.Channels.Where(x => x.ChannelID == music.ChannelID).FirstOrDefault();
                    if (channel != null)
                    {
                        if (channel.CreateMemberID == this.LoginMember.MemberID || music.MemberID == this.LoginMember.MemberID)
                        {
                            context.Musics.Remove(music);
                            context.SaveChanges();
                            result.Success();
                        }
                        else
                        {
                            result.Error("삭제할 권한이 없습니다.");
                        }
                    }
                    else
                    {
                        result.Error("소속 채널에 오류가 있습니다.");
                    }
                }
                else
                {
                    result.Error("대상을 찾을 수 없습니다.");
                }
            }

            return Json(result);

        }
Ejemplo n.º 36
0
        public JsonResult RecommendProc(int MusicID)
        {
            ReturnResult result = new ReturnResult();

            this.LoginCheck();

            using (var context = new SharedPlayerContext())
            {
                Music music = context.Musics.Where(x => x.MusicID == MusicID).FirstOrDefault();
                if (music != null && music.MusicID > 0)
                {
                    music.RecommendCount = music.RecommendCount + 1;
                    context.SaveChanges();
                    result.Success();
                }
                else
                {
                    result.Error("대상을 찾을 수 없습니다.");
                }
            }

            return Json(result);
        }
Ejemplo n.º 37
0
        public JsonResult RemoveFavorite(int ChannelID)
        {
            ReturnResult result = new ReturnResult();

            this.LoginCheck();

            using (var context = new SharedPlayerContext())
            {
                Channel channel = context.Channels.Where(x => x.ChannelID == ChannelID).FirstOrDefault();
                if (channel != null && channel.ChannelID > 0)
                {
                    Favorite favo = context.Favorites.Where(x => x.MemberID == this.LoginMember.MemberID).Where(x => x.ChannelID == ChannelID).FirstOrDefault();

                    if (favo != null && favo.FavoriteID > 0)
                    {
                        context.Favorites.Remove(favo);
                        context.SaveChanges();
                        result.Success();
                    }
                    else
                    {
                        result.Fail("대상을 찾을 수 없습니다.");
                    }
                }
                else
                {
                    result.Fail("대상을 찾을 수 없습니다.");
                }
            }

            return Json(result);
        }
Ejemplo n.º 38
0
        public ReturnResult CheckUserAccount(string UserAccount, string UserPassWord)
        {
            ReturnResult ReturnResult = new ReturnResult();

              if (MyCardQueryLog.Properties.Settings.Default.IsTest.ToUpper() == "FALSE") {
                  if (MyCardQueryLog.Properties.Settings.Default.In34.ToUpper() == "FALSE")
                {
                    MyCardQueryLogWS.Service1Client MyCardQueryLogWS = new MyCardQueryLogWS.Service1Client();
                    MyCardQueryLogWS.ReturnResult MyCardQueryLogWSRe = new MyCardQueryLogWS.ReturnResult();
                    InValue = "CheckUserAccount";
                    try
                    {
                        MyCardQueryLogWSRe = MyCardQueryLogWS.CheckUserAccount(UserAccount.Trim(), UserPassWord.Trim());
                        ReturnResult.ReturnMsgNo = Convert.ToString(MyCardQueryLogWSRe.ReturnMsgNo);
                        ReturnResult.ReturnMsg = MyCardQueryLogWSRe.ReturnMsg;
                    }
                    catch (Exception ex)
                    {
                        OutValue = "|回應|" + "Exception|" + ex.ToString();
                        ErrorLog(InValue + OutValue);
                        ReturnResult.ReturnMsgNo = "-99";
                        ReturnResult.ReturnMsg = "系統發生錯誤";
                    } 
                }
                else
                {
                    switch (UserAccount.Trim().ToUpper())
                    {
                        case "RDONCALLUSER":
                            if (UserPassWord.Trim() == "sw27889188!")
                            {
                                ReturnResult.ReturnMsgNo = "1";
                                ReturnResult.ReturnMsg = "成功";
                            }
                            else
                            {
                                ReturnResult.ReturnMsgNo = "-2";
                                ReturnResult.ReturnMsg = "輸入密碼錯誤";
                            }
                            break;
                        case "DBONCALLUSER":
                            if (UserPassWord.Trim() == "abc123~")
                            {
                                ReturnResult.ReturnMsgNo = "1";
                                ReturnResult.ReturnMsg = "成功";
                            }
                            else
                            {
                                ReturnResult.ReturnMsgNo = "-2";
                                ReturnResult.ReturnMsg = "輸入密碼錯誤";
                            }
                            break;
                        case "MISONCALLUSER":
                            if (UserPassWord.Trim() == "abc123~")
                            {
                                ReturnResult.ReturnMsgNo = "1";
                                ReturnResult.ReturnMsg = "成功";
                            }
                            else
                            {
                                ReturnResult.ReturnMsgNo = "-2";
                                ReturnResult.ReturnMsg = "輸入密碼錯誤";
                            }
                            break;
                        default:
                            ReturnResult.ReturnMsgNo = "-1";
                            ReturnResult.ReturnMsg = "無帳號";
                            break;
                    } 
                  
                } 
            } 
            else
            {
                switch (UserAccount.Trim().ToUpper())
                {
                    case "RDONCALLUSER":
                        if (UserPassWord.Trim().ToUpper() == "SW27889188!")
                        {
                            ReturnResult.ReturnMsgNo = "1";
                            ReturnResult.ReturnMsg = "成功";
                        }
                        else
                        {
                            ReturnResult.ReturnMsgNo = "-2";
                            ReturnResult.ReturnMsg = "輸入密碼錯誤";
                        }
                        break;
                    case "DBONCALLUSER":
                        if (UserPassWord.Trim().ToUpper() == "ABC123~")
                        {
                            ReturnResult.ReturnMsgNo = "1";
                            ReturnResult.ReturnMsg = "成功";
                        }
                        else
                        {
                            ReturnResult.ReturnMsgNo = "-2";
                            ReturnResult.ReturnMsg = "輸入密碼錯誤";
                        }
                        break;
                    case "MISONCALLUSER":
                        if (UserPassWord.Trim().ToUpper() == "ABC123~")
                        {
                            ReturnResult.ReturnMsgNo = "1";
                            ReturnResult.ReturnMsg = "成功";
                        }
                        else
                        {
                            ReturnResult.ReturnMsgNo = "-2";
                            ReturnResult.ReturnMsg = "輸入密碼錯誤";
                        }
                        break;
                    default:
                        ReturnResult.ReturnMsgNo = "-1";
                        ReturnResult.ReturnMsg = "無帳號";
                        break;
                } 
            }
            return ReturnResult;
        }
Ejemplo n.º 39
0
 public FileSearcher(string dataPattern, int bufferSize, EndTest endTest, GetCount getCount, ReturnResult returnResult, GetFirstFileInfo getFirstFileInfo)
 {
     this.dataPattern = dataPattern.ToLower();
     this.bufferSize = bufferSize;
     this.endTest = endTest;
     this.getCount = getCount;
     this.returnResult = returnResult;
     this.getFirstFileInfo = getFirstFileInfo;
 }
        public CommonModule(IPdfTemplateHelper pdfTemplateHelper, IEmailer emailer,
            IPdfBarcodesGenerator pdfBarcodesGenerator) : base("/api")
		{
		    _pdfTemplateHelper = pdfTemplateHelper;
            _emailer = emailer;
            _pdfBarcodesGenerator = pdfBarcodesGenerator;
            //	BARCODE FUNCTIONS
			//	Returns a list of airports
			Get["/getAirports"] = _ =>
			{
				var airportList = CustomerSite.ToList().Where(x => x.IsAirport).ToList().OrderBy(x => x.Name);
				return Response.AsJson(airportList.ToList());
			};
			//	Returns a list of airports that have been formatted for a select input
			Get["/getAirportList"] = _ =>
			{
				var airports = CustomerSite.ToList().Where(x => x.IsAirport).ToList();
				List<SelectList> airportList = new List<SelectList>();

				foreach(var airport in airports)
				{
					airportList.Add(new SelectList(){
						id = airport.RecordID,
						text = airport.Name.Trim()
					});
				}

				return Response.AsJson(airportList.OrderBy(x => x.text).ToList());
			};
            
            //	Returns all available pdf templates
		    Get["/getPdfTemplates"] = _ => Response.AsJson(_pdfTemplateHelper.GetTemplates());

            //	Returna a list of Airlines
            Get["/getAirlines"] = _ =>
			{
				var airlineList = AirlineDBO.ToList().OrderBy(x => x.Name);
				return Response.AsJson(airlineList.ToList());
			};
			//	Returns a list of Airlines that have been formatted for a select input
			Get["/getAirlineList"] = _ =>
			{
				var airlines = AirlineDBO.ToList();
				List<SelectList> airlineList = new List<SelectList>();

				foreach(var airline in airlines)
				{
					airlineList.Add(new SelectList()
					{
						id = airline.RecordID,
						text = airline.Name.Trim()
					});
				}

				return Response.AsJson(airlineList.OrderBy(x => x.text).ToList());
			};
            //  Returns a list of barcodes
            Post["/getBarcodes/{type}"] = _ =>
            {
				BarcodeWhere where = this.Bind<BarcodeWhere>();
				DateTime start = new DateTime();
				DateTime end = new DateTime();
				bool validStart = DateTime.TryParse(where.StartDate, out start);
				bool validEnd = DateTime.TryParse(where.EndDate, out end);
				//	If no dates were provided, this gets all.
				if(!validStart && !validEnd)
				{
					var barcodeList = BarcodeCreation.ToListDTO();
					return Response.AsJson(barcodeList.OrderByDescending(x => x.CreatedDateTime).ToList());
				}
				//	If one of the dates isn't valid, this returns.
				else if(!validStart || !validEnd)
				{
					return HttpStatusCode.BadRequest;
				}
				//	Otherwise this returns the filtered results
				else
				{
					var barcodeList = BarcodeCreation.ToListDTO(start, end);
					return Response.AsJson(barcodeList.OrderByDescending(x => x.CreatedDateTime).ToList());
				}
            };
			//	Returns all the details of a barcode - BarcodeCreation, FastTrackBarcode, FastTrackBarcode.Actions
			Get["/getBarcode/{type}/{recordID}"] = _ =>
			{
				Guid recordID;
				bool validGuid = Guid.TryParse(_.recordID, out recordID);
				//	If an invalid Guid was provided, return bad request
				if (!validGuid)
				{
					return HttpStatusCode.BadRequest;
				}
				var barcode = BarcodeCreation.Load(recordID);
				return Response.AsJson(barcode);
			};
			//	Returns a list of barcode actions
			Get["/getBarcodeActions/{type}/{recordID}"] = _ =>
			{
				Guid recordGUID;
				bool validGuid = Guid.TryParse(_.recordID, out recordGUID);
				if (!validGuid)
				{
					return HttpStatusCode.BadRequest;
				}
				var fastTrackActions = FastTrackBarcode.Actions(recordGUID);
				return Response.AsJson(fastTrackActions);
			};
			//	For creating a barcode
			Post["/createBarcode/{type}/{format}"] = _ =>
			{
				string type = _.type;
				string format = _.format;
				//	If departure airport, copy to guid field and then replace with iata
			    IBarcodeGenerator barcodeGenerator = null;
			    FastTrackOptions barcodeOptions = new FastTrackOptions
			    {
			        Quantity = 1
			    };

                Guid temp = new Guid();
                //	Generate barcode
                switch (type)
				{
					case "fasttrack":
				        barcodeGenerator =
				            new AddbarcodeCreationRecordToDb(new SaveFastTrackBarcodeRecordToDb(new BarcodeGenerator()));

                        barcodeOptions = this.Bind<FastTrackOptions>();

                        //	If airline, copy to guid field and then replace with iata, unless it is ---
                        if (!string.IsNullOrWhiteSpace(barcodeOptions.Airline) && barcodeOptions.Airline.Trim() != "---")
						{
							if(Guid.TryParse(barcodeOptions.Airline, out temp))
							{
								Airline airline = Airline.Load(temp);
								//	If no airline was found, empty airline fields
								if(airline == null)
								{
									barcodeOptions.Airline = "---";
									barcodeOptions.AirlineGuid = null;
								}
								//	Otherwise update fields
								else
								{
									barcodeOptions.Airline = airline.AirlineIATA;
									barcodeOptions.AirlineGuid = temp;
								}
							}
						}
						//	If departure airport, copy to guid field and then replace with iata
						if (!string.IsNullOrWhiteSpace(barcodeOptions.DepartureAirport))
						{
							if(Guid.TryParse(barcodeOptions.DepartureAirport, out temp))
							{
								CustomerSite site = CustomerSite.Load(temp);
								//	If no airport was found, that means it doesn't exist, so empties departure fields
								if(site == null)
								{
									barcodeOptions.DepartureAirport = null;
									barcodeOptions.DepartureAirportGuid = null;
								}
								//	Otherwise update fields
								else
								{
									barcodeOptions.DepartureAirportGuid = temp;
									barcodeOptions.DepartureAirport = site.AirportIATADesignation;
								}
							}
						}
						//	If destination airport, copy to guid field and then replace with iata
						if (!string.IsNullOrWhiteSpace(barcodeOptions.DestinationAirport))
						{
							if (Guid.TryParse(barcodeOptions.DestinationAirport, out temp))
							{
								//	If the same as departure, just copy name
								if(barcodeOptions.DepartureAirport == barcodeOptions.DestinationAirport)
								{
									barcodeOptions.DestinationAirport = barcodeOptions.DepartureAirport;
									barcodeOptions.DestinationAirportGuid = barcodeOptions.DepartureAirportGuid;
								}
								//	Otherwise load airport details
								else
								{
									CustomerSite site = CustomerSite.Load(temp);
									//	If no airport was found, that means it doesn't exist, so empties departure fields
									if (site == null)
									{
										barcodeOptions.DestinationAirport = null;
										barcodeOptions.DestinationAirportGuid = null;
									}
									//	Otherwise update fields
									else
									{
										barcodeOptions.DestinationAirportGuid = temp;
										barcodeOptions.DestinationAirport = site.AirportIATADesignation;
									}
								}
							}
						}
						break;
					case "test":
                        barcodeGenerator = new TestBarcodeGenerator();
						break;
					default:
						return HttpStatusCode.BadRequest;
				}
				switch (format)
				{
					case "image":
						List<string> returnText = new List<string>();
                        IBarcodeFileGenerator imageGenerator = new BarcodeImageFileGenerator(barcodeGenerator);

                        for (var i = 0; i < barcodeOptions.Quantity; i++)
				        {
				            returnText.Add(Convert.ToBase64String(imageGenerator.GenerateFile(barcodeOptions).ToArray()));
				        }

						return Response.AsJson(returnText);
					//break;
					case "email":
				        var result = new EmailFastTrackBarcodes(_emailer).EmailBarcodeFile(barcodeOptions,
				            new BarcodePdfFileGenerator(barcodeGenerator, _pdfBarcodesGenerator));

				        return result ? HttpStatusCode.Accepted : HttpStatusCode.BadRequest;
					case "pdf":
				        var stream =
				            new BarcodePdfFileGenerator(barcodeGenerator, _pdfBarcodesGenerator).GenerateFile(barcodeOptions);
                        var streamClone = new MemoryStream(stream.ToArray());
                        Response response = new Response();
				        response.Headers.Add("Content-Disposition",
				            "attachment; filename=GeneratedBarcode" + DateTime.Now.ToString("dd MMM yyyy HH mm") + ".pdf");

						response.Headers.Add("responseType", "arraybuffer");
						response.Contents = responseStream =>
						{
                            streamClone.CopyTo(responseStream);
						};
						return response;
				}
				//	Return BadRequest if not returned already
				return HttpStatusCode.BadRequest;
			};
			//	Exports all the barcodes
			Post["/exportBarcodes/{type}"] = _ =>
			{
				List<string> barcodeGuids = this.BindTo(new List<string>());
				//	If no guids were posted, export all
				if (barcodeGuids.Count() == 0)
				{
					return CSVExporter.ExportBarcodes();
				}
				//	Otherwise export select few
				else
				{
					return CSVExporter.ExportBarcodes(barcodeGuids);
				}
			};
			//	logs the user in using sems data object
			Post["/login/{type}"] = _ =>
			{
				//bind to object model
				var loginParams = this.Bind<Login>();
				//decrypt username
				loginParams.Username = Decrypt.DecryptString(loginParams.Username, _.type + "key");
				//pass sems data obejct user method the username
				var user = User.LoadUser(loginParams.Username);
				//if no user, return 401
				if (user == null)
				{
					Console.WriteLine("No User");
					return HttpStatusCode.Unauthorized;
				}
				//decrypt password
				loginParams.Password = Decrypt.DecryptString(loginParams.Password, _.type + "key");
				//if incorrect password, return 401
				if (user.Password != loginParams.Password)
				{
					Console.WriteLine("Wrong Password");
					return HttpStatusCode.Unauthorized;
				}
				var token = user.RecordID;
				//login but dont redirect, this is handled front end by angular
				return this.LoginWithoutRedirect(token);
			};
			//	logs the user in using sems data object
			Post["/login"] = _ =>
            {
                //bind to object model
                var loginParams = this.Bind<Login>();
				//pass sems data obejct user method the username
				var user = MachSecure.SEMS.DataObjects.User.LoadUser(loginParams.Username);
                //if no user, return 401
                if (user == null)
				{
					Console.WriteLine("Wrong Username");
					return HttpStatusCode.Unauthorized;
				}
                //if incorrect password, return 401
                if (user.Password != loginParams.Password)
				{
					Console.WriteLine("Wrong Password");
					return HttpStatusCode.Unauthorized;
				}
				var token = user.RecordID;
                //login but dont redirect, this is handled front end by angular
                return this.LoginWithoutRedirect(token);
            };
			//	log the user out and redirect to home
            Get["/logout"] = _ => this.LogoutAndRedirect("../#/");
			//	Gets the current logged in user
            Get["/user"] = _ =>
            {
                var user = Context.CurrentUser;
                return Response.AsJson(user);
            };
			//	Tests connection
            Get["/test"] = _ =>
            {
                List<string> s = new List<string>();
				//SMTP.SendEmail("*****@*****.**", "Test Email", "This is a test e-mail");

				for (int i = 0; i < 1000000; i++)
                {
                    s.Add("test");
                }

                return Response.AsJson(s);
            };
		//	/BARCODE ACTIONS
		//	ROSTER IMPORT FUNCTIONS
			//	Returns contents of a csv file
			Post["/readCSV"] = _ =>
			{
				ReadCsvOptions options = this.Bind<ReadCsvOptions>();
				ReturnResult result = new ReturnResult();
				var files = Request.Files;
				//	If no file, return
				if(files.Count() == 0)
				{
					result.Success = false;
					result.Error = "No file found";
					result.ErrorDescription = "No CSV file was uploaded";
					result.Result = null;
					return Response.AsJson(result);
				}
				List<CsvObject> csvs = new List<CsvObject>();
				foreach (var file in files)
				{
					string extension = Path.GetExtension(file.Name);
					//	If not a csv file, return
					if(extension != ".csv")
					{
						result.Success = false;
						result.Error = "Invalid file";
						result.ErrorDescription = file.Name + " is not a csv file";
						result.Result = null;
						return Response.AsJson(result);
					}
					StreamReader csvReader = new StreamReader(file.Value);
					CsvObject csv = new CsvObject();
					List<string[]> rows = new List<string[]>();
					int index = 0;
					bool escape = false;
					while (!csvReader.EndOfStream && escape != true)
					{
						string line = csvReader.ReadLine();
						string[] values = line.Split(',');
						//	If headers, place into headers string[]
						if (index == 0)
						{
							csv.Headers = values;
						}
						else
						{
							rows.Add(values);
						}
						index++;
						//	If there is a limit, and this exceeds it, this sets escape to true
						if (options.Limit != null && options.Limit > 0 && index > options.Limit)
						{
							escape = true;
						}
					}
					csv.Rows = rows;
					csvs.Add(csv);
				}
				//	To get this far, it was successful, so it returns so
				result.Success = true;
				result.Error = null;
				result.ErrorDescription = null;
				result.Result = csvs;
				return Response.AsJson(result);
			};
		//	/ROSTER IMPORT FUNCTIONS
		}
Ejemplo n.º 41
0
        //資料查詢
        public JsonResult IndexDataJson(string select, string view, string where, string orderby, string iseasyquery, string strquery)
        {
            ReturnResult ReturnResult = new ReturnResult();
            ReturnDBResult ReturnDBResult = new ReturnDBResult();

            if (NeedSn(view, where))
            {
                ReturnResult.ReturnMsgNo = "MQLD0001";
                ReturnResult.ReturnMsg = "此查詢必須要有SN";
                return Json(ReturnResult, JsonRequestBehavior.AllowGet);   
            } 

            ReturnDBResult = ViewQueryLog(select, view, where, orderby, iseasyquery, strquery);

            ReturnResult.ReturnMsgNo = Convert.ToString(ReturnDBResult.ReturnMsgNo);
            ReturnResult.ReturnMsg = ReturnDBResult.ReturnMsg;
            ReturnResult.ReturnTB = ReturnTB(ReturnDBResult);
            return Json(ReturnResult, JsonRequestBehavior.AllowGet);
        }