private async Task <StorageModels.Project> GetProjectAsync(ExceptionModel model)
        {
            var project = await dbContext.Projects.FirstOrDefaultAsync(f => f.Token == model.Token);

            if (project == null)
            {
                project = new StorageModels.Project
                {
                    Token = model.Token
                };
            }
            return(project);
        }
 public IHttpActionResult PostCollection(CollectionModel data)
 {
     try
     {
         var result = oSvc.PostCollection(data);
         return(Ok(result));
     }
     catch (Exception ex)
     {
         ExceptionModel exc = oException.Set(ex);
         return(Ok(exc));
     }
 }
        private async Task <StorageModels.Manufacturer> GetManufacturerAsync(ExceptionModel model)
        {
            var manufacturer = await dbContext.Manufacturers.FirstOrDefaultAsync(f => f.Name == model.Manufacturer);

            if (manufacturer == null)
            {
                manufacturer = new StorageModels.Manufacturer
                {
                    Name = model.Manufacturer
                };
            }
            return(manufacturer);
        }
 public IHttpActionResult GetCollections(string title = "", int?status = null, int?collectionid = null)
 {
     try
     {
         var result = oSvc.GetCollection(title, status, collectionid);
         return(Ok(result));
     }
     catch (Exception ex)
     {
         ExceptionModel oExc = oException.Set(ex);
         return(Ok(oExc));
     }
 }
        private async Task <StorageModels.Model> GetModelAsync(ExceptionModel model)
        {
            var dbModel = await dbContext.Models.FirstOrDefaultAsync(f => f.Name == model.Model);

            if (dbModel == null)
            {
                dbModel = new StorageModels.Model
                {
                    Name  = model.Model,
                    Brand = await GetBrandAsync(model)
                };
            }
            return(dbModel);
        }
        private async Task <StorageModels.Brand> GetBrandAsync(ExceptionModel model)
        {
            var dbBrand = await dbContext.Brands.FirstOrDefaultAsync(f => f.Name == model.Brand);

            if (dbBrand == null)
            {
                dbBrand = new StorageModels.Brand
                {
                    Name         = model.Brand,
                    Manufacturer = await GetManufacturerAsync(model)
                };
            }
            return(dbBrand);
        }
Exemplo n.º 7
0
        /// <summary>
        /// 微信支付成功返回数据
        /// </summary>
        /// <param name="data"></param>
        private void OnPaySuccess(WxPayData data)
        {
            var attach    = (string)data.GetValue("attach");
            var wxOrderId = (string)data.GetValue("transaction_id");

            if (string.IsNullOrEmpty(attach))
            {
                var em = new ExceptionModel()
                {
                    Content = "微信支付返回:attach为空"
                };
                em.Save();
                throw em;
            }
            if (string.IsNullOrEmpty(wxOrderId))
            {
                var em = new ExceptionModel()
                {
                    Content = "微信支付返回:微信订单号为空"
                };
                em.Save();
                throw em;
            }
            string[] aa                = attach.Split(',');
            string   uniacid           = aa[0];
            string   accountID         = aa[1];
            string   orderID           = aa[2];
            var      mongo             = new MongoDBTool();
            var      accountCollection = mongo.GetMongoCollection <AccountModel>();

            var filter    = Builders <AccountModel> .Filter;
            var filterSum = filter.Eq(x => x.AccountID, new ObjectId(accountID)) & filter.Eq("Orders.OrderID", new ObjectId(orderID));
            var account   = accountCollection.Find(filterSum).FirstOrDefault();
            var wcOrder   = account.Orders.Find(x => x.OrderID.Equals(new ObjectId(orderID)) && !x.IsPaid);

            if (wcOrder == null)
            {
                var em = new ExceptionModel()
                {
                    Content = "微信支付返回:订单不存在或者已经生成"
                };
                em.Save();
                throw em;
            }
            var update = Builders <AccountModel> .Update
                         .Set("Orders.$.WeChatOrderID", wxOrderId)
                         .Set("Orders.$.IsPaid", true);

            accountCollection.UpdateOne(filterSum, update);
        }
Exemplo n.º 8
0
        /// <summary>
        /// 创建语音口令红包
        /// </summary>
        /// <param name="uniacid"></param>
        /// <param name="accountID"></param>
        /// <param name="packetsModel"></param>
        /// <returns></returns>
        internal async Task <string> CreateVoicePackets(string uniacid, ObjectId accountID, VoicePacketsModel packetsModel)
        {
            CheckPeopleNum(packetsModel);
            CheckText(packetsModel.TextCmd);

            packetsModel.uniacid    = uniacid;
            packetsModel.CreateTime = DateTime.Now;
            return(await Task.Run(() =>
            {
                var account = GetModelByIDAndUniacID(accountID, uniacid);
                if (account == null)
                {
                    var e = new ExceptionModel()
                    {
                        MethodFullName = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName,
                        Content = $"用户为空:accountID={accountID.ToString()},uniacid={uniacid}",
                        ExceptionDate = DateTime.Now
                    };
                    e.Save();
                    throw e;
                }

                var serviceMoney = GetServiceMoney(uniacid, packetsModel.Amount);
                var balance = account.Balances - (packetsModel.Amount + serviceMoney);

                packetsModel.PacketsID = ObjectId.GenerateNewId();
                packetsModel.CreatePeople = new Participant
                {
                    AccountID = account.AccountID,
                    AccountAvatar = account.AccountAvatar,
                    AccountName = account.AccountName,
                    CreateTime = DateTime.Now
                };
                if (balance < 0)
                {
                    WeChatOrder weChatOrder;
                    WXPayModel wXPayModel = GetCreatePacketsPayParams(-balance, packetsModel, uniacid, account, out weChatOrder);
                    return new BaseResponseModel3 <bool, string, WXPayModel>()
                    {
                        StatusCode = ActionParams.code_ok, JsonData = false, JsonData1 = packetsModel.PacketsID.ToString(), JsonData2 = wXPayModel
                    }.ToJson();
                }
                CreateVoicePackets(account, packetsModel, serviceMoney, balance);
                return new BaseResponseModel2 <bool, string>()
                {
                    StatusCode = ActionParams.code_ok, JsonData = true, JsonData1 = packetsModel.PacketsID.ToString()
                }.ToJson();
            }));
        }
        /// <summary>
        /// Configures a global exception handling on for app
        /// </summary>
        /// <param name="app">app to apply global exception handling on</param>
        public static void UseGlobalExceptionHandler(this IApplicationBuilder app)
        {
            app.UseExceptionHandler(error =>
            {
                // Globally track exceptions to return appropriate http responses and status codes
                error.Run(async context =>
                {
                    // Set up exception handler to listen for exception
                    var exceptionHandlerFeature = context.Features.Get <IExceptionHandlerFeature>();
                    var exception = exceptionHandlerFeature.Error;

                    // Set default status code for exception is 500 (Internal Server Error) if exception does not match those traced
                    var statusCode = (int)HttpStatusCode.InternalServerError;

                    // Globally track resource not found exceptions (404),
                    // Badly formatted input exception (412) when model input is invalid
                    // And unauthorization exception (401) when user fails to meet authorization requirement
                    if (exception is ResourceNotFoundException)
                    {
                        statusCode = (int)HttpStatusCode.NotFound;
                    }
                    else if (exception is ModelFormatException)
                    {
                        statusCode = (int)HttpStatusCode.PreconditionFailed;
                    }
                    else if (exception is ArgumentOutOfRangeException)
                    {
                        statusCode = (int)HttpStatusCode.BadRequest;
                    }

                    // On exception construct error model and specify HTTP status code content type
                    context.Response.ContentType = "application/json";
                    context.Response.StatusCode  = statusCode;
                    var exceptionModel           = new ExceptionModel
                    {
                        StatusCode       = statusCode,
                        ExceptionMessage = exception.Message,
                        StackTrace       = exception.StackTrace
                    };

                    // Log explicit exception message when exception occurs to log file
                    var logService = app.ApplicationServices.GetService(typeof(ILogService)) as ILogService;
                    logService.LogToDatabase(exceptionModel);

                    // Send exception model as HTTP response back to client
                    await context.Response.WriteAsync(exceptionModel.ToString());
                });
            });
        }
Exemplo n.º 10
0
        private async Task <Share> PostShareAsync(Share share)
        {
            CheckTokenThenAddToHeaders();
            var content  = new StringContent(share.ToJson(), Encoding.UTF8, "application/json");
            var response = await _client.PostAsync($"{_apiHost}v2/shares", content);

            var responseJson = await response.Content.ReadAsStringAsync();

            if (!response.IsSuccessStatusCode)
            {
                throw new ApiException(ExceptionModel.FromJson(responseJson));
            }

            return(Share.FromJson(responseJson));
        }
Exemplo n.º 11
0
        public async Task <IActionResult> UpdateException(long id, ExceptionModel exceptionModel)
        {
            if (id != exceptionModel.ExceptionId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                await _exceptionService.MarkExceptionAsFixedAsync(id);

                return(RedirectToAction(nameof(ExceptionList)));
            }
            return(View(exceptionModel));
        }
Exemplo n.º 12
0
        public virtual byte[] ReadBytes(DbDataReader dataReader, int ordinalPosition)
        {
            try
            {
                Byte[] bytes = new Byte[(int)(dataReader.GetBytes(ordinalPosition, 0, null, 0, Int32.MaxValue))];
                dataReader.GetBytes(ordinalPosition, 0, bytes, 0, bytes.Length);

                return(bytes);
            }
            catch (Exception ex)
            {
                ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name);
                return(null);
            }
        }
        private ExceptionModel GetExceptionModel(Exception exception)
        {
            var exceptions = FlattenExceptions(exception).ToArray();

            // Pick the last exception as the root since it's the most specific one - just like the YSOD and ELMAH does
            var root = exceptions.Last();

            var model = new ExceptionModel
            {
                Type    = root.Type,
                Message = root.Message
            };

            return(model);
        }
Exemplo n.º 14
0
        /// <summary>
        /// This routine provides a wrapper around VerifyHash converting the strings containing the
        /// data, hash and salt into byte arrays before calling VerifyHash.
        /// </summary>
        /// <param name="Data">A UTF-8 encoded string containing the data to verify</param>
        /// <param name="Hash">A base-64 encoded string containing the previously stored hash</param>
        /// <param name="Salt">A base-64 encoded string containing the previously stored salt</param>
        /// <returns></returns>

        public bool VerifyHashString(string Data, string Hash, string Salt)
        {
            try
            {
                byte[] HashToVerify = Convert.FromBase64String(Hash);
                byte[] SaltToVerify = Convert.FromBase64String(Salt);
                byte[] DataToVerify = Encoding.UTF8.GetBytes(Data);
                return(VerifyHash(DataToVerify, HashToVerify, SaltToVerify));
            }
            catch (Exception ex)
            {
                ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name);
                return(false);
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// log exception and return exception model
        /// </summary>
        /// <param name="exception">the system exception</param>
        /// <returns>the exception model</returns>
        public ExceptionModel LogException(Exception exception)
        {
            var returnValue = new ExceptionModel();

            returnValue.Message    = exception.Message;
            returnValue.Source     = exception.Source;
            returnValue.StackTrace = exception.StackTrace;

            //while (exception.InnerException != null)
            //{
            //    returnValue.InnerException = this.LogException(exception.InnerException);
            //}

            return(returnValue);
        }
Exemplo n.º 16
0
        /// <summary>
        /// 获取红包列表
        /// </summary>
        /// <param name="uniacid"></param>
        /// <param name="accountID"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        internal List <VoicePacketsModel> GetPacketsList(string uniacid, ObjectId accountID, PacketsDoType type)
        {
            var account       = GetModelByIDAndUniacID(accountID, uniacid);
            var vpmCollection = mongo.GetMongoCollection <VoicePacketsModel>();

            switch (type)
            {
            case PacketsDoType.send:
                if (account.SendPackets == null)
                {
                    var em = new ExceptionModel()
                    {
                        ExceptionParam = ActionParams.code_null
                    };
                    em.Save();
                    throw em;
                }
                for (int i = 0; i < account.SendPackets.Count; i++)
                {
                    account.SendPackets[i] = vpmCollection.Find(x => x.PacketsID.Equals(account.SendPackets[i].PacketsID)).FirstOrDefault();
                }
                return(account.SendPackets);

            case PacketsDoType.receive:
                if (account.ReceivePackets == null)
                {
                    var em = new ExceptionModel()
                    {
                        ExceptionParam = ActionParams.code_null
                    };
                    em.Save();
                    throw em;
                }
                for (int i = 0; i < account.ReceivePackets.Count; i++)
                {
                    account.ReceivePackets[i] = vpmCollection.Find(x => x.PacketsID.Equals(account.ReceivePackets[i].PacketsID)).FirstOrDefault();
                }
                return(account.ReceivePackets);

            default:
                var e = new ExceptionModel()
                {
                    Content = "获取红包列表type类型未知"
                };
                e.Save();
                throw e;
            }
        }
Exemplo n.º 17
0
        //private const string RegisterEmail = "ODS.Email";
        //private const string QueryStringKey = "ODS.QueryString";

        public Configurations()
        {
            Exception = new ExceptionModel();

            PageTitle   = "Merachel";
            HasHeader   = true;
            HasFooter   = true;
            HasMenuBar  = true;
            IsDashBoard = false;
            ModuleName  = "New Form";
            MenuName    = "New Form";

            // Get current logon user without domain.
            string userName = string.Empty;

            if (HttpContext.Current.User.Identity.Name.IndexOf('@') > 0)
            {
                userName = HttpContext.Current.User.Identity.Name.Split('@')[0];
            }
            else
            {
                if (HttpContext.Current.User.Identity.Name.IndexOf('\\') > 0)
                {
                    userName = HttpContext.Current.User.Identity.Name.Split('\\')[1];
                }
            }

            SessionUserName = userName;

            // Get all default settings.
            this.MerachelUrl    = GetServiceUrl(); //GetScheme() + HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.ApplicationPath.TrimEnd('/');
            this.MerachelWebUrl = GetWebUrl();

            JavaScriptAndCssVersion = ConfigurationManager.AppSettings["JavaScriptAndCssVersion"];
            string cookieVersion = ConfigurationManager.AppSettings["CookieVersion"];

            // Get configuration settings.
            CookieNameConfiguration = "merachel-configuration-" + cookieVersion;
            CookieValue             = "{}";

            AccountModel session = GetSessionInfo();

            if (session != null)
            {
                RoleInfoModel role = (from obj in session.UserRoles where obj.Sequence == 1 select obj).FirstOrDefault();
                RoleName = role.RoleName;
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// 配置异常类型映射
        /// </summary>
        /// <param name="ex">异常实例</param>
        /// <param name="service">服务名称,MVC控制器或API控制器默认为控制器名称(不包括后缀Controller)</param>
        /// <param name="exceptionModel">异常数据</param>
        /// <returns></returns>
        public WebExceptionModel MapTo(Exception ex, string service, ExceptionModel exceptionModel)
        {
            WebExceptionModel webExceptionModel = null;

            if (exceptionModel.Code.IsNullOrEmpty())
            {
                ExceptionModel exceptionModel2 = null;
                var            exType          = ex.GetType();
                do
                {
                    exceptionModel2 = TypeMappers.GetValueBy(exType);
                    exType          = exType.BaseType;
                } while (exceptionModel2 == null);
                exceptionModel.Code = exceptionModel2.Code;
                if (exceptionModel.Message.IsNullOrEmpty())
                {
                    exceptionModel.Message = exceptionModel2.Message;
                }
                if (exceptionModel.Details.IsNullOrEmpty())
                {
                    exceptionModel.Details = exceptionModel2.Details;
                }
            }
            else
            {
                if (service == null)
                {
                    service = "";
                }
                var codeMappers = WebCodeMappers.GetValueBy(service);
                if (codeMappers == null && service.Length > 0)
                {
                    service     = "";
                    codeMappers = WebCodeMappers.GetValueBy(service);
                }
                webExceptionModel = codeMappers.GetValueBy(exceptionModel.Code);
            }
            if (webExceptionModel == null)
            {
                var exType = ex.GetType();
                do
                {
                    webExceptionModel = WebTypeMappers.GetValueBy(exType);
                    exType            = exType.BaseType;
                } while (webExceptionModel == null);
            }
            return(webExceptionModel);
        }
Exemplo n.º 19
0
        /// <summary>
        /// 提现完成
        /// </summary>
        /// <param name="uniacid"></param>
        /// <param name="accountID"></param>
        /// <param name="money"></param>
        internal void PullBalanceFinish(string uniacid, ObjectId accountID, decimal money)
        {
            var account  = GetModelByIDAndUniacID(accountID, uniacid);
            var balances = account.Balances - money;

            if (balances < 0)
            {
                var em = new ExceptionModel()
                {
                    ExceptionParam = ActionParams.code_insufficient_balance
                };
                em.Save();
                throw em;
            }
            collection.UpdateOne(x => x.AccountID.Equals(accountID), Builders <AccountModel> .Update.Set(x => x.Balances, balances));
        }
Exemplo n.º 20
0
        /// <summary>
        /// Get information about authorized user, if your access token invalid you will get ApiException error
        /// </summary>
        /// <exception cref="ApiException"></exception>
        /// <returns></returns>
        public async Task <Profile> GetOwnProfileAsync()
        {
            CheckTokenThenAddToHeaders();
            var response = await _client.GetAsync($"{_apiHost}v2/me");

            var jsonData = await response.Content.ReadAsStringAsync();

            var profile = Profile.FromJson(jsonData);

            if (!response.IsSuccessStatusCode)
            {
                throw new ApiException(ExceptionModel.FromJson(await response.Content.ReadAsStringAsync()));
            }

            return(profile);
        }
Exemplo n.º 21
0
        private String GetRole(String username)
        {
            try
            {
                RestaurantController restaurantController = new RestaurantController();
                LoginIdModel         loginIdModel         = new Restaurants.Models.LoginIdModel();

                loginIdModel.LoginId = username;
                return(restaurantController.GetUserRole(loginIdModel).Content.Role);
            }
            catch (Exception ex)
            {
                ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name);
                return("");
            }
        }
Exemplo n.º 22
0
        private async Task <EntityElements <Share> > GetPostsAsync(string ownerURN, int sharesPerOwner = 100)
        {
            CheckTokenThenAddToHeaders();
            var response = await _client.GetAsync($"{_apiHost}v2/shares?q=owners&owners={ownerURN}&sharesPerOwner={sharesPerOwner}");

            var responseJson = await response.Content.ReadAsStringAsync();

            var shares = EntityElements <Share> .FromJson(responseJson);

            if (!response.IsSuccessStatusCode)
            {
                throw new ApiException(ExceptionModel.FromJson(responseJson));
            }

            return(shares);
        }
Exemplo n.º 23
0
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            var ex = new ExceptionModel
            {
                Name       = actionExecutedContext.Exception.Message,
                Detail     = actionExecutedContext.Exception.StackTrace,
                Action     = actionExecutedContext.ActionContext.ActionDescriptor.ActionName,
                Controller = actionExecutedContext.ActionContext.ControllerContext.ControllerDescriptor.ControllerName
            };

            //1. Log
            Logger.LogWrite(ex);
            //2. Response
            actionExecutedContext.Response =
                actionExecutedContext.Request.CreateResponse(HttpStatusCode.BadRequest, ex);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Converts an exception to an <see cref="ExceptionModel"/>.
        /// If the <see cref="Exception.Data"/> dictionary contains a
        /// key called 'fingerprint' it will be used to calculate the
        /// 'fingerprint' field on the notice.
        /// </summary>
        public static ExceptionModel CreateFromException(Exception ex)
        {
            var m = new ExceptionModel(ex.GetType().Name, ex.Message);

            if (ex.Data.Contains("fingerprint"))
            {
                m.Fingerprint = ex.Data["fingerprint"].ToString();
            }

            if (ex.Data.Count > 0)
            {
                m.Data = ex.Data.Keys.Cast <object>().ToDictionary(k => k, k => ex.Data[k]);
            }

            return(m);
        }
Exemplo n.º 25
0
        public static void UseGlobalExceptionHandler(this IApplicationBuilder app)
        {
            app.UseExceptionHandler(errorMsg =>
            {
                errorMsg.Run(async context =>
                {
                    var exceptionHandlerFeature = context.Features.Get <IExceptionHandlerFeature>();



                    if (exceptionHandlerFeature != null)
                    {
                        var exceptionType            = exceptionHandlerFeature.Error;
                        var statusCode               = (int)HttpStatusCode.InternalServerError;
                        context.Response.ContentType = "application/json";

                        if (exceptionType is ResourceNotFoundException)
                        {
                            statusCode = (int)HttpStatusCode.NotFound;
                        }
                        else if (exceptionType is ModelFormatException)
                        {
                            statusCode = (int)HttpStatusCode.PreconditionFailed;
                        }
                        else if (exceptionType is ArgumentOutOfRangeException)
                        {
                            statusCode = (int)HttpStatusCode.BadRequest;
                        }

                        ExceptionModel exceptionModel = new ExceptionModel {
                            StatusCode       = statusCode,
                            ExceptionMessage = exceptionType.Message,
                            StackTrace       = exceptionType.StackTrace.ToString()
                        };

                        var logService = app.ApplicationServices.GetService(typeof(ILogService)) as ILogService;
                        logService.LogToDatabase(exceptionModel);

                        await context.Response.WriteAsync(new ExceptionModel {
                            StatusCode       = statusCode,
                            ExceptionMessage = exceptionType.Message,
                            StackTrace       = exceptionType.StackTrace.ToString()
                        }.ToString());
                    }
                });
            });
        }
Exemplo n.º 26
0
        /// <summary>
        /// Configures a global exception handling on for app
        /// </summary>
        /// <param name="app">app to apply global exception handling on</param>
        public static void ConfigureExceptionHandler(this IApplicationBuilder app)
        {
            app.UseExceptionHandler(error =>
            {
                // Globally track exceptions to return appropriate http responses and status codes
                error.Run(async context =>
                {
                    // Set up exception handler to listen for exception
                    var exceptionHandlerFeature = context.Features.Get <IExceptionHandlerFeature>();
                    var exception = exceptionHandlerFeature.Error;

                    // Set default status code for exception is 500 (Internal Server Error) if exception does not match those traced
                    var statusCode = (int)HttpStatusCode.InternalServerError;

                    // Globally track resource not found exceptions (404) and
                    // Badly formatted input exception (412) when model input is invalid
                    if (exception is ResourceNotFoundException)
                    {
                        statusCode = (int)HttpStatusCode.NotFound;
                    }
                    else if (exception is ParameterFormatException)
                    {
                        statusCode = (int)HttpStatusCode.BadRequest;
                    }
                    else if (exception is AuthorizationException)
                    {
                        statusCode = (int)HttpStatusCode.Unauthorized;
                    }
                    else if (exception is InputFormatException)
                    {
                        statusCode = (int)HttpStatusCode.PreconditionFailed;
                    }

                    // Log explicit exception message when exception occurs to log file
                    var logService = app.ApplicationServices.GetService(typeof(ILogService)) as ILogService;
                    logService.LogToFile($"Exception: {exception.Message}\n\tStatus Code: {statusCode}\n\tStack trace:\n{exception.StackTrace}");

                    // On exception respond with the error model format as a HTTP response back to client
                    context.Response.ContentType = "application/json";
                    context.Response.StatusCode  = statusCode;
                    var exceptionResponse        = new ExceptionModel {
                        StatusCode = statusCode, Message = exception.Message
                    };
                    await context.Response.WriteAsync(exceptionResponse.ToString());
                });
            });
        }
Exemplo n.º 27
0
        private Int32 GetSystemUserIdFromLogin(String loginId)
        {
            SystemUserModel systemUserModel = new SystemUserModel();


            try
            {
                SqlDataReader reader       = null;
                Int32         systemUserId = 0;
                SqlConnection myConnection = new SqlConnection();
                myConnection.ConnectionString = System.Configuration.ConfigurationManager.AppSettings["DBConnection"];

                SqlCommand sqlCmd = new SqlCommand();
                sqlCmd             = new SqlCommand();
                sqlCmd.CommandText = "spGetSystemUserIdFromLogin";
                sqlCmd.CommandType = CommandType.StoredProcedure;
                sqlCmd.Connection  = myConnection;

                SqlParameter parameter = new SqlParameter();
                parameter.ParameterName = "@Login_Id";
                parameter.SqlDbType     = SqlDbType.VarChar;
                parameter.Direction     = ParameterDirection.Input;
                parameter.Size          = 50;
                parameter.Value         = loginId;
                sqlCmd.Parameters.Add(parameter);

                myConnection.Open();
                reader = sqlCmd.ExecuteReader();

                int systemUserIdOrdinal = reader.GetOrdinal("System_User_Id");

                if (reader.Read())
                {
                    systemUserId = reader.GetInt32(systemUserIdOrdinal);
                }

                myConnection.Close();

                return(systemUserId);
            }
            catch (Exception ex)
            {
                ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name);
                return(-1);
            }
        }
Exemplo n.º 28
0
        internal void SaveCarInfo(string uniacid, ObjectId accountID, string carNumber, string accountPhone)
        {
            if (string.IsNullOrEmpty(carNumber) || string.IsNullOrEmpty(accountPhone))
            {
                var em = new ExceptionModel()
                {
                    Content = "参数为空"
                };
                em.Save();
                throw em;
            }
            var filter    = Builders <AccountModel> .Filter;
            var filterSum = filter.Eq(x => x.uniacid, uniacid) & filter.Eq(x => x.AccountID, accountID);
            var update    = Builders <AccountModel> .Update.Set(x => x.CarNumber, carNumber).Set(x => x.AccountPhoneNumber, accountPhone);

            collection.UpdateOne(filterSum, update);
        }
Exemplo n.º 29
0
        public int AddException(Exception ex, string absoluteURL)
        {
            var            member = HttpContext.Session.GetObjectFromJson <MemberModel>("Member");
            int            id     = 0;
            ExceptionModel model  = new ExceptionModel();

            model.StackTrace     = ex.StackTrace;
            model.AbsoluteUrl    = absoluteURL;
            model.MemberId       = member.MemberID;
            model.MemberFullName = member.FullName;
            using (TWHContext context = new TWHContext())
            {
                id = context.AddException(model);
            }

            return(id);
        }
Exemplo n.º 30
0
        public static T GetData <T>(IRestResponse <T> response) where T : new()
        {
            if (response.StatusCode == 0)
            {
                throw new Exception(response.ErrorException.Message);
            }

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                ExceptionModel exceptionModel = JsonConvert.DeserializeObject <ExceptionModel>(response.Content);
                throw new Exception(exceptionModel.Message);
            }

            T result = response.Data;

            return(result);
        }
Exemplo n.º 31
0
        public ExceptionModel ParseExceptionModel(Exception exp)
        {
            if (exp == null)
                return null;

            var result = new ExceptionModel();
            result.ErrCode = 500;
            result.ErrType = "HttpStatusCode";
            result.ErrName = "HttpStatusCode.InternalServerError";
            result.ErrMsg = exp.Message;
            result.StackTraces = exp.StackTrace?.Split('\n');

            if (exp is DbEntityValidationException)
            {
                var be = exp as DbEntityValidationException;
                if (be != null && be.EntityValidationErrors != null)
                {
                    result.ErrData = be.EntityValidationErrors.Select(it => new
                    {
                        EntityType = it?.Entry?.Entity?.GetType(),
                        ValidationErrors = it?.ValidationErrors
                    });
                }
            }

            if (exp is BusinessException)
            {
                var be = exp as BusinessException;
                if (be != null)
                {
                    result.ErrCode = be.ErrorCode;
                    result.ErrType = be.ErrorCodeType;
                    result.ErrName = be.ErrorName;
                }
            }

            if (exp.InnerException != null)
                result.InnerErr = ParseExceptionModel(exp.InnerException);

            return result;
        }
        void Log_GlobalWriteToExternalLog(string formattedMessage, CoreLib.Diagnostics.LogEntryType type, object extra)
        {
            using (ILogMethod method = Log.LogMethod(this.DYN_MODULE_NAME, "Log_GlobalWriteToExternalLog"))
            {
                try
                {
                    Dispatcher.Invoke(new Action(() =>
                    {
                        if (type == CoreLib.Diagnostics.LogEntryType.Exception)
                        {
                            if (axConsole.Exceptions.Count >= 32767)
                                axConsole.Exceptions.Clear();

                            ExceptionModel item = new ExceptionModel()
                            {
                                SNo = axConsole.Exceptions.Count + 1,
                                ReceivedTime = DateTime.Now,
                                Exception = formattedMessage,
                            };
                            axConsole.Exceptions.Add(item);
                        }

                        if (axConsole.Output.Length > 32767)
                        {
                            axConsole.Output = string.Empty;
                        }

                        axConsole.Output += DateTime.Now.ToFullString() + "\t" + formattedMessage + Environment.NewLine;
                        axConsole.ScrollToEnd();
                    }));
                }
                catch (Exception ex)
                {
                    method.Exception(ex);
                }
            }
        }
Exemplo n.º 33
0
    // Generates documentation for an exception, added to operation documentation
    public void FormatExceptionDocumentation(ExceptionModel exception)
    {
        var documentation = CleanupDocumentation(exception.Documentation);


        
        #line default
        #line hidden
        
        #line 231 "C:\code\dotnet\clean\sdk\src\ServiceClientGenerator\Generators\BaseGenerator.tt"
this.Write("        /// <exception cref=\"");

        
        #line default
        #line hidden
        
        #line 232 "C:\code\dotnet\clean\sdk\src\ServiceClientGenerator\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));

        
        #line default
        #line hidden
        
        #line 232 "C:\code\dotnet\clean\sdk\src\ServiceClientGenerator\Generators\BaseGenerator.tt"
this.Write(".Model.");

        
        #line default
        #line hidden
        
        #line 232 "C:\code\dotnet\clean\sdk\src\ServiceClientGenerator\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(exception.Name));

        
        #line default
        #line hidden
        
        #line 232 "C:\code\dotnet\clean\sdk\src\ServiceClientGenerator\Generators\BaseGenerator.tt"
this.Write("\">\r\n");

        
        #line default
        #line hidden
        
        #line 233 "C:\code\dotnet\clean\sdk\src\ServiceClientGenerator\Generators\BaseGenerator.tt"

        WriteCommentBlock("        ", documentation);

        
        #line default
        #line hidden
        
        #line 235 "C:\code\dotnet\clean\sdk\src\ServiceClientGenerator\Generators\BaseGenerator.tt"
this.Write("        /// </exception>\r\n");

        
        #line default
        #line hidden
        
        #line 237 "C:\code\dotnet\clean\sdk\src\ServiceClientGenerator\Generators\BaseGenerator.tt"

    }
Exemplo n.º 34
0
        private ActionResult InvokeFailureAction(ExceptionModel exceptionModel, Func<ActionResult> customOnFailure)
        {
            if (customOnFailure != null)
            {
                return customOnFailure();
            }

            NotificationType notificationType = exceptionModel.NotificationType;
            string notificationMessage = exceptionModel.NotificationMessage;
            SetNotification(notificationType, notificationMessage);

            if (HttpContext.Request.IsAjaxRequest())
            {
                return FailureJsonResult();
            }

            return new EmptyResult();
        }
Exemplo n.º 35
0
    // Generates documentation for an exception, added to operation documentation
    public void FormatExceptionDocumentation(ExceptionModel exception)
    {
        var documentation = CleanupDocumentation(exception.Documentation);


        
        #line default
        #line hidden
        
        #line 237 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("        /// <exception cref=\"");

        
        #line default
        #line hidden
        
        #line 238 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));

        
        #line default
        #line hidden
        
        #line 238 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(".Model.");

        
        #line default
        #line hidden
        
        #line 238 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(exception.Name));

        
        #line default
        #line hidden
        
        #line 238 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("\">\r\n");

        
        #line default
        #line hidden
        
        #line 239 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"

        WriteCommentBlock("        ", documentation);

        
        #line default
        #line hidden
        
        #line 241 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("        /// </exception>\r\n");

        
        #line default
        #line hidden
        
        #line 243 "C:\codebase\V3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"

    }