public oCreateOrderResponse PostOrder(oCreateOrderRequest order) { long iRefId = 0; string sref = String.Empty; bool bOrderInserted = false; bool bItemsInserted = false; long? iDentity = 0; //this is if the thumnail is too big(by using a HEAD command), default to this as it makes the PDF document too big string stemp_thumb = "https://yourdomain.com/RedBubble/images/na.gif"; //get custom http header code from config file var config = ConfigurationManager.GetSection("applicationSettings/redbubble.Properties.Settings"); var xAuthToken = ((ClientSettingsSection)config).Settings.Get("XAuthToken").Value.ValueXml.InnerText; //get remote information IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest; var headers = request.Headers["X-Auth-Token"]; OperationContext context = OperationContext.Current; MessageProperties prop = context.IncomingMessageProperties; RemoteEndpointMessageProperty endpoint = prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; string ip = endpoint.Address.ToString(); if (xAuthToken != headers) { sref = "Auth Failed"; LogError(order.external_ref, "AuthFailed", sref, order, ip); throw new System.ServiceModel.Web.WebFaultException(HttpStatusCode.Unauthorized); } using (var dc = new redbubbleDataContext()) { try { List <items> line_items = order.items; int? iLineItemsCount = line_items.Count; //database might want this for easier count of items so a join is not needed DateTime dtSaleDate; dtSaleDate = Convert.ToDateTime(order.sale_datetime); bool berror = false; #region validate_all_fields if (order.external_ref == 0 || order.external_ref == null) { sref = "missing purchase order external_ref order number"; berror = true; LogError(order.external_ref, "RedBubble endpoint", sref, order, ip); throw new System.ServiceModel.Web.WebFaultException(HttpStatusCode.InternalServerError); } //check more order fields of course foreach (items itmt in line_items) { if (itmt.external_ref == 0 || itmt.external_ref == null) { sref = "missing order line external_ref item number"; berror = true; LogError(order.external_ref, "RedBubble endpoint", sref, order, ip); throw new System.ServiceModel.Web.WebFaultException(HttpStatusCode.InternalServerError); } //check more items of course } //end for items #endregion if (berror == false) { try { ISingleResult <sp_insert_orders_oheadResult> res = dc.sp_insert_orders_ohead(order.external_ref, dtSaleDate, order.purchase_complete, order.company_ref_id, order.customer_name, order.shipping_address_1, order.shipping_address_2, order.shipping_address_3, order.shipping_address_4, order.shipping_postcode, order.shipping_country, order.shipping_country_code, order.shipping_method, order.phone, iLineItemsCount, ip, ref iDentity); iDentity = (long?)order.external_ref; bOrderInserted = true; } catch (Exception ex) { berror = true; LogError(order.external_ref, "RedBubble endpoint", ex.Message.ToString(), order, ip); } //insert into orders_oline try { foreach (items itm in line_items) { dc.sp_insert_orders_oline(iDentity, itm.external_ref, itm.sku, itm.description, itm.quantity, itm.external_url, stemp_thumb, itm.artist_name, itm.title, itm.color, itm.size); bItemsInserted = true; } } catch (Exception ex2) { berror = true; LogError(order.external_ref, "RedBubble endpoint", ex2.Message.ToString(), order, ip); } if (berror == true) { try { if (bOrderInserted == true) { dc.sp_delete_orders_ohead(iDentity); } if (bItemsInserted == true) { dc.sp_delete_orders_oline(iDentity); } } catch {} throw new System.ServiceModel.Web.WebFaultException(HttpStatusCode.InternalServerError); } else { iRefId = order.external_ref; sref = iDentity.ToString(); } try { order = null; } catch { } } else { throw new System.ServiceModel.Web.WebFaultException(HttpStatusCode.InternalServerError); } } //end try catch (Exception ex) { try { sref = ex.Message; if (bOrderInserted == true) { dc.sp_delete_orders_ohead(iDentity); } if (bItemsInserted == true) { dc.sp_delete_orders_oline(iDentity); } using (var dc2 = new stylusDataContext()) { dc2.sp_insert_orders_error_log(order.external_ref, "RedBubble endpoint", ex.Message.ToString(), ip); } } catch {} throw new System.ServiceModel.Web.WebFaultException(HttpStatusCode.InternalServerError); } }//end using var resp2 = new oCreateOrderResponse(); resp2.id = iRefId; resp2.sref = sref; return(resp2); }
protected string GetRequestingIpAddress() { RemoteEndpointMessageProperty endPointProperty = (RemoteEndpointMessageProperty)OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name]; return(endPointProperty.Address); }
public ConvertResponseMessage Convert(MessageContracts.Converter.V1.ConvertMessage message) { Guid requestId = Guid.NewGuid(); if (this.logger != null) { RemoteEndpointMessageProperty endpointProperty = OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; RequestLog requestLog = new RequestLog { RequestId = requestId, RequestDateUtc = DateTime.UtcNow, SenderIp = endpointProperty.Address, FileExtension = message.FileExtension, FileSize = message.FileBytes.Length, CustomAttributes = message.CustomAttributes?.ToDictionary(p => p.Name, p => p.Value) }; this.logger.LogRequest(requestLog); } byte[] fileBytes = null; Exception convertException = null; try { fileBytes = this.converter.Convert(message.FileBytes, message.FileExtension); } catch (Exception e) { convertException = e; } if (this.logger != null) { ResponseLog responseLog = new ResponseLog { RequestId = requestId, ResponseDateUtc = DateTime.UtcNow, ResultFileSize = fileBytes?.Length, ErrorType = convertException.ToConvertErrorType() }; this.logger.LogResponse(responseLog); } if (convertException == null) { return(new ConvertResponseMessage { RequestId = requestId, FileBytes = fileBytes }); } else { FaultException fault; try { fault = convertException.ToV1FaultConverter(); } catch (NotSupportedException) { throw convertException; } throw fault; } }
/// <summary> /// 调用方法前 输出参数值 /// </summary> /// <param name="operationName"></param> /// <param name="inputs"></param> /// <returns></returns> public object BeforeCall(string operationName, object[] inputs) { String guid = Guid.NewGuid().ToString(); try { if (WcfBeforeCallEvent != null) { OperationContext context = OperationContext.Current; string AbsolutePath = ""; if (context != null) { //获取传递的自定义消息头 HeaderContext headercontext = HeaderOperater.GetServiceWcfHeader(context); string wcfappname = HeaderOperater.GetServiceWcfAppNameHeader(context); wcfappname = wcfappname == null ? "" : wcfappname; if (headercontext != null) { guid = headercontext.CorrelationState; } //获取客户端请求的路径 AbsolutePath = context.EndpointDispatcher.EndpointAddress.Uri.AbsolutePath; //获取客户端ip和端口 MessageProperties properties = context.IncomingMessageProperties; RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; string client_ip = endpoint.Address; //int client_port = endpoint.Port; if (!AbsolutePath.Contains("Com/FrameWork/Helper/Wcf")) { Hashtable ht = new Hashtable(); ht.Add("ip", client_ip + "_" + wcfappname); ht.Add("url", AbsolutePath); ht.Add("operatename", operationName); //MonitorData.Instance.UpdateOperateNums(client_ip, AbsolutePath, operationName); Thread th = new Thread(new ParameterizedThreadStart(Run)); th.Start(ht); } } WcfBeforeCallEvent(operationName, inputs, AbsolutePath, guid); #region //Console.WriteLine("返回操作开始:" + AbsolutePath + "/" + operationName); //Console.WriteLine("*************调用操作编号:" + guid.ToString() + "**************"); //for (int i = 0; i < inputs.Length; i++) //{ // Type T = inputs[i].GetType(); // Console.WriteLine("操作参数" + i.ToString() + " 类型为:" + T.ToString()); // Console.WriteLine("操作参数" + i.ToString() + " ToString为:" + inputs[i].ToString()); // Console.WriteLine("操作参数" + i.ToString() + " 属性:"); // PropertyInfo[] PIs = T.GetProperties(); // foreach (PropertyInfo PI in PIs) // { // Console.Write(PI.Name + ":"); // Console.WriteLine(PI.GetValue(inputs[i], null)); // } //} #endregion } } catch { } return(guid); }
/// <summary> 登陆验证 /// </summary> /// <param name="str"></param> /// <returns></returns> public string LoginIn(string str) { RespFunStruct resp = new RespFunStruct(); try { string loginStr = HXCCommon.DotNetEncrypt.DESEncrypt.Decrypt(str); LoginInput loginObj = Newtonsoft.Json.JsonConvert.DeserializeObject <LoginInput>(loginStr); if (string.IsNullOrEmpty(loginObj.acccode)) { resp.IsSuccess = "0"; resp.Msg = "帐套不能为空"; } else { SetDbName(loginObj.acccode, false); string tempUserID = BLL.DBHelper.GetSingleValue("验证用户是否存在", GlobalStaticObj_Server.Instance.CurrAccDbName, "sys_user", "user_id", " land_name='" + loginObj.username + "'", ""); if (string.IsNullOrEmpty(tempUserID)) { resp.IsSuccess = "0"; resp.Msg = "登录用户不存在"; } //else if (LoginSessionInfo.Instance.dicLoginInfos.ContainsKey(tempUserID)) //{ // resp.IsSuccess = "0"; // resp.Msg = "该用户已在其他电脑登录"; //} else { OperationContext context = OperationContext.Current; //获取传进的消息属性 MessageProperties properties = context.IncomingMessageProperties; //获取消息发送的远程终结点IP和端口 RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; string IPStr = endpoint.Address + ":" + endpoint.Port.ToString(); DataSet ds = BLL.ClientUser.UserLogin(loginObj, IPStr, GlobalStaticObj_Server.Instance.CurrAccDbName); if (ds == null || ds.Tables.Count == 0 || (ds.Tables.Count == 1 && ds.Tables[0].Rows.Count == 0)) { resp.IsSuccess = "0"; resp.Msg = "登录密码错误"; } else { string userID = ds.Tables[0].Rows[0][0].ToString(); //将登陆id及cookie信息加入到缓存中 string cookieStr = LoginSessionInfo.Instance.LoginIn(userID);; DataTable dt = new DataTable("cookieStr"); DataColumn dc = new DataColumn("cookieStr", typeof(string)); dt.Columns.Add(dc); DataRow dr = dt.NewRow(); dr["cookieStr"] = cookieStr; dt.Rows.Add(dr); ds.Tables.Add(dt); resp.IsSuccess = "1"; resp.ReturnObject = JsonConvert.SerializeObject(ds); } } } } catch (Exception ex) { resp.IsSuccess = "0"; resp.Msg = "登陆失败:" + ex.Message; Utility.Log.Log.writeLineToLog("【登陆验证】" + ex.Message, "wcf服务"); } return(HXCCommon.DotNetEncrypt.DESEncrypt.Encrypt(Newtonsoft.Json.JsonConvert.SerializeObject(resp))); }
//Implements #region # 登录 —— LoginInfo Login(string loginId, string password) /// <summary> /// 登录 /// </summary> /// <param name="loginId">登录名</param> /// <param name="password">密码</param> /// <returns>登录信息</returns> public LoginInfo Login(string loginId, string password) { #region # 验证参数 if (string.IsNullOrWhiteSpace(loginId)) { throw new ArgumentNullException(nameof(loginId), "用户名不可为空!"); } if (string.IsNullOrWhiteSpace(password)) { throw new ArgumentNullException(nameof(password), "密码不可为空!"); } #endregion lock (_Sync) { /****************验证机器****************/ this.AuthenticateMachine(); /****************登录验证****************/ User currentUser = this._repMediator.UserRep.SingleOrDefault(loginId); #region # 验证 if (currentUser == null) { throw new InvalidOperationException($"用户名\"{loginId}\"不存在!"); } if (!currentUser.Enabled) { throw new InvalidOperationException("用户已停用!"); } if (currentUser.Password != password.ToMD5()) { throw new InvalidOperationException("登录失败,密码错误!"); } #endregion //生成公钥 Guid publicKey = Guid.NewGuid(); //生成登录信息 LoginInfo loginInfo = new LoginInfo(currentUser.Number, currentUser.Name, publicKey); #region # 登录信息的信息系统部分/菜单部分/权限部分 ICollection <Guid> roleIds = this._repMediator.RoleRep.FindIds(loginId, null); /*信息系统部分*/ IEnumerable <string> systemNos = currentUser.GetInfoSystemNos(); IDictionary <string, InfoSystem> systems = this._repMediator.InfoSystemRep.Find(systemNos); loginInfo.LoginSystemInfos.AddRange(systems.Values.Select(x => x.ToLoginSystemInfo())); /*菜单部分*/ IEnumerable <Guid> authorityIds = this._repMediator.AuthorityRep.FindIdsByRole(roleIds); IEnumerable <Menu> menus = this._repMediator.MenuRep.FindByAuthority(authorityIds, null); menus = menus.TailRecurseParentNodes(); ICollection <LoginMenuInfo> menuTree = menus.ToTree(null); loginInfo.LoginMenuInfos.AddRange(menuTree); /*权限部分*/ IEnumerable <Authority> authorities = this._repMediator.AuthorityRep.FindByRole(roleIds); loginInfo.LoginAuthorityInfos = authorities.GroupBy(x => x.SystemNo).ToDictionary(x => x.Key, x => x.Select(y => y.ToLoginAuthorityInfo()).ToArray()); #endregion //以公钥为键,登录信息为值,存入分布式缓存 CacheMediator.Set(publicKey.ToString(), loginInfo, DateTime.Now.AddMinutes(_Timeout)); //获取客户端IP MessageProperties properties = OperationContext.Current.IncomingMessageProperties; string ip = "localhost"; if (properties.ContainsKey(RemoteEndpointMessageProperty.Name)) { RemoteEndpointMessageProperty endpoint = (RemoteEndpointMessageProperty)properties[RemoteEndpointMessageProperty.Name]; ip = endpoint.Address; } //生成登录记录 this.GenerateLoginRecord(publicKey, ip, currentUser.Number, currentUser.Name); return(loginInfo); } }
public EntitySysLogin Login(string LoginID, string PassWord, int confirmFlg) { CommonUtl.ExLogger.Info(CLASS_NM + ".Login"); CommonUtl.ExLogger.Info(CommonUtl.gConnectionString1); #region Field EntitySysLogin entity = null; int userId = 0; string userNm = ""; int companyId = 0; string companyNm = ""; int groupId = 0; string groupNm = ""; int personId = 0; string personNm = ""; int beforeUserId = 0; string accountBeginPeriod = ""; string accountEndPeriod = ""; string databaseString = ""; string databaseProvider = ""; string groupDisplayNm = ""; int evidenceSaveFlg = 0; int invoicePrintFlg = 0; int idFigureSlipNo = 10; int idFigureCustomer = 10; int idFigurePurchase = 10; int idFigureGoods = 10; int estimateApprovalFlg = 1; int reportSizeUser = 0; int reportSizeAll = 0; int demoFlg = 0; string sysVer = ""; string message = ""; ExMySQLData sysdb = null; ExMySQLData db; StringBuilder sb; DataTable dt; #endregion #region ログインID、パスワードチェック try { // sb = new StringBuilder(); sb.Append("SELECT UR.* " + Environment.NewLine); sb.Append(" ,CP.NAME AS COMPANY_NAME " + Environment.NewLine); sb.Append(" ,GP.NAME AS GROUP_NAME " + Environment.NewLine); sb.Append(" ,GP.ESTIMATE_APPROVAL_FLG " + Environment.NewLine); sb.Append(" ,GP.INVOICE_PRINT_FLG " + Environment.NewLine); sb.Append(" FROM SYS_M_USER AS UR" + Environment.NewLine); sb.Append(" LEFT JOIN SYS_M_COMPANY AS CP" + Environment.NewLine); sb.Append(" ON UR.COMPANY_ID = CP.ID " + Environment.NewLine); sb.Append(" AND CP.DELETE_FLG = 0 " + Environment.NewLine); sb.Append(" AND CP.DISPLAY_FLG = 1 " + Environment.NewLine); sb.Append(" LEFT JOIN SYS_M_COMPANY_GROUP AS GP" + Environment.NewLine); sb.Append(" ON UR.GROUP_ID = GP.ID " + Environment.NewLine); sb.Append(" AND GP.DELETE_FLG = 0 " + Environment.NewLine); sb.Append(" AND GP.DISPLAY_FLG = 1 " + Environment.NewLine); sb.Append(" WHERE UR.DELETE_FLG = 0 " + Environment.NewLine); sb.Append(" AND UR.LOGIN_ID = " + ExEscape.zRepStr(LoginID) + Environment.NewLine); sb.Append(" AND UR.PASSWORD = "******"ID"]); userNm = ExCast.zCStr(dt.DefaultView[0]["NAME"]); companyId = ExCast.zCInt(dt.DefaultView[0]["COMPANY_ID"]); companyNm = ExCast.zCStr(dt.DefaultView[0]["COMPANY_NAME"]); groupId = ExCast.zCInt(dt.DefaultView[0]["GROUP_ID"]); groupNm = ExCast.zCStr(dt.DefaultView[0]["GROUP_NAME"]); personId = ExCast.zCInt(dt.DefaultView[0]["PERSON_ID"]); estimateApprovalFlg = ExCast.zCInt(dt.DefaultView[0]["ESTIMATE_APPROVAL_FLG"]); invoicePrintFlg = ExCast.zCInt(dt.DefaultView[0]["INVOICE_PRINT_FLG"]); // 前回セッションIDの保持 beforeUserId = ExCast.zCInt(HttpContext.Current.Session[ExSession.USER_ID]); } else { entity = new EntitySysLogin((int)EntitySysLogin.geLoginReturn.Failure, // Return CD "ログインID、または、パスワードが不正です。"); // Return Message return(entity); } } catch (Exception ex) { CommonUtl.ExLogger.Error(CLASS_NM + ".Login(ID,Pass Check)", ex); entity = new EntitySysLogin((int)EntitySysLogin.geLoginReturn.Error, // Return CD "ログイン処理でエラーが発生しました。" + Environment.NewLine + "システム管理者へ報告して下さい。" + Environment.NewLine + ex.ToString()); // Return Message return(entity); } #endregion #region 前回ログインチェック try { // 前回ログイン有り if (ExCast.zCStr(HttpContext.Current.Session[ExSession.USER_ID]) != "") { // 前回ログインと同じ if (ExCast.zCInt(HttpContext.Current.Session[ExSession.USER_ID]) == userId) { if (CommonUtl.gDemoKbn == 1) { // 再ログインとして返す entity = new EntitySysLogin((int)EntitySysLogin.geLoginReturn.Again, // Return CD ""); // Return Message return(entity); } // 同一セッションが存在しているか確認 if (ExSession.ExistsSessionInf(userId, ExCast.zCStr(HttpContext.Current.Session[ExSession.SESSION_RANDOM_STR]), ref message) == true) { // 再ログインとして返す entity = new EntitySysLogin((int)EntitySysLogin.geLoginReturn.Again, // Return CD ""); // Return Message return(entity); } else { // 違うセッションパラメータが設定されていた場合、削除 ExSession.DelSessionInf(userId); } } //// 前回ログインと別 //else //{ // // 一旦ログオフする // if (pvtLogoff(ExCast.zCStr(HttpContext.Current.Session[ExSession.IP_ADRESS]), // ExCast.zCStr(HttpContext.Current.Session[ExSession.USER_ID]), // ExCast.zCStr(HttpContext.Current.Session[ExSession.SESSION_RANDOM_STR]), // ExCast.zCStr(HttpContext.Current.Session[ExSession.PERSON_ID])) == false) // { // entity = new EntitySysLogin((int)EntitySysLogin.geLoginReturn.Error, // Return CD // "ログオフ処理に失敗しました。" + Environment.NewLine + // "システム管理者へ報告して下さい。" + CommonUtl.gstrErrMsg); // Return Message // } //} } } catch (Exception ex) { CommonUtl.ExLogger.Error(CLASS_NM + ".Login(Before Login Check)", ex); entity = new EntitySysLogin((int)EntitySysLogin.geLoginReturn.Error, // Return CD "前回ログインチェック処理でエラーが発生しました。" + Environment.NewLine + "システム管理者へ報告して下さい。" + Environment.NewLine + ex.ToString()); // Return Message return(entity); } #endregion #region システム設定取得 try { sb.Length = 0; sb.Append("SELECT ST.*" + Environment.NewLine); sb.Append(" FROM SYS_M_SETTING AS ST" + Environment.NewLine); sb.Append(" WHERE ST.DELETE_FLG = 0 " + Environment.NewLine); sb.Append(" AND ST.DISPLAY_FLG = 1 " + Environment.NewLine); sb.Append(" AND ST.COMPANY_ID = " + companyId.ToString() + Environment.NewLine); dt = CommonUtl.gMySqlDt.GetDataTable(sb.ToString()); if (dt.DefaultView.Count > 0) { accountBeginPeriod = ExCast.zCStr(dt.DefaultView[0]["ACCOUNT_BEGIN_PERIOD"]); accountEndPeriod = ExCast.zCStr(dt.DefaultView[0]["ACCOUNT_END_PERIOD"]); databaseString = ExCast.zCStr(dt.DefaultView[0]["DATABESE_SETTING"]); databaseProvider = ExCast.zCStr(dt.DefaultView[0]["DATABESE_PROVIDER"]); groupDisplayNm = ExCast.zCStr(dt.DefaultView[0]["GROUP_DISPLAY_NAME"]); evidenceSaveFlg = ExCast.zCInt(dt.DefaultView[0]["EVIDENCE_SAVE_FLG"]); idFigureSlipNo = ExCast.zCInt(dt.DefaultView[0]["ID_FIGURE_SLIP_NO"]); idFigureCustomer = ExCast.zCInt(dt.DefaultView[0]["ID_FIGURE_CUSTOMER"]); idFigurePurchase = ExCast.zCInt(dt.DefaultView[0]["ID_FIGURE_PURCHASE"]); idFigureGoods = ExCast.zCInt(dt.DefaultView[0]["ID_FIGURE_GOODS"]); reportSizeUser = ExCast.zCInt(dt.DefaultView[0]["REPORT_SAVE_SIZE_USER"]); reportSizeAll = ExCast.zCInt(dt.DefaultView[0]["REPORT_SAVE_SIZE_ALL"]); demoFlg = ExCast.zCInt(dt.DefaultView[0]["DEMO_FLG"]); sysVer = ExCast.zCStr(dt.DefaultView[0]["SYSTEM_VER"]); } else { entity = new EntitySysLogin((int)EntitySysLogin.geLoginReturn.Failure, // Return CD "システム設定データが存在しません。" + Environment.NewLine + "システム管理者へ報告して下さい。"); // Return Message return(entity); } } catch (Exception ex) { CommonUtl.ExLogger.Error(CLASS_NM + ".Login(Get System Setting)", ex); entity = new EntitySysLogin((int)EntitySysLogin.geLoginReturn.Error, // Return CD "システム設定の取得処理でエラーが発生しました。" + Environment.NewLine + "システム管理者へ報告して下さい。" + Environment.NewLine + ex.ToString()); // Return Message return(entity); } #endregion #region 別データベース接続確認 try { db = new ExMySQLData(databaseString); db.DbOpen(); } catch (Exception ex) { CommonUtl.ExLogger.Error(CLASS_NM + ".Login(DB Connect)", ex); entity = new EntitySysLogin((int)EntitySysLogin.geLoginReturn.Error, // Return CD "個別データベースの接続に失敗しました。" + Environment.NewLine + "システム管理者へ報告して下さい。" + Environment.NewLine + ex.Message); // Return Message return(entity); } #endregion #region 担当者名取得 try { sb.Length = 0; sb.Append("SELECT PS.* " + Environment.NewLine); sb.Append(" FROM M_PERSON AS PS" + Environment.NewLine); sb.Append(" WHERE PS.COMPANY_ID = " + companyId.ToString() + Environment.NewLine); sb.Append(" AND PS.ID = " + personId.ToString() + Environment.NewLine); sb.Append(" AND PS.DELETE_FLG = 0" + Environment.NewLine); sb.Append(" AND PS.DISPLAY_FLG = 1" + Environment.NewLine); dt = CommonUtl.gMySqlDt.GetDataTable(sb.ToString()); if (dt.DefaultView.Count > 0) { personNm = ExCast.zCStr(dt.DefaultView[0]["NAME"]); } } catch (Exception ex) { CommonUtl.ExLogger.Error(CLASS_NM + ".Login(Get Person)", ex); entity = new EntitySysLogin((int)EntitySysLogin.geLoginReturn.Error, // Return CD "担当者名の取得処理でエラーが発生しました。" + Environment.NewLine + "システム管理者へ報告して下さい。" + Environment.NewLine + ex.ToString()); // Return Message return(entity); } #endregion #region ログイン履歴登録情報設定 string random = ""; string ipAdress = ""; string date = ""; string time = ""; try { //ランダム文字列取得 random = ExRandomString.GetRandomString(); // IP取得 OperationContext context = OperationContext.Current; MessageProperties properties = context.IncomingMessageProperties; RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; ipAdress = endpoint.Address.ToString(); // 日時取得 DateTime now = DateTime.Now; date = now.ToString("yyyy/MM/dd"); time = now.ToString("HH:mm:ss"); } catch (Exception ex) { CommonUtl.ExLogger.Error(CLASS_NM + ".Login(Get History Inf)", ex); entity = new EntitySysLogin((int)EntitySysLogin.geLoginReturn.Error, // Return CD "ログイン履歴情報の設定に失敗しました。" + Environment.NewLine + "システム管理者へ報告して下さい。" + Environment.NewLine + ex.ToString()); // Return Message return(entity); } #endregion #region セッション情報設定 try { if (ExSession.AddSessionInf(userId, random, db, ref message) == false) { entity = new EntitySysLogin((int)EntitySysLogin.geLoginReturn.Warmn, // Return CD "セッション情報の設定に失敗しました。" + Environment.NewLine + "システム管理者へ報告して下さい。" + Environment.NewLine + message); // Return Message } } catch (Exception ex) { CommonUtl.ExLogger.Error(CLASS_NM + ".Login(Set Session Inf)", ex); entity = new EntitySysLogin((int)EntitySysLogin.geLoginReturn.Error, // Return CD "セッション情報の設定に失敗しました。" + Environment.NewLine + "システム管理者へ報告して下さい。" + Environment.NewLine + ex.ToString()); // Return Message return(entity); } #endregion if (confirmFlg == 1) { #region ログオフ処理 try { // 前回ログイン有り if (ExCast.zCStr(HttpContext.Current.Session[ExSession.USER_ID]) != "") { // 前回セッションとログインIDが違う場合 if (ExCast.zCInt(HttpContext.Current.Session[ExSession.USER_ID]) != userId) { // ログオフする if (pvtLogoff(ExCast.zCStr(HttpContext.Current.Session[ExSession.IP_ADRESS]), ExCast.zCStr(HttpContext.Current.Session[ExSession.USER_ID]), ExCast.zCStr(HttpContext.Current.Session[ExSession.SESSION_RANDOM_STR]), ExCast.zCStr(HttpContext.Current.Session[ExSession.PERSON_ID])) == false) { entity = new EntitySysLogin((int)EntitySysLogin.geLoginReturn.Error, // Return CD "ログオフ処理に失敗しました。" + Environment.NewLine + "システム管理者へ報告して下さい。" + CommonUtl.gstrErrMsg); // Return Message return(entity); } } } } catch (Exception ex) { CommonUtl.ExLogger.Error(CLASS_NM + ".Login(Logoff)", ex); entity = new EntitySysLogin((int)EntitySysLogin.geLoginReturn.Error, // Return CD "ログオフに失敗しました。" + Environment.NewLine + "システム管理者へ報告して下さい。" + Environment.NewLine + ex.ToString()); // Return Message return(entity); } #endregion #region ログイン履歴登録 try { #region System Databese Open try { sysdb = new ExMySQLData(); sysdb.DbOpen(); } catch (Exception ex) { CommonUtl.ExLogger.Error(CLASS_NM + ".Login(DbOpen)", ex); entity = new EntitySysLogin((int)EntitySysLogin.geLoginReturn.Error, // Return CD "ログイン履歴の登録に失敗しました。(DbOpen)" + Environment.NewLine + "システム管理者へ報告して下さい。" + Environment.NewLine + ex.ToString()); // Return Message return(entity); } #endregion #region BeginTransaction try { sysdb.ExBeginTransaction(); } catch (Exception ex) { sysdb.ExRollbackTransaction(); CommonUtl.ExLogger.Error(CLASS_NM + ".Login(BeginTransaction)", ex); entity = new EntitySysLogin((int)EntitySysLogin.geLoginReturn.Error, // Return CD "ログイン履歴の登録に失敗しました。(BeginTransaction)" + Environment.NewLine + "システム管理者へ報告して下さい。" + Environment.NewLine + ex.ToString()); // Return Message return(entity); } #endregion #region Insert sb.Length = 0; sb.Append("INSERT INTO SYS_H_USER_LOGIN_HISTORY " + Environment.NewLine); sb.Append(" (USER_ID" + Environment.NewLine); sb.Append(" ,LOGIN_DIVISION" + Environment.NewLine); sb.Append(" ,LOGIN_DATE" + Environment.NewLine); sb.Append(" ,LOGIN_TIME" + Environment.NewLine); sb.Append(" ,SESSION_STRING" + Environment.NewLine); sb.Append(" ,IP_ADRESS" + Environment.NewLine); sb.Append(" ,UPDATE_FLG" + Environment.NewLine); sb.Append(" ,DELETE_FLG" + Environment.NewLine); sb.Append(" ,CREATE_PG_ID" + Environment.NewLine); sb.Append(" ,CREATE_ADRESS" + Environment.NewLine); sb.Append(" ,CREATE_USER_ID" + Environment.NewLine); sb.Append(" ,CREATE_PERSON_ID" + Environment.NewLine); sb.Append(" ,CREATE_DATE" + Environment.NewLine); sb.Append(" ,CREATE_TIME" + Environment.NewLine); sb.Append(" ,UPDATE_PG_ID" + Environment.NewLine); sb.Append(" ,UPDATE_ADRESS" + Environment.NewLine); sb.Append(" ,UPDATE_USER_ID" + Environment.NewLine); sb.Append(" ,UPDATE_PERSON_ID" + Environment.NewLine); sb.Append(" ,UPDATE_DATE" + Environment.NewLine); sb.Append(" ,UPDATE_TIME" + Environment.NewLine); sb.Append(")" + Environment.NewLine); sb.Append("VALUES (" + userId + Environment.NewLine); // USER_ID sb.Append(" ,1" + Environment.NewLine); // LOGIN_DIVISION sb.Append(" ," + ExEscape.zRepStr(date) + Environment.NewLine); // LOGIN_DATE sb.Append(" ," + ExEscape.zRepStr(time) + Environment.NewLine); // LOGIN_TIME sb.Append(" ," + ExEscape.zRepStr(random) + Environment.NewLine); // SESSION_STRING sb.Append(" ," + ExEscape.zRepStr(ipAdress) + Environment.NewLine); // IP_ADRESS sb.Append(CommonUtl.GetInsSQLCommonColums(CommonUtl.UpdKbn.Ins, "SYSTEM", "", ExCast.zCInt(personId), "0", ExCast.zCStr(ipAdress), ExCast.zCStr(userId))); sb.Append(")"); sysdb.ExecuteSQL(sb.ToString(), false); #endregion #region CommitTransaction try { sysdb.ExCommitTransaction(); } catch (Exception ex) { CommonUtl.gMySqlDt.ExRollbackTransaction(); CommonUtl.ExLogger.Error(CLASS_NM + ".Login(CommitTransaction)", ex); entity = new EntitySysLogin((int)EntitySysLogin.geLoginReturn.Error, // Return CD "ログイン履歴の登録に失敗しました。(BeginTransaction)" + Environment.NewLine + "システム管理者へ報告して下さい。" + Environment.NewLine + ex.ToString()); // Return Message return(entity); } #endregion #region System Database Close try { sysdb.DbClose(); } catch (Exception ex) { sysdb.ExRollbackTransaction(); CommonUtl.ExLogger.Error(CLASS_NM + ".Login(DbClose)", ex); entity = new EntitySysLogin((int)EntitySysLogin.geLoginReturn.Error, // Return CD "ログイン履歴の登録に失敗しました。(DbClose)" + Environment.NewLine + "システム管理者へ報告して下さい。" + Environment.NewLine + ex.ToString()); // Return Message return(entity); } finally { sysdb = null; } #endregion #region セッションの保持 // セッションの保持 HttpContext.Current.Session[ExSession.COMPANY_ID] = companyId; HttpContext.Current.Session[ExSession.GROUP_ID] = groupId; HttpContext.Current.Session[ExSession.USER_ID] = userId; HttpContext.Current.Session[ExSession.USER_NM] = userNm; HttpContext.Current.Session[ExSession.PERSON_ID] = personId; HttpContext.Current.Session[ExSession.DEFAULT_PERSON_ID] = personId; HttpContext.Current.Session[ExSession.SESSION_RANDOM_STR] = random; HttpContext.Current.Session[ExSession.IP_ADRESS] = ipAdress; HttpContext.Current.Session[ExSession.DB_CONNECTION_STR] = databaseString; HttpContext.Current.Session[ExSession.DATA_CLASS] = db; HttpContext.Current.Session[ExSession.EVIDENCE_SAVE_FLG] = evidenceSaveFlg; HttpContext.Current.Session[ExSession.ACCOUNT_BEGIN_PERIOD] = accountBeginPeriod; HttpContext.Current.Session[ExSession.ACCOUNT_END_PERIOD] = accountEndPeriod; HttpContext.Current.Session[ExSession.ID_FIGURE_SLIP_NO] = idFigureSlipNo; HttpContext.Current.Session[ExSession.ID_FIGURE_CUSTOMER] = idFigureCustomer; HttpContext.Current.Session[ExSession.ID_FIGURE_PURCHASE] = idFigurePurchase; HttpContext.Current.Session[ExSession.ID_FIGURE_GOODS] = idFigureGoods; HttpContext.Current.Session[ExSession.REPORT_SAVE_SIZE_USER] = reportSizeUser; HttpContext.Current.Session[ExSession.REPORT_SAVE_SIZE_ALL] = reportSizeAll; HttpContext.Current.Session[ExSession.GROUP_DISPLAY_NAME] = groupDisplayNm; HttpContext.Current.Session[ExSession.ESTIMATE_APPROVAL_FLG] = estimateApprovalFlg; HttpContext.Current.Session[ExSession.RECEIPT_ACCOUNT_INVOICE_PRINT_FLG] = invoicePrintFlg; #endregion } catch (Exception ex) { sysdb.ExRollbackTransaction(); CommonUtl.ExLogger.Error(CLASS_NM + ".Login(Add History)", ex); entity = new EntitySysLogin((int)EntitySysLogin.geLoginReturn.Error, // Return CD "ログイン履歴の登録に失敗しました。" + Environment.NewLine + "システム管理者へ報告して下さい。" + Environment.NewLine + ex.ToString()); // Return Message return(entity); } #endregion } else { #region セッションの保持 // セッションの保持 HttpContext.Current.Session[ExSession.COMPANY_ID] = companyId; HttpContext.Current.Session[ExSession.GROUP_ID] = groupId; HttpContext.Current.Session[ExSession.USER_ID] = userId; HttpContext.Current.Session[ExSession.USER_NM] = userNm; HttpContext.Current.Session[ExSession.PERSON_ID] = personId; HttpContext.Current.Session[ExSession.DEFAULT_PERSON_ID] = personId; HttpContext.Current.Session[ExSession.SESSION_RANDOM_STR] = random; HttpContext.Current.Session[ExSession.IP_ADRESS] = ipAdress; HttpContext.Current.Session[ExSession.DB_CONNECTION_STR] = databaseString; HttpContext.Current.Session[ExSession.DATA_CLASS] = db; HttpContext.Current.Session[ExSession.EVIDENCE_SAVE_FLG] = evidenceSaveFlg; HttpContext.Current.Session[ExSession.ACCOUNT_BEGIN_PERIOD] = accountBeginPeriod; HttpContext.Current.Session[ExSession.ACCOUNT_END_PERIOD] = accountEndPeriod; HttpContext.Current.Session[ExSession.ID_FIGURE_SLIP_NO] = idFigureSlipNo; HttpContext.Current.Session[ExSession.ID_FIGURE_CUSTOMER] = idFigureCustomer; HttpContext.Current.Session[ExSession.ID_FIGURE_PURCHASE] = idFigurePurchase; HttpContext.Current.Session[ExSession.ID_FIGURE_GOODS] = idFigureGoods; HttpContext.Current.Session[ExSession.REPORT_SAVE_SIZE_USER] = reportSizeUser; HttpContext.Current.Session[ExSession.REPORT_SAVE_SIZE_ALL] = reportSizeAll; HttpContext.Current.Session[ExSession.GROUP_DISPLAY_NAME] = groupDisplayNm; HttpContext.Current.Session[ExSession.ESTIMATE_APPROVAL_FLG] = estimateApprovalFlg; HttpContext.Current.Session[ExSession.RECEIPT_ACCOUNT_INVOICE_PRINT_FLG] = invoicePrintFlg; #endregion } entity = new EntitySysLogin((int)EntitySysLogin.geLoginReturn.Normal, // Return CD "", // Return Message companyId, // Company ID companyNm, // Company Name groupId, // Group ID groupNm, // Group Name personId, // Default Person ID personNm, // Default Person Name groupDisplayNm, // Group Display Name evidenceSaveFlg, // Evidence Flg idFigureSlipNo, // idFigureCustomer, // idFigurePurchase, // idFigureGoods, // random); // Session String entity.user_id = userId; entity.user_nm = userNm; entity.estimate_approval_flg = estimateApprovalFlg; entity.receipt_account_invoice_print_flg = invoicePrintFlg; entity.demo_flg = demoFlg; entity.sys_ver = sysVer; return(entity); }
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { StringBuilder sb = new StringBuilder(); string guid = Guid.NewGuid().ToString(); sb.AppendFormat("请求标识:{0},调用前日志", guid).AppendLine(); try { Uri requestUri = request.Headers.To; sb.AppendFormat("请求地址:{0}", requestUri).AppendLine(); OperationContext context = OperationContext.Current; MessageProperties prop = context.IncomingMessageProperties; RemoteEndpointMessageProperty endpoint = prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; if (endpoint != null) { sb.AppendFormat("请求IP:{0}", endpoint.Address).AppendLine(); } HttpRequestMessageProperty httpReq = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name]; sb.AppendFormat("请求方式:{0}", httpReq.Method).AppendLine(); sb.AppendLine("请求Headers:"); foreach (string header in httpReq.Headers.AllKeys) { if (string.IsNullOrEmpty(header)) { continue; } if (header.ToLower() == "cookie") { continue; } sb.AppendFormat("{0}:{1}", header, httpReq.Headers[header]).AppendLine(); } MessageHeaders incomingMessageHeaders = OperationContext.Current.IncomingMessageHeaders; string currentActionName = incomingMessageHeaders.Action; if (string.IsNullOrEmpty(currentActionName)) { currentActionName = incomingMessageHeaders.To.Segments[incomingMessageHeaders.To.Segments.Length - 1]; } SynchronizedKeyedCollection <string, DispatchOperation> operations = OperationContext.Current.EndpointDispatcher.DispatchRuntime.Operations; DispatchOperation operation = operations.FirstOrDefault(d => d.Name == currentActionName); if (operation != null) { string actionName = OperationContext.Current.IncomingMessageProperties["HttpOperationName"] as string; Type hostType = OperationContext.Current.Host.Description.ServiceType; sb.AppendFormat("请求类:{0}", hostType.FullName).AppendLine(); sb.AppendFormat("请求方法:{0}", actionName).AppendLine(); } sb.AppendLine("请求内容:"); sb.AppendLine(this.MessageToString(ref request)); Logger.Error(sb.ToString()); } catch (Exception ex) { Logger.Error("日志记录异常:{0}", ex); } return(guid); }
} // end AfterReceiveRequest /// <summary> /// service traffic outbound response /// </summary> /// <param name="reply"></param> /// <param name="correlationState"></param> public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState) { // object prop; // string requestHeader = null; //Console.WriteLine("In {0}", MethodBase.GetCurrentMethod().Name); WCFContainer w = null; try { try { w = (WCFContainer)correlationState; } catch (Exception ex) { Logger.debug(ex, "can't get reference to the correlation object"); } if (w == null) { Logger.debug("can't get reference to the correlation object"); return; } /****************************** * BEGIN, do not remove this code, there's some kind of strange bug in wcf that causes services using this handler to hang after 10 invocations * unless this code is execute. I believe it's related to obtaining http headers */ /* * if (OperationContext.Current.IncomingMessageProperties.TryGetValue(HttpRequestMessageProperty.Name, out prop)) * { * HttpRequestMessageProperty reqProp = (HttpRequestMessageProperty)prop; * requestHeader = reqProp.Headers["X-MyHeader"]; * // Console.WriteLine("Got the request header: {0}", requestHeader); * } * * if (!OperationContext.Current.OutgoingMessageProperties.TryGetValue(HttpResponseMessageProperty.Name, out prop)) * { * prop = new HttpResponseMessageProperty(); * OperationContext.Current.OutgoingMessageProperties.Add(HttpResponseMessageProperty.Name, prop); * } * HttpResponseMessageProperty respProp = (HttpResponseMessageProperty)prop; * respProp.Headers["X-MyResponseHeader2"] = "Added from BeforeSendReply - " + requestHeader; * */ /********************************** * END */ } catch (Exception ex) { Logger.debug(ex, "can't get reference to the correlation object"); } //this is usually a ?wsdl request or a null request such a get MessageProcessor ctx = MessageProcessor.Instance; try { string use = string.Empty; use = w.thisid; String action = "urn:undeterminable"; if (w.action != null) { action = w.action; action = action.Replace("\"", ""); action = action.Replace("'", ""); if (String.IsNullOrEmpty(action)) { action = "urn:undeterminable"; } } if (action.Equals("urn:undeterminable") && w.myinboundheaders != null && !String.IsNullOrEmpty(w.myinboundheaders.Headers["SOAPAction"])) // if (System.ServiceModel.OperationContext.Current.RequestContext.RequestMessage.Headers != null && // !String.IsNullOrEmpty(System.ServiceModel.OperationContext.Current.RequestContext.RequestMessage.Headers.Action)) { action = w.myinboundheaders.Headers["SOAPAction"]; //System.ServiceModel.OperationContext.Current.RequestContext.RequestMessage.Headers.Action; action = action.Replace("\"", ""); action = action.Replace("'", ""); if (String.IsNullOrEmpty(action)) { action = "urn:undeterminable"; } } if (action.Equals("urn:undeterminable") && HttpContext.Current != null) { action = HttpContext.Current.Request.Headers.Get("SOAPAction"); action = action.Replace("\"", ""); action = action.Replace("'", ""); if (String.IsNullOrEmpty(action)) { action = "urn:undeterminable"; } } if (action.Equals("urn:undeterminable") && HttpContext.Current != null) { action = HttpContext.Current.Request.HttpMethod; action = action.Replace("\"", ""); action = action.Replace("'", ""); if (String.IsNullOrEmpty(action)) { action = "urn:undeterminable"; } } string ip = string.Empty; NameValueCollection reqheaders = null; if (w.myinboundheaders != null && w.myinboundheaders.Headers != null) { reqheaders = w.myinboundheaders.Headers; } NameValueCollection resheaders = new NameValueCollection(); if (HttpContext.Current != null) { ip = HttpContext.Current.Request.UserHostAddress; resheaders = HttpContext.Current.Response.Headers; reqheaders = HttpContext.Current.Request.Headers; } else { if (OperationContext.Current != null) { try { MessageProperties messageProperties = OperationContext.Current.IncomingMessageProperties; if (w.myinboundheaders == null) { w.myinboundheaders = messageProperties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty; } RemoteEndpointMessageProperty endpointProperty = messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; ip = endpointProperty.Address; } catch (Exception ex) { Logger.debug(ex); } if (w.myinboundheaders != null) { if (action.Equals("urn:undeterminable")) { action = w.myinboundheaders.Method + w.myinboundheaders.QueryString; } if (w.myinboundheaders.Headers != null) { reqheaders = w.myinboundheaders.Headers; } } } } if (ip == "127.0.0.1" || ip == "::1") { try { string myHost = System.Net.Dns.GetHostName(); System.Net.IPAddress[] list = System.Net.Dns.GetHostEntry(myHost).AddressList; for (int i = 0; i < list.Length; i++) { if (!IPAddress.IsLoopback(System.Net.Dns.GetHostEntry(myHost).AddressList[i])) { ip = System.Net.Dns.GetHostEntry(myHost).AddressList[i].ToString(); break; } } } catch (Exception ex) { Logger.debug(ex); } } string user = user = w.user; if (resheaders != null && MessageProcessor.GetConfig.DependencyInjectionEnabled) { resheaders.Add(FGSMSConstants.MessageId, use); resheaders.Add(FGSMSConstants.transactionthreadKey, w.thistid); } if (MessageProcessor.GetConfig.DependencyInjectionEnabled)// && !OperationContext.Current.OutgoingMessageProperties.TryGetValue(HttpResponseMessageProperty.Name, out prop)) { HttpResponseMessageProperty respProp = null; try { respProp = (HttpResponseMessageProperty)OperationContext.Current.OutgoingMessageProperties[HttpResponseMessageProperty.Name]; } catch { } if (respProp != null) { respProp.Headers.Add(FGSMSConstants.MessageId, use); respProp.Headers.Add(FGSMSConstants.transactionthreadKey, w.thistid); } if (reply != null && reply.Version != MessageVersion.None) { try { reply.Headers.Add(new FGSMSSoapHeaderRelatedMessageIdWCF(use)); reply.Headers.Add(new FGSMSSoapHeaderTransactionThreadIdWCF(w.thistid)); } catch { } } //else can't add response http headers! } MessageProcessor.ProcessMessage(w.url, //System.ServiceModel.OperationContext.Current.RequestContext.RequestMessage.Headers.To.ToString(), w.start, DateTime.Now, action, w.req, //System.ServiceModel.OperationContext.Current.RequestContext.RequestMessage.ToString(), MessageHelper.MessagetoString(ref reply), // reply.ToString(), use, (reply == null) ? false : reply.IsFault, HttpContext.Current, ip, this.GetType().FullName, user, "Current .net thread: " + Thread.CurrentThread.ManagedThreadId, //thread id w.thistid, //related transaction (id of the inbound message) w.relatedid, reqheaders, resheaders); } catch (Exception ex) { Logger.error(ex, this.GetType().FullName + " Error from FGSMS WCF Service Agent, BeforeSendReply. This typically means that the message traffic to the url " + w.url + " could not be added the queue: "); } try { MessageProcessor.ClearTransactionThreadId(Thread.CurrentContext.ContextID.ToString() + Thread.CurrentThread.ManagedThreadId.ToString() + ":" + Thread.GetDomainID().ToString() + Thread.CurrentThread.Name); } catch (Exception ex) { Logger.debug(ex); } } // end BeforeSendReply
public void LoginIpAddress() { //For token, email and roles are required var mockData = new MockData { Users = new List <User> { new User { id = 1, username = "******", password = "******", customer_code = "cust", email = "email", Roles = new List <Role> { new Role { id = Role.User } }, Customer = new Customer { code = "cust" } } } }; unitOfWork.Data = mockData; controller.Request = new HttpRequestMessage(); var context = new HttpContext( new HttpRequest("", "http://tempuri.org", ""), new HttpResponse(new StringWriter()) ); Mock <HttpContextWrapper> moqWrapper = new Mock <HttpContextWrapper>(context); Mock <HttpRequestBase> moqRequest = new Mock <HttpRequestBase>(); moqRequest.SetupGet(x => x.UserHostAddress).Returns("100.100"); moqWrapper.Setup(x => x.Request).Returns(moqRequest.Object); //MS_HttpContext prop controller.Request.Properties["MS_HttpContext"] = moqWrapper.Object; var result = controller.Login("username", "password"); Assert.IsNotNull(result); var user = mockData.Users.FirstOrDefault(); Assert.IsNotNull(user); Assert.IsNotNull(user.Sessions); Assert.AreEqual(1, user.Sessions.Count); Assert.AreEqual("100.100", user.Sessions[0].ip_addr); //Remoteendpoint ip user.Sessions.Clear(); controller.Request.Properties.Remove("MS_HttpContext"); RemoteEndpointMessageProperty prop = new RemoteEndpointMessageProperty("200.200", 80); controller.Request.Properties[RemoteEndpointMessageProperty.Name] = prop; result = controller.Login("username", "password"); Assert.IsNotNull(result); Assert.IsNotNull(user); Assert.IsNotNull(user.Sessions); Assert.AreEqual(1, user.Sessions.Count); Assert.AreEqual("200.200", user.Sessions[0].ip_addr); //Httpcontext current /*user.Sessions.Clear(); * controller.Request.Properties.Remove(RemoteEndpointMessageProperty.Name); * context.Request.ServerVariables.Add("REMOTE_ADDR", "300.300"); * HttpContext.Current = context; * result = controller.Login("username", "password"); * Assert.IsNotNull(result); * Assert.IsNotNull(user); * Assert.IsNotNull(user.Sessions); * Assert.AreEqual(1, user.Sessions.Count); * Assert.AreEqual("300.300", user.Sessions[0].ip_addr);*/ }
public static ErrorLogInfo CreateErrorLog(ServiceCode serviceCode, int n4ErrorCode, string strLoginID, string strErrorMessage, string strStackTrace, out int n4ErrorLogSN, out DateTime dtCreateDate) { ErrorLogCreateSPWrapper errorLogCreateSPWrapper = new ErrorLogCreateSPWrapper(); errorLogCreateSPWrapper.n4ServiceCode = serviceCode.Parse(0); errorLogCreateSPWrapper.n4ErrorCode = n4ErrorCode; errorLogCreateSPWrapper.strErrorMessage = strErrorMessage; errorLogCreateSPWrapper.strLoginID = strLoginID; errorLogCreateSPWrapper.strStackTrace = strStackTrace; errorLogCreateSPWrapper.n1PlatformCode = Platform.GetPlatformForErrorLog().Parse <byte>(0); errorLogCreateSPWrapper.strServerName = Environment.HostName; errorLogCreateSPWrapper.strServerIP = Environment.LocalIP; if (HttpContext.Current != null) { errorLogCreateSPWrapper.strDomainName = Environment.HttpHostName; errorLogCreateSPWrapper.strRequestUrl = Environment.RequestUrl; errorLogCreateSPWrapper.strClientIP = Environment.ClientIP; errorLogCreateSPWrapper.strUrlReferrer = Environment.ReferrerUrl; StringBuilder stringBuilder = new StringBuilder(); string arg = HttpContext.Current.Request.ServerVariables["ALL_HTTP"]; string httpMethod = HttpContext.Current.Request.HttpMethod; string arg2 = HttpContext.Current.Request.ServerVariables["QUERY_STRING"]; stringBuilder.AppendFormat("[Headers]\r\n{0}\r\n[HttpMethod]\r\n{1}\r\n[QueryString]\r\n{2}\r\n[Form]\r\n", arg, httpMethod, arg2); foreach (object obj in HttpContext.Current.Request.Form) { string text = (string)obj; if (text != "__VIEWSTATE") { stringBuilder.AppendFormat("{0}:{1}\r\n", text, HttpContext.Current.Request.Form[text]); } } errorLogCreateSPWrapper.strRequestInfo = stringBuilder.ToString(); } else if (OperationContext.Current != null && OperationContext.Current.RequestContext != null) { errorLogCreateSPWrapper.strDomainName = OperationContext.Current.RequestContext.RequestMessage.Headers.To.Host; errorLogCreateSPWrapper.strRequestUrl = OperationContext.Current.RequestContext.RequestMessage.Headers.To.AbsoluteUri; RemoteEndpointMessageProperty remoteEndpointMessageProperty = OperationContext.Current.RequestContext.RequestMessage.Properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; if (remoteEndpointMessageProperty != null) { errorLogCreateSPWrapper.strClientIP = remoteEndpointMessageProperty.Address; } HttpRequestMessageProperty httpRequestMessageProperty = OperationContext.Current.RequestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty; if (httpRequestMessageProperty != null) { if (httpRequestMessageProperty.QueryString != null && httpRequestMessageProperty.QueryString != string.Empty) { errorLogCreateSPWrapper.strRequestUrl = string.Format("{0}?{1}", OperationContext.Current.RequestContext.RequestMessage.Headers.To.AbsoluteUri, httpRequestMessageProperty.QueryString); } StringBuilder stringBuilder2 = new StringBuilder(); foreach (string text2 in httpRequestMessageProperty.Headers.AllKeys) { stringBuilder2.AppendFormat("{0}:{1}", text2, httpRequestMessageProperty.Headers[text2]); } errorLogCreateSPWrapper.strRequestInfo = string.Format("[Hearder]\r\n{0}\r\n[HttpMethod]\r\n{1}\r\n[QueryString]\r\n{2}\r\n[Form]\r\n", stringBuilder2.ToString(), httpRequestMessageProperty.Method, httpRequestMessageProperty.QueryString); } } else { errorLogCreateSPWrapper.strDomainName = Environment.ProgramName; errorLogCreateSPWrapper.strRequestUrl = Environment.ProgramLocation; } ErrorLogCreateSPResult errorLogCreateSPResult = errorLogCreateSPWrapper.Execute(); if (errorLogCreateSPResult.SPErrorCode == 0) { n4ErrorLogSN = errorLogCreateSPResult.n4ErrorLogSN; dtCreateDate = errorLogCreateSPResult.dtCreateDate; return(errorLogCreateSPResult.errorLogInfo); } n4ErrorLogSN = 0; dtCreateDate = DateTime.MinValue; return(null); }
/// <summary> /// Create audit data /// </summary> public static AuditData CreateAuditData(IEnumerable <DomainResourceBase> records) { // Audit data AuditData retVal = null; AuditableObjectLifecycle lifecycle = AuditableObjectLifecycle.Access; // Get the actor information string userId = String.Empty; if (OperationContext.Current.Channel.RemoteAddress != null && OperationContext.Current.Channel.RemoteAddress.Uri != null) { userId = OperationContext.Current.Channel.RemoteAddress.Uri.OriginalString; } else if (OperationContext.Current.ServiceSecurityContext != null && OperationContext.Current.ServiceSecurityContext.PrimaryIdentity != null) { userId = OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name; } MessageProperties properties = OperationContext.Current.IncomingMessageProperties; RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; string remoteEndpoint = "http://anonymous"; if (endpoint != null) { remoteEndpoint = endpoint.Address; } CodeValue itiNameMap = null; if (records == null || records.FirstOrDefault() == null && !s_configuration.ActionMap.TryGetValue(String.Format("{0} ", WebOperationContext.Current.IncomingRequest.Method), out itiNameMap) || records.FirstOrDefault() != null && !s_configuration.ActionMap.TryGetValue(String.Format("{0} {1}", WebOperationContext.Current.IncomingRequest.Method, records.FirstOrDefault().GetType().Name), out itiNameMap)) { itiNameMap = new CodeValue( WebOperationContext.Current.IncomingRequest.Method, "urn:ietf:rfc:2616" ) { DisplayName = WebOperationContext.Current.IncomingRequest.Method } } ; // TODO: Clean this up switch (WebOperationContext.Current.IncomingRequest.Method) { case "GET": { retVal = new AuditData(DateTime.Now, ActionType.Execute, OutcomeIndicator.Success, EventIdentifierType.Query, AuditUtil.CopyCode(itiNameMap)); // Audit actor for Patient Identity Source retVal.Actors.Add(new AuditActorData() { UserIsRequestor = true, UserIdentifier = userId, ActorRoleCode = new List <AuditCode>() { new AuditCode("110153", "DCM") { DisplayName = "Source" } }, NetworkAccessPointId = remoteEndpoint, NetworkAccessPointType = NetworkAccessPointType.IPAddress, UserName = userId }); // Audit actor for FHIR service retVal.Actors.Add(new AuditActorData() { UserIdentifier = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.BaseUri.ToString(), UserIsRequestor = false, ActorRoleCode = new List <AuditCode>() { new AuditCode("110152", "DCM") { DisplayName = "Destination" } }, NetworkAccessPointType = NetworkAccessPointType.MachineName, NetworkAccessPointId = Dns.GetHostName(), UserName = Environment.UserName }); // Serialize the query retVal.AuditableObjects.Add(new AuditableObject() { Type = AuditableObjectType.SystemObject, Role = AuditableObjectRole.Query, IDTypeCode = AuditableObjectIdType.Custom, CustomIdTypeCode = AuditUtil.CopyCode(itiNameMap), ObjectId = itiNameMap.DisplayName.Replace(" ", ""), QueryData = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri.Query)), ObjectData = new List <ObjectDataExtension>() { new ObjectDataExtension(String.Empty, WebOperationContext.Current.IncomingRequest.Headers.ToByteArray()) } }); break; } case "POST": { retVal = new AuditData(DateTime.Now, ActionType.Create, OutcomeIndicator.Success, EventIdentifierType.Import, AuditUtil.CopyCode(itiNameMap)); // Audit actor for Patient Identity Source retVal.Actors.Add(new AuditActorData() { UserIsRequestor = true, UserIdentifier = userId, ActorRoleCode = new List <AuditCode>() { new AuditCode("110153", "DCM") { DisplayName = "Source" } }, NetworkAccessPointId = remoteEndpoint, NetworkAccessPointType = NetworkAccessPointType.IPAddress, UserName = userId }); // Audit actor for FHIR service retVal.Actors.Add(new AuditActorData() { UserIdentifier = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.BaseUri.ToString(), UserIsRequestor = false, ActorRoleCode = new List <AuditCode>() { new AuditCode("110152", "DCM") { DisplayName = "Destination" } }, NetworkAccessPointType = NetworkAccessPointType.MachineName, NetworkAccessPointId = Dns.GetHostName(), UserName = Environment.UserName }); break; } case "PUT": { retVal = new AuditData(DateTime.Now, ActionType.Update, OutcomeIndicator.Success, EventIdentifierType.Import, AuditUtil.CopyCode(itiNameMap)); // Audit actor for Patient Identity Source retVal.Actors.Add(new AuditActorData() { UserIsRequestor = true, UserIdentifier = userId, ActorRoleCode = new List <AuditCode>() { new AuditCode("110153", "DCM") { DisplayName = "Source" } }, NetworkAccessPointId = remoteEndpoint, NetworkAccessPointType = NetworkAccessPointType.IPAddress, UserName = userId }); // Audit actor for FHIR service retVal.Actors.Add(new AuditActorData() { UserIdentifier = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.BaseUri.ToString(), UserIsRequestor = false, ActorRoleCode = new List <AuditCode>() { new AuditCode("110152", "DCM") { DisplayName = "Destination" } }, NetworkAccessPointType = NetworkAccessPointType.MachineName, NetworkAccessPointId = Dns.GetHostName(), UserName = Environment.UserName }); break; } case "DELETE": { retVal = new AuditData(DateTime.Now, ActionType.Delete, OutcomeIndicator.Success, EventIdentifierType.Import, AuditUtil.CopyCode(itiNameMap)); // Audit actor for Patient Identity Source retVal.Actors.Add(new AuditActorData() { UserIsRequestor = true, UserIdentifier = userId, ActorRoleCode = new List <AuditCode>() { new AuditCode("110153", "DCM") { DisplayName = "Source" } }, NetworkAccessPointId = remoteEndpoint, NetworkAccessPointType = NetworkAccessPointType.IPAddress, UserName = userId }); // Audit actor for FHIR service retVal.Actors.Add(new AuditActorData() { UserIdentifier = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.BaseUri.ToString(), UserIsRequestor = false, ActorRoleCode = new List <AuditCode>() { new AuditCode("110152", "DCM") { DisplayName = "Destination" } }, NetworkAccessPointType = NetworkAccessPointType.MachineName, NetworkAccessPointId = Dns.GetHostName(), UserName = Environment.UserName }); break; } default: { retVal = new AuditData(DateTime.Now, ActionType.Execute, OutcomeIndicator.Success, EventIdentifierType.ApplicationActivity, new AuditCode( String.Format("GET {0}", WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri.OriginalString), "http://marc-hi.ca/fhir/actions")); break; } } if (records != null) { foreach (DomainResourceBase pat in records) { // TODO: Make this more generic AuditableObject aud = null; var ptcptObjMap = pat.GetType().GetCustomAttributes(typeof(ParticipantObjectMapAttribute), true); string domain = String.Empty; if (ptcptObjMap.Length > 0) { var mapAttribute = ptcptObjMap[0] as ParticipantObjectMapAttribute; domain = ApplicationContext.Current.GetService <IOidRegistrarService>()?.GetOid(mapAttribute.OidName)?.Oid; aud = new AuditableObject() { IDTypeCode = mapAttribute.IdType, Role = mapAttribute.Role, Type = mapAttribute.Type }; } else { continue; } // Lifecycle switch (retVal.ActionCode) { case ActionType.Create: aud.LifecycleType = AuditableObjectLifecycle.Creation; break; case ActionType.Delete: aud.LifecycleType = AuditableObjectLifecycle.LogicalDeletion; break; case ActionType.Execute: aud.LifecycleType = AuditableObjectLifecycle.Access; break; case ActionType.Read: aud.LifecycleType = AuditableObjectLifecycle.Disclosure; break; case ActionType.Update: aud.LifecycleType = AuditableObjectLifecycle.Amendment; break; } aud.ObjectId = String.Format("{1}^^^&{0}&ISO", domain, pat.Id); retVal.AuditableObjects.Add(aud); } } return(retVal); }
public bool CheckRequest(STC_MSG msg) { OperationContext context = OperationContext.Current; MessageProperties msgProp = context.IncomingMessageProperties; RemoteEndpointMessageProperty remoteProp = msgProp[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; ServiceSecurityContext ssc = ServiceSecurityContext.Current; Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine("Demande entrente : " + "<" + ssc.WindowsIdentity.Name + ">" + ssc.WindowsIdentity.User); Console.WriteLine("Adresse cliente : " + remoteProp.Address); Console.WriteLine("Port client : " + remoteProp.Port); Console.WriteLine("Détail du message ->"); Console.WriteLine("Application cliente : " + msg.app_name); Console.WriteLine("Application token : " + msg.app_token); Console.WriteLine("Application version : " + msg.app_version); Console.WriteLine("Opération info : " + msg.op_info); Console.WriteLine("Opération nom : " + msg.op_name); Console.WriteLine("Opération statut : " + msg.op_statut); Console.WriteLine("Utilisteur login : "******"Utilisteur password : "******"Utilisteur token : " + msg.user_token); if (msg.data != null) { int i = msg.data.Length; Console.WriteLine("Le message contient {0} donnée(s) spécifique(s)", i + 1); } else { Console.WriteLine("Le message ne contient pas de données spécifiques"); } if (msg.app_token == "apptoken") // App token to change { if (msg.app_name == "Middleware") //tmp app_name { if (msg.app_version == "2.0") //tmp app_version { return(true); } else { this.msg.op_info = "App version invalid"; this.msg.op_statut = false; this.msg.app_version = ""; } } else { this.msg.op_info = "This plateforme doesn't handle this application."; this.msg.op_statut = false; this.msg.app_name = ""; } } else { this.msg.op_info = "App token invalid"; this.msg.op_statut = false; this.msg.app_token = ""; } this.msg.data = null; this.msg.op_name = ""; this.msg.user_login = ""; this.msg.user_psw = ""; this.msg.user_token = ""; return(false); }
/// <summary> /// Decorates the specified rollbar data. /// </summary> /// <param name="rollbarData">The rollbar data.</param> protected override void Decorate(Data rollbarData) { if (this._httpRequestMessage == null) { return; // there is nothing to decorate with... } if (rollbarData.Request == null) { rollbarData.Request = new Request(this._arbitraryKeyValuePairs); } rollbarData.Request.Url = this._httpRequestMessage.RequestUri?.AbsoluteUri; rollbarData.Request.QueryString = this._httpRequestMessage.RequestUri?.Query; rollbarData.Request.Params = null; rollbarData.Request.Headers = new Dictionary <string, string>(this._httpRequestMessage.Headers.Count()); foreach (var header in this._httpRequestMessage.Headers) { rollbarData.Request.Headers.Add(header.Key, StringUtility.Combine(header.Value, ", ")); } rollbarData.Request.Method = this._httpRequestMessage.Method.Method; switch (rollbarData.Request.Method.ToUpperInvariant()) { case "POST": var task = this._httpRequestMessage.Content.ReadAsStringAsync(); task.Wait(); rollbarData.Request.PostBody = task.Result; rollbarData.Request.PostParams = null; break; case "GET": rollbarData.Request.GetParams = null; break; default: System.Diagnostics.Trace.WriteLine( $"No-op processing {rollbarData.Request.Method.ToUpperInvariant()} HTTP method." ); break; } #if (NETFX) if (this._rollbarConfig == null) { return; } string userIP = null; const string HttpContextProperty = "MS_HttpContext"; const string RemoteEndpointMessagePropery = "System.ServiceModel.Channels.RemoteEndpointMessageProperty"; if (this._httpRequestMessage.Properties.ContainsKey(HttpContextProperty)) { HttpContextBase ctx = this._httpRequestMessage.Properties[HttpContextProperty] as HttpContextBase; if (ctx != null) { userIP = ctx.Request.UserHostAddress; } } else if (this._httpRequestMessage.Properties.ContainsKey(RemoteEndpointMessagePropery)) { RemoteEndpointMessageProperty remoteEndpoint = this._httpRequestMessage.Properties[RemoteEndpointMessagePropery] as RemoteEndpointMessageProperty; if (remoteEndpoint != null) { userIP = remoteEndpoint.Address; } } rollbarData.Request.UserIp = HttpRequestMessagePackageDecorator.DecideCollectableUserIPValue(userIP, this._rollbarConfig.IpAddressCollectionPolicy); #endif }
public Message Echo(Message input) { RemoteEndpointMessageProperty remp = (RemoteEndpointMessageProperty)input.Properties[RemoteEndpointMessageProperty.Name]; return(Message.CreateMessage(input.Version, "echo", input.GetBody <string>() + ";" + remp.Address + ";" + remp.Port.ToString())); }
/// <summary> /// Deserialize the request /// </summary> public void DeserializeRequest(Message request, object[] parameters) { try { #if DEBUG RemoteEndpointMessageProperty endpoint = (RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name]; this.m_traceSource.TraceEvent(TraceEventType.Information, 0, "Received request from: {0}:{1}", endpoint.Address, endpoint.Port); #endif HttpRequestMessageProperty httpRequest = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name]; string contentType = httpRequest.Headers[HttpRequestHeader.ContentType]; UriTemplateMatch templateMatch = (UriTemplateMatch)request.Properties.SingleOrDefault(o => o.Value is UriTemplateMatch).Value; // Not found if (templateMatch == null) { throw new WebFaultException(HttpStatusCode.NotFound); } for (int pNumber = 0; pNumber < parameters.Length; pNumber++) { var parm = this.m_operationDescription.Messages[0].Body.Parts[pNumber]; // Simple parameter if (templateMatch.BoundVariables.AllKeys.Any(o => o.ToLower() == parm.Name.ToLower())) { var rawData = templateMatch.BoundVariables[parm.Name]; parameters[pNumber] = Convert.ChangeType(rawData, parm.Type); } // Use XML Serializer else if (contentType?.StartsWith("application/xml") == true) { var messageFormatProperty = (WebBodyFormatMessageProperty)request.Properties[WebBodyFormatMessageProperty.Name]; XmlDictionaryReader rawReader = request.GetReaderAtBodyContents(); switch (messageFormatProperty.Format) { case WebContentFormat.Raw: { rawReader.ReadStartElement("Binary"); byte[] rawBody = rawReader.ReadContentAsBase64(); using (MemoryStream ms = new MemoryStream(rawBody)) { using (XmlReader bodyReader = XmlReader.Create(ms)) { while (bodyReader.NodeType != XmlNodeType.Element) { bodyReader.Read(); } Type eType = s_knownTypes.FirstOrDefault(o => o.GetCustomAttribute <XmlRootAttribute>()?.ElementName == bodyReader.LocalName && o.GetCustomAttribute <XmlRootAttribute>()?.Namespace == bodyReader.NamespaceURI); XmlSerializer xsz = s_serializers[eType]; parameters[pNumber] = xsz.Deserialize(bodyReader); } } } break; case WebContentFormat.Xml: { rawReader.MoveToStartElement(); using (rawReader) { Type eType = s_knownTypes.FirstOrDefault(o => o.GetCustomAttribute <XmlRootAttribute>()?.ElementName == rawReader.LocalName && o.GetCustomAttribute <XmlRootAttribute>()?.Namespace == rawReader.NamespaceURI); this.m_traceSource.TraceEvent(TraceEventType.Information, 0, "Contract: {0}", typeof(TContract).Name); this.m_traceSource.TraceEvent(TraceEventType.Information, 0, "Attempting to deserialize type: {0}", eType?.Name); XmlSerializer xsz = s_serializers[eType]; parameters[pNumber] = xsz.Deserialize(rawReader); } } break; } } // Use JSON Serializer else if (contentType?.StartsWith("application/json") == true) { // Read the binary contents form the WCF pipeline XmlDictionaryReader bodyReader = request.GetReaderAtBodyContents(); bodyReader.ReadStartElement("Binary"); byte[] rawBody = bodyReader.ReadContentAsBase64(); // Now read the JSON data MemoryStream ms = new MemoryStream(rawBody); StreamReader sr = new StreamReader(ms); JsonSerializer jsz = new JsonSerializer() { Binder = new ModelSerializationBinder(), TypeNameAssemblyFormat = 0, TypeNameHandling = TypeNameHandling.All }; jsz.Converters.Add(new StringEnumConverter()); var dserType = parm.Type; parameters[pNumber] = jsz.Deserialize(sr, dserType); } else if (contentType == "application/octet-stream") { XmlDictionaryReader rawReader = request.GetReaderAtBodyContents(); rawReader.ReadStartElement("Binary"); byte[] rawBody = rawReader.ReadContentAsBase64(); MemoryStream ms = new MemoryStream(rawBody); parameters[pNumber] = ms; } else if (contentType != null)// TODO: Binaries { throw new InvalidOperationException("Invalid request format"); } } } catch (Exception e) { this.m_traceSource.TraceEvent(TraceEventType.Error, e.HResult, e.ToString()); throw; } }
/// <summary> 登陆验证 /// </summary> /// <param name="str"></param> /// <returns></returns> public string LoginIn(string str) { RespFunStruct resp = new RespFunStruct(); try { string loginStr = HXCCommon.DotNetEncrypt.DESEncrypt.Decrypt(str); LoginInput loginObj = Newtonsoft.Json.JsonConvert.DeserializeObject <LoginInput>(loginStr); #region 账套信息 if (string.IsNullOrEmpty(loginObj.acccode)) { resp.IsSuccess = "0"; resp.Msg = "帐套不能为空"; return(HXCCommon.DotNetEncrypt.DESEncrypt.Encrypt(Newtonsoft.Json.JsonConvert.SerializeObject(resp))); } #endregion SetDbName(loginObj.acccode, false); #region 软件注册信息 DataTable dt = BLL.DBHelper.GetTable("获取注册信息", GlobalStaticObj_Server.DbPrefix + GlobalStaticObj_Server.CommAccCode, "tb_signing_info", "authentication_status,protocol_expires_time", "", "", ""); if (dt.Rows.Count == 0) { resp.IsSuccess = "0"; resp.Msg = "软件未注册"; return(HXCCommon.DotNetEncrypt.DESEncrypt.Encrypt(Newtonsoft.Json.JsonConvert.SerializeObject(resp))); } DataSources.EnumAuthenticationStatus enumAuthenticationStatus = (DataSources.EnumAuthenticationStatus)Convert.ToInt32(dt.Rows[0]["authentication_status"].ToString()); if (enumAuthenticationStatus != DataSources.EnumAuthenticationStatus.AUTHORIZED) { resp.IsSuccess = "0"; resp.Msg = "软件" + DataSources.GetDescription(enumAuthenticationStatus, true); return(HXCCommon.DotNetEncrypt.DESEncrypt.Encrypt(Newtonsoft.Json.JsonConvert.SerializeObject(resp))); } DateTime applyTime = Common.UtcLongToLocalDateTime(Convert.ToInt64(dt.Rows[0]["protocol_expires_time"].ToString())); if (applyTime < GlobalStaticObj_Server.Instance.CurrentDateTime) { resp.IsSuccess = "0"; resp.Msg = "软件过期"; return(HXCCommon.DotNetEncrypt.DESEncrypt.Encrypt(Newtonsoft.Json.JsonConvert.SerializeObject(resp))); } #endregion #region 验证用户 string tempUserID = BLL.DBHelper.GetSingleValue("验证用户是否存在", GlobalStaticObj_Server.Instance.CurrAccDbName, "sys_user", "user_id", " land_name='" + loginObj.username + "'", ""); if (string.IsNullOrEmpty(tempUserID)) { resp.IsSuccess = "0"; resp.Msg = "登录用户不存在"; return(HXCCommon.DotNetEncrypt.DESEncrypt.Encrypt(Newtonsoft.Json.JsonConvert.SerializeObject(resp))); } //if (LoginSessionInfo.Instance.dicLoginInfos.ContainsKey(tempUserID)) //{ // resp.IsSuccess = "0"; // resp.Msg = "该用户已在其他电脑登录"; // return HXCCommon.DotNetEncrypt.DESEncrypt.Encrypt(Newtonsoft.Json.JsonConvert.SerializeObject(resp)); //} OperationContext context = OperationContext.Current; //获取传进的消息属性 MessageProperties properties = context.IncomingMessageProperties; //获取消息发送的远程终结点IP和端口 RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; string IPStr = string.Empty; if (string.IsNullOrEmpty(endpoint.Address) || endpoint.Address.Equals("::1")) { IPStr = "127.0.0.1"; } else { IPStr = endpoint.Address; } IPStr += ":" + endpoint.Port.ToString(); DataSet ds = new DataSet(); string errMsg = BLL.ClientUser.UserLogin(loginObj, IPStr, GlobalStaticObj_Server.Instance.CurrAccDbName, out ds); if (!string.IsNullOrEmpty(errMsg)) { resp.IsSuccess = "0"; //resp.Msg = "登录密码错误"; resp.Msg = errMsg; return(HXCCommon.DotNetEncrypt.DESEncrypt.Encrypt(Newtonsoft.Json.JsonConvert.SerializeObject(resp))); } if (ds == null || ds.Tables.Count == 0 || (ds.Tables.Count == 1 && ds.Tables[0].Rows.Count == 0)) { resp.IsSuccess = "0"; resp.Msg = "登录异常"; return(HXCCommon.DotNetEncrypt.DESEncrypt.Encrypt(Newtonsoft.Json.JsonConvert.SerializeObject(resp))); } #endregion string userID = ds.Tables[0].Rows[0][0].ToString(); //将登陆id及cookie信息加入到缓存中 string cookieStr = LoginSessionInfo.Instance.LoginIn(loginObj.acccode, userID);; DataTable dtReturn = new DataTable("cookieStr"); DataColumn dc = new DataColumn("cookieStr", typeof(string)); dtReturn.Columns.Add(dc); DataRow dr = dtReturn.NewRow(); dr["cookieStr"] = cookieStr; dtReturn.Rows.Add(dr); ds.Tables.Add(dtReturn); resp.IsSuccess = "1"; resp.ReturnObject = JsonConvert.SerializeObject(ds); } catch (Exception ex) { resp.IsSuccess = "0"; resp.Msg = "登陆失败:" + ex.Message; GlobalStaticObj_Server.WCFLogService.WriteLog("登陆验证", ex); } return(HXCCommon.DotNetEncrypt.DESEncrypt.Encrypt(Newtonsoft.Json.JsonConvert.SerializeObject(resp))); }
/// <summary> /// GetRemoteAddress /// </summary> /// <returns></returns> private string GetRemoteAddress() { RemoteEndpointMessageProperty endpoint = OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; return(endpoint.Address); }
/// <summary>WCF サービス本体</summary> /// <param name="param">REST 形式で送信された引数(ParamDataContract)</param> /// <returns>REST 形式で送信される戻り値(ReturnDataContract)</returns> private ReturnDataContract Call(ParamDataContract param) { // ステータス string status = "-"; // 戻り値 ReturnDataContract retValue = new ReturnDataContract(); #region 呼出し制御関係の変数 // アセンブリ名 string assemblyName = ""; // クラス名 string className = ""; #endregion #region 引数・戻り値関係の変数 // 引数・戻り値の.NETオブジェクト MuParameterValue muParameterValue = null; MuReturnValue muReturnValue = null; // エラー情報(ログ出力用) string errorType = ""; // 2009/09/15-この行 string errorMessageID = ""; string errorMessage = ""; string errorToString = ""; #endregion try { // 開始ログの出力 LogIF.InfoLog("SERVICE-IF", FxLiteral.SIF_STATUS_START); #region 前解決 // ★ status = FxLiteral.SIF_STATUS_NAME_SERVICE; // 名前解決(インプロセス) ServiceForRt.IPR_NS.NameResolution(param.ServiceName, out assemblyName, out className); #endregion #region 引数の.NETオブジェクト化(UOC) // ★ status = FxLiteral.SIF_STATUS_DESERIALIZE; // ★★ 引数の.NETオブジェクト化をUOCする(必要に応じて)。 // 引数文字列の.NETオブジェクト化 // クライアントの IP アドレス string IpAddress = string.Empty; // クライアントの IP アドレスを取得 OperationContext context = OperationContext.Current; if (context.IncomingMessageProperties.ContainsKey(RemoteEndpointMessageProperty.Name) == true) { RemoteEndpointMessageProperty property = (RemoteEndpointMessageProperty)context.IncomingMessageProperties[RemoteEndpointMessageProperty.Name]; IpAddress = property.Address; } // ParamDataContractを使用して初期化するなど muParameterValue = new MuParameterValue( param.ScreenId == null ? string.Empty : param.ScreenId, // 画面名 param.ControlId == null ? string.Empty : param.ControlId, // ボタン名 param.MethodName == null ? string.Empty : param.MethodName, // メソッド名 param.ActionType == null ? string.Empty : param.ActionType, // アクションタイプ new MyUserInfo(param.UserName, IpAddress)); // ParameterValueを引数のBeanフィールドに設定 muParameterValue.Bean = param.Info; // 引数クラスをパラメタ セットに格納 object[] paramSet = new object[] { muParameterValue, DbEnum.IsolationLevelEnum.User }; #endregion #region 認証処理(UOC) // ★ status = FxLiteral.SIF_STATUS_AUTHENTICATION; //// ★★ 認証が通っているかどうか確認する。 //if (!HttpContext.Current.Request.IsAuthenticated) //{ // throw new BusinessSystemException("Authentication", "認証されていません。"); //} // ★★ コンテキストの情報を使用するなどして // 認証処理をUOCする(必要に応じて)。 //// 認証チケットの復号化 //string[] authTicket = (string[])BinarySerialize.BytesToObject( // CustomEncode.FromBase64String( // SymmetricCryptography.DecryptString( // context, GetConfigParameter.GetConfigValue("private-key"), // EnumSymmetricAlgorithm.TripleDESCryptoServiceProvider))); //// ユーザIDの設定 //muParameterValue.User.UserName = authTicket[0]; // 認証チケットの整合性を確認 // Forms認証では、machinekeyを使用している。 // 必要に応じて認証サービス側も作り変える。 //// B層・D層呼出し //// タイムスタンプのチェックと、更新 //// スライディング・タイムアウトの実装、 //// 必要であればアカウントの検証も実施 //BaseReturnValue _returnValue = (BaseReturnValue)Latebind.InvokeMethod( // "xxxx", "yyyy", // FxLiteral.TRANSMISSION_INPROCESS_METHOD_NAME, // new object[] { new AuthParameterValue("-", "-", "zzzz", "", // muParameterValue.User, authTicket[1]), // DbEnum.IsolationLevelEnum.User }); //if (_returnValue.ErrorFlag) //{ // // 認証エラー // throw new BusinessSystemException("xxxx", "認証チケットが不正か、タイムアウトです。"); //} #endregion #region B層・D層呼出し // ★ status = FxLiteral.SIF_STATUS_INVOKE; try { // B層・D層呼出し //// DLL名も指定するパターン(別DLLに含まれる) //muReturnValue = (MuReturnValue)Latebind.InvokeMethod( // assemblyName, className, FxLiteral.TRANSMISSION_INPROCESS_METHOD_NAME, paramSet); // DLL名は指定しないパターン(ExecutingAssemblyに含まれる) Assembly asm = Assembly.GetExecutingAssembly(); // DLL名は指定しないパターンでの例外処理 Type t = asm.GetType(className); if (t == null) { throw new BusinessSystemException("NoLBTypeInExecutingAssembly", string.Format("{0}クラスがExecutingAssemblyに存在しません。", className)); } object o = Activator.CreateInstance(t); muReturnValue = (MuReturnValue)Latebind.InvokeMethod(o, FxLiteral.TRANSMISSION_INPROCESS_METHOD_NAME, paramSet); } catch (System.Reflection.TargetInvocationException rtEx) { // InnerExceptionを投げなおす。 throw rtEx.InnerException; } #endregion #region 戻り値の文字列化 // ★ status = FxLiteral.SIF_STATUS_SERIALIZE; if (muReturnValue.ErrorFlag) { // エラー情報を設定する。 ErrorInfo errorInfo = new ErrorInfo(); // 業務例外 errorInfo.ErrorType = FxEnum.ErrorType.BusinessApplicationException.ToString(); errorInfo.MessageID = muReturnValue.ErrorMessageID; errorInfo.Message = muReturnValue.ErrorMessage; errorInfo.Information = muReturnValue.ErrorInfo; // ログ出力用の情報を保存 errorType = FxEnum.ErrorType.BusinessApplicationException.ToString(); // 2009/09/15-この行 errorMessageID = muReturnValue.ErrorMessageID; errorMessage = muReturnValue.ErrorMessage; errorToString = muReturnValue.ErrorInfo; // エラー情報を戻す。 retValue.Error = errorInfo; } #endregion // ★ status = ""; // 戻り値を設定 if (muReturnValue.Bean != null && muReturnValue.Bean is Informations) { // 正規の戻り値の場合 retValue.Info = (Informations)muReturnValue.Bean; } else { //// 不正な戻り値の場合 //retValue.Info = new Informations(""); throw new Exception("不正な戻り値"); } // 戻り値を返す。 return(retValue); } //catch (BusinessApplicationException baEx) //{ // ここには来ない↑ //} catch (BusinessSystemException bsEx) { // エラー情報を設定する。 ErrorInfo errorInfo = new ErrorInfo(); // システム例外 errorInfo.ErrorType = FxEnum.ErrorType.BusinessSystemException.ToString(); errorInfo.MessageID = bsEx.messageID; errorInfo.Message = bsEx.Message; errorInfo.Information = string.Empty; // ログ出力用の情報を保存 errorType = FxEnum.ErrorType.BusinessSystemException.ToString(); // 2009/09/15-この行 errorMessageID = bsEx.messageID; errorMessage = bsEx.Message; errorToString = bsEx.ToString(); // エラー情報を戻す。 retValue.Error = errorInfo; return(retValue); } catch (FrameworkException fxEx) { // エラー情報を設定する。 ErrorInfo errorInfo = new ErrorInfo(); // フレームワーク例外 // ★ インナーエクセプション情報は消失 errorInfo.ErrorType = FxEnum.ErrorType.FrameworkException.ToString(); errorInfo.MessageID = fxEx.messageID; errorInfo.Message = fxEx.Message; errorInfo.Information = string.Empty; // ログ出力用の情報を保存 errorType = FxEnum.ErrorType.FrameworkException.ToString(); // 2009/09/15-この行 errorMessageID = fxEx.messageID; errorMessage = fxEx.Message; errorToString = fxEx.ToString(); // エラー情報を戻す。 retValue.Error = errorInfo; return(retValue); } catch (Exception ex) { // エラー情報を設定する。 ErrorInfo errorInfo = new ErrorInfo(); // フレームワーク例外 // ★ インナーエクセプション情報は消失 errorInfo.ErrorType = FxEnum.ErrorType.ElseException.ToString(); errorInfo.MessageID = "-"; errorInfo.Message = ex.ToString(); errorInfo.Information = string.Empty; // ログ出力用の情報を保存 errorType = FxEnum.ErrorType.ElseException.ToString(); // 2009/09/15-この行 errorMessageID = "-"; errorMessage = ex.Message; // どちらを戻すべきか? // Muの場合は、ToStringがデフォ //errorToString = ex.Message; errorToString = ex.ToString(); // エラー情報を戻す。 retValue.Error = errorInfo; return(retValue); //throw; // コメントアウト } finally { // 用途によってSessionを解放するかどうかを検討。 //// Sessionステートレス //Session.Clear(); //Session.Abandon(); // 終了ログの出力 if (status == "") { // 終了ログ出力 LogIF.InfoLog("SERVICE-IF", "正常終了"); } else { // 終了ログ出力 LogIF.ErrorLog("SERVICE-IF", "異常終了" + ":" + status + "\r\n" + "エラー タイプ:" + errorType + "\r\n" // 2009/09/15-この行 + "エラー メッセージID:" + errorMessageID + "\r\n" + "エラー メッセージ:" + errorMessage + "\r\n" + errorToString + "\r\n"); } } }
public static void LogWrite(string content, string dir) { if (!string.IsNullOrEmpty(content)) { string fileNamePath = string.Empty; StringBuilder sbLog = new StringBuilder(); sbLog.Append("Start====================================================================\r\n"); sbLog.Append("记录时间:" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\r\n"); try { OperationContext context = OperationContext.Current; if (context != null) { //获取传进的消息属性 MessageProperties properties = context.IncomingMessageProperties; //获取消息发送的远程终结点IP和端口 RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; if (endpoint != null) { string strIp = endpoint.Address + ":" + endpoint.Port; sbLog.AppendFormat("访问IP:{0}\r\n", strIp); } } } catch { } sbLog.AppendFormat("内容:{0}\r\n", content); sbLog.Append("End=====================================================================\r\n\r\n"); try { string basePath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase; if (!basePath.EndsWith("\\")) { basePath = string.Format(@"{0}\Log", basePath); } else { basePath = string.Format(@"{0}Log", basePath); } if (!string.IsNullOrEmpty(dir)) { basePath = string.Format(@"{0}\{1}\", basePath, dir.Trim(new char[] { '\\' })); } if (!Directory.Exists(basePath)) { Directory.CreateDirectory(basePath); } //每小时一个 fileNamePath = basePath + System.DateTime.Now.ToString("yyyy-MM-dd HH") + ".txt"; if (File.Exists(fileNamePath)) { FileInfo fi = new FileInfo(fileNamePath); if (fi.Length > maxFileSize) { //转为每分钟一个文件 fileNamePath = basePath + System.DateTime.Now.ToString("yyyy-MM-dd HHmm") + ".txt"; } } //写文件 File.AppendAllText(fileNamePath, sbLog.ToString()); } catch (Exception ex) { content += "\r\n写文件异常[Log]::" + ex.Message + "\r\n"; //写文件 File.AppendAllText(fileNamePath, sbLog.ToString()); } } }
public Stream InvokeMethod(Stream Params) { String ipAddress = ""; OperationContext context = OperationContext.Current; MessageProperties properties = context.IncomingMessageProperties; if (properties.ContainsKey(RemoteEndpointMessageProperty.Name)) { RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; ipAddress = string.Format("{0}:{1}", endpoint.Address, endpoint.Port); } List <string> parameters = new List <string>(); try { ApplicationContext AppContext = ApplicationContext.Current; AppContext.Identification.IPAddress = ipAddress; LoginLog(AppContext); } catch (Exception ex) { logger.Error("log login:"******""; try { Stream ms = ReadMemoryStream(Params); //Params.Dispose(); Stream unzipstream = Yqun.Common.Encoder.Compression.DeCompressStream(ms); //ms.Dispose(); Hashtable paramsList = Yqun.Common.Encoder.Serialize.DeSerializeFromStream(unzipstream) as Hashtable; //unzipstream.Dispose(); string path = ServerLoginInfos.DBConnectionInfo.LocalStartPath; parameters.Add(path); string Assembly_Name = paramsList["assembly_name"].ToString(); parameters.Add(Assembly_Name); string FileName = Path.Combine(path.Trim(), Assembly_Name.Trim()); parameters.Add(FileName); Method_Name = paramsList["method_name"].ToString(); Method_Paremeters = paramsList["method_paremeters"] as object[]; object o = InvokeMethod(FileName, Method_Name, Method_Paremeters); Hashtable t = new Hashtable(); t.Add("return_value", o); Stream stream = Serialize.SerializeToStream(t); Stream zipstream = Compression.CompressStream(stream); //stream.Dispose(); return(zipstream); } catch (Exception ex) { String log = ""; foreach (var item in Method_Paremeters) { log += item.ToString() + ";"; } logger.Error(string.Format("[{0}]访问服务出错,原因为“{1}”,参数列表为{2}, 传入参数为{3},方法名称{4}", ApplicationContext.Current.UserName, ex.Message, string.Join(",", parameters.ToArray()), log, Method_Name )); } return(null); }
private OperationDataArgs OperationA01(List <string> AListStringArgs) { OperationDataArgs LOperationReturn = new OperationDataArgs(); int LIntHttpBindingPort = 0; int LIntService01Port = 0; string LStrRemoteIPAddress = string.Empty; string LStrSendMessage = string.Empty; string LStrReadMessage = string.Empty; string LStrVerificationCode004 = string.Empty; TcpClient LTcpClient = null; SslStream LSslStream = null; string LStrCallReturn = string.Empty; List <string> LListStringArgs = new List <string>(); try { LStrVerificationCode004 = CreateVerificationCode(EncryptionAndDecryption.UMPKeyAndIVType.M004); #region 获取UMP Service 01端口 LIntHttpBindingPort = GetIISHttpBindingPort(ref LStrCallReturn); if (LIntHttpBindingPort <= 0) { LOperationReturn.BoolReturn = false; LOperationReturn.StringReturn = LStrCallReturn; return(LOperationReturn); } LIntService01Port = LIntHttpBindingPort - 1; #endregion #region 获取客户端IP地址 OperationContext LOperationContext = OperationContext.Current; MessageProperties LMessageProperties = LOperationContext.IncomingMessageProperties; RemoteEndpointMessageProperty LRemoteEndpointMessageProperty = LMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; LStrRemoteIPAddress = LRemoteEndpointMessageProperty.Address.ToString(); #endregion #region 创建消息字符串 foreach (string LStrSingleArgs in AListStringArgs) { LListStringArgs.Add(LStrSingleArgs); } LListStringArgs[7] = LStrRemoteIPAddress; LStrSendMessage = EncryptionAndDecryption.EncryptDecryptString("M01B01", LStrVerificationCode004, EncryptionAndDecryption.UMPKeyAndIVType.M004); foreach (string LStrSingleArgs in LListStringArgs) { LStrSendMessage += AscCodeToChr(27) + LStrSingleArgs; } #endregion #region 发送消息给服务,写操作日志 LTcpClient = new TcpClient("127.0.0.1", LIntService01Port); LSslStream = new SslStream(LTcpClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); LSslStream.AuthenticateAsClient("VoiceCyber.PF", null, SslProtocols.Default, false); byte[] LByteMesssage = Encoding.UTF8.GetBytes(LStrSendMessage + "\r\n"); LSslStream.Write(LByteMesssage); LSslStream.Flush(); if (!ReadMessageFromServer(LSslStream, ref LStrReadMessage)) { LOperationReturn.BoolReturn = false; } LOperationReturn.StringReturn = LStrReadMessage; #endregion } catch (Exception ex) { LOperationReturn.BoolReturn = false; LOperationReturn.StringReturn = ex.ToString(); } finally { if (LSslStream != null) { LSslStream.Close(); } if (LTcpClient != null) { LTcpClient.Close(); } } return(LOperationReturn); }
public STC_MSG m_service(STC_MSG msg) { int i; Console.ForegroundColor = ConsoleColor.Blue; OperationContext ctx = OperationContext.Current; MessageProperties msgP = ctx.IncomingMessageProperties; RemoteEndpointMessageProperty remP = msgP[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; ServiceSecurityContext ssc = ServiceSecurityContext.Current; Console.WriteLine("Demande entrante : " + "<" + ssc.WindowsIdentity.Name + ">" + ssc.WindowsIdentity.User); Console.WriteLine("Adresse cliente : " + remP.Address); Console.WriteLine("Port client : " + remP.Port); Console.WriteLine("Détail du message ->"); Console.WriteLine("Application cliente : " + msg.app_name); Console.WriteLine("Application token : " + msg.app_token); Console.WriteLine("Application version : " + msg.app_version); Console.WriteLine("Opération info : " + msg.op_info); Console.WriteLine("Opération nom : " + msg.op_name); Console.WriteLine("Opération statut : " + msg.op_statut); Console.WriteLine("Utilisteur login : "******"Utilisteur password : "******"Utilisteur token : " + msg.user_token); if (msg.data != null) { i = msg.data.Length; Console.WriteLine("Le message contient {0} donnée(s) spécifique(s)", i + 1); } else { Console.WriteLine("Le message ne contient pas de données spécifiques"); } Console.WriteLine(""); if (msg.app_token == "12345") { Console.WriteLine("App Token:" + msg.app_token); if (msg.op_name == "authentifier") { Console.WriteLine("Operation Name:" + msg.op_name); this.msg = msg; this.service = new PCS_personne(); this.msg = ((PCS_personne)this.service).m_authentifier(this.msg); } } else { this.msg.app_name = ""; this.msg.app_token = ""; this.msg.app_version = ""; this.msg.data = null; this.msg.op_info = "Cette application n'est pas prise en charge par la plateforme."; this.msg.op_name = ""; this.msg.op_statut = false; this.msg.user_login = ""; this.msg.user_psw = ""; this.msg.user_token = ""; } return(this.msg); }
public Stream Html(bool update) { if (isShuttingDown) { return(new MemoryStream(Encoding.Default.GetBytes("kill"))); } if (html == null) { return(null); } OperationContext context = OperationContext.Current; MessageProperties messageProperties = context.IncomingMessageProperties; RemoteEndpointMessageProperty endpointProperty = messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; string key = endpointProperty.Address + WebOperationContext.Current.IncomingRequest.UserAgent; Logger.WriteLine(update + " " + key + " " + WebOperationContext.Current.IncomingRequest.UserAgent); WebOperationContext.Current.OutgoingResponse.ContentType = "text/html"; lock (resetEvents) { if (!resetEvents.ContainsKey(key)) { AutoResetEvent a = new AutoResetEvent(false); resetEvents[key] = a; update = false; } } Logger.WriteLine(update); if (!update) { resetEvents[key].Reset(); string userAgent = WebOperationContext.Current.IncomingRequest.UserAgent; if (userAgent == null) { return(new MemoryStream(Encoding.Default.GetBytes(htmlWp7))); } if (userAgent.IndexOf("iPhone") >= 0) { return(new MemoryStream(Encoding.Default.GetBytes(htmlIPhone))); } if (userAgent.IndexOf("iPad") >= 0) { return(new MemoryStream(Encoding.Default.GetBytes(htmlIPad))); } if (userAgent.IndexOf("Android") >= 0) { return(new MemoryStream(Encoding.Default.GetBytes(htmlAndroid))); } if (userAgent.IndexOf("Windows Phone") >= 0) { return(new MemoryStream(Encoding.Default.GetBytes(htmlWp7))); } return(new MemoryStream(Encoding.Default.GetBytes(htmlWp7))); } Interlocked.Increment(ref numToKill); if (resetEvents[key].WaitOne(10000)) { Interlocked.Decrement(ref numToKill); if (isShuttingDown) { if (numToKill == 0) { killResetEvent.Set(); } return(new MemoryStream(Encoding.Default.GetBytes("kill"))); } return(new MemoryStream(Encoding.Default.GetBytes(insideDiv))); } Interlocked.Decrement(ref numToKill); return(null); }
/// <summary> /// 登录 /// </summary> /// <param name="loginname_"></param> /// <param name="password_"></param> /// <returns></returns> public UserInfoEntity Login(string loginname_, string password_) { try { UserInfoEntity ent = new UserInfoEntity(); //验证服务器是否授权 //int aut = DataCache.IsAuth; //if (aut != 0) //{ // ent.IsOK = aut; // return ent; //} using (BFdbContext db = new BFdbContext()) { var user = db.TBUSER.FirstOrDefault(p => p.USERID.ToLower() == loginname_.ToLower() && p.PWD == password_ && p.DELFLAG == "0"); if (user == null) { ent.IsOK = -99; ent.Msg = "-1"; } else { ent.IsOK = 0; ent.ID = user.ID; ent.USERID = user.USERID; ent.USERNAME = user.USERNAME; ent.PASSWORD = user.PWD; ent.EMAIL = user.EMAIL; ent.TELEPHONE = user.TELEPHONE; ent.RE_REVIEW = user.RE_REVIEW; string sql = @"select distinct a.id, a.menuname, a.menucode, a.remark,a.updatedate,a.updateid,a.createdate,a.createid from tb_menu a,tb_rolemenurelation b,tb_userrolerelation c where a.id=b.menuid and b.roleid=c.roleid and c.userid='{0}'"; ent.MenuList = db.SqlQuery <TBMENU>(string.Format(sql, user.ID)).ToList(); //提供方法执行的上下文环境 OperationContext context = OperationContext.Current; //获取传进的消息属性 MessageProperties properties = context.IncomingMessageProperties; RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; TBUSERLOG log = new TBUSERLOG(); log.CREATEDATE = DateTime.Now; log.ID = Guid.NewGuid().ToString("N"); log.IP = endpoint.Address; log.REMARK = ""; log.TYPE = "0"; log.USERID = ent.ID; db.Insert <TBUSERLOG>(log); } return(ent); } } catch (Exception ex) { log.Error(ex); throw GetFault(ex); } }
//User Login public LoginCL User_Login(User_LoginIN user_Login) { //Initialize Logger log4net.Config.XmlConfigurator.Configure(); //Initialize Logger LoginCL results_final = new LoginCL(); try { string objUSER_AGENT = Common.USER_AGENT(); if (objUSER_AGENT != ConfigurationManager.AppSettings["User-Agent"].ToString()) { ctx.OutgoingResponse.StatusCode = (System.Net.HttpStatusCode) 401; goto Finish; } //get IPAddress OperationContext context = OperationContext.Current; MessageProperties messageProperties = context.IncomingMessageProperties; RemoteEndpointMessageProperty endpointProperty = messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; //get IPAddress string encPWD = Common.Password_Encrypt(user_Login.password); Hashtable parameters = new Hashtable(); parameters.Clear(); parameters.Add("@EMAIL", user_Login.email); parameters.Add("@PASSWORD", encPWD); parameters.Add("@IPADDRESS", endpointProperty.Address + ":" + endpointProperty.Port); parameters.Add("@MODE", "LOGIN"); DataSet dsrec = objDb.senddataset_SP("GC_REGISTRATION_PRC", parameters); if (dsrec.Tables[0].Rows.Count > 0) { if (dsrec.Tables[0].Rows[0]["RSTATUS"].ToString().ToLower() == "invalid") { //ctx.OutgoingResponse.StatusCode = HttpStatusCode.NoContent; ctx.OutgoingResponse.StatusCode = (System.Net.HttpStatusCode) 211; goto Finish; } if (dsrec.Tables[0].Rows[0]["RSTATUS"].ToString().ToLower() == "email not verified") { //Send email verification mail here.. //ctx.OutgoingResponse.StatusCode = HttpStatusCode.NoContent; ctx.OutgoingResponse.StatusCode = (System.Net.HttpStatusCode) 415; goto Finish; } if (dsrec.Tables[0].Rows[0]["RSTATUS"].ToString().ToLower() == "user blocked") { ctx.OutgoingResponse.StatusCode = (System.Net.HttpStatusCode) 419; goto Finish; } //string objResponse = string.Empty; //Int32 objRegistrationId = Convert.ToInt32(dsrec.Tables[0].Rows[0]["REGISTRATIONID"].ToString()); //if (objRegistrationId == 0) //{ // ctx.OutgoingResponse.StatusCode = (System.Net.HttpStatusCode)211; // goto Finish; //} results_final.RegistrationId = objDb.ENC_REGID(Convert.ToInt32(dsrec.Tables[0].Rows[0]["REGISTRATIONID"].ToString())); results_final.name = dsrec.Tables[0].Rows[0]["NAME"].ToString(); results_final.email = dsrec.Tables[0].Rows[0]["EMAIL"].ToString(); results_final.mobile = dsrec.Tables[0].Rows[0]["MOBILE"].ToString(); results_final.SERVER_DATETIME = Common.GetUTCdatetime_epoch(); } else { ctx.OutgoingResponse.StatusCode = (System.Net.HttpStatusCode) 211; } Finish: return(results_final); } catch (Exception ex) { ctx.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError; logger.Error("User.svc/User_Login: "******"::" + ex.StackTrace.ToString()); return(results_final); } }
private OperationReturn LogOnUMP(List <string> listParams) { OperationReturn optReturn = new OperationReturn(); optReturn.Result = true; optReturn.Code = 0; try { #region 解析参数 //ListParams //参考S000ACodes中的说明,此处从略 if (listParams == null || listParams.Count < 4) { optReturn.Result = false; optReturn.Code = Defines.RET_PARAM_INVALID; optReturn.Message = string.Format("Request param is null or count invalid"); return(optReturn); } string strAccount = listParams[0]; string strPassword = listParams[1]; string strLoginMethod = listParams[2]; string strLoginHost = listParams[3]; string strLoginIP = string.Empty; if (listParams.Count > 4) { strLoginIP = listParams[4]; } else { #region 获取客户端IP地址 string strRemote = string.Empty; OperationContext context = OperationContext.Current; MessageProperties properties = context.IncomingMessageProperties; RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; if (endpoint != null) { strRemote = endpoint.Address; } strLoginIP = strRemote; #endregion } WriteOperationLog( string.Format( "LogOnUMP:\tAccount:{0};Password:***;LoginMethod:{1};LoginHost:{2};LoginIP:{3};", strAccount, strLoginMethod, strLoginHost, strLoginIP)); #endregion #region 参数验证 #endregion #region 读取AppServerInfo optReturn = ReadAppServerInfo(); if (!optReturn.Result) { return(optReturn); } AppServerInfo appServerInfo = optReturn.Data as AppServerInfo; if (appServerInfo == null) { optReturn.Result = false; optReturn.Code = Defines.RET_OBJECT_NULL; optReturn.Message = string.Format("AppServerInfo is null"); return(optReturn); } #endregion #region 向Service01发送消息 string strSendMessage = string.Format("{0}{1}{2}{1}{3}{1}{4}{1}{5}{1}{6}{1}{7}", EncryptToClient("M01A01"), ConstValue.SPLITER_CHAR, EncryptToClient(strAccount), EncryptToClient(strPassword), EncryptToClient(strLoginMethod), EncryptToClient("11000"), EncryptToClient(strLoginHost), EncryptToClient(strLoginIP)); WriteOperationLog(string.Format("LogOnUMP:\tSendMessage:{0}", strSendMessage)); TcpClient tcpClient = new TcpClient("127.0.0.1", appServerInfo.SupportHttps ? appServerInfo.Port - 2 : appServerInfo.Port - 1); SslStream sslStream = new SslStream(tcpClient.GetStream(), false, (s, cert, chain, err) => true); sslStream.AuthenticateAsClient("VoiceCyber.PF", null, SslProtocols.Default, false); byte[] byteData = Encoding.UTF8.GetBytes(strSendMessage + "\r\n"); sslStream.Write(byteData, 0, byteData.Length); sslStream.Flush(); string strReadedMessage = string.Empty; if (!ReadMessageFromServer(sslStream, ref strReadedMessage)) { optReturn.Result = false; optReturn.Code = Defines.RET_FAIL; optReturn.Message = strReadedMessage; return(optReturn); } WriteOperationLog(string.Format("LogOnUMP:\tReadedMessage:{0}", strReadedMessage)); string[] arrReadedMessage = strReadedMessage.Split(new[] { ConstValue.SPLITER_CHAR }, StringSplitOptions.None); List <string> listReturn = new List <string>(); for (int i = 0; i < arrReadedMessage.Length; i++) { listReturn.Add(DecryptFromClient(arrReadedMessage[i])); } #region 如果登录成功,获取用户所在的部门的编码和部门名称 if (listReturn.Count > 0) { string strReturnCode = listReturn[0]; if (strReturnCode == "S01A00" || strReturnCode == "S01A02" || strReturnCode == "S01A03") { if (listReturn.Count > 2) { string strUserID = listReturn[2]; List <string> listRequestParams = new List <string>(); listRequestParams.Add(strUserID); listRequestParams.Add("0"); listRequestParams.Add(ConstValue.RESOURCE_ORG.ToString()); listRequestParams.Add("-1"); optReturn = GetUserCtlObjList(listRequestParams); if (!optReturn.Result) { return(optReturn); } List <string> listOrgReturn = optReturn.Data as List <string>; if (listOrgReturn != null && listOrgReturn.Count > 0) { string strOrgInfo = listOrgReturn[0]; optReturn = XMLHelper.DeserializeObject <ResourceObject>(strOrgInfo); if (!optReturn.Result) { return(optReturn); } ResourceObject org = optReturn.Data as ResourceObject; if (org != null) { listReturn.Add(org.ObjID.ToString()); //编码 listReturn.Add(org.Name); //名称 } } } } } #endregion sslStream.Close(); tcpClient.Close(); #endregion optReturn.Data = listReturn; } catch (Exception ex) { optReturn.Result = false; optReturn.Code = Defines.RET_FAIL; optReturn.Message = ex.Message; return(optReturn); } return(optReturn); }
//User Login public SignupCL Signup(SignupIN signup) { //Initialize Logger log4net.Config.XmlConfigurator.Configure(); //Initialize Logger SignupCL results_final = new SignupCL(); try { string objUSER_AGENT = Common.USER_AGENT(); if (objUSER_AGENT != ConfigurationManager.AppSettings["User-Agent"].ToString()) { ctx.OutgoingResponse.StatusCode = (System.Net.HttpStatusCode) 401; goto Finish; } //get IPAddress OperationContext context = OperationContext.Current; MessageProperties messageProperties = context.IncomingMessageProperties; RemoteEndpointMessageProperty endpointProperty = messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; //get IPAddress string encPWD = Common.Password_Encrypt(signup.password); Hashtable parameters = new Hashtable(); parameters.Clear(); parameters.Add("@NAME", signup.name); parameters.Add("@EMAIL", signup.email); parameters.Add("@MOBILE", signup.mobile); parameters.Add("@PASSWORD", encPWD); parameters.Add("@IPADDRESS", endpointProperty.Address + ":" + endpointProperty.Port); parameters.Add("@MODE", "SIGNUP"); DataSet dsrec = objDb.senddataset_SP("GC_REGISTRATION_PRC", parameters); if (dsrec.Tables[0].Rows.Count > 0) { if (dsrec.Tables[0].Rows[0]["RSTATUS"].ToString().ToLower() == "invalid") { //ctx.OutgoingResponse.StatusCode = HttpStatusCode.NoContent; ctx.OutgoingResponse.StatusCode = (System.Net.HttpStatusCode) 211; goto Finish; } results_final.SERVER_DATETIME = Common.GetUTCdatetime_epoch(); //Send email verification mail here.. } else { ctx.OutgoingResponse.StatusCode = (System.Net.HttpStatusCode) 209; } Finish: return(results_final); } catch (Exception ex) { ctx.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError; logger.Error("User.svc/Signup: " + ex.Message.ToString() + "::" + ex.StackTrace.ToString()); return(results_final); } }
/// <summary> /// Check access /// </summary> public override bool CheckAccess(OperationContext operationContext) { RemoteEndpointMessageProperty remoteEndpoint = (RemoteEndpointMessageProperty)operationContext.IncomingMessageProperties[RemoteEndpointMessageProperty.Name]; try { this.m_traceSource.TraceInformation("CheckAccess"); // Http message inbound HttpRequestMessageProperty httpMessage = (HttpRequestMessageProperty)operationContext.IncomingMessageProperties[HttpRequestMessageProperty.Name]; // Get the authorize header String authorization = httpMessage.Headers[System.Net.HttpRequestHeader.Authorization]; if (authorization == null) { if (httpMessage.Method == "OPTIONS" || httpMessage.Method == "PING") { //operationContext.ServiceSecurityContext.AuthorizationContext.Properties["Identities"] = identities; operationContext.ServiceSecurityContext.AuthorizationContext.Properties["Principal"] = Core.Security.AuthenticationContext.AnonymousPrincipal; Core.Security.AuthenticationContext.Current = new Core.Security.AuthenticationContext(Core.Security.AuthenticationContext.AnonymousPrincipal); return(true); // OPTIONS is non PHI infrastructural } else { throw new UnauthorizedRequestException("Missing Authorization header", "Bearer", this.m_configuration.Security.ClaimsAuth.Realm, this.m_configuration.Security.ClaimsAuth.Audiences.FirstOrDefault()); } } else if (!authorization.Trim().StartsWith("bearer", StringComparison.InvariantCultureIgnoreCase)) { throw new UnauthorizedRequestException("Invalid authentication scheme", "Bearer", this.m_configuration.Security.ClaimsAuth.Realm, this.m_configuration.Security.ClaimsAuth.Audiences.FirstOrDefault()); } String authorizationToken = authorization.Substring(6).Trim(); JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); var identityModelConfig = ApplicationContext.Current.GetService <IConfigurationManager>().GetSection("system.identityModel") as SystemIdentityModelSection; if (!handler.CanReadToken(authorizationToken)) { throw new SecurityTokenException("Token is not in a valid format"); } SecurityToken token = null; var identities = handler.ValidateToken(authorizationToken, this.m_configuration?.Security?.ClaimsAuth?.ToConfigurationObject(), out token); // Validate token expiry if (token.ValidTo < DateTime.Now.ToUniversalTime()) { throw new SecurityTokenException("Token expired"); } else if (token.ValidFrom > DateTime.Now.ToUniversalTime()) { throw new SecurityTokenException("Token not yet valid"); } operationContext.ServiceSecurityContext.AuthorizationContext.Properties["Identities"] = identities.Identities; operationContext.ServiceSecurityContext.AuthorizationContext.Properties["Principal"] = identities; Core.Security.AuthenticationContext.Current = new Core.Security.AuthenticationContext(identities); this.m_traceSource.TraceInformation("User {0} authenticated via JWT", identities.Identity.Name); return(base.CheckAccess(operationContext)); } catch (UnauthorizedAccessException e) { this.m_traceSource.TraceEvent(TraceEventType.Error, e.HResult, "JWT Token Error (From: {0}) : {1}", remoteEndpoint?.Address, e); throw; } catch (UnauthorizedRequestException e) { this.m_traceSource.TraceEvent(TraceEventType.Error, e.HResult, "JWT Token Error (From: {0}) : {1}", remoteEndpoint?.Address, e); throw; } catch (Exception e) { this.m_traceSource.TraceEvent(TraceEventType.Error, e.HResult, "JWT Token Error (From: {0}) : {1}", remoteEndpoint?.Address, e); throw new SecurityTokenException(e.Message, e); } }
public static string FormatEP(RemoteEndpointMessageProperty ep) { return(ep.Address + ":" + ep.Port); }