Ejemplo n.º 1
0
        /// <summary>
        /// Constructs a new processor for the provided data files.
        /// </summary>
        /// <param name="events">The data file containing events.</param>
        /// <param name="counters">The data file containing harware coutnters.</param>
        public EventProcessor(TraceLog events, TraceCounter[] counters)
        {
            // Add our data sources
            this.TraceLog = events;
            this.Counters = counters;
            this.CoreCount = this.Counters.Max(c => c.Core) + 1;

            // A last switch per core
            for (int i = 0; i < this.CoreCount; ++i)
                this.LookupLastSwitch.Add(i, null);
        }
Ejemplo n.º 2
0
        public static void CreateSubLog(string moduleName, string baseModuleName)
        {
            try
            {
                FieldInfo fi = typeof(TraceDispenser).GetField("g_ListenerList", BindingFlags.Static | BindingFlags.NonPublic);
                TraceDispenser td = new TraceDispenser();
                string key = string.Format("\\{0}\\{1}.{2}", Constants.APPLICATION_NAME, baseModuleName, moduleName);
                Hashtable tracelist = (Hashtable)fi.GetValue(td);
                if (!tracelist.ContainsKey(key))
                {
                    TraceLog baseLog = TraceDispenser.GetTraceLog(baseModuleName, Constants.APPLICATION_NAME);
                    ArrayList baseconfigs = (ArrayList)GetFieldValue(baseLog, "TracerConfigList");
                    TraceLog newlog = new TraceLog();

                    Type btftype = typeof(TraceLog).Assembly.GetType("Com.SouthernCompany.Cool.Diagnostics.BaseTracerFile");
                    object btf = Activator.CreateInstance(btftype);

                    //Path.GetInvalidFileNameChars()
                    string safemodulename = moduleName;
                    foreach (char c in Path.GetInvalidFileNameChars())
                        safemodulename = safemodulename.Replace(c.ToString(), "");
                    string basefilename = (string)GetFieldValue(baseconfigs[0], "m_FileName");
                    SetFieldValue(btf, "m_FileName", Path.Combine(Path.GetDirectoryName(basefilename), baseModuleName + "." + safemodulename + ".log"));
                    SetFieldValue(btf, "m_PrevFileName", Path.Combine(Path.GetDirectoryName(basefilename), baseModuleName + "." + safemodulename + ".prev.log"));
                    SetFieldValue(btf, "m_EnableLogging", GetFieldValue(baseconfigs[0], "m_EnableLogging"));
                    SetFieldValue(btf, "m_EnableFlush", GetFieldValue(baseconfigs[0], "m_EnableFlush"));
                    SetFieldValue(btf, "m_ActiveFilterMask", GetFieldValue(baseconfigs[0], "m_ActiveFilterMask"));
                    SetFieldValue(btf, "m_MaxLogFileSize", GetFieldValue(baseconfigs[0], "m_MaxLogFileSize"));

                    SetFieldValue(newlog, "TracerConfigList", new ArrayList(new object[] { btf }));

                    MethodInfo mi = typeof(TraceLog).GetMethod("SetAppName", BindingFlags.NonPublic | BindingFlags.Instance);
                    mi.Invoke(newlog, new object[] { baseModuleName + "." + moduleName, Constants.APPLICATION_NAME, "" });

                    mi = typeof(TraceLog).GetMethod("InitializeMutex", BindingFlags.NonPublic | BindingFlags.Instance);
                    mi.Invoke(newlog, new object[0]);//, new object[] { moduleName, Constants.APPLICATION_NAME, "" });

                    mi = typeof(TraceLog).GetMethod("InitializeLogging", BindingFlags.NonPublic | BindingFlags.Instance);
                    mi.Invoke(newlog, new object[0]);// new object[] { moduleName, Constants.APPLICATION_NAME, "" });
                    newlog.LogEvent("CoolTracer version=" + btftype.Assembly.ToString(), (long)0x10L);
                    newlog.LogEvent("Identity=" + WindowsIdentity.GetCurrent().Name.ToString(), (long)0x10L);

                    tracelist.Add(key, newlog);
                    Log.Write(string.Format("Created sub-log '{0}.{1}', filename '{2}'.", baseModuleName, moduleName, Path.Combine(Path.GetDirectoryName(basefilename), baseModuleName + "." + safemodulename + ".log")), Mask.Diagnostic);
                }
            }
            catch (Exception ex)
            {
                Log.Write(string.Format("Unable to create sub-log '{0}.{1}': ", baseModuleName, moduleName) + ex.ToString(), Mask.Failure);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Constructs a new processor for the provided data files.
        /// </summary>
        /// <param name="preprocessor">The preprocessor to use (copies everything)</param>
        public EventProcessor(EventProcessor preprocessor)
        {
            // Copy stuff we already calculated
            this.TraceLog = preprocessor.TraceLog;
            this.Counters = preprocessor.Counters;
            this.Start = preprocessor.Start;
            this.End = preprocessor.End;
            this.Duration = preprocessor.Duration;
            this.Interval = preprocessor.Interval;
            this.Count = preprocessor.Count;
            this.CoreCount = preprocessor.CoreCount;
            this.Process = preprocessor.Process;
            this.Threads = preprocessor.Threads;
            this.Frames = preprocessor.Frames;
            this.Faults = preprocessor.Faults;
            this.Switches = preprocessor.Switches;
            this.Lifetimes = preprocessor.Lifetimes;
            this.LockAcquisitions = preprocessor.LockAcquisitions;

            // A last switch per core
            for (int i = 0; i < this.CoreCount; ++i)
                this.LookupLastSwitch.Add(i, null);
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Afters the count all.
 /// </summary>
 /// <param name="log">The log.</param>
 public void AfterCountAll(TraceLog log)
 {
     TraceQuery(log);
 }
Ejemplo n.º 5
0
 /// <summary>
 /// Afters the average all.
 /// </summary>
 /// <param name="log">The log.</param>
 public void AfterAverageAll(TraceLog log)
 {
     TraceQuery(log);
 }
Ejemplo n.º 6
0
 /// <summary>
 /// Afters the truncate.
 /// </summary>
 /// <param name="log">The log.</param>
 public void AfterTruncate(TraceLog log)
 {
     TraceQuery(log);
 }
Ejemplo n.º 7
0
 /// <summary>
 /// Afters the query multiple.
 /// </summary>
 /// <param name="log">The log.</param>
 public void AfterQueryMultiple(TraceLog log)
 {
     TraceQuery(log);
 }
Ejemplo n.º 8
0
 /// <summary>
 /// Afters the merge all.
 /// </summary>
 /// <param name="log">The log.</param>
 public void AfterMergeAll(TraceLog log)
 {
     TraceQuery(log);
 }
Ejemplo n.º 9
0
 void ITraceListener.OnNewTraceLog(TraceLog traceLog)
 {
 }
Ejemplo n.º 10
0
        public void ListenerCallback(IAsyncResult result)
        {
            HttpListener        listener = (HttpListener)result.AsyncState;
            HttpListenerContext context  = listener.EndGetContext(result);

            listener.BeginGetContext(ListenerCallback, listener);

            var ssid = Guid.NewGuid();
            HttpListenerRequest  request  = context.Request;
            HttpListenerResponse response = context.Response;

            string data = "";

            if (Environment.OSVersion.Platform == PlatformID.Unix)
            {
                if (string.Compare(request.HttpMethod, "get", true) == 0)
                {
                    data = request.RawUrl.Substring(8);
                    data = HttpUtility.UrlDecode(data);
                }
            }
            else
            {
                data = request.QueryString["d"];
            }

            if (string.IsNullOrEmpty(data))
            {
                using (var reader = new StreamReader(request.InputStream, request.ContentEncoding))
                {
                    data = reader.ReadToEnd();
                    data = HttpUtility.ParseQueryString(data)["d"];
                }
            }

            int gameId, serverId, statuscode;
            var requestParam = RequestParse.Parse(request.RemoteEndPoint.Address.ToString(), request.RawUrl, data, out gameId, out serverId, out statuscode);

            if (statuscode != (int)HttpStatusCode.OK)
            {
                response.StatusCode = statuscode;
                response.Close();
                return;
            }

            requestParam["UserHostAddress"] = request.RemoteEndPoint.Address.ToString();
            requestParam["ssid"]            = ssid.ToString("N");
            requestParam["http"]            = "1";

            var clientConnection = new HttpClientConnection {
                Context = context, SSID = ssid, Param = requestParam
            };

            clientConnection.TimeoutTimer = new Timer(TimeoutSendback, clientConnection, httpProxyTimeout, Timeout.Infinite);
            byte[] paramData = Encoding.ASCII.GetBytes(RequestParse.ToQueryString(requestParam));
            pool[ssid] = clientConnection;

            try
            {
                gsConnectionManager.Send(gameId, serverId, paramData);
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("无法连接游服error:{0}", ex);
                var responseData = RequestParse.CtorErrMsg(10000, RequestParse.ErrorMsgConnectFail, requestParam);
                SendDataBack(ssid, responseData, 0, responseData.Length);
            }
        }
Ejemplo n.º 11
0
 private void PostTraceLog(TraceLog traceLog)
 {
     MethodCompiler.Compiler.PostTraceLog(traceLog);
 }
Ejemplo n.º 12
0
        /// <summary>
        /// 增加空密码处理
        /// 修改:伍张发
        /// </summary>
        /// <returns></returns>
        public int GetUserId()
        {
            RegType regType = RegType;
            PwdType pwdType = PwdType.DES;

            SetLoginType(ref regType, ref pwdType, PassportId);

            var command = ConnectManager.Provider.CreateCommandStruct("SnsUserInfo", CommandMode.Inquiry);

            command.OrderBy = "USERID ASC";
            command.Columns = "USERID,PASSPORTID,DEVICEID,REGTYPE,RETAILID,RETAILUSER,WEIXINCODE";
            command.Filter  = ConnectManager.Provider.CreateCommandFilter();

            string password = _PassportPwd;

            if (regType == RegType.Normal)
            {
                if (pwdType == PwdType.MD5)
                {
                    password = PasswordEncryptMd5(_PassportPwd);
                }
                command.Filter.Condition = string.Format("{0} AND {1}",
                                                         command.Filter.FormatExpression("PassportId"),
                                                         command.Filter.FormatExpression("PassportPwd")
                                                         );
                command.Filter.AddParam("PassportId", _PassportId);
                command.Filter.AddParam("PassportPwd", password);
            }
            else if (regType == RegType.Guest)
            {
                if (pwdType == PwdType.MD5)
                {
                    if (password.Length != 32)
                    {
                        //判断是否已经MD5加密
                        password = PasswordEncryptMd5(_PassportPwd);
                    }
                }

                command.Filter.Condition = string.Format("{0} AND {1} AND {2} AND {3}",
                                                         command.Filter.FormatExpression("DeviceID"),
                                                         command.Filter.FormatExpression("PassportPwd"),
                                                         command.Filter.FormatExpression("PassportId"),
                                                         command.Filter.FormatExpression("RegType")
                                                         );
                command.Filter.AddParam("DeviceID", _deviceID);
                command.Filter.AddParam("PassportPwd", password);
                command.Filter.AddParam("PassportId", _PassportId);
                command.Filter.AddParam("RegType", (int)regType);
            }
            else
            {
                command.Filter.Condition = string.Format("{0} AND {1}",
                                                         command.Filter.FormatExpression("RetailID"),
                                                         command.Filter.FormatExpression("RetailUser")
                                                         );
                command.Filter.AddParam("RetailID", RetailID);
                command.Filter.AddParam("RetailUser", RetailUser);
            }

            command.Parser();

            using (var aReader = ConnectManager.Provider.ExecuteReader(CommandType.Text, command.Sql, command.Parameters))
            {
                SnsCenterUser user = new SnsCenterUser();
                if (aReader.Read())
                {
                    try
                    {
                        _userid     = Convert.ToInt32(aReader["userid"]);
                        _PassportId = aReader["PassportId"].ToString();
                        _deviceID   = aReader["DeviceID"].ToNotNullString();
                        RegType     = aReader["RegType"].ToEnum <RegType>();
                        RetailID    = aReader["RetailID"].ToNotNullString();
                        RetailUser  = aReader["RetailUser"].ToNotNullString();
                        WeixinCode  = aReader["WeixinCode"].ToNotNullString();
                    }
                    catch (Exception ex)
                    {
                        TraceLog.WriteError("GetUserId method error:{0}, sql:{0}", ex, command.Sql);
                    }
                    return(_userid);
                }
                else
                {
                    return(0);
                }
            }
        }
Ejemplo n.º 13
0
		static DebugLog()
		{
			DebugLog._policyEngineTraceLog = new TraceLog("ClaimsTransformationRulesParser");
		}
Ejemplo n.º 14
0
 /// <summary>
 /// 跟踪日志
 /// </summary>
 /// <param name="log">日志记录</param>
 public static void Print(TraceLog log)
 {
     IRepository<string> repository = AgileEAP.Core.Infrastructure.EngineContext.Current.Resolve<IRepository<string>>();
     repository.SaveOrUpdate(log);
 }
Ejemplo n.º 15
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="uriPrefixes"></param>
        /// <returns></returns>
        public Task Run(params string[] uriPrefixes)
        {
            Error = null;
            // Establish a host-handler context:
            _hostContext = new HostContext(this, _handler);

            _listener.IgnoreWriteExceptions = true;

            if (uriPrefixes.Length == 0)
            {
                TraceLog.WriteError("Http start listenning url is null");
            }
            // Add the server bindings:
            foreach (var prefix in uriPrefixes)
            {
                _listener.Prefixes.Add(prefix.EndsWith("/") ? prefix : prefix + "/");
            }

            return(Task.Run(async() =>
            {
                // Configure the handler:
                if (_configValues != null)
                {
                    var config = _handler as IConfigurationTrait;
                    if (config != null)
                    {
                        var task = config.Configure(_hostContext, _configValues);
                        if (task != null)
                        {
                            if (!await task)
                            {
                                return;
                            }
                        }
                    }
                }

                // Initialize the handler:
                var init = _handler as IInitializationTrait;
                if (init != null)
                {
                    var task = init.Initialize(_hostContext);
                    if (task != null)
                    {
                        if (!await task)
                        {
                            return;
                        }
                    }
                }

                try
                {
                    // Start the HTTP listener:
                    _listener.Start();
                }
                catch (HttpListenerException hlex)
                {
                    Error = hlex;
                    TraceLog.WriteError("Http start listenning error:{0}", hlex);
                    return;
                }

                // Accept connections:
                // Higher values mean more connections can be maintained yet at a much slower average response time; fewer connections will be rejected.
                // Lower values mean less connections can be maintained yet at a much faster average response time; more connections will be rejected.
                var sem = new Semaphore(_accepts, _accepts);

                while (true)
                {
                    sem.WaitOne();

#pragma warning disable 4014
                    _listener.GetContextAsync().ContinueWith(async(t) =>
                    {
                        try
                        {
                            sem.Release();
                            var ctx = await t;
                            await ProcessListenerContext(ctx, this);

                            return;
                        }
                        catch (Exception ex)
                        {
                            TraceLog.WriteError("Http request unknow error:{0}", ex);
                        }
                    });
#pragma warning restore 4014
                }
            }));
        }
Ejemplo n.º 16
0
        /// <summary>
        /// 尝试接收数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="receiveParam"></param>
        /// <param name="dataList"></param>
        /// <returns>return null is load error</returns>
        public bool TryReceiveData <T>(TransReceiveParam receiveParam, out List <T> dataList) where T : AbstractEntity, new()
        {
            //var watch = RunTimeWatch.StartNew("Cache load " + receiveParam.RedisKey);
            dataList = null;
            bool hasDbConnect = DbConnectionProvider.CreateDbProvider(receiveParam.Schema) != null;
            var  schema       = receiveParam.Schema;

            //表为空时,不加载数据
            if (schema == null ||
                string.IsNullOrEmpty(schema.EntityName))
            {
                //DB is optional and can no DB configuration
                dataList = new List <T>();
                return(true);
            }
            //配置库不放到Redis,尝试从DB加载
            if (schema.StorageType.HasFlag(StorageType.ReadOnlyDB) ||
                schema.StorageType.HasFlag(StorageType.ReadWriteDB))
            {
                if (!hasDbConnect)
                {
                    dataList = new List <T>();
                    return(true);
                }
                if (_dbTransponder.TryReceiveData(receiveParam, out dataList))
                {
                    //TraceLog.ReleaseWriteDebug("The readonly-data:{0} has been loaded {1}", receiveParam.RedisKey, dataList.Count);
                    return(true);
                }
                TraceLog.WriteError("The data:{0} loaded  from db fail.\r\n{1}", receiveParam.RedisKey, TraceLog.GetStackTrace());
                return(false);
            }

            if (schema.StorageType.HasFlag(StorageType.ReadOnlyRedis) ||
                schema.StorageType.HasFlag(StorageType.ReadWriteRedis))
            {
                //watch.Check("init");
                if (!string.IsNullOrEmpty(receiveParam.RedisKey) &&
                    _redisTransponder.TryReceiveData(receiveParam, out dataList))
                {
                    //watch.Check("loaded");
                    if (dataList.Count > 0)
                    {
                        //watch.Flush(true);
                        //TraceLog.ReleaseWriteDebug("The data:{0} has been loaded {1}", receiveParam.RedisKey, dataList.Count);
                        return(true);
                    }
                    //从Redis历史记录表中加载
                    if (hasDbConnect && Setting != null && Setting.IsStorageToDb)
                    {
                        var result = TryLoadHistory(receiveParam.RedisKey, out dataList);
                        TraceLog.Write("The data:{0} has been loaded {1} from history.", receiveParam.RedisKey, dataList.Count);
                        return(result);
                    }
                    //watch.Flush(true);
                    dataList = new List <T>();
                    return(true);
                }
                //read faild from redis.
                TraceLog.WriteError("The data:{0} loaded  from redis fail.\r\n{1}", receiveParam.RedisKey, TraceLog.GetStackTrace());
                return(false);
            }
            return(true);
        }
Ejemplo n.º 17
0
        public override bool TakeAction()
        {
            TraceLog.ReleaseWriteFatal(_orderInfo);
            //string AppUrl = ConfigUtils.GetSetting("AppStoreUrl");
            if (AppUrl == string.Empty || _orderInfo.IndexOf("Sandbox") > 0)
            {
                AppUrl = "https://sandbox.itunes.apple.com/verifyReceipt";
            }
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(AppUrl);

            req.Method = "POST";
            byte[] ReceiptData = Encoding.UTF8.GetBytes(_orderInfo);
            TDictionary <string, string> dict = new TDictionary <string, string>();

            dict.Add("receipt-data", Convert.ToBase64String(ReceiptData));
            byte[] content = Encoding.UTF8.GetBytes(JsonUtils.Serialize(dict));
            req.ContentLength = content.Length;
            Stream stream = req.GetRequestStream();

            stream.Write(content, 0, content.Length);
            stream.Close();
            WebResponse resp = req.GetResponse();

            stream = resp.GetResponseStream();

            StreamReader reader   = new StreamReader(stream);
            string       response = reader.ReadToEnd();

            req.Abort();
            resp.Close();
            TraceLog.ReleaseWriteFatal(response);

            AppStoreInfo appStoreInfo = new AppStoreInfo();

            try
            {
                appStoreInfo = JsonUtils.Deserialize <AppStoreInfo>(response);
            }
            catch (Exception ex)
            {
                this.SaveLog(ex);
                ErrorCode = LanguageManager.GetLang().ErrorCode;
                ErrorInfo = LanguageManager.GetLang().LoadDataError;
                return(false);
            }
            if (appStoreInfo.status != 0)
            {
                ErrorCode = LanguageManager.GetLang().ErrorCode;
                ErrorInfo = LanguageManager.GetLang().St1066_PayError;
                return(false);
            }
            //int silver = AppStoreHelper.GetSilverPiece(appStoreInfo.receipt.product_id, _gameID);
            //PaymentService.GetAppStore(_gameID, _serviceID, _passportId, silver, appStoreInfo.receipt.transaction_id, _deviceId);

            AppStoreHelper appStore = AppStoreHelper.GetSilverPiece(appStoreInfo.receipt.product_id, _gameID);

            PaymentService.GetAppStore(_gameID, _serviceID, _passportId, appStore.SilverPiece, appStore.RMB, appStoreInfo.receipt.transaction_id, _deviceId);
            // TraceLog.ReleaseWriteFatal("appstore完成");
            //TraceLog.ReleaseWriteFatal("GameID" + _gameID + "ServerID" + _serviceID);

            //int silver = 10;
            //string test = "1234567894561111111";
            //PaymentService.GetAppStore(_gameID, _serviceID, _passportId, silver, test, _deviceId);
            return(true);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// 从历史库中加载数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="redisKey"></param>
        /// <param name="dataList"></param>
        /// <returns></returns>
        public bool TryLoadHistory <T>(string redisKey, out List <T> dataList) where T : ISqlEntity
        {
            string[] entityAndKeys = (redisKey ?? "").Split('_');
            var      entityKey     = entityAndKeys.Length > 1 ? entityAndKeys[1] : null;
            string   entityNameKey = RedisConnectionPool.GetRedisEntityKeyName(entityAndKeys[0]);

            bool result = false;

            dataList = null;
            SchemaTable schemaTable;

            if (EntitySchemaSet.TryGet <EntityHistory>(out schemaTable))
            {
                try
                {
                    var provider = DbConnectionProvider.CreateDbProvider(schemaTable);
                    if (provider == null)
                    {
                        //DB is optional and can no DB configuration
                        dataList = new List <T>();
                        return(true);
                    }
                    TransReceiveParam receiveParam = new TransReceiveParam(entityNameKey);
                    receiveParam.Schema = schemaTable;
                    int    maxCount     = receiveParam.Schema.Capacity;
                    var    filter       = new DbDataFilter(maxCount);
                    string key          = schemaTable.Keys[0];
                    var    entitySchema = EntitySchemaSet.Get(entityAndKeys[0]);

                    if (entitySchema != null && entitySchema.Keys.Length == 1)
                    {
                        filter.Condition = provider.FormatFilterParam(key);
                        filter.Parameters.Add(key, string.Format("{0}_{1}", entityNameKey, entityKey));
                    }
                    else
                    {
                        filter.Condition = provider.FormatFilterParam(key, "LIKE");
                        filter.Parameters.Add(key, string.Format("{0}_%{1}%", entityNameKey, entityKey));
                    }
                    receiveParam.DbFilter = filter;

                    List <EntityHistory> historyList;
                    if (_dbTransponder.TryReceiveData(receiveParam, out historyList))
                    {
                        if (historyList.Count == 0)
                        {
                            dataList = new List <T>();
                            return(true);
                        }
                        dataList = new List <T>();
                        var keyBytes   = new byte[historyList.Count][];
                        var valueBytes = new byte[historyList.Count][];
                        for (int i = 0; i < keyBytes.Length; i++)
                        {
                            var entityHistory = historyList[i];
                            keyBytes[i]   = RedisConnectionPool.ToByteKey(entityHistory.Key.Split('_')[1]);
                            valueBytes[i] = entityHistory.Value;
                            dataList.Add((T)_serializer.Deserialize(entityHistory.Value, typeof(T)));
                        }
                        //从DB备份中恢复到Redis, 多个Key时也要更新
                        var entitys = dataList.ToArray();
                        RedisConnectionPool.Process(client =>
                        {
                            client.HMSet(entityNameKey, keyBytes, valueBytes);
                            if (entitySchema.Keys.Length > 1)
                            {
                                RedisConnectionPool.UpdateFromMutilKeyMap <T>(client, entityKey, entitys);
                            }
                        });
                        result = true;
                    }
                }
                catch (Exception ex)
                {
                    TraceLog.WriteError("Try load Redis's history key:{0}\r\nerror:{1}", entityNameKey, ex);
                }
            }
            else
            {
                dataList = new List <T>();
                result   = true;
            }
            return(result);
        }
Ejemplo n.º 19
0
 protected abstract void OnSaveLog(TraceLog log);
Ejemplo n.º 20
0
        /// <summary>
        /// 清除过期缓存
        /// </summary>
        public virtual void DisposeCache()
        {
            KeyValuePair <string, CacheContainer>[] containerList = ToArray();
            var entityKeyDict = new Dictionary <string, bool>();

            foreach (var containerPair in containerList)
            {
                var itemSetList = containerPair.Value.Collection.ToList <CacheItemSet>();
                foreach (var itemPair in itemSetList)
                {
                    CacheItemSet itemSet = itemPair.Value;
                    if (itemSet.ItemType == CacheType.Entity)
                    {
                        //所有对象都过期才删除
                        if (entityKeyDict.ContainsKey(containerPair.Key))
                        {
                            entityKeyDict[containerPair.Key] = entityKeyDict[containerPair.Key] &&
                                                               (!itemSet.HasChanged && itemSet.IsPeriod &&
                                                                !itemSet.HasItemChanged);
                        }
                        else
                        {
                            entityKeyDict[containerPair.Key] = (!itemSet.HasChanged && itemSet.IsPeriod &&
                                                                !itemSet.HasItemChanged);
                        }
                        continue;
                    }
                    if (itemSet.HasChanged || !itemSet.IsPeriod)
                    {
                        //clear sub item is expired.
                        itemSet.RemoveExpired(itemPair.Key);
                        continue;
                    }
                    if (!itemSet.TryProcessExpired(itemPair.Key))
                    {
                        continue;
                    }
                    TraceLog.ReleaseWrite("Cache item:{0} key:{1} expired has been removed.", containerPair.Key, itemPair.Key);
                    object temp;
                    if (containerPair.Value.Collection.TryRemove(itemPair.Key, out temp))
                    {
                        itemSet.ResetStatus();
                        itemSet.Dispose();
                    }
                }
                if (containerPair.Value.Collection.Count == 0)
                {
                    containerPair.Value.ResetStatus();
                }
            }
            //处理共享缓存
            foreach (var pair in entityKeyDict)
            {
                //排除不过期的
                if (!pair.Value)
                {
                    continue;
                }

                CacheContainer container;
                if (TryRemove(pair.Key, out container, t => true))
                {
                    var itemSetList = container.Collection.ToList <CacheItemSet>();
                    TraceLog.ReleaseWrite("Cache shard entity:{0} expired has been removed, count:{1}.", pair.Key, itemSetList.Count());
                    foreach (var itemPair in itemSetList)
                    {
                        CacheItemSet itemSet = itemPair.Value;
                        object       temp;
                        if (container.Collection.TryRemove(itemPair.Key, out temp))
                        {
                            itemSet.ResetStatus();
                            itemSet.Dispose();
                        }
                    }
                    container.ResetStatus();
                    container.Dispose();
                }
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// 完成工作项
        /// </summary>
        public void CompleteWorkItem(IUser user)
        {
            using (ITransaction trans = UnitOfWork.BeginTransaction(typeof(WorkItem)))
            {
                Context.WorkItem.CurrentState = (short)WorkItemStatus.Compeleted;
                Context.WorkItem.Executor = WFUtil.User.ID;
                Context.WorkItem.ExecutorName = WFUtil.User.Name;
                Context.WorkItem.ExecuteTime = DateTime.Now;
                Persistence.Repository.SaveOrUpdate(Context.WorkItem);

                TraceLog traceLog = new TraceLog()
                {
                    ActionType = (short)Operation.Complete,
                    ActivityID = Context.ActivityInst.ActivityDefID,
                    ActivityInstID = Context.ActivityInst.ID,
                    ClientIP = WebUtil.GetClientIP(),
                    ID = IdGenerator.NewComb().ToSafeString(),
                    Operator = WFUtil.User.ID,
                    ProcessID = Context.ProcessInst.ProcessDefID,
                    ProcessInstID = Context.ProcessInst.ID,
                    WorkItemID = Context.WorkItem.ID,
                    Message = string.Format("完成工作项{0}", Context.WorkItem.Name),
                    CreateTime = DateTime.Now
                };
                Persistence.Repository.SaveOrUpdate(traceLog);

                trans.Commit();
            }
        }
Ejemplo n.º 22
0
        public override void Process()
        {
            TraceLog.WriteInfo("Start get room info process");
            RCGetRoomInfo response = new RCGetRoomInfo();

            response.RoomInfo = new PBRoomInfo()
            {
                Id        = m_Room.Id,
                StartTime = m_Room.StartTime,
                State     = (int)m_Room.State
            };
            RoomSessionUser user = new RoomSessionUser(m_Request.PlayerId, m_Request.RoomId);

            user.Online(m_Session);

            foreach (var roomPlayer in m_Room.Players)
            {
                PBRoomPlayerInfo rp = new PBRoomPlayerInfo();
                rp.PlayerInfo = new PBPlayerInfo()
                {
                    Id           = roomPlayer.Value.PlayerId,
                    Name         = roomPlayer.Value.Name,
                    Level        = roomPlayer.Value.Level,
                    VipLevel     = roomPlayer.Value.VipLevel,
                    PortraitType = roomPlayer.Value.PortraitType,
                    PositionX    = roomPlayer.Value.PositionX,
                    PositionY    = roomPlayer.Value.PositionY,
                    Rotation     = roomPlayer.Value.Rotation,
                };
                foreach (var hero in roomPlayer.Value.Heros)
                {
                    PBLobbyHeroInfo lh = new PBLobbyHeroInfo()
                    {
                        Type = hero.HeroType,
                    };
                    lh.SkillLevels.AddRange(hero.Skills);

                    PBRoomHeroInfo rh = new PBRoomHeroInfo()
                    {
                        EntityId                 = hero.EntityId,
                        LobbyHeroInfo            = lh,
                        HP                       = hero.HP,
                        MaxHP                    = hero.MaxHP,
                        PhysicalAttack           = hero.PhysicalAttack,
                        PhysicalDefense          = hero.PhysicalDefense,
                        MagicAttack              = hero.MagicAttack,
                        MagicDefense             = hero.MagicDefense,
                        PhysicalAtkHPAbsorbRate  = hero.PhysicalAtkHPAbsorbRate,
                        PhysicalAtkReflectRate   = hero.PhysicalAtkReflectRate,
                        MagicAtkHPAbsorbRate     = hero.MagicAtkHPAbsorbRate,
                        MagicAtkReflectRate      = hero.MagicAtkReflectRate,
                        CriticalHitProb          = hero.CriticalHitProb,
                        CriticalHitRate          = hero.CriticalHitRate,
                        OppPhysicalDfsReduceRate = hero.OppPhysicalDfsReduceRate,
                        OppMagicDfsReduceRate    = hero.OppMagicDfsReduceRate,
                        DamageReductionRate      = hero.DamageReductionRate,
                        AntiCriticalHitProb      = hero.AntiCriticalHitProb,
                        AdditionalDamage         = hero.AdditionalDamage,
                        RecoverHP                = hero.RecoverHP,
                        ReducedSkillCoolDownRate = hero.ReducedSkillCoolDownRate,
                        HeroSwitchCoolDownRate   = hero.ReduceSwitchHeroCoolDownRate,
                        Camp                     = roomPlayer.Value.Camp,
                    };
                    rp.RoomHeroInfo.Add(rh);
                }
                response.RoomInfo.RoomPlayerInfo.Add(rp);
            }
            byte[] buffer = CustomActionDispatcher.GeneratePackageStream((int)ActionType, ProtoBufUtils.Serialize(response));
            m_Session.SendAsync(buffer, 0, buffer.Length);
        }
Ejemplo n.º 23
0
 /// <summary>
 /// Afters the minimum.
 /// </summary>
 /// <param name="log">The log.</param>
 public void AfterMin(TraceLog log)
 {
     TraceQuery(log);
 }
Ejemplo n.º 24
0
 private static void watcher_Error(object sender, ErrorEventArgs e)
 {
     TraceLog.WriteError("Script file has changed error:{0}", e.GetException().ToString());
 }
Ejemplo n.º 25
0
 /// <summary>
 /// Afters the sum all.
 /// </summary>
 /// <param name="log">The log.</param>
 public void AfterSumAll(TraceLog log)
 {
     TraceQuery(log);
 }
Ejemplo n.º 26
0
        private static ScriptRuntimeScope InitScriptRuntimeScope()
        {
            //star compile
            if (Interlocked.Exchange(ref _isCompiling, 1) == 0)
            {
                ScriptRuntimeDomain runtimeDomain = null;
                try
                {
                    string runtimePath = MathUtils.RuntimePath ?? MathUtils.RuntimeBinPath;

                    runtimeDomain = new ScriptRuntimeDomain(typeof(ScriptRuntimeDomain).Name, new[] { _settupInfo.RuntimePath, });
                    foreach (var assemblyName in AppDomain.CurrentDomain.GetAssemblies())//_settupInfo.ReferencedAssemblyNames)
                    {
                        ////排除System的dll
                        //if (string.IsNullOrEmpty(assemblyName) ||
                        //    !Path.IsPathRooted(assemblyName)) continue;
                        string key = Path.GetFileNameWithoutExtension(assemblyName.GetName().Name);

                        runtimeDomain.AddAssembly(key, assemblyName);
                    }
                    var scope = runtimeDomain.CreateScope(_settupInfo);
                    //ignore error, allow model is empty.
                    if (scope == null)
                    {
                        if (_runtimeDomain == null)
                        {
                            _runtimeDomain = runtimeDomain;
                        }
                        return(scope);
                    }

                    //update befor
                    bool isFirstRun = _runtimeDomain == null;
                    if (!isFirstRun && _settupInfo.ModelChangedBefore != null)
                    {
                        if (_runtimeDomain.Scope.ModelAssembly != null)
                        {
                            _settupInfo.ModelChangedBefore(_runtimeDomain.Scope.ModelAssembly);
                        }
                        TimeListener.Clear();
                        if (_runtimeDomain.MainInstance != null)
                        {
                            _runtimeDomain.MainInstance.Stop();
                        }
                    }
                    runtimeDomain.Scope.InitDll();
                    runtimeDomain.Scope.Init();
                    runtimeDomain.Scope.InitCsharp();

                    runtimeDomain.MainInstance = (dynamic)runtimeDomain.Scope.Execute(_settupInfo.ScriptMainProgram, _settupInfo.ScriptMainTypeName);
                    if (_runtimeDomain != null)
                    {
                        //unload pre-domain
                        _runtimeDomain.Dispose();
                    }
                    _runtimeDomain = runtimeDomain;
                    EntitySchemaSet.EntityAssembly = scope.ModelAssembly;
                    //update after
                    if (!isFirstRun && _settupInfo.ModelChangedAfter != null && scope.ModelAssembly != null)
                    {
                        _settupInfo.ModelChangedAfter(scope.ModelAssembly);
                    }
                    else if (scope.ModelAssembly != null)
                    {
                        ProtoBufUtils.LoadProtobufType(scope.ModelAssembly);
                        EntitySchemaSet.LoadAssembly(scope.ModelAssembly);
                    }
                    PrintCompiledMessage();
                    //replace runtime
                    if (!isFirstRun && runtimeDomain.MainInstance != null)
                    {
                        runtimeDomain.MainInstance.ReStart();
                    }
                    return(scope);
                }
                finally
                {
                    Interlocked.Exchange(ref _isCompiling, 0);
                }
            }
            else
            {
                TraceLog.WriteLine("{1} {0} has not compiled in other thread.", "model", DateTime.Now.ToString("HH:mm:ss"));
            }
            return(null);
        }
Ejemplo n.º 27
0
 /// <summary>
 /// Afters the update all.
 /// </summary>
 /// <param name="log">The log.</param>
 public void AfterUpdateAll(TraceLog log)
 {
     TraceQuery(log);
 }
Ejemplo n.º 28
0
        private static void DoWatcherChanged(object state)
        {
            try
            {
                if (IsCompiling)
                {
                    //延迟处理
                    _changeWatchingTimer.Change(_settupInfo.ScriptChangedDelay, Timeout.Infinite);
                    return;
                }
                HashSet <string> tmp = new HashSet <string>();
                var changedFiles     = Interlocked.Exchange <HashSet <string> >(ref _changedFiles, tmp);
                _changeWatchingTimer.Change(Timeout.Infinite, Timeout.Infinite);

                HashSet <string> localChangedFiles = new HashSet <string>();
                foreach (var file in changedFiles)
                {
                    //check file changed for md5 encode.
                    if (_runtimeDomain.Scope.VerifyScriptHashCode(file))
                    {
                        continue;
                    }
                    localChangedFiles.Add(file);
                }
                TraceLog.WriteLine("Update script file count:{0}.", localChangedFiles.Count);
                if (localChangedFiles.Count == 0)
                {
                    return;
                }
                bool hasModelFile = false;
                //以文件类型分组
                var changeGroup = localChangedFiles.GroupBy(t =>
                {
                    if (!hasModelFile && _runtimeDomain.Scope.IsModelScript(t))
                    {
                        hasModelFile = true;
                    }
                    return(Path.GetExtension(t));
                })
                                  .OrderBy(t => t.Key);

                bool isLoop = true;
                foreach (var group in changeGroup)
                {
                    if (!isLoop)
                    {
                        break;
                    }

                    string ext = group.Key.ToLower();
                    switch (ext)
                    {
                    case ".cs":
                        //star compile
                        if (hasModelFile)
                        {
                            TraceLog.WriteLine("{1} {0} compile start...", "model script", DateTime.Now.ToString("HH:mm:ss"));
                            var scope = InitScriptRuntimeScope();

                            PrintCompiledMessage("model script", scope != null && scope.ModelAssembly != null ? scope.ModelAssembly.FullName : "null");
                            isLoop = false;
                        }
                        else
                        {
                            if (Interlocked.Exchange(ref _isCompiling, 1) == 0)
                            {
                                try
                                {
                                    var str = group.Last();

                                    TraceLog.WriteLine("{1} {0} compile start...", "csharp script", DateTime.Now.ToString("HH:mm:ss"));

                                    _runtimeDomain.Scope.InitCsharp();
                                    _runtimeDomain.MainInstance = (dynamic)_runtimeDomain.Scope.Execute(_settupInfo.ScriptMainProgram, typeName: _settupInfo.ScriptMainTypeName);
                                    RunMainProgram();
                                    //   _runtimeDomain.MainInstance.Start(_runtimeDomain.MainArgs);
                                    PrintCompiledMessage("csharp script");
                                }
                                finally
                                {
                                    Interlocked.Exchange(ref _isCompiling, 0);
                                }
                            }
                            else
                            {
                                TraceLog.WriteLine("{1} {0} has not compiled in other thread.", "csharp script", DateTime.Now.ToString("HH:mm:ss"));
                            }
                        }

                        break;

                    case ".py":
                        _runtimeDomain.Scope.InitPython(group.ToArray());
                        PrintCompiledMessage("python script");
                        break;

                    case ".lua":
                        _runtimeDomain.Scope.InitLua();
                        PrintCompiledMessage("lua script");
                        break;

                    default:
                        throw new NotSupportedException(string.Format("Script type \"{0}\" not supported.", ext));
                    }
                    DoScriptLoaded(ext, group.ToArray());
                }
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("DoWatcherChanged error:{0}", ex);
            }
        }
Ejemplo n.º 29
0
 /// <summary>
 /// Afters the batch query.
 /// </summary>
 /// <param name="log">The log.</param>
 public void AfterBatchQuery(TraceLog log)
 {
     TraceQuery(log);
 }
Ejemplo n.º 30
0
 /// <summary>
 /// Afters the delete all.
 /// </summary>
 /// <param name="log">The log.</param>
 public void AfterDeleteAll(TraceLog log)
 {
     TraceQuery(log);
 }
Ejemplo n.º 31
0
        public ICallTreeDataProvider Get()
        {
            var queryString = this.httpRequest.Query;

            string filename  = queryString["filename"];
            string stacktype = queryString["stacktype"];

            if (string.IsNullOrEmpty(filename))
            {
                throw new ArgumentNullException("filename");
            }

            if (string.IsNullOrEmpty(stacktype))
            {
                throw new ArgumentNullException("stacktype");
            }

            /* symbols and sources related parameters */
            string     sympathStr         = (string)queryString["sympath"] ?? SymbolPath.MicrosoftSymbolServerPath;
            SymbolPath symPath            = new SymbolPath(sympathStr);
            string     defaultSymbolCache = symPath.DefaultSymbolCache();

            // Normalize the symbol path.
            symPath    = symPath.InsureHasCache(defaultSymbolCache);
            sympathStr = symPath.ToString();

            string srcpath = (string)queryString["srcpath"];
            //TODO FIX NOW: Dont spew to the Console, send it back to the client.
            SymbolReader symbolReader = new SymbolReader(Console.Out, sympathStr);

            if (srcpath != null)
            {
                symbolReader.SourcePath = srcpath;
            }

            string modulePatStr = (string)queryString["symLookupPats"] ?? @"^(clr|ntoskrnl|ntdll|.*\.ni)";

            /* filtering parameters */
            string start     = (string)queryString["start"] ?? string.Empty;
            string end       = (string)queryString["end"] ?? string.Empty;
            string incpats   = (string)queryString["incpats"] ?? string.Empty;
            string excpats   = (string)queryString["excpats"] ?? string.Empty;
            string foldpats  = (string)queryString["foldpats"] ?? string.Empty;
            string grouppats = (string)queryString["grouppats"] ?? string.Empty;
            string foldpct   = (string)queryString["foldpct"] ?? string.Empty;
            string find      = (string)queryString["find"] ?? string.Empty;

            EtlxFile etlxFile;

            // Do it twice so that XXX.etl.zip becomes XXX.
            string etlxFilePath = Path.ChangeExtension(Path.ChangeExtension(filename, null), ".etlx");

            lock (this.etlxCache)
            {
                if (this.etlxCache.TryGetValue(filename, out etlxFile))
                {
                    if (etlxFile == null)
                    {
                        throw new ArgumentNullException("etlxFile");
                    }
                }
                else
                {
                    etlxFile = new EtlxFile(filename)
                    {
                        Pending = true
                    };
                    this.etlxCache.Set(filename, etlxFile, this.cacheExpirationTime);
                }
            }

            lock (etlxFile)
            {
                if (etlxFile.Pending)
                {
                    if (!File.Exists(etlxFilePath))
                    {
                        // if it's a zip file
                        if (string.Equals(Path.GetExtension(filename), ".zip", StringComparison.OrdinalIgnoreCase))
                        {
                            //TODO FIX NOW: Dont spew to the Console, send it back to the client.
                            ZippedETLReader reader = new ZippedETLReader(filename, Console.Out);
                            reader.SymbolDirectory = defaultSymbolCache;
                            reader.EtlFileName     = Path.ChangeExtension(etlxFilePath, etlExtension);
                            reader.UnpackArchive();
                            TraceLog.CreateFromEventTraceLogFile(reader.EtlFileName, etlxFilePath);
                        }
                        else
                        {
                            TraceLog.CreateFromEventTraceLogFile(filename, etlxFilePath);
                        }
                    }

                    etlxFile.TraceLog = TraceLog.OpenOrConvert(etlxFilePath);
                    etlxFile.Pending  = false;
                }

                Regex modulePat = new Regex(modulePatStr, RegexOptions.IgnoreCase);
                foreach (var moduleFile in etlxFile.TraceLog.ModuleFiles)
                {
                    if (modulePat.IsMatch(moduleFile.Name))
                    {
                        etlxFile.TraceLog.CodeAddresses.LookupSymbolsForModule(symbolReader, moduleFile);
                    }
                }
            }

            StackViewerSession stackViewerSession;

            lock (this.stackViewerSessionCache)
            {
                var filterParams = new FilterParams {
                    Name = filename + stacktype, StartTimeRelativeMSec = start, EndTimeRelativeMSec = end, MinInclusiveTimePercent = foldpct, FoldRegExs = foldpats, IncludeRegExs = incpats, ExcludeRegExs = excpats, GroupRegExs = grouppats
                };
                var keyBuilder = new StringBuilder();
                keyBuilder.Append(filterParams.Name).Append("?" + filterParams.StartTimeRelativeMSec).Append("?" + filterParams.EndTimeRelativeMSec).Append("?" + filterParams.MinInclusiveTimePercent).Append("?" + filterParams.FoldRegExs).Append("?" + filterParams.IncludeRegExs).Append("?" + filterParams.ExcludeRegExs).Append("?" + filterParams.GroupRegExs).Append("?" + find);

                var stackViewerKey = keyBuilder.ToString();
                if (this.stackViewerSessionCache.TryGetValue(stackViewerKey, out stackViewerSession))
                {
                    if (stackViewerSession == null)
                    {
                        throw new ArgumentNullException("stackViewerSession");
                    }
                }
                else
                {
                    stackViewerSession = new StackViewerSession(filename, stacktype, etlxFile.TraceLog, filterParams, symbolReader);
                    this.stackViewerSessionCache.Set(stackViewerKey, stackViewerSession, cacheExpirationTime);
                }
            }

            lock (stackViewerSession)
            {
                if (stackViewerSession.Pending)
                {
                    stackViewerSession.InitializeDataProvider();
                    stackViewerSession.Pending = false;
                }
            }

            return(stackViewerSession.GetDataProvider());
        }
Ejemplo n.º 32
0
 /// <summary>
 /// Afters the execute non query.
 /// </summary>
 /// <param name="log">The log.</param>
 public void AfterExecuteNonQuery(TraceLog log)
 {
     TraceQuery(log);
 }
Ejemplo n.º 33
0
        static async Task ProcessListenerContext(HttpListenerContext listenerContext, HttpAsyncHost host)
        {
            Stopwatch sw              = Stopwatch.StartNew();
            string    rawUrl          = string.Empty;
            string    userHostAddress = string.Empty;
            long      actionTime      = 0;
            string    identity        = string.Empty;

            try
            {
                rawUrl          = listenerContext.Request.RawUrl;
                userHostAddress = host.HttpCdnAddress.GetUserHostAddress(listenerContext.Request.RemoteEndPoint, key => listenerContext.Request.Headers[key]);
                // Get the response action to take:
                var requestContext = new HttpRequestContext(host._hostContext, listenerContext.Request, listenerContext.User, userHostAddress);
                var action         = await host._handler.Execute(requestContext);

                actionTime = sw.ElapsedMilliseconds;

                if (action != null)
                {
                    if (listenerContext.Request.HttpMethod == "POST")
                    {
                        rawUrl += action.RequestParams;
                    }
                    identity = action.Identity;
                    // Take the action and await its completion:
                    var responseContext = new HttpRequestResponseContext(requestContext, listenerContext.Response);
                    var task            = action.Execute(responseContext);
                    if (task != null)
                    {
                        await task;
                    }
                }
                // Close the response and send it to the client:
                listenerContext.Response.Close();
                sw.Stop();
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("Http ProcessListenerContext {0}\r\nUrl:{1}\r\nHost:{2}, User:{3}", ex, rawUrl, userHostAddress, identity);
            }
            finally
            {
                if (sw.ElapsedMilliseconds >= 5)
                {
                    TraceLog.Write("Http request action time:{0}ms, total:{1}ms.\r\nRawUrl:{2}\r\nHost:{3}, User:{4}", actionTime, sw.ElapsedMilliseconds, rawUrl, userHostAddress, identity);
                }
                if (sw.ElapsedMilliseconds == 0)
                {
                }
                else if (sw.ElapsedMilliseconds <= 20)
                {
                    Interlocked.Increment(ref _20s);
                }
                else if (sw.ElapsedMilliseconds <= 50)
                {
                    Interlocked.Increment(ref _50s);
                }
                else if (sw.ElapsedMilliseconds <= 100)
                {
                    Interlocked.Increment(ref _100s);
                }
                else if (sw.ElapsedMilliseconds <= 200)
                {
                    Interlocked.Increment(ref _200s);
                }
                else if (sw.ElapsedMilliseconds <= 500)
                {
                    Interlocked.Increment(ref _500s);
                }
                else if (sw.ElapsedMilliseconds <= 1000)
                {
                    Interlocked.Increment(ref _1000s);
                }
                else if (sw.ElapsedMilliseconds <= 2000)
                {
                    Interlocked.Increment(ref _2000s);
                }
                else if (sw.ElapsedMilliseconds <= 5000)
                {
                    Interlocked.Increment(ref _5000s);
                }
                else
                {
                    TraceLog.WriteError("Http request action timeout:{0}ms, total:{1}ms.\r\nRawUrl:{2}\r\nHost:{3}, User:{4}", actionTime, sw.ElapsedMilliseconds, rawUrl, userHostAddress, identity);
                    Interlocked.Increment(ref _up);
                }
            }
        }
Ejemplo n.º 34
0
 /// <summary>
 /// Afters the execute reader.
 /// </summary>
 /// <param name="log">The log.</param>
 public void AfterExecuteReader(TraceLog log)
 {
     TraceQuery(log);
 }
Ejemplo n.º 35
0
 public AllocTickConverter(TraceLog log)
 {
     m_traceLog = log;
 }
Ejemplo n.º 36
0
 /// <summary>
 /// Afters the execute scalar.
 /// </summary>
 /// <param name="log">The log.</param>
 public void AfterExecuteScalar(TraceLog log)
 {
     TraceQuery(log);
 }
Ejemplo n.º 37
0
 internal void SaveLog(TraceLog log)
 {
     this.OnSaveLog(log);
 }
Ejemplo n.º 38
0
 /// <summary>
 /// Afters the exists.
 /// </summary>
 /// <param name="log">The log.</param>
 public void AfterExists(TraceLog log)
 {
     TraceQuery(log);
 }
Ejemplo n.º 39
0
 /// <summary>
 /// Constructs a new processor for the provided data files.
 /// </summary>
 /// <param name="events">The data file containing events.</param>
 /// <param name="counters">The data file containing harware coutnters.</param>
 public PreProcessor(TraceLog events, TraceCounter[] counters)
     : base(events, counters)
 {
 }
Ejemplo n.º 40
0
 /// <summary>
 /// Afters the insert all.
 /// </summary>
 /// <param name="log">The log.</param>
 public void AfterInsertAll(TraceLog log)
 {
     TraceQuery(log);
 }
        private void PostTraceLog(string traceLogMessage, TraceLog logType)
        {
            Hashtable messagePacket = new Hashtable();

            messagePacket.Add("PacketName", "TraceLog");
            messagePacket.Add("TraceLogType", ((int)logType).ToString());
            messagePacket.Add("TraceLogMessage", traceLogMessage);
            host.PostMessagePacket(messagePacket);
        }
Ejemplo n.º 42
0
        public void Run(object state)
        {
            try
            {
                EventPublisher.Publish<WorkItemExecutingEvent>(new WorkItemExecutingEvent()
                {
                    UUID = string.Format("{0}-{1}-{2}-WorkItemExecutingEvent", Context.ProcessDefine.ID, Context.ProcessDefine.Version, Context.Activity.ID),
                    Context = Context
                });

                CompleteWorkItem(WFUtil.User);

                EventPublisher.Publish<WorkItemExecutedEvent>(new WorkItemExecutedEvent()
                {
                    UUID = string.Format("{0}-{1}-{2}-WorkItemExecutedEvent", Context.ProcessDefine.ID, Context.ProcessDefine.Version, Context.Activity.ID),
                    Context = Context
                });
            }
            catch (Exception ex)
            {
                TraceLog traceLog = new TraceLog()
                {
                    ActionType = (short)Operation.Complete,
                    ActivityID = Context.ActivityInst.ActivityDefID,
                    ActivityInstID = Context.ActivityInst.ID,
                    ClientIP = WebUtil.GetClientIP(),
                    ID = IdGenerator.NewComb().ToSafeString(),
                    Operator = WFUtil.User.ID,
                    ProcessID = Context.ProcessInst.ProcessDefID,
                    ProcessInstID = Context.ProcessInst.ID,
                    WorkItemID = Context.WorkItem.ID,
                    Message = string.Format("完成工作项{0}出错,WorkItemID={1}", Context.WorkItem.Name, Context.WorkItem.ID),
                    CreateTime = DateTime.Now
                };
                Persistence.Repository.SaveOrUpdate(traceLog);
                AbortWorkItem();
                WFUtil.HandleException(new WFException(GetType().FullName, string.Format("完成工作项{0}出错,WorkItemID={1}", Context.WorkItem.Name, Context.WorkItem.ID), ex));

                EventPublisher.Publish<WorkItemErrorEvent>(new WorkItemErrorEvent()
                {
                    UUID = string.Format("{0}-{1}-{2}-WorkItemErrorEvent", Context.ProcessDefine.ID, Context.ProcessDefine.Version, Context.Activity.ID),
                    Context = Context
                });
            }
        }