示例#1
0
 void Awake()
 {
     if (instance == null)
     {
         instance = this;
     }
 }
示例#2
0
        public override bool AllowMessage(DebugMessage message)
        {
            if(message == null) {
                return true;
            }

            return Enabled && (message.Type == DebugMessageType.Error);
        }
示例#3
0
 internal ServerNamedPipe(string name, uint outBuffer, uint inBuffer, int maxReadBytes, bool secure, IChannelManager pipeManager, DebugMessage activityRef)
 {
     DebugMessageRef = activityRef;
     PipeManager = pipeManager;
     PipeConnection = new ServerPipeConnection(name, outBuffer, inBuffer, maxReadBytes, secure);
     PipeThread = new Thread(new ThreadStart(PipeListener));
     PipeThread.IsBackground = true;
     PipeThread.Name = "Pipe Thread " + this.PipeConnection.NativeHandle.ToString();
     LastAction = DateTime.Now;
 }
示例#4
0
        public static ClientMessage ReadFrom(System.IO.BinaryReader reader)
        {
            switch (reader.ReadInt32())
            {
            case DebugMessage.TAG:
                return(DebugMessage.ReadFrom(reader));

            case ActionMessage.TAG:
                return(ActionMessage.ReadFrom(reader));

            case DebugUpdateDone.TAG:
                return(DebugUpdateDone.ReadFrom(reader));

            case RequestDebugState.TAG:
                return(RequestDebugState.ReadFrom(reader));

            default:
                throw new System.Exception("Unexpected tag value");
            }
        }
示例#5
0
    //[Sirenix.OdinInspector.Button]
    public void ClearMessagesForTag(tags tag)
    {
        bool hasFoundAsset = false;

        for (int i = 0; i < messages.Count; i++)
        {
            DebugMessage msg = messages[i];
            if (msg.tag == tag /*&& UnityEditor.AssetDatabase.LoadAssetAtPath("Assets/AlexScripts/AlexToolScripts/Resources/" + msg.name + ".asset", typeof(DebugMessage)) != null*/)
            {
                hasFoundAsset = true;
                //UnityEditor.AssetDatabase.DeleteAsset("Assets/AlexScripts/AlexToolScripts/Resources/" + msg.name + ".asset");
                messages.Remove(msg);
                //UnityEditor.AssetDatabase.SaveAssets();
            }
        }
        if (hasFoundAsset)
        {
            ClearMessagesForTag(tag);
        }
    }
示例#6
0
 WayPoint obstacleAvoidance(WayPoint nextWaypoint, WayPoint currentLocation)
 {
     // Everything is in meters and radians
     if (Settings.UseVision)
     {
         if (AvoidanceVector.magnitude > 0)
         {
             SumVector             = new Vector2d(currentLocation, nextWaypoint);
             SumVector.magnitude  /= SumVector.magnitude;                           //Normalize(Check if normalize is needed)
             SumVector.magnitude  *= Alpha;                                         // Influence(Check if maxspeed is needed)
             AvoidanceVector.angle = (temp.angle + (45 * Math.PI / 180) + Heading); // add heading + 90Make Lidar data relative to robot position
             DebugMessage.Clear();
             DebugMessage.Append((AvoidanceVector.angle * 180 / Math.PI));
             SumVector          += AvoidanceVector;                                      //combine Avoidance and Attraction vector
             SumVector.magnitude = Math.Max(ReachWaypointZone + 1, SumVector.magnitude); //set the minimum vector length to 4 meters
             nextWaypoint        = WayPoint.Projection(currentLocation, SumVector.angle, SumVector.magnitude);
         }
     }
     return(nextWaypoint);
 }
        private void ReceivedMessage(CommunicationMessage message)
        {
            if (!IsMe(message.To))
            {
                DebugMessage?.Invoke($"Received an invalid message: addressed to someone other than me - to: {message.To.Name}, {message.Type}, from {message.From.Name})");
                return;
            }

            DebugMessage?.Invoke($"{message.To.Name} << Received ({message.Type}) from {message.From.Name}");

            if (message.To.Role == IdentityRole.Host && !message.From.Equals(_hostId))
            {
                UpdateHostClientList(message.From, message);
            }
            else
            {
                RequestClientListFromHost();
            }

            SendResponse(message.To, message, _hostClientsList);
        }
        private void MessageCallBack(DebugMessage response)
        {
            if (response == null)
            {
                return;
            }

            lock (queue)
            {
                //Console.WriteLine(response.ToString());

                sent.Remove(response);
            }

            var message = response.Other as UnitTestRequest;

            if (message != null)
            {
                message.ParseResultData(response.ResponseData);
            }
        }
示例#9
0
        void _debugActionWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            while (!((BackgroundWorker)sender).CancellationPending)
            {
                try
                {
                    DebugActionQueueObject dao = null;
                    TaskQueues.TryDequeue(out dao);

                    if (dao != null && dao.ActionObj.Action.Name != null && dao.ActionObj.Action.Name.Length >= 1 && dao.ActionObj.StepList != null && dao.ActionObj.StepList.Length >= 1)
                    {
                        //有效任务
                        if (MainService.TaskService.RunMode == RunModeType.Debug)
                        {
                            //执行动作
                            MainService.TaskService.RunAction(dao.ActionObj.Action, new List <SpeakerLibrary.SportDB.Robot_Steps>(dao.ActionObj.StepList));

                            //发送回复
                            DebugMessage dm = new DebugMessage();
                            dm.Command = CommandConst.ActionRunFinish;
                            dm.Content = dao.MessageId;
                            SendMessage(dao.ConnectionName, dm);
                        }
                    }
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine(ex.ToString());
                }

                try
                {
                    Thread.Sleep(15);
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine(ex.ToString());
                }
            }
        }
示例#10
0
        private void hideType_Click(object sender, EventArgs e)
        {
            if (messages.SelectedRows.Count == 1)
            {
                DataGridViewRow typerow = messages.SelectedRows[0];

                int msgIdx = GetMessageIndex(typerow.Index);

                DebugMessage msg = m_Core.DebugMessages[msgIdx];

                bool hiderows = IsRowVisible(msgIdx);

                m_SuppressRefresh = true;

                for (int i = 0; i < m_Core.DebugMessages.Count; i++)
                {
                    var message = m_Core.DebugMessages[i];

                    if (message.category == msg.category &&
                        message.severity == msg.severity &&
                        message.messageID == msg.messageID)
                    {
                        if (hiderows)
                        {
                            HideRow(i);
                        }
                        else
                        {
                            ShowRow(i);
                        }
                    }
                }

                m_SuppressRefresh = false;

                RefreshMessageList();

                messages.ClearSelection();
            }
        }
示例#11
0
        private void MessageCallBack(DebugMessage response)
        {
            if (response == null)
            {
                return;
            }

            lock (Queue)
            {
                LastResponse = (int)StopWatch.ElapsedMilliseconds;

                CompletedUnitTestCount++;
                Pending.Remove(response);

                //Console.WriteLine("Received: " + (response.Other as UnitTest).FullMethodName);
                //Console.WriteLine(response.ToString());

                if (CompletedUnitTestCount % 1000 == 0 && StopWatch.Elapsed.Seconds != 0)
                {
                    Console.WriteLine("Unit Tests - Count: " + CompletedUnitTestCount.ToString() + " Elapsed: " + ((int)StopWatch.Elapsed.TotalSeconds).ToString() + " (" + (CompletedUnitTestCount / StopWatch.Elapsed.TotalSeconds).ToString("F2") + " per second)");
                }
            }

            if (response.Other is UnitTest unitTest)
            {
                UnitTestSystem.ParseResultData(unitTest, response.ResponseData);

                if (Equals(unitTest.Expected, unitTest.Result))
                {
                    unitTest.Status = UnitTestStatus.Passed;
                }
                else
                {
                    unitTest.Status = UnitTestStatus.Failed;
                }

                //Console.WriteLine("RECD: " + unitTest.MethodTypeName + "." + unitTest.MethodName);
            }
        }
示例#12
0
        private void DisplayMemory(DebugMessage message)
        {
            cbSelect.Enabled = Enabled;

            int  start = message.GetInt32(0);
            int  lines = message.GetInt32(4) / 16;
            uint at    = (uint)start;

            try
            {
                string[] newlines = new string[lines];

                for (int line = 0; line < lines; line++)
                {
                    string l = at.ToString("X").PadLeft(8, '0') + ':';
                    string d = string.Empty;
                    for (int x = 0; x < 16; x++)
                    {
                        byte mem = message.ResponseData[at - start + 8];
                        if (x % 4 == 0)
                        {
                            l = l + ' ';
                        }
                        l = l + mem.ToString("X").PadLeft(2, '0');
                        char b = (char)mem;
                        d = d + (char.IsLetterOrDigit(b) ? b : '.');
                        at++;
                    }

                    newlines[line] = l + ' ' + d;
                }
                lbMemory.Lines = newlines;
                Status         = string.Empty;
            }
            catch (Exception e)
            {
                Status = "Error: " + e.ToString();
            }
        }
示例#13
0
        private void DebugBlocked(StepTaskEntityBase stepTaskEntity)
        {
            _hitBreakPointsLock.EnterWriteLock();

            // 暂停的场景
            CoroutineHandle coroutineHandle = stepTaskEntity.Coroutine;

            if (_hitBreakPoints.ContainsKey(coroutineHandle.Id))
            {
                _hitBreakPoints[coroutineHandle.Id] = stepTaskEntity;
            }
            // 断点命中的场景
            else
            {
                _hitBreakPoints.Add(coroutineHandle.Id, stepTaskEntity);
            }
            _hitBreakPointsLock.ExitWriteLock();

            CallStack breakPoint = stepTaskEntity.GetStack();

            _watchDatas.Values.Clear();
            foreach (string watchData in _watchDatas.Names)
            {
                string variableName = ModuleUtils.GetVariableNameFromParamValue(watchData);
                _watchDatas.Values.Add(_context.VariableMapper.GetWatchDataValue(variableName, watchData));
            }
            DebugMessage debugMessage = new DebugMessage(MessageNames.BreakPointHitName, _context.SessionId,
                                                         breakPoint, false)
            {
                WatchData = _watchDatas
            };

            // 发送断点命中消息
            _context.MessageTransceiver.SendMessage(debugMessage);
            _context.LogSession.Print(LogLevel.Debug, _context.SessionId, $"Breakpoint hitted:{breakPoint}");

            coroutineHandle.WaitSignal();
        }
示例#14
0
    public void SaveCode(Text nameTextComponent)
    {
        int    result = -1;
        string text   = "";

        if (nameTextComponent != null)
        {
            text = nameTextComponent.text;
        }
        if (sourceCodeComponent != null)
        {
            result = sourceCodeComponent.SaveCode(text);
        }
        if (result == 0)
        {
            DebugMessage.SuccessMessage(TranslationManager.GetMessage("SavedSuccessfully"));
            PanelSaveBg.ExitAnimation();
        }
        else
        {
            DebugMessage.ErrorMessage(TranslationManager.GetMessage("ErrorSaving"));
        }
    }
示例#15
0
        private void btnUploadData_Click(object sender, EventArgs e)
        {
            if (Client != null && Client.Connections.Count >= 1)
            {
                if (MessageBox.Show("真的要同步吗?", "提示", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    DebugMessage dm = new DebugMessage();
                    dm.Command = CommandConst.UploadDataBase;
                    dm.MsgId   = Guid.NewGuid().ToString();
                    dm.Content = Convert.ToBase64String(File.ReadAllBytes(Path.Combine(Application.StartupPath, "static.db")));

                    SocketLibrary.Connection conn = null;
                    Client.Connections.TryGetValue(Client.ClientName, out conn);
                    if (conn != null)
                    {
                        SocketLibrary.Message msg = new SocketLibrary.Message(SocketLibrary.Message.CommandType.SendMessage, DebugMessage.ToJson(dm));
                        conn.messageQueue.Enqueue(msg);
                    }

                    MessageBox.Show("同步完成!");
                }
            }
        }
示例#16
0
		public T Run<T>(string ns, string type, string method, params object[] parameters)
		{
			CheckCompiled();

			var request = new UnitTestRequest(ns, type, method, parameters);

			request.Resolve(typeSystem, linker);

			var message = new DebugMessage(DebugCode.ExecuteUnitTest, request.Message)
			{
				Other = request
			};
			QueueMessage(message);

			while (!request.HasResult)
			{
				Thread.Sleep(5);
			}

			var result = request.Result;

			if (request.RuntimeMethod.Signature.ReturnType.IsVoid)
				return default(T);

			try
			{
				if (default(T) is ValueType)
					return (T)result;
				else
					return default(T);
			}
			catch (InvalidCastException e)
			{
				Debug.Fail(String.Format("Failed to convert result {0} of destination {1} destination type {2}.", result, result.GetType(), typeof(T).ToString()));
				throw;
			}
		}
示例#17
0
        private void send()
        {
            try
            {
                while (true)
                {
                    newData.WaitOne();

                    if (msgQueue.Count > 0)
                    {
                        Message msg = msgQueue.Dequeue();
                        if (msg.To == null)
                        {
                            DebugMessage.show("sending message to all clients");
                            ClientManager.sendToAll(msg.Body);
                        }
                        else
                        {
                            DebugMessage.show("sending message to client with ip: " + msg.To.TcpClient.Client.RemoteEndPoint);
                            msg.To.ClientStream.Write(msg.Body, 0, msg.Body.Length);
                        }
                    }
                }
            }
            catch (ThreadAbortException e)
            {
                ErrorMessage.show("send thread aborting, exception was:\r\n" + e.ToString());
            }
            catch (SocketException e)
            {
                ErrorMessage.show("SocketException in send thread, exception was:\r\n" + e.ToString());
            }
            finally
            {
                DebugMessage.show("exiting send thread");
            }
        }
示例#18
0
        private static void DebugCallback(DebugSource source,
                                          DebugType type,
                                          int id,
                                          DebugSeverity severity,
                                          int length,
                                          IntPtr message,
                                          IntPtr userParam)
        {
            string messageString = Marshal.PtrToStringAnsi(message, length);

            DebugMessage?.Invoke(messageString, source, type, severity, id);

            _log.Debug($"{severity.GetName()} {type.GetName()} | {messageString}");

            // if (type == DebugType.DebugTypePerformance)
            // {
            //     throw new Exception("Performance Error");
            // }

            if (type == DebugType.DebugTypeError && severity == DebugSeverity.DebugSeverityHigh)
            {
                throw new Exception(messageString);
            }
        }
示例#19
0
        public DebugEventInfo(DebugMessage message) : base(message.Id, EventType.Debug, message.Time)
        {
            switch (message.Name)
            {
            case MessageNames.BreakPointHitName:
                this.BreakPoint = message.BreakPoints[0];
                this.WatchData  = message.WatchData;
                this.IsDebugHit = true;
                break;

            case MessageNames.StepOverName:
            case MessageNames.StepIntoName:
            case MessageNames.ContinueName:
            case MessageNames.RunToEndName:
                this.IsDebugHit = false;
                this.BreakPoint = null;
                this.WatchData  = null;
                break;

            case MessageNames.RequestValueName:
                this.IsDebugHit = false;
                this.BreakPoint = message.BreakPoints[0];
                this.WatchData  = message.WatchData;
                break;

            case MessageNames.PauseName:
                this.IsDebugHit = false;
                this.BreakPoint = null;
                this.WatchData  = null;
                break;

            default:
                throw new ArgumentOutOfRangeException();
                break;
            }
        }
示例#20
0
 public PipeManager(DebugMessage activityRef)
 {
     DebugMessageRef = activityRef;
 }
示例#21
0
        public override bool AllowMessage(DebugMessage message)
        {
            if(message == null) {
                return true;
            }

            return Enabled && (message.BaseMethod.DeclaringObject == _object);
        }
示例#22
0
        public override bool AllowMessage(DebugMessage message)
        {
            if(message == null) {
                return true;
            }

            return Enabled && (message.BaseMethod.DeclaringNamespace == _namespace);
        }
示例#23
0
 /// <summary>Raises the <see cref="DebugMessage"/> event.</summary>
 /// <param name="e">
 ///     The <see cref="DebugEventArgs" /> instance containing the
 ///     event data.
 /// </param>
 /// <autogeneratedoc />
 /// TODO Edit XML Comment Template for OnDebugMessage
 private void OnDebugMessage(DebugEventArgs e)
 {
     Logger?.Debug(e.Message);
     DebugMessage?.Invoke(this, e);
 }
示例#24
0
        public override bool FilterMessage(DebugMessage message)
        {
            if (message == null)
            {
                return true;
            }

            if (message.message.Contains("block"))
            {
                return true;
            }

            return false;
        }
示例#25
0
 protected virtual void OnDebugMessage(string message, bool lineFeed, bool timeStamp)
 {
     DebugMessage?.Invoke(this, new DebugLogMessageEventArgs(message, lineFeed, timeStamp));
 }
示例#26
0
 public void DebugMsg(string Msg)
 {
     DebugMessage?.Invoke(Msg);
 }
示例#27
0
 private ConsoleColor GetMessageColor(DebugMessage message)
 {
     switch(message.Type) {
         case DebugMessageType.Error: {
             return ConsoleColor.Red;
             break;
         }
         case DebugMessageType.Warning: {
             return ConsoleColor.Yellow;
             break;
         }
         default: {
             return ConsoleColor.Green;
             break;
         }
     }
 }
        public void Initialize()
        {
            // Create the font
            mFont = GameObjectManager.pInstance.pContentManager.Load<SpriteFont>("Fonts\\DebugDisplay");

            mDynamicMsgs = new List<DebugMessage>(32);

            mDefaultHeader = new DebugMessage();
            mDefaultHeader.mMessage = "Debug Information:";
            mDynamicMsgs.Add(mDefaultHeader);

            // Allocate our constant string
            mConstantMsgs = new DebugMessage[mMaxConstMsgs];

            // Clear all the messages.
            for (int i = 0; i < mMaxConstMsgs; i++)
            {
                DebugMessage temp = new DebugMessage();
                temp.mMessage = "";
                mConstantMsgs[i] = temp;
            }

            mTextShadowColor = Color.Black;
            mTextColor = Color.White;

            mCurrentTag = null;
        }
        public void AddDynamicMessage(String newMsg, String tag)
        {
            // TODO: This should probably just keep reusing the same entries rather than reallocating
            //       every time. Not too worries since this is all wrapped in ALLOW_GARBAGE.
            DebugMessage d = new DebugMessage();
            d.mMessage = newMsg;
            d.mTag = tag;

            mDynamicMsgs.Add(d);
        }
示例#30
0
        public override bool DumpMessage(DebugMessage message)
        {
            dumpCount++;

            return true;
        }
示例#31
0
 protected virtual void OnDebugMessage(string text)
 {
     DebugMessage?.Invoke(this, new DebugLogMessageEventArgs(text));
 }
示例#32
0
 protected virtual void OnDebugMessage(object sender, EventArgs e)
 {
     DebugMessage?.Invoke(sender, e);
 }
示例#33
0
 public void DebugMessageConstructorTest()
 {
     DebugMessage target = new DebugMessage();
     Assert.Inconclusive("TODO: Implement code to verify target");
 }
示例#34
0
 private void UpdatePointers(DebugMessage message)
 {
     multibootStructure   = (uint)message.GetUInt32(4);
     physicalPageFreeList = (uint)message.GetUInt32(12);
 }
示例#35
0
        public void NotifyDebugMessage(TeamId team, string message)
        {
            var dm = new DebugMessage(message);

            _packetHandlerManager.BroadcastPacketTeam(team, dm, Channel.CHL_S2C);
        }
示例#36
0
        public override bool DumpMessage(DebugMessage message)
        {
            if(!Enabled) {
                return false;
            }

            writer.Write(message.Time.ToLongTimeString() + " | ");

            switch(message.Type) {
                case DebugMessageType.Error: {
                    writer.Write("Error");
                    break;
                }
                case DebugMessageType.Warning: {
                    writer.Write("Warning");
                    break;
                }
                default: {
                    writer.Write("Unknown");
                    break;
                }
            }

            writer.WriteLine(" | #" + HandledMessages);
            writer.WriteLine(message.Message + "\n");
            writer.Write("METHOD: ");
            writer.WriteLine(GetMethodTypeString(message.BaseMethod.Type) + message.BaseMethod.Method);
            writer.Write("LINE:   ");
            writer.WriteLine(message.BaseMethod.Line);
            writer.Write("FILE:   ");

            if(TruncateFile) {
                FileInfo fi = new FileInfo(message.BaseMethod.File);
                writer.WriteLine(fi.Name);
            }
            else {
                writer.WriteLine(message.BaseMethod.File);
            }

            if(UseStackInfo && message.HasStack) {
                writer.WriteLine("\nSTACK:");

                for(int i = 0; i < message.StackSegments.Count; i++) {
                    writer.WriteLine();
                    writer.Write("METHOD: ");
                    writer.WriteLine(GetMethodTypeString(message.BaseMethod.Type) + message.StackSegments[i].Method);
                    writer.Write("LINE:   ");
                    writer.WriteLine(message.StackSegments[i].Line);
                    writer.Write("FILE:   ");

                    if(TruncateFile) {
                        if(message.StackSegments[i].File != null) {
                            FileInfo fi = new FileInfo(message.StackSegments[i].File);
                            writer.WriteLine(fi.Name);
                        }
                    }
                    else {
                        writer.WriteLine(message.StackSegments[i].File);
                    }
                }
            }

            writer.WriteLine("**************************************************\n");
            writer.Flush();
            HandledMessages++;
            return true;
        }
示例#37
0
        public override void OnClientStep(uint ID, DebugMessage msg)
        {
            var contract = contracts.ContainsKey(msg.scriptHash) ? contracts[msg.scriptHash] : null;

            if (contract != null)
            {
                int index = -1;
                for (int i = 0; i < contract.instructions.Length; i++)
                {
                    var entry = contract.instructions[i];
                    if (msg.offset >= entry.startOfs && msg.offset <= entry.endOfs)
                    {
                        index = i;
                        break;
                    }
                }

                bool found = false;

                if (contract.map != null)
                {
                    string filePath;
                    try
                    {
                        int line = contract.map.ResolveLine(msg.offset, out filePath);

                        string[] lines;

                        if (fileContent.ContainsKey(filePath))
                        {
                            lines = fileContent[filePath];
                        }
                        else
                        {
                            lines = File.ReadAllLines(filePath);
                            fileContent[filePath] = lines;
                        }

                        if (lastFile != filePath || lastLine != line)
                        {
                            WriteLine(ConsoleColor.Gray, line + ", " + lines[line - 1]);
                            lastLine = line;
                            lastFile = filePath;
                        }

                        found = true;
                    }
                    catch
                    {
                        found = false;
                    }
                }

                if (index >= 0)
                {
                    if (lastInstruction >= 0 && Math.Abs(lastInstruction - index) > 20)
                    {
                        WriteLine(ConsoleColor.DarkGray, new string('.', 70));
                    }
                    lastInstruction = index;
                }

                if (!found && index >= 0)
                {
                    var    entry = contract.instructions[index];
                    string extra = "";

                    if (entry.data != null)
                    {
                        extra = " => " + FormattingUtils.OutputData(entry.data, false);
                    }

                    WriteLine(ConsoleColor.Gray, msg.offset + ", " + entry.opcode + extra);
                    found = true;
                }

                if (!found)
                {
                    contract = null;
                }
            }

            if (contract == null)
            {
                WriteLine(ConsoleColor.Gray, msg.offset + ", [External code]");
            }
        }
示例#38
0
        public void DebugMessageConstructorTest()
        {
            DebugMessage target = new DebugMessage();

            Assert.Inconclusive("TODO: Implement code to verify target");
        }
示例#39
0
 public PipeManager(DebugMessage activityRef)
 {
     DebugMessageRef = activityRef;
 }
示例#40
0
        public void NotifyDebugMessage(int userId, string message)
        {
            var dm = new DebugMessage(message);

            _packetHandlerManager.SendPacket(userId, dm, Channel.CHL_S2C);
        }
示例#41
0
文件: JsonBase.cs 项目: radtek/safeid
        public static T JsonWebRequest <T>(Uri uri, String postData, String ContentType, Dictionary <String, String> headers, String method, CookieContainer cookie, DebugMessage debugCallback)
        {
            String jData = TextWebRequest(uri, postData, ContentType, headers, method, cookie, debugCallback);

            if (jData == "")
            {
                return((T)((Object)null));
            }
            else
            {
                return(Deserialize <T>(jData));
            }
        }
示例#42
0
        public void NotifyDebugMessage(string htmlDebugMessage)
        {
            var dm = new DebugMessage(htmlDebugMessage);

            _packetHandlerManager.BroadcastPacket(dm, Channel.CHL_S2C);
        }
示例#43
0
文件: JsonBase.cs 项目: radtek/safeid
        public static String TextWebRequest(Uri uri, String postData, String ContentType, Dictionary <String, String> headers, String method, CookieContainer cookie, DebugMessage debugCallback)
        {
            if (debugCallback != null)
            {
                debugCallback("Request URI: ", uri.AbsoluteUri);
            }

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

            request.UserAgent = "Mozilla/5.0 (compatible; SafeID/1.0; +http://www.safeid.com.br)";

            if (cookie != null)
            {
                request.CookieContainer = cookie;
            }

            if (headers != null)
            {
                foreach (String k in headers.Keys)
                {
                    switch (k.ToLower())
                    {
                    default:
                        request.Headers.Add(k, headers[k]);
                        break;
                    }
                }
            }

            //request.ServicePoint.Expect100Continue = false;
            //ServicePointManager.MaxServicePointIdleTime = 2000;

            if (!String.IsNullOrWhiteSpace(method))
            {
                switch (method.ToUpper())
                {
                case "GET":
                case "POST":
                case "PUT":
                case "DELETE":
                    request.Method = method.ToUpper();
                    break;

                default:
                    request.Method = "GET";
                    break;
                }
            }
            else
            {
                request.Method = "GET";
            }

            try
            {
                if (debugCallback != null)
                {
                    debugCallback("POST Data", postData);
                }
                if (!String.IsNullOrWhiteSpace(postData))
                {
                    request.ContentType = ContentType.Split(";".ToCharArray(), 2)[0].Trim() + "; charset=UTF-8";

                    // Create POST data and convert it to a byte array.
                    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                    request.ContentLength = byteArray.Length;
                    using (Stream dataStream = request.GetRequestStream())
                    {
                        dataStream.Write(byteArray, 0, byteArray.Length);
                    }
                }

                //request.Headers.Add("Content-Type", "application/json; charset=UTF-8");
            }
            catch (Exception ex)
            {
                if (debugCallback != null)
                {
                    debugCallback("POST Data Error", ex.Message);
                }
            }

            String jData = "";

            try
            {
                // Get the response.
                if (debugCallback != null)
                {
                    debugCallback("GetResponse", "");
                }
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    Encoding enc = Encoding.UTF8;
                    try
                    {
                        enc = Encoding.GetEncoding(response.ContentEncoding);
                    }
                    catch { }

                    Stream dataStream = response.GetResponseStream();
                    using (StreamReader reader = new StreamReader(dataStream, enc))
                        jData = reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                if (debugCallback != null)
                {
                    debugCallback("GetResponse Error", ex.Message);
                }
                try
                {
                    if (ex is WebException)
                    {
                        using (WebResponse response = ((WebException)ex).Response)
                        {
                            HttpWebResponse httpResponse = (HttpWebResponse)response;
                            using (Stream data = response.GetResponseStream())
                                using (var reader = new StreamReader(data))
                                {
                                    jData = reader.ReadToEnd();
                                }
                        }
                    }
                }
                catch { }
            }

            if (debugCallback != null)
            {
                debugCallback("Return Text", jData);
            }
            if (jData == "")
            {
                return("");
            }
            else
            {
                return(jData);
            }
        }
示例#44
0
        public override bool DumpMessage(DebugMessage message)
        {
            if(!Enabled) {
                return false;
            }

            Console.ForegroundColor = ConsoleColor.Gray;
            Console.Write(message.Time.ToLongTimeString() + " | ");
            Console.ForegroundColor = GetMessageColor(message);

            if(message.Type == DebugMessageType.Error) {
                Console.Write("Error");
            }
            else if(message.Type == DebugMessageType.Unknown) {
                Console.Write("Unknown");
            }
            else {
                Console.Write("Warning");
            }

            Console.ResetColor();
            Console.WriteLine(" | #" + HandledMessages);

            Console.ForegroundColor = GetMessageColor(message);
            Console.WriteLine("\n" + message.Message + "\n\n");
            Console.ResetColor();

            Console.ForegroundColor = ConsoleColor.Gray;
            Console.Write("NAMESPACE: ");
            Console.WriteLine(message.BaseMethod.DeclaringNamespace);
            Console.ResetColor();

            Console.Write("OBJECT:    ");
            Console.WriteLine(message.BaseMethod.DeclaringObject);
            Console.ResetColor();

            Console.Write("METHOD:    ");

            if(SimplifyMethod) {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine(ExtractSimplifiedMethod(message.BaseMethod.Method));
            }
            else {
                WriteMethodInfo(message.BaseMethod.Type, message.BaseMethod.Method,
                                ConsoleColor.DarkYellow, ConsoleColor.Yellow);
            }

            Console.ResetColor();
            Console.Write("LINE:      ");
            Console.WriteLine(message.BaseMethod.Line);
            Console.ResetColor();

            Console.Write("FILE:      ");

            if(TruncateFile) {
                FileInfo fi = new FileInfo(message.BaseMethod.File);
                Console.WriteLine(fi.Name);
            }
            else {
                Console.WriteLine(message.BaseMethod.File);
            }

            Console.ResetColor();

            if(UseStackInfo && message.HasStack) {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("\nSTACK:");

                for(int i = 0; i < message.StackSegments.Count; i++) {
                    Console.WriteLine();
                    Console.ResetColor();
                    Console.Write("METHOD: ");

                    WriteMethodInfo(message.StackSegments[i].Type, message.StackSegments[i].Method,
                                ConsoleColor.DarkCyan, ConsoleColor.Cyan);

                    Console.ResetColor();
                    Console.Write("LINE:   ");
                    Console.ForegroundColor = ConsoleColor.DarkCyan;
                    Console.WriteLine(message.StackSegments[i].Line);
                    Console.ResetColor();
                    Console.Write("FILE:   ");
                    Console.ForegroundColor = ConsoleColor.DarkCyan;
                    if(TruncateFile) {
                        if(message.StackSegments[i].File != null) {
                            FileInfo fi = new FileInfo(message.StackSegments[i].File);
                            Console.WriteLine(fi.Name);
                        }
                    }
                    else {
                        Console.WriteLine(message.StackSegments[i].File);
                    }
                }
            }

            Console.ForegroundColor = ConsoleColor.DarkGray;
            Console.WriteLine();
            WriteSeparator(ConsoleColor.DarkGray);
            HandledMessages++;
            return true;
        }
示例#45
0
        public override bool DumpMessage(DebugMessage message)
        {
            if(!IsOpen || !_enabled) {
                return false;
            }

            try {
                HandleResponse(client.HandleDebugMessage(clientName, message));
            }
            catch(CommunicationException ce) {
                Console.WriteLine("Failed to call method on WCF service. Exception: {0}", ce.Message);
                return false;
            }

            return true;
        }