Example #1
0
        public static void ApplyPatch(FpuSegment seg)
        {
            Process p=new Process();
            p.StartInfo.FileName="nasm.exe";
            p.StartInfo.Arguments="out.txt";
            p.StartInfo.UseShellExecute=false;
            p.StartInfo.CreateNoWindow=true;
            p.Start();
            p.WaitForExit();
            p.Close();
            FileInfo fi=new FileInfo("out");
            if(fi.Length==0) throw new OptimizationException("Patcher: Code generator produced uncompilable code");
            ArrayList code=new ArrayList();
            for(int i=0;i<seg.Pre.Length;i++) {
                code.AddRange(HexToString(seg.Pre[i].code));
            }
            code.AddRange(Program.ReadFileBytes("out"));
            for(int i=0;i<seg.Post.Length;i++) {
                code.AddRange(HexToString(seg.Post[i].code));
            }
            if(code.Count>seg.End-seg.Start) throw new OptimizationException("Patcher: Patch to big to fit into code");

            /*if(Program.TestPatches) {
                TestPatch(seg); //TESTPATCH CALL
            }*/
            if(Program.Benchmark) {
                Benchmark(seg); //BENCHMARK CALL!!!!!!!!!!!!!!!!!!!!!!!! <---------------- OVER HERE
            }
            byte[] Code=new byte[seg.End-seg.Start];
            code.CopyTo(Code);
            for(int i=code.Count;i<(seg.End-seg.Start);i++) {
                Code[i]=144;    //Fill the rest of the code up with nop's
            }
            long a=(seg.End-seg.Start)-code.Count;
            if(a>255) {
                throw new OptimizationException("Patcher: Patch end address out of range of a short jump");
            } else if(a>2) {
                Code[code.Count]=235;
                Code[code.Count+1]=(byte)(a-2);
            }
            if(Program.Restrict) {
                if(PatchCount<Program.FirstPatch||PatchCount>Program.LastPatch) {
                    PatchCount++;
                    throw new OptimizationException("Patcher: Patch restricted");
                }
                PatchCount++;
            }
            #if emitpatch
            FileStream fs2=File.Create("emittedpatch.patch",4096);
            BinaryWriter bw=new BinaryWriter(fs2);
            bw.Write(seg.Start);
            bw.Write(Code.Length);
            bw.Write(Code,0,Code.Length);
            bw.Close();
            #endif
            FileStream fs=File.Open("code",FileMode.Open);
            fs.Position=seg.Start;
            fs.Write(Code,0,Code.Length);
            fs.Close();
        }
Example #2
0
        /// <summary>
        /// Anche nelle sottodirectory
        /// </summary>
        /// <param name="path"></param>
        /// <param name="pattern"></param>
        /// <returns></returns>
        public static System.Collections.ArrayList GetFiles(string path, string pattern)
        {
            System.Collections.ArrayList list = new System.Collections.ArrayList();
            try
            {
                list.AddRange(System.IO.Directory.GetFiles(path, pattern));
            }
            catch { }

            string[] dirs = null;
            try
            {
                dirs = System.IO.Directory.GetDirectories(path);
            }
            catch { }

            if (dirs != null)
            {
                foreach (string dir in dirs)
                {
                    list.AddRange(GetFiles(dir, pattern));
                }
            }
            return list;
        }
        private void btnRandomize_Click(object sender, EventArgs e)
        {
            var random = new Random();
            var splitArray = new string[1];
            var list = new System.Collections.ArrayList();

            splitArray[0] = Environment.NewLine; // Used to split the list of owners in the textbox

            // Add contents of textbox to array
            list.AddRange(txtList.Text.Split(splitArray, StringSplitOptions.RemoveEmptyEntries));

            txtList.Clear();

            var length = list.Count;

            // Loop through list, randomly selecting an item, adding it to the output list,
            // then removing it from the list
            for (var x = 0; x < length; x++)
            {
                var index = random.Next(list.Count);

                txtList.Text +=  list[index] + Environment.NewLine;
                list.Remove(list[index].ToString());
            }

            // Add output to clipboard
            if (!String.IsNullOrEmpty(txtList.Text))
                Clipboard.SetText(txtList.Text);
        }
Example #4
0
 public static void CopyDirectory(string sourcedirectory, string targetdirectory, string logname, string[] extensionesexcluidas, bool iferrorfinish)
 {
     DirectoryInfo source = new DirectoryInfo(sourcedirectory);
     DirectoryInfo target = new DirectoryInfo(targetdirectory);
     System.Collections.ArrayList extensiones = new System.Collections.ArrayList();
     if (extensionesexcluidas != null)
     {
         extensiones.AddRange(extensionesexcluidas);
     }
     _CopyAll(source, target, logname, extensiones,iferrorfinish);
 }
Example #5
0
 public static byte[] String_To_Bytes(string[] S)
 {
     System.Collections.ArrayList BB = new System.Collections.ArrayList();
     foreach (string s in S)
     {
         // check for empty strings
         if (!(s.Equals("")))
             BB.AddRange(String_To_Bytes(s));
         BB.Add((byte) 10); // Adds the newline character at the end of each string.
     }
     return (byte[]) BB.ToArray(typeof (byte));
 }
Example #6
0
 public static byte[] Array_To_Bytes(System.Array Arr)
 {
     System.Collections.ArrayList BB = new System.Collections.ArrayList();
     foreach (var V in Arr)
     {
         string S = V.ToString();
         // check for empty strings
         if (!(S.Equals("")))
             BB.AddRange(String_To_Bytes(S));
         BB.Add((byte)10); // Adds the newline character at the end of each array item.
     }
     return (byte[]) BB.ToArray(typeof (byte));
 }
Example #7
0
 private static object Deserialize(object obj1)
 {
     if (obj1 == null)
     {
         return null;
     }
     if (obj1.GetType() == typeof(string))
     {
         string str = obj1.ToString();
         if ((((str.Length == 19) && (str[10] == 'T')) && (str[4] == '-')) && (str[13] == ':'))
         {
             obj1 = Convert.ToDateTime(obj1);
         }
         return obj1;
     }
     if (obj1 is Newtonsoft.Json.Linq.JObject)
     {
         Newtonsoft.Json.Linq.JObject obj2 = obj1 as Newtonsoft.Json.Linq.JObject;
         System.Collections.Hashtable hashtable = new System.Collections.Hashtable();
         foreach (System.Collections.Generic.KeyValuePair<string, Newtonsoft.Json.Linq.JToken> pair in obj2)
         {
             hashtable[pair.Key] = Deserialize(pair.Value);
         }
         obj1 = hashtable;
         return obj1;
     }
     if (obj1 is System.Collections.IList)
     {
         System.Collections.ArrayList list = new System.Collections.ArrayList();
         list.AddRange(obj1 as System.Collections.IList);
         int num = 0;
         int count = list.Count;
         while (num < count)
         {
             list[num] = Deserialize(list[num]);
             num++;
         }
         obj1 = list;
         return obj1;
     }
     if (typeof(Newtonsoft.Json.Linq.JValue) == obj1.GetType())
     {
         Newtonsoft.Json.Linq.JValue value2 = (Newtonsoft.Json.Linq.JValue)obj1;
         obj1 = Deserialize(value2.Value);
     }
     return obj1;
 }
        public override ICSSoft.STORMNET.UI.Runner[] GetRunners()
        {
            System.Collections.ArrayList arr = new System.Collections.ArrayList();
            arr.AddRange(base.GetRunners());
            // *** Start programmer edit section *** (SimpleTestAuditProject GetRunners())

            // *** End programmer edit section *** (SimpleTestAuditProject GetRunners())
            arr.Add(new ICSSoft.STORMNET.UI.ContRunner(typeof(SimpleTestAuditProject.MainObjL), "SimpleTestAuditProject", "Main obj", ""));
            arr.Add(new ICSSoft.STORMNET.UI.ContRunner(typeof(SimpleTestAuditProject.MasterObjL), "SimpleTestAuditProject", "Master obj", ""));
            arr.Add(new ICSSoft.STORMNET.UI.ContRunner(typeof(SimpleTestAuditProject.DetailMasterL), "SimpleTestAuditProject", "DetailMasterL", ""));
            arr.Add(new ICSSoft.STORMNET.Windows.Forms.FormRunner(typeof(SimpleTestAuditProject.WinformShowAuditFormU), "SimpleTestAuditProject", "ShowAuditFormU", ""));
            // *** Start programmer edit section *** (SimpleTestAuditProject GetRunners() End)

            // *** End programmer edit section *** (SimpleTestAuditProject GetRunners() End)
            // *** Start programmer edit section *** (SimpleTestAuditProject Audit)
            arr.Add(new ICSSoft.STORMNET.UI.ContRunner(typeof(ICSSoft.STORMNET.Business.Audit.WinForms.AuditEntityL), "Аудит", "Аудит операций", ""));
            arr.Add(new ICSSoft.STORMNET.UI.ContRunner(typeof(ICSSoft.STORMNET.Business.Audit.WinForms.AuditEntityByObjectsL), "Аудит", "Аудит объектов", ""));
            // *** End programmer edit section *** (SimpleTestAuditProject Audit)
            ICSSoft.STORMNET.UI.Runner[] retArray = new ICSSoft.STORMNET.UI.Runner[arr.Count];
            arr.CopyTo(retArray);
            return(retArray);
        }
        internal virtual void  Update(BufferedDeletes in_Renamed)
        {
            numTerms  += in_Renamed.numTerms;
            bytesUsed += in_Renamed.bytesUsed;

            System.Collections.ArrayList keys   = new System.Collections.ArrayList(in_Renamed.terms.Keys);
            System.Collections.ArrayList values = new System.Collections.ArrayList(in_Renamed.terms.Values);
            for (int i = 0; i < keys.Count; i++)
            {
                terms[keys[i]] = values[i];
            }

            keys   = new System.Collections.ArrayList(in_Renamed.queries.Keys);
            values = new System.Collections.ArrayList(in_Renamed.queries.Values);
            for (int i = 0; i < keys.Count; i++)
            {
                queries[keys[i]] = values[i];
            }

            docIDs.AddRange(in_Renamed.docIDs);
            in_Renamed.Clear();
        }
Example #10
0
        /// <summary>
        /// Gets a list of the objects in the current nodes collection and its children nodes.
        /// </summary>
        /// <returns>An arraylist of objects.</returns>
        public System.Collections.ArrayList GetList()
        {
            if (this.Count == 0)
            {
                return(new System.Collections.ArrayList());
            }
            System.Collections.ArrayList newlist   = new System.Collections.ArrayList();
            System.Collections.ArrayList childlist = null;

            for (int i = 0; i < this.Count; i++)
            {
                newlist.Add(this[i].Value);
                childlist = this[i].Nodes.GetList();
                if (childlist.Count > 0)
                {
                    newlist.AddRange(childlist);
                }
                childlist = null;
            }

            return(newlist);
        }
Example #11
0
        }                                                                                                           // 1.0.012

        #endregion

        #region Private Methods
        // private void InsertRange(bool replace, int index, params System.Windows.Forms.TabPage[] theTabPages)
        //
        /// <summary>
        /// Inserts the range.
        /// </summary>
        /// <param name="replace">if set to <c>true</c> [replace].</param>
        /// <param name="index">The index.</param>
        /// <param name="theTabPages">The tab pages.</param>
        private void InsertRange(bool replace, int index, params System.Windows.Forms.TabPage[] theTabPages) // 1.0.010
        {                                                                                                    // 1.0.004
            #region Put existing [base.TabPages] into an ArrayList sequenced in the present order
            System.Collections.ArrayList alTabPages = new System.Collections.ArrayList(this.Count);          // 1.0.003
            for (int idx = 0; idx < this.Count; idx++)                                                       // 1.0.003
            {                                                                                                // 1.0.003
                alTabPages.Add(base[idx]);                                                                   // 1.0.010
            }                                                                                                // 1.0.003
            #endregion
            #region Add/Insert [theTabPages] at appropriate location in the ArrayList
            if (replace &&                                                                              // Replace TabPage at [index] with [theTabPages]?	// 1.0.004
                ((index >= 0) && (index < alTabPages.Count)))                                           // 1.0.004
            {                                                                                           // 1.0.004
                alTabPages.RemoveAt(index);                                                             // 1.0.004
            }                                                                                           // 1.0.004
            if ((index >= 0) && (index < alTabPages.Count))                                             // 1.0.004
            {                                                                                           // 1.0.004
                alTabPages.InsertRange(index, theTabPages);                                             // 1.0.004
            }                                                                                           // 1.0.004
            else                                                                                        // 1.0.004
            {                                                                                           // 1.0.004
                alTabPages.AddRange(theTabPages);                                                       // 1.0.004
            }                                                                                           // 1.0.004
            #endregion
            #region Rebuild the [base.TabPages] Collection
            _owner.SuspendLayout();                                                                                             // 1.0.003
            base.Clear();                                                                                                       // 1.0.003
            for (int idxNew = 0; idxNew < alTabPages.Count; idxNew++)                                                           // 1.0.003
            {                                                                                                                   // 1.0.003
                System.Windows.Forms.TabPage aTabPage = (System.Windows.Forms.TabPage)alTabPages[idxNew];                       // 1.0.010
                aTabPage.TabIndex = idxNew;                                                                                     // 1.0.003
                base.Add(aTabPage);                                                                                             // 1.0.003
            }                                                                                                                   // 1.0.003
            alTabPages.Clear();                                                                                                 // 1.0.003
            _owner.ResumeLayout(false);                                                                                         // 1.0.003
            _owner.Invalidate();                                                                                                // 1.0.003
            #endregion
        }                                                                                                                       // 1.0.004
Example #12
0
            public void StatusProgressAllowed_AssignedToCaseOfficer_ByCustomer()
            {
                ApplicationProgression.GetPermitInfo();

                ApplicationProgression.PI.PermitStatus = new BO.ReferenceData.BOPermitStatus((int)BOPermitInfo.PermitStatusTypes.ProgressAllowed);
                ApplicationProgression.PI.AssignedTo   = new BO.ReferenceData.BOStatusAssignedToGroup((int)Common.AssignedToList.CaseOfficer);

                ApplicationProgression.PI.Save(_ssoCaseOfficerUserId);
                Console.WriteLine("Saved PI");

                uk.gov.defra.Phoenix.BO.Application.BOPermitInfo.StatusList[] ReturnedStatusList = ApplicationProgression.PI.GetStatusList(true,
                                                                                                                                           _ssoCustomerUserId);


                System.Collections.ArrayList idList = new System.Collections.ArrayList();
                idList.AddRange(new int[] { (int)BOPermitInfo.PermitStatusTypes.CancelPending });


                //imports                (int)BOPermitInfo.PermitStatusTypes.IssuedDraft

                uk.gov.defra.Phoenix.BO.Application.BOPermitInfo.StatusList[] ListToCheckAgainst = GetStatusList(idList);
                Assert.AreSame((BOPermitInfo.StatusList[])ListToCheckAgainst, (BOPermitInfo.StatusList[])ReturnedStatusList);
            }
        /// <summary>
        /// Transform the string into integers representing the Code128 codes
        /// necessary to represent it
        /// </summary>
        /// <param name="AsciiData">String to be encoded</param>
        /// <returns>Code128 representation</returns>
        private int[] StringToCode128(string AsciiData)
        {
            // turn the string into ascii byte data
            byte[] asciiBytes = Encoding.ASCII.GetBytes(AsciiData);

            // decide which codeset to start with
            Code128Code.CodeSetAllowed csa1 = asciiBytes.Length > 0 ? Code128Code.CodesetAllowedForChar(asciiBytes[0]) : Code128Code.CodeSetAllowed.CodeAorB;
            Code128Code.CodeSetAllowed csa2 = asciiBytes.Length > 0 ? Code128Code.CodesetAllowedForChar(asciiBytes[1]) : Code128Code.CodeSetAllowed.CodeAorB;
            CodeSet currcs = GetBestStartSet(csa1, csa2);

            // set up the beginning of the barcode
            System.Collections.ArrayList codes = new System.Collections.ArrayList(asciiBytes.Length + 3); // assume no codeset changes, account for start, checksum, and stop
            codes.Add(Code128Code.StartCodeForCodeSet(currcs));

            // add the codes for each character in the string
            for (int i = 0; i < asciiBytes.Length; i++)
            {
                int thischar = asciiBytes[i];
                int nextchar = asciiBytes.Length > (i + 1) ? asciiBytes[i + 1] : -1;

                codes.AddRange(Code128Code.CodesForChar(thischar, nextchar, ref currcs));
            }

            // calculate the check digit
            int checksum = (int)(codes[0]);

            for (int i = 1; i < codes.Count; i++)
            {
                checksum += i * (int)(codes[i]);
            }
            codes.Add(checksum % 103);

            codes.Add(Code128Code.StopCode());

            int[] result = codes.ToArray(typeof(int)) as int[];
            return(result);
        }
 public static System.Collections.ArrayList QueryUser(string clientID, string userID, string url = "")
 {
     string jsonString;
     if (Operators.CompareString(url, "", false) == 0)
     {
         jsonString = JSONHelper.Get(string.Format("https://api.instagram.com/v1/users/{0}/media/recent/?client_id={1}", userID, clientID));
     }
     else
     {
         jsonString = JSONHelper.Get(string.Format(url, new object[0]));
     }
     System.Collections.Generic.Dictionary<string, object> dictionary = JSONHelper.DeserializeToDictionary(jsonString);
     System.Collections.ArrayList arrayList = (System.Collections.ArrayList)dictionary["data"];
     if (dictionary.ContainsKey("pagination"))
     {
         System.Collections.Generic.Dictionary<string, object> dictionary2 = (System.Collections.Generic.Dictionary<string, object>)dictionary["pagination"];
         if (dictionary2.ContainsKey("next_url"))
         {
             string url2 = Conversions.ToString(dictionary2["next_url"]);
             arrayList.AddRange(JSONHelper.Instagram.User.QueryUser("", "", url2));
         }
     }
     return arrayList;
 }
Example #15
0
 public System.Windows.Forms.ListViewItem[] LVIWordContent()
 {
     //===== ここから
     //まず情報を取り出す
     System.Collections.ArrayList array = new System.Collections.ArrayList();
     System.Xml.XmlElement        child;
     for (int i = 0; i < this.elem.ChildNodes.Count; i++)
     {
         if (this.elem.ChildNodes[i].NodeType != System.Xml.XmlNodeType.Element)
         {
             continue;
         }
         child = (System.Xml.XmlElement) this.elem.ChildNodes[i];
         if (child.Name.ToLower() != "word")
         {
             continue;
         }
         array.AddRange(((Hanyu.Word)child).GetContents());
     }
     //一つずつ ListViewItem に変換していく
     System.Collections.ArrayList      r = new System.Collections.ArrayList();
     System.Windows.Forms.ListViewItem item;
     Hanyu.ElemWordContent             content;
     for (int i = 0; i < array.Count; i++)
     {
         content = (Hanyu.ElemWordContent)array[i];
         item    = new System.Windows.Forms.ListViewItem(new string[] { content.ParentElemWord.Name, content.ListViewText });
         item.UseItemStyleForSubItems = false;
         item.SubItems[0].Font        = new System.Drawing.Font("SimSun", 10);
         item.Tag = content;
         //TODO:content.Part に応じて item に imageIndex を付ける
         r.Add(item);
     }
     //===== ここまで
     return((System.Windows.Forms.ListViewItem[])r.ToArray(typeof(System.Windows.Forms.ListViewItem)));
 }
Example #16
0
        public ActionResult GetSuggestUsers(int roleId, int count, string keyword)
        {
            ActionResult ActionResult = new ActionResult();

            try
            {
                if (string.IsNullOrEmpty(keyword))
                {
                    return(ActionResult.Data = new List <UserRoleDto>());
                }

                string displayMatch  = keyword + "%";
                int    totalRecords  = 0;
                int    totalRecords2 = 0;
                bool   isAdmin       = UserManager.IsAdmin(PortalSettings);

                System.Collections.ArrayList matchedUsers = UserController.GetUsersByDisplayName(PortalSettings.PortalId, displayMatch, 0, count,
                                                                                                 ref totalRecords, false, false);
                matchedUsers.AddRange(UserController.GetUsersByUserName(PortalSettings.PortalId, displayMatch, 0, count, ref totalRecords2, false, false));
                IEnumerable <UserRoleDto> finalUsers = matchedUsers
                                                       .Cast <UserInfo>()
                                                       .Where(x => isAdmin || !x.Roles.Contains(PortalSettings.AdministratorRoleName))
                                                       .Select(u => new UserRoleDto()
                {
                    UserId      = u.UserID,
                    DisplayName = $"{u.DisplayName} ({u.Username})"
                });

                ActionResult.Data = finalUsers.ToList().GroupBy(x => x.UserId).Select(group => group.First());
            }
            catch (Exception ex)
            {
                ActionResult.AddError("HttpStatusCode.InternalServerError" + HttpStatusCode.InternalServerError, ex.Message);
            }
            return(ActionResult);
        }
Example #17
0
        private void GetXMLButton_Click(object sender, EventArgs e)
        {
            System.Collections.ArrayList regs = new System.Collections.ArrayList();
            regs.AddRange(RegCodesEDT.Items);

            if (FormsList.SelectedIndex == 0)
            {
                //DataSet ds = ws.Data101FormEx(regs.ToArray(), System.Convert.ToInt32(symbolEdt.Text), System.Convert.ToDateTime(dformEDT.Text), System.Convert.ToDateTime(dtoEDT.Text));
                //if (ds != null)
                //{
                //    dataGridView1.DataSource = ds.Tables[0];
                //          string shema = ds.GetXmlSchema();
                //          System.IO.File.WriteAllText("Data101FormEx.xsd", shema,  Encoding.UTF8);
                //}

                var ds = ws.Data101FullExXML(regs.ToArray(), System.Convert.ToInt32(symbolEdt.Text), System.Convert.ToDateTime(dformEDT.Text), System.Convert.ToDateTime(dtoEDT.Text));
                MessageBox.Show(ds.OuterXml);
            }
            if (FormsList.SelectedIndex == 1)
            {
                var ds = ws.Data102FormExXML(regs.ToArray(), System.Convert.ToInt32(symbolEdt.Text), System.Convert.ToDateTime(dformEDT.Text), System.Convert.ToDateTime(dtoEDT.Text));
                MessageBox.Show(ds.OuterXml);
            }
        }
Example #18
0
        public override void  down(Event evt)
        {
            Message msg;
            long    time_to_wait, start_time;

            switch (evt.Type)
            {
            case Event.FIND_INITIAL_MBRS:                      // sent by GMS layer, pass up a GET_MBRS_OK event

                //We pass this event down to tcp so that it can take some measures.
                passDown(evt);

                initial_members.Clear();
                msg = new Message(null, null, null);

                msg.putHeader(HeaderType.TCPPING, new PingHeader(PingHeader.GET_MBRS_REQ, (System.Object)local_addr, group_addr));

                // if intitial nodes have been specified and static is true, then only those
                // members will form the cluster, otherwise, nodes having the same IP Multicast and port
                // will form the cluster dyanamically.

                mbrDiscoveryInProcess = true;
                lock (members.SyncRoot)
                {
                    if (initial_hosts != null)
                    {
                        for (System.Collections.IEnumerator it = initial_hosts.GetEnumerator(); it.MoveNext();)
                        {
                            Address addr = (Address)it.Current;
                            msg.Dest = addr;
                            if (Stack.NCacheLog.IsInfoEnabled)
                            {
                                Stack.NCacheLog.Info("[FIND_INITIAL_MBRS] sending PING request to " + msg.Dest);
                            }
                            passDown(new Event(Event.MSG_URGENT, msg.copy(), Priority.Critical));
                        }
                    }
                }

                // 2. Wait 'timeout' ms or until 'num_initial_members' have been retrieved

                if (Stack.NCacheLog.IsInfoEnabled)
                {
                    Stack.NCacheLog.Info("TcpPing.down()", "[FIND_INITIAL_MBRS] waiting for results...............");
                }
                lock (initial_members.SyncRoot)
                {
                    start_time   = (System.DateTime.Now.Ticks - 621355968000000000) / 10000;
                    time_to_wait = timeout;

                    while (initial_members.Count < num_initial_members && time_to_wait > 0)
                    {
                        try
                        {
                            if (Stack.NCacheLog.IsInfoEnabled)
                            {
                                Stack.NCacheLog.Info("TcpPing.down()", "initial_members Count: " + initial_members.Count + "initialHosts Count: " + num_initial_members);
                            }
                            if (Stack.NCacheLog.IsInfoEnabled)
                            {
                                Stack.NCacheLog.Info("TcpPing.down()", "Time to wait for next response: " + time_to_wait);
                            }
                            ///Big_clusterd: initial members will be pulsed in case connection is not available.
                            ///so here we dont have to wait till each member is timed out.
                            ///this significantly improves time for initial member discovery.
                            bool timeExpire = System.Threading.Monitor.Wait(initial_members.SyncRoot, TimeSpan.FromMilliseconds(time_to_wait));
                        }
                        catch (System.Exception e)
                        {
                            Stack.NCacheLog.Error("TCPPing.down(FIND_INITIAL_MBRS)", e.ToString());
                        }
                        time_to_wait = timeout - ((System.DateTime.Now.Ticks - 621355968000000000) / 10000 - start_time);
                    }
                    mbrDiscoveryInProcess = false;
                }
                if (Stack.NCacheLog.IsInfoEnabled)
                {
                    Stack.NCacheLog.Info("TcpPing.down()", "[FIND_INITIAL_MBRS] initial members are " + Global.CollectionToString(initial_members));
                }
                if (Stack.NCacheLog.IsInfoEnabled)
                {
                    Stack.NCacheLog.Info("TcpPing.down()", "[FIND_INITIAL_MBRS] initial members count " + initial_members.Count);
                }

                //remove those which are not functional due to twoPhaseConnect
                for (int i = initial_members.Count - 1; i >= 0; i--)
                {
                    PingRsp rsp = initial_members[i] as PingRsp;
                    if (!rsp.IsStarted)
                    {
                        initial_members.RemoveAt(i);
                    }
                }

                // 3. Send response
                passUp(new Event(Event.FIND_INITIAL_MBRS_OK, initial_members));
                break;


            case Event.TMP_VIEW:
            case Event.VIEW_CHANGE:
                System.Collections.ArrayList tmp;
                if ((tmp = ((View)evt.Arg).Members) != null)
                {
                    lock (members.SyncRoot)
                    {
                        members.Clear();
                        members.AddRange(tmp);
                    }
                }
                passDown(evt);
                break;

            /****************************After removal of NackAck *********************************/
            //TCPPING emulates a GET_DIGEST call, which is required by GMS. This is needed
            //since we have now removed NAKACK from the stack!
            case Event.GET_DIGEST:
                pbcast.Digest digest = new pbcast.Digest(members.Count);
                for (int i = 0; i < members.Count; i++)
                {
                    Address sender = (Address)members[i];
                    digest.add(sender, 0, 0);
                }
                passUp(new Event(Event.GET_DIGEST_OK, digest));
                return;

            case Event.SET_DIGEST:
                // Not needed! Just here to let you know that it is needed by GMS!
                return;

            /********************************************************************************/

            case Event.BECOME_SERVER:                      // called after client has joined and is fully working group member
                if (Stack.NCacheLog.IsInfoEnabled)
                {
                    Stack.NCacheLog.Info("TcpPing.down()", "received BECOME_SERVER event");
                }
                passDown(evt);
                is_server = true;
                break;


            case Event.CONNECT:
                object[] addrs = ((object[])evt.Arg);
                group_addr    = (string)addrs[0];
                subGroup_addr = (string)addrs[1];

                twoPhaseConnect = (bool)addrs[3];
                if (twoPhaseConnect)
                {
                    timeout = 1000;
                }
                passDown(evt);
                break;


            case Event.DISCONNECT:
                passDown(evt);
                break;

            case Event.HAS_STARTED:
                hasStarted = true;
                passDown(evt);
                break;

            default:
                passDown(evt);                         // Pass on to the layer below us
                break;
            }
        }
 public static System.Collections.IList getAllChemObjects(ISetOfReactions set_Renamed)
 {
     System.Collections.ArrayList list = new System.Collections.ArrayList();
     IReaction[] reactions = set_Renamed.Reactions;
     for (int i = 0; i < reactions.Length; i++)
     {
         IReaction reaction = reactions[i];
         list.AddRange(ReactionManipulator.getAllChemObjects(reaction));
     }
     return list;
 }
        public void Update(GameTime gameTime)
        {
            if (es.EditMode)
            {
                if (es.EditType == EditorType.EntityMode)
                {
                    if (Mouse.GetState().LeftButton == ButtonState.Pressed)
                    {
                        if (draggedEntity != null)
                        {
                            draggedEntity.getAs<Position>().EntityPosition = RenderingSystem.camera.RealCoordsFromScreen(Mouse.GetState().X, Mouse.GetState().Y) - MouseOffset;
                            draggedEntity.getAs<Position>().EntityPosition -= new Vector2(draggedEntity.getAs<Position>().EntityPosition.X % (int)es.GridType, draggedEntity.getAs<Position>().EntityPosition.Y % (int)es.GridType);

                            //draggedEntity.getAs<Position>().EntityPosition = RenderingSystem.camera.RealCoordsFromScreen(Mouse.GetState().X, Mouse.GetState().Y) - MouseOffset;
                        }
                        else
                        {
                            draggedEntity = TestForTargetedDrawable(Mouse.GetState().X, Mouse.GetState().Y);
                            if (draggedEntity != null)
                            {
                                MouseOffset = RenderingSystem.camera.RealCoordsFromScreen(Mouse.GetState().X, Mouse.GetState().Y) - draggedEntity.getAs<Position>().EntityPosition;
                            }
                        }

                        selectedEntity = TestForTargetedDrawable(Mouse.GetState().X, Mouse.GetState().Y);
                    }
                    else
                    {
                        draggedEntity = null;
                    }
                }
                else if (es.EditType == EditorType.WallMode)
                {
                    if (Keyboard.GetState().IsKeyDown(Keys.Add))
                    {
                        System.Threading.Thread.Sleep(100);

                        if (selectedEntity == null)
                        {
                            selectedEntity = new Entity(es.CreateEntityID());
                        }

                        Wall entWall = selectedEntity.getAs<Wall>();

                        if (entWall == null)
                        {
                            entWall = new Wall();
                            es.RegisterComponent(selectedEntity, entWall);
                        }

                        System.Collections.ArrayList wallPoints = new System.Collections.ArrayList();
                        if (entWall.WallPoints != null)
                        {
                            wallPoints.AddRange(entWall.WallPoints);
                        }

                        if (wallPoints.Count == 0)
                        {
                            wallPoints.Add(new Vector2(0, 0));
                        }
                        Vector2 lastPoint = (Vector2)wallPoints[wallPoints.Count - 1];
                        wallPoints.Add(new Vector2(lastPoint.X + 30, lastPoint.Y + 30));

                        entWall.WallPoints = (Vector2[])wallPoints.ToArray(typeof(Vector2));
                    }

                    if (Keyboard.GetState().IsKeyDown(Keys.Subtract))
                    {
                        if (selectedEntity != null)
                        {
                            Wall entWall = selectedEntity.getAs<Wall>();

                            if (entWall != null)
                            {
                                if (entWall.WallPoints != null)
                                {
                                    System.Collections.ArrayList wallPoints = new System.Collections.ArrayList();
                                    wallPoints.AddRange(entWall.WallPoints);

                                    for (int i = 0; i < wallPoints.Count; i++)
                                    {
                                        if (selectedVertex == i)
                                        {
                                            wallPoints.RemoveAt(i);
                                            break;
                                        }
                                    }

                                    entWall.WallPoints = (Vector2[])wallPoints.ToArray(typeof(Vector2));
                                }
                            }
                        }
                    }

                    if (Mouse.GetState().LeftButton == ButtonState.Pressed)
                    {
                        if (selectedEntity != null)
                        {
                            Wall entWall = selectedEntity.getAs<Wall>();
                            if (entWall != null)
                            {
                                if (draggedVertex != -1)
                                {
                                    entWall.WallPoints[draggedVertex] = RenderingSystem.camera.RealCoordsFromScreen(Mouse.GetState().X, Mouse.GetState().Y) - selectedEntity.getAs<Position>().EntityPosition;
                                }
                                else
                                {
                                    for (int i = 0; i < entWall.WallPoints.Length; i++)// (Vector2 wallPoint in entWall.WallPoints)
                                    {
                                        Vector2 rectPos = RenderingSystem.camera.ScreenCoordsFromWorldPosition(entWall.WallPoints[i] + selectedEntity.getAs<Position>().EntityPosition);
                                        Rectangle entRect = new Rectangle((int)(rectPos.X - 15), (int)(rectPos.Y - 15), 30, 30);

                                        if (entRect.Contains(Mouse.GetState().X, Mouse.GetState().Y))
                                        {
                                            draggedVertex = i;
                                        }
                                    }
                                }

                                for (int i = 0; i < entWall.WallPoints.Length; i++)// (Vector2 wallPoint in entWall.WallPoints)
                                {
                                    Vector2 rectPos = RenderingSystem.camera.ScreenCoordsFromWorldPosition(entWall.WallPoints[i] + selectedEntity.getAs<Position>().EntityPosition);
                                    Rectangle entRect = new Rectangle((int)(rectPos.X - 15), (int)(rectPos.Y - 15), 30, 30);

                                    if (entRect.Contains(Mouse.GetState().X, Mouse.GetState().Y))
                                    {
                                        selectedVertex = i;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        draggedVertex = -1;
                    }
                }
            }
        }
        private bool LoadParametersTable()
        {
            bool parametersExist=false;

            // open report
            if(_report.State==Report.StateEnum.Closed)
                _report.Open();

            System.Collections.ArrayList list=new System.Collections.ArrayList();

            foreach(Hierarchy hier in _report.Schema.Hierarchies)
                list.AddRange(hier.GetPromptCalcMembers());

            foreach(CalculatedMember cmem in list)
            {
                parametersExist=true;
                AddParameterInput(cmem);
            }

            return parametersExist;
        }
Example #22
0
 /// <summary> Convert the elements in the Collection to an ArrayList </summary>
 public static System.Collections.ArrayList GetElements(System.Xml.Schema.XmlSchemaObjectCollection seqItems, System.Xml.Schema.XmlSchemaObjectCollection schemaItems)
 {
     System.Collections.ArrayList elements = new System.Collections.ArrayList();
     foreach(System.Xml.Schema.XmlSchemaObject obj in seqItems)
     {
         if(obj is System.Xml.Schema.XmlSchemaElement)
                    elements.Add(obj);
         else if(obj is System.Xml.Schema.XmlSchemaChoice)
         {
             System.Xml.Schema.XmlSchemaChoice choice = obj as System.Xml.Schema.XmlSchemaChoice;
             // Add each element of the choice
             foreach(System.Xml.Schema.XmlSchemaObject item in choice.Items)
                 if(item is System.Xml.Schema.XmlSchemaElement)
                     elements.Add(item);
                 else if(item is System.Xml.Schema.XmlSchemaGroupRef)
                 {
                     // Find the Group
                     string groupName = (obj as System.Xml.Schema.XmlSchemaGroupRef).RefName.Name;
                     System.Xml.Schema.XmlSchemaGroup group = null;
                     foreach(System.Xml.Schema.XmlSchemaObject schemaItem in schemaItems)
                         if(schemaItem is System.Xml.Schema.XmlSchemaGroup && groupName==(schemaItem as System.Xml.Schema.XmlSchemaGroup).Name)
                         {
                             group = schemaItem as System.Xml.Schema.XmlSchemaGroup; // Found
                             break;
                         }
                     if(group==null) // Not found
                         throw new System.Exception("Unknown xs:group " + groupName + string.Format(", nh-mapping.xsd({0})", obj.LineNumber));
                     elements.AddRange( GetElements(group.Particle.Items, schemaItems) );
                 }
                 else if(item is System.Xml.Schema.XmlSchemaSequence)
                 {
                     System.Xml.Schema.XmlSchemaSequence subSeq = item as System.Xml.Schema.XmlSchemaSequence;
                     elements.AddRange( GetElements(subSeq.Items, schemaItems) );
                 }
                 else
                     log.Warn("Unknown Object: " + item.ToString() + string.Format(", nh-mapping.xsd({0})", item.LineNumber));
         }
         else if(obj is System.Xml.Schema.XmlSchemaGroupRef)
         {
             // Find the Group
             string groupName = (obj as System.Xml.Schema.XmlSchemaGroupRef).RefName.Name;
             System.Xml.Schema.XmlSchemaGroup group = null;
             foreach(System.Xml.Schema.XmlSchemaObject schemaItem in schemaItems)
                 if(schemaItem is System.Xml.Schema.XmlSchemaGroup && groupName==(schemaItem as System.Xml.Schema.XmlSchemaGroup).Name)
                 {
                     group = schemaItem as System.Xml.Schema.XmlSchemaGroup; // Found
                     break;
                 }
             if(group==null) // Not found
                 throw new System.Exception("Unknown xs:group " + groupName + string.Format(", nh-mapping.xsd({0})", obj.LineNumber));
             elements.AddRange( GetElements(group.Particle.Items, schemaItems) );
         }
         else if(obj is System.Xml.Schema.XmlSchemaSequence)
         {
             System.Xml.Schema.XmlSchemaSequence subSeq = obj as System.Xml.Schema.XmlSchemaSequence;
             elements.AddRange( GetElements(subSeq.Items, schemaItems) );
         }
         else
             log.Warn("Unknown Object: " + obj.ToString() + string.Format(", nh-mapping.xsd({0})", obj.LineNumber));
     }
     return elements;
 }
Example #23
0
        /// <summary>
        /// Computes the momentum and confidence limits using positions and slopes provided.
        /// </summary>
        /// <param name="data">the position and slopes of the track (even Z-unordered). The <c>Field</c> member is used to define the plate.</param>
        /// <returns>the momentum and confidence limits.</returns>
        public MomentumResult ProcessData(SySal.Tracking.MIPEmulsionTrackInfo[] data)
        {
            int            i;
            MomentumResult result = new MomentumResult();

            System.Collections.ArrayList tr = new System.Collections.ArrayList();
            tr.AddRange(data);
            tr.Sort(new DataSorter());

            int nseg = tr.Count;
            int npl  = (int)(((SySal.Tracking.MIPEmulsionTrackInfo)tr[tr.Count - 1]).Field - ((SySal.Tracking.MIPEmulsionTrackInfo)tr[0]).Field) + 1;

            if (nseg < 2)
            {
                throw new Exception("PMSang - Warning! nseg < 2 (" + nseg + ")- impossible to estimate momentum!");
            }
            if (npl < nseg)
            {
                throw new Exception("PMSang - Warning! npl < nseg (" + npl + ", " + nseg + ")");
            }

            int plmax = (int)((SySal.Tracking.MIPEmulsionTrackInfo)tr[tr.Count - 1]).Field + 1;

            if (plmax < 1 || plmax > 1000)
            {
                throw new Exception("PMSang - Warning! plmax = " + plmax + " - correct the segments PID's!");
            }

            float xmean, ymean, zmean, txmean, tymean, wmean;
            float xmean0, ymean0, zmean0, txmean0, tymean0, wmean0;

            FitTrackLine(tr, out xmean0, out ymean0, out zmean0, out txmean0, out tymean0, out wmean0);
            float tmean = (float)Math.Sqrt(txmean0 * txmean0 + tymean0 * tymean0);

            SySal.Tracking.MIPEmulsionTrackInfo aas;
            float sigmax = 0, sigmay = 0;

            for (i = 0; i < tr.Count; i++)
            {
                aas     = (SySal.Tracking.MIPEmulsionTrackInfo)tr[i];
                sigmax += (float)((txmean0 - aas.Slope.X) * (txmean0 - aas.Slope.X));
                sigmay += (float)((tymean0 - aas.Slope.Y) * (tymean0 - aas.Slope.Y));
            }
            sigmax = (float)(Math.Sqrt(sigmax / tr.Count));
            sigmay = (float)(Math.Sqrt(sigmay / tr.Count));
            for (i = 0; i < tr.Count; i++)
            {
                aas = (SySal.Tracking.MIPEmulsionTrackInfo)tr[i];
                if (Math.Abs(aas.Slope.X - txmean0) > 3 * sigmax || Math.Abs(aas.Slope.Y - tymean0) > 3 * sigmay)
                {
                    aas.Slope.X = 0; aas.Slope.Y = 0;
                }
            }

            FitTrackLine(tr, out xmean0, out ymean0, out zmean0, out txmean0, out tymean0, out wmean0);

            float PHI = (float)Math.Atan2(txmean0, tymean0);

            for (i = 0; i < tr.Count; i++)
            {
                aas = (SySal.Tracking.MIPEmulsionTrackInfo)tr[i];
                float slx = (float)(aas.Slope.Y * Math.Cos(-PHI) - aas.Slope.X * Math.Sin(-PHI));
                float sly = (float)(aas.Slope.X * Math.Cos(-PHI) + aas.Slope.Y * Math.Sin(-PHI));
                aas.Slope.X = slx;
                aas.Slope.Y = sly;
            }

            FitTrackLine(tr, out xmean, out ymean, out zmean, out txmean, out tymean, out wmean);



            // -- start calcul --

            int minentr = C.MinEntries; // min number of entries in the cell to accept the cell for fitting
            int stepmax = npl - 1;      //npl/minentr;     // max step
            int size    = stepmax + 1;  // vectors size

            int maxcell = 14;

            double[] da  = new double[Math.Min(size, maxcell)];
            double[] dax = new double[Math.Min(size, maxcell)];
            double[] day = new double[Math.Min(size, maxcell)];

            int[] nentr  = new int[Math.Min(size, maxcell)];
            int[] nentrx = new int[Math.Min(size, maxcell)];
            int[] nentry = new int[Math.Min(size, maxcell)];

            SySal.Tracking.MIPEmulsionTrackInfo s1, s2;
            int ist;

            for (ist = 1; ist <= stepmax; ist++)         // cycle by the step size
            {
                int i1;
                for (i1 = 0; i1 < nseg - 1; i1++)          // cycle by the first seg
                {
                    s1 = (SySal.Tracking.MIPEmulsionTrackInfo)tr[i1];
                    /* ???? KRYSS: how could this be null ???? if(!s1) continue; */
                    int i2;
                    for (i2 = i1 + 1; i2 < nseg; i2++)      // cycle by the second seg
                    {
                        s2 = (SySal.Tracking.MIPEmulsionTrackInfo)tr[i2];
                        /* ???? KRYSS: how could this be null ???? if(!s2) continue; */
                        int icell = (int)Math.Abs(s2.Field - s1.Field);
                        if (icell > maxcell)
                        {
                            continue;
                        }
                        if (icell == ist)
                        {
                            if (s2.Slope.X != 0 && s1.Slope.X != 0)
                            {
                                dax[icell - 1]    += (float)((Math.Atan(s2.Slope.X) - Math.Atan(s1.Slope.X)) * (Math.Atan(s2.Slope.X) - Math.Atan(s1.Slope.X)));
                                nentrx[icell - 1] += 1;
                            }
                            if (s2.Slope.Y != 0 && s1.Slope.Y != 0)
                            {
                                day[icell - 1]    += (float)((Math.Atan(s2.Slope.Y) - Math.Atan(s1.Slope.Y)) * (Math.Atan(s2.Slope.Y) - Math.Atan(s1.Slope.Y)));
                                nentry[icell - 1] += 1;
                            }
                            if (s2.Slope.X != 0.0 && s1.Slope.X != 0.0 && s2.Slope.Y != 0.0 && s1.Slope.Y != 0.0)
                            {
                                da[icell - 1] += (float)(((Math.Atan(s2.Slope.X) - Math.Atan(s1.Slope.X)) * (Math.Atan(s2.Slope.X) - Math.Atan(s1.Slope.X)))
                                                         + ((Math.Atan(s2.Slope.Y) - Math.Atan(s1.Slope.Y)) * (Math.Atan(s2.Slope.Y) - Math.Atan(s1.Slope.Y))));
                                nentr[icell - 1] += 1;
                            }
                        }
                    }
                }
            }

            if (m_DiffLog != null)
            {
                m_DiffLog.WriteLine("Entries: " + da.Length);
                int u;
                m_DiffLog.WriteLine("3D");
                for (u = 0; u < nentr.Length; u++)
                {
                    m_DiffLog.WriteLine(u + " " + nentr[u] + " " + da[u]);
                }
                m_DiffLog.WriteLine("Longitudinal");
                for (u = 0; u < nentrx.Length; u++)
                {
                    m_DiffLog.WriteLine(u + " " + nentrx[u] + " " + dax[u]);
                }
                m_DiffLog.WriteLine("Transverse");
                for (u = 0; u < nentry.Length; u++)
                {
                    m_DiffLog.WriteLine(u + " " + nentry[u] + " " + day[u]);
                }
                m_DiffLog.Flush();
            }

            float Zcorr = (float)Math.Sqrt(1 + txmean0 * txmean0 + tymean0 * tymean0); // correction due to non-zero track angle and crossed lead thickness

            int maxX = 0, maxY = 0, max3D = 0;                                         // maximum value for the function fit

            double[][] vindx     = new double[Math.Min(size, maxcell)][];
            double[][] errvindx  = new double[Math.Min(size, maxcell)][];
            double[][] vindy     = new double[Math.Min(size, maxcell)][];
            double[][] errvindy  = new double[Math.Min(size, maxcell)][];
            double[][] vind3d    = new double[Math.Min(size, maxcell)][];
            double[][] errvind3d = new double[Math.Min(size, maxcell)][];
            double[]   errda     = new double[Math.Min(size, maxcell)];
            double[]   errdax    = new double[Math.Min(size, maxcell)];
            double[]   errday    = new double[Math.Min(size, maxcell)];

            System.Collections.ArrayList ar_vindx     = new System.Collections.ArrayList();
            System.Collections.ArrayList ar_errvindx  = new System.Collections.ArrayList();
            System.Collections.ArrayList ar_vindy     = new System.Collections.ArrayList();
            System.Collections.ArrayList ar_errvindy  = new System.Collections.ArrayList();
            System.Collections.ArrayList ar_vind3d    = new System.Collections.ArrayList();
            System.Collections.ArrayList ar_errvind3d = new System.Collections.ArrayList();
            System.Collections.ArrayList ar_da        = new System.Collections.ArrayList();
            System.Collections.ArrayList ar_dax       = new System.Collections.ArrayList();
            System.Collections.ArrayList ar_day       = new System.Collections.ArrayList();
            System.Collections.ArrayList ar_errda     = new System.Collections.ArrayList();
            System.Collections.ArrayList ar_errdax    = new System.Collections.ArrayList();
            System.Collections.ArrayList ar_errday    = new System.Collections.ArrayList();



            ist = 0;
            int ist1 = 0, ist2 = 0;                          // use the counter for case of missing cells

            for (i = 0; i < vind3d.Length /* size */; i++)
            {
                if (nentrx[i] >= minentr && Math.Abs(dax[i]) < 0.1)
                {
                    if (ist >= vindx.Length)
                    {
                        continue;
                    }

                    ar_vindx.Add(new double[1] {
                        i + 1
                    });
                    ar_errvindx.Add(new double[1] {
                        .25
                    });
                    ar_dax.Add(Math.Sqrt(dax[i] / (nentrx[i] * Zcorr)));
                    ar_errdax.Add((double)ar_dax[ar_dax.Count - 1] / Math.Sqrt(2 * nentrx[i]));
                    ist++;
                    maxX = ist;
                }
                if (nentry[i] >= minentr && Math.Abs(day[i]) < 0.1)
                {
                    if (ist1 >= vindy.Length)
                    {
                        continue;
                    }

                    ar_vindy.Add(new double[1] {
                        i + 1
                    });
                    ar_errvindy.Add(new double[1] {
                        .25
                    });
                    ar_day.Add(Math.Sqrt(day[i] / (nentry[i] * Zcorr)));
                    ar_errday.Add((double)ar_day[ar_day.Count - 1] / Math.Sqrt(2 * nentry[i]));
                    ist1++;
                    maxY = ist1;
                }
                if (nentr[i] >= minentr / 2 && Math.Abs(da[i]) < 0.1)
                {
                    if (ist2 >= vind3d.Length)
                    {
                        continue;
                    }

                    ar_vind3d.Add(new double[1] {
                        i + 1
                    });
                    ar_errvind3d.Add(new double[1] {
                        .25
                    });
                    ar_da.Add(Math.Sqrt(da[i] / (2 * nentr[i] * Zcorr)));
                    ar_errda.Add((double)ar_da[ar_da.Count - 1] / Math.Sqrt(4 * nentr[i]));
                    ist2++;
                    max3D = ist2;
                }
            }

            vindx     = (double[][])ar_vindx.ToArray(typeof(double[]));
            vindy     = (double[][])ar_vindy.ToArray(typeof(double[]));
            vind3d    = (double[][])ar_vind3d.ToArray(typeof(double[]));
            errvindx  = (double[][])ar_errvindx.ToArray(typeof(double[]));
            errvindy  = (double[][])ar_errvindy.ToArray(typeof(double[]));
            errvind3d = (double[][])ar_errvind3d.ToArray(typeof(double[]));
            da        = (double[])ar_da.ToArray(typeof(double));
            dax       = (double[])ar_dax.ToArray(typeof(double));
            day       = (double[])ar_day.ToArray(typeof(double));
            errda     = (double[])ar_errda.ToArray(typeof(double));
            errdax    = (double[])ar_errdax.ToArray(typeof(double));
            errday    = (double[])ar_errday.ToArray(typeof(double));

            float dt = (float)(C.SlopeError3D_0 + C.SlopeError3D_1 * Math.Abs(tmean) + C.SlopeError3D_2 * tmean * tmean);  // measurements errors parametrization

            dt *= dt;
            float dtx = (float)(C.SlopeErrorLong_0 + C.SlopeErrorLong_1 * Math.Abs(txmean) + C.SlopeErrorLong_2 * txmean * txmean);  // measurements errors parametrization

            dtx *= dtx;
            float dty = (float)(C.SlopeErrorTransv_0 + C.SlopeErrorTransv_1 * Math.Abs(tymean) + C.SlopeErrorTransv_2 * tymean * tymean);  // measurements errors parametrization

            dty *= dty;

            float x0 = (float)(C.RadiationLength / 1000);


            // the fit results
            float ePx = 0.0f, ePy = 0.0f;            // the estimated momentum
            float eDPx = 0.0f, eDPy = 0.0f;          // the fit error

            float ePXmin = 0.0f, ePXmax = 0.0f;      // momentum 90% errors range
            float ePYmin = 0.0f, ePYmax = 0.0f;      // momentum 90% errors range

            // the output of PMSang
            float eP = 0.0f, eDP = 0.0f;
            float ePmin = 0.0f, ePmax = 0.0f;         // momentum 90% errors range

            /*
             * eF1X = MCSErrorFunction("eF1X",x0,dtx);    eF1X->SetRange(0,14);
             * eF1X->SetParameter(0,2000.);                             // starting value for momentum in GeV
             * eF1Y = MCSErrorFunction("eF1Y",x0,dty);    eF1Y->SetRange(0,14);
             * eF1Y->SetParameter(0,2000.);                             // starting value for momentum in GeV
             * eF1 = MCSErrorFunction("eF1",x0,dt);     eF1->SetRange(0,14);
             * eF1->SetParameter(0,2000.);                             // starting value for momentum in GeV
             */

            NumericalTools.AdvancedFitting.LeastSquares LSF = new NumericalTools.AdvancedFitting.LeastSquares();
            LSF.Logger = m_FitLog;
            float chi2_3D = -1.0f;
            float chi2_T  = -1.0f;
            float chi2_L  = -1.0f;

            if (max3D > 0)
            {
                try
                {
                    LSF.Fit(new MyNF(x0, dt), 1, vind3d, da, errvind3d, errda, 100);
                    eP  = (float)(1.0f / 1000.0f * Math.Abs(LSF.BestFit[0]));
                    eDP = (float)(1.0f / 1000.0f * LSF.StandardErrors[0]);
                    EstimateMomentumError(eP, npl, tymean, out ePmin, out ePmax);
                    chi2_3D = (float)LSF.EstimatedVariance;
                }
                catch (Exception)
                {
                    ePmin = ePmax = eP = -99;
                }
            }
            if (maxX > 0)
            {
                try
                {
                    LSF.Fit(new MyNF(x0, dtx), 1, vindx, dax, errvindx, errdax, 100);
                    ePx  = (float)(1.0f / 1000.0f * Math.Abs(LSF.BestFit[0]));
                    eDPx = (float)(1.0f / 1000.0f * LSF.StandardErrors[0]);
                    EstimateMomentumError(ePx, npl, txmean, out ePXmin, out ePXmax);
                    chi2_L = (float)LSF.EstimatedVariance;
                }
                catch (Exception)
                {
                    ePXmin = ePXmax = ePx = -99;
                }
            }
            if (maxY > 0)
            {
                try
                {
                    LSF.Fit(new MyNF(x0, dty), 1, vindy, day, errvindy, errday, 100);
                    ePy  = (float)(1.0f / 1000.0f * Math.Abs(LSF.BestFit[0]));
                    eDPy = (float)(1.0f / 1000.0f * LSF.StandardErrors[0]);
                    EstimateMomentumError(ePy, npl, tmean, out ePYmin, out ePYmax);
                    chi2_T = (float)LSF.EstimatedVariance;
                }
                catch (Exception)
                {
                    ePYmin = ePYmax = ePy = -99;
                }
            }

            result.ConfidenceLevel = 0.90;
            if (!C.IgnoreLongitudinal && !C.IgnoreTransverse)
            {
                result.Value      = Math.Round(eP / 0.01) * 0.01;
                result.LowerBound = Math.Round(ePmin / 0.01) * 0.01;
                result.UpperBound = Math.Round(ePmax / 0.01) * 0.01;
                if (tmean > 0.2 && ((chi2_T >= 0.0 && chi2_T < chi2_3D) || (chi2_3D < 0.0 && chi2_T >= 0.0)))
                {
                    result.Value      = Math.Round(ePy / 0.01) * 0.01;
                    result.LowerBound = Math.Round(ePYmin / 0.01) * 0.01;
                    result.UpperBound = Math.Round(ePYmax / 0.01) * 0.01;
                }
            }
            else if (!C.IgnoreTransverse && C.IgnoreLongitudinal)
            {
                result.Value      = Math.Round(ePy / 0.01) * 0.01;
                result.LowerBound = Math.Round(ePYmin / 0.01) * 0.01;
                result.UpperBound = Math.Round(ePYmax / 0.01) * 0.01;
            }
            else if (!C.IgnoreLongitudinal && C.IgnoreTransverse)
            {
                result.Value      = Math.Round(ePx / 0.01) * 0.01;
                result.LowerBound = Math.Round(ePXmin / 0.01) * 0.01;
                result.UpperBound = Math.Round(ePXmax / 0.01) * 0.01;
            }
            else
            {
                result.Value = result.LowerBound = result.UpperBound = -99;
                throw new Exception("Both projections are disabled in scattering estimation!");
            }
            return(result);
        }
Example #24
0
        static void Main(string[] args)
        {
            IncreaseCost[] applications = new IncreaseCost[4];
            IncreaseCost   app0         = new Game("Heroes3", 15, 200, "No license");
            IncreaseCost   app1         = new Game("Disciples", 5, 500, "Official license");
            IncreaseCost   app2         = new Software("Util_1", 0, 30);
            IncreaseCost   app3         = new Software("Util_1", 0, 40);

            applications[0] = app0;
            applications[1] = app1;
            applications[2] = app2;
            applications[3] = app3;

            list1.AddRange(applications);

            list2.AddFirst(app0);
            list2.AddAfter(list2.First, app1);
            list2.AddLast(app2);
            list2.AddAfter(list2.Last, app3);

            //list1.Add(new Game("Heroes3", 15, 200, "No license"));

            int flag = 100;

            while (flag != 0)
            {
                Console.Clear();
                Console.WriteLine("Меню : ");
                Console.WriteLine("1 – просмотр коллекции");
                Console.WriteLine("2 – добавление элемента (используйте конструктор с 1-2 параметрами)");
                Console.WriteLine("3 – добавление элемента по указанному индексу");
                Console.WriteLine("4 – нахождение элемента с начала коллекции (переопределить метод Equals или оператор == для вашего класса – сравнение только по полю name)");
                Console.WriteLine("5 – нахождение элемента с конца коллекции");
                Console.WriteLine("6 – удаление элемента по индексу");
                Console.WriteLine("7 – удаление элемента по значению");
                Console.WriteLine("8 – реверс коллекции");
                Console.WriteLine("9 – сортировка");
                Console.WriteLine("10 – выполнение методов всех объектов, поддерживающих Interface2");

                Console.WriteLine("11 – LinkedList просмотр коллекции");
                Console.WriteLine("12 – LinkedList добавление элемента (используйте конструктор с 1-2 параметрами)");
                Console.WriteLine("13 – LinkedList добавление элемента по указанному индексу");
                Console.WriteLine("14 – LinkedList нахождение элемента с начала коллекции (переопределить метод Equals или оператор == для вашего класса – сравнение только по полю name)");
                Console.WriteLine("15 – LinkedList нахождение элемента с конца коллекции");
                Console.WriteLine("16 – LinkedList удаление элемента по индексу");
                Console.WriteLine("17 – LinkedList удаление элемента по значению");
                Console.WriteLine("18 – LinkedList реверс коллекции");
                Console.WriteLine("19 – LinkedList сортировка");
                Console.WriteLine("20 – LinkedList выполнение методов всех объектов, поддерживающих Interface2");

                Console.WriteLine("0 – выход");
                flag = Convert.ToInt32(Console.ReadLine());

                switch (flag)
                {
                //просмотр коллекции
                case (1):
                {
                    Console.Clear();

                    if (Program.list1.Count > 0)
                    {
                        Console.WriteLine("list1 содержит : " + list1.Count);
                        foreach (Object obj in Program.list1)
                        {
                            Console.WriteLine("************************************************************");
                            Console.WriteLine(obj.ToString());
                        }
                    }
                    else
                    {
                        Console.WriteLine("list1 пустой");
                    }

                    Console.ReadLine();
                    break;
                }

                //добавление элемента
                case (2):
                {
                    Console.Clear();

                    Console.WriteLine("Теперь создаем обьект");
                    Console.WriteLine("Введите name");
                    String name = Console.ReadLine();
                    Console.WriteLine("Введите bugs");
                    int bugs = Convert.ToInt32(Console.ReadLine());
                    Console.WriteLine("Введите cost");
                    double cost = Convert.ToDouble(Console.ReadLine());
                    Console.WriteLine("Введите licenseAgreement");
                    String licenseAgreement = Console.ReadLine();

                    if (licenseAgreement.Equals("0"))
                    {
                        list1.Add(new Software(name, bugs, cost));
                        Console.WriteLine("Done");
                        Console.WriteLine("создали Software");
                    }
                    else
                    {
                        list1.Add(new Game(name, bugs, cost, licenseAgreement));
                        Console.WriteLine("Done");
                        Console.WriteLine("создали Game");
                    }
                    Console.WriteLine("И добавили в list1");

                    Console.ReadLine();
                    break;
                }

                //добавление элемента по указанному индексу
                case (3):
                {
                    Console.Clear();
                    try
                    {
                        Console.WriteLine("Теперь создаем обьект");
                        Console.WriteLine("Введите name");
                        String name = Console.ReadLine();
                        Console.WriteLine("Введите bugs");
                        int bugs = Convert.ToInt32(Console.ReadLine());
                        Console.WriteLine("Введите cost");
                        double cost = Convert.ToDouble(Console.ReadLine());
                        Console.WriteLine("Введите licenseAgreement");
                        String licenseAgreement = Console.ReadLine();
                        Console.WriteLine("Введите index");
                        int index = Convert.ToInt32(Console.ReadLine());

                        if (licenseAgreement.Equals("0"))
                        {
                            list1.Insert(index, new Software(name, bugs, cost));
                            Console.WriteLine("Done");
                            Console.WriteLine("создали Software");
                        }
                        else
                        {
                            list1.Insert(index, new Game(name, bugs, cost, licenseAgreement));
                            Console.WriteLine("Done");
                            Console.WriteLine("создали Game");
                        }
                        Console.WriteLine("И добавили в list1");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Не могу выполнить");
                    }

                    Console.ReadLine();
                    break;
                }

                //нахождение элемента с начала коллекции
                case (4):
                {
                    Console.Clear();

                    Console.WriteLine("Находим элемент по имени name с начала");
                    Console.WriteLine("Введите name");
                    String   name    = Console.ReadLine();
                    Software finding = null;
                    for (int i = 0; i < list1.Count; i++)
                    {
                        if (name.Equals(((Software)list1[i]).getName()))
                        {
                            finding = (Software)list1[i];
                            break;
                        }
                    }

                    if (finding != null)
                    {
                        Console.WriteLine("Нашел");
                        if (finding is Game)
                        {
                            Console.WriteLine(((Game)finding).ToString());
                        }
                        else
                        {
                            Console.WriteLine(((Software)finding).ToString());
                        }
                    }
                    else
                    {
                        Console.WriteLine("Не нашел");
                    }

                    Console.ReadLine();
                    break;
                }

                //нахождение элемента с конца коллекции
                case (5):
                {
                    Console.Clear();

                    Console.WriteLine("Находим элемент по имени name с конца");
                    Console.WriteLine("Введите name");
                    String   name    = Console.ReadLine();
                    Software finding = null;

                    for (int i = list1.Count - 1; i >= 0; i--)
                    {
                        if (name.Equals(((Software)list1[i]).getName()))
                        {
                            finding = (Software)list1[i];
                            break;
                        }
                    }

                    if (finding != null)
                    {
                        Console.WriteLine("Нашел");
                        if (finding is Game)
                        {
                            Console.WriteLine(((Game)finding).ToString());
                        }
                        else
                        {
                            Console.WriteLine(((Software)finding).ToString());
                        }
                    }
                    else
                    {
                        Console.WriteLine("Не нашел");
                    }

                    Console.ReadLine();
                    break;
                }

                //удаление элемента по индексу
                case (6):
                {
                    Console.Clear();

                    try
                    {
                        Console.WriteLine("Удалим элемент по индексу");
                        Console.WriteLine("Введите индекс");
                        int index = Convert.ToInt32(Console.ReadLine());
                        list1.RemoveAt(index);
                        Console.WriteLine("Эх жаль элемента");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Че-то пошло не так :)");
                    }

                    Console.ReadLine();
                    break;
                }

                //удаление элемента по значению
                case (7):
                {
                    Console.Clear();

                    try
                    {
                        Console.WriteLine("Удалим элемент по значению");
                        Console.WriteLine("Введите name");
                        String name = Console.ReadLine();
                        for (int i = 0; i < list1.Count; i++)
                        {
                            if (name.Equals(((Software)list1[i]).getName()))
                            {
                                list1.RemoveAt(i);
                                Console.WriteLine("Эх жаль элемента");
                                break;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Че-то пошло не так :)");
                    }

                    Console.ReadLine();
                    break;
                }

                //реверс коллекции
                case (8):
                {
                    Console.Clear();

                    Console.WriteLine("Произведем реверс list1");
                    list1.Reverse();
                    Console.WriteLine("Готово :)");

                    Console.ReadLine();
                    break;
                }

                //сортировка
                case (9):
                {
                    Console.Clear();

                    Console.WriteLine("Отсортируем по name list1");
                    list1.Sort();
                    Console.WriteLine("Готово )");

                    Console.ReadLine();
                    break;
                }

                //выполнение методов всех объектов, поддерживающих Interface2
                case (10):
                {
                    Console.Clear();

                    foreach (IncreaseCost obj in list1)
                    {
                        if (obj is DecreaseCost)
                        {
                            Console.WriteLine("Ура");
                            Console.WriteLine("************************************************************");
                            ((DecreaseCost)obj).decreaseCost();
                            ((DecreaseCost)obj).information();
                            ((DecreaseCost)obj).statistic();
                            ((DecreaseCost)obj).info();
                        }
                    }


                    Console.ReadLine();
                    break;
                }


                //LinkedList просмотр коллекции
                case (11):
                {
                    Console.Clear();

                    if (Program.list2.Count > 0)
                    {
                        Console.WriteLine("list2 содержит : " + list2.Count);
                        foreach (Object obj in Program.list2)
                        {
                            Console.WriteLine("************************************************************");
                            Console.WriteLine(obj.ToString());
                        }
                    }
                    else
                    {
                        Console.WriteLine("list2 пустой");
                    }

                    Console.ReadLine();
                    break;
                }

                //LinkedList добавление элемента
                case (12):
                {
                    Console.Clear();

                    Console.WriteLine("Теперь создаем обьект");
                    Console.WriteLine("Введите name");
                    String name = Console.ReadLine();
                    Console.WriteLine("Введите bugs");
                    int bugs = Convert.ToInt32(Console.ReadLine());
                    Console.WriteLine("Введите cost");
                    double cost = Convert.ToDouble(Console.ReadLine());
                    Console.WriteLine("Введите licenseAgreement");
                    String licenseAgreement = Console.ReadLine();

                    if (licenseAgreement.Equals("0"))
                    {
                        list2.AddFirst(new Software(name, bugs, cost));
                        Console.WriteLine("Done");
                        Console.WriteLine("создали Software");
                    }
                    else
                    {
                        list2.AddFirst(new Game(name, bugs, cost, licenseAgreement));
                        Console.WriteLine("Done");
                        Console.WriteLine("создали Game");
                    }
                    Console.WriteLine("И добавили в list2");

                    Console.ReadLine();
                    break;
                }

                //LinkedList добавление элемента по указанному индексу
                case (13):
                {
                    Console.Clear();
                    try
                    {
                        Console.WriteLine("Теперь создаем обьект");
                        Console.WriteLine("Введите name");
                        String name = Console.ReadLine();
                        Console.WriteLine("Введите bugs");
                        int bugs = Convert.ToInt32(Console.ReadLine());
                        Console.WriteLine("Введите cost");
                        double cost = Convert.ToDouble(Console.ReadLine());
                        Console.WriteLine("Введите licenseAgreement");
                        String licenseAgreement = Console.ReadLine();
                        Console.WriteLine("Введите index обьекта после котрого вставим этот");
                        int          index = Convert.ToInt32(Console.ReadLine());
                        IncreaseCost obj   = list2.ElementAt(index);


                        if (licenseAgreement.Equals("0"))
                        {
                            list2.AddAfter(list2.Find(obj), new Software(name, bugs, cost));
                            Console.WriteLine("Done");
                            Console.WriteLine("создали Software");
                        }
                        else
                        {
                            list2.AddAfter(list2.Find(obj), new Game(name, bugs, cost, licenseAgreement));
                            Console.WriteLine("Done");
                            Console.WriteLine("создали Game");
                        }
                        Console.WriteLine("И добавили в list2");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Не могу выполнить");
                    }

                    Console.ReadLine();
                    break;
                }

                //LinkedList нахождение элемента с начала коллекции
                case (14):
                {
                    Console.Clear();

                    Console.WriteLine("Находим элемент по имени name с начала");
                    Console.WriteLine("Введите name");
                    String   name    = Console.ReadLine();
                    Software finding = null;

                    LinkedListNode <IncreaseCost> node = list2.First;
                    for (int i = 0; i < list2.Count; i++)
                    {
                        IncreaseCost obj = node.Value;
                        if (name.Equals(((Software)obj).getName()))
                        {
                            finding = (Software)obj;
                        }
                        node = node.Next;
                    }

                    if (finding != null)
                    {
                        Console.WriteLine("Нашел");
                        if (finding is Game)
                        {
                            Console.WriteLine(((Game)finding).ToString());
                        }
                        else
                        {
                            Console.WriteLine(((Software)finding).ToString());
                        }
                    }
                    else
                    {
                        Console.WriteLine("Не нашел");
                    }

                    Console.ReadLine();
                    break;
                }

                //LinkedList нахождение элемента с конца коллекции
                case (15):
                {
                    Console.Clear();

                    Console.WriteLine("Находим элемент по имени name с начала");
                    Console.WriteLine("Введите name");
                    String   name    = Console.ReadLine();
                    Software finding = null;

                    LinkedListNode <IncreaseCost> node = list2.Last;
                    for (int i = 0; i < list2.Count; i++)
                    {
                        IncreaseCost obj = node.Value;
                        if (name.Equals(((Software)obj).getName()))
                        {
                            finding = (Software)obj;
                        }
                        node = node.Previous;
                    }

                    if (finding != null)
                    {
                        Console.WriteLine("Нашел");
                        if (finding is Game)
                        {
                            Console.WriteLine(((Game)finding).ToString());
                        }
                        else
                        {
                            Console.WriteLine(((Software)finding).ToString());
                        }
                    }
                    else
                    {
                        Console.WriteLine("Не нашел");
                    }

                    Console.ReadLine();
                    break;
                }

                //LinkedList удаление элемента по индексу
                case (16):
                {
                    Console.Clear();

                    try
                    {
                        Console.WriteLine("Удалим элемент по индексу");
                        Console.WriteLine("Введите индекс");
                        int index = Convert.ToInt32(Console.ReadLine());
                        list2.Remove(list2.ElementAt(index));
                        Console.WriteLine("Эх жаль элемента");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Че-то пошло не так :)");
                    }

                    Console.ReadLine();
                    break;
                }

                //LinkedList удаление элемента по значению
                case (17):
                {
                    Console.Clear();

                    try
                    {
                        Console.WriteLine("Удалим элемент по значению");
                        Console.WriteLine("Введите name");
                        String name = Console.ReadLine();
                        LinkedListNode <IncreaseCost> node = list2.First;
                        for (int i = 0; i < list2.Count; i++)
                        {
                            IncreaseCost obj = node.Value;
                            if (name.Equals(((Software)obj).getName()))
                            {
                                list2.Remove(obj);
                                Console.WriteLine("Эх жаль элемента");
                                break;
                            }
                            node = node.Next;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Че-то пошло не так :)");
                    }

                    Console.ReadLine();
                    break;
                }

                //LinkedList реверс коллекции
                case (18):
                {
                    Console.Clear();

                    Console.WriteLine("Произведем реверс list2");
                    IncreaseCost[]            array = list2.ToArray();
                    LinkedList <IncreaseCost> list3 = new LinkedList <IncreaseCost>();
                    foreach (IncreaseCost obj in list2)
                    {
                        list3.AddFirst(obj);
                    }
                    list2 = list3;
                    Console.WriteLine("Готово :)");

                    Console.ReadLine();
                    break;
                }

                //LinkedList сортировка
                case (19):
                {
                    Console.Clear();

                    Console.WriteLine("Отсортируем по name list2");
                    IncreaseCost[] array = new IncreaseCost[list2.Count];
                    int            i     = 0;
                    foreach (IncreaseCost obj in list2)
                    {
                        array[i] = obj;
                        i++;
                    }
                    Array.Sort(array);
                    list2.Clear();
                    for (int q = 0; q < array.Length; q++)
                    {
                        list2.AddLast(array[q]);
                    }
                    Console.WriteLine("Готово )");

                    Console.ReadLine();
                    break;
                }

                //выполнение методов всех объектов, поддерживающих Interface2
                case (20):
                {
                    Console.Clear();

                    foreach (IncreaseCost obj in list2)
                    {
                        if (obj is DecreaseCost)
                        {
                            Console.WriteLine("Ура");
                            Console.WriteLine("************************************************************");
                            ((DecreaseCost)obj).decreaseCost();
                            ((DecreaseCost)obj).information();
                            ((DecreaseCost)obj).statistic();
                            ((DecreaseCost)obj).info();
                        }
                    }

                    Console.ReadLine();
                    break;
                }



                case (0):
                {
                    Console.Clear();
                    break;
                }
                }
            }
        }
Example #25
0
        /// <summary>
        /// Gets a list of the objects in the current nodes collection and its children nodes.
        /// </summary>
        /// <returns>An arraylist of objects.</returns>
        public System.Collections.ArrayList GetList()
        {
            if (this.Count == 0) return new System.Collections.ArrayList();
            System.Collections.ArrayList newlist = new System.Collections.ArrayList();
            System.Collections.ArrayList childlist = null;

            for(int i=0; i<this.Count; i++)
            {
                newlist.Add(this[i].Value);
                childlist = this[i].Nodes.GetList();
                if (childlist.Count > 0)
                {
                    newlist.AddRange(childlist);
                }
                childlist = null;
            }

            return newlist;
        }
Example #26
0
        // ---------------------------------------------------------------------
        public DateTime[] GetAllDates(int year)
        {
            if (year <= 0)
            {
                year = DateTime.Today.Year;
            }

            var dateList =
                new System.Collections.ArrayList();

            if (EventType == EventType.Recurring)
            {
                switch (Recurring)
                {
                case RecurringEvent.None:
                    if (year == this.year)
                    {
                        dateList.Add(new DateTime(year, Month, Day));
                    }
                    break;

                case RecurringEvent.Annually:
                    dateList.Add(new DateTime(year, Month, Day));
                    break;

                case RecurringEvent.Biweekly:
                    var date = new DateTime(year, 1, 1);

                    if (date < Date())
                    {
                        date = Date();
                    }

                    var timeSpan = Date() - date;
                    var offset   = (timeSpan.Days % 14);

                    for (date = date.AddDays(offset);
                         date.Year == year;
                         date = date.AddDays(14))
                    {
                        dateList.Add(date);
                    }

                    break;

                case RecurringEvent.Monthly:
                    dateList.AddRange(Monthly(1, year));
                    break;

                case RecurringEvent.Quarterly:
                    dateList.AddRange(Monthly(3, year));
                    break;

                case RecurringEvent.Semiannually:
                    dateList.AddRange(Monthly(6, year));
                    break;
                }
            }

            // A zero month indicates that the movable event repeats for all
            // months
            else if (EventType == EventType.Movable &&
                     Recurring == RecurringEvent.Monthly)
            {
                // Clone a copy so we don't mess up the original event.
                var ev   = (Event)Clone();
                var date = Date(year);

                if (date < ev.Date())
                {
                    date = ev.Date();
                }

                ev.Month = date.Month;

                var maxMonths =
                    CultureInfo.CurrentCulture.Calendar.GetMonthsInYear(year);

                for (;;)
                {
                    dateList.Add(ev.Date());

                    if ((ev.Month + 1) > maxMonths)
                    {
                        break;
                    }

                    ev.Month += 1;
                }
            }
            else
            {
                dateList.Add(Date(year));
            }

            var dates = new DateTime[dateList.Count];

            dateList.CopyTo(dates);
            return(dates);
        }
        /// <summary>
        /// Lista, dentro de um diretório, todos os arquivos cujo nome corresponde ao filtro.
        /// O filtro é uma string que pode conter vários filtros separados por '|'.
        /// </summary>
        /// <returns>Lista com o nome completo de todos os arquivos que correspondem ao filtro.</returns>
        /// <param name="p_directoryname">Nome do diretório.</param>
        /// <param name="p_filter">String que pode conter vários filtros separados por '|'.</param>
        /// <param name="p_searchoption">Opção de busca.</param>
        private string[] FilterList(string p_directoryname, string p_filter, System.IO.SearchOption p_searchoption)
        {
            System.Collections.ArrayList v_tempfiles;
            string[] v_filters;

            v_tempfiles = new System.Collections.ArrayList();

            v_filters = p_filter.Split('|');

            foreach (string v_filter in v_filters)
                v_tempfiles.AddRange(System.IO.Directory.GetFiles(p_directoryname, v_filter, p_searchoption));

            return (string[]) v_tempfiles.ToArray(typeof(string));
        }
 private Scorer MakeCountingSumScorerSomeReq()
 {
     // At least one required scorer.
     if (optionalScorers.Count < minNrShouldMatch)
     {
         return new NonMatchingScorer(); // fewer optional clauses than minimum that should match
     }
     else if (optionalScorers.Count == minNrShouldMatch)
     {
         // all optional scorers also required.
         System.Collections.ArrayList allReq = new System.Collections.ArrayList(requiredScorers);
         allReq.AddRange(optionalScorers);
         return AddProhibitedScorers(CountingConjunctionSumScorer(allReq));
     }
     else
     {
         // optionalScorers.size() > minNrShouldMatch, and at least one required scorer
         Scorer requiredCountingSumScorer = (requiredScorers.Count == 1)?new SingleMatchScorer(this, (Scorer) requiredScorers[0]):CountingConjunctionSumScorer(requiredScorers);
         if (minNrShouldMatch > 0)
         {
             // use a required disjunction scorer over the optional scorers
             return AddProhibitedScorers(DualConjunctionSumScorer(requiredCountingSumScorer, CountingDisjunctionSumScorer(optionalScorers, minNrShouldMatch)));
         }
         else
         {
             // minNrShouldMatch == 0
             return new ReqOptSumScorer(AddProhibitedScorers(requiredCountingSumScorer), ((optionalScorers.Count == 1)?new SingleMatchScorer(this, (Scorer) optionalScorers[0]):CountingDisjunctionSumScorer(optionalScorers, 1))); // require 1 in combined, optional scorer.
         }
     }
 }
Example #29
0
        public static System.Collections.ArrayList getSubSetRecursive(System.Collections.ArrayList set, int index = 0)
        {
            System.Collections.ArrayList result = null;
            if (index == set.Count)
            {
                result = new System.Collections.ArrayList();
                System.Collections.ArrayList empty = new System.Collections.ArrayList();
                //empty.Add('@');
                result.Add(empty);
            }
            else
            {
                result = getSubSetRecursive(set, index + 1);
                object o = set[index];
                System.Collections.ArrayList more_subsets = new System.Collections.ArrayList();
                foreach (System.Collections.ArrayList subsets in result)
                {
                    System.Collections.ArrayList new_subset = new System.Collections.ArrayList();
                    new_subset.AddRange(subsets);
                    new_subset.Add(o);
                    more_subsets.Add(new_subset);
                }
                result.AddRange(more_subsets);
                //System.Collections.ArrayList subset_new_elem = new System.Collections.ArrayList();
                //subset_new_elem.Add(o);
                //result.Add(subset_new_elem);
                /*
                int result_loop_count = result_loop.Count;
                for (int i = 0; i < result_loop_count; i++)
                {
                    System.Collections.ArrayList new_subset = new System.Collections.ArrayList();
                    foreach (object o_pre in result_loop[i])
                    {
                        new_subset.Add(o_pre);
                    }
                    new_subset.Add(o);
                    result_loop.Add(new_subset);
                    //System.Collections.ArrayList subset_clone = (System.Collections.ArrayList)subset.Clone();
                    //subset_clone.Add(o);
                    //result_loop.Add(subset_clone);

                }
                System.Collections.ArrayList subset_new_elem = new System.Collections.ArrayList();
                subset_new_elem.Add(o);
                result_loop.Add(subset_new_elem);
                return result_loop;*/
            }
            return result;
        }
Example #30
0
        private int[] Convert(string data)
        {
            byte[] asciiBytes = Encoding.ASCII.GetBytes(data);

            CodeSetAllowed csa1 = asciiBytes.Length > 0 ? CodesetAllowedForChar(asciiBytes[0]) : CodeSetAllowed.CodeAorB;
            CodeSetAllowed csa2 = asciiBytes.Length > 0 ? CodesetAllowedForChar(asciiBytes[1]) : CodeSetAllowed.CodeAorB;
            CodeSet currcs = PickStartSet(csa1, csa2);

            System.Collections.ArrayList codes = new System.Collections.ArrayList(asciiBytes.Length + 3);
            codes.Add(StartCode(currcs));

            for (int i = 0; i < asciiBytes.Length; i++)
            {
                int thischar = asciiBytes[i];
                int nextchar = asciiBytes.Length > (i + 1) ? asciiBytes[i + 1] : -1;

                codes.AddRange(CodesForChar(thischar, nextchar, ref currcs));
            }

            int checksum = (int)(codes[0]);
            for (int i = 1; i < codes.Count; i++)
            {
                checksum += i * (int)(codes[i]);
            }
            codes.Add(checksum % 103);

            codes.Add(StopCode());

            int[] result = codes.ToArray(typeof(int)) as int[];
            return result;
        }
Example #31
0
        /*
        public static void TestPatch(FpuSegment seg) {
            ArrayList TempCode;
            //Generate the code
            TempCode=new ArrayList(Program.ReadFileBytes("out"));
            byte[] sseCode=(byte[])TempCode.ToArray(typeof(byte));
            TempCode.Clear();
            StreamWriter sr=new StreamWriter("tout.txt");
            sr.WriteLine("bits 32");
            foreach(string s in seg.TestData) {
                sr.WriteLine(s);
            }
            sr.Close();
            Process p=new Process();
            p.StartInfo.FileName="nasm.exe";
            p.StartInfo.Arguments="-o tout tout.txt";
            p.StartInfo.UseShellExecute=false;
            p.StartInfo.CreateNoWindow=true;
            p.Start();
            p.WaitForExit();
            p.Close();
            FileInfo fi=new FileInfo("tout");
            if(fi.Length==0) throw new OptimizationException("Patcher: patch tester produced uncompilable code");
            TempCode.AddRange(Program.ReadFileBytes("tout"));
            byte[] fpuCode=(byte[])TempCode.ToArray(typeof(byte));
            //inject and run the code
            if(sseCode.Length>InjectionLength||fpuCode.Length>InjectionLength)
                throw new OptimizationException("Checker: Injection site is too short");
            try {
                File.Delete("asmTester2.exe");
            } catch { }
            try {
                File.Copy("asmTester.exe","asmTester2.exe");
                FileStream fs=File.Open("asmTester2.exe",FileMode.Open);
                fs.Position=TestPoint1;
                fs.Write(fpuCode,0,fpuCode.Length);
                fs.Position=TestPoint2;
                fs.Write(sseCode,0,sseCode.Length);
                fs.Close();
                p=new Process();
                p.StartInfo.UseShellExecute=false;
                p.StartInfo.CreateNoWindow=true;
                p.StartInfo.FileName="asmTester2.exe";
                p.Start();
                p.WaitForExit();
                if(!p.HasExited) {
                    p.Kill();
                    p.Close();
                    throw new OptimizationException("Checker: Process has not exited");
                }
                if(p.ExitCode!=1) {
                    p.Close();
                    throw new OptimizationException("Checker: Patch appears to be corrupt");
                }
                p.Close();
            } catch (Exception e) {
                if(e is OptimizationException) throw;
                throw new OptimizationException("Checker: Something threw an exception");
            }

        }
        */
        public static void Benchmark(FpuSegment seg)
        {
            ArrayList TempCode;
            //Get the sse code
            TempCode=new ArrayList(Program.ReadFileBytes("out"));
            TempCode.AddRange(JumpCode);
            byte[] bytes=(byte[])TempCode.ToArray(typeof(byte));
            TempCode.Clear();
            //Get the fpu code
            int a=0;
            for(int i=0;i<seg.Lines.Length;i++) {
                if(a==CodeGenerator.FpuLines.Length) break;
                if(CodeGenerator.FpuLines[a]==i) {
                    TempCode.AddRange(HexToString(seg.Lines[i].code));
                    a++;
                }
            }
            TempCode.AddRange(JumpCode);
            byte[] bytes2=(byte[])TempCode.ToArray(typeof(byte));
            Benchmark(bytes,bytes2);
            if(!Program.IgnoreBenchmark) {
                if(SseTime>=FpuTime+Bias) throw new OptimizationException("Benchmarker: Patch was slower than original code");
            }
        }
Example #32
0
        public static void ApplyPatch(FpuSegment seg)
        {
            Process p = new Process();

            p.StartInfo.FileName        = "nasm.exe";
            p.StartInfo.Arguments       = "out.txt";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow  = true;
            p.Start();
            p.WaitForExit();
            p.Close();
            FileInfo fi = new FileInfo("out");

            if (fi.Length == 0)
            {
                throw new OptimizationException("Patcher: Code generator produced uncompilable code");
            }
            ArrayList code = new ArrayList();

            for (int i = 0; i < seg.Pre.Length; i++)
            {
                code.AddRange(HexToString(seg.Pre[i].code));
            }
            code.AddRange(Program.ReadFileBytes("out"));
            for (int i = 0; i < seg.Post.Length; i++)
            {
                code.AddRange(HexToString(seg.Post[i].code));
            }
            if (code.Count > seg.End - seg.Start)
            {
                throw new OptimizationException("Patcher: Patch to big to fit into code");
            }

            /*if(Program.TestPatches) {
             *  TestPatch(seg); //TESTPATCH CALL
             * }*/
            if (Program.Benchmark)
            {
                Benchmark(seg); //BENCHMARK CALL!!!!!!!!!!!!!!!!!!!!!!!! <---------------- OVER HERE
            }
            byte[] Code = new byte[seg.End - seg.Start];
            code.CopyTo(Code);
            for (int i = code.Count; i < (seg.End - seg.Start); i++)
            {
                Code[i] = 144;    //Fill the rest of the code up with nop's
            }
            long a = (seg.End - seg.Start) - code.Count;

            if (a > 255)
            {
                throw new OptimizationException("Patcher: Patch end address out of range of a short jump");
            }
            else if (a > 2)
            {
                Code[code.Count]     = 235;
                Code[code.Count + 1] = (byte)(a - 2);
            }
            if (Program.Restrict)
            {
                if (PatchCount < Program.FirstPatch || PatchCount > Program.LastPatch)
                {
                    PatchCount++;
                    throw new OptimizationException("Patcher: Patch restricted");
                }
                PatchCount++;
            }
#if emitpatch
            FileStream   fs2 = File.Create("emittedpatch.patch", 4096);
            BinaryWriter bw  = new BinaryWriter(fs2);
            bw.Write(seg.Start);
            bw.Write(Code.Length);
            bw.Write(Code, 0, Code.Length);
            bw.Close();
#endif
            FileStream fs = File.Open("code", FileMode.Open);
            fs.Position = seg.Start;
            fs.Write(Code, 0, Code.Length);
            fs.Close();
        }
Example #33
0
        /// <summary> Write a Class XML Element from attributes in a type. </summary>
        public virtual void WriteClass(System.Xml.XmlWriter writer, System.Type type)
        {
            object[] attributes = type.GetCustomAttributes(typeof(ClassAttribute), false);
            if(attributes.Length == 0)
                return;
            ClassAttribute attribute = attributes[0] as ClassAttribute;

            writer.WriteStartElement( "class" );
            // Attribute: <entity-name>
            if(attribute.EntityName != null)
            writer.WriteAttributeString("entity-name", GetAttributeValue(attribute.EntityName, type));
            // Attribute: <name>
            if(attribute.Name != null)
            writer.WriteAttributeString("name", GetAttributeValue(attribute.Name, type));
            // Attribute: <proxy>
            if(attribute.Proxy != null)
            writer.WriteAttributeString("proxy", GetAttributeValue(attribute.Proxy, type));
            // Attribute: <lazy>
            if( attribute.LazySpecified )
            writer.WriteAttributeString("lazy", attribute.Lazy ? "true" : "false");
            // Attribute: <schema-action>
            if(attribute.SchemaAction != null)
            writer.WriteAttributeString("schema-action", GetAttributeValue(attribute.SchemaAction, type));
            // Attribute: <table>
            if(attribute.Table != null)
            writer.WriteAttributeString("table", GetAttributeValue(attribute.Table, type));
            // Attribute: <schema>
            if(attribute.Schema != null)
            writer.WriteAttributeString("schema", GetAttributeValue(attribute.Schema, type));
            // Attribute: <catalog>
            if(attribute.Catalog != null)
            writer.WriteAttributeString("catalog", GetAttributeValue(attribute.Catalog, type));
            // Attribute: <subselect>
            if(attribute.Subselect != null)
            writer.WriteAttributeString("subselect", GetAttributeValue(attribute.Subselect, type));
            // Attribute: <discriminator-value>
            if(attribute.DiscriminatorValue != null)
            writer.WriteAttributeString("discriminator-value", GetAttributeValue(attribute.DiscriminatorValue, type));
            // Attribute: <mutable>
            if( attribute.MutableSpecified )
            writer.WriteAttributeString("mutable", attribute.Mutable ? "true" : "false");
            // Attribute: <abstract>
            if( attribute.AbstractSpecified )
            writer.WriteAttributeString("abstract", attribute.Abstract ? "true" : "false");
            // Attribute: <polymorphism>
            if(attribute.Polymorphism != PolymorphismType.Unspecified)
            writer.WriteAttributeString("polymorphism", GetXmlEnumValue(typeof(PolymorphismType), attribute.Polymorphism));
            // Attribute: <where>
            if(attribute.Where != null)
            writer.WriteAttributeString("where", GetAttributeValue(attribute.Where, type));
            // Attribute: <persister>
            if(attribute.Persister != null)
            writer.WriteAttributeString("persister", GetAttributeValue(attribute.Persister, type));
            // Attribute: <dynamic-update>
            if( attribute.DynamicUpdateSpecified )
            writer.WriteAttributeString("dynamic-update", attribute.DynamicUpdate ? "true" : "false");
            // Attribute: <dynamic-insert>
            if( attribute.DynamicInsertSpecified )
            writer.WriteAttributeString("dynamic-insert", attribute.DynamicInsert ? "true" : "false");
            // Attribute: <batch-size>
            if(attribute.BatchSize != -9223372036854775808)
            writer.WriteAttributeString("batch-size", attribute.BatchSize.ToString());
            // Attribute: <select-before-update>
            if( attribute.SelectBeforeUpdateSpecified )
            writer.WriteAttributeString("select-before-update", attribute.SelectBeforeUpdate ? "true" : "false");
            // Attribute: <optimistic-lock>
            if(attribute.OptimisticLock != OptimisticLockMode.Unspecified)
            writer.WriteAttributeString("optimistic-lock", GetXmlEnumValue(typeof(OptimisticLockMode), attribute.OptimisticLock));
            // Attribute: <check>
            if(attribute.Check != null)
            writer.WriteAttributeString("check", GetAttributeValue(attribute.Check, type));
            // Attribute: <rowid>
            if(attribute.RowId != null)
            writer.WriteAttributeString("rowid", GetAttributeValue(attribute.RowId, type));
            // Attribute: <node>
            if(attribute.Node != null)
            writer.WriteAttributeString("node", GetAttributeValue(attribute.Node, type));

            WriteUserDefinedContent(writer, type, null, attribute);
            // Element: <meta>
            System.Collections.ArrayList MetaList = FindAttributedMembers( attribute, typeof(MetaAttribute), type );
            foreach( System.Reflection.MemberInfo member in MetaList )
            {
                object[] objects = member.GetCustomAttributes(typeof(MetaAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteMeta(writer, member, memberAttrib as MetaAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(MetaAttribute), attribute);
            // Element: <subselect>
            System.Collections.ArrayList SubselectList = FindAttributedMembers( attribute, typeof(SubselectAttribute), type );
            foreach( System.Reflection.MemberInfo member in SubselectList )
            {
                object[] objects = member.GetCustomAttributes(typeof(SubselectAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteSubselect(writer, member, memberAttrib as SubselectAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(SubselectAttribute), attribute);
            // Element: <cache>
            System.Collections.ArrayList CacheList = FindAttributedMembers( attribute, typeof(CacheAttribute), type );
            foreach( System.Reflection.MemberInfo member in CacheList )
            {
                object[] objects = member.GetCustomAttributes(typeof(CacheAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteCache(writer, member, memberAttrib as CacheAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(CacheAttribute), attribute);
            // Element: <synchronize>
            System.Collections.ArrayList SynchronizeList = FindAttributedMembers( attribute, typeof(SynchronizeAttribute), type );
            foreach( System.Reflection.MemberInfo member in SynchronizeList )
            {
                object[] objects = member.GetCustomAttributes(typeof(SynchronizeAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteSynchronize(writer, member, memberAttrib as SynchronizeAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(SynchronizeAttribute), attribute);
            // Element: <comment>
            System.Collections.ArrayList CommentList = FindAttributedMembers( attribute, typeof(CommentAttribute), type );
            foreach( System.Reflection.MemberInfo member in CommentList )
            {
                object[] objects = member.GetCustomAttributes(typeof(CommentAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteComment(writer, member, memberAttrib as CommentAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(CommentAttribute), attribute);
            // Element: <tuplizer>
            System.Collections.ArrayList TuplizerList = FindAttributedMembers( attribute, typeof(TuplizerAttribute), type );
            foreach( System.Reflection.MemberInfo member in TuplizerList )
            {
                object[] objects = member.GetCustomAttributes(typeof(TuplizerAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteTuplizer(writer, member, memberAttrib as TuplizerAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(TuplizerAttribute), attribute);
            // Element: <id>
            System.Collections.ArrayList IdList = FindAttributedMembers( attribute, typeof(IdAttribute), type );
            foreach( System.Reflection.MemberInfo member in IdList )
            {
                object[] objects = member.GetCustomAttributes(typeof(IdAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteId(writer, member, memberAttrib as IdAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(IdAttribute), attribute);
            // Element: <composite-id>
            System.Collections.ArrayList CompositeIdList = FindAttributedMembers( attribute, typeof(CompositeIdAttribute), type );
            foreach( System.Reflection.MemberInfo member in CompositeIdList )
            {
                object[] objects = member.GetCustomAttributes(typeof(CompositeIdAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteCompositeId(writer, member, memberAttrib as CompositeIdAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(CompositeIdAttribute), attribute);
            // Element: <discriminator>
            System.Collections.ArrayList DiscriminatorList = FindAttributedMembers( attribute, typeof(DiscriminatorAttribute), type );
            foreach( System.Reflection.MemberInfo member in DiscriminatorList )
            {
                object[] objects = member.GetCustomAttributes(typeof(DiscriminatorAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteDiscriminator(writer, member, memberAttrib as DiscriminatorAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(DiscriminatorAttribute), attribute);
            // Element: <natural-id>
            System.Collections.ArrayList NaturalIdList = FindAttributedMembers( attribute, typeof(NaturalIdAttribute), type );
            foreach( System.Reflection.MemberInfo member in NaturalIdList )
            {
                object[] objects = member.GetCustomAttributes(typeof(NaturalIdAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteNaturalId(writer, member, memberAttrib as NaturalIdAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(NaturalIdAttribute), attribute);
            // Element: <version>
            System.Collections.ArrayList VersionList = FindAttributedMembers( attribute, typeof(VersionAttribute), type );
            foreach( System.Reflection.MemberInfo member in VersionList )
            {
                object[] objects = member.GetCustomAttributes(typeof(VersionAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteVersion(writer, member, memberAttrib as VersionAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(VersionAttribute), attribute);
            // Element: <timestamp>
            System.Collections.ArrayList TimestampList = FindAttributedMembers( attribute, typeof(TimestampAttribute), type );
            foreach( System.Reflection.MemberInfo member in TimestampList )
            {
                object[] objects = member.GetCustomAttributes(typeof(TimestampAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteTimestamp(writer, member, memberAttrib as TimestampAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(TimestampAttribute), attribute);
            // Element: <property>
            System.Collections.ArrayList PropertyList = FindAttributedMembers( attribute, typeof(PropertyAttribute), type );
            foreach( System.Reflection.MemberInfo member in PropertyList )
            {
                object[] objects = member.GetCustomAttributes(typeof(PropertyAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteProperty(writer, member, memberAttrib as PropertyAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(PropertyAttribute), attribute);
            // Element: <many-to-one>
            System.Collections.ArrayList ManyToOneList = FindAttributedMembers( attribute, typeof(ManyToOneAttribute), type );
            foreach( System.Reflection.MemberInfo member in ManyToOneList )
            {
                object[] objects = member.GetCustomAttributes(typeof(ManyToOneAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteManyToOne(writer, member, memberAttrib as ManyToOneAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(ManyToOneAttribute), attribute);
            // Element: <one-to-one>
            System.Collections.ArrayList OneToOneList = FindAttributedMembers( attribute, typeof(OneToOneAttribute), type );
            foreach( System.Reflection.MemberInfo member in OneToOneList )
            {
                object[] objects = member.GetCustomAttributes(typeof(OneToOneAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteOneToOne(writer, member, memberAttrib as OneToOneAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(OneToOneAttribute), attribute);
            // Element: <component>
            WriteNestedComponentTypes(writer, type);
            WriteUserDefinedContent(writer, type, typeof(ComponentAttribute), attribute);
            // Element: <dynamic-component>
            System.Collections.ArrayList DynamicComponentList = FindAttributedMembers( attribute, typeof(DynamicComponentAttribute), type );
            foreach( System.Reflection.MemberInfo member in DynamicComponentList )
            {
                object[] objects = member.GetCustomAttributes(typeof(DynamicComponentAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                WriteDynamicComponent(writer, member, memberAttribs[0] as DynamicComponentAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(DynamicComponentAttribute), attribute);
            // Element: <properties>
            System.Collections.ArrayList PropertiesList = FindAttributedMembers( attribute, typeof(PropertiesAttribute), type );
            foreach( System.Reflection.MemberInfo member in PropertiesList )
            {
                object[] objects = member.GetCustomAttributes(typeof(PropertiesAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteProperties(writer, member, memberAttrib as PropertiesAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(PropertiesAttribute), attribute);
            // Element: <any>
            System.Collections.ArrayList AnyList = FindAttributedMembers( attribute, typeof(AnyAttribute), type );
            foreach( System.Reflection.MemberInfo member in AnyList )
            {
                object[] objects = member.GetCustomAttributes(typeof(AnyAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteAny(writer, member, memberAttrib as AnyAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(AnyAttribute), attribute);
            // Element: <map>
            System.Collections.ArrayList MapList = FindAttributedMembers( attribute, typeof(MapAttribute), type );
            foreach( System.Reflection.MemberInfo member in MapList )
            {
                object[] objects = member.GetCustomAttributes(typeof(MapAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteMap(writer, member, memberAttrib as MapAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(MapAttribute), attribute);
            // Element: <set>
            System.Collections.ArrayList SetList = FindAttributedMembers( attribute, typeof(SetAttribute), type );
            foreach( System.Reflection.MemberInfo member in SetList )
            {
                object[] objects = member.GetCustomAttributes(typeof(SetAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteSet(writer, member, memberAttrib as SetAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(SetAttribute), attribute);
            // Element: <list>
            System.Collections.ArrayList ListList = FindAttributedMembers( attribute, typeof(ListAttribute), type );
            foreach( System.Reflection.MemberInfo member in ListList )
            {
                object[] objects = member.GetCustomAttributes(typeof(ListAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteList(writer, member, memberAttrib as ListAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(ListAttribute), attribute);
            // Element: <bag>
            System.Collections.ArrayList BagList = FindAttributedMembers( attribute, typeof(BagAttribute), type );
            foreach( System.Reflection.MemberInfo member in BagList )
            {
                object[] objects = member.GetCustomAttributes(typeof(BagAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteBag(writer, member, memberAttrib as BagAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(BagAttribute), attribute);
            // Element: <idbag>
            System.Collections.ArrayList IdBagList = FindAttributedMembers( attribute, typeof(IdBagAttribute), type );
            foreach( System.Reflection.MemberInfo member in IdBagList )
            {
                object[] objects = member.GetCustomAttributes(typeof(IdBagAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteIdBag(writer, member, memberAttrib as IdBagAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(IdBagAttribute), attribute);
            // Element: <array>
            System.Collections.ArrayList ArrayList = FindAttributedMembers( attribute, typeof(ArrayAttribute), type );
            foreach( System.Reflection.MemberInfo member in ArrayList )
            {
                object[] objects = member.GetCustomAttributes(typeof(ArrayAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteArray(writer, member, memberAttrib as ArrayAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(ArrayAttribute), attribute);
            // Element: <primitive-array>
            System.Collections.ArrayList PrimitiveArrayList = FindAttributedMembers( attribute, typeof(PrimitiveArrayAttribute), type );
            foreach( System.Reflection.MemberInfo member in PrimitiveArrayList )
            {
                object[] objects = member.GetCustomAttributes(typeof(PrimitiveArrayAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WritePrimitiveArray(writer, member, memberAttrib as PrimitiveArrayAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(PrimitiveArrayAttribute), attribute);
            // Element: <join>
            System.Collections.ArrayList JoinList = FindAttributedMembers( attribute, typeof(JoinAttribute), type );
            foreach( System.Reflection.MemberInfo member in JoinList )
            {
                object[] objects = member.GetCustomAttributes(typeof(JoinAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteJoin(writer, member, memberAttrib as JoinAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(JoinAttribute), attribute);
            // Element: <subclass>
            WriteNestedSubclassTypes(writer, type);
            WriteUserDefinedContent(writer, type, typeof(SubclassAttribute), attribute);
            // Element: <joined-subclass>
            WriteNestedJoinedSubclassTypes(writer, type);
            WriteUserDefinedContent(writer, type, typeof(JoinedSubclassAttribute), attribute);
            // Element: <union-subclass>
            WriteNestedUnionSubclassTypes(writer, type);
            WriteUserDefinedContent(writer, type, typeof(UnionSubclassAttribute), attribute);
            // Element: <loader>
            System.Collections.ArrayList LoaderList = FindAttributedMembers( attribute, typeof(LoaderAttribute), type );
            foreach( System.Reflection.MemberInfo member in LoaderList )
            {
                object[] objects = member.GetCustomAttributes(typeof(LoaderAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteLoader(writer, member, memberAttrib as LoaderAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(LoaderAttribute), attribute);
            // Element: <sql-insert>
            System.Collections.ArrayList SqlInsertList = FindAttributedMembers( attribute, typeof(SqlInsertAttribute), type );
            foreach( System.Reflection.MemberInfo member in SqlInsertList )
            {
                object[] objects = member.GetCustomAttributes(typeof(SqlInsertAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteSqlInsert(writer, member, memberAttrib as SqlInsertAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(SqlInsertAttribute), attribute);
            // Element: <sql-update>
            System.Collections.ArrayList SqlUpdateList = FindAttributedMembers( attribute, typeof(SqlUpdateAttribute), type );
            foreach( System.Reflection.MemberInfo member in SqlUpdateList )
            {
                object[] objects = member.GetCustomAttributes(typeof(SqlUpdateAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteSqlUpdate(writer, member, memberAttrib as SqlUpdateAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(SqlUpdateAttribute), attribute);
            // Element: <sql-delete>
            System.Collections.ArrayList SqlDeleteList = FindAttributedMembers( attribute, typeof(SqlDeleteAttribute), type );
            foreach( System.Reflection.MemberInfo member in SqlDeleteList )
            {
                object[] objects = member.GetCustomAttributes(typeof(SqlDeleteAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteSqlDelete(writer, member, memberAttrib as SqlDeleteAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(SqlDeleteAttribute), attribute);
            // Element: <filter>
            System.Collections.ArrayList FilterList = FindAttributedMembers( attribute, typeof(FilterAttribute), type );
            foreach( System.Reflection.MemberInfo member in FilterList )
            {
                object[] objects = member.GetCustomAttributes(typeof(FilterAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteFilter(writer, member, memberAttrib as FilterAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(FilterAttribute), attribute);
            // Element: <resultset>
            System.Collections.ArrayList ResultSetList = FindAttributedMembers( attribute, typeof(ResultSetAttribute), type );
            foreach( System.Reflection.MemberInfo member in ResultSetList )
            {
                object[] objects = member.GetCustomAttributes(typeof(ResultSetAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteResultSet(writer, member, memberAttrib as ResultSetAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(ResultSetAttribute), attribute);
            // Element: <query>
            System.Collections.ArrayList QueryList = FindAttributedMembers( attribute, typeof(QueryAttribute), type );
            foreach( System.Reflection.MemberInfo member in QueryList )
            {
                object[] objects = member.GetCustomAttributes(typeof(QueryAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteQuery(writer, member, memberAttrib as QueryAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(QueryAttribute), attribute);
            // Element: <sql-query>
            System.Collections.ArrayList SqlQueryList = FindAttributedMembers( attribute, typeof(SqlQueryAttribute), type );
            foreach( System.Reflection.MemberInfo member in SqlQueryList )
            {
                object[] objects = member.GetCustomAttributes(typeof(SqlQueryAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteSqlQuery(writer, member, memberAttrib as SqlQueryAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(SqlQueryAttribute), attribute);

            writer.WriteEndElement();
        }
Example #34
0
        /// <summary>
        /// 合并字符串数组,例如:"1,2,3,"和"2,3,5,"生成"1,2,3,5,"
        /// </summary>
        /// <param name="s1"></param>
        /// <param name="s2"></param>
        /// <returns></returns>
        public static string UnionStr(string s1, string s2)
        {
            string[] strs1, strs2;
            strs1 = s1.Split(',');
            strs2 = s2.Split(',');

            System.Collections.ArrayList sc = new System.Collections.ArrayList();
            sc.AddRange(strs1);
            foreach (string s in strs2)
            {
                if (s != string.Empty && !sc.Contains(s))
                {
                    sc.Add(s);
                }
            }

            string lastStr = ",";
            foreach (string s in sc)
            {
                lastStr += s + ",";
            }
            return lastStr;
        }
Example #35
0
        /// <summary> Write a HibernateMapping XML Element from attributes in a type. </summary>
        public virtual void WriteHibernateMapping(System.Xml.XmlWriter writer, System.Type type)
        {
            object[] attributes = type.GetCustomAttributes(typeof(HibernateMappingAttribute), false);
            if(attributes.Length == 0)
                return;
            HibernateMappingAttribute attribute = attributes[0] as HibernateMappingAttribute;

            writer.WriteStartElement( "hibernate-mapping" );
            // Attribute: <schema>
            if(attribute.Schema != null)
            writer.WriteAttributeString("schema", GetAttributeValue(attribute.Schema, type));
            // Attribute: <catalog>
            if(attribute.Catalog != null)
            writer.WriteAttributeString("catalog", GetAttributeValue(attribute.Catalog, type));
            // Attribute: <default-cascade>
            if(attribute.DefaultCascade != null)
            writer.WriteAttributeString("default-cascade", GetAttributeValue(attribute.DefaultCascade, type));
            // Attribute: <default-access>
            if(attribute.DefaultAccess != null)
            writer.WriteAttributeString("default-access", GetAttributeValue(attribute.DefaultAccess, type));
            // Attribute: <default-lazy>
            if( attribute.DefaultLazySpecified )
            writer.WriteAttributeString("default-lazy", attribute.DefaultLazy ? "true" : "false");
            // Attribute: <auto-import>
            if( attribute.AutoImportSpecified )
            writer.WriteAttributeString("auto-import", attribute.AutoImport ? "true" : "false");
            // Attribute: <namespace>
            if(attribute.Namespace != null)
            writer.WriteAttributeString("namespace", GetAttributeValue(attribute.Namespace, type));
            // Attribute: <assembly>
            if(attribute.Assembly != null)
            writer.WriteAttributeString("assembly", GetAttributeValue(attribute.Assembly, type));

            WriteUserDefinedContent(writer, type, null, attribute);
            // Element: <meta>
            System.Collections.ArrayList MetaList = FindAttributedMembers( attribute, typeof(MetaAttribute), type );
            foreach( System.Reflection.MemberInfo member in MetaList )
            {
                object[] objects = member.GetCustomAttributes(typeof(MetaAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteMeta(writer, member, memberAttrib as MetaAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(MetaAttribute), attribute);
            // Element: <typedef>
            System.Collections.ArrayList TypeDefList = FindAttributedMembers( attribute, typeof(TypeDefAttribute), type );
            foreach( System.Reflection.MemberInfo member in TypeDefList )
            {
                object[] objects = member.GetCustomAttributes(typeof(TypeDefAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteTypeDef(writer, member, memberAttrib as TypeDefAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(TypeDefAttribute), attribute);
            // Element: <import>
            WriteNestedImportTypes(writer, type);
            WriteUserDefinedContent(writer, type, typeof(ImportAttribute), attribute);
            // Element: <class>
            WriteNestedClassTypes(writer, type);
            WriteUserDefinedContent(writer, type, typeof(ClassAttribute), attribute);
            // Element: <subclass>
            WriteNestedSubclassTypes(writer, type);
            WriteUserDefinedContent(writer, type, typeof(SubclassAttribute), attribute);
            // Element: <joined-subclass>
            WriteNestedJoinedSubclassTypes(writer, type);
            WriteUserDefinedContent(writer, type, typeof(JoinedSubclassAttribute), attribute);
            // Element: <union-subclass>
            WriteNestedUnionSubclassTypes(writer, type);
            WriteUserDefinedContent(writer, type, typeof(UnionSubclassAttribute), attribute);
            // Element: <resultset>
            System.Collections.ArrayList ResultSetList = FindAttributedMembers( attribute, typeof(ResultSetAttribute), type );
            foreach( System.Reflection.MemberInfo member in ResultSetList )
            {
                object[] objects = member.GetCustomAttributes(typeof(ResultSetAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteResultSet(writer, member, memberAttrib as ResultSetAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(ResultSetAttribute), attribute);
            // Element: <query>
            System.Collections.ArrayList QueryList = FindAttributedMembers( attribute, typeof(QueryAttribute), type );
            foreach( System.Reflection.MemberInfo member in QueryList )
            {
                object[] objects = member.GetCustomAttributes(typeof(QueryAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteQuery(writer, member, memberAttrib as QueryAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(QueryAttribute), attribute);
            // Element: <sql-query>
            System.Collections.ArrayList SqlQueryList = FindAttributedMembers( attribute, typeof(SqlQueryAttribute), type );
            foreach( System.Reflection.MemberInfo member in SqlQueryList )
            {
                object[] objects = member.GetCustomAttributes(typeof(SqlQueryAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteSqlQuery(writer, member, memberAttrib as SqlQueryAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(SqlQueryAttribute), attribute);
            // Element: <filter-def>
            System.Collections.ArrayList FilterDefList = FindAttributedMembers( attribute, typeof(FilterDefAttribute), type );
            foreach( System.Reflection.MemberInfo member in FilterDefList )
            {
                object[] objects = member.GetCustomAttributes(typeof(FilterDefAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteFilterDef(writer, member, memberAttrib as FilterDefAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(FilterDefAttribute), attribute);
            // Element: <database-object>
            System.Collections.ArrayList DatabaseObjectList = FindAttributedMembers( attribute, typeof(DatabaseObjectAttribute), type );
            foreach( System.Reflection.MemberInfo member in DatabaseObjectList )
            {
                object[] objects = member.GetCustomAttributes(typeof(DatabaseObjectAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteDatabaseObject(writer, member, memberAttrib as DatabaseObjectAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(DatabaseObjectAttribute), attribute);

            writer.WriteEndElement();
        }
Example #36
0
		public override System.Collections.ICollection GetTerms()
		{
			System.Collections.ArrayList terms = new System.Collections.ArrayList();
			System.Collections.IEnumerator i = clauses.GetEnumerator();
			while (i.MoveNext())
			{
				SpanQuery clause = (SpanQuery) i.Current;
                //{{}}// _SupportClass.ICollectionSupport.AddAll(terms, clause.GetTerms()); // {{Aroush}}
                terms.AddRange(clause.GetTerms());
			}
			return terms;
		}
        public virtual void  TestNorms()
        {
            // tmp dir
            System.String tempDir = System.IO.Path.GetTempPath();
            if (tempDir == null)
            {
                throw new System.IO.IOException("java.io.tmpdir undefined, cannot run test");
            }

            // test with a single index: index1
            System.IO.FileInfo indexDir1 = new System.IO.FileInfo(System.IO.Path.Combine(tempDir, "lucenetestindex1"));
            Directory          dir1      = FSDirectory.Open(indexDir1);

            IndexWriter.Unlock(dir1);

            norms         = new System.Collections.ArrayList();
            modifiedNorms = new System.Collections.ArrayList();

            CreateIndex(dir1);
            DoTestNorms(dir1);

            // test with a single index: index2
            System.Collections.ArrayList norms1         = norms;
            System.Collections.ArrayList modifiedNorms1 = modifiedNorms;
            int numDocNorms1 = numDocNorms;

            norms         = new System.Collections.ArrayList();
            modifiedNorms = new System.Collections.ArrayList();
            numDocNorms   = 0;

            System.IO.FileInfo indexDir2 = new System.IO.FileInfo(System.IO.Path.Combine(tempDir, "lucenetestindex2"));
            Directory          dir2      = FSDirectory.Open(indexDir2);

            CreateIndex(dir2);
            DoTestNorms(dir2);

            // add index1 and index2 to a third index: index3
            System.IO.FileInfo indexDir3 = new System.IO.FileInfo(System.IO.Path.Combine(tempDir, "lucenetestindex3"));
            Directory          dir3      = FSDirectory.Open(indexDir3);

            CreateIndex(dir3);
            IndexWriter iw = new IndexWriter(dir3, anlzr, false, IndexWriter.MaxFieldLength.LIMITED);

            iw.SetMaxBufferedDocs(5);
            iw.SetMergeFactor(3);
            iw.AddIndexes(new Directory[] { dir1, dir2 });
            iw.Close();

            norms1.AddRange(norms);
            norms = norms1;
            modifiedNorms1.AddRange(modifiedNorms);
            modifiedNorms = modifiedNorms1;
            numDocNorms  += numDocNorms1;

            // test with index3
            VerifyIndex(dir3);
            DoTestNorms(dir3);

            // now with optimize
            iw = new IndexWriter(dir3, anlzr, false, IndexWriter.MaxFieldLength.LIMITED);
            iw.SetMaxBufferedDocs(5);
            iw.SetMergeFactor(3);
            iw.Optimize();
            iw.Close();
            VerifyIndex(dir3);

            dir1.Close();
            dir2.Close();
            dir3.Close();
        }
Example #38
0
        static void Main(string[] args)
        {
            // Colecciones adentro de System.Collection
            // ArrayList
            // BitArray
            // Hashtable (k,v)
            // Queue
            // SortedList (k,v) k,v
            // Stack
            int       r    = 0;
            Coleccion show = new Coleccion();

            #region https://youtu.be/GAal3fPN59g
            System.Collections.ArrayList Palabras =
                new System.Collections.ArrayList();

            // Podemos adiccionar con rango
            Palabras.AddRange(new System.String[] {
                "Hola", "como", "estas?"
            });

            CountElement.Count(Palabras);

            // Recorremos el Array con loop for
            show.Show(Palabras, 2);

            // Agragar mas palabra
            Palabras.Add("Bien y tu?");
            // Volvemos a mostrar el total de elementos
            CountElement.Count(Palabras);

            //Recorriendo con foreach
            show.ShowForeach(Palabras, 2);

            #endregion

            #region https://youtu.be/bdGSQ-9N22s
            // Array con valores numericos
            System.Collections.ArrayList Valores =
                new System.Collections.ArrayList();

            Valores.AddRange(new int[] { 5, 6 });
            Valores.Add(7);
            Valores.Add(8);

            ////
            CountElement.Count(Valores);
            ////

            // Recorremos con loop for
            show.Show(Valores, 1, r);


            // Verificar si existe un elemento en el ArrayList
            //con el metodo Contains()
            System.Console.WriteLine(" 5 existe " + Valores.Contains(5));
            System.Console.WriteLine(" 1 existe {0}", Valores.Contains(1));
            System.Console.Write("--------\n");

            // Insertamos en un indice en particular
            Valores.Insert(2, 4);

            ////
            CountElement.Count(Valores);
            ////

            show.ShowForeach(Valores, 2);

            // Remover un elemento
            Valores.Remove(4);
            CountElement.Count(Valores);
            show.Show(Valores, 1, r);

            // Remover en una posicion
            Valores.RemoveAt(0);
            CountElement.Count(Valores);
            show.Show(Valores, 1, r);
            #endregion
            System.Console.ReadKey();
        }
Example #39
0
 /// <summary>Returns a collection of all terms matched by this query.</summary>
 /// <deprecated> use ExtractTerms instead
 /// </deprecated>
 /// <seealso cref="#ExtractTerms(Set)">
 /// </seealso>
 public override System.Collections.ICollection GetTerms()
 {
     System.Collections.ArrayList terms = new System.Collections.ArrayList();
     System.Collections.IEnumerator i = clauses.GetEnumerator();
     while (i.MoveNext())
     {
         SpanQuery clause = (SpanQuery) i.Current;
         terms.AddRange(clause.GetTerms());
     }
     return terms;
 }
        /// <summary>
        /// Transform the string into integers representing the Code128 codes
        /// necessary to represent it
        /// </summary>
        /// <param name="AsciiData">String to be encoded</param>
        /// <returns>Code128 representation</returns>
        private int[] StringToCode128( string AsciiData )
        {
            // turn the string into ascii byte data
             byte[] asciiBytes = Encoding.ASCII.GetBytes( AsciiData );

             // decide which codeset to start with
             Code128Code.CodeSetAllowed csa1 = asciiBytes.Length>0 ? Code128Code.CodesetAllowedForChar( asciiBytes[0] ) : Code128Code.CodeSetAllowed.CodeAorB;
             Code128Code.CodeSetAllowed csa2 = asciiBytes.Length>0 ? Code128Code.CodesetAllowedForChar( asciiBytes[1] ) : Code128Code.CodeSetAllowed.CodeAorB;
             CodeSet currcs = GetBestStartSet(csa1,csa2);

             // set up the beginning of the barcode
             System.Collections.ArrayList codes = new System.Collections.ArrayList(asciiBytes.Length + 3); // assume no codeset changes, account for start, checksum, and stop
             codes.Add(Code128Code.StartCodeForCodeSet(currcs));

             // add the codes for each character in the string
             for (int i = 0; i < asciiBytes.Length; i++)
             {
            int thischar = asciiBytes[i];
            int nextchar = asciiBytes.Length>(i+1) ? asciiBytes[i+1] : -1;

            codes.AddRange( Code128Code.CodesForChar(thischar, nextchar, ref currcs) );
             }

             // calculate the check digit
             int checksum = (int)(codes[0]);
             for (int i = 1; i < codes.Count; i++)
             {
            checksum += i * (int)(codes[i]);
             }
             codes.Add( checksum % 103 );

             codes.Add( Code128Code.StopCode() );

             int[] result = codes.ToArray(typeof(int)) as int[];
             return result;
        }
        protected void InsertImaginaryIndentDedentTokens()
        {
            IToken t = stream.LT(1);

            stream.Consume();
            IList hiddenTokens;

            // if not a NEWLINE, doesn't signal indent/dedent work; just enqueue
            if (t.Type != PythonLexer.NEWLINE)
            {
                hiddenTokens = stream.GetTokens(lastTokenAddedIndex + 1, t.TokenIndex - 1);
                if (hiddenTokens != null)
                {
                    tokens.AddRange(hiddenTokens);
                }
                lastTokenAddedIndex = t.TokenIndex;
                tokens.Add(t);
                return;
            }

            // we know it's a newline

            BitSet hidden = BitSet.Of(PythonLexer.COMMENT,
                                      PythonLexer.LEADING_WS,
                                      PythonLexer.CONTINUED_LINE,
                                      PythonLexer.NEWLINE);

            hidden.Add(PythonLexer.WS);

            // save NEWLINE in the queue
            //System.out.println("found newline: "+t+" stack is "+StackString());
            hiddenTokens = stream.GetTokens(lastTokenAddedIndex + 1, t.TokenIndex - 1, hidden);

            if (hiddenTokens != null)
            {
                tokens.AddRange(hiddenTokens);
            }
            lastTokenAddedIndex = t.TokenIndex;
            tokens.Add(t);

            // grab first token of next line
            t = stream.LT(1);
            stream.Consume();
            hiddenTokens = stream.GetTokens(lastTokenAddedIndex + 1, t.TokenIndex - 1, hidden);

            if (hiddenTokens != null)
            {
                tokens.AddRange(hiddenTokens);
            }
            lastTokenAddedIndex = t.TokenIndex;

            // compute cpos as the char pos of next non-WS token in line
            int cpos = t.CharPositionInLine;             // column dictates indent/dedent

            if (t.Type == TokenTypes.EndOfFile)
            {
                cpos = -1;                 // pretend EOF always happens at left edge
            }
            else if (t.Type == PythonLexer.LEADING_WS)
            {
                cpos = t.Text.Length;
            }

            //System.out.println("next token is: "+t);

            // compare to last indent level
            int lastIndent = Peek();

            //System.out.println("cpos, lastIndent = "+cpos+", "+lastIndent);

            if (cpos > lastIndent)
            {             // they indented; track and gen INDENT
                Push(cpos);
                //System.out.println("Push("+cpos+"): "+StackString());
                IToken indent = new ClassicToken(PythonParser.INDENT, "");
                indent.CharPositionInLine = t.CharPositionInLine;
                indent.Line = t.Line;
                tokens.Add(indent);
            }
            else if (cpos < lastIndent)
            {             // they dedented
                // how far back did we dedent?
                int prevIndex = FindPreviousIndent(cpos);
                //System.out.println("dedented; prevIndex of cpos="+cpos+" is "+prevIndex);
                // generate DEDENTs for each indent level we backed up over
                for (int d = sp - 1; d >= prevIndex; d--)
                {
                    IToken dedent = new ClassicToken(PythonParser.DEDENT, "");
                    dedent.CharPositionInLine = t.CharPositionInLine;
                    dedent.Line = t.Line;
                    tokens.Add(dedent);
                }
                sp = prevIndex;                 // pop those off indent level
            }
            if (t.Type != PythonLexer.LEADING_WS)
            {             // discard WS
                tokens.Add(t);
            }
        }
Example #42
0
        public string[] GetFriends(int m_id)
        {
            string[] arrResult = null;
            string strRet = null;
            string[] friends = null;
            try
            {
                strRet = HttpHelper.GetPage("http://www.kaixin001.com/friend/?uid=" + m_id.ToString(), cookie);
                friends = GetMatchs(@"<a href=""/home/\?uid=(?<text1>[\d]*?)"" title=""(?<text2>[^<>]*?)"">", strRet);

                string[] pages = GetMatchs(@"<a href=""\?uid=(?<text1>[\d]*?)&viewtype=&start=(?<text2>[\d]*?)"" class=fy onfocus=""this.blur\(\);"">(?<text3>[\d]*?)</a>", strRet);

                System.Collections.ArrayList sc = new System.Collections.ArrayList();
                sc.AddRange(friends);

                if (pages.Length > 0)
                {
                    for(int linki=0;linki<pages.Length;linki++)
                    {
                        string link = "http://www.kaixin001.com/friend/?uid=" + m_id.ToString() + "&viewtype=&start=" + pages[linki].Substring(pages[linki].IndexOf('_') + 1, pages[linki].Length - (pages[linki].IndexOf('_') + 1));
                        string pageContent = HttpHelper.GetPage(link, cookie);
                        sc.AddRange(GetMatchs(@"<a href=""/home/\?uid=(?<text1>[\d]*?)"" title=""(?<text2>[^<>]*?)"">", pageContent));

                    }

                }
                arrResult = (String[])sc.ToArray(typeof(string));
            }
            catch
            {
                arrResult = null;
            }
            return arrResult;
        }
Example #43
0
        private clsAppSampleGroupCollection m_objGenerateAppSampleGroups()
        {
            m_objGenerateAppUnitItems();
            clsAppSampleGroupCollection objSampleGroups = new clsAppSampleGroupCollection();

            clsDomainController_SampleGroupManage objSampleGroupManage = new clsDomainController_SampleGroupManage();

            foreach (clsLIS_AppApplyUnit objAppUnit in m_objAppApplyUnits)
            {
                bool blnAppSampleGroupExist        = false;
                clsSampleGroup_VO objSampleGroupVO = null;
                long lngRes = objSampleGroupManage.m_lngGetSampleGoupVOByApplyUnitID(objAppUnit.m_StrApplyUnitID, out objSampleGroupVO);
                if (lngRes > 0 && objSampleGroupVO != null)
                {
//					objAppCheckItem.m_StrSampleGroupID = objSampleGroupVO.strSampleGroupID;
                    clsLIS_AppSampleGroup objAppSampleGroup = null;
                    foreach (clsLIS_AppSampleGroup obj in objSampleGroups)
                    {
                        if (obj.m_ObjSampleGroup.m_ObjDataVO.strSampleGroupID == objSampleGroupVO.strSampleGroupID)
                        {
                            objAppSampleGroup      = obj;
                            blnAppSampleGroupExist = true;
                            break;
                        }
                    }
                    if (!blnAppSampleGroupExist)
                    {
                        clsLIS_SampleGroup objSampleGroup = new clsLIS_SampleGroup();
                        objSampleGroup.m_ObjDataVO = objSampleGroupVO;
                        clsT_OPR_LIS_APP_SAMPLE_VO objAppSampleGroupVO = new clsT_OPR_LIS_APP_SAMPLE_VO();
                        clsLIS_AppSampleGroup      objAppSGroup        = new clsLIS_AppSampleGroup(objAppSampleGroupVO);
                        objAppSGroup.m_ObjSampleGroup   = objSampleGroup;
                        objAppSGroup.m_StrSampleGroupID = objSampleGroup.m_ObjDataVO.strSampleGroupID;
                        objSampleGroups.Add(objAppSGroup);
                        objAppSampleGroup = objAppSGroup;
                    }
                    System.Collections.ArrayList arlSU = new System.Collections.ArrayList();
                    if (objAppSampleGroup.m_ObjAppUnitArr != null)
                    {
                        arlSU.AddRange(objAppSampleGroup.m_ObjAppUnitArr);
                    }
                    arlSU.Add(objAppUnit);
                    objAppSampleGroup.m_ObjAppUnitArr = (clsLIS_AppApplyUnit[])arlSU.ToArray(typeof(clsLIS_AppApplyUnit));

                    for (int i = 0; i < objAppUnit.m_ObjItemArr.Length; i++)
                    {
                        bool blnItemExist = false;
                        foreach (clsLIS_AppCheckItem objAppItem in objAppSampleGroup.m_ObjAppCheckItems)
                        {
                            if (objAppItem.m_StrCheckItemID == objAppUnit.m_ObjItemArr[i].m_strCHECK_ITEM_ID_CHR)
                            {
                                blnItemExist = true;
                                break;
                            }
                        }
                        if (!blnItemExist)
                        {
                            clsT_OPR_LIS_APP_CHECK_ITEM_VO objAppItemVO    = new clsT_OPR_LIS_APP_CHECK_ITEM_VO();
                            clsLIS_AppCheckItem            objAppCheckItem = new clsLIS_AppCheckItem(objAppItemVO);

                            objAppCheckItem.m_StrCheckItemID               = objAppUnit.m_ObjItemArr[i].m_strCHECK_ITEM_ID_CHR;
                            objAppCheckItem.m_StrSampleGroupID             = objAppSampleGroup.m_StrSampleGroupID;
                            objAppCheckItem.m_ObjDataVO.m_strItemprice_mny = objAppUnit.m_ObjItemArr[i].m_strItemprice_mny;

                            objAppSampleGroup.m_ObjAppCheckItems.Add(objAppCheckItem);
                        }
                    }
                }
            }
            return(objSampleGroups);
        }
Example #44
0
		public static void  IndexSerial(System.Collections.IDictionary docs, Directory dir)
		{
			IndexWriter w = new IndexWriter(dir, new WhitespaceAnalyzer(), IndexWriter.MaxFieldLength.UNLIMITED);
			
			// index all docs in a single thread
			System.Collections.IEnumerator iter = docs.Values.GetEnumerator();
			while (iter.MoveNext())
			{
				Document d = (Document) iter.Current;
				System.Collections.ArrayList fields = new System.Collections.ArrayList();
				fields.AddRange(d.GetFields());
				// put fields in same order each time
                //{{Lucene.Net-2.9.1}} No, don't change the order of the fields
				//SupportClass.CollectionsHelper.Sort(fields, fieldNameComparator);
				
				Document d1 = new Document();
				d1.SetBoost(d.GetBoost());
				for (int i = 0; i < fields.Count; i++)
				{
					d1.Add((Fieldable) fields[i]);
				}
				w.AddDocument(d1);
				// System.out.println("indexing "+d1);
			}
			
			w.Close();
		}
Example #45
0
        private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            System.Collections.ArrayList counters = new System.Collections.ArrayList();

            if (this.listBox2.SelectedIndex != -1)
            {
                System.Diagnostics.PerformanceCounterCategory selectedPerfCat = new System.Diagnostics.PerformanceCounterCategory(this.listBox1.SelectedItem.ToString());
                string selectedInstance = this.listBox2.SelectedItem.ToString();
                this.listBox3.Items.Clear();

                try
                {
                    counters.AddRange(selectedPerfCat.GetCounters(selectedInstance));

                    foreach (System.Diagnostics.PerformanceCounter counter in counters)
                    {
                        this.listBox3.Items.Add(counter.CounterName);
                    }

                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("Unable to list the counters for this category:\n" + ex.Message);
                }
            }
        }
        public void Default_AddRange(int[] items, int capacity)
        {
            var arrayList = new System.Collections.ArrayList(capacity);

            arrayList.AddRange(items);
        }
Example #47
0
        private void StreamFile()
        {
            string strPath;


            FileStream fileStream = new FileStream(txtPath.Text,
                                                   FileMode.Open,
                                                   FileAccess.Read,
                                                   FileShare.Read);

            StreamReader objStream = new StreamReader(fileStream);

            strPath = "\\\\sqlserver01\\imports\\MedicalWeighted_" + DateTime.Today.ToString("MM-dd-yyyy") + ".txt";
            StreamWriter objWrite = new StreamWriter(strPath); //("C:\\Users\\jeremyp\\Documents\\Development\\Medical\\htcMedical\\DataDumps\\NewFile.txt");
            string       strLine;
            int          j = 0;

            System.Collections.ArrayList objList = new System.Collections.ArrayList();


            while ((strLine = objStream.ReadLine()) != null)
            {
                string[] arLine;
                if (j > 0)
                {
                    //hardcode to remove a comma from the provider's name
                    strLine = Regex.Replace(strLine, "MELNICK,", "MELNICK");
                    //hardcode to sync provider's name with DB
                    strLine = Regex.Replace(strLine, "LINDA ANNE TROUTMAN ZELOWS", "Linda Zelows");
                    //hardcode to sync provider's name with DB
                    strLine = Regex.Replace(strLine, "LAURA ANN SMITH-CREASER", "Laura Creaser");
                    //hardcode to sync provider's name with DB
                    strLine = Regex.Replace(strLine, "CYNTHIA LYNN GRIFFIN LMHC", "Cynthia Griffin");

                    // replacing commas, double-quotes and whitespace
                    strLine = Regex.Replace(strLine, ",", "|");
                    strLine = Regex.Replace(strLine, "\"", "");


                    arLine    = strLine.Split('|');
                    arLine[1] = Regex.Replace(arLine[1], "%", "");
                    arLine[1] = Regex.Replace(arLine[1], ">", "");
                    arLine[2] = Regex.Replace(arLine[2], "%", "");
                    arLine[2] = Regex.Replace(arLine[2], ">", "");
                    //removing middle initial from string(provider's name)
                    arLine[8] = Regex.Replace(arLine[8], "\\w\\.\\040", "");
                    arLine[8] = Regex.Replace(arLine[8], "\\040\\w\\040", " ");
                    objList.AddRange(arLine[8].Split(' '));
                    if (objList.Count > 2)
                    {
                        do
                        {
                            objList.RemoveAt(2);
                        } while (objList.Count > 2);
                    }
                    string[] arField = (string[])objList.ToArray(typeof(string));
                    arLine[8] = string.Join("|", arField);
                    objList.Clear();

                    strLine = string.Join("|", arLine);
                    strLine = Regex.Replace(strLine, " ", "");
                    strLine = CreateSubstring(strLine);


                    objWrite.WriteLine(strLine);

                    /*
                     * for (int t = 0; t <= 3; t++)
                     * {
                     *  strLine = strLine.Substring(0, strLine.LastIndexOf('|'));
                     * }
                     *  objWrite.WriteLine(strLine + "||");
                     */
                }
                j++;
            }

            objStream.Close();
            objWrite.Close();
        }
Example #48
0
        private void ReadDirectoryContents(string current_directory, out string[] new_directory_parts)
        {
            if (current_directory == "/")
            {
                new_directory_parts     = new string[] { "" };
                currentDirectoryMatches = false;
            }
            else
            {
                string[] drives = Directory.GetLogicalDrives();

                if (Array.IndexOf(drives, current_directory) != -1)
                {
                    BrowserType = BrowserType.LOGICAL_DRIVE;
                    //currentDirectory = " Pick Logical Drive to Browse";
                }

                //currentDirectory= currentDirectory.Trim(Path.GetInvalidFileNameChars());
                //currentDirectory = currentDirectory.Replace(" ", "_");
                Path.GetInvalidFileNameChars();

                new_directory_parts = current_directory.Split(Path.DirectorySeparatorChar);

                if (DirectorySelectionPattern != null)
                {
                    string[] generation = new string[0];

                    if (BrowserType != BrowserType.LOGICAL_DRIVE)
                    {
                        generation = Directory.GetDirectories(Path.GetDirectoryName(current_directory), DirectorySelectionPattern);
                    }
                    currentDirectoryMatches = Array.IndexOf(generation, current_directory) >= 0;
                }
                else
                {
                    currentDirectoryMatches = false;
                }
            }

            if (BrowserType == BrowserType.FILE || DirectorySelectionPattern == null)
            {
                directories            = Directory.GetDirectories(current_directory);
                nonMatchingDirectories = new string[0];
            }
            else if (BrowserType == BrowserType.LOGICAL_DRIVE)
            {
                directories            = Directory.GetLogicalDrives();
                nonMatchingDirectories = new string[0];
                nonMatchingFiles       = new string[0];
            }
            else
            {
                directories = Directory.GetDirectories(current_directory, DirectorySelectionPattern);
                string[] all_directory            = Directory.GetDirectories(current_directory);
                var      non_matching_directories = new List <string>();

                foreach (string directoryPath in all_directory)
                {
                    if (Array.IndexOf(directories, directoryPath) < 0)
                    {
                        non_matching_directories.Add(directoryPath);
                    }
                }

                nonMatchingDirectories = non_matching_directories.ToArray();

                for (int i = 0; i < nonMatchingDirectories.Length; ++i)
                {
                    int last_separator = nonMatchingDirectories[i].LastIndexOf(Path.DirectorySeparatorChar);
                    nonMatchingDirectories[i] = nonMatchingDirectories[i].Substring(last_separator + 1);
                }

                Array.Sort(nonMatchingDirectories);
            }

            if ((BrowserType != BrowserType.LOGICAL_DRIVE))
            {
                for (int i = 0; i < directories.Length; ++i)
                {
                    directories[i] = directories[i].Substring(directories[i].LastIndexOf(Path.DirectorySeparatorChar) + 1);
                }
            }

            if (BrowserType == BrowserType.DIRECTORY || FileSelectionPattern == null)
            {
                files            = Directory.GetFiles(current_directory);
                nonMatchingFiles = new string[0];
            }
            else
            {
                // ArrayList will hold all file names
                System.Collections.ArrayList al_files = new System.Collections.ArrayList();

                // Create an array of filter string
                string[] multiple_filters = FileSelectionPattern.Split(';');

                // for each filter find mathing file names
                foreach (string FileFilter in multiple_filters)
                {
                    // add found file names to array list
                    al_files.AddRange(Directory.GetFiles(current_directory, FileFilter, SearchOption.TopDirectoryOnly));
                }

                // get the string array of relevant file names
                files = (string[])al_files.ToArray(typeof(string));

                var non_matching_files = new List <string>();

                foreach (string filePath in Directory.GetFiles(current_directory))
                {
                    if (Array.IndexOf(files, filePath) < 0)
                    {
                        non_matching_files.Add(filePath);
                    }
                }

                nonMatchingFiles = non_matching_files.ToArray();

                for (int i = 0; i < nonMatchingFiles.Length; ++i)
                {
                    nonMatchingFiles[i] = Path.GetFileName(nonMatchingFiles[i]);
                }

                Array.Sort(nonMatchingFiles);
            }

            for (int i = 0; i < files.Length; ++i)
            {
                files[i] = Path.GetFileName(files[i]);
            }

            Array.Sort(files);

            BuildContent();
        }
Example #49
0
        public static void  Main(System.String[] args)
        {
            /*TODO: Change dS and dI to decrease injuries and suspensions of all teams, even those who
             * haven't played a match*/
            bool injuries = false, suspensions = false, rosters = false, injList = true, susList = true;

            System.String xls = null;

            for (int i = 0; i < args.Length; i++)
            {
                /* Parse parameter */
                if (args[i].ToLower().StartsWith("-di"))
                {
                    injuries = true;
                }
                else if (args[i].ToLower().StartsWith("-ds"))
                {
                    suspensions = true;
                }
                else if (args[i].ToLower().StartsWith("-ur"))
                {
                    rosters = true;
                }
                else if (args[i].ToLower().StartsWith("-x:"))
                {
                    xls = args[i].Substring(3);
                }
                else if (args[i].ToLower().StartsWith("-xe:"))
                {
                    externalUrl = args[i].Substring(4);
                }
                else if (args[i].ToLower().StartsWith("-xi:"))
                {
                    externalUrli = args[i].Substring(4);
                }
                else if (args[i].ToLower().StartsWith("-xs:"))
                {
                    externalUrls = args[i].Substring(4);
                }
                else if (args[i].ToLower().StartsWith("-xf:"))
                {
                    externalUrlf = args[i].Substring(4);
                }
                else if (args[i].ToLower().StartsWith("-f:"))
                {
                    fixtureFile = args[i].Substring(3);
                }
                else if (args[i].ToLower().Equals("-h"))
                {
                    help();
                }
                else
                {
                    System.Console.Out.WriteLine("Illegal parameter passed to League Updater : use 'java " + commandname + " -h' for help");
                    System.Environment.Exit(-1);
                }
            }

            System.Console.Out.WriteLine(Version.FullVersion);
            System.Console.Out.WriteLine();

            Config.loadConfig("league.xml");

            if (!injuries && !suspensions && !rosters)
            {
                injuries    = true;
                suspensions = true;
                rosters     = true;
            }

            Match[] matches;

            if (fixtureFile == null)
            {
                MatchesParser MP = new MatchesParser();
                matches = MP.Matches;
            }
            else
            {
                FixtureParser FP = new FixtureParser(fixtureFile, externalUrlf);
                MatchesParser MP = new MatchesParser(FP.Commentaries);
                matches         = MP.Matches;
                competitionName = FP.CompetitionName;
                FP.updateFixtures(matches);
            }
            try
            {
                if (injuries)
                {
                    for (int i = 0; i < matches.Length; i++)
                    {
                        matches[i].decreaseInjuries();
                        System.Console.Out.WriteLine("Decreased injuries in team " + matches[i].HomeTeam);
                        System.Console.Out.WriteLine("Decreased injuries in team " + matches[i].AwayTeam);
                    }
                }
                if (suspensions)
                {
                    for (int i = 0; i < matches.Length; i++)
                    {
                        matches[i].decreaseSuspensions();
                        System.Console.Out.WriteLine("Decreased suspensions in team " + matches[i].HomeTeam);
                        System.Console.Out.WriteLine("Decreased suspensions in team " + matches[i].AwayTeam);
                    }
                }
                if (rosters)
                {
                    for (int i = 0; i < matches.Length; i++)
                    {
                        matches[i].updateRosters();
                        System.Console.Out.WriteLine("Updated roster for team " + matches[i].HomeTeam);
                        System.Console.Out.WriteLine("Updated roster for team " + matches[i].AwayTeam);
                    }
                }

                if (injList)
                {
                    System.Collections.ArrayList injured = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));
                    for (int i = 0; i < matches.Length; i++)
                    {
                        injured.AddRange(matches[i].Injured());
                    }
                    //Write the file
                    //UPGRADE_TODO: Constructor 'java.io.OutputStreamWriter.OutputStreamWriter' was converted to 'System.IO.StreamWriter.StreamWriter' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioOutputStreamWriterOutputStreamWriter_javaioOutputStream_javalangString'"
                    //UPGRADE_TODO: Constructor 'java.io.FileOutputStream.FileOutputStream' was converted to 'System.IO.FileStream.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioFileOutputStreamFileOutputStream_javalangString'"
                    System.IO.StreamWriter FW = new System.IO.StreamWriter(new System.IO.FileStream("injured.xml", System.IO.FileMode.Create), System.Text.Encoding.GetEncoding("iso-8859-1"));
                    writeInjured(FW, injured);
                    System.Console.Out.WriteLine("Injured List written in the Injured.xml file");
                }
                if (susList)
                {
                    System.Collections.ArrayList suspended = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));
                    for (int i = 0; i < matches.Length; i++)
                    {
                        suspended.AddRange(matches[i].Suspended());
                    }
                    //Write the file
                    //UPGRADE_TODO: Constructor 'java.io.OutputStreamWriter.OutputStreamWriter' was converted to 'System.IO.StreamWriter.StreamWriter' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioOutputStreamWriterOutputStreamWriter_javaioOutputStream_javalangString'"
                    //UPGRADE_TODO: Constructor 'java.io.FileOutputStream.FileOutputStream' was converted to 'System.IO.FileStream.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioFileOutputStreamFileOutputStream_javalangString'"
                    System.IO.StreamWriter FW = new System.IO.StreamWriter(new System.IO.FileStream("suspended.xml", System.IO.FileMode.Create), System.Text.Encoding.GetEncoding("iso-8859-1"));
                    writeSuspended(FW, suspended);
                    System.Console.Out.WriteLine("Suspension List written in the Suspended.xml file");
                }
            }
            catch (System.Exception err)
            {
                System.Console.Out.WriteLine("Error found while applying actions.");
                SupportClass.WriteStackTrace(err, Console.Error);
                System.Environment.Exit(-1);
            }
        }
Example #50
0
        /// <summary> Write a Component XML Element from attributes in a type. </summary>
        public virtual void WriteComponent(System.Xml.XmlWriter writer, System.Type type)
        {
            object[] attributes = type.GetCustomAttributes(typeof(ComponentAttribute), false);
            if(attributes.Length == 0)
                return;
            ComponentAttribute attribute = attributes[0] as ComponentAttribute;

            writer.WriteStartElement( "component" );
            // Attribute: <class>
            if(attribute.Class != null)
            writer.WriteAttributeString("class", GetAttributeValue(attribute.Class, type));
            // Attribute: <name>
            writer.WriteAttributeString("name", attribute.Name==null ? DefaultHelper.Get_Component_Name_DefaultValue(type) : GetAttributeValue(attribute.Name, type));
            // Attribute: <access>
            if(attribute.Access != null)
            writer.WriteAttributeString("access", GetAttributeValue(attribute.Access, type));
            // Attribute: <unique>
            if( attribute.UniqueSpecified )
            writer.WriteAttributeString("unique", attribute.Unique ? "true" : "false");
            // Attribute: <update>
            if( attribute.UpdateSpecified )
            writer.WriteAttributeString("update", attribute.Update ? "true" : "false");
            // Attribute: <insert>
            if( attribute.InsertSpecified )
            writer.WriteAttributeString("insert", attribute.Insert ? "true" : "false");
            // Attribute: <lazy>
            if( attribute.LazySpecified )
            writer.WriteAttributeString("lazy", attribute.Lazy ? "true" : "false");
            // Attribute: <optimistic-lock>
            if( attribute.OptimisticLockSpecified )
            writer.WriteAttributeString("optimistic-lock", attribute.OptimisticLock ? "true" : "false");
            // Attribute: <node>
            if(attribute.Node != null)
            writer.WriteAttributeString("node", GetAttributeValue(attribute.Node, type));

            WriteUserDefinedContent(writer, type, null, attribute);
            // Element: <meta>
            System.Collections.ArrayList MetaList = FindAttributedMembers( attribute, typeof(MetaAttribute), type );
            foreach( System.Reflection.MemberInfo member in MetaList )
            {
                object[] objects = member.GetCustomAttributes(typeof(MetaAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteMeta(writer, member, memberAttrib as MetaAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(MetaAttribute), attribute);
            // Element: <tuplizer>
            System.Collections.ArrayList TuplizerList = FindAttributedMembers( attribute, typeof(TuplizerAttribute), type );
            foreach( System.Reflection.MemberInfo member in TuplizerList )
            {
                object[] objects = member.GetCustomAttributes(typeof(TuplizerAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteTuplizer(writer, member, memberAttrib as TuplizerAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(TuplizerAttribute), attribute);
            // Element: <parent>
            System.Collections.ArrayList ParentList = FindAttributedMembers( attribute, typeof(ParentAttribute), type );
            foreach( System.Reflection.MemberInfo member in ParentList )
            {
                object[] objects = member.GetCustomAttributes(typeof(ParentAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteParent(writer, member, memberAttrib as ParentAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(ParentAttribute), attribute);
            // Element: <property>
            System.Collections.ArrayList PropertyList = FindAttributedMembers( attribute, typeof(PropertyAttribute), type );
            foreach( System.Reflection.MemberInfo member in PropertyList )
            {
                object[] objects = member.GetCustomAttributes(typeof(PropertyAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteProperty(writer, member, memberAttrib as PropertyAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(PropertyAttribute), attribute);
            // Element: <many-to-one>
            System.Collections.ArrayList ManyToOneList = FindAttributedMembers( attribute, typeof(ManyToOneAttribute), type );
            foreach( System.Reflection.MemberInfo member in ManyToOneList )
            {
                object[] objects = member.GetCustomAttributes(typeof(ManyToOneAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteManyToOne(writer, member, memberAttrib as ManyToOneAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(ManyToOneAttribute), attribute);
            // Element: <one-to-one>
            System.Collections.ArrayList OneToOneList = FindAttributedMembers( attribute, typeof(OneToOneAttribute), type );
            foreach( System.Reflection.MemberInfo member in OneToOneList )
            {
                object[] objects = member.GetCustomAttributes(typeof(OneToOneAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteOneToOne(writer, member, memberAttrib as OneToOneAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(OneToOneAttribute), attribute);
            // Element: <component>
            WriteNestedComponentTypes(writer, type);
            WriteUserDefinedContent(writer, type, typeof(ComponentAttribute), attribute);
            // Element: <dynamic-component>
            System.Collections.ArrayList DynamicComponentList = FindAttributedMembers( attribute, typeof(DynamicComponentAttribute), type );
            foreach( System.Reflection.MemberInfo member in DynamicComponentList )
            {
                object[] objects = member.GetCustomAttributes(typeof(DynamicComponentAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                WriteDynamicComponent(writer, member, memberAttribs[0] as DynamicComponentAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(DynamicComponentAttribute), attribute);
            // Element: <any>
            System.Collections.ArrayList AnyList = FindAttributedMembers( attribute, typeof(AnyAttribute), type );
            foreach( System.Reflection.MemberInfo member in AnyList )
            {
                object[] objects = member.GetCustomAttributes(typeof(AnyAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteAny(writer, member, memberAttrib as AnyAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(AnyAttribute), attribute);
            // Element: <map>
            System.Collections.ArrayList MapList = FindAttributedMembers( attribute, typeof(MapAttribute), type );
            foreach( System.Reflection.MemberInfo member in MapList )
            {
                object[] objects = member.GetCustomAttributes(typeof(MapAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteMap(writer, member, memberAttrib as MapAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(MapAttribute), attribute);
            // Element: <set>
            System.Collections.ArrayList SetList = FindAttributedMembers( attribute, typeof(SetAttribute), type );
            foreach( System.Reflection.MemberInfo member in SetList )
            {
                object[] objects = member.GetCustomAttributes(typeof(SetAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteSet(writer, member, memberAttrib as SetAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(SetAttribute), attribute);
            // Element: <list>
            System.Collections.ArrayList ListList = FindAttributedMembers( attribute, typeof(ListAttribute), type );
            foreach( System.Reflection.MemberInfo member in ListList )
            {
                object[] objects = member.GetCustomAttributes(typeof(ListAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteList(writer, member, memberAttrib as ListAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(ListAttribute), attribute);
            // Element: <bag>
            System.Collections.ArrayList BagList = FindAttributedMembers( attribute, typeof(BagAttribute), type );
            foreach( System.Reflection.MemberInfo member in BagList )
            {
                object[] objects = member.GetCustomAttributes(typeof(BagAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteBag(writer, member, memberAttrib as BagAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(BagAttribute), attribute);
            // Element: <idbag>
            System.Collections.ArrayList IdBagList = FindAttributedMembers( attribute, typeof(IdBagAttribute), type );
            foreach( System.Reflection.MemberInfo member in IdBagList )
            {
                object[] objects = member.GetCustomAttributes(typeof(IdBagAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteIdBag(writer, member, memberAttrib as IdBagAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(IdBagAttribute), attribute);
            // Element: <array>
            System.Collections.ArrayList ArrayList = FindAttributedMembers( attribute, typeof(ArrayAttribute), type );
            foreach( System.Reflection.MemberInfo member in ArrayList )
            {
                object[] objects = member.GetCustomAttributes(typeof(ArrayAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteArray(writer, member, memberAttrib as ArrayAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(ArrayAttribute), attribute);
            // Element: <primitive-array>
            System.Collections.ArrayList PrimitiveArrayList = FindAttributedMembers( attribute, typeof(PrimitiveArrayAttribute), type );
            foreach( System.Reflection.MemberInfo member in PrimitiveArrayList )
            {
                object[] objects = member.GetCustomAttributes(typeof(PrimitiveArrayAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WritePrimitiveArray(writer, member, memberAttrib as PrimitiveArrayAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(PrimitiveArrayAttribute), attribute);

            writer.WriteEndElement();
        }
        public static void Validate <T>() where T : new()
        {
            object instance = new T();

            System.Reflection.PropertyInfo[] props = instance.GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);

            object[] defaults = new object[props.Length];
            for (int i = 0; i < props.Length; i++)
            {
                if (props[i].CanRead && props[i].CanWrite)
                {
                    defaults[i] = props[i].GetValue(instance, null);
                }
            }


            for (int i = 0; i < props.Length; i++)
            {
                if (!props[i].CanRead || !props[i].CanWrite)
                {
                    continue;
                }

                System.Collections.ArrayList values = new System.Collections.ArrayList();
                if (typeof(Enum).IsAssignableFrom(props[i].PropertyType))
                {
                    System.Reflection.FieldInfo[] enums = props[i].PropertyType.GetFields(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
                    foreach (System.Reflection.FieldInfo field in enums)
                    {
                        values.Add(field.GetValue(null));
                    }
                }
                else
                {
                    if (typeof(bool) == props[i].PropertyType)
                    {
                        values.AddRange(new object[] { true, false });
                    }
                    else
                    {
                        if (typeof(byte) == props[i].PropertyType)
                        {
                            for (int b = 0; b < 256; b++)
                            {
                                values.Add((byte)b);
                            }
                        }
                        else
                        {
                            if (typeof(int) == props[i].PropertyType)
                            {
                                continue;
                            }
                            throw new ArgumentException();
                        }
                    }
                }

                foreach (object value in values)
                {
                    props[i].SetValue(instance, value, null);

                    if (value.Equals(TextureFilter.PyramidalQuad) ||
                        value.Equals(TextureFilter.GaussianQuad) ||
                        (value.Equals(TextureFilter.Anisotropic) && props[i].Name == "MagFilter") ||
                        (value.Equals(TextureFilter.Anisotropic) && props[i].Name == "MipFilter"))
                    {
                        continue;//special cases :-)
                    }
                    if (props[i].GetValue(instance, null).Equals(value) == false)
                    {
                        throw new ArgumentException();
                    }

                    for (int p = 0; p < props.Length; p++)
                    {
                        if (!props[p].CanRead || !props[p].CanWrite)
                        {
                            continue;
                        }
                        if (p != i)
                        {
                            if (props[p].GetValue(instance, null).Equals(defaults[p]) == false)
                            {
                                throw new ArgumentException();
                            }
                        }
                    }
                }

                props[i].SetValue(instance, defaults[i], null);
            }
        }
Example #52
0
        /// <summary> Write a JoinedSubclass XML Element from attributes in a type. </summary>
        public virtual void WriteJoinedSubclass(System.Xml.XmlWriter writer, System.Type type)
        {
            object[] attributes = type.GetCustomAttributes(typeof(JoinedSubclassAttribute), false);
            if(attributes.Length == 0)
                return;
            JoinedSubclassAttribute attribute = attributes[0] as JoinedSubclassAttribute;

            writer.WriteStartElement( "joined-subclass" );
            // Attribute: <entity-name>
            if(attribute.EntityName != null)
            writer.WriteAttributeString("entity-name", GetAttributeValue(attribute.EntityName, type));
            // Attribute: <name>
            if(attribute.Name != null)
            writer.WriteAttributeString("name", GetAttributeValue(attribute.Name, type));
            // Attribute: <proxy>
            if(attribute.Proxy != null)
            writer.WriteAttributeString("proxy", GetAttributeValue(attribute.Proxy, type));
            // Attribute: <table>
            if(attribute.Table != null)
            writer.WriteAttributeString("table", GetAttributeValue(attribute.Table, type));
            // Attribute: <schema>
            if(attribute.Schema != null)
            writer.WriteAttributeString("schema", GetAttributeValue(attribute.Schema, type));
            // Attribute: <catalog>
            if(attribute.Catalog != null)
            writer.WriteAttributeString("catalog", GetAttributeValue(attribute.Catalog, type));
            // Attribute: <subselect>
            if(attribute.Subselect != null)
            writer.WriteAttributeString("subselect", GetAttributeValue(attribute.Subselect, type));
            // Attribute: <dynamic-update>
            if( attribute.DynamicUpdateSpecified )
            writer.WriteAttributeString("dynamic-update", attribute.DynamicUpdate ? "true" : "false");
            // Attribute: <dynamic-insert>
            if( attribute.DynamicInsertSpecified )
            writer.WriteAttributeString("dynamic-insert", attribute.DynamicInsert ? "true" : "false");
            // Attribute: <select-before-update>
            if( attribute.SelectBeforeUpdateSpecified )
            writer.WriteAttributeString("select-before-update", attribute.SelectBeforeUpdate ? "true" : "false");
            // Attribute: <extends>
            if(attribute.Extends != null)
            writer.WriteAttributeString("extends", GetAttributeValue(attribute.Extends, type));
            // Attribute: <lazy>
            if( attribute.LazySpecified )
            writer.WriteAttributeString("lazy", attribute.Lazy ? "true" : "false");
            // Attribute: <abstract>
            if( attribute.AbstractSpecified )
            writer.WriteAttributeString("abstract", attribute.Abstract ? "true" : "false");
            // Attribute: <persister>
            if(attribute.Persister != null)
            writer.WriteAttributeString("persister", GetAttributeValue(attribute.Persister, type));
            // Attribute: <check>
            if(attribute.Check != null)
            writer.WriteAttributeString("check", GetAttributeValue(attribute.Check, type));
            // Attribute: <batch-size>
            if(attribute.BatchSize != -1)
            writer.WriteAttributeString("batch-size", attribute.BatchSize.ToString());
            // Attribute: <node>
            if(attribute.Node != null)
            writer.WriteAttributeString("node", GetAttributeValue(attribute.Node, type));

            WriteUserDefinedContent(writer, type, null, attribute);
            // Element: <meta>
            System.Collections.ArrayList MetaList = FindAttributedMembers( attribute, typeof(MetaAttribute), type );
            foreach( System.Reflection.MemberInfo member in MetaList )
            {
                object[] objects = member.GetCustomAttributes(typeof(MetaAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteMeta(writer, member, memberAttrib as MetaAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(MetaAttribute), attribute);
            // Element: <subselect>
            System.Collections.ArrayList SubselectList = FindAttributedMembers( attribute, typeof(SubselectAttribute), type );
            foreach( System.Reflection.MemberInfo member in SubselectList )
            {
                object[] objects = member.GetCustomAttributes(typeof(SubselectAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteSubselect(writer, member, memberAttrib as SubselectAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(SubselectAttribute), attribute);
            // Element: <synchronize>
            System.Collections.ArrayList SynchronizeList = FindAttributedMembers( attribute, typeof(SynchronizeAttribute), type );
            foreach( System.Reflection.MemberInfo member in SynchronizeList )
            {
                object[] objects = member.GetCustomAttributes(typeof(SynchronizeAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteSynchronize(writer, member, memberAttrib as SynchronizeAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(SynchronizeAttribute), attribute);
            // Element: <comment>
            System.Collections.ArrayList CommentList = FindAttributedMembers( attribute, typeof(CommentAttribute), type );
            foreach( System.Reflection.MemberInfo member in CommentList )
            {
                object[] objects = member.GetCustomAttributes(typeof(CommentAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteComment(writer, member, memberAttrib as CommentAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(CommentAttribute), attribute);
            // Element: <tuplizer>
            System.Collections.ArrayList TuplizerList = FindAttributedMembers( attribute, typeof(TuplizerAttribute), type );
            foreach( System.Reflection.MemberInfo member in TuplizerList )
            {
                object[] objects = member.GetCustomAttributes(typeof(TuplizerAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteTuplizer(writer, member, memberAttrib as TuplizerAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(TuplizerAttribute), attribute);
            // Element: <key>
            System.Collections.ArrayList KeyList = FindAttributedMembers( attribute, typeof(KeyAttribute), type );
            foreach( System.Reflection.MemberInfo member in KeyList )
            {
                object[] objects = member.GetCustomAttributes(typeof(KeyAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteKey(writer, member, memberAttrib as KeyAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(KeyAttribute), attribute);
            // Element: <property>
            System.Collections.ArrayList PropertyList = FindAttributedMembers( attribute, typeof(PropertyAttribute), type );
            foreach( System.Reflection.MemberInfo member in PropertyList )
            {
                object[] objects = member.GetCustomAttributes(typeof(PropertyAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteProperty(writer, member, memberAttrib as PropertyAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(PropertyAttribute), attribute);
            // Element: <many-to-one>
            System.Collections.ArrayList ManyToOneList = FindAttributedMembers( attribute, typeof(ManyToOneAttribute), type );
            foreach( System.Reflection.MemberInfo member in ManyToOneList )
            {
                object[] objects = member.GetCustomAttributes(typeof(ManyToOneAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteManyToOne(writer, member, memberAttrib as ManyToOneAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(ManyToOneAttribute), attribute);
            // Element: <one-to-one>
            System.Collections.ArrayList OneToOneList = FindAttributedMembers( attribute, typeof(OneToOneAttribute), type );
            foreach( System.Reflection.MemberInfo member in OneToOneList )
            {
                object[] objects = member.GetCustomAttributes(typeof(OneToOneAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteOneToOne(writer, member, memberAttrib as OneToOneAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(OneToOneAttribute), attribute);
            // Element: <component>
            WriteNestedComponentTypes(writer, type);
            WriteUserDefinedContent(writer, type, typeof(ComponentAttribute), attribute);
            // Element: <dynamic-component>
            System.Collections.ArrayList DynamicComponentList = FindAttributedMembers( attribute, typeof(DynamicComponentAttribute), type );
            foreach( System.Reflection.MemberInfo member in DynamicComponentList )
            {
                object[] objects = member.GetCustomAttributes(typeof(DynamicComponentAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                WriteDynamicComponent(writer, member, memberAttribs[0] as DynamicComponentAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(DynamicComponentAttribute), attribute);
            // Element: <properties>
            System.Collections.ArrayList PropertiesList = FindAttributedMembers( attribute, typeof(PropertiesAttribute), type );
            foreach( System.Reflection.MemberInfo member in PropertiesList )
            {
                object[] objects = member.GetCustomAttributes(typeof(PropertiesAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteProperties(writer, member, memberAttrib as PropertiesAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(PropertiesAttribute), attribute);
            // Element: <any>
            System.Collections.ArrayList AnyList = FindAttributedMembers( attribute, typeof(AnyAttribute), type );
            foreach( System.Reflection.MemberInfo member in AnyList )
            {
                object[] objects = member.GetCustomAttributes(typeof(AnyAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteAny(writer, member, memberAttrib as AnyAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(AnyAttribute), attribute);
            // Element: <map>
            System.Collections.ArrayList MapList = FindAttributedMembers( attribute, typeof(MapAttribute), type );
            foreach( System.Reflection.MemberInfo member in MapList )
            {
                object[] objects = member.GetCustomAttributes(typeof(MapAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteMap(writer, member, memberAttrib as MapAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(MapAttribute), attribute);
            // Element: <set>
            System.Collections.ArrayList SetList = FindAttributedMembers( attribute, typeof(SetAttribute), type );
            foreach( System.Reflection.MemberInfo member in SetList )
            {
                object[] objects = member.GetCustomAttributes(typeof(SetAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteSet(writer, member, memberAttrib as SetAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(SetAttribute), attribute);
            // Element: <list>
            System.Collections.ArrayList ListList = FindAttributedMembers( attribute, typeof(ListAttribute), type );
            foreach( System.Reflection.MemberInfo member in ListList )
            {
                object[] objects = member.GetCustomAttributes(typeof(ListAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteList(writer, member, memberAttrib as ListAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(ListAttribute), attribute);
            // Element: <bag>
            System.Collections.ArrayList BagList = FindAttributedMembers( attribute, typeof(BagAttribute), type );
            foreach( System.Reflection.MemberInfo member in BagList )
            {
                object[] objects = member.GetCustomAttributes(typeof(BagAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteBag(writer, member, memberAttrib as BagAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(BagAttribute), attribute);
            // Element: <idbag>
            System.Collections.ArrayList IdBagList = FindAttributedMembers( attribute, typeof(IdBagAttribute), type );
            foreach( System.Reflection.MemberInfo member in IdBagList )
            {
                object[] objects = member.GetCustomAttributes(typeof(IdBagAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteIdBag(writer, member, memberAttrib as IdBagAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(IdBagAttribute), attribute);
            // Element: <array>
            System.Collections.ArrayList ArrayList = FindAttributedMembers( attribute, typeof(ArrayAttribute), type );
            foreach( System.Reflection.MemberInfo member in ArrayList )
            {
                object[] objects = member.GetCustomAttributes(typeof(ArrayAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteArray(writer, member, memberAttrib as ArrayAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(ArrayAttribute), attribute);
            // Element: <primitive-array>
            System.Collections.ArrayList PrimitiveArrayList = FindAttributedMembers( attribute, typeof(PrimitiveArrayAttribute), type );
            foreach( System.Reflection.MemberInfo member in PrimitiveArrayList )
            {
                object[] objects = member.GetCustomAttributes(typeof(PrimitiveArrayAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WritePrimitiveArray(writer, member, memberAttrib as PrimitiveArrayAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(PrimitiveArrayAttribute), attribute);
            // Element: <joined-subclass>
            WriteNestedJoinedSubclassTypes(writer, type);
            WriteUserDefinedContent(writer, type, typeof(JoinedSubclassAttribute), attribute);
            // Element: <loader>
            System.Collections.ArrayList LoaderList = FindAttributedMembers( attribute, typeof(LoaderAttribute), type );
            foreach( System.Reflection.MemberInfo member in LoaderList )
            {
                object[] objects = member.GetCustomAttributes(typeof(LoaderAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteLoader(writer, member, memberAttrib as LoaderAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(LoaderAttribute), attribute);
            // Element: <sql-insert>
            System.Collections.ArrayList SqlInsertList = FindAttributedMembers( attribute, typeof(SqlInsertAttribute), type );
            foreach( System.Reflection.MemberInfo member in SqlInsertList )
            {
                object[] objects = member.GetCustomAttributes(typeof(SqlInsertAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteSqlInsert(writer, member, memberAttrib as SqlInsertAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(SqlInsertAttribute), attribute);
            // Element: <sql-update>
            System.Collections.ArrayList SqlUpdateList = FindAttributedMembers( attribute, typeof(SqlUpdateAttribute), type );
            foreach( System.Reflection.MemberInfo member in SqlUpdateList )
            {
                object[] objects = member.GetCustomAttributes(typeof(SqlUpdateAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteSqlUpdate(writer, member, memberAttrib as SqlUpdateAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(SqlUpdateAttribute), attribute);
            // Element: <sql-delete>
            System.Collections.ArrayList SqlDeleteList = FindAttributedMembers( attribute, typeof(SqlDeleteAttribute), type );
            foreach( System.Reflection.MemberInfo member in SqlDeleteList )
            {
                object[] objects = member.GetCustomAttributes(typeof(SqlDeleteAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteSqlDelete(writer, member, memberAttrib as SqlDeleteAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(SqlDeleteAttribute), attribute);
            // Element: <resultset>
            System.Collections.ArrayList ResultSetList = FindAttributedMembers( attribute, typeof(ResultSetAttribute), type );
            foreach( System.Reflection.MemberInfo member in ResultSetList )
            {
                object[] objects = member.GetCustomAttributes(typeof(ResultSetAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteResultSet(writer, member, memberAttrib as ResultSetAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(ResultSetAttribute), attribute);
            // Element: <query>
            System.Collections.ArrayList QueryList = FindAttributedMembers( attribute, typeof(QueryAttribute), type );
            foreach( System.Reflection.MemberInfo member in QueryList )
            {
                object[] objects = member.GetCustomAttributes(typeof(QueryAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteQuery(writer, member, memberAttrib as QueryAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(QueryAttribute), attribute);
            // Element: <sql-query>
            System.Collections.ArrayList SqlQueryList = FindAttributedMembers( attribute, typeof(SqlQueryAttribute), type );
            foreach( System.Reflection.MemberInfo member in SqlQueryList )
            {
                object[] objects = member.GetCustomAttributes(typeof(SqlQueryAttribute), false);
                System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
                memberAttribs.AddRange(objects);
                memberAttribs.Sort();
                foreach(object memberAttrib in memberAttribs)
                    WriteSqlQuery(writer, member, memberAttrib as SqlQueryAttribute, attribute, type);
            }
            WriteUserDefinedContent(writer, type, typeof(SqlQueryAttribute), attribute);

            writer.WriteEndElement();
        }
 /// <summary> Convert the elements in the Collection to an ArrayList </summary>
 public static System.Collections.ArrayList GetElements(System.Xml.Schema.XmlSchemaObjectCollection seqItems, System.Xml.Schema.XmlSchemaObjectCollection schemaItems)
 {
     System.Collections.ArrayList elements = new System.Collections.ArrayList();
     foreach (System.Xml.Schema.XmlSchemaObject obj in seqItems)
     {
         if (obj is System.Xml.Schema.XmlSchemaElement)
         {
             elements.Add(obj);
         }
         else if (obj is System.Xml.Schema.XmlSchemaChoice)
         {
             System.Xml.Schema.XmlSchemaChoice choice = obj as System.Xml.Schema.XmlSchemaChoice;
             // Add each element of the choice
             foreach (System.Xml.Schema.XmlSchemaObject item in choice.Items)
             {
                 if (item is System.Xml.Schema.XmlSchemaElement)
                 {
                     elements.Add(item);
                 }
                 else if (item is System.Xml.Schema.XmlSchemaGroupRef)
                 {
                     // Find the Group
                     string groupName = (obj as System.Xml.Schema.XmlSchemaGroupRef).RefName.Name;
                     System.Xml.Schema.XmlSchemaGroup group = null;
                     foreach (System.Xml.Schema.XmlSchemaObject schemaItem in schemaItems)
                     {
                         if (schemaItem is System.Xml.Schema.XmlSchemaGroup && groupName == (schemaItem as System.Xml.Schema.XmlSchemaGroup).Name)
                         {
                             group = schemaItem as System.Xml.Schema.XmlSchemaGroup;                                     // Found
                             break;
                         }
                     }
                     if (group == null)                          // Not found
                     {
                         throw new System.Exception("Unknown xs:group " + groupName + string.Format(", nh-mapping.xsd({0})", obj.LineNumber));
                     }
                     elements.AddRange(GetElements(group.Particle.Items, schemaItems));
                 }
                 else if (item is System.Xml.Schema.XmlSchemaSequence)
                 {
                     System.Xml.Schema.XmlSchemaSequence subSeq = item as System.Xml.Schema.XmlSchemaSequence;
                     elements.AddRange(GetElements(subSeq.Items, schemaItems));
                 }
                 else
                 {
                     log.Warn("Unknown Object: " + item.ToString() + string.Format(", nh-mapping.xsd({0})", item.LineNumber));
                 }
             }
         }
         else if (obj is System.Xml.Schema.XmlSchemaGroupRef)
         {
             // Find the Group
             string groupName = (obj as System.Xml.Schema.XmlSchemaGroupRef).RefName.Name;
             System.Xml.Schema.XmlSchemaGroup group = null;
             foreach (System.Xml.Schema.XmlSchemaObject schemaItem in schemaItems)
             {
                 if (schemaItem is System.Xml.Schema.XmlSchemaGroup && groupName == (schemaItem as System.Xml.Schema.XmlSchemaGroup).Name)
                 {
                     group = schemaItem as System.Xml.Schema.XmlSchemaGroup;                             // Found
                     break;
                 }
             }
             if (group == null)                  // Not found
             {
                 throw new System.Exception("Unknown xs:group " + groupName + string.Format(", nh-mapping.xsd({0})", obj.LineNumber));
             }
             elements.AddRange(GetElements(group.Particle.Items, schemaItems));
         }
         else if (obj is System.Xml.Schema.XmlSchemaSequence)
         {
             System.Xml.Schema.XmlSchemaSequence subSeq = obj as System.Xml.Schema.XmlSchemaSequence;
             elements.AddRange(GetElements(subSeq.Items, schemaItems));
         }
         else
         {
             log.Warn("Unknown Object: " + obj.ToString() + string.Format(", nh-mapping.xsd({0})", obj.LineNumber));
         }
     }
     return(elements);
 }
Example #54
0
 ///<summary>
 ///Adds the elements of an ICollection to the end of the base_scopeArrayList
 ///</summary>
 ///<param name="c">The ICollection whose elements should be added to the end of the ArrayList. The collection itself cannot be a null reference (Nothing in Visual Basic), but it can contain elements that are a null reference.<param>
 ///<returns>Return value is void</returns>
 private void AddRange(System.Collections.ICollection c)
 {
     arr.AddRange(c);
 }
        protected override bool Execute(IIntegrationResult result)
        {
            List<string> filesToDelete = new List<string>();
            result.BuildProgressInformation.SignalStartRunTask(!string.IsNullOrEmpty(Description) ? Description : "Reading Modifications");

            List<object> stuff = new List<object>();
            System.Collections.ArrayList AllModifications = new System.Collections.ArrayList();

            foreach (string file in GetModificationFiles(result))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(Modification[]));
                StringReader reader = new StringReader(fileSystem.Load(file).ReadToEnd());
                object dummy = serializer.Deserialize(reader);
                reader.Close();
                System.Collections.ArrayList currentModification = new System.Collections.ArrayList((Modification[])dummy);

                AllModifications.AddRange(currentModification);

                if (deleteAfterRead) filesToDelete.Add(file);
            }

            Modification[] newMods = new Modification[result.Modifications.Length + AllModifications.Count];

            //copy existing modifications
            result.Modifications.CopyTo(newMods, 0);

            // copy modifications read from the file(s)
            int modificationCounter = result.Modifications.Length;
            foreach (Modification mod in AllModifications)
            {
                newMods[modificationCounter] = mod;
                modificationCounter++;
            }

            result.Modifications = newMods;

            // Delete all the files
            foreach (string file in filesToDelete)
            {
                try
                {
                    File.Delete(file);
                }
                catch (IOException error)
                {
                    Log.Warning(
                        string.Format(
                            "Unable to delete file '{0}' - {1}",
                            file,
                            error.Message));
                }
            }

            return true;
        }
 /// <summary> Returns a List of all IChemObject in this ChemFile.
 /// 
 /// </summary>
 /// <returns>  A list of all ChemObjects
 /// </returns>
 public static System.Collections.IList getAllChemObjects(IChemFile file)
 {
     System.Collections.ArrayList list = new System.Collections.ArrayList();
     list.Add(file);
     for (int i = 0; i < file.ChemSequenceCount; i++)
     {
         list.AddRange(ChemSequenceManipulator.getAllChemObjects(file.getChemSequence(i)));
     }
     return list;
 }
        /// <summary>
        /// Executes the specified result.
        /// </summary>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        protected override bool Execute(IIntegrationResult result)
        {
            List <string> filesToDelete = new List <string>();

            result.BuildProgressInformation.SignalStartRunTask(!string.IsNullOrEmpty(Description) ? Description : "Reading Modifications");


            System.Collections.ArrayList allModifications = new System.Collections.ArrayList();


            foreach (string file in GetModificationFiles(result))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(Modification[]));
                StringReader  reader     = new StringReader(fileSystem.Load(file).ReadToEnd());
                object        dummy      = serializer.Deserialize(reader);
                reader.Close();
                System.Collections.ArrayList currentModification = new System.Collections.ArrayList((Modification[])dummy);

                allModifications.AddRange(currentModification);

                if (deleteAfterRead)
                {
                    filesToDelete.Add(file);
                }
            }

            Modification[] newMods = new Modification[result.Modifications.Length + allModifications.Count];

            //copy existing modifications
            result.Modifications.CopyTo(newMods, 0);

            // copy modifications read from the file(s)
            int modificationCounter = result.Modifications.Length;

            foreach (Modification mod in allModifications)
            {
                newMods[modificationCounter] = mod;
                modificationCounter++;
            }

            result.Modifications = newMods;

            // Delete all the files
            foreach (string file in filesToDelete)
            {
                try
                {
                    File.Delete(file);
                }
                catch (IOException error)
                {
                    Log.Warning(
                        string.Format(
                            CultureInfo.CurrentCulture, "Unable to delete file '{0}' - {1}",
                            file,
                            error.Message));
                }
            }

            return(true);
        }