Exemplo n.º 1
1
		public static void DumpRares_OnCommand(CommandEventArgs e)
		{
			LogHelper Logger = new LogHelper("RaresDump.log", false);
			try
			{
				foreach (DODGroup dg in RareFactory.DODGroup)
				{
					if (dg is DODGroup)
					{
						foreach (DODInstance di in dg.DODInst)
						{
							if (di is DODInstance)
							{
								if (di.RareTemplate == null)
									Logger.Log(LogType.Text, String.Format("DODInstance {0} has a null RareTemplate.", di.Name));
								else
									Logger.Log(LogType.Item, di.RareTemplate, String.Format("DODInstance {0}: ({1}).", di.Name, di.RareTemplate.GetType().ToString()));
									
							}
						}
					}
				}

				Logger.Log(LogType.Text, "------------- RareFactory.DODInst -------------");

				foreach (DODInstance di in  RareFactory.DODInst)
				{
					if (di is DODInstance)
					{
						if (di.RareTemplate == null)
							Logger.Log(LogType.Text, String.Format("DODInstance {0} has a null RareTemplate.", di.Name));
						else
							Logger.Log(LogType.Item, di.RareTemplate, String.Format("DODInstance {0}: ({1}).", di.Name, di.RareTemplate.GetType().ToString()));
					}
				}

				e.Mobile.SendMessage("Done.");
			}
			catch (Exception ex)
			{
				LogHelper.LogException(ex);
				e.Mobile.SendMessage(ex.Message);
			}
			finally
			{
				Logger.Finish();
			}
		}
 public override void Prepare(ImportOption Option)
 {
     _Option = Option;
     _InsertRecList = new List<DAO.ResultScoreRecord>();
     _UpdateRecList = new List<DAO.ResultScoreRecord>();
     _LogHelper = new LogHelper();
 }
Exemplo n.º 3
0
		private static void LagReport_OnCommand(CommandEventArgs arg)
		{
			Mobile from = arg.Mobile;

			if (from is PlayerMobile)
			{
				PlayerMobile pm = (PlayerMobile)from;

				// Limit to 5 minutes between lag reports
				if ((pm.LastLagTime + TimeSpan.FromMinutes(5.0)) < DateTime.Now)
				{
					// Let them log again
					LogHelper lh = new LogHelper("lagreports.log", false, true);
					lh.Log(LogType.Mobile, from, Server.Engines.CronScheduler.Cron.GetRecentTasks()); //adam: added schduled tasks!

					//Requested by Adam:
					Console.WriteLine("Lag at: {0}", DateTime.Now.ToShortTimeString());

					// Update LastLagTime on PlayerMobile
					pm.LastLagTime = DateTime.Now;

					lh.Finish();

					from.SendMessage("The fact that you are experiencing lag has been logged. We will review this with other data to try and determine the cause of this lag. Thank you for your help.");
				}
				else
				{

					from.SendMessage("It has been less than five minutes since you last reported lag. Please wait five minutes between submitting lag reports.");
				}

			}

		}
Exemplo n.º 4
0
		public static void FindItemByType_OnCommand(CommandEventArgs e)
		{
			try
			{
				if (e.Length == 1)
				{
					LogHelper Logger = new LogHelper("FindItemByType.log", e.Mobile, false);

					string name = e.GetString(0);

					foreach (Item item in World.Items.Values)
					{
						if (item != null && item.GetType().ToString().ToLower().IndexOf(name.ToLower()) >= 0)
						{
							Logger.Log(LogType.Item, item);
						}
					}
					Logger.Finish();
				}
				else
				{
					e.Mobile.SendMessage("Format: FindItemByType <type>");
				}
			}
			catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); }
		}
Exemplo n.º 5
0
		public static void FindMultiByType_OnCommand(CommandEventArgs e)
		{
			try
			{
				if (e.Length == 1)
				{
					LogHelper Logger = new LogHelper("FindMultiByType.log", e.Mobile, false);

					string name = e.GetString(0);

					foreach (ArrayList list in Server.Multis.BaseHouse.Multis.Values)
					{
						for (int i = 0; i < list.Count; i++)
						{
							BaseHouse house = list[i] as BaseHouse;
							// like Server.Multis.Tower
							if (house.GetType().ToString().ToLower().IndexOf(name.ToLower()) >= 0)
							{
								Logger.Log(house);
							}
						}
					}
					Logger.Finish();
				}
				else
				{
					e.Mobile.SendMessage("Format: FindMultiByType <type>");
				}
			}
			catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); }
		}
Exemplo n.º 6
0
 // todo: rewrite with more secure method.
 public static LogHelper GetLogger()
 {
     if(logHlelp == null)
     {
         ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
         logHlelp = new LogHelper(log);
     }
        
     return logHlelp;
 }
Exemplo n.º 7
0
		private static void MakeDeco_OnCommand(CommandEventArgs arg)
		{
			Mobile from = arg.Mobile;
			LogHelper Logger = new LogHelper("makedeco.log", from, true);

			// Loop through town regions and search out items
			// within

			foreach (Region reg in from.Map.Regions)
			{
				if (reg is FeluccaTown || reg is CustomRegion)
				{
					for (int pos = 0; pos < reg.Coords.Count; pos++)
					{
						if (reg.Coords[pos] is Rectangle2D)
						{

							Rectangle2D area = (Rectangle2D)reg.Coords[pos];
							IPooledEnumerable eable = from.Map.GetItemsInBounds(area);

							foreach (object obj in eable)
							{
								if (obj is Container)
								{
									Container cont = (Container)obj;

									if (cont.Movable == false &&
										cont.PlayerCrafted == false &&
										cont.Name != "Goodwill" &&
										!(cont.RootParent is Mobile) &&
										!(cont is TrashBarrel) &&
										cont.Deco == false &&
										!(cont.IsLockedDown) &&
										!(cont.IsSecure))
									{

										// Exclude ransom chests
										if (cont.Name != null && cont.Name.ToLower().IndexOf("ransom") >= 0)
											continue;

										// Found one
										cont.Deco = true;
										Logger.Log(LogType.Item, cont);
									}
								}
							}

							eable.Free();
						}
					}
				}
			}

			Logger.Finish();
		}
Exemplo n.º 8
0
		public override void OnDoubleClick( Mobile from )
		{
            Utility.TimeCheck tc = new Utility.TimeCheck();
            tc.Start();
			Place(from, new Point3D(from.Location.X, from.Location.Y, from.Location.Z), true);
            tc.End();
            LogHelper Logger = new LogHelper("TownshipPlacementTime.log", false);
            //from.SendMessage(String.Format("Stone placement took {0}", tc.TimeTaken));
            Logger.Log(LogType.Text, String.Format("Stone placement check at {0} took {1}", from.Location, tc.TimeTaken));
            Logger.Finish();
		}
 void LogHelper_MessageEvent(object sender, LogHelper.MessageEventArgs e)
 {
     try
     {
         _tcpClientActor.WriteLine(e.Message);
     }
     catch (Exception exp)
     {
         LogHelper.LogException(exp, false, LogHelper.ExceptionSeverity.ErrorException);
     }
 }
Exemplo n.º 10
0
        //Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
        public MySQLHelper(string connStr,LogHelper<TxtLogWriter> log)
            : base(connStr,log)
        {
            ParamSign = "@";
            //if (this.Conn.State == System.Data.ConnectionState.Open)
            //{

            //    this.ExcuteNonQuery("set character_set_results=" + charset);
            //    this.ExcuteNonQuery("set character_set_client=" + charset);
            //    this.ExcuteNonQuery("set character_set_connection=" + charset);
            //}
        }
Exemplo n.º 11
0
		public static void RehydrateWorld_OnCommand(CommandEventArgs e)
		{
			// make it known			
			Server.World.Broadcast(0x35, true, "The world is rehydrating, please wait.");
			Console.WriteLine("World: rehydrating...");
			DateTime startTime = DateTime.Now;

			LogHelper Logger = new LogHelper("RehydrateWorld.log", e.Mobile, true);

			// Extract property & value from command parameters
			ArrayList containers = new ArrayList();

			// Loop items and check vs. types
			foreach (Item item in World.Items.Values)
			{
				if (item is Container)
				{
					if ((item as Container).CanFreezeDry == true)
						containers.Add(item);
				}
			}

			Logger.Log(LogType.Text,
				string.Format("{0} containers scheduled for Rehydration...",
					containers.Count));

			int count = 0;
			for (int ix = 0; ix < containers.Count; ix++)
			{
				Container cont = containers[ix] as Container;

				if (cont != null)
				{
					// Rehydrate it if necessary
					if (cont.CanFreezeDry && cont.IsFreezeDried == true)
						cont.Rehydrate();
					count++;
				}
			}

			Logger.Log(LogType.Text,
				string.Format("{0} containers actually Rehydrated", count));

			Logger.Finish();

			e.Mobile.SendMessage("{0} containers actually Rehydrated", count);

			DateTime endTime = DateTime.Now;
			Console.WriteLine("done in {0:F1} seconds.", (endTime - startTime).TotalSeconds);
			Server.World.Broadcast(0x35, true, "World rehydration complete. The entire process took {0:F1} seconds.", (endTime - startTime).TotalSeconds);
		}
Exemplo n.º 12
0
		public static void FindItemByID_OnCommand(CommandEventArgs e)
		{
			try
			{
				if (e.Length == 1)
				{
					//erl: LogHelper class handles generic logging functionality
					LogHelper Logger = new LogHelper("FindItemByID.log", e.Mobile, false);

					int ItemId = 0;
					string sx = e.GetString(0).ToLower();

					try
					{
						if (sx.StartsWith("0x"))
						{   // assume hex
							sx = sx.Substring(2);
							ItemId = int.Parse(sx, System.Globalization.NumberStyles.AllowHexSpecifier);
						}
						else
						{   // assume decimal
							ItemId = int.Parse(sx);
						}
					}
					catch
					{
						e.Mobile.SendMessage("Format: FindItemByID <ItemID>");
						return;
					}

					foreach (Item ix in World.Items.Values)
					{
						if (ix is Item)
							if (ix.ItemID == ItemId)
							{
								Logger.Log(LogType.Item, ix);
							}
					}
					Logger.Finish();
				}
				else
					e.Mobile.SendMessage("Format: FindItemByID <ItemID>");
			}
			catch (Exception err)
			{

				e.Mobile.SendMessage("Exception: " + err.Message);
			}

			e.Mobile.SendMessage("Done.");
		}
Exemplo n.º 13
0
 /// <summary>
 /// ��ȡLog����
 /// </summary>
 /// <returns></returns>
 public static LogHelper GetInstance()
 {
     if (instance == null)
     {
         lock (obj)
         {
             if (instance == null)
             {
                 instance = new LogHelper();
                 FileInfo configFile = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "Config\\log4net.config");
                 log4net.Config.XmlConfigurator.Configure(configFile);
             }
         }
     }
     return instance;
 }
Exemplo n.º 14
0
        public DataTableRemoting(string clientKey)
        {
            mLogHelper = TableHelper.GetLogHelper(clientKey);
            string message = "get new loghelper success.";
            mLogHelper.LogMessage(clientKey, message, LogType.Program);

            mClientKey = clientKey;
            NetClient netclient = NetClientManager.GetNetClient(clientKey);
            mHostName = netclient.HostName;
            mDBName = netclient.Database;
            message = "get net client success.";
            mLogHelper.LogMessage(clientKey, message, LogType.Program);

            mTableUnitManager = TableHelper.GetTableUnitManager(clientKey);
            message = "get table unit manager success.";
            mLogHelper.LogMessage(clientKey, message, LogType.Program);

            message = "get new DataTableRemoting.";
            mLogHelper.LogMessage(mClientKey, message, LogType.Program);
        }
Exemplo n.º 15
0
		public static void ComLogger_OnCommand(CommandEventArgs e)
		{
			LogHelper Logger = new LogHelper("Commoditydeed.log", true);

			foreach (Item m in World.Items.Values)
			{

				if (m != null)
				{
					if (m is CommodityDeed && ((CommodityDeed)m).Commodity != null)
					{
						string output = string.Format("{0}\t{1,-25}\t{2,-25}",
							m.Serial + ",", ((CommodityDeed)m).Commodity + ",", ((CommodityDeed)m).Commodity.Amount);

						Logger.Log(LogType.Text, output);
					}
				}
			}
			Logger.Finish();
		}
Exemplo n.º 16
0
		public static void FindItemByName_OnCommand(CommandEventArgs e)
		{
			if (e.Length == 1)
			{
				LogHelper Logger = new LogHelper("FindItemByName.log", e.Mobile, false);

				string name = e.GetString(0).ToLower();

				foreach (Item item in World.Items.Values)
					if (item.Name != null && item.Name.ToLower().IndexOf(name) >= 0)
						Logger.Log(LogType.Item, item);

				Logger.Finish();


			}
			else
			{
				e.Mobile.SendMessage("Format: FindItemByName <name>");
			}
		}
Exemplo n.º 17
0
		public static void FindItem_OnCommand(CommandEventArgs e)
		{
			if (e.Length > 1)
			{

				LogHelper Logger = new LogHelper("finditem.log", e.Mobile, false);

				// Extract property & value from command parameters

				string sProp = e.GetString(0);
				string sVal = "";

				if (e.Length > 2)
				{

					sVal = e.GetString(1);

					// Concatenate the strings
					for (int argi = 2; argi < e.Length; argi++)
						sVal += " " + e.GetString(argi);
				}
				else
					sVal = e.GetString(1);

				Regex PattMatch = new Regex("= \"*" + sVal, RegexOptions.IgnoreCase);

				// Loop through assemblies and add type if has property

				Type[] types;
				Assembly[] asms = ScriptCompiler.Assemblies;

				ArrayList MatchTypes = new ArrayList();

				for (int i = 0; i < asms.Length; ++i)
				{
					types = ScriptCompiler.GetTypeCache(asms[i]).Types;

					foreach (Type t in types)
					{

						if (typeof(Item).IsAssignableFrom(t))
						{

							// Reflect type
							PropertyInfo[] allProps = t.GetProperties(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public);

							foreach (PropertyInfo prop in allProps)
								if (prop.Name.ToLower() == sProp.ToLower())
									MatchTypes.Add(t);
						}
					}
				}

				// Loop items and check vs. types

				foreach (Item item in World.Items.Values)
				{
					Type t = item.GetType();
					bool match = false;

					foreach (Type MatchType in MatchTypes)
					{
						if (t == MatchType)
						{
							match = true;
							break;
						}
					}

					if (match == false)
						continue;

					// Reflect instance of type (matched)

					if (PattMatch.IsMatch(Properties.GetValue(e.Mobile, item, sProp)))
						Logger.Log(LogType.ItemSerial, item);

				}

				Logger.Finish();
			}
			else
			{
				// Badly formatted
				e.Mobile.SendMessage("Format: FindItem <property> <value>");
			}
		}
Exemplo n.º 18
0
		public static Spawner GetRandomSpawner(SpawnerType type)
		{
			// if still empty, fail
			if (m_Spawners.Count == 0)
				return null;

			Spawner spawner = null;
			Utility.TimeCheck tc = new Utility.TimeCheck();
			tc.Start();
			//try to find an appropriate spawner
			for (int count = 0; count < m_Spawners.Count * 2; ++count)
			{
				// pick one at random..
				Spawner random = m_Spawners[Utility.Random(m_Spawners.Count)] as Spawner;
				Region region = Server.Region.Find(random.Location, Map.Felucca);

				// test if this spawner satisfies type required
				switch (type)
				{
					case SpawnerType.Overland:
						{
							// Must be running
							if (!random.Running)
								continue;

							if (region != null)
							{	// No Towns
								if (IsTown(region.Name))
									continue;

								// no green acres, inside houses, etc..
								if (IsValidRegion(random.Location, region) == false)
									continue;
							}

							break;
						}

					default:
						{
							if (region != null)
							{
								// no green acres, inside houses, etc..
								if (IsValidRegion(random.Location, region) == false)
									continue;
							}

							break;
						}
				}

				//this is a good candidate!
				spawner = random;
				break;
			}
			tc.End();
			if (tc.Elapsed() > 30)
			{
				LogHelper logger = new LogHelper("SpawnerCache");
				logger.Log("Warning:  Spawner overland search took " + tc.Elapsed().ToString() + "ms");
			}

			return spawner;

		}
Exemplo n.º 19
0
        ///// <summary>
        ///// 系统日志 主动调用
        ///// </summary>
        //private readonly LogHelper _logHelper = new LogHelper(MethodBase.GetCurrentMethod().DeclaringType);

        /// <summary>
        /// 系统日志 对try块进行了封装
        /// </summary>
        /// <param name="type"></param>
        /// <param name="function">方法名称</param>
        /// <param name="errorHandel">异常处理方式</param>
        /// <param name="tryHandel">调试代码</param>
        /// <param name="catchHandel">异常处理方式</param>
        /// <param name="finallHandel">最终处理方式</param>
        public void Logger(Type type, string function, Action tryHandel, Action <Exception> catchHandel = null,
                           Action finallHandel = null, ErrorHandel errorHandel = ErrorHandel.Throw)
        {
            LogHelper.Logger(type, function, errorHandel, tryHandel, catchHandel, finallHandel);
        }
Exemplo n.º 20
0
        protected void Page_Load(object sender, EventArgs e)
        {
            tea = (Teacher)Session["loginuser"];
            TitleRecordBll trbll      = new TitleRecordBll();
            PathBll        pathBll    = new PathBll();
            Teacher        teacher    = (Teacher)Session["loginuser"];
            string         teaAccount = teacher.TeaAccount;

            collegeId = teacher.college.ColID;
            string addop = Context.Request.Form["op"];
            string type  = Request.QueryString["type"];

            op = Request["op"];
            try
            {
                if (op == "add")
                {
                    string         stuAccount = Request["stuAccount"];
                    string         opinion    = Request["opinion"];
                    GuideRecordBll guideBll   = new GuideRecordBll();
                    GuideRecord    guide      = new GuideRecord();
                    DataSet        dsTR       = trbll.GetByAccount(stuAccount);
                    int            i          = dsTR.Tables[0].Rows.Count - 1;
                    guide.opinion = opinion;
                    TitleRecord titleRecord = new TitleRecord();
                    titleRecord.TitleRecordId = Convert.ToInt32(dsTR.Tables[0].Rows[i]["titleRecordId"].ToString());
                    guide.titleRecord         = titleRecord;
                    guide.dateTime            = DateTime.Now;
                    path             = pathBll.Select(titleRecord.TitleRecordId, stuAccount);
                    guide.path       = path;
                    path.titleRecord = titleRecord;
                    path.state       = 1;
                    path.type        = 0;
                    Result result = pathBll.updateState(path);
                    if (result == Result.更新成功)
                    {
                        Result row = guideBll.Insert(guide);
                        if (row == Result.添加成功)
                        {
                            StudentBll studentBll = new StudentBll();
                            Student    stu        = studentBll.GetModel(stuAccount);
                            LogHelper.Info(this.GetType(), tea.TeaAccount + " - " + tea.TeaName + " - 教师添加 - " + stuAccount + " - " + stu.RealName + " - 学生的指导记录");
                            Response.Write("提交成功");
                            Response.End();
                        }
                        else
                        {
                            Response.Write("提交失败");
                            Response.End();
                        }
                    }
                    else
                    {
                        Response.Write("提交失败");
                        Response.End();
                    }
                }
                else if (op == "download")
                {
                    download = "download";
                    string account          = Request["stuAccount"];
                    Path   getTitleRecordId = pathBll.getTitleRecordId(account);
                    int    titleRecordId    = getTitleRecordId.titleRecord.TitleRecordId;
                    paperPath = pathBll.Select(titleRecordId, account);
                    //Response.Redirect(paperPath.paperPath);
                    Response.Write("<script>$('#loadHref').href = '" + paperPath.paperPath + "';</script>");
                    //Response.End();
                }
                if (!IsPostBack)
                {
                    Search();
                    getPage(Search());
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(this.GetType(), ex);
            }
        }
Exemplo n.º 21
0
    /// <summary>
    /// 繫結資料到控制項
    /// </summary>
    /// <param name="vdb"></param>
    private void databind(string strFLAG)
    {
        #region

        //抓取本頁初次登記的時間

        string SessionIDName = string.Format("{0}_{1}", PAGE_DT_01, PageTimeStamp.Value);

        STMModel.MaintainStoreBase BCO = new STMModel.MaintainStoreBase(ConnectionDB);

        ParameterList.Clear();

        //門市基本31
        TextBox txt_TELAREA = (TextBox)this.SLP_TEL_NO.FindControl("T1");
        TextBox txt_TELNO = (TextBox)this.SLP_TEL_NO.FindControl("T2");
        TextBox txt_FAXAREA = (TextBox)this.SLP_FAX_NO.FindControl("T1");
        TextBox txt_FAXNO = (TextBox)this.SLP_FAX_NO.FindControl("T2");

        ParameterList.Add(GetValueSetParameter(this.SLP_STORE.Text.Trim(),"string",CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_MDC_START_DATE.StartDate,"string",CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_MDC_START_DATE.EndDate,"string",CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_MDC_END_DATE.StartDate, "string", CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_MDC_END_DATE.EndDate, "string", CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_CHAN_NO.Text,"string",CheckBoxLikeSearch.Checked));;
        ParameterList.Add(GetValueSetParameter(this.SLP_GROUP_NO.Text,"string",CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.txtOLD_STORE.Text, "string", CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_STORE_OPEN_DATE.StartDate,"string",CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_STORE_OPEN_DATE.EndDate,"string",CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_STORE_CLOSE_DATE.StartDate,"string",CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_STORE_CLOSE_DATE.EndDate,"string",CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_REOPEN_DATE.StartDate,"string",CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_REOPEN_DATE.EndDate,"string",CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_REMODEL_DATE.StartDate,"string",CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_REMODEL_DATE.EndDate,"string",CheckBoxLikeSearch.Checked));      
        ParameterList.Add(GetValueSetParameter(this.SLP_Z_O.Text,"string",CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_D_O.Text,"string",CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_STORE_TYPE.Text,"string",CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.txtSTORE_ZIP.Text,"string",CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(txt_TELAREA.Text,"string",CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(txt_TELNO.Text,"string",CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(txt_FAXAREA.Text,"string",CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(txt_FAXNO.Text,"string",CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.txtSTORE_ADDRESS.Text,"string",CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_CREATE_DATE.StartDate,"string",CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_CREATE_DATE.EndDate,"string",CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_CREATE_UID.Text,"string",CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_UPDATE_DATE.StartDate,"string",CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_UPDATE_DATE.EndDate, "string", CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_UPDATE_UID.Text, "string", CheckBoxLikeSearch.Checked));
        
        //配送屬性17
        RadioButtonList rdo_DIS_SW = (RadioButtonList)this.SLP_DIS_SW.FindControl("R1");
        RadioButtonList rdo_MARKET_RESEARCH = (RadioButtonList)this.SLP_MARKET_RESEARCH.FindControl("R1");
        RadioButtonList rdo_SING_VEN = (RadioButtonList)this.SLP_SING_VEN.FindControl("R1");
        RadioButtonList rdo_MDC_TAXABLE = (RadioButtonList)this.SLP_MDC_TAXABLE.FindControl("R1");
        RadioButtonList rdo_MDC_TAXFREE = (RadioButtonList)this.SLP_MDC_TAXFREE.FindControl("R1");

        ParameterList.Add(GetValueSetParameter(this.SLP_AREA_NO.Text, "string", CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_AREA_CODE.Text, "string", CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_SHELVE_CM3.Text, "int", CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_ROUTE.Text, "string", CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.txtSTEP.Text, "string", CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.txtARRIVE_TIME.Text, "string", CheckBoxLikeSearch.Checked));

        if (rdo_DIS_SW.SelectedValue == "")
            ParameterList.Add(DBNull.Value);
        if (rdo_DIS_SW.SelectedValue == "1")
            ParameterList.Add(1);
        if (rdo_DIS_SW.SelectedValue == "0")
            ParameterList.Add(0);

        ParameterList.Add(this.ddlALLOCATION_TIMES.Text);
        ParameterList.Add(GetValueSetParameter(this.SLP_ALLOCATION_TIMES.Text, "int", CheckBoxLikeSearch.Checked));

        if (rdo_MARKET_RESEARCH.SelectedValue == "")
            ParameterList.Add(DBNull.Value);
        if (rdo_MARKET_RESEARCH.SelectedValue == "1")
            ParameterList.Add(1);
        if (rdo_MARKET_RESEARCH.SelectedValue == "0")
            ParameterList.Add(0);

        ParameterList.Add(GetValueSetParameter(this.SLP_AC_UID.Text, "string", CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_SAL_ID.Text, "string", CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_FEAT_GRADE.Text, "string", CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.txtPAY_RFNO.Text, "string", CheckBoxLikeSearch.Checked));

        if (rdo_SING_VEN.SelectedValue == "")
            ParameterList.Add(DBNull.Value);
        if (rdo_SING_VEN.SelectedValue == "1")
            ParameterList.Add(1);
        if (rdo_SING_VEN.SelectedValue == "0")
            ParameterList.Add(0);

        if (rdo_MDC_TAXABLE.SelectedValue == "")
            ParameterList.Add(DBNull.Value);
        if (rdo_MDC_TAXABLE.SelectedValue == "1")
            ParameterList.Add(1);
        if (rdo_MDC_TAXABLE.SelectedValue == "0")
            ParameterList.Add(0);
        
        if (rdo_MDC_TAXFREE.SelectedValue == "")
            ParameterList.Add(DBNull.Value);
        if (rdo_MDC_TAXFREE.SelectedValue == "1")
            ParameterList.Add(1);
        if (rdo_MDC_TAXFREE.SelectedValue == "0")
            ParameterList.Add(0);

        //屬性19
        CheckBox chk_W1 = (CheckBox)this.SLP_Boolean_W1.FindControl("C1");
        CheckBox chk_W2 = (CheckBox)this.SLP_Boolean_W2.FindControl("C1");
        CheckBox chk_W3 = (CheckBox)this.SLP_Boolean_W3.FindControl("C1");
        CheckBox chk_W4 = (CheckBox)this.SLP_Boolean_W4.FindControl("C1");
        CheckBox chk_W5 = (CheckBox)this.SLP_Boolean_W5.FindControl("C1");
        CheckBox chk_W6 = (CheckBox)this.SLP_Boolean_W6.FindControl("C1");
        CheckBox chk_W7 = (CheckBox)this.SLP_Boolean_W7.FindControl("C1");

        ParameterList.Add(GetValueSetParameter(this.txtCOPY_SOURCE.Text, "string", CheckBoxLikeSearch.Checked));
        ParameterList.Add(this.ddlPSM.Text);
        ParameterList.Add(GetValueSetParameter(this.SLP_PSM.Text, "int", CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_BUSINESS_NO.Text, "string", CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_OPEN_TIME.Text, "string", CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_CLOSE_TIME.Text, "string", CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_COMPETITION.Text, "string", CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_REMARK.Text, "string", CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_STORE_SPE.Text, "string", CheckBoxLikeSearch.Checked));
        ParameterList.Add(chk_W1.Checked ? "1" : null);
        ParameterList.Add(chk_W2.Checked ? "1" : null);
        ParameterList.Add(chk_W3.Checked ? "1" : null);
        ParameterList.Add(chk_W4.Checked ? "1" : null);
        ParameterList.Add(chk_W5.Checked ? "1" : null);
        ParameterList.Add(chk_W6.Checked ? "1" : null);
        ParameterList.Add(chk_W7.Checked ? "1" : null);
        ParameterList.Add(GetValueSetParameter(this.SLP_SHELF_NO.Text, "string", CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_DISPLAY_NUM.Text, "int", CheckBoxLikeSearch.Checked));
        ParameterList.Add(GetValueSetParameter(this.SLP_SHELVE_CM3_2.Text, "int", CheckBoxLikeSearch.Checked));

        ParameterList.Add(GetValueSetParameter(this.txtStoreName.Text, "string", CheckBoxLikeSearch.Checked)); //2010/06/14新增店名查詢欄位

        if (strFLAG != "EXCEL")
        {
            DataTable Dt = BCO.QuerySwitch(STMModel.MaintainStoreBase.QueryType.QueryByLike, ParameterList);
            int iRowCount = (this.TextBoxRowCountLimit.Text.Trim() == string.Empty) ? 9999 : int.Parse(TextBoxRowCountLimit.Text);
            while (Dt.Rows.Count > iRowCount)
            {
                DataRow dr = Dt.Rows[Dt.Rows.Count - 1];
                dr.Delete();
                Dt.AcceptChanges();
            }
            Session[SessionIDName] = Dt;
            GridView1.DataSource = Dt;

            //設定分頁大小
            GridView1.PageSize = (TextBoxPagesize.Text == "") ? 10 : (int.Parse(TextBoxPagesize.Text) < 0) ? 10 : int.Parse(TextBoxPagesize.Text);
            GridView1.PageIndex = 0;
            GridView1.DataBind();

            LabelQueryRecordCount.Text = string.Format(" {0} Rows ", Dt.Rows.Count.ToString());

            if (Dt == null || (Dt != null && Dt.Rows.Count <= 0))
            {
                ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "ClientScript", "alert('查無資料');", true);
            }

            #region 將Key值存到Session中

            ArrayList arl_Key = new ArrayList();

            foreach (DataRow drRow in Dt.Rows)
            { arl_Key.Add("store=" + drRow["STORE"].ToString() + "&date=" + drRow["MDC_START_DATE"].ToString()); }

            Session["STM012_SortKey" + this.PageTimeStamp.Value] = arl_Key;
        }
        else
        {
            DataTable Dt1 = BCO.QuerySwitch(STMModel.MaintainStoreBase.QueryType.Excel, ParameterList);
            int iRowCount = (this.TextBoxRowCountLimit.Text.Trim() == string.Empty) ? 9999 : int.Parse(TextBoxRowCountLimit.Text);
            while (Dt1.Rows.Count > iRowCount)
            {
                DataRow dr = Dt1.Rows[Dt1.Rows.Count - 1];
                dr.Delete();
                Dt1.AcceptChanges();
            }

            for (int j = 0; j < Dt1.Rows.Count; j++)
            {
                LogHelper LOG = new LogHelper(ConnectionDB);
                ParameterList.Clear();
                ParameterList.Add("STM01門市主檔");//0
                ParameterList.Add(Session["UID"].ToString());//1
                ParameterList.Add("O");//2
                ParameterList.Add(Dt1.Rows[j]["STORE"].ToString());//3
                ParameterList.Add(Request.ServerVariables["Server_Name"]);//4

                LOG.AddSafeLog(ParameterList);
            }

                Session[SessionIDName] = Dt1;
        }

        #endregion

        #endregion
    }//databind
Exemplo n.º 22
0
        public LoginWindow()
        {
            InitializeComponent();

            string versionValue = string.Empty;

            try
            {
                XmlDocument doc      = new XmlDocument();
                String      CurrPath = Directory.GetCurrentDirectory().Trim();
                if (CurrPath.EndsWith("upgrade"))
                {
                    doc.Load(@"config.xml");
                }
                else
                {
                    doc.Load(@"upgrade\config.xml");
                }
                XmlElement root = doc.DocumentElement;

                foreach (XmlElement item in root.ChildNodes)
                {
                    string codeTxt = string.Empty;
                    string nameTxt = string.Empty;
                    if (item.Name == "CurrVersion")
                    {
                        versionValue = item.ChildNodes[0].Value;
                        break;
                    }
                }
            }
            catch (Exception err)
            {
                LogHelper.WriteWarnLog("Get version failed:" + err.Message);
                versionValue = Properties.Settings.Default.app_version;
            }

            competent_organization.Content = Properties.Settings.Default.competent_organization;
            province.Content        = Properties.Settings.Default.province;
            app_type.Content        = Properties.Settings.Default.app_type;
            app_name.Content        = Properties.Settings.Default.app_name + "V" + versionValue;
            support_company.Content = Properties.Settings.Default.support_company;
            support_tel.Content     = Properties.Settings.Default.support_tel;
            RESTClient.REST_HOST    = Properties.Settings.Default.rest_host;

            if (!Directory.Exists(CommDef.ApplicationDataPath))
            {
                Directory.CreateDirectory(CommDef.ApplicationDataPath);
            }

            string computerInfo    = ComputerInfo.GetComputerInfo();
            string encryptComputer = new EncryptionHelper().EncryptString(computerInfo);

            EncryptionHelper help       = new EncryptionHelper(EncryptionKeyEnum.KeyB);
            string           md5String  = help.GetMD5String(encryptComputer);
            string           registInfo = help.EncryptString(md5String);

            //判断是否已经运行
            Process selfProcess = Process.GetCurrentProcess();

            Process[] allProcess = Process.GetProcessesByName("SignInApp");
            foreach (Process item in allProcess)
            {
                if (item.Id != selfProcess.Id)
                {
                    item.Kill();
                }
            }

            if (RegistFileHelper.ExistRegistInfofile() == true)
            {
                string inputRegist = RegistFileHelper.ReadRegistFile();
                if (registInfo == inputRegist)
                {
                    if (File.Exists(CONF_FILE_NAME) == false)
                    {
                        FileStream fs = new FileStream(CONF_FILE_NAME, FileMode.CreateNew);
                        if (fs != null)
                        {
                            fs.Close();
                        }
                        return;
                    }

                    string userName   = "";
                    string password   = "";
                    string isRemember = "";
                    bool   ret        = GetConfInfo(ref userName, ref password, ref isRemember);
                    if (ret)
                    {
                        if (userName != "")
                        {
                            account.Text            = userName;
                            this.account.Foreground = new SolidColorBrush(System.Windows.Media.Color.FromRgb(0x00, 0x00, 0x00));
                        }

                        if (isRemember == "true")
                        {
                            this.password.Password    = password;
                            this.remainFlag.IsChecked = true;
                        }
                    }
                    return;
                }
            }
            RegistWindow RegistWindowPage = new RegistWindow();

            RegistWindowPage.Show();
            this.Close();
        }
        public override void MTL_CarOutRequest(object sender, ValueChangedEventArgs args)
        {
            var recevie_function =
                scApp.getFunBaseObj <MtlToOHxC_MtlCarOutRepuest>(MTL.EQPT_ID) as MtlToOHxC_MtlCarOutRepuest;
            var send_function =
                scApp.getFunBaseObj <OHxCToMtl_MtlCarOutReply>(MTL.EQPT_ID) as OHxCToMtl_MtlCarOutReply;

            try
            {
                recevie_function.Read(bcfApp, MTL.EqptObjectCate, MTL.EQPT_ID);
                LogHelper.Log(logger: logger, LogLevel: LogLevel.Info, Class: nameof(MTLValueDefMapActionNew), Device: DEVICE_NAME_MTL,
                              Data: recevie_function.ToString(),
                              VehicleID: MTL.EQPT_ID);
                int    pre_car_out_vh_num = recevie_function.CarID;
                ushort hand_shake         = recevie_function.Handshake;
                if (hand_shake == 1)
                {
                    send_function.ReturnCode = 1;
                    if (recevie_function.Canacel == 1)
                    {
                        scApp.MTLService.carOutRequestCancle(MTL);
                        LogHelper.Log(logger: logger, LogLevel: LogLevel.Info, Class: nameof(MTSValueDefMapActionNew), Device: DEVICE_NAME_MTL,
                                      Data: $"Process MTL car out cancel",
                                      VehicleID: MTL.EQPT_ID);
                    }
                    else
                    {
                        AVEHICLE      pre_car_out_vh       = scApp.VehicleBLL.cache.getVhByNum(pre_car_out_vh_num);
                        MaintainSpace maintainSpace        = scApp.EquipmentBLL.cache.GetMaintainSpace();//todo 之後會有兩個MTS 要知道是哪個MTS
                        var           car_out_check_result = scApp.MTLService.checkVhAndMTxCarOutStatus(this.MTL, maintainSpace, pre_car_out_vh);
                        send_function.ReturnCode = car_out_check_result.isSuccess ? (ushort)1 : (ushort)2;
                        LogHelper.Log(logger: logger, LogLevel: LogLevel.Info, Class: nameof(MTLValueDefMapActionNew), Device: DEVICE_NAME_MTL,
                                      Data: $"Process MTL car out request, is success:{car_out_check_result.isSuccess},result:{car_out_check_result.result}",
                                      VehicleID: MTL.EQPT_ID);
                    }
                }
                else
                {
                    send_function.ReturnCode = 0;
                }
                send_function.Handshake = hand_shake == 0 ? (ushort)0 : (ushort)1;
                send_function.Write(bcfApp, MTL.EqptObjectCate, MTL.EQPT_ID);

                LogHelper.Log(logger: logger, LogLevel: LogLevel.Info, Class: nameof(MTLValueDefMapActionNew), Device: DEVICE_NAME_MTL,
                              Data: send_function.ToString(),
                              VehicleID: MTL.EQPT_ID);
                MTL.SynchronizeTime = DateTime.Now;
                //if (send_function.Handshake == 1 && send_function.ReturnCode == 1)
                if (send_function.Handshake == 1 && send_function.ReturnCode == 1 && recevie_function.Canacel != 1)
                {
                    AVEHICLE pre_car_out_vh = scApp.VehicleBLL.cache.getVhByNum(pre_car_out_vh_num);
                    scApp.MTLService.processCarOutScenario(MTL, pre_car_out_vh);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Exception");
            }
            finally
            {
                scApp.putFunBaseObj <MtlToOHxC_MtlCarOutRepuest>(recevie_function);
                scApp.putFunBaseObj <OHxCToMtl_MtlCarOutReply>(send_function);
            }
        }
Exemplo n.º 24
0
 public void TestFixtureTearDown()
 {
     LogHelper.ResetLogging();
 }
Exemplo n.º 25
0
		public static void TrackIt(Mobile from, string text, bool accomplice)
		{
			LogHelper Logger = new LogHelper("Cheater.log", false);
			Logger.Log(LogType.Mobile, from, text);
			if (accomplice == true)
			{
				IPooledEnumerable eable = from.GetMobilesInRange(24);
				foreach (Mobile m in eable)
				{
					if (m is PlayerMobile && m != from)
						Logger.Log(LogType.Mobile, m, "Possible accomplice.");
				}
				eable.Free();
			}
			Logger.Finish();
		}
Exemplo n.º 26
0
        public IHttpActionResult Get(int CurrentPage, string Date = "", string Name = "")
        {
            //申明参数
            int _pageSize = 10;
            int count     = 1;

            try
            {
                Response <IEnumerable <SeeDoctorHistory> > response = new Response <IEnumerable <SeeDoctorHistory> >();

                PageInfo pageInfo = new PageInfo()
                {
                    PageIndex  = CurrentPage,
                    PageSize   = _pageSize,
                    OrderField = "DIAGNOSISTIME",
                    Order      = OrderEnum.desc
                };

                Expression <Func <HR_SEEDOCTORHISTORY, bool> > predicate = p => true;
                if (!string.IsNullOrEmpty(Date) && string.IsNullOrEmpty(Name))
                {
                    DateTime dt = DateTime.Parse(Date);
                    predicate = p => p.DIAGNOSISTIME == dt;
                }
                else if (string.IsNullOrEmpty(Date) && !string.IsNullOrEmpty(Name))
                {
                    UserInfoService service = new UserInfoService();
                    List <UserInfo> users   = service.GetList(Name);
                    if (users == null)
                    {
                        response.Data       = null;
                        response.PagesCount = 1;

                        return(Ok(response));
                    }

                    IEnumerable <string> ids = (from o in users select o.UserId).ToList();

                    predicate = p => ids.Contains(p.PERSONID);
                }
                else if (!string.IsNullOrEmpty(Date) && !string.IsNullOrEmpty(Name))
                {
                    UserInfoService service = new UserInfoService();
                    List <UserInfo> users   = service.GetList(Name);
                    if (users == null)
                    {
                        response.Data       = null;
                        response.PagesCount = 1;

                        return(Ok(response));
                    }

                    IEnumerable <string> ids = (from o in users select o.UserId).ToList();
                    DateTime             dt  = DateTime.Parse(Date);

                    predicate = p => ids.Contains(p.PERSONID) && p.DIAGNOSISTIME == dt;
                }

                var list = bll.GetList(pageInfo, predicate);
                count = pageInfo.Total / _pageSize;
                if (pageInfo.Total % _pageSize > 0)
                {
                    count += 1;
                }

                response.Data       = list;
                response.PagesCount = count;

                return(Ok(response));
            }
            catch (Exception ex)
            {
                LogHelper.WriteInfo(ex.ToString());
                return(BadRequest("异常"));
            }
        }
Exemplo n.º 27
0
 public void TestFixtureSetUp()
 {
     LogHelper.ConfigureLogging();
     LogHelper.SetLoggingLevel(Level.Info);
 }
Exemplo n.º 28
0
 public Pump_Jasco_PU_4180(LogHelper log) : base(log)
 {
     settings = new Pump_Jasco_PU_4180_Setting();
     log.Add("Initializing Jasco PU-4180 HPLC pump");
 }
Exemplo n.º 29
0
        public string Update(HttpContext context)
        {
            string strResult = "";
            string realName  = context.Request["realName"];
            string post      = context.Request["post"];
            string sex       = string.IsNullOrWhiteSpace(context.Request["Sexs"]) ? "男" : context.Request["Sexs"];
            string mobile    = context.Request["mobile"];
            string phone     = context.Request["phone"];
            string qq        = context.Request["qq"];
            string email     = context.Request["email"];
            string address   = context.Request["address"];
            string zip       = context.Request["zip"];

            try
            {
                if (address.Length < 7)
                {
                    return("{ \"result\": false,\"msg\": \"地址长度不正确!\"}");
                }
                var user = RequestSession.GetSessionUser();
                if (user != null)
                {
                    using (var db = new UdowsYunPublicEntities())
                    {
                        int?started = db.Company.Find(user.CompanyId)?.stateId;
                        if (started == 2)
                        {
                            return("{ \"result\": false,\"msg\": \"已审核通过,不可修改!\"}");
                        }
                        string         newsLabel = "";
                        List <Company> n         = db.Company.Where(p => p.userId == user.id).ToList();
                        if (n.Any())
                        {
                            foreach (var val in n)
                            {
                                var c = db.Company.Find(val.id);
                                c.realName = realName.Trim().Replace(" ", "");
                                c.post     = post.Trim().Replace(" ", "");
                                c.sex      = sex.Trim().Replace(" ", "");
                                c.mobile   = mobile.Trim().Replace(" ", "");
                                c.phone    = phone.Trim().Replace(" ", "");
                                c.qq       = qq.Trim().Replace(" ", "");
                                c.email    = email.Trim().Replace(" ", "");
                                c.address  = address.Trim().Replace(" ", "");
                                c.zip      = zip.Trim().Replace(" ", "");
                                c.FastDefaultStringReplace <Company>();
                            }
                            db.SaveChanges();
                            strResult = "{ \"result\": true,\"msg\": \"修改成功!\"}";
                        }
                        else
                        {
                            strResult = "{ \"result\": false,\"msg\": \"请先补充公司资料!\"}";
                        }
                    }
                }
                else
                {
                    strResult = "{ \"result\": false,\"msg\": \"登录超时,请重新登录!\"}";
                }
            }
            catch (DbEntityValidationException e)
            {
                LogHelper lh = new LogHelper();
                lh.WriteLog(e.EntityValidationErrors.ToString());
                strResult = "{ \"result\": false,\"msg\": \"" + e.EntityValidationErrors + "\"}";
            }
            return(strResult);
        }
Exemplo n.º 30
0
        /// <summary>
        /// 创建"县级公司"房地信息汇总表模板(前两行,字段;第三行,总计)
        /// </summary>
        /// <returns></returns>
        public static Table Template_country(DocX document)
        {
            Table t = null;

            try
            {
                t = document.AddTable(3, 14);

                #region "前三行"
                t.Rows[0].Cells[0].Paragraphs.First().Append("序号").Bold().Alignment         = Alignment.center;
                t.Rows[0].Cells[1].Paragraphs.First().Append("地块名称").Bold().Alignment       = Alignment.center;
                t.Rows[0].Cells[2].Paragraphs.First().Append("地块占地面积(m2)").Bold().Alignment = Alignment.center;
                t.Rows[0].Cells[3].Paragraphs.First().Append("建筑名称").Bold().Alignment       = Alignment.center;
                t.Rows[0].Cells[4].Paragraphs.First().Append("建筑层数").Bold().Alignment       = Alignment.center;
                t.Rows[0].Cells[6].Paragraphs.First().Append("建筑结构").Bold().Alignment       = Alignment.center;
                t.Rows[0].Cells[7].Paragraphs.First().Append("建筑年代").Bold().Alignment       = Alignment.center;
                t.Rows[0].Cells[8].Paragraphs.First().Append("建筑面积(m2)").Bold().Alignment   = Alignment.center;
                t.Rows[0].Cells[11].Paragraphs.First().Append("具体使用功能").Bold().Alignment    = Alignment.center;
                t.Rows[0].Cells[12].Paragraphs.First().Append("使用部门").Bold().Alignment      = Alignment.center;
                t.Rows[0].Cells[13].Paragraphs.First().Append("备注").Bold().Alignment        = Alignment.center;
                t.Rows[1].Cells[4].Paragraphs.First().Append("地上").Bold().Alignment         = Alignment.center;
                t.Rows[1].Cells[5].Paragraphs.First().Append("地下").Bold().Alignment         = Alignment.center;
                t.Rows[1].Cells[8].Paragraphs.First().Append("总体").Bold().Alignment         = Alignment.center;
                t.Rows[1].Cells[9].Paragraphs.First().Append("地上").Bold().Alignment         = Alignment.center;
                t.Rows[1].Cells[10].Paragraphs.First().Append("地下").Bold().Alignment        = Alignment.center;
                t.Rows[2].Cells[0].Paragraphs.First().Append("合计").Bold().Alignment         = Alignment.center;

                t.Rows[0].Cells[0].VerticalAlignment  = VerticalAlignment.Center;//垂直居中
                t.Rows[0].Cells[1].VerticalAlignment  = VerticalAlignment.Center;
                t.Rows[0].Cells[2].VerticalAlignment  = VerticalAlignment.Center;
                t.Rows[0].Cells[3].VerticalAlignment  = VerticalAlignment.Center;
                t.Rows[0].Cells[4].VerticalAlignment  = VerticalAlignment.Center;
                t.Rows[0].Cells[6].VerticalAlignment  = VerticalAlignment.Center;
                t.Rows[0].Cells[7].VerticalAlignment  = VerticalAlignment.Center;
                t.Rows[0].Cells[8].VerticalAlignment  = VerticalAlignment.Center;
                t.Rows[0].Cells[11].VerticalAlignment = VerticalAlignment.Center;
                t.Rows[0].Cells[12].VerticalAlignment = VerticalAlignment.Center;
                t.Rows[0].Cells[13].VerticalAlignment = VerticalAlignment.Center;
                t.Rows[1].Cells[4].VerticalAlignment  = VerticalAlignment.Center;
                t.Rows[1].Cells[5].VerticalAlignment  = VerticalAlignment.Center;
                t.Rows[1].Cells[8].VerticalAlignment  = VerticalAlignment.Center;
                t.Rows[1].Cells[9].VerticalAlignment  = VerticalAlignment.Center;
                t.Rows[1].Cells[10].VerticalAlignment = VerticalAlignment.Center;
                t.Rows[2].Cells[0].VerticalAlignment  = VerticalAlignment.Center;

                //单元格合并操作(先竖向合并,再横向合并,以免报错,因为横向合并会改变列数)
                t.MergeCellsInColumn(0, 0, 1);
                t.MergeCellsInColumn(1, 0, 1);
                t.MergeCellsInColumn(2, 0, 1);
                t.MergeCellsInColumn(3, 0, 1);
                t.MergeCellsInColumn(6, 0, 1);
                t.MergeCellsInColumn(7, 0, 1);
                t.MergeCellsInColumn(11, 0, 1);
                t.MergeCellsInColumn(12, 0, 1);
                t.MergeCellsInColumn(13, 0, 1);
                t.Rows[0].MergeCells(4, 5);
                t.Rows[0].MergeCells(7, 9);
                #endregion
            }
            catch (System.Exception ex)
            {
                LogHelper.WriteLog(typeof(tableHelper), ex);
            }
            return(t);
        }
Exemplo n.º 31
0
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="configPath"></param>
        /// <returns></returns>
        public static ILog GetInstance(string configPath)
        {
            logHelper = new LogHelper(configPath);

            return log;
        }
Exemplo n.º 32
0
		public override void OnResponse( NetState state, int index )
		{
            //pla, 03/10/07
            // Log help stuck attempt
            if (index != 2)
            {
                LogHelper log = new LogHelper("HelpStuck.log");
                if (log != null)
                {
                    log.Log(LogType.Mobile, state.Mobile);
                    log.Finish();
                }
            }
			if ( index == 0 )
			{
				bool bGood = false;
				if (m_From.Alive == false) //dead: always allow to transport
				{
					bGood = true;
				}
				else if (m_From.Region is Regions.FeluccaDungeon) //alive and in dungeon
				{
					m_From.SendMessage("You have chosen to die.");
					m_From.Kill();
					bGood = true;
				}
				else if (m_From.TotalWeight < StuckMenu.MAXHELPSTUCKALIVEWEIGHT) //alive and out of dungeon and not over weight limit
				{
					bGood = true;
				}
				else // alive, out of dungeon, over weight limit
				{
					m_From.SendMessage("You are too encumbered to be moved, drop most of your stuff and help-stuck again.");
				}

				if (bGood)
				{
					//auto-choose destination now, so don't give them this message
					//m_From.SendMessage("You will now be given the standard help-stuck menu.");

					StuckMenu menu = new StuckMenu(m_From, m_From, true, true);
					//menu.BeginClose();
					//m_From.SendGump(menu);
					menu.AutoSelect();
				}
			}
			else if ( index == 1 )
			{
				if (!HelpGump.TryMoveStuckPlayer(m_From, 4))
				{
					int staffonline = 0;
					foreach (NetState ns in NetState.Instances)
					{
						Mobile m = ns.Mobile;
						if (m != null && m.AccessLevel >= AccessLevel.Counselor && m.AutoPageNotify)
							staffonline++;
					}

					if (staffonline == 0)
					{
						StuckMenu menu = new StuckMenu(m_From, m_From, true);
						//menu.BeginClose();
						//m_From.SendGump(menu);
						menu.AutoSelect();
					}
				}
			}
			else if (index == 2)
			{
				m_From.SendMessage("Help Stuck request cancelled.");
			}
		}
Exemplo n.º 33
0
        private void RefreshCurrentNotes()
        {
            NoteManager noteManager = new NoteManager(SysConfigInfo.WebServerBaseAddr);
            Response <SearchNotesResponse> response = null;

            if (this.titleRadioButton.Checked)
            {
                response = noteManager.SearchNotesByTitleAndAuthorId(new SearchNotesByKeyStrAndAuthorIdRequest()
                {
                    AuthorId  = SysConfigInfo.OnlineUser.Id,
                    KeyStr    = this.keystrTextBox.Text,
                    PageIndex = this.index,
                    PageSize  = this.PageSize
                },
                                                                     new TokenCheckInfo()
                {
                    Token   = SysConfigInfo.OnlineUser.Token,
                    UserId  = SysConfigInfo.OnlineUser.Id,
                    Version = SysConfigInfo.Version
                });
            }
            else if (this.remarkRadioButton.Checked)
            {
                response = noteManager.SearchNotesByRemarkAndAuthorId(new SearchNotesByKeyStrAndAuthorIdRequest()
                {
                    AuthorId  = SysConfigInfo.OnlineUser.Id,
                    KeyStr    = this.keystrTextBox.Text,
                    PageIndex = this.index,
                    PageSize  = this.PageSize
                },
                                                                      new TokenCheckInfo()
                {
                    Token   = SysConfigInfo.OnlineUser.Token,
                    UserId  = SysConfigInfo.OnlineUser.Id,
                    Version = SysConfigInfo.Version
                });
            }
            else
            {
                response = noteManager.SearchNotesByTimeSpanAndAuthorId(new SearchNotesByTimeSpanAndAuthorIdRequest()
                {
                    AuthorId  = SysConfigInfo.OnlineUser.Id,
                    StartTime = this.startDateTimePicker.Value,
                    EndTime   = this.endDateTimePicker.Value,
                    PageIndex = this.index,
                    PageSize  = this.PageSize
                },
                                                                        new TokenCheckInfo()
                {
                    Token   = SysConfigInfo.OnlineUser.Token,
                    UserId  = SysConfigInfo.OnlineUser.Id,
                    Version = SysConfigInfo.Version
                });
            }

            if (response == null)
            {
                MessageBox.Show("找不到指定的服务!");
            }
            else
            {
                if (response.Code != 0 || response.ResponseData == null || !response.HasAccessed)
                {
                    MessageBox.Show(response.Description);
                    LogHelper.WriteLog(LogType.Info, this.GetType().ToString(), "RefreshCurrentNotes", response.Description);
                }
                else
                {
                    this.totalRows = response.ResponseData.TotalRows;
                    this.notes.Clear();

                    if (response.ResponseData.Notes != null)
                    {
                        foreach (Note note in response.ResponseData.Notes)
                        {
                            ListNoteUnit unit = new ListNoteUnit();
                            unit.Init(note);
                            this.notes.Add(unit);
                        }
                    }

                    this.ReloadNoteUnits();
                }
            }
        }
Exemplo n.º 34
0
        private void LoginHandler()
        {
            string strAccount  = "";
            string strPassword = "";

            this.Dispatcher.Invoke(() => {
                strAccount  = this.account.Text;
                strPassword = this.password.Password;
            });

            string outMessage = "";
            string response   = RESTClient.Login(strAccount, strPassword, ref outMessage, Properties.Settings.Default.Test);

            if (response == null || response == "")
            {
                if (outMessage == "")
                {
                    outMessage = "登录失败,服务器错误";
                }
                this.Dispatcher.Invoke(() => {
                    broder_back.Visibility     = Visibility.Collapsed;
                    _loading.Visibility        = Visibility.Collapsed;
                    WarningTipWindow tipDialog = new WarningTipWindow(outMessage);
                    tipDialog.ShowDialog();
                });
                LogHelper.WriteWarnLog(outMessage);
                return;
            }

            try
            {
                JObject jResp  = (JObject)JsonConvert.DeserializeObject(response);
                String  status = (String)jResp.SelectToken("status", true);
                if (status != "success")
                {
                    string message = (String)jResp.SelectToken("message", true);
                    this.Dispatcher.Invoke(() => {
                        broder_back.Visibility     = Visibility.Collapsed;
                        _loading.Visibility        = Visibility.Collapsed;
                        WarningTipWindow tipDialog = new WarningTipWindow("登录失败:" + message);
                        tipDialog.ShowDialog();
                    });
                    LogHelper.WriteWarnLog(strAccount + "登录失败:" + message);
                    return;
                }

                JArray jArray = (JArray)jResp.SelectToken("data", true);
                if (jArray == null || jArray.Count == 0)
                {
                    this.Dispatcher.Invoke(() => {
                        broder_back.Visibility     = Visibility.Collapsed;
                        _loading.Visibility        = Visibility.Collapsed;
                        WarningTipWindow tipDialog = new WarningTipWindow("登录失败,data为空");
                        tipDialog.ShowDialog();
                    });
                    LogHelper.WriteWarnLog(strAccount + "登录失败: data为空");
                    return;
                }

                JToken jToken = null;
                foreach (var item in jArray)
                {
                    jToken = item;
                    break;
                }

                LogHelper.WriteInfoLog(strAccount + "登录成功");
                string sessionid = (String)jToken.SelectToken("sessionid", true);
                RESTClient.SESSION_ID = sessionid;
                Org org = new Org();
                org.id      = (long)jToken.SelectToken("org_id", true);
                org.name    = (String)jToken.SelectToken("org_name", true);
                org.address = (String)jToken.SelectToken("address", true);
                this.Dispatcher.Invoke(() => {
                    broder_back.Visibility = Visibility.Collapsed;
                    _loading.Visibility    = Visibility.Collapsed;
                    MainWindow mainWindow  = new MainWindow(org);
                    mainWindow.Show();
                    this.Close();
                });
                return;
            }
            catch (Exception err)
            {
                this.Dispatcher.Invoke(() => {
                    broder_back.Visibility     = Visibility.Collapsed;
                    _loading.Visibility        = Visibility.Collapsed;
                    WarningTipWindow tipDialog = new WarningTipWindow(strAccount + "登录失败," + err.Message);
                    tipDialog.ShowDialog();
                });
                return;
            }
        }
Exemplo n.º 35
0
 public EcShippingMethodInit()
 {
     log = LogFactory.GetLogger(LogType.QuartzLog);
 }
Exemplo n.º 36
0
    /// <summary>
    ///   requested by the head teller
    /// </summary>
    /// <param name="messageCode">
    ///   Expected: test, announce
    /// </param>
    /// <param name="testPhoneNumber">Used when Testing </param>
    /// <param name="text"></param>
    /// <param name="idList"></param>
    /// <returns></returns>
    public JsonResult SendHeadTellerMessage(string idList)
    {
      // var htMessageCode = messageCode.AsEnum(HtEmailCodes._unknown_);
      //
      // if (htMessageCode == HtEmailCodes._unknown_)
      // {
      //   return new
      //   {
      //     Success = false,
      //     Status = "Invalid request"
      //   }.AsJsonResult();
      // }
      //

      var db = UserSession.GetNewDbContext;
      var now = DateTime.Now;
      var hostSite = SettingsHelper.Get("HostSite", "");

      var election = UserSession.CurrentElection;
      var text = election.SmsText;

      if (text.HasNoContent())
      {
        return new
        {
          Success = false,
          Status = "SMS text not set"
        }.AsJsonResult();
      }

      var phoneNumbersToSendTo = new List<NamePhone>();

      // switch (htMessageCode)
      // {
      //   case HtEmailCodes.Test:
      //     phoneNumbersToSendTo.Add(new NamePhone
      //     {
      //       Phone = testPhoneNumber, 
      //       PersonName = election.EmailFromNameWithDefault,
      //       FirstName = "(voter's first name)",
      //       VoterContact = testPhoneNumber
      //     });
      //     break;
      //
      //   case HtEmailCodes.Intro:
      var personIds = idList.Replace("[", "").Replace("]", "").Split(',').Select(s => s.AsInt()).ToList();

      phoneNumbersToSendTo.AddRange(db.Person
        .Where(p => p.ElectionGuid == election.ElectionGuid && p.Phone != null && p.Phone.Trim().Length > 0)
        .Where(p => p.CanVote.Value)
        .Where(p => personIds.Contains(p.C_RowId))
        .Select(p => new NamePhone
        {
          Phone = p.Phone,
          PersonName = p.C_FullNameFL,
          FirstName = p.FirstName,
          VoterContact = p.Phone,
          PersonGuid = p.PersonGuid
        })
      );
      //     break;
      //
      //   default:
      //     // not possible
      //     return null;
      // }

      // var whenOpen = election.OnlineWhenOpen.GetValueOrDefault();
      // var whenOpenUtc = whenOpen.ToUniversalTime();
      // var openIsFuture = whenOpen - now > 0.minutes();
      //
      // var whenClosed = election.OnlineWhenClose.GetValueOrDefault();
      // var whenClosedUtc = whenClosed.ToUniversalTime();
      // var remainingTime = whenClosed - now;
      // var howLong = "";
      // if (remainingTime.Days > 1)
      // {
      //   howLong = remainingTime.Days + " days";
      // }
      // else
      // {
      //   howLong = remainingTime.Hours + " hours";
      // }

      // var numSmsSegments = text.Length / 160;

      var numSent = 0;
      var errors = new List<string>();
      var numToSend = phoneNumbersToSendTo.Count;

      LogHelper.Add($"Sms: Sending to {numToSend} {numToSend.Plural("people", "person")} (see above)", true);
      var startTime = DateTime.Now;
      
      phoneNumbersToSendTo.ForEach(p =>
      {
        var phoneNumber = p.Phone;

        if (!PhoneNumberChecker.IsMatch(phoneNumber))
        {
          errors.Add("Invalid phone number: " + phoneNumber);
          return;
        }

        var messageText = text.FilledWithObject(new
        {
          hostSite,
          p.PersonName,
          p.FirstName,
          p.VoterContact,
        });

        var ok = SendSms(phoneNumber, messageText, p.PersonGuid, out var errorMessage);

        if (ok)
          numSent++;
        else
          errors.Add(errorMessage);
      });

      var seconds = (DateTime.Now - startTime).TotalSeconds.AsInt();

      var msg2 = $"Sms: Sent to {numSent} {numSent.Plural("people", "person")} in {seconds} second{seconds.Plural()}";
      if (errors.Count > 0) msg2 = $" - {errors.Count} failed to send. First error: {errors[0]}";
      LogHelper.Add(msg2, true);

      return new
      {
        Success = numSent > 0,
        Status = msg2
      }.AsJsonResult();
    }
Exemplo n.º 37
0
        public static void PrintRightTag(YKBoxInfo box,List<MaterialInfo> mats)
        {
            try
            {
                int skuCount = 0;
                if(box.Details!=null && box.Details.Count>0)
                {
                    skuCount = box.Details.Select(i => i.Matnr).Distinct().Count();
                }
                string filepath = "";
                if (skuCount>1)
                {
                    filepath = Application.StartupPath + "\\LabelMultiSku.mrt";
                }
                else if(skuCount == 1)
                {
                    filepath = Application.StartupPath + "\\LabelSku.mrt";
                }
                if(filepath == "")
                {
                    throw new Exception("no sku");
                }

                StiReport report = new StiReport();
                report.Load(filepath);
                report.Compile();

                if(skuCount>1)
                {
                    //multi
                    report["HU"] = box.Hu;
                    report["STORAGETYPE"] = box.Target;

                    string content = "";
                    List<string> matnrlist = box.Details.Select(i => i.Matnr).Distinct().ToList();
                    foreach (string matnr in matnrlist)
                    {
                        string zsatnr = box?.Details?.First(i => i.Matnr == matnr).Zsatnr;
                        string zcolsn = box?.Details?.First(i => i.Matnr == matnr).Zcolsn;
                        string zsiztx = box?.Details?.First(i => i.Matnr == matnr).Zsiztx;
                        int count = box.Details.FindAll(i => i.Matnr == matnr).Count;

                        string controlFlag = "";
                        controlFlag = mats.FirstOrDefault(i => i.MATNR == matnr).PUT_STRA;

                        content += string.Format("|{0,-13}|{1,-7}|{2,-14}|{3,-3}|{4,-7}|\r\n",
                            zsatnr, zcolsn, zsiztx, count, controlFlag);
                    }
                    report["CONTENT"] = content;

                }
                else
                {
                    string zsatnr = box?.Details?.First().Zsatnr;
                    string zcolsn = box?.Details?.First().Zcolsn;
                    string zsiztx = box?.Details?.First().Zsiztx;
                    int count = box.Details.Count(i => i.IsAdd != 1);

                    string controlFlag = "";
                    string mat = box?.Details?.First().Matnr;
                    controlFlag = mats.FirstOrDefault(i => i.MATNR == mat).PUT_STRA;
                    string MAKTX = mats.FirstOrDefault(i => i.MATNR == mat).MAKTX;

                    report["HU"] = box.Hu;
                    report["STORAGETYPE"] = box.Target;
                    report["RUKUBIAOZHI"] = controlFlag;
                    report["LIFNR"] = box.LIFNR;
                    report["PINHAO"] = zsatnr;
                    report["SEHAO"] = zcolsn;
                    report["GUIGE"] = zsiztx;
                    report["SHULIANG"] = count.ToString();
                    report["MAKTX"] = MAKTX;
                }

                PrinterSettings printerSettings = new PrinterSettings();
                report.Print(false, printerSettings);

            }
            catch (Exception ex)
            {
                LogHelper.Error("打印正常箱标(按规格)出错", ex.Message + "\r\n" + ex.StackTrace);
            }
        }
Exemplo n.º 38
0
        /// <summary>
        /// 处理命令反馈
        /// </summary>
        public bool GetCallBack()
        {
            try
            {
                int    offlinecount     = 0;
                int    allheadleftlengh = 6;
                int    receivedlengh    = 0;
                byte[] bufferhead       = new byte[6];
                while (allheadleftlengh - receivedlengh > 0)
                {
                    byte[] buffertemp = new byte[allheadleftlengh - receivedlengh];
                    int    lengh      = Tcpsocket.Receive(buffertemp);
                    if (lengh <= 0)
                    {
                        if (offlinecount == 3)
                        {
                            throw new Exception("Socket  错误!");
                        }
                        offlinecount += 1;
                        Thread.Sleep(1000 * 2);
                    }
                    Buffer.BlockCopy(buffertemp, 0, bufferhead, receivedlengh, lengh);
                    receivedlengh += lengh;
                }
                offlinecount  = 0;
                receivedlengh = 0;
                int    allcontentleftlengh = int.Parse(Convert.ToString(bufferhead[5], 10));
                byte[] buffercontent       = new byte[allcontentleftlengh];
                while (allcontentleftlengh - receivedlengh > 0)
                {
                    byte[] buffertemp = new byte[allcontentleftlengh - receivedlengh];
                    int    lengh      = Tcpsocket.Receive(buffertemp);
                    if (lengh <= 0)
                    {
                        if (offlinecount == 3)
                        {
                            throw new Exception("Socket  错误!");
                        }
                        offlinecount += 1;
                        Thread.Sleep(1000 * 2);
                    }
                    Buffer.BlockCopy(buffertemp, 0, buffercontent, receivedlengh, lengh);
                    receivedlengh += lengh;
                }

                //读返回
                if (buffercontent[1] == 0x03)
                {
                    IODeviceInfo IOInfo = new IODeviceInfo();
                    IOInfo.ID = this.DeviceID;
                    //解析 1-8口
                    char[] bytestr = Convert.ToString(buffercontent[4], 2).PadLeft(8, '0').ToArray();
                    for (int i = 0; i < 8; i++)
                    {
                        IOPortInfo ioport = new IOPortInfo();
                        ioport.PortNo    = 8 - i;
                        ioport.PortState = bytestr[i] == '1' ? 1 : 0;
                        IOInfo.DIPortList.Add(ioport);
                    }
                    //9-16口
                    bytestr = Convert.ToString(buffercontent[3], 2).PadLeft(8, '0').ToArray();
                    for (int i = 0; i < 8; i++)
                    {
                        IOPortInfo ioport = new IOPortInfo();
                        ioport.PortNo    = 16 - i;
                        ioport.PortState = bytestr[i] == '1' ? 1 : 0;
                        IOInfo.DIPortList.Add(ioport);
                    }
                    //17-24口
                    bytestr = Convert.ToString(buffercontent[6], 2).PadLeft(8, '0').ToArray();
                    for (int i = 0; i < 8; i++)
                    {
                        IOPortInfo ioport = new IOPortInfo();
                        ioport.PortNo    = 24 - i;
                        ioport.PortState = bytestr[i] == '1' ? 1 : 0;
                        IOInfo.DIPortList.Add(ioport);
                    }
                    //25-32口
                    bytestr = Convert.ToString(buffercontent[5], 2).PadLeft(8, '0').ToArray();
                    for (int i = 0; i < 8; i++)
                    {
                        IOPortInfo ioport = new IOPortInfo();
                        ioport.PortNo    = 32 - i;
                        ioport.PortState = bytestr[i] == '1' ? 1 : 0;
                        IOInfo.DIPortList.Add(ioport);
                    }
                    DelegateState.InvokeIOFeedBackEvent(IOInfo);
                    LastRecTime = DateTime.Now;
                    return(true);
                }
                //写返回
                if (buffercontent[1] == 0x10)
                {
                    LastRecTime = DateTime.Now;
                    return(true);
                }
                return(false);
            }
            catch (Exception ex)
            { LogHelper.WriteLog("AGV解析编解码错误!" + ex.Message); }
            return(false);
        }
Exemplo n.º 39
0
        public void SetPathChecked(IEnumerable <string> list, bool isChecked = true)
        {
            if (list.IsNullOrEmpty() || this.RootFolder.IsNull()) //this.RootFolder.IsLoading
            {
                return;
            }

            IsChecking = true;
            int totalItems      = list.Count();
            int checkProcessing = 0;

            Action action = () =>
            {
                int       i       = 0;
                const int timeout = 60;
                //Add timeout for checking mask view can't be removed
                // minutes
                while (true)
                {
                    Thread.Sleep(1 * 1000);
                    if (!IsChecking)
                    {
                        return;
                    }
                    if (i++ > timeout)
                    {
                        if (IsChecking)
                        {
                            IsChecking = false;
                        }
                        return;
                    }
                }
            };

            action.BeginInvoke((ar) => action.EndInvoke(ar), action);

            foreach (string path in list)
            {
                ///Maybe change explore factory during checking
                if (RootFolder.IsNull())
                {
                    IsChecking = false;
                    break;
                }

                this.RootFolder.GetItemAsync(path, (file) =>
                {
                    checkProcessing++;
                    LogHelper.DebugFormat("/**** set checked index:{0}, total:{1}", checkProcessing, totalItems);
                    if (checkProcessing == totalItems)
                    {
                        IsChecking = false;
                    }
                    if (!file.IsNull())
                    {
                        file.IsChecked = isChecked;
#if DEBUG
                        //if (file is CloudFile || file is CloudFolder)
                        //{
                        //    LogHelper.DebugFormat("/++++ set checked path:{0}", file.FolderPath + file.Name);
                        //}
                        //else
                        //{
                        //    LogHelper.DebugFormat("/++++ set checked path:{0}", file.FullPath);
                        //}
#endif
                    }
                });
            }
        }
Exemplo n.º 40
0
 /// <summary>
 ///     构造函数
 /// </summary>
 public HeBeiK3Job()
 {
     log      = new LogHelper();
     services = IOC.Resolve <IOpen3Code>();
     email    = IOC.Resolve <IEmail>();
 }
Exemplo n.º 41
0
        public void ProcessAlarmReport(string eqptID, string err_code, ErrorStatus status, string errorDesc)
        {
            try
            {
                string node_id            = eqptID;
                string eq_id              = eqptID;
                bool   is_all_alarm_clear = SCUtility.isMatche(err_code, "0") && status == ErrorStatus.ErrReset;
                //List<ALARM> alarms = null;
                List <ALARM> alarms = new List <ALARM>();
                scApp.getRedisCacheManager().BeginTransaction();
                using (TransactionScope tx = SCUtility.getTransactionScope())
                {
                    using (DBConnection_EF con = DBConnection_EF.GetUContext())
                    {
                        LogHelper.Log(logger: logger, LogLevel: LogLevel.Debug, Class: nameof(VehicleService), Device: DEVICE_NAME_AGV,
                                      Data: $"Process eq alarm report.alarm code:{err_code},alarm status{status},error desc:{errorDesc}");
                        ALARM alarm = null;
                        if (is_all_alarm_clear)
                        {
                            alarms = scApp.AlarmBLL.resetAllAlarmReport(eq_id);
                            scApp.AlarmBLL.resetAllAlarmReport2Redis(eq_id);
                        }
                        else
                        {
                            switch (status)
                            {
                            case ErrorStatus.ErrSet:
                                //將設備上報的Alarm填入資料庫。
                                alarm = scApp.AlarmBLL.setAlarmReport(node_id, eqptID, err_code, errorDesc);
                                //將其更新至Redis,保存目前所發生的Alarm
                                scApp.AlarmBLL.setAlarmReport2Redis(alarm);
                                //alarms = new List<ALARM>() { alarm };
                                if (alarm != null)
                                {
                                    alarms.Add(alarm);
                                }
                                break;

                            case ErrorStatus.ErrReset:
                                //將設備上報的Alarm從資料庫刪除。
                                alarm = scApp.AlarmBLL.resetAlarmReport(eq_id, err_code);
                                //將其更新至Redis,保存目前所發生的Alarm
                                scApp.AlarmBLL.resetAlarmReport2Redis(alarm);
                                //alarms = new List<ALARM>() { alarm };
                                if (alarm != null)
                                {
                                    alarms.Add(alarm);
                                }
                                break;
                            }
                        }
                        tx.Complete();
                    }
                }
                scApp.getRedisCacheManager().ExecuteTransaction();
                //通知有Alarm的資訊改變。
                scApp.getNatsManager().PublishAsync(SCAppConstants.NATS_SUBJECT_CURRENT_ALARM, new byte[0]);

                foreach (ALARM report_alarm in alarms)
                {
                    if (report_alarm == null)
                    {
                        continue;
                    }
                    if (report_alarm.ALAM_LVL != E_ALARM_LVL.Error)
                    {
                        continue;
                    }
                    //需判斷Alarm是否存在如果有的話則需再判斷MCS是否有Disable該Alarm的上報
                    if (scApp.AlarmBLL.IsReportToHost(report_alarm.ALAM_CODE))
                    {
                        string alarm_code = report_alarm.ALAM_CODE;
                        //scApp.ReportBLL.ReportAlarmHappend(eqpt.VEHICLE_ID, alarm.ALAM_STAT, alarm.ALAM_CODE, alarm.ALAM_DESC, out reportqueues);
                        List <AMCSREPORTQUEUE> reportqueues = new List <AMCSREPORTQUEUE>();
                        if (report_alarm.ALAM_STAT == ErrorStatus.ErrSet)
                        {
                            scApp.ReportBLL.ReportAlarmHappend(report_alarm.ALAM_STAT, alarm_code, report_alarm.ALAM_DESC);
                            scApp.ReportBLL.newReportUnitAlarmSet(eq_id, alarm_code, report_alarm.ALAM_DESC, reportqueues);
                        }
                        else
                        {
                            scApp.ReportBLL.ReportAlarmHappend(report_alarm.ALAM_STAT, alarm_code, report_alarm.ALAM_DESC);
                            scApp.ReportBLL.newReportUnitAlarmClear(eq_id, alarm_code, report_alarm.ALAM_DESC, reportqueues);
                        }
                        scApp.ReportBLL.newSendMCSMessage(reportqueues);

                        LogHelper.Log(logger: logger, LogLevel: LogLevel.Debug, Class: nameof(VehicleService), Device: DEVICE_NAME_AGV,
                                      Data: $"do report alarm to mcs,alarm code:{err_code},alarm status{status}");
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Log(logger: logger, LogLevel: LogLevel.Warn, Class: nameof(VehicleService), Device: DEVICE_NAME_AGV,
                              Data: ex);
            }
        }
Exemplo n.º 42
0
 public override Task Handle(CounterEvent @event)
 {
     LogHelper.GetLogger <CounterEventHandler2>().Info($"Event Info: {@event.ToJson()}, Handler Type:{GetType().FullName}");
     return(Task.CompletedTask);
 }
Exemplo n.º 43
0
		public static List<Spawner> GetSpawnersByRegion(Region region)
		{
			if (region == null) return null;
			List<Spawner> spawners = new List<Spawner>();
			//time this search, log if it takes longer than .30 seconds
			Utility.TimeCheck tc = new Utility.TimeCheck();
			tc.Start();
			foreach (Spawner s in m_Spawners)
				if (Region.Find(s.Location, s.Map) == region)
					spawners.Add(s);
			tc.End();
			if (tc.Elapsed() > 30)
			{
				LogHelper logger = new LogHelper("SpawnerCache");
				logger.Log("Warning:  Spawner search by region for " + region.Name + " took " + tc.Elapsed().ToString() + "ms");
			}
			return spawners;
		}
Exemplo n.º 44
0
 /// <summary>
 /// 初始化函数
 /// </summary>
 public HeBeiHYC2Job()
 {
     log      = new LogHelper();
     services = IOC.Resolve <IDTOpenCode>();
     email    = IOC.Resolve <IEmail>();
 }
Exemplo n.º 45
0
			public override void OnResponse( NetState state, RelayInfo info )
			{
				if ( info.ButtonID == 1 )
				{
					try
					{
						Utility.TimeCheck tc = new Utility.TimeCheck();
						tc.Start();
						m_TSDeed.Place(m_From, m_Location, false);
						tc.End();
						LogHelper Logger = new LogHelper("TownshipPlacementTime.log", false);
						//from.SendMessage(String.Format("Stone placement took {0}", tc.TimeTaken));
						Logger.Log(LogType.Text, String.Format("Stone placement ACTUAL at {0} took {1}", m_Location, tc.TimeTaken));
						Logger.Finish();
					}
					catch (Exception ex)
					{
						EventSink.InvokeLogException(new LogExceptionEventArgs(ex));
					}
				}
			}
Exemplo n.º 46
0
        protected override void OnException(ExceptionContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            //If exception handled before, do nothing.
            //If this is child action, exception should be handled by main action.
            if (context.ExceptionHandled || context.IsChildAction)
            {
                base.OnException(context);
                return;
            }

            //Log exception
            if (_wrapResultAttribute.LogError)
            {
                LogHelper.LogException(Logger, context.Exception);
            }

            // If custom errors are disabled, we need to let the normal ASP.NET exception handler
            // execute so that the user can see useful debugging information.
            if (!context.HttpContext.IsCustomErrorEnabled)
            {
                base.OnException(context);
                return;
            }

            // If this is not an HTTP 500 (for example, if somebody throws an HTTP 404 from an action method),
            // ignore it.
            if (new HttpException(null, context.Exception).GetHttpCode() != 500)
            {
                base.OnException(context);
                return;
            }

            //Check WrapResultAttribute
            if (!_wrapResultAttribute.WrapOnError)
            {
                base.OnException(context);
                return;
            }

            //We handled the exception!
            context.ExceptionHandled = true;

            //Return a special error response to the client.
            context.HttpContext.Response.Clear();
            context.Result = IsJsonResult()
                ? GenerateJsonExceptionResult(context)
                : GenerateNonJsonExceptionResult(context);

            // Certain versions of IIS will sometimes use their own error page when
            // they detect a server error. Setting this property indicates that we
            // want it to try to render ASP.NET MVC's error page instead.
            context.HttpContext.Response.TrySkipIisCustomErrors = true;

            //Trigger an event, so we can register it.
            EventBus.Trigger(this, new AbpHandledExceptionData(context.Exception));
        }
Exemplo n.º 47
0
 public GlobalVar()
 {
     _Loger = LogHelper<SynTextLog>.Me;
     _Loger.IsSync = true;
 }
Exemplo n.º 48
0
 public void Update(IStockSubject subject)
 {
     LogHelper.Log($"Investor: {name} has been notified about change {subject.Currency} currency to: {subject.Price:C2}");
 }
Exemplo n.º 49
0
        /// <summary>
        /// 初始化
        /// </summary>
        /// <returns></returns>
        public static ILog GetInstance()
        {
            logHelper = new LogHelper(null);

            return log;
        }
Exemplo n.º 50
0
        public Result UploadAccessFile(byte[] accessFile, string fileCoverID, string account, string fileExtension, string accessFileName)
        {
            Result result    = new Result();
            string saveToUrl = @ParameterAPI.GetConfig("FileURL").ConfigValue + @"\\" + account + @"\\" + fileCoverID + @"\\" + accessFileName + "." + fileExtension;

            try
            {
                Guid        g           = new Guid(fileCoverID);
                PCBEntities pCBEntities = new PCBEntities();
                int         count       = pCBEntities.PCB_FileCoverTB.Count <PCB_FileCoverTB>(p => p.FileCoverID == g);
                if (count <= 0)
                {
                    result.IsOK        = false;
                    result.Description = "封面ID不存在";
                    return(result);
                }
                PCB_AccessFileTB pCB_AccessFileTB = pCBEntities.PCB_AccessFileTB.FirstOrDefault(p => p.CreateAccount == account && p.FileExtension == fileExtension && p.FileCoverID == g && p.AccessFileName == accessFileName);// pCBEntities.PCB_AccessFileTB.FirstOrDefault(p => p.FileCoverID == new Guid(fileCoverID) && p.CreateAccount == account && p.FileExtension == fileExtension);
                if (pCB_AccessFileTB != null || pCB_AccessFileTB != default(PCB_AccessFileTB))
                {
                    result.IsOK        = false;
                    result.Description = "上传的文件已经存在";
                    return(result);
                }
                //string fileName=Guid.NewGuid().ToString();

                result = Common.Common.FileWrite(saveToUrl, accessFile);
                if (!result.IsOK)
                {
                    return(result);
                }
                pCB_AccessFileTB = new PCB_AccessFileTB();
                pCB_AccessFileTB.AccessFileID   = Guid.NewGuid();
                pCB_AccessFileTB.AccessFileName = accessFileName;
                pCB_AccessFileTB.FileCoverID    = new Guid(fileCoverID);
                pCB_AccessFileTB.AccessFileURL  = ParameterAPI.GetConfig("DowLoadFileURL").ConfigValue + "//" + account + "//" + fileCoverID + "//" + accessFileName + "." + fileExtension;
                pCB_AccessFileTB.FileExtension  = fileExtension;
                pCB_AccessFileTB.CreateAccount  = account;
                pCB_AccessFileTB.FileMD5        = Common.Common.GetMD5Hash(accessFile);
                pCB_AccessFileTB.FileSize       = accessFile.Length.ToString();
                pCB_AccessFileTB.CreateDateTime = DateTime.Now;
                pCBEntities.AddToPCB_AccessFileTB(pCB_AccessFileTB);
                result.IsOK = Convert.ToBoolean(pCBEntities.SaveChanges());
                if (!result.IsOK)
                {
                    File.Delete(saveToUrl);
                    result.Description = "上传失败";
                    return(result);
                }
                //Bitmap bmp = new Bitmap(Imagefilename);

                //MemoryStream ms = new MemoryStream();
                //bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                //byte[] arr = new byte[ms.Length];
                //ms.Position = 0;
                //ms.Read(arr, 0, (int)ms.Length);
                //ms.Close();
                //string r = Convert.ToBase64String(arr);
                //Result ret = UpdateFileCover(r, "chenc");
            }
            catch (Exception ex)
            {
                File.Delete(saveToUrl);
                LogHelper.WriteLog(GetType()).Info(ex.StackTrace);
                result.IsOK        = false;
                result.Description = ex.InnerException.Message;
            }
            return(result);
        }
Exemplo n.º 51
0
    /// <summary>
    /// 輸出為EXCEL
    /// </summary>
    public void WriteToXls()
    {
        try
        {
            LogHelper LOG = new LogHelper(ConntionDB);

            databind();
            DataTable Dt = (DataTable)GridView1.DataSource;
            if (Dt.Columns["ID"] != null) Dt.Columns.Remove("ID");
            if (Dt.Columns["ENABLE"] != null) Dt.Columns.Remove("ENABLE");
            if (Dt.Columns["ORGANIZATIONCODE"] != null) Dt.Columns.Remove("ORGANIZATIONCODE");
            if (Dt.Columns["CODE"] != null) Dt.Columns["CODE"].ColumnName = "代碼";
            if (Dt.Columns["NAME"] != null) Dt.Columns["NAME"].ColumnName = "名稱";
            if (Dt.Columns["CREATEDATE"] != null) Dt.Columns["CREATEDATE"].ColumnName = "建立日期";
            if (Dt.Columns["CREATEUID"] != null) Dt.Columns["CREATEUID"].ColumnName = "建立人員";
            if (Dt.Columns["UPDATEDATE"] != null) Dt.Columns["UPDATEDATE"].ColumnName = "異動日期";
            if (Dt.Columns["UPDATEUID"] != null) Dt.Columns["UPDATEUID"].ColumnName = "異動人員";
            if (Dt.Columns["PASSWORD"] != null) Dt.Columns["PASSWORD"].ColumnName = "密碼";
            if (Dt.Columns["MEMO"] != null) Dt.Columns["MEMO"].ColumnName = "備註";

            foreach (DataRow dr in Dt.Rows)
            {
                ParameterList.Clear();
                ParameterList.Add("SYS04人員");//0
                ParameterList.Add(Session["UID"].ToString());//1
                ParameterList.Add("O");//2
                ParameterList.Add(dr["代碼"].ToString());//3
                ParameterList.Add(Request.ServerVariables["Server_Name"]);//4

                LOG.AddSafeLog(ParameterList);

                for (int i = 0; i < Dt.Columns.Count; i++)
                {
                    if (Dt.Columns[i].DataType == Type.GetType("System.String"))
                    {
                        dr[i] = string.Format("&nbsp;{0}", dr[i].ToString());
                    }
                }
            }
            Export(System.Text.Encoding.UTF8, PageProgramCode + ".xls", "application/ms-excel", Dt);
        }
        catch (Exception ex)
        {
            ErrorMsgLabel.Text = ex.Message;
        }
        finally { }
    }
Exemplo n.º 52
0
        protected void CreateCompanyButton_Click(object sender, EventArgs e)
        {
            if (IsValid)
            {
                Admin loggedInAdmin = Helpers.GetLoggedInAdmin();


                try
                {
                    Company new_company = Company.CreateCompany();

                    new_company.name       = NameTextBox.Text;
                    new_company.brand_name = BrandNameTextBox.Text;

                    new_company.company_number = ABNTextBox.Text.Trim();
                    new_company.contact_name   = ContactNameTextBox.Text;

                    new_company.contact_email      = ContactEmailTextBox.Text.Trim();
                    new_company.transactions_email = TransactionEmailTextBox.Text.Trim();

                    new_company.address = AddressTextBox.Text;
                    new_company.suburb  = SuburbTextBox.Text;
                    new_company.state   = StateDropDownList.SelectedValue;

                    new_company.postcode = PostcodeTextBox.Text;
                    new_company.country  = "Australia";

                    new_company.phone = PhoneTextBox.Text;

                    new_company.website = WebsiteTextBox.Text;
                    new_company.api_key = Guid.NewGuid().ToString();

                    new_company.is_active = true;

                    new_company.is_customer     = false;
                    new_company.is_supplier     = false;
                    new_company.is_manufacturer = false;

                    switch (CompanyTypeRadioButtonList.SelectedValue)
                    {
                    case "Retailer":
                        new_company.is_customer = true;
                        break;

                    case "Supplier":
                        new_company.is_supplier = true;
                        break;

                    case "Manufacturer":
                        new_company.is_manufacturer = true;
                        break;
                    }

                    new_company.creation_datetime = DateTime.Now;
                    new_company.has_POSSystem     = true;
                    new_company.Save();
                    new_company.Refresh();

                    Session["company_id"] = new_company.company_id;
                    Response.Redirect("/manage/Companies/ViewCompany.aspx", false);
                }
                catch (Exception ex)
                {
                    LogHelper.WriteError(ex.ToString());
                    CreateCompanyErrorLabel.Text = ex.ToString();
                }
            }
        }
Exemplo n.º 53
0
		public static void LogException(Exception ex, string additionalMessage)
		{
			try
			{
				LogHelper Logger = new LogHelper("Exception.log", false);
				string text = String.Format("{0}\r\n{1}\r\n{2}", additionalMessage, ex.Message, ex.StackTrace);
				Logger.Log(LogType.Text, text);
				Logger.Finish();
				Console.WriteLine(text);
			}
			catch
			{
				// do nothing here as we do not want to enter a "cycle of doom!"
				//  Basically, we do not want the caller to catch an exception here, and call
				//  LogException() again, where it throws another exception, and so forth
			}
		}
Exemplo n.º 54
0
        private void RadContextMenu_ItemClick(object sender, RadRoutedEventArgs e)
        {
            RadContextMenu menu        = (RadContextMenu)sender;
            RadMenuItem    clickedItem = e.OriginalSource as RadMenuItem;
            GridViewRow    row         = menu.GetClickedElement <GridViewRow>();

            if (clickedItem != null && row != null)
            {
                string header = Convert.ToString(clickedItem.Header);

                switch (header)
                {
                case "新建":

                    break;

                case "编辑":

                    break;

                case "删除":
                    DirectoryInfoModel directoryInfoModel = row.DataContext as DirectoryInfoModel;
                    gridView.Items.Remove(row.DataContext);
                    if (File.Exists(directoryInfoModel.FullName))
                    {
                        try
                        {
                            File.Delete(directoryInfoModel.FullName);
                            Application.Current.Dispatcher.BeginInvoke(new Action(() => {
                                RadWindow.Alert(new DialogParameters
                                {
                                    Content = "删除成功!",
                                    DefaultPromptResultValue = directoryInfoModel.Name,
                                    Theme           = new Windows8Theme(),
                                    Header          = "提示",
                                    TopOffset       = 30,
                                    OkButtonContent = "关闭",
                                });
                            }));
                        }
                        catch (Exception ex)
                        {
                            LogHelper.ErrorLog(ex, "删除文件");
                            Application.Current.Dispatcher.BeginInvoke(new Action(() => {
                                RadWindow.Alert(new DialogParameters
                                {
                                    Content = "删除失败!",
                                    DefaultPromptResultValue = directoryInfoModel.Name,
                                    Theme           = new Windows8Theme(),
                                    Header          = "提示",
                                    TopOffset       = 30,
                                    OkButtonContent = "关闭",
                                });
                            }));
                        }
                    }
                    break;

                default:
                    break;
                }
            }
        }
Exemplo n.º 55
0
		private static void EventSink_AddItem(AddItemEventArgs e)
		{
			LogHelper lh = new LogHelper("AddItem.log", false, true);
			lh.Log(LogType.Mobile, e.from, String.Format("Used [Add Item to create ItemID:{0}, Serial:{1}", e.item.ItemID.ToString(), e.item.Serial.ToString()));
			lh.Finish();
		}
Exemplo n.º 56
0
        public override async Task Run(object prm)
        {
            if (IsRunning || !Settings.Config.ModuleIndustrialJobs)
            {
                return;
            }
            IsRunning = true;
            try
            {
                if ((DateTime.Now - _lastCheckTime).TotalMinutes < _checkInterval)
                {
                    return;
                }
                _lastCheckTime = DateTime.Now;
                await LogHelper.LogModule("Running Industrial Jobs module check...", Category);

                foreach (var(groupName, group) in Settings.IndustrialJobsModule.GetEnabledGroups())
                {
                    var chars = GetParsedCharacters(groupName) ?? new List <long>();
                    foreach (var characterID in chars)
                    {
                        var rtoken = await SQLHelper.GetRefreshTokenForIndustryJobs(characterID);

                        if (rtoken == null)
                        {
                            await SendOneTimeWarning(characterID, $"Industry jobs feed token for character {characterID} not found! User is not authenticated.");

                            continue;
                        }

                        var tq = await APIHelper.ESIAPI.RefreshToken(rtoken, Settings.WebServerModule.CcpAppClientId, Settings.WebServerModule.CcpAppSecret, $"From {Category} | Char ID: {characterID}");

                        var token = tq.Result;
                        if (string.IsNullOrEmpty(token))
                        {
                            if (tq.Data.IsNotValid)
                            {
                                await LogHelper.LogWarning($"Industry token for character {characterID} is outdated or no more valid!");
                            }
                            else
                            {
                                await LogHelper.LogWarning($"Unable to get industry token for character {characterID}. Current check cycle will be skipped. {tq.Data.ErrorCode}({tq.Data.Message})");
                            }

                            continue;
                        }

                        if (group.Filters.Any(a => a.Value.FeedPersonalJobs))
                        {
                            await ProcessIndustryJobs(false, group, characterID, token);
                        }
                        if (group.Filters.Any(a => a.Value.FeedCorporateJobs))
                        {
                            await ProcessIndustryJobs(true, group, characterID, token);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                await LogHelper.LogEx(ex.Message, ex, Category);
            }
            finally
            {
                IsRunning = false;
            }
        }
Exemplo n.º 57
0
		public static void On_RHFile(CommandEventArgs e)
		{
			if (e.Arguments.Length != 1)
			{
				e.Mobile.SendMessage("Usage: [LoadCont <filename>");
				return;
			}

			try
			{
				int loaded = 0;
				int count;
				LogHelper log = new LogHelper(e.Arguments[0] + " LoadCont.log");
				log.Log(LogType.Text, String.Format("Reload process initiated by {0}, with {1} as backup data.", e.Mobile, e.Arguments[0]));

				using (FileStream idxfs = new FileStream(e.Arguments[0] + ".idx", FileMode.Open, FileAccess.Read))
				{
					using (FileStream binfs = new FileStream(e.Arguments[0] + ".bin", FileMode.Open, FileAccess.Read))
					{
						GenericReader bin = new BinaryFileReader(new BinaryReader(binfs));
						GenericReader idx = new BinaryFileReader(new BinaryReader(idxfs));

						count = idx.ReadInt();
						if (count == -1)
							log.Log(LogType.Text, "No item data to reload."); // do nothing
						else
						{
							ArrayList items = new ArrayList(count);
							log.Log(LogType.Text, String.Format("Attempting to reload {0} items.", count));

							Type[] ctortypes = new Type[] { typeof(Serial) };
							object[] ctorargs = new object[1];

							for (int i = 0; i < count; i++)
							{
								string type = idx.ReadString();
								Serial serial = (Serial)idx.ReadInt();
								long position = idx.ReadLong();
								int length = idx.ReadInt();

								Type t = ScriptCompiler.FindTypeByFullName(type);
								if (t == null)
								{
									Console.WriteLine("Warning: Tried to load nonexistent type {0}. Ignoring item.", type);
									log.Log(String.Format("Warning: Tried to load nonexistent type {0}. Ignoring item.", type));
									continue;
								}

								ConstructorInfo ctor = t.GetConstructor(ctortypes);
								if (ctor == null)
								{
									Console.WriteLine("Warning: Tried to load type {0} which has no serialization constructor. Ignoring item.", type);
									log.Log(String.Format("Warning: Tried to load type {0} which has no serialization constructor. Ignoring item.", type));
									continue;
								}

								Item item = null;
								try
								{
									if (World.FindItem(serial) != null)
									{
										log.Log(LogType.Item, World.FindItem(serial), "Serial already in use!! Loading of saved item failed.");
									}
									else if (!World.IsReserved(serial))
									{
										log.Log(String.Format("Serial {0} is not reserved!! Loading of saved item failed.", serial));
									}
									else
									{
										ctorargs[0] = serial;
										item = (Item)(ctor.Invoke(ctorargs));
									}
								}
								catch (Exception ex)
								{
									LogHelper.LogException(ex);
									Console.WriteLine("An exception occurred while trying to invoke {0}'s serialization constructor.", t.FullName);
									Console.WriteLine(ex.ToString());
									log.Log(String.Format("An exception occurred while trying to invoke {0}'s serialization constructor.", t.FullName));
									log.Log(ex.ToString());
								}

								if (item != null)
								{
									World.FreeSerial(serial);

									World.AddItem(item);
									items.Add(new object[] { item, position, length });
									log.Log(String.Format("Successfully created item {0}", item));
								}
							}

							for (int i = 0; i < items.Count; i++)
							{
								object[] entry = (object[])items[i];
								Item item = entry[0] as Item;
								long position = (long)entry[1];
								int length = (int)entry[2];

								if (item != null)
								{
									bin.Seek(position, SeekOrigin.Begin);

									try
									{
										item.Deserialize(bin);

										// take care of parent hierarchy
										object p = item.Parent;
										if (p is Item)
										{
											((Item)p).RemoveItem(item);
											item.Parent = null;
											((Item)p).AddItem(item);
										}
										else if (p is Mobile)
										{
											((Mobile)p).RemoveItem(item);
											item.Parent = null;
											((Mobile)p).AddItem(item);
										}
										else
										{
											item.Delta(ItemDelta.Update);
										}

										item.ClearProperties();

										object rp = item.RootParent;
										if (rp is Item)
											((Item)rp).UpdateTotals();
										else if (rp is Mobile)
											((Mobile)rp).UpdateTotals();
										else
											item.UpdateTotals();

										if (bin.Position != (position + length))
											throw new Exception(String.Format("Bad serialize on {0}", item));

										log.Log(LogType.Item, item, "Successfully loaded.");
										loaded++;
									}
									catch (Exception ex)
									{
										LogHelper.LogException(ex);
										Console.WriteLine("Caught exception while deserializing {0}:", item);
										Console.WriteLine(ex.ToString());
										Console.WriteLine("Deleting item.");
										log.Log(String.Format("Caught exception while deserializing {0}:", item));
										log.Log(ex.ToString());
										log.Log("Deleting item.");
										item.Delete();
									}
								}
							}

						}
						idx.Close();
						bin.Close();
					}
				}

				Console.WriteLine("Attempted to load {0} items: {1} loaded, {2} failed.", count, loaded, count - loaded);
				log.Log(String.Format("Attempted to load {0} items: {1} loaded, {2} failed.", count, loaded, count - loaded));
				e.Mobile.SendMessage("Attempted to load {0} items: {1} loaded, {2} failed.", count, loaded, count - loaded);
				log.Finish();
			}
			catch (Exception ex)
			{
				LogHelper.LogException(ex);
				Console.WriteLine(ex.ToString());
				e.Mobile.SendMessage("Exception: {0}", ex.Message);
			}
		}
Exemplo n.º 58
0
        private async Task <bool> OnAuthRequest(HttpListenerRequestEventArgs context)
        {
            if (!Settings.Config.ModuleIndustrialJobs)
            {
                return(false);
            }

            var request  = context.Request;
            var response = context.Response;

            try
            {
                RunningRequestCount++;
                var port = Settings.WebServerModule.WebExternalPort;

                if (request.HttpMethod == HttpMethod.Get.ToString())
                {
                    if (request.Url.LocalPath == "/callback" || request.Url.LocalPath == $"{port}/callback")
                    {
                        var clientID = Settings.WebServerModule.CcpAppClientId;
                        var secret   = Settings.WebServerModule.CcpAppSecret;
                        var prms     = request.Url.Query.TrimStart('?').Split('&');
                        var code     = prms[0].Split('=')[1];
                        var state    = prms.Length > 1 ? prms[1].Split('=')[1] : null;

                        if (string.IsNullOrEmpty(state))
                        {
                            return(false);
                        }

                        if (!state.StartsWith("ijobsauth"))
                        {
                            return(false);
                        }
                        //var groupName = HttpUtility.UrlDecode(state.Replace("ijobsauth", ""));

                        var result = await WebAuthModule.GetCharacterIdFromCode(code, clientID, secret);

                        if (result == null)
                        {
                            await WebServerModule.WriteResponce(
                                WebServerModule.GetAccessDeniedPage("Industry Jobs Module", LM.Get("accessDenied"),
                                                                    WebServerModule.GetAuthPageUrl()), response);

                            return(true);
                        }

                        var lCharId = Convert.ToInt64(result[0]);
                        //var group = Settings.IndustrialJobsModule.Groups[groupName];
                        var    allowedCharacters = GetAllParsedCharactersWithGroups();
                        string allowedGroup      = null;
                        foreach (var(group, allowedCharacterIds) in allowedCharacters)
                        {
                            if (allowedCharacterIds.Contains(lCharId))
                            {
                                allowedGroup = group;
                                break;
                            }
                        }

                        if (string.IsNullOrEmpty(allowedGroup))
                        {
                            await WebServerModule.WriteResponce(
                                WebServerModule.GetAccessDeniedPage("Industry Jobs Module", LM.Get("accessDenied"),
                                                                    WebServerModule.GetAuthPageUrl()), response);

                            return(true);
                        }

                        await SQLHelper.InsertOrUpdateTokens("", result[0], null, null, result[1]);

                        await WebServerModule.WriteResponce(File
                                                            .ReadAllText(SettingsManager.FileTemplateMailAuthSuccess)
                                                            .Replace("{headerContent}", WebServerModule.GetHtmlResourceDefault(false))
                                                            .Replace("{header}", "authTemplateHeader")
                                                            .Replace("{body}", LM.Get("industryJobsAuthSuccessHeader"))
                                                            .Replace("{body2}", LM.Get("industryJobsAuthSuccessBody"))
                                                            .Replace("{backText}", LM.Get("backText")), response
                                                            );

                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                await LogHelper.LogEx(ex.Message, ex, Category);
            }
            finally
            {
                RunningRequestCount--;
            }
            return(false);
        }
Exemplo n.º 59
0
 void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
 {
     LogHelper.Error("Unexpected error", (Exception)e.ExceptionObject);
     ForceDialog(((Exception)e.ExceptionObject).Message, "Unexpected error");
     //this.ShowMessageAsync("Unexpected error", ((Exception)e.ExceptionObject).Message, MessageDialogStyle.Affirmative);
 }
Exemplo n.º 60
0
        public static void PrintErrorTag(YKBoxInfo box,bool checkSku)
        {
            try
            {
                string content = "";
                string filepath = Application.StartupPath + "\\LabelError.mrt";
                if (box.Details.Count > 0)
                {
                    List<string> matnrlist = box.Details.Select(i => i.Matnr).Distinct().ToList();
                    if (matnrlist.Count > 10)
                    {
                        if (checkSku)
                        {
                            content = Consts.Default.SHANG_PIN_DA_YU_SHI;
                        }
                    }
                    else
                    {
                        bool isExist = false;
                        foreach (string matnr in matnrlist)
                        {
                            string zsatnr = box?.Details?.First(i => i.Matnr == matnr).Zsatnr;
                            string zcolsn = box?.Details?.First(i => i.Matnr == matnr).Zcolsn;
                            string zsiztx = box?.Details?.First(i => i.Matnr == matnr).Zsiztx;
                            int count = box.Details.FindAll(i => i.Matnr == matnr).Count;
                            if (zsiztx.Contains("/"))
                            {
                            }
                            else
                            {
                                isExist = true;
                            }
                            content += string.Format("{0}/{1}/{2}/{3}\r\n",
                                zsatnr, zcolsn, zsiztx, count);
                        }

                        if(isExist)
                        {
                            filepath = Application.StartupPath + "\\LabelError_Small.mrt";
                        }
                    }
                }
                else
                {
                    content = "未扫描到商品";
                }

                
                StiReport report = new StiReport();
                report.Load(filepath);
                report.Compile();
                report["HU"] = box.Hu;
                report["CONTENT"] = content;
                PrinterSettings printerSettings = new PrinterSettings();
                report.Print(false, printerSettings);

            }
            catch (Exception ex)
            {
                LogHelper.Error("打印异常箱标出错", ex.Message + "\r\n" + ex.StackTrace);
            }
        }