Esempio n. 1
0
        public void InvalidEmailAdress2()
        {
            bool        expected = false;
            ProcessData pd       = new ProcessData();

            Assert.AreEqual(expected, pd.ValidEmail("testatnapier.ac.uk Email subject        This is the body of the email, www.example.com"));
        }
Esempio n. 2
0
        /// <summary>
        /// load Module data from XmlNode
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        public static ProcessData LoadFromXml(XmlNode node)
        {
            if (null == node)
                return null;
            ProcessData pData = new ProcessData();
            pData.m_strProcessName = XmlLoaderBase.getInnerTextByPath(node, "./name");
            pData.m_strProcessId = XmlLoaderBase.getInnerTextByPath(node, "./id");
            if (null == pData.m_strProcessId || 0 == pData.m_strProcessId.Length)
                return null;
            pData.m_nProcessId = Convert.ToInt32(pData.m_strProcessId);

            XmlNodeList mList = node.SelectNodes("./modules/module");
            if (null == mList)
                return null;
            pData.m_lstModules = new Dictionary<string, ModuleData>();
            foreach(XmlNode n in mList)
            {
                if (null == n)
                    continue;
                ModuleData mData = ModuleDataLoader.LoadFromXml(n);
                if (null == mData)
                    return null;
                pData.m_lstModules.Add(mData.m_strModuleName, mData);
            }
            return pData;
        }
Esempio n. 3
0
        /// <summary>
        /// Extracts the animation.
        /// </summary>
        /// <returns>
        /// The animation.
        /// </returns>
        /// <param name='processData'>
        /// Process data.
        /// </param>
        protected static Object ExtractAnimation(ProcessData processData)
        {
            string animAsset;
            string animName;
            string animTransform;

            if (!processData.ManifestInst.GetAssetDependAnim(processData.FromAsset, processData.AssetFile, out animAsset, out animName, out animTransform))
            {
                Debug.LogErrorFormat("Failed to load asset dependent assets: {0}", processData.LogString);
                return(null);
            }

            GameObject fromAssetObject = AssetDatabase.LoadAssetAtPath(processData.FromAsset, typeof(Object)) as GameObject;

            Transform animTrans = ObjectUtil.GetTransFromRoot(fromAssetObject.transform, animTransform);

            if (animTrans == null)
            {
                Debug.LogErrorFormat("Failed to get animation transform: {0}", processData.LogString);
                return(null);
            }

            Animation      animation = animTrans.gameObject.GetComponent <Animation>();
            AnimationState animState = animation[animName];

            Object assetObject = ( Object )animState.clip;

            return(assetObject);
        }
Esempio n. 4
0
        public void ValidTwitterMessage()
        {
            bool        expected = true;
            ProcessData pd       = new ProcessData();

            Assert.AreEqual(expected, pd.ValidTweet("@tweetId IMO, impressive. #Awesome @Napier"));
        }
Esempio n. 5
0
        /// <summary>
        /// Extracts the material.
        /// </summary>
        /// <returns>
        /// The material.
        /// </returns>
        /// <param name='processData'>
        /// Process data.
        /// </param>
        protected static Object ExtractMaterial(ProcessData processData)
        {
            Object   assetObject = AssetDatabase.LoadAssetAtPath(processData.AssetFile, typeof(Object));
            Material material    = assetObject as Material;

            foreach (string propertyName in Defines.MAT_TEX_PROPERTY_NAMES)
            {
                if (material.HasProperty(propertyName))
                {
                    Texture texture = material.GetTexture(propertyName);

                    if (texture != null)
                    {
                        string texAssetFile = PathUtil.UnifyPath(AssetDatabase.GetAssetPath(texture));

                        if (processData.ManifestInst.HasAsset(texAssetFile))
                        {
                            // Add dependent texture.
                            processData.ManifestInst.AddDependTexToAsset(processData.AssetFile, texAssetFile, propertyName);
                        }
                    }
                }
            }

            return(null);
        }
Esempio n. 6
0
    ProcessData PreProcess()
    {
        Debug.Log("PreProcess");
        var Data = new ProcessData();

        if (AccumulatedPositionsBuffer == null)
        {
            AccumulatedPositionsBuffer = new Texture2D(AccumulatedPositions.width, AccumulatedPositions.height, TextureFormat.RGBAFloat, false);
        }
        Data.BufferPositions = AccumulatedPositionsBuffer.GetPixels();

        var Min = WorldBoundsBox.bounds.min;
        var Max = WorldBoundsBox.bounds.max;

        Data.WorldMin = WorldBoundsBox.transform.TransformPoint(Min);
        Data.WorldMax = WorldBoundsBox.transform.TransformPoint(Max);

        Data.BlockWidth   = AccumulatedPositionsBuffer.width;
        Data.BufferWidth  = AccumulatedPositionsBuffer.width;
        Data.BufferHeight = AccumulatedPositionsBuffer.height;
        Data.BlockDepth   = Mathf.FloorToInt(Mathf.Sqrt(Data.BufferHeight));
        Data.BlockHeight  = (int)(Data.BufferHeight / Data.BlockDepth);

        Data.FramePositions = LastPositionTexture.GetPixels();

        return(Data);
    }
Esempio n. 7
0
        public static ProcessData InitiateProcessData(Permissions access, Resource resource, string aid, string gpid, string pid, string cid, string gcid)
        {
            var n_aid  = TryToParseToInt(aid);
            var n_gpid = TryToParseToLong(gpid);
            var n_pid  = TryToParseToLong(pid);
            var n_cid  = TryToParseToLong(cid);
            var n_gcid = TryToParseToLong(gcid);

            var pd = new ProcessData();

            // Only populate data that is numerical.
            pd.AccountId = (n_aid.isNotNull && n_aid.isLong) ? n_aid.value : null;
            pd.Gpid      = (n_gpid.isNotNull && n_gpid.isLong) ? n_gpid.value : null;
            pd.Pid       = (n_pid.isNotNull && n_pid.isLong) ? n_pid.value : null;
            pd.Cid       = (n_cid.isNotNull && n_cid.isLong) ? n_cid.value : null;
            pd.Gcid      = (n_gcid.isNotNull && n_gcid.isLong) ? n_gcid.value : null;
            // Only populate data that is a string.
            pd.AccountName = (n_aid.isNotNull && n_aid.isString) ? n_aid.value : null;
            pd.Gpname      = (n_gpid.isNotNull && n_gpid.isString) ? n_gpid.value : null;
            pd.Pname       = (n_pid.isNotNull && n_pid.isString) ? n_pid.value : null;
            pd.Cname       = (n_cid.isNotNull && n_cid.isString) ? n_cid.value : null;
            pd.Gcname      = (n_gcid.isNotNull && n_gcid.isString) ? n_gcid.value : null;

            pd.Resource = resource;
            pd.Access   = access;

            return(pd);
        }
        private void button2_Click(object sender, EventArgs e)
        {
            chartBorrow.Series["Series1"].Points.Clear();
            string    sql  = "select * from PHIEUMUON";
            DataTable data = new DataTable();

            data = ProcessData.ExcuteQuery(sql);

            int total = data.Rows.Count;

            int[] count = new int[4] {
                0, 0, 0, 0
            };
            string[] name = new string[4] {
                "Tiểu thuyết", "Khoa học", "Ngoại ngữ", "Truyện tranh"
            };

            int month = (int)monthPick.Value;

            for (int i = 0; i < 4; i++)
            {
                sql = string.Format("select * from SACH,PHIEUMUON where SACH.MASACH = PHIEUMUON.MASACH and month(PHIEUMUON.NGAYMUON) = {0} and LOAI={1}",
                                    month, i);
                data     = ProcessData.ExcuteQuery(sql);
                count[i] = data.Rows.Count;
            }

            for (int i = 0; i < 4; i++)
            {
                chartBorrow.Series["Series1"].Points.AddXY(name[i], count[i]);
            }
        }
Esempio n. 9
0
        private void RecIterate(Node <T> current, ProcessData <T> pd, TraversalOrder to)
        {
            if (to == TraversalOrder.PRE_ORDER)
            {
                pd(current.Data);
            }



            if (current.Left != null)
            {
                RecIterate(current.Left, pd, to);
            }

            if (to == TraversalOrder.IN_ORDER)
            {
                pd(current.Data);
            }

            if (current.Right != null)
            {
                RecIterate(current.Right, pd, to);
            }

            if (to == TraversalOrder.POST_ORDER)
            {
                pd(current.Data);
            }
        }
Esempio n. 10
0
        public ProcessTimelineItem(ProcessData process)
        {
            Process = process;

            Children = new List <Timeline.IItem>(process.Threads.Count);
            process.Threads.ForEach(thread => Children.Add(new ThreadTimelineItem(thread)));
        }
Esempio n. 11
0
        public void InvalidPhoneNumber()
        {
            bool        expected = false;
            ProcessData pd       = new ProcessData();

            Assert.AreEqual(expected, pd.ValidSMS("3339006040 IMO this app is amazing. Good work."));
        }
Esempio n. 12
0
        public void ValidEmailMessage()
        {
            bool        expected = true;
            ProcessData pd       = new ProcessData();

            Assert.AreEqual(expected, pd.ValidEmail("[email protected] Email subject        This is the body of the email, www.example.com"));
        }
 public ScoringModel RunAlgorithms(ProcessData processData)
 {
     try
     {
         GetUserData(processData);
         var accelerationAlgo   = new Acceleration();
         var accelerationEvents = accelerationAlgo.Checkacc(dataList);
         concatList(accelerationEvents);
         var speedAlgo   = new Speed();
         var speedEvents = speedAlgo.GetSpeedData(dataList);
         concatList(speedEvents);
         var aggressiveTurningAlgo   = new AgreesiveTurning();
         var turnAndLaneChangeEvents = aggressiveTurningAlgo.CheckAgressiveTurning_And_LaneChange(dataList);       //lane change algo is run within aggressive turning
         concatList(turnAndLaneChangeEvents);
         InsertDrivingEvents(eventsList);
         var SessionId    = processData.Session_Id;
         var scoring      = new Scoring();
         var sessionScore = scoring.Score_Driving_Of_User(eventsList, SessionId);
         return(sessionScore);
     }
     catch (Exception ex)
     {
         throw new Exception("Failed to Retrieve data");
     }
 }
Esempio n. 14
0
        public static DataTable readAll()
        {
            string sql    = "select * from SACH";
            var    result = ProcessData.ExcuteQuery(sql);

            return(result);
        }
Esempio n. 15
0
 public void ChangeDatas(ProcessData process)
 {
     for (int i = 0; i < datas.Count; ++i)
     {
         datas[i] = process(datas[i]);
     }
 }
Esempio n. 16
0
    public Process ActivateProcess(ProcessData processData)
    {
        Process newProcess = new Process(processData);

        ActiveProcesses.AddUnique(newProcess);
        return(newProcess);
    }
Esempio n. 17
0
        public CustomTransfer UpdateProcessListTransfers()
        {
            long totalDownloaded = 0;
            long totalUploaded   = 0;

            lock (PIDUsageDictionary)
            {
                lock (MainWindowForm.ProcessDataSourceLocker)
                {
                    foreach (Int32 PIDWithCurrentZeroTransferSpeed in ListOfPidTransfersToBeZeroed)
                    {
                        var processesDataToBeUpdated = ProcessDataSource.Where(processData =>
                                                                               processData.PID == PIDWithCurrentZeroTransferSpeed);
                        foreach (ProcessData processData in processesDataToBeUpdated)
                        {
                            processData.SetDownloadingTransfer(0);
                            processData.SetUploadingTransfer(0);
                        }
                    }
                    ListOfPidTransfersToBeZeroed.Clear();
                    foreach (KeyValuePair <Int32, CustomTransfer> PIDUsagePair in PIDUsageDictionary)
                    {
                        ProcessData processDataToBeUpdated = ProcessDataSource.FirstOrDefault(
                            processData => (processData.isAlive || (Utils.ElapsedTime(processData.EndTime) < DeadPIDLookupTimer)) &&
                            processData.PID == PIDUsagePair.Key);
                        if (!(processDataToBeUpdated is null))
                        {
                            processDataToBeUpdated.AddReceivedSize(PIDUsagePair.Value.Received);
                            processDataToBeUpdated.AddUploadSize(PIDUsagePair.Value.Sent);
                            processDataToBeUpdated.SetDownloadingTransfer(Utils.CalculateSpeedPerSecond(PIDUsagePair.Value.Received, stopWatch.ElapsedMilliseconds));
                            processDataToBeUpdated.SetUploadingTransfer(Utils.CalculateSpeedPerSecond(PIDUsagePair.Value.Sent, stopWatch.ElapsedMilliseconds));
                            ListOfPidTransfersToBeZeroed.Add(PIDUsagePair.Key);
                        }
Esempio n. 18
0
        private void RegisterProcess(ClientContext clientContext)
        {
            // Starting offset in 'data'
            int offset = sizeof(UInt32);

            // Remote processes are not supported by the memory watcher,
            // they can use the logging system however
            if (clientContext.IsRemote)
            {
                // Silent return, it's not an error
                return;
            }

            // All registering needs is a process Id
            UInt64 processId = BitConverter.ToUInt64(clientContext.Data, offset);

            ProcessData newProcessData = ProcessReader.OpenProcess((int)processId);

            if (newProcessData == null)
            {
                clientContext.Disconnect();
                return;
            }

            clientContext.ProcessData = newProcessData;

            lock (attachedProcesses)
                attachedProcesses.Add(newProcessData);

            if (ProcessConnect != null)
            {
                ProcessConnect(newProcessData);
            }
        }
Esempio n. 19
0
        private void NetworkWrite(ProcessData Processor, SocketPurpose Purpose, Socket NetworkSocket, byte[] Data, int offset, IAsyncResult ar)
        {
            try
            {
                int length = NetworkSocket.EndSend(ar);

                if (length + offset < Data.Length)
                {
                    NetworkSocket.BeginSend(Data, length, Data.Length - (length + offset), SocketFlags.None,
                                            delegate(IAsyncResult AsR) { NetworkWrite(Processor, Purpose, NetworkSocket, Data, length + offset, AsR); },
                                            null);
                }
                else
                {
                    NetworkSocket.BeginReceive(networkBuf, 0, 1024, SocketFlags.None,
                                               delegate(IAsyncResult AsR) { NetworkReceive(Purpose, NetworkSocket, AsR); },
                                               null);
                }
            }
            catch (SocketException e)
            {
                OnSocketException(Purpose, NetworkSocket, e);
            }
            catch (ObjectDisposedException)
            {
                OnObjectDisposedException(Purpose, NetworkSocket);
            }
        }
Esempio n. 20
0
        public void InvalidTwitterMessage()
        {
            bool        expected = false;
            ProcessData pd       = new ProcessData();

            Assert.AreEqual(expected, pd.ValidTweet("@John421 I'm happy I have lived long enough to see that! I'm happy I have lived long enough to see that! I'm happy I have lived long enough to see that!"));
        }
Esempio n. 21
0
        public static DataTable readWithCatID(int CatID)
        {
            string sql    = String.Format("select * from SACH where LOAI={0}", CatID);
            var    result = ProcessData.ExcuteQuery(sql);

            return(result);
        }
Esempio n. 22
0
        public void ValidSMSMessage()
        {
            bool        expected = true;
            ProcessData pd       = new ProcessData();

            Assert.AreEqual(expected, pd.ValidSMS("+443339006040 The message LOL."));
        }
Esempio n. 23
0
        public static DataTable findWithName(String Name)
        {
            string sql    = String.Format("select * from SACH where TENSACH LIKE N'%{0}%'", Name);
            var    result = ProcessData.ExcuteQuery(sql);

            return(result);
        }
Esempio n. 24
0
        public void InvalidSMSMessage()
        {
            bool        expected = false;
            ProcessData pd       = new ProcessData();

            Assert.AreEqual(expected, pd.ValidSMS("+443339006040 IMO this app is amazing. Good work. A protoplanet is a large planetary embryo that originated within a protoplanetary disc and has undergone internal melting."));
        }
Esempio n. 25
0
    /// <summary>
    /// event_MessageHandler
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="args"></param>
    void event_MessageHandler(object sender, EMSMessageEventArgs args)
    {
        // Since args.Message is generic message we need to box into TextMessage
        // which allows us access to the message.Text content.
        TextMessage message = (TextMessage)args.Message;
        string      msg     = message.Text;

        var primefactors = ProcessData.GetPrimeFactors(Convert.ToInt32(msg));

        Console.Write("Prime Factors for " + msg + " = ");
        foreach (var item in primefactors)
        {
            Console.Write(item.ToString() + " ");
        }

        Console.WriteLine("");

        // Acknowledge we received the message.  If the message did not get written to disk
        // we want to not acknowledge the message was received.
        if (ackMode == Session.CLIENT_ACKNOWLEDGE ||
            ackMode == Session.EXPLICIT_CLIENT_ACKNOWLEDGE ||
            ackMode == Session.EXPLICIT_CLIENT_DUPS_OK_ACKNOWLEDGE)
        {
            args.Message.Acknowledge();
        }
    }
    /// <summary>
    /// プロセスを実行
    /// </summary>
    public void StartProcess(ProcessData procData)
    {
        if(procData.use && !procData.IsRunning)
        {
            FileInfo fileInfo = new FileInfo(procData.exePath);
            if(fileInfo.Exists)
            {
                Process proc = new Process();
                proc.StartInfo.FileName = Path.GetFullPath(procData.exePath);

                //引数設定
                if(procData.argument != "")
                    proc.StartInfo.Arguments = procData.argument;

                //ウィンドウスタイル設定
                if(!ApplicationSetting.Instance.GetBool("IsDebug"))
                    proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

                try
                {
                    proc.Start();

                    processList.Add(proc);
                    procData.IsRunning = true;
                }
                catch(Exception e)
                {
                    UnityEngine.Debug.Log("ExternalProcess :: process start error - " + e.Message);
                }
            }
        }
    }
Esempio n. 27
0
 public static bool InsertProcessDataInDB(List <Process> processes)
 {
     try
     {
         using (var db = new testServicesEntities())
         {
             foreach (var process in processes)
             {
                 ProcessData processData = new ProcessData();
                 processData.DiskSpace       = process.VirtualMemorySize64;
                 processData.DateTimeOfUsage = DateTime.Now;
                 processData.PropertyName    = "VirtualMemorySize64";
                 processData.PropertyName    = process.ProcessName;
                 db.ProcessDatas.Add(processData);
                 db.SaveChanges();
             }
         }
         return(true);
     }
     catch (Exception ex)
     {
         //Log the ex to so I know what is jacked up
         return(false);
     }
 }
Esempio n. 28
0
 public override void Iterate(ProcessData <T> pd, TraversalOrder to)
 {
     if (nRoot != null)
     {
         RecIterate(nRoot, pd, to);
     }
 }
Esempio n. 29
0
        public void InvalidEmailBody()
        {
            bool        expected = false;
            ProcessData pd       = new ProcessData();

            Assert.AreEqual(expected, pd.ValidEmail("[email protected] test subject         A protoplanet is a large planetary embryo that originated within a protoplanetary disc and has undergone internal melting to produce a differentiated interior. Protoplanets are thought to form out of kilometer-sized planetesimals that gravitationally perturb each other's orbits and collide, gradually coalescing into the dominant planets. In the case of the Solar System, it is thought that the collisions of planetesimals created a few hundred planetary embryos. Such embryos were similar to Ceres and Pluto with masses of about 1022 to 1023 kg and were a few thousand kilometers in diameter. Over the course of hundreds of millions of years, they collided with one another. The exact sequence whereby planetary embryos collided to assemble the planets is not known, but it is thought that initial collisions would have replaced the first generation of embryos with a second generation consisting of fewer but larger embryos. These in their turn would have collided to create a third generation of fewer but even larger embryos. Eventually, only a handful of embryos were left, which collided to complete the assembly of the planets proper."));
        }
Esempio n. 30
0
        public void NumberOfElectorsInList2012()
        {
            var dir = Path.GetDirectoryName(this.GetType().Assembly.Location);

            var electionsLast     = ProcessData.GetElectionDataWithNormalizedPlace(dir + @"..\..\..\..\Elections\ElectionInfoPresident\ElectionInfoPresident2012.xml");
            var electionsByRegion = electionsLast
                                    .GroupBy(kvp => kvp.Value.TextData.Region, kvp => kvp.Value)
                                    .ToDictionary(g => g.Key, g => g.ToList());
            var foo = "Putin";

            Assert.AreEqual(1994310, SortByDelta.NumberVotedFor(electionsByRegion, "Город Москва", foo));

            Assert.AreEqual(7309869, SortByDelta.NumberOfElectorsInList(electionsByRegion, "Город Москва"));
            Assert.AreEqual(5779495, SortByDelta.NumberOfElectorsInList(electionsByRegion, "Московская область"));
            Assert.AreEqual(3849426, SortByDelta.NumberOfElectorsInList(electionsByRegion, "Город Санкт-Петербург"));
            Assert.AreEqual(3803307, SortByDelta.NumberOfElectorsInList(electionsByRegion, "Краснодарский край"));
            Assert.AreEqual(3527808, SortByDelta.NumberOfElectorsInList(electionsByRegion, "Свердловская область"));
            Assert.AreEqual(3315673, SortByDelta.NumberOfElectorsInList(electionsByRegion, "Ростовская область"));
            Assert.AreEqual(3014076, SortByDelta.NumberOfElectorsInList(electionsByRegion, "Республика Башкортостан"));
            Assert.AreEqual(2866307, SortByDelta.NumberOfElectorsInList(electionsByRegion, "Республика Татарстан (Татарстан)"));
            Assert.AreEqual(2777766, SortByDelta.NumberOfElectorsInList(electionsByRegion, "Нижегородская область"));
            Assert.AreEqual(2757879, SortByDelta.NumberOfElectorsInList(electionsByRegion, "Челябинская область"));

            foreach (var regionPair in electionsByRegion)
            {
                //Trace.WriteLine(regionPair.Key);
            }

            Assert.AreEqual(85, electionsByRegion.Count);
        }
Esempio n. 31
0
        private void StatisticForm_Load(object sender, EventArgs e)
        {
            string    sql  = "select * from SACH";
            DataTable data = new DataTable();

            data = ProcessData.ExcuteQuery(sql);

            int total = data.Rows.Count;

            int[] count = new int[4] {
                0, 0, 0, 0
            };
            string[] name = new string[4] {
                "Tiểu thuyết", "Khoa học", "Ngoại ngữ", "Truyện tranh"
            };

            for (int i = 0; i < 4; i++)
            {
                sql      = string.Format("select * from SACH where LOAI={0}", i);
                data     = ProcessData.ExcuteQuery(sql);
                count[i] = data.Rows.Count;
            }

            for (int i = 0; i < 4; i++)
            {
                chartBook.Series["Series1"].Points.AddXY(name[i], count[i]);
            }
        }
Esempio n. 32
0
        public void InvalidTwitterId2()
        {
            bool        expected = false;
            ProcessData pd       = new ProcessData();

            Assert.AreEqual(expected, pd.ValidTweet("@John421John4211 I'm happy I have lived long enough to see that! This is for you @JeanRochefort #ELM"));
        }
Esempio n. 33
0
        /// <summary>
        /// Reload the <see cref="Process" /> with the specified <see cref="T:Tridion.ContentManager.CoreService.Client.ProcessData" />
        /// </summary>
        /// <param name="processData"><see cref="T:Tridion.ContentManager.CoreService.Client.ProcessData" /></param>
        protected void Reload(ProcessData processData)
        {
            if (processData == null)
                throw new ArgumentNullException("processData");

            mProcessData = processData;
            base.Reload(processData);
        }
Esempio n. 34
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Process"/> class.
        /// </summary>
        /// <param name="client"><see cref="T:TcmCoreService.Client" /></param>
        /// <param name="processData"><see cref="T:Tridion.ContentManager.CoreService.Client.ProcessData" /></param>
        protected Process(Client client, ProcessData processData)
            : base(client, processData)
        {
            if (processData == null)
                throw new ArgumentNullException("processData");

            mProcessData = processData;
        }
 /// <summary>
 /// Constructor of the controller class!
 /// </summary>
 public Controller()
 {
     PrepareView();
     form1.setController(this);
     connectDialog.setController(this);
     processData = new ProcessData(54);
     UpdateStatus(this, new UpdateStatusEvent("Wilkommen zu SomnoSoftware 0.2"));
     UpdateStatus(this, new UpdateStatusEvent("Bitte beachten Sie die Anweisungen bevor Sie eine Verbindung mit dem Sensor herstellen"));
     runner();
 }
Esempio n. 36
0
        private static void Main()
        {
            //Example 1
            var dataProcessor = new ProcessData(@"Files\testfile.log");
            System.Console.ReadLine();

            //Example 2
            while (true) {
                // Take user input on thread 1.
                var result = System.Console.ReadLine();
                // Start computation on thread 2.
                VowelCounter.Process(result);
            }
        }
Esempio n. 37
0
		public Connection(int connectionID, Socket client, ProcessData processData)
		{
			// Initialize members
			_connectionId = connectionID;
			_client = client;
			_stringBuffer = new StringBuilder();
			_receiveBuffer = new byte[_bufferSize + 1];
			_processData = processData;
			_connected = true;
			_lastActivity = DateTime.Now;
			_session = new SmtpSession();
			BeginReceive();

			Send("220 {0}", Dns.GetHostName().ToLower());
		}
 /// <summary>
 /// Add a new processor.  Processors can be added on the fly to adjust how
 /// a game object responds depending on game conditions.
 /// </summary>
 /// <param name="p">New processor.</param>
 /// <returns>True if processor successfully added, otherwise false.</returns>
 public bool AddProcessor(Processor p)
 {
     if (SceneObject != null)
     {
         ProcessData data = new ProcessData();
         if (_InitProcessor(p, ref data))
         {
             _processors.Add(p);
             _processData.Add(data);
             return true;
         }
         return false;
     }
     _processors.Add(p);
     _processData.Add(new ProcessData());
     return true;
 }
        /// <summary>
        /// Gets process usage information for a process.
        /// </summary>
        /// <param name="processId">The process id for which to get the data.</param>
        /// <returns>A ProcessData object containing metrics.</returns>
        public static ProcessData GetProcessUsage(int processId)
        {
            ProcessData returnValue = null;
            ProcessTimes processTimes = new ProcessTimes();
            IntPtr processHandle = NativeMethods.ProcessHandleError;
            int snapshotIndex = 0;

            while (snapshotIndex < SnapshotCount)
            {
                Process currentProcess = Process.GetProcessById(processId);

                try
                {
                    processHandle = NativeMethods.OpenProcess(NativeMethods.ProcessAllAccess, false, (uint)currentProcess.Id);
                    bool snapshotSucceeded = NativeMethods.GetProcessTimes(processHandle, out processTimes.RawCreationTime, out processTimes.RawExitTime, out processTimes.RawKernelTime, out processTimes.RawUserTime);

                    if (snapshotSucceeded)
                    {
                        processTimes.ConvertTime();

                        if (returnValue != null)
                        {
                            returnValue.UpdateCpuUsage(processTimes.UserTime.Ticks, processTimes.KernelTime.Ticks);
                        }
                        else
                        {
                            returnValue = new ProcessData(currentProcess.Id, currentProcess.ProcessName, processTimes.UserTime.Ticks, processTimes.KernelTime.Ticks, currentProcess.WorkingSet64);
                        }

                        snapshotIndex++;
                    }
                }
                finally
                {
                    if (processHandle != NativeMethods.ProcessHandleError)
                    {
                        NativeMethods.CloseHandle(processHandle);
                    }
                }

                Thread.Sleep(250);
            }

            return returnValue;
        }
Esempio n. 40
0
        public static void Parse(XmlNode node)
        {
            Thread t = null;
            ProcessData data = new ProcessData();
            string procName = ExtractVariableOrArray.ExtractValue(GetNode.Value(node, "name"));
            string output = ExtractVariableOrArray.ExtractValue(GetNode.Value(node, "output"));
            string error = ExtractVariableOrArray.ExtractValue(GetNode.Value(node, "error"));
            int timeout = 0;
            if (GetNode.Value(node, "timeout") != string.Empty)
                timeout = int.Parse(ExtractVariableOrArray.ExtractValue(GetNode.Value(node, "timeout")));

            XmlNodeList arguments = node.ChildNodes[0].ChildNodes;
            data.procName = procName;
            data.output = output;
            data.error = error;
            data.timeout = timeout;
            data.arguments = arguments;

            t = new Thread(LaunchProcess);
            t.Start(data);
            t.Join();

            XmlToObject.GoToSibling(node);
        }
Esempio n. 41
0
	static void TryGDB (int pid, ProcessData data)
	{
		string filename = Path.GetTempFileName ();

		using (StreamWriter sw = new StreamWriter (new FileStream (filename, FileMode.Open, FileAccess.Write)))
		{
			sw.WriteLine ("attach " + pid);
			sw.WriteLine ("info threads");
			sw.WriteLine ("thread apply all p mono_print_thread_dump(0)");
			sw.WriteLine ("thread apply all backtrace");
			sw.Flush ();

			ProcessStartInfo psi = new ProcessStartInfo {
				FileName = "gdb",
				Arguments = "-batch -x \"" + filename + "\" -nx",
				UseShellExecute = false,
				RedirectStandardError = true,
				RedirectStandardOutput = true,
			};

			using (Process process = new Process { StartInfo = psi })
			{
				process.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e) {
					lock (data.stdoutLock) {
						if (e.Data != null)
							data.stdout.AppendLine (e.Data);
					}
				};

				process.ErrorDataReceived += delegate (object sender, DataReceivedEventArgs e) {
					lock (data.stderrLock) {
						if (e.Data != null)
							data.stderr.AppendLine (e.Data);
					}
				};

				process.Start ();
				process.BeginOutputReadLine ();
				process.BeginErrorReadLine ();
				if (!process.WaitForExit (60 * 1000))
					process.Kill ();
			}
		}
	}
Esempio n. 42
0
	static void TryLLDB (int pid, ProcessData data)
	{
		string filename = Path.GetTempFileName ();

		using (StreamWriter sw = new StreamWriter (new FileStream (filename, FileMode.Open, FileAccess.Write)))
		{
			sw.WriteLine ("process attach --pid " + pid);
			sw.WriteLine ("thread list");
			sw.WriteLine ("thread backtrace all");
			sw.WriteLine ("detach");
			sw.WriteLine ("quit");
			sw.Flush ();

			ProcessStartInfo psi = new ProcessStartInfo {
				FileName = "lldb",
				Arguments = "--batch --source \"" + filename + "\" --no-lldbinit",
				UseShellExecute = false,
				RedirectStandardError = true,
				RedirectStandardOutput = true,
			};

			using (Process process = new Process { StartInfo = psi })
			{
				process.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e) {
					lock (data.stdoutLock) {
						if (e.Data != null)
							data.stdout.AppendLine (e.Data);
					}
				};

				process.ErrorDataReceived += delegate (object sender, DataReceivedEventArgs e) {
					lock (data.stderrLock) {
						if (e.Data != null)
							data.stderr.AppendLine (e.Data);
					}
				};

				process.Start ();
				process.BeginOutputReadLine ();
				process.BeginErrorReadLine ();
				if (!process.WaitForExit (60 * 1000))
					process.Kill ();
			}
		}
	}
Esempio n. 43
0
	static void TryThreadDump (int pid, ProcessData data)
	{
		try {
			TryGDB (pid, data);
			return;
		} catch {
		}

#if !FULL_AOT_DESKTOP && !MOBILE
		/* LLDB cannot produce managed stacktraces for all the threads */
		try {
			Syscall.kill (pid, Signum.SIGQUIT);
			Thread.Sleep (1000);
		} catch {
		}
#endif

		try {
			TryLLDB (pid, data);
			return;
		} catch {
		}
	}
        /// <summary>
        /// Establishes the SerialCommunication
        /// </summary>
        /// <param name="sender">Object that calls the function</param>
        /// <param name="e">Default, empty and useless event argument</param>
        public void Connect(Object sender, EventArgs e)
        {
            //Deactivate Button
            form1.ChangeConnectButtonState(false);
            connectDialog.ChangeConnectButtonState(false);

            //Searches all availible Prots for Sensor .. or disconnects
            if (!processData.sensorAnswer)
            {
                serial = new SerialCommunication(this);
                serial.NewSerialDataRecieved += new EventHandler<SerialDataEventArgs>(NewSerialDataRecieved);
                processData = new ProcessData(54);

                string[] portNames;
                portNames = serial.GetPortNames();
                for (int i = 0; i < portNames.Length; i++)
                {
                    UpdateStatus(this, new UpdateStatusEvent("Versuche mit " + portNames[i] + " zu verbinden"));
                    serial.Connect(portNames[i]);
                    serial.CallSensor();
                    Delay(300);
                    if (processData.sensorAnswer)
                    {
                        UpdateStatus(this, new UpdateStatusEvent("Verbunden mit " + portNames[i]));
                        firstPackage = true;
                        break;
                    }
                }
                if (processData.sensorAnswer)
                {
                    serial.StartSensor();
                    connectDialog.Hide();
                    form1.Show();
                }
                else
                {
                    UpdateStatus(this, new UpdateStatusEvent("Kein Sensor gefunden"));
                    UpdateStatus(this, new UpdateStatusEvent("Stellen Sie sicher, dass Bluetooth am Computer aktiviert ist und der Sensor eingeschaltet ist"));
                    UpdateStatus(this, new UpdateStatusEvent("Schalten Sie den Sensor aus und wieder ein und versuchen Sie es erneut"));
                }
            }
            else
            {
                if (ShowDialog("Möchten Sie die Verbindung zum Sensor wirklich schließen?", "Verbindung schließen") == DialogResult.OK)
                    Disconnect();
            }

            //Enable/Disable Disconnect Timer
            form1.EnableTimer(processData.sensorAnswer);
            //Save Button aktivieren/deaktivieren
            form1.ChangeSaveButtonState(processData.sensorAnswer);
            //Connect Button anpassen
            form1.ChangeConnectButtonText(processData.sensorAnswer);
            //Activate Button
            form1.ChangeConnectButtonState(true);
            connectDialog.ChangeConnectButtonState(true);
        }
Esempio n. 45
0
	public static int Main (String[] args) {
		// Defaults
		int concurrency = 1;
		int timeout = 2 * 60; // in seconds
		int expectedExitCode = 0;
		string testsuiteName = null;
		string inputFile = null;

		DateTime test_start_time = DateTime.UtcNow;

		// FIXME: Add support for runtime arguments + env variables

		string disabled_tests = null;
		string runtime = "mono";
		var opt_sets = new List<string> ();

		// Process options
		int i = 0;
		while (i < args.Length) {
			if (args [i].StartsWith ("-")) {
				if (args [i] == "-j") {
					if (i + 1 >= args.Length) {
						Console.WriteLine ("Missing argument to -j command line option.");
						return 1;
					}
					if (args [i + 1] == "a")
						concurrency = Environment.ProcessorCount;
					else
						concurrency = Int32.Parse (args [i + 1]);
					i += 2;
				} else if (args [i] == "--timeout") {
					if (i + 1 >= args.Length) {
						Console.WriteLine ("Missing argument to --timeout command line option.");
						return 1;
					}
					timeout = Int32.Parse (args [i + 1]);
					i += 2;
				} else if (args [i] == "--disabled") {
					if (i + 1 >= args.Length) {
						Console.WriteLine ("Missing argument to --disabled command line option.");
						return 1;
					}
					disabled_tests = args [i + 1];
					i += 2;
				} else if (args [i] == "--runtime") {
					if (i + 1 >= args.Length) {
						Console.WriteLine ("Missing argument to --runtime command line option.");
						return 1;
					}
					runtime = args [i + 1];
					i += 2;
				} else if (args [i] == "--opt-sets") {
					if (i + 1 >= args.Length) {
						Console.WriteLine ("Missing argument to --opt-sets command line option.");
						return 1;
					}
					foreach (var s in args [i + 1].Split ())
						opt_sets.Add (s);
					i += 2;
				} else if (args [i] == "--expected-exit-code") {
					if (i + 1 >= args.Length) {
						Console.WriteLine ("Missing argument to --expected-exit-code command line option.");
						return 1;
					}
					expectedExitCode = Int32.Parse (args [i + 1]);
					i += 2;
				} else if (args [i] == "--testsuite-name") {
					if (i + 1 >= args.Length) {
						Console.WriteLine ("Missing argument to --testsuite-name command line option.");
						return 1;
					}
					testsuiteName = args [i + 1];
					i += 2;
				} else if (args [i] == "--input-file") {
					if (i + 1 >= args.Length) {
						Console.WriteLine ("Missing argument to --input-file command line option.");
						return 1;
					}
					inputFile = args [i + 1];
					i += 2;
				} else {
					Console.WriteLine ("Unknown command line option: '" + args [i] + "'.");
					return 1;
				}
			} else {
				break;
			}
		}

		if (String.IsNullOrEmpty (testsuiteName)) {
			Console.WriteLine ("Missing the required --testsuite-name command line option.");
			return 1;
		}

		var disabled = new Dictionary <string, string> ();

		if (disabled_tests != null) {
			foreach (string test in disabled_tests.Split ())
				disabled [test] = test;
		}

		var tests = new List<string> ();

		if (!String.IsNullOrEmpty (inputFile)) {
			tests.AddRange (File.ReadAllLines (inputFile));
		} else {
			// The remaining arguments are the tests
			for (int j = i; j < args.Length; ++j)
				if (!disabled.ContainsKey (args [j]))
					tests.Add (args [j]);
		}

		var passed = new List<ProcessData> ();
		var failed = new List<ProcessData> ();
		var timedout = new List<ProcessData> ();

		object monitor = new object ();

		if (concurrency != 1)
			Console.WriteLine ("Running tests: ");

		var test_info = new Queue<TestInfo> ();
		if (opt_sets.Count == 0) {
			foreach (string s in tests)
				test_info.Enqueue (new TestInfo { test = s });
		} else {
			foreach (string opt in opt_sets) {
				foreach (string s in tests)
					test_info.Enqueue (new TestInfo { test = s, opt_set = opt });
			}
		}		

		List<Thread> threads = new List<Thread> (concurrency);

		for (int j = 0; j < concurrency; ++j) {
			Thread thread = new Thread (() => {
				while (true) {
					TestInfo ti;

					lock (monitor) {
						if (test_info.Count == 0)
							break;
						ti = test_info.Dequeue ();
					}

					string test = ti.test;
					string opt_set = ti.opt_set;

					if (concurrency == 1)
						Console.Write ("Testing " + test + "... ");

					/* Spawn a new process */
					string process_args;
					if (opt_set == null)
						process_args = test;
					else
						process_args = "-O=" + opt_set + " " + test;
					ProcessStartInfo info = new ProcessStartInfo (runtime, process_args);
					info.UseShellExecute = false;
					info.RedirectStandardOutput = true;
					info.RedirectStandardError = true;
					Process p = new Process ();
					p.StartInfo = info;

					ProcessData data = new ProcessData ();
					data.test = test;

					string log_prefix = "";
					if (opt_set != null)
						log_prefix = "." + opt_set.Replace ("-", "no").Replace (",", "_");

					data.stdoutFile = test + log_prefix + ".stdout";
					data.stdout = new StreamWriter (new FileStream (data.stdoutFile, FileMode.Create));

					data.stderrFile = test + log_prefix + ".stderr";
					data.stderr = new StreamWriter (new FileStream (data.stderrFile, FileMode.Create));

					p.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e) {
						if (e.Data != null) {
							data.stdout.WriteLine (e.Data);
						} else {
							data.stdout.Flush ();
							data.stdout.Close ();
						}
					};

					p.ErrorDataReceived += delegate (object sender, DataReceivedEventArgs e) {
						if (e.Data != null) {
							data.stderr.WriteLine (e.Data);
						} else {
							data.stderr.Flush ();
							data.stderr.Close ();
						}
					};

					p.Start ();

					p.BeginOutputReadLine ();
					p.BeginErrorReadLine ();

					if (!p.WaitForExit (timeout * 1000)) {
						lock (monitor) {
							timedout.Add (data);
						}

						if (concurrency == 1)
							Console.WriteLine ("timed out.");
						else
							Console.Write (".");

						p.Kill ();
					} else if (p.ExitCode != expectedExitCode) {
						lock (monitor) {
							failed.Add (data);
						}

						if (concurrency == 1)
							Console.WriteLine ("failed.");
						else
							Console.Write (".");
					} else {
						lock (monitor) {
							passed.Add (data);
						}

						if (concurrency == 1)
							Console.WriteLine ("passed.");
						else
							Console.Write (".");
					}

					p.Close ();
				}
			});

			thread.Start ();

			threads.Add (thread);
		}

		for (int j = 0; j < threads.Count; ++j)
			threads [j].Join ();

		int npassed = passed.Count;
		int nfailed = failed.Count;
		int ntimedout = timedout.Count;

		TimeSpan test_time = DateTime.UtcNow - test_start_time;
		XmlWriterSettings xmlWriterSettings = new XmlWriterSettings ();
		xmlWriterSettings.NewLineOnAttributes = true;
		xmlWriterSettings.Indent = true;
		using (XmlWriter writer = XmlWriter.Create (String.Format ("TestResults_{0}.xml", testsuiteName), xmlWriterSettings)) {
			// <?xml version="1.0" encoding="utf-8" standalone="no"?>
			writer.WriteStartDocument ();
			// <!--This file represents the results of running a test suite-->
			writer.WriteComment ("This file represents the results of running a test suite");
			// <test-results name="/home/charlie/Dev/NUnit/nunit-2.5/work/src/bin/Debug/tests/mock-assembly.dll" total="21" errors="1" failures="1" not-run="7" inconclusive="1" ignored="4" skipped="0" invalid="3" date="2010-10-18" time="13:23:35">
			writer.WriteStartElement ("test-results");
			writer.WriteAttributeString ("name", String.Format ("{0}-tests.dummy", testsuiteName));
			writer.WriteAttributeString ("total", (npassed + nfailed + ntimedout).ToString());
			writer.WriteAttributeString ("failures", (nfailed + ntimedout).ToString());
			writer.WriteAttributeString ("not-run", "0");
			writer.WriteAttributeString ("date", DateTime.Now.ToString ("yyyy-MM-dd"));
			writer.WriteAttributeString ("time", DateTime.Now.ToString ("HH:mm:ss"));
			//   <environment nunit-version="2.4.8.0" clr-version="4.0.30319.17020" os-version="Unix 3.13.0.45" platform="Unix" cwd="/home/directhex/Projects/mono/mcs/class/corlib" machine-name="marceline" user="******" user-domain="marceline" />
			writer.WriteStartElement ("environment");
			writer.WriteAttributeString ("nunit-version", "2.4.8.0" );
			writer.WriteAttributeString ("clr-version", Environment.Version.ToString() );
			writer.WriteAttributeString ("os-version", Environment.OSVersion.ToString() );
			writer.WriteAttributeString ("platform", Environment.OSVersion.Platform.ToString() );
			writer.WriteAttributeString ("cwd", Environment.CurrentDirectory );
			writer.WriteAttributeString ("machine-name", Environment.MachineName );
			writer.WriteAttributeString ("user", Environment.UserName );
			writer.WriteAttributeString ("user-domain", Environment.UserDomainName );
			writer.WriteEndElement ();
			//   <culture-info current-culture="en-GB" current-uiculture="en-GB" />
			writer.WriteStartElement ("culture-info");
			writer.WriteAttributeString ("current-culture", CultureInfo.CurrentCulture.Name );
			writer.WriteAttributeString ("current-uiculture", CultureInfo.CurrentUICulture.Name );
			writer.WriteEndElement ();
			//   <test-suite name="corlib_test_net_4_5.dll" success="True" time="114.318" asserts="0">
			writer.WriteStartElement ("test-suite");
			writer.WriteAttributeString ("name", String.Format ("{0}-tests.dummy", testsuiteName));
			writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString());
			writer.WriteAttributeString ("time", test_time.Seconds.ToString());
			writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString());
			//     <results>
			writer.WriteStartElement ("results");
			//       <test-suite name="MonoTests" success="True" time="114.318" asserts="0">
			writer.WriteStartElement ("test-suite");
			writer.WriteAttributeString ("name","MonoTests");
			writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString());
			writer.WriteAttributeString ("time", test_time.Seconds.ToString());
			writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString());
			//         <results>
			writer.WriteStartElement ("results");
			//           <test-suite name="MonoTests" success="True" time="114.318" asserts="0">
			writer.WriteStartElement ("test-suite");
			writer.WriteAttributeString ("name", testsuiteName);
			writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString());
			writer.WriteAttributeString ("time", test_time.Seconds.ToString());
			writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString());
			//             <results>
			writer.WriteStartElement ("results");
			// Dump all passing tests first
			foreach (ProcessData pd in passed) {
				// <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
				writer.WriteStartElement ("test-case");
				writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}", testsuiteName, pd.test));
				writer.WriteAttributeString ("executed", "True");
				writer.WriteAttributeString ("success", "True");
				writer.WriteAttributeString ("time", "0");
				writer.WriteAttributeString ("asserts", "0");
				writer.WriteEndElement ();
			}
			// Now dump all failing tests
			foreach (ProcessData pd in failed) {
				// <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
				writer.WriteStartElement ("test-case");
				writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}", testsuiteName, pd.test));
				writer.WriteAttributeString ("executed", "True");
				writer.WriteAttributeString ("success", "False");
				writer.WriteAttributeString ("time", "0");
				writer.WriteAttributeString ("asserts", "1");
				writer.WriteStartElement ("failure");
				writer.WriteStartElement ("message");
				writer.WriteCData (DumpPseudoTrace (pd.stdoutFile));
				writer.WriteEndElement ();
				writer.WriteStartElement ("stack-trace");
				writer.WriteCData (DumpPseudoTrace (pd.stderrFile));
				writer.WriteEndElement ();
				writer.WriteEndElement ();
				writer.WriteEndElement ();
			}
			// Then dump all timing out tests
			foreach (ProcessData pd in timedout) {
				// <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
				writer.WriteStartElement ("test-case");
				writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}_timedout", testsuiteName, pd.test));
				writer.WriteAttributeString ("executed", "True");
				writer.WriteAttributeString ("success", "False");
				writer.WriteAttributeString ("time", "0");
				writer.WriteAttributeString ("asserts", "1");
				writer.WriteStartElement ("failure");
				writer.WriteStartElement ("message");
				writer.WriteCData (DumpPseudoTrace (pd.stdoutFile));
				writer.WriteEndElement ();
				writer.WriteStartElement ("stack-trace");
				writer.WriteCData (DumpPseudoTrace (pd.stderrFile));
				writer.WriteEndElement ();
				writer.WriteEndElement ();
				writer.WriteEndElement ();
			}
			//             </results>
			writer.WriteEndElement ();
			//           </test-suite>
			writer.WriteEndElement ();
			//         </results>
			writer.WriteEndElement ();
			//       </test-suite>
			writer.WriteEndElement ();
			//     </results>
			writer.WriteEndElement ();
			//   </test-suite>
			writer.WriteEndElement ();
			// </test-results>
			writer.WriteEndElement ();
			writer.WriteEndDocument ();
		}

		Console.WriteLine ();
		Console.WriteLine ("{0,4} test(s) passed", npassed);
		Console.WriteLine ("{0,4} test(s) failed", nfailed);
		Console.WriteLine ("{0,4} test(s) timed out", ntimedout);

		if (nfailed > 0) {
			Console.WriteLine ();
			Console.WriteLine ("Failed test(s):");
			foreach (ProcessData pd in failed) {
				Console.WriteLine ();
				Console.WriteLine (pd.test);
				DumpFile (pd.stdoutFile);
				DumpFile (pd.stderrFile);
			}
		}

		if (ntimedout > 0) {
			Console.WriteLine ();
			Console.WriteLine ("Timed out test(s):");
			foreach (ProcessData pd in timedout) {
				Console.WriteLine ();
				Console.WriteLine (pd.test);
				DumpFile (pd.stdoutFile);
				DumpFile (pd.stderrFile);
			}
		}

		return (ntimedout == 0 && nfailed == 0) ? 0 : 1;
	}
Esempio n. 46
0
 public static ProcesosDelSistema generarInstanciaProcesos()
 {
     ProcesosDelSistema procesosDelSistema = new ProcesosDelSistema();
     Process[] procs = Process.GetProcesses();
     foreach (Process pr in procs)
     {
         ProcessData proceso = new ProcessData("" + pr.Id, pr.ProcessName, pr.MainWindowTitle);
         procesosDelSistema.procesos.Add(proceso);
     }
     return procesosDelSistema;
 }
Esempio n. 47
0
            /// <summary>
            ///     Start a process
            /// </summary>
            /// <param name="processData">Information about th process to be started</param>
            static private void startProcess(ProcessData processData)
            {
                log.Debug("Waiting mutex release before process start.");
                Shortcuts.Handler handler = Shortcuts.Handler.getInstance();
                if (handler != null)
                    handler.waitModifiersReleased();

                log.Info("Starting process: " + processData.StartPath);

                Process process = new Process();
                process.StartInfo.FileName = processData.StartPath;
                process.StartInfo.Arguments = String.Join<string>(" ", processData.StartArguments);
                process.StartInfo.WorkingDirectory = processData.StartFolder;
                process.StartInfo.UseShellExecute = processData.Shell;

                process.Start();
            }
Esempio n. 48
0
        private void ProcessFinish(ProcessData Processor, SocketPurpose Purpose, Socket NetworkSocket, IAsyncResult ar)
        {
            try
            {
                byte[] writeData = Processor.EndInvoke(ar);

                if (writeData != null)
                {
                    NetworkSocket.BeginSend(writeData, 0, writeData.Length, SocketFlags.None,
                        delegate(IAsyncResult AsR) { NetworkWrite(Processor, Purpose, NetworkSocket, writeData, 0, AsR); },
                        null);
                }
                else
                {
                    NetworkSocket.BeginReceive(networkBuf, 0, 1024, SocketFlags.None,
                            delegate(IAsyncResult AsR) { NetworkReceive(Purpose, NetworkSocket, AsR); },
                            null);
                }
            }
            catch (JTAGException e)
            {
                Console.WriteLine("JTAG Error while procesing.  {0}", e.Message);

                Disconnect();
                DeviceInUse = false;

                OnError();
            }
            catch (SocketException e)
            {
                OnSocketException(Purpose, NetworkSocket, e);
            }
            catch (ObjectDisposedException)
            {
                OnObjectDisposedException(Purpose, NetworkSocket);
            }
        }
        protected override bool _OnRegister(TorqueObject owner)
        {
            if (!base._OnRegister(owner) || !(owner is T2DSceneObject))
                return false;

            for (int i = 0; i < _processors.Count; i++)
            {
                ProcessData data = new ProcessData();
                if (!_InitProcessor(_processors[i], ref data))
                {
                    Assert.Fatal(false, "Float interface " + _processors[i].InterfaceName + " not found.");
                    return false;
                }
                _processData[i] = data;
            }

            ProcessList.Instance.AddTickCallback(SceneObject, this, 0.0f);

            return true;
        }
	public static int Main (String[] args) {
		// Defaults
		int concurrency = 1;
		int timeout = 2 * 60; // in seconds

		DateTime test_start_time = DateTime.UtcNow;

		// FIXME: Add support for runtime arguments + env variables

		string disabled_tests = null;
		string runtime = "mono";
		var opt_sets = new List<string> ();

		// Process options
		int i = 0;
		while (i < args.Length) {
			if (args [i].StartsWith ("-")) {
				if (args [i] == "-j") {
					if (i + i >= args.Length) {
						Console.WriteLine ("Missing argument to -j command line option.");
						return 1;
					}
					if (args [i + 1] == "a")
						concurrency = Environment.ProcessorCount;
					else
						concurrency = Int32.Parse (args [i + 1]);
					i += 2;
				} else if (args [i] == "--timeout") {
					if (i + i >= args.Length) {
						Console.WriteLine ("Missing argument to --timeout command line option.");
						return 1;
					}
					timeout = Int32.Parse (args [i + 1]);
					i += 2;
				} else if (args [i] == "--disabled") {
					if (i + i >= args.Length) {
						Console.WriteLine ("Missing argument to --disabled command line option.");
						return 1;
					}
					disabled_tests = args [i + 1];
					i += 2;
				} else if (args [i] == "--runtime") {
					if (i + i >= args.Length) {
						Console.WriteLine ("Missing argument to --runtime command line option.");
						return 1;
					}
					runtime = args [i + 1];
					i += 2;
				} else if (args [i] == "--opt-sets") {
					if (i + i >= args.Length) {
						Console.WriteLine ("Missing argument to --opt-sets command line option.");
						return 1;
					}
					foreach (var s in args [i + 1].Split ())
						opt_sets.Add (s);
					i += 2;
				} else {
					Console.WriteLine ("Unknown command line option: '" + args [i] + "'.");
					return 1;
				}
			} else {
				break;
			}
		}

		var disabled = new Dictionary <string, string> ();

		if (disabled_tests != null) {
			foreach (string test in disabled_tests.Split ())
				disabled [test] = test;
		}

		// The remaining arguments are the tests
		var tests = new List<string> ();
		for (int j = i; j < args.Length; ++j)
			if (!disabled.ContainsKey (args [j]))
				tests.Add (args [j]);

		int npassed = 0;
		int nfailed = 0;

		var processes = new List<Process> ();
		var passed = new List<ProcessData> ();
		var failed = new List<ProcessData> ();
		var process_data = new Dictionary<Process, ProcessData> ();

		object monitor = new object ();

		var terminated = new List<Process> ();

		if (concurrency != 1)
			Console.WriteLine ("Running tests: ");

		var test_info = new List<TestInfo> ();
		if (opt_sets.Count == 0) {
			foreach (string s in tests)
				test_info.Add (new TestInfo { test = s });
		} else {
			foreach (string opt in opt_sets) {
				foreach (string s in tests)
					test_info.Add (new TestInfo { test = s, opt_set = opt });
			}
		}		

		foreach (TestInfo ti in test_info) {
			lock (monitor) {
				while (processes.Count == concurrency) {
					/* Wait for one process to terminate */
					Monitor.Wait (monitor);
				}

				/* Cleaup terminated processes */
				foreach (Process dead in terminated) {
					if (process_data [dead].stdout != null)
						process_data [dead].stdout.Close ();
					if (process_data [dead].stderr != null)
						process_data [dead].stderr.Close ();
					// This is needed to avoid CreateProcess failed errors :(
					dead.Close ();
				}
				terminated.Clear ();
			}

			string test = ti.test;
			string opt_set = ti.opt_set;

			if (concurrency == 1)
				Console.Write ("Testing " + test + "... ");

			/* Spawn a new process */
			string process_args;
			if (opt_set == null)
				process_args = test;
			else
				process_args = "-O=" + opt_set + " " + test;
			ProcessStartInfo info = new ProcessStartInfo (runtime, process_args);
			info.UseShellExecute = false;
			info.RedirectStandardOutput = true;
			info.RedirectStandardError = true;
			Process p = new Process ();
			p.StartInfo = info;
			p.EnableRaisingEvents = true;

			ProcessData data = new ProcessData ();
			data.test = test;

			p.Exited += delegate (object sender, EventArgs e) {
				// Anon methods share some of their state, so we can't use
				// variables which change during the loop (test, p)
				Process dead = (Process)sender;

				lock (monitor) {
					if (dead.ExitCode == 0) {
						if (concurrency == 1)
							Console.WriteLine ("passed.");
						else
							Console.Write (".");
						passed.Add(process_data [dead]);
						npassed ++;
					} else {
						if (concurrency == 1)
							Console.WriteLine ("failed.");
						else
							Console.Write ("F");
						failed.Add (process_data [dead]);
						nfailed ++;
					}
					processes.Remove (dead);
					terminated.Add (dead);
					Monitor.Pulse (monitor);
				}
			};

			string log_prefix = "";
			if (opt_set != null)
				log_prefix = "." + opt_set.Replace ("-", "no").Replace (",", "_");

			data.stdoutFile = test + log_prefix + ".stdout";
			data.stdout = new StreamWriter (new FileStream (data.stdoutFile, FileMode.Create));

			data.stderrFile = test + log_prefix + ".stderr";
			data.stderr = new StreamWriter (new FileStream (data.stderrFile, FileMode.Create));

			p.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e) {
				Process p2 = (Process)sender;

				StreamWriter fs;

				lock (monitor) {
					fs = process_data [p2].stdout;

					if (String.IsNullOrEmpty (e.Data))
						process_data [p2].stdout = null;
				}

				if (String.IsNullOrEmpty (e.Data)) {
					fs.Close ();
				} else {
					fs.WriteLine (e.Data);
					fs.Flush ();
				}
			};

			p.ErrorDataReceived += delegate (object sender, DataReceivedEventArgs e) {
				Process p2 = (Process)sender;

				StreamWriter fs;

				lock (monitor) {
					fs = process_data [p2].stderr;

					if (String.IsNullOrEmpty (e.Data))
						process_data [p2].stderr = null;

				}

				if (String.IsNullOrEmpty (e.Data)) {
					fs.Close ();

					lock (monitor) {
						process_data [p2].stderr = null;
					}
				} else {
					fs.WriteLine (e.Data);
					fs.Flush ();
				}
			};

			lock (monitor) {
				processes.Add (p);
				process_data [p] = data;
			}
			p.Start ();

			p.BeginOutputReadLine ();
			p.BeginErrorReadLine ();
		}

		bool timed_out = false;

		/* Wait for all processes to terminate */
		while (true) {
			lock (monitor) {
				int nprocesses = processes.Count;

				if (nprocesses == 0)
					break;

				bool res = Monitor.Wait (monitor, 1000 * timeout);
				if (!res) {
					timed_out = true;
					break;
				}
			}
		}

		TimeSpan test_time = DateTime.UtcNow - test_start_time;
		XmlWriterSettings xmlWriterSettings = new XmlWriterSettings ();
		xmlWriterSettings.NewLineOnAttributes = true;
		xmlWriterSettings.Indent = true;
		using (XmlWriter writer = XmlWriter.Create ("TestResults_runtime.xml", xmlWriterSettings)) {
			// <?xml version="1.0" encoding="utf-8" standalone="no"?>
			writer.WriteStartDocument ();
			// <!--This file represents the results of running a test suite-->
			writer.WriteComment ("This file represents the results of running a test suite");
			// <test-results name="/home/charlie/Dev/NUnit/nunit-2.5/work/src/bin/Debug/tests/mock-assembly.dll" total="21" errors="1" failures="1" not-run="7" inconclusive="1" ignored="4" skipped="0" invalid="3" date="2010-10-18" time="13:23:35">
			writer.WriteStartElement ("test-results");
			writer.WriteAttributeString ("name", "runtime-tests.dummy");
			writer.WriteAttributeString ("total", (npassed + nfailed).ToString());
			writer.WriteAttributeString ("failures", nfailed.ToString());
			writer.WriteAttributeString ("not-run", "0");
			writer.WriteAttributeString ("date", DateTime.Now.ToString ("yyyy-MM-dd"));
			writer.WriteAttributeString ("time", DateTime.Now.ToString ("HH:mm:ss"));
			//   <environment nunit-version="2.4.8.0" clr-version="4.0.30319.17020" os-version="Unix 3.13.0.45" platform="Unix" cwd="/home/directhex/Projects/mono/mcs/class/corlib" machine-name="marceline" user="******" user-domain="marceline" />
			writer.WriteStartElement ("environment");
			writer.WriteAttributeString ("nunit-version", "2.4.8.0" );
			writer.WriteAttributeString ("clr-version", Environment.Version.ToString() );
			writer.WriteAttributeString ("os-version", Environment.OSVersion.ToString() );
			writer.WriteAttributeString ("platform", Environment.OSVersion.Platform.ToString() );
			writer.WriteAttributeString ("cwd", Environment.CurrentDirectory );
			writer.WriteAttributeString ("machine-name", Environment.MachineName );
			writer.WriteAttributeString ("user", Environment.UserName );
			writer.WriteAttributeString ("user-domain", Environment.UserDomainName );
			writer.WriteEndElement ();
			//   <culture-info current-culture="en-GB" current-uiculture="en-GB" />
			writer.WriteStartElement ("culture-info");
			writer.WriteAttributeString ("current-culture", CultureInfo.CurrentCulture.Name );
			writer.WriteAttributeString ("current-uiculture", CultureInfo.CurrentUICulture.Name );
			writer.WriteEndElement ();
			//   <test-suite name="corlib_test_net_4_5.dll" success="True" time="114.318" asserts="0">
			writer.WriteStartElement ("test-suite");
			writer.WriteAttributeString ("name","runtime-tests.dummy");
			writer.WriteAttributeString ("success", (nfailed == 0).ToString());
			writer.WriteAttributeString ("time", test_time.Seconds.ToString());
			writer.WriteAttributeString ("asserts", nfailed.ToString());
			//     <results>
			writer.WriteStartElement ("results");
			//       <test-suite name="MonoTests" success="True" time="114.318" asserts="0">
			writer.WriteStartElement ("test-suite");
			writer.WriteAttributeString ("name","MonoTests");
			writer.WriteAttributeString ("success", (nfailed == 0).ToString());
			writer.WriteAttributeString ("time", test_time.Seconds.ToString());
			writer.WriteAttributeString ("asserts", nfailed.ToString());
			//         <results>
			writer.WriteStartElement ("results");
			//           <test-suite name="MonoTests" success="True" time="114.318" asserts="0">
			writer.WriteStartElement ("test-suite");
			writer.WriteAttributeString ("name","runtime");
			writer.WriteAttributeString ("success", (nfailed == 0).ToString());
			writer.WriteAttributeString ("time", test_time.Seconds.ToString());
			writer.WriteAttributeString ("asserts", nfailed.ToString());
			//             <results>
			writer.WriteStartElement ("results");
			// Dump all passing tests first
			foreach (ProcessData pd in passed) {
				// <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
				writer.WriteStartElement ("test-case");
				writer.WriteAttributeString ("name", "MonoTests.runtime." + pd.test);
				writer.WriteAttributeString ("executed", "True");
				writer.WriteAttributeString ("success", "True");
				writer.WriteAttributeString ("time", "0");
				writer.WriteAttributeString ("asserts", "0");
				writer.WriteEndElement ();
			}
			// Now dump all failing tests
			foreach (ProcessData pd in failed) {
				// <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
				writer.WriteStartElement ("test-case");
				writer.WriteAttributeString ("name", "MonoTests.runtime." + pd.test);
				writer.WriteAttributeString ("executed", "True");
				writer.WriteAttributeString ("success", "False");
				writer.WriteAttributeString ("time", "0");
				writer.WriteAttributeString ("asserts", "1");
				writer.WriteStartElement ("failure");
				writer.WriteStartElement ("message");
				writer.WriteCData (DumpPseudoTrace (pd.stdoutFile));
				writer.WriteEndElement ();
				writer.WriteStartElement ("stack-trace");
				writer.WriteCData (DumpPseudoTrace (pd.stderrFile));
				writer.WriteEndElement ();
				writer.WriteEndElement ();
				writer.WriteEndElement ();
			}
			//             </results>
			writer.WriteEndElement ();
			//           </test-suite>
			writer.WriteEndElement ();
			//         </results>
			writer.WriteEndElement ();
			//       </test-suite>
			writer.WriteEndElement ();
			//     </results>
			writer.WriteEndElement ();
			//   </test-suite>
			writer.WriteEndElement ();
			// </test-results>
			writer.WriteEndElement ();
			writer.WriteEndDocument ();
		}

		Console.WriteLine ();

		if (timed_out) {
			Console.WriteLine ("\nrunning tests timed out:\n");
			Console.WriteLine (npassed + nfailed);
			lock (monitor) {
				foreach (Process p in processes) {
					ProcessData pd = process_data [p];
					pd.CloseStreams ();
					Console.WriteLine (pd.test);
					p.Kill ();
					DumpFile (pd.stdoutFile);
					DumpFile (pd.stderrFile);
				}
			}
			return 1;
		}

		Console.WriteLine ("" + npassed + " test(s) passed. " + nfailed + " test(s) did not pass.");
		if (nfailed > 0) {
			Console.WriteLine ("\nFailed tests:\n");
			foreach (ProcessData pd in failed) {
				Console.WriteLine (pd.test);
				DumpFile (pd.stdoutFile);
				DumpFile (pd.stderrFile);
			}
			return 1;
		} else {
			return 0;
		}
	}
Esempio n. 51
0
	public static int Main (String[] args) {
		// Defaults
		int concurrency = 1;
		int timeout = 2 * 60; // in seconds
		int expectedExitCode = 0;
		bool verbose = false;
		string testsuiteName = null;
		string inputFile = null;

		string disabled_tests = null;
		string runtime = "mono";
		string config = null;
		string mono_path = null;
		var opt_sets = new List<string> ();

		string aot_run_flags = null;
		string aot_build_flags = null;

		// Process options
		int i = 0;
		while (i < args.Length) {
			if (args [i].StartsWith ("-")) {
				if (args [i] == "-j") {
					if (i + 1 >= args.Length) {
						Console.WriteLine ("Missing argument to -j command line option.");
						return 1;
					}
					if (args [i + 1] == "a")
						concurrency = Environment.ProcessorCount;
					else
						concurrency = Int32.Parse (args [i + 1]);
					i += 2;
				} else if (args [i] == "--timeout") {
					if (i + 1 >= args.Length) {
						Console.WriteLine ("Missing argument to --timeout command line option.");
						return 1;
					}
					timeout = Int32.Parse (args [i + 1]);
					i += 2;
				} else if (args [i] == "--disabled") {
					if (i + 1 >= args.Length) {
						Console.WriteLine ("Missing argument to --disabled command line option.");
						return 1;
					}
					disabled_tests = args [i + 1];
					i += 2;
				} else if (args [i] == "--runtime") {
					if (i + 1 >= args.Length) {
						Console.WriteLine ("Missing argument to --runtime command line option.");
						return 1;
					}
					runtime = args [i + 1];
					i += 2;
				} else if (args [i] == "--config") {
					if (i + 1 >= args.Length) {
						Console.WriteLine ("Missing argument to --config command line option.");
						return 1;
					}
					config = args [i + 1];
					i += 2;
				} else if (args [i] == "--opt-sets") {
					if (i + 1 >= args.Length) {
						Console.WriteLine ("Missing argument to --opt-sets command line option.");
						return 1;
					}
					foreach (var s in args [i + 1].Split ())
						opt_sets.Add (s);
					i += 2;
				} else if (args [i] == "--expected-exit-code") {
					if (i + 1 >= args.Length) {
						Console.WriteLine ("Missing argument to --expected-exit-code command line option.");
						return 1;
					}
					expectedExitCode = Int32.Parse (args [i + 1]);
					i += 2;
				} else if (args [i] == "--testsuite-name") {
					if (i + 1 >= args.Length) {
						Console.WriteLine ("Missing argument to --testsuite-name command line option.");
						return 1;
					}
					testsuiteName = args [i + 1];
					i += 2;
				} else if (args [i] == "--input-file") {
					if (i + 1 >= args.Length) {
						Console.WriteLine ("Missing argument to --input-file command line option.");
						return 1;
					}
					inputFile = args [i + 1];
					i += 2;
				} else if (args [i] == "--runtime") {
					if (i + 1 >= args.Length) {
						Console.WriteLine ("Missing argument to --runtime command line option.");
						return 1;
					}
					runtime = args [i + 1];
					i += 2;
				} else if (args [i] == "--mono-path") {
					if (i + 1 >= args.Length) {
						Console.WriteLine ("Missing argument to --mono-path command line option.");
						return 1;
					}
					mono_path = args [i + 1].Substring(0, args [i + 1].Length);

					i += 2;
				} else if (args [i] == "--aot-run-flags") {
					if (i + 1 >= args.Length) {
						Console.WriteLine ("Missing argument to --aot-run-flags command line option.");
						return 1;
					}
					aot_run_flags = args [i + 1].Substring(0, args [i + 1].Length);
					i += 2;
				} else if (args [i] == "--aot-build-flags") {
					if (i + 1 >= args.Length) {
						Console.WriteLine ("Missing argument to --aot-build-flags command line option.");
						return 1;
					}
					aot_build_flags = args [i + 1].Substring(0, args [i + 1].Length);
					i += 2;
				} else if (args [i] == "--verbose") {
					verbose = true;
					i ++;
				} else {
					Console.WriteLine ("Unknown command line option: '" + args [i] + "'.");
					return 1;
				}
			} else {
				break;
			}
		}

		if (String.IsNullOrEmpty (testsuiteName)) {
			Console.WriteLine ("Missing the required --testsuite-name command line option.");
			return 1;
		}

		var disabled = new Dictionary <string, string> ();

		if (disabled_tests != null) {
			foreach (string test in disabled_tests.Split ())
				disabled [test] = test;
		}

		var tests = new List<string> ();

		if (!String.IsNullOrEmpty (inputFile)) {
			tests.AddRange (File.ReadAllLines (inputFile));
		} else {
			// The remaining arguments are the tests
			for (int j = i; j < args.Length; ++j)
				if (!disabled.ContainsKey (args [j]))
					tests.Add (args [j]);
		}

		var passed = new List<ProcessData> ();
		var failed = new List<ProcessData> ();
		var timedout = new List<ProcessData> ();

		object monitor = new object ();

		Console.WriteLine ("Running tests: ");

		var test_info = new Queue<TestInfo> ();
		if (opt_sets.Count == 0) {
			foreach (string s in tests)
				test_info.Enqueue (new TestInfo { test = s });
		} else {
			foreach (string opt in opt_sets) {
				foreach (string s in tests)
					test_info.Enqueue (new TestInfo { test = s, opt_set = opt });
			}
		}

		/* compute the max length of test names, to have an optimal output width */
		int output_width = -1;
		foreach (TestInfo ti in test_info) {
			if (ti.test.Length > output_width)
				output_width = Math.Min (120, ti.test.Length);
		}

		if (aot_build_flags != null)  {
			Console.WriteLine("AOT compiling tests");

			object aot_monitor = new object ();
			var aot_queue = new Queue<String> (tests); 

			List<Thread> build_threads = new List<Thread> (concurrency);

			for (int j = 0; j < concurrency; ++j) {
				Thread thread = new Thread (() => {
					while (true) {
						String test_name;

						lock (aot_monitor) {
							if (aot_queue.Count == 0)
								break;
							test_name = aot_queue.Dequeue ();
						}

						string test_bitcode_output = test_name + "_bitcode_tmp";
						string test_bitcode_arg = ",temp-path=" + test_bitcode_output;
						string aot_args = aot_build_flags + test_bitcode_arg + " " + test_name;

						Directory.CreateDirectory(test_bitcode_output);

						ProcessStartInfo job = new ProcessStartInfo (runtime, aot_args);
						job.UseShellExecute = false;
						job.EnvironmentVariables[ENV_TIMEOUT] = timeout.ToString();
						job.EnvironmentVariables[MONO_PATH] = mono_path;
						Process compiler = new Process ();
						compiler.StartInfo = job;

						compiler.Start ();

						if (!compiler.WaitForExit (timeout * 1000)) {
							try {
								compiler.Kill ();
							} catch {
							}
							throw new Exception(String.Format("Timeout AOT compiling tests, output in {0}", test_bitcode_output));
						} else if (compiler.ExitCode != 0) {
							throw new Exception(String.Format("Error AOT compiling tests, output in {0}", test_bitcode_output));
						} else {
							Directory.Delete (test_bitcode_output, true);
						}
					}
				});

				thread.Start ();

				build_threads.Add (thread);
			}

			for (int j = 0; j < build_threads.Count; ++j)
				build_threads [j].Join ();

			Console.WriteLine("Done compiling");
		}

		List<Thread> threads = new List<Thread> (concurrency);

		DateTime test_start_time = DateTime.UtcNow;

		for (int j = 0; j < concurrency; ++j) {
			Thread thread = new Thread (() => {
				while (true) {
					TestInfo ti;

					lock (monitor) {
						if (test_info.Count == 0)
							break;
						ti = test_info.Dequeue ();
					}

					var output = new StringWriter ();

					string test = ti.test;
					string opt_set = ti.opt_set;

					if (verbose) {
						output.Write (String.Format ("{{0,-{0}}} ", output_width), test);
					} else {
						Console.Write (".");
					}

					string test_invoke;

					if (aot_run_flags != null)
						test_invoke = aot_run_flags + " " + test;
					else
						test_invoke = test;

					/* Spawn a new process */
					string process_args;
					if (opt_set == null)
						process_args = test_invoke;
					else
						process_args = "-O=" + opt_set + " " + test_invoke;

					ProcessStartInfo info = new ProcessStartInfo (runtime, process_args);
					info.UseShellExecute = false;
					info.RedirectStandardOutput = true;
					info.RedirectStandardError = true;
					info.EnvironmentVariables[ENV_TIMEOUT] = timeout.ToString();
					if (config != null)
						info.EnvironmentVariables["MONO_CONFIG"] = config;
					if (mono_path != null)
						info.EnvironmentVariables[MONO_PATH] = mono_path;
					Process p = new Process ();
					p.StartInfo = info;

					ProcessData data = new ProcessData ();
					data.test = test;

					string log_prefix = "";
					if (opt_set != null)
						log_prefix = "." + opt_set.Replace ("-", "no").Replace (",", "_");

					data.stdoutName = test + log_prefix + ".stdout";
					data.stdout = new StringBuilder ();

					data.stderrName = test + log_prefix + ".stderr";
					data.stderr = new StringBuilder ();

					p.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e) {
						if (e.Data != null) {
							data.stdout.AppendLine (e.Data);
						}
					};

					p.ErrorDataReceived += delegate (object sender, DataReceivedEventArgs e) {
						if (e.Data != null) {
							data.stderr.AppendLine (e.Data);
						}
					};

					var start = DateTime.UtcNow;

					p.Start ();

					p.BeginOutputReadLine ();
					p.BeginErrorReadLine ();

					if (!p.WaitForExit (timeout * 1000)) {
						lock (monitor) {
							timedout.Add (data);
						}

#if !MOBILE_STATIC
						// Force the process to print a thread dump
						try {
							Syscall.kill (p.Id, Signum.SIGQUIT);
							Thread.Sleep (1000);
						} catch {
						}
#endif

						if (verbose) {
							output.Write ($"timed out ({timeout}s)");
						}

						try {
							p.Kill ();
						} catch {
						}
					} else if (p.ExitCode != expectedExitCode) {
						var end = DateTime.UtcNow;

						lock (monitor) {
							failed.Add (data);
						}

						if (verbose)
							output.Write ("failed, time: {0}, exit code: {1}", (end - start).ToString (TEST_TIME_FORMAT), p.ExitCode);
					} else {
						var end = DateTime.UtcNow;

						lock (monitor) {
							passed.Add (data);
						}

						if (verbose)
							output.Write ("passed, time: {0}", (end - start).ToString (TEST_TIME_FORMAT));
					}

					p.Close ();

					lock (monitor) {
						if (verbose)
							Console.WriteLine (output.ToString ());
					}
				}
			});

			thread.Start ();

			threads.Add (thread);
		}

		for (int j = 0; j < threads.Count; ++j)
			threads [j].Join ();

		TimeSpan test_time = DateTime.UtcNow - test_start_time;

		int npassed = passed.Count;
		int nfailed = failed.Count;
		int ntimedout = timedout.Count;

		XmlWriterSettings xmlWriterSettings = new XmlWriterSettings ();
		xmlWriterSettings.NewLineOnAttributes = true;
		xmlWriterSettings.Indent = true;

		string xmlPath = String.Format ("TestResult-{0}.xml", testsuiteName);
		using (XmlWriter writer = XmlWriter.Create (xmlPath, xmlWriterSettings)) {
			// <?xml version="1.0" encoding="utf-8" standalone="no"?>
			writer.WriteStartDocument ();
			// <!--This file represents the results of running a test suite-->
			writer.WriteComment ("This file represents the results of running a test suite");
			// <test-results name="/home/charlie/Dev/NUnit/nunit-2.5/work/src/bin/Debug/tests/mock-assembly.dll" total="21" errors="1" failures="1" not-run="7" inconclusive="1" ignored="4" skipped="0" invalid="3" date="2010-10-18" time="13:23:35">
			writer.WriteStartElement ("test-results");
			writer.WriteAttributeString ("name", String.Format ("{0}-tests.dummy", testsuiteName));
			writer.WriteAttributeString ("total", (npassed + nfailed + ntimedout).ToString());
			writer.WriteAttributeString ("failures", (nfailed + ntimedout).ToString());
			writer.WriteAttributeString ("not-run", "0");
			writer.WriteAttributeString ("date", DateTime.Now.ToString ("yyyy-MM-dd"));
			writer.WriteAttributeString ("time", DateTime.Now.ToString ("HH:mm:ss"));
			//   <environment nunit-version="2.4.8.0" clr-version="4.0.30319.17020" os-version="Unix 3.13.0.45" platform="Unix" cwd="/home/directhex/Projects/mono/mcs/class/corlib" machine-name="marceline" user="******" user-domain="marceline" />
			writer.WriteStartElement ("environment");
			writer.WriteAttributeString ("nunit-version", "2.4.8.0" );
			writer.WriteAttributeString ("clr-version", Environment.Version.ToString() );
			writer.WriteAttributeString ("os-version", Environment.OSVersion.ToString() );
			writer.WriteAttributeString ("platform", Environment.OSVersion.Platform.ToString() );
			writer.WriteAttributeString ("cwd", Environment.CurrentDirectory );
			writer.WriteAttributeString ("machine-name", Environment.MachineName );
			writer.WriteAttributeString ("user", Environment.UserName );
			writer.WriteAttributeString ("user-domain", Environment.UserDomainName );
			writer.WriteEndElement ();
			//   <culture-info current-culture="en-GB" current-uiculture="en-GB" />
			writer.WriteStartElement ("culture-info");
			writer.WriteAttributeString ("current-culture", CultureInfo.CurrentCulture.Name );
			writer.WriteAttributeString ("current-uiculture", CultureInfo.CurrentUICulture.Name );
			writer.WriteEndElement ();
			//   <test-suite name="corlib_test_net_4_5.dll" success="True" time="114.318" asserts="0">
			writer.WriteStartElement ("test-suite");
			writer.WriteAttributeString ("name", String.Format ("{0}-tests.dummy", testsuiteName));
			writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString());
			writer.WriteAttributeString ("time", test_time.Seconds.ToString());
			writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString());
			//     <results>
			writer.WriteStartElement ("results");
			//       <test-suite name="MonoTests" success="True" time="114.318" asserts="0">
			writer.WriteStartElement ("test-suite");
			writer.WriteAttributeString ("name","MonoTests");
			writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString());
			writer.WriteAttributeString ("time", test_time.Seconds.ToString());
			writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString());
			//         <results>
			writer.WriteStartElement ("results");
			//           <test-suite name="MonoTests" success="True" time="114.318" asserts="0">
			writer.WriteStartElement ("test-suite");
			writer.WriteAttributeString ("name", testsuiteName);
			writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString());
			writer.WriteAttributeString ("time", test_time.Seconds.ToString());
			writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString());
			//             <results>
			writer.WriteStartElement ("results");
			// Dump all passing tests first
			foreach (ProcessData pd in passed) {
				// <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
				writer.WriteStartElement ("test-case");
				writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}", testsuiteName, pd.test));
				writer.WriteAttributeString ("executed", "True");
				writer.WriteAttributeString ("success", "True");
				writer.WriteAttributeString ("time", "0");
				writer.WriteAttributeString ("asserts", "0");
				writer.WriteEndElement ();
			}
			// Now dump all failing tests
			foreach (ProcessData pd in failed) {
				// <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
				writer.WriteStartElement ("test-case");
				writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}", testsuiteName, pd.test));
				writer.WriteAttributeString ("executed", "True");
				writer.WriteAttributeString ("success", "False");
				writer.WriteAttributeString ("time", "0");
				writer.WriteAttributeString ("asserts", "1");
				writer.WriteStartElement ("failure");
				writer.WriteStartElement ("message");
				writer.WriteCData (FilterInvalidXmlChars (pd.stdout.ToString ()));
				writer.WriteEndElement ();
				writer.WriteStartElement ("stack-trace");
				writer.WriteCData (FilterInvalidXmlChars (pd.stderr.ToString ()));
				writer.WriteEndElement ();
				writer.WriteEndElement ();
				writer.WriteEndElement ();
			}
			// Then dump all timing out tests
			foreach (ProcessData pd in timedout) {
				// <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
				writer.WriteStartElement ("test-case");
				writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}_timedout", testsuiteName, pd.test));
				writer.WriteAttributeString ("executed", "True");
				writer.WriteAttributeString ("success", "False");
				writer.WriteAttributeString ("time", "0");
				writer.WriteAttributeString ("asserts", "1");
				writer.WriteStartElement ("failure");
				writer.WriteStartElement ("message");
				writer.WriteCData (FilterInvalidXmlChars (pd.stdout.ToString ()));
				writer.WriteEndElement ();
				writer.WriteStartElement ("stack-trace");
				writer.WriteCData (FilterInvalidXmlChars (pd.stderr.ToString ()));
				writer.WriteEndElement ();
				writer.WriteEndElement ();
				writer.WriteEndElement ();
			}
			//             </results>
			writer.WriteEndElement ();
			//           </test-suite>
			writer.WriteEndElement ();
			//         </results>
			writer.WriteEndElement ();
			//       </test-suite>
			writer.WriteEndElement ();
			//     </results>
			writer.WriteEndElement ();
			//   </test-suite>
			writer.WriteEndElement ();
			// </test-results>
			writer.WriteEndElement ();
			writer.WriteEndDocument ();

			string babysitterXmlList = Environment.GetEnvironmentVariable("MONO_BABYSITTER_NUNIT_XML_LIST_FILE");
			if (!String.IsNullOrEmpty(babysitterXmlList)) {
				try {
					string fullXmlPath = Path.GetFullPath(xmlPath);
					File.AppendAllText(babysitterXmlList, fullXmlPath + Environment.NewLine);
				} catch (Exception e) {
					Console.WriteLine("Attempted to record XML path to file {0} but failed.", babysitterXmlList);
				}
			}
		}

		if (verbose) {
			Console.WriteLine ();
			Console.WriteLine ("Time: {0}", test_time.ToString (TEST_TIME_FORMAT));
			Console.WriteLine ();
			Console.WriteLine ("{0,4} test(s) passed", npassed);
			Console.WriteLine ("{0,4} test(s) failed", nfailed);
			Console.WriteLine ("{0,4} test(s) timed out", ntimedout);
		} else {
			Console.WriteLine ();
			Console.WriteLine (String.Format ("{0} test(s) passed, {1} test(s) did not pass.", npassed, nfailed));
		}

		if (nfailed > 0) {
			Console.WriteLine ();
			Console.WriteLine ("Failed test(s):");
			foreach (ProcessData pd in failed) {
				Console.WriteLine ();
				Console.WriteLine (pd.test);
				DumpFile (pd.stdoutName, pd.stdout.ToString ());
				DumpFile (pd.stderrName, pd.stderr.ToString ());
			}
		}

		if (ntimedout > 0) {
			Console.WriteLine ();
			Console.WriteLine ("Timed out test(s):");
			foreach (ProcessData pd in timedout) {
				Console.WriteLine ();
				Console.WriteLine (pd.test);
				DumpFile (pd.stdoutName, pd.stdout.ToString ());
				DumpFile (pd.stderrName, pd.stderr.ToString ());
			}
		}

		return (ntimedout == 0 && nfailed == 0) ? 0 : 1;
	}
Esempio n. 52
0
        private void NetworkWrite(ProcessData Processor, SocketPurpose Purpose, Socket NetworkSocket, byte[] Data, int offset, IAsyncResult ar)
        {
            try
            {
                int length = NetworkSocket.EndSend(ar);

                if (length + offset < Data.Length)
                {
                    NetworkSocket.BeginSend(Data, length, Data.Length - (length + offset), SocketFlags.None,
                        delegate(IAsyncResult AsR) { NetworkWrite(Processor, Purpose, NetworkSocket, Data, length + offset, AsR); },
                        null);
                }
                else
                {
                    NetworkSocket.BeginReceive(networkBuf, 0, 1024, SocketFlags.None,
                            delegate(IAsyncResult AsR) { NetworkReceive(Purpose, NetworkSocket, AsR); },
                            null);
                }
            }
            catch (SocketException e)
            {
                OnSocketException(Purpose, NetworkSocket, e);
            }
            catch (ObjectDisposedException)
            {
                OnObjectDisposedException(Purpose, NetworkSocket);
            }
        }
Esempio n. 53
0
	public static int Main (String[] args) {
		// Defaults
		int concurrency = 1;
		int timeout = 2 * 60; // in seconds

		// FIXME: Add support for runtime arguments + env variables

		string disabled_tests = null;
		string runtime = "mono";
		var opt_sets = new List<string> ();

		// Process options
		int i = 0;
		while (i < args.Length) {
			if (args [i].StartsWith ("-")) {
				if (args [i] == "-j") {
					if (i + i >= args.Length) {
						Console.WriteLine ("Missing argument to -j command line option.");
						return 1;
					}
					if (args [i + 1] == "a")
						concurrency = Environment.ProcessorCount;
					else
						concurrency = Int32.Parse (args [i + 1]);
					i += 2;
				} else if (args [i] == "--timeout") {
					if (i + i >= args.Length) {
						Console.WriteLine ("Missing argument to --timeout command line option.");
						return 1;
					}
					timeout = Int32.Parse (args [i + 1]);
					i += 2;
				} else if (args [i] == "--disabled") {
					if (i + i >= args.Length) {
						Console.WriteLine ("Missing argument to --disabled command line option.");
						return 1;
					}
					disabled_tests = args [i + 1];
					i += 2;
				} else if (args [i] == "--runtime") {
					if (i + i >= args.Length) {
						Console.WriteLine ("Missing argument to --runtime command line option.");
						return 1;
					}
					runtime = args [i + 1];
					i += 2;
				} else if (args [i] == "--opt-sets") {
					if (i + i >= args.Length) {
						Console.WriteLine ("Missing argument to --opt-sets command line option.");
						return 1;
					}
					foreach (var s in args [i + 1].Split ())
						opt_sets.Add (s);
					i += 2;
				} else {
					Console.WriteLine ("Unknown command line option: '" + args [i] + "'.");
					return 1;
				}
			} else {
				break;
			}
		}

		var disabled = new Dictionary <string, string> ();

		if (disabled_tests != null) {
			foreach (string test in disabled_tests.Split ())
				disabled [test] = test;
		}

		// The remaining arguments are the tests
		var tests = new List<string> ();
		for (int j = i; j < args.Length; ++j)
			if (!disabled.ContainsKey (args [j]))
				tests.Add (args [j]);

		int npassed = 0;
		int nfailed = 0;

		var processes = new List<Process> ();
		var failed = new List<ProcessData> ();
		var process_data = new Dictionary<Process, ProcessData> ();

		object monitor = new object ();

		var terminated = new List<Process> ();

		if (concurrency != 1)
			Console.WriteLine ("Running tests: ");

		var test_info = new List<TestInfo> ();
		if (opt_sets.Count == 0) {
			foreach (string s in tests)
				test_info.Add (new TestInfo { test = s });
		} else {
			foreach (string opt in opt_sets) {
				foreach (string s in tests)
					test_info.Add (new TestInfo { test = s, opt_set = opt });
			}
		}		

		foreach (TestInfo ti in test_info) {
			lock (monitor) {
				while (processes.Count == concurrency) {
					/* Wait for one process to terminate */
					Monitor.Wait (monitor);
				}

				/* Cleaup terminated processes */
				foreach (Process dead in terminated) {
					if (process_data [dead].stdout != null)
						process_data [dead].stdout.Close ();
					if (process_data [dead].stderr != null)
						process_data [dead].stderr.Close ();
					// This is needed to avoid CreateProcess failed errors :(
					dead.Close ();
				}
				terminated.Clear ();
			}

			string test = ti.test;
			string opt_set = ti.opt_set;

			if (concurrency == 1)
				Console.Write ("Testing " + test + "... ");

			/* Spawn a new process */
			string process_args;
			if (opt_set == null)
				process_args = test;
			else
				process_args = "-O=" + opt_set + " " + test;
			ProcessStartInfo info = new ProcessStartInfo (runtime, process_args);
			info.UseShellExecute = false;
			info.RedirectStandardOutput = true;
			info.RedirectStandardError = true;
			Process p = new Process ();
			p.StartInfo = info;
			p.EnableRaisingEvents = true;

			ProcessData data = new ProcessData ();
			data.test = test;

			p.Exited += delegate (object sender, EventArgs e) {
				// Anon methods share some of their state, so we can't use
				// variables which change during the loop (test, p)
				Process dead = (Process)sender;

				lock (monitor) {
					if (dead.ExitCode == 0) {
						if (concurrency == 1)
							Console.WriteLine ("passed.");
						else
							Console.Write (".");
						npassed ++;
					} else {
						if (concurrency == 1)
							Console.WriteLine ("failed.");
						else
							Console.Write ("F");
						failed.Add (process_data [dead]);
						nfailed ++;
					}
					processes.Remove (dead);
					terminated.Add (dead);
					Monitor.Pulse (monitor);
				}
			};

			string log_prefix = "";
			if (opt_set != null)
				log_prefix = "." + opt_set.Replace ("-", "no").Replace (",", "_");

			data.stdoutFile = test + log_prefix + ".stdout";
			data.stdout = new StreamWriter (new FileStream (data.stdoutFile, FileMode.Create));

			data.stderrFile = test + log_prefix + ".stderr";
			data.stderr = new StreamWriter (new FileStream (data.stderrFile, FileMode.Create));

			p.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e) {
				Process p2 = (Process)sender;

				StreamWriter fs;

				lock (monitor) {
					fs = process_data [p2].stdout;

					if (String.IsNullOrEmpty (e.Data))
						process_data [p2].stdout = null;
				}

				if (String.IsNullOrEmpty (e.Data)) {
					fs.Close ();
				} else {
					fs.WriteLine (e.Data);
					fs.Flush ();
				}
			};

			p.ErrorDataReceived += delegate (object sender, DataReceivedEventArgs e) {
				Process p2 = (Process)sender;

				StreamWriter fs;

				lock (monitor) {
					fs = process_data [p2].stderr;

					if (String.IsNullOrEmpty (e.Data))
						process_data [p2].stderr = null;

				}

				if (String.IsNullOrEmpty (e.Data)) {
					fs.Close ();

					lock (monitor) {
						process_data [p2].stderr = null;
					}
				} else {
					fs.WriteLine (e.Data);
					fs.Flush ();
				}
			};

			lock (monitor) {
				processes.Add (p);
				process_data [p] = data;
			}
			p.Start ();

			p.BeginOutputReadLine ();
			p.BeginErrorReadLine ();
		}

		bool timed_out = false;

		/* Wait for all processes to terminate */
		while (true) {
			lock (monitor) {
				int nprocesses = processes.Count;

				if (nprocesses == 0)
					break;

				bool res = Monitor.Wait (monitor, 1000 * timeout);
				if (!res) {
					timed_out = true;
					break;
				}
			}
		}

		Console.WriteLine ();

		if (timed_out) {
			Console.WriteLine ("\nrunning tests timed out:\n");
			Console.WriteLine (npassed + nfailed);
			lock (monitor) {
				foreach (Process p in processes) {
					ProcessData pd = process_data [p];
					pd.CloseStreams ();
					Console.WriteLine (pd.test);
					p.Kill ();
					DumpFile (pd.stdoutFile);
					DumpFile (pd.stderrFile);
				}
			}
			return 1;
		}

		Console.WriteLine ("" + npassed + " test(s) passed. " + nfailed + " test(s) did not pass.");
		if (nfailed > 0) {
			Console.WriteLine ("\nFailed tests:\n");
			foreach (ProcessData pd in failed) {
				Console.WriteLine (pd.test);
				DumpFile (pd.stdoutFile);
				DumpFile (pd.stderrFile);
			}
			return 1;
		} else {
			return 0;
		}
	}
        protected bool _InitProcessor(Processor p, ref ProcessData data)
        {
            ValueInterface<float> iface = SceneObject.Components.GetInterface<ValueInterface<float>>("float", p.InterfaceName);
            if (iface != null)
            {
                float val = iface.Value;
                p.Init(SceneObject, ref val);
                iface.Value = val;
                data.Interface = iface;
                data.PreTick = val;
                data.PostTick = val;
                return true;
            }

            return false;
        }