AddRange() публичный метод

public AddRange ( ICollection c ) : void
c ICollection
Результат void
Пример #1
0
 public void calcLaserEnds()
 {
     ArrayList toIterate = new ArrayList();
     toIterate.AddRange(Game1.miscObjects);
     toIterate.AddRange(Game1.solidTiles);
     laserEnds[0] = 0;
     laserEnds[1] = 999999;
     laserEnds[2] = 0;
     laserEnds[3] = 999999;
     foreach (Object m in toIterate)
     {
         if ((m != this) && (m.getX() == x) && (m.blocksProjectiles()) && (m.getSolid() == true))
         {
             //calc laser end points
             if ((m.getY() > y) && (m.getY() < laserEnds[3]))
                 laserEnds[3] = m.getY() - 32;
             if ((m.getY() < y) && (m.getY() > laserEnds[2]))
                 laserEnds[2] = m.getY() + 32;
         }
         if ((m != this) && (m.getY() == y) && (m.blocksProjectiles()) && (m.getSolid() == true))
         {
             //calc laser end points
             if ((m.getX() > x) && (m.getX() < laserEnds[1]))
                 laserEnds[1] = m.getX() - 32;
             if ((m.getX() < x) && (m.getX() > laserEnds[0]))
                 laserEnds[0] = m.getX() + 32;
         }
     }
 }
 internal bool ImportComComponent(string path, OutputMessageCollection outputMessages, string outputDisplayName)
 {
     ComImporter importer = new ComImporter(path, outputMessages, outputDisplayName);
     if (importer.Success)
     {
         ArrayList list = new ArrayList();
         if (this.typeLibs != null)
         {
             list.AddRange(this.typeLibs);
         }
         if (importer.TypeLib != null)
         {
             list.Add(importer.TypeLib);
         }
         this.typeLibs = (TypeLib[]) list.ToArray(typeof(TypeLib));
         list.Clear();
         if (this.comClasses != null)
         {
             list.AddRange(this.comClasses);
         }
         if (importer.ComClasses != null)
         {
             list.AddRange(importer.ComClasses);
         }
         this.comClasses = (ComClass[]) list.ToArray(typeof(ComClass));
     }
     return importer.Success;
 }
Пример #3
0
		public static Mnozina operator + (Mnozina a, Mnozina b)
		{
			ArrayList c = new ArrayList();
			c.AddRange(a.seznam);
			c.AddRange(b.seznam);
			return new Mnozina(c);
		}
Пример #4
0
 static void Main(string[] args)
 {
     ArrayList list = new ArrayList();
     list.Add(true);
     list.Add(1);
     list.Add("张三");
     list.AddRange(new int[] { 1, 2, 3, 4, 5 });
     list.AddRange(list);
     
     //list.Clear();//清空所有元素
     //list.Remove(true);//删除单个元素
     //list.RemoveAt(0);//根据下标删除元素
     //list.RemoveRange(0, 3);
     //list.Sort();//升序排列
     //list.Reverse();//反转
     //list.Insert(1, "插入的");
     //list.InsertRange(0, new string[] { "zs", "ls" });
     //bool b=list.Contains(1);
     //Console.WriteLine(b);
     list.Add("wisdom");
     if (!list.Contains("wisdom"))
     {
         list.Add("wisdom");
     }
     else
     {
         Console.WriteLine("已经有这个屌丝啦");
     }
     for (int i = 0; i < list.Count; i++)
     {
         Console.WriteLine(list[i]);
     }
     Console.ReadKey();
 }
Пример #5
0
        public string[] GetFileList(string SourcePath, bool Subdir)
        {
            SourcePath = SourcePath.Trim().TrimEnd(new char[] { Path.DirectorySeparatorChar });
            string sourceDir  = null;
            string fileFilter = "*";

            if (Directory.Exists(SourcePath))
            {             // Source is a Directory
                sourceDir = SourcePath;
            }
            else if (Directory.Exists(Path.GetDirectoryName(SourcePath)))
            {             // Source is a File Filter
                sourceDir  = Path.GetDirectoryName(SourcePath);
                fileFilter = Path.GetFileName(SourcePath);
            }
            else
            {             // Source not found
                throw new DirectoryNotFoundException("Cannot find \"" + Path.GetDirectoryName(SourcePath) + "\".");
            }

            System.Collections.ArrayList fileList = new System.Collections.ArrayList();
            fileList.AddRange(System.IO.Directory.GetFiles(sourceDir, fileFilter));
            if (Subdir)
            {
                foreach (string subDir in System.IO.Directory.GetDirectories(sourceDir))
                {
                    fileList.AddRange(GetFileList(Path.Combine(subDir, fileFilter), Subdir));
                }
            }

            return((string[])fileList.ToArray(Type.GetType("System.String")));
        }
		public static ArrayList GetHouses( Mobile owner )
		{
			ArrayList list = new ArrayList();

			Account acct = owner.Account as Account;

			if ( acct == null )
			{
				list.AddRange( BaseHouse.GetHouses( owner ) );
			}
			else
			{
				for ( int i = 0; i < acct.Length; ++i )
				{
					Mobile mob = acct[i];

					if ( mob != null )
						list.AddRange( BaseHouse.GetHouses( mob ) );
				}
			}

			list.Sort( HouseComparer.Instance );

			return list;
		}
Пример #7
0
 public static void setCBItems(vdUsr.vdComboBox cbo, ICollection col1, ICollection col2, Type converter, object selected, object objDefault)
 {
     ArrayList al = new ArrayList(col1.Count + col2.Count);
     al.AddRange(col1);
     al.AddRange(col2);
     setCBItems(cbo, al, converter, selected, objDefault);
 }
    	protected override Type[] TestCases()
        {
            if (!Directory.Exists(Db4oLibrarian.LibraryPath()))
            {
                TestPlatform.GetStdErr().WriteLine("DISABLED: " + GetType());
                return new Type[] { };
            }

            ArrayList list = new ArrayList();
            list.AddRange(base.TestCases());

            Type[] netTypes = new Type[] {
                typeof(SimplestPossibleHandlerUpdateTestCase),
                typeof(GenericListVersionUpdateTestCase),
                typeof(GenericDictionaryVersionUpdateTestCase),
                typeof(DateTimeHandlerUpdateTestCase),
				typeof(DateTimeOffsetHandlerUpdateTestCase),
                typeof(IndexedDateTimeUpdateTestCase),
                typeof(DecimalHandlerUpdateTestCase),
				typeof(EnumHandlerUpdateTestCase),
                typeof(GUIDHandlerUpdateTestCase),
                typeof(HashtableUpdateTestCase),
                typeof(NestedStructHandlerUpdateTestCase),
                typeof(SByteHandlerUpdateTestCase),
                typeof(StructHandlerUpdateTestCase),
                typeof(UIntHandlerUpdateTestCase),
                typeof(ULongHandlerUpdateTestCase),
                typeof(UShortHandlerUpdateTestCase),
            };

            list.AddRange(netTypes);
        	return (Type[]) list.ToArray(typeof(Type));
        }
Пример #9
0
 public bool ExecuteAll(Course c, List<CourseDetail> cdList,List<CoursePicture> plist)
 {
     ArrayList list = new ArrayList();
     try
     {
         int course_id = GetCourseId(c);
         //獲得操作Course表的sql語句
         List<string> listStr = GetSqlByCourseDetail(cdList, course_id);
         //獲取操作圖片的sql語句
         List<string> plistStr = GetSqlByPicture(plist, course_id);
         if (listStr.Count != 0)
         {
             list.AddRange(listStr);
         }
         if (plistStr.Count != 0)
         {
             list.AddRange(plistStr);
         }
         if (list.Count != 0)
         {
             return _courseImpl.SaveAll(list);
         }
         else
         {
             return true;
         }
         
     }
     catch (Exception ex)
     {
         throw new Exception("CourseMgr-->SaveAll" + ex.Message,ex);
     }
 }
Пример #10
0
 public ArrayList GetAllEOSData()
 {
     ArrayList arr = new ArrayList();
     arr.AddRange(_liveSweepUnitOutputs);
     arr.AddRange(_doneSweepUnitOutputs);
     return arr;
 }
Пример #11
0
 /**
  * Appends two lists of results.
  *
  * @param l1 the first list.
  * @param l2 the second list.
  * @return the appended list.
  */
 internal static List Append(List l1, List l2)
 {
     var result = new ArrayList(l1.list.Count + l2.list.Count);
     result.AddRange(l1.list);
     result.AddRange(l2.list);
     return new List(result);
 }
Пример #12
0
        /// <summary>
        /// Retrieves an array of all InstanceMemento's stored by this MementoSource
        /// </summary>
        /// <returns></returns>
        public InstanceMemento[] GetAllMementos()
        {
            var list = new ArrayList();
            list.AddRange(fetchInternalMementos());
            list.AddRange(_externalMementos.Values);

            return (InstanceMemento[]) list.ToArray(typeof (InstanceMemento));
        }
Пример #13
0
 public static ArrayList GetNetworkComputers()
 {
     //TODO: need to convert this to a dict possibly?  currently there can be duplicates
     ArrayList ar = new ArrayList();
     ar.AddRange(GetNetworkWin32Api());
     ar.AddRange(GetNetworkDirectoryServices());
     return ar;
 }
Пример #14
0
 public ArrayList GetAllEOSData()
 {
     ArrayList arr = new ArrayList();
     arr.AddRange(_liveEOSOutput);
     arr.AddRange(_doneEOSOutput);
     arr.AddRange(_rLiveEOSOutput);
     arr.AddRange(_rDoneEOSOutput);
     return arr;
 }
Пример #15
0
 public ICollection Search(String text, int projectId)
 {
     var result = new ArrayList();
     result.AddRange(GetProjects(text, projectId));
     result.AddRange(GetMilestones(text, projectId));
     result.AddRange(GetTasks(text, projectId));
     result.AddRange(GetMessages(text, projectId));
     return result;
 }
Пример #16
0
        public IList CreateAll()
        {
            var list = new ArrayList();

            list.AddRange(countryBuilder.BuildAll());
            list.AddRange(cityBuilder.BuildAll());

            return list;
        }
Пример #17
0
        public static Type[] Union(Type[] set1, Type[] set2)
        {
            ArrayList types = new ArrayList();

            if (set1 != null) types.AddRange(set1);
            if (set2 != null) types.AddRange(set2);

            return (Type[]) types.ToArray(typeof(Type));
        }
        /// <summary>
        /// Gets a list of NFS config files (Nfs*.xml;Nfs*.config) from AppDomain.CurrentDomain.BaseDirectory including sub-directories
        /// </summary>
        /// <param name="returnPath">should the string[] contain the path to each file</param>
        /// <returns>a string array of file names optionally including their paths</returns>    
        public static string[] GetNFSConfigFilesInBaseDirectory(bool returnPath)
        {
            ArrayList configFiles = new ArrayList();
            configFiles.AddRange(GetFileListInBaseDirectory("Nfs*.xml", returnPath));
            configFiles.AddRange(GetFileListInBaseDirectory("Nfs*.config", returnPath));
            configFiles.TrimToSize();

            return (string[]) configFiles.ToArray(typeof (string));
        }
Пример #19
0
        public ArrayList GetChessPieces()
        {
            ArrayList whitePieces = white.ListPieces();
            ArrayList blackPieces = black.ListPieces();
            ArrayList mergedList = new ArrayList();
            mergedList.AddRange( whitePieces );
            mergedList.AddRange( blackPieces );

            return mergedList;
        }
Пример #20
0
		public IList Apply(IList original) {
			ArrayList right = new ArrayList();
			foreach (Hunk hunk in this) {
				if (hunk.Same)
					right.AddRange(new Range(original, hunk.Start, hunk.Count));
				else
					right.AddRange(hunk.Right);
			}
			return right;
		}
Пример #21
0
 private static IAppender[] GetAppenders()
 {
     ArrayList list = new ArrayList();
     list.AddRange(((log4net.Repository.Hierarchy.Hierarchy) LogManager.GetRepository()).Root.Appenders);
     foreach (ILog log in LogManager.GetCurrentLoggers())
     {
         list.AddRange(((Logger) log.Logger).Appenders);
     }
     return (IAppender[]) list.ToArray(typeof(IAppender));
 }
Пример #22
0
        public ArrayList ToArrayList()
        {
            var result = new ArrayList();
            if (null != Left)
                result.AddRange( Left.ToArrayList() );
            result.Add(_key);
            if (null != Right)
                result.AddRange(Right.ToArrayList());

            return result;
        }
Пример #23
0
 protected void Page_Load(object sender, EventArgs e)
 {
     var settings = new ArrayList {new {Key = "JIRA HOST", Value = JiraConfiguration.JiraHost}};
     settings.AddRange(
         FeedsConfiguration.Feeds.Select(
             config => new {Key = config.Id.ToUpper() + " PRIVATE PATH", Value = config.PrivatePath}).OrderBy(item => item.Key).ToList());
     settings.AddRange(
         FeedsConfiguration.Feeds.Select(
             config => new { Key = config.Id.ToUpper() + " PUBLIC PATH", Value = config.PublicPath }).OrderBy(item => item.Key).ToList());
     rptSettings.DataSource = settings;
     rptSettings.DataBind();
 }
Пример #24
0
        private static IAppender[] GetAppenders()
        {
            var appenders = new ArrayList();

            appenders.AddRange(((Hierarchy)LogManager.GetRepository()).Root.Appenders);

            foreach (ILog log in LogManager.GetCurrentLoggers())
            {
                appenders.AddRange(((Logger)log.Logger).Appenders);
            }

            return (IAppender[])appenders.ToArray(typeof(IAppender));
        }
Пример #25
0
        public ArrayList GetChildModelList(ArrayList AL)
        {
            ArrayList modelList = new ArrayList();

            for (int i = 0; i < AL.Count; i++)
            {
                ModelClass MC = (ModelClass)AL[i];

                modelList.AddRange(MC.WaveChild);
                modelList.AddRange(MC.CopyChild);

            }

            return modelList;
        }
Пример #26
0
            /// <seealso cref="Graph.edgesOf(Object)">
            /// </seealso>
            public override System.Collections.IList edgesOf(System.Object vertex)
            {
                System.Collections.ArrayList inAndOut = new System.Collections.ArrayList(getEdgeContainer(vertex).m_incoming);
                inAndOut.AddRange(getEdgeContainer(vertex).m_outgoing);

                // we have two copies for each self-loop - remove one of them.
                if (Enclosing_Instance.m_allowingLoops)
                {
                    System.Collections.IList loops = getAllEdges(vertex, vertex);

                    for (int i = 0; i < inAndOut.Count;)
                    {
                        System.Object e = inAndOut[i];

                        if (loops.Contains(e))
                        {
                            inAndOut.RemoveAt(i);
                            loops.Remove(e);                             // so we remove it only once
                        }
                        else
                        {
                            i++;
                        }
                    }
                }

                return(inAndOut);
            }
        public string getRandomFromArrayList(string arrayListName, ref ArrayList aList)
        {
            ArrayList alQueued;

            if (htArrayListQueues.ContainsKey(arrayListName))
            {
                alQueued = (ArrayList)htArrayListQueues[arrayListName];

                if (alQueued.Count <= 1)
                {
                    alQueued.AddRange(aList);
                }
            }
            else
            {
                alQueued = new ArrayList();
                alQueued.AddRange(aList);
            }

            int iRandom = rnd.Next(0, alQueued.Count - 1);
            string sReturnable = alQueued[iRandom].ToString();
            alQueued.RemoveAt(iRandom);

            htArrayListQueues[arrayListName] = alQueued;

            return sReturnable;
        }
Пример #28
0
        public static string Text_Decryption(string text, int bits, string encryption_key)
        {
            string result = String.Empty;
            ArrayList list = new ArrayList();

            try
            {
                RSACryptoServiceProvider rsacsp = new RSACryptoServiceProvider(bits);
                rsacsp.FromXmlString(encryption_key);
                int blockSizeBase64 = (bits / 8 % 3 != 0) ?  (((bits / 8) / 3) * 4) + 4 : ((bits / 8) / 3) * 4;
                int iterations = text.Length / blockSizeBase64;

                for (int i = 0; i < iterations; i++)
                {
                    Byte[] encrypted_bytes = Convert.FromBase64String(text.Substring(blockSizeBase64 * i, blockSizeBase64));
                    Array.Reverse(encrypted_bytes);
                    list.AddRange(rsacsp.Decrypt(encrypted_bytes, true));
                }

            }
            catch (Exception e)
            {
                result = "<Error>" + e.Message + "</Error>";
            }

            result = Encoding.UTF32.GetString((Byte[])list.ToArray(typeof(Byte)));

            return result;
        }
Пример #29
0
        private void PrintForm_Load(object sender, EventArgs e)
        { 
            var inif = new INIFile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\eXpressPrint\\config.ini");

            if (!string.IsNullOrEmpty(inif.Read("PRINT_OPT", "AUTO")))
            {
                if (inif.Read("PRINT_OPT", "AUTO").Equals("Y"))
                    PrintAndReturn(_PrintImage);
            }


            if (!string.IsNullOrEmpty(inif.Read("PRINT_SET", "COPIES")))
            {
                var arr = new ArrayList();
               
                arr.AddRange(inif.Read("PRINT_SET", "COPIES").Split(','));

                var sortedList = arr.Cast<string>().OrderBy(item => int.Parse(item));

                foreach (var item in sortedList)
                {
                    comboBoxNumOfCopies.Items.Add(item);
                }

                comboBoxNumOfCopies.Items.Insert(0,"--Select--");
                comboBoxNumOfCopies.SelectedIndex = 0;
            }
            
            formState.Maximize(this);
            txtNumberOfCopies.Focus();
        }
Пример #30
0
        static void Main(string[] args)
        {
            //string[] strArray = { "First", "Second", "Third" };
            //Console.WriteLine("This array has {0} items", strArray.Length);
            //Console.WriteLine();

            //foreach (string s in strArray) 
            //{
            //    Console.WriteLine("Array Entry: {0}", s);
            //}

            //Console.WriteLine();
            //Array.Reverse(strArray);

            //foreach (string s in strArray)
            //{
            //    Console.WriteLine("Array Entry: {0}", s);
            //}

            // Working with the ArrayList
            ArrayList strArray = new ArrayList();
            strArray.AddRange(new string[] { "First", "Second", "Third" });
            Console.WriteLine("This collection has {0} items.", strArray.Count);
            strArray.Add("string");
            Console.WriteLine("This collection now has {0} items", strArray.Count);
            foreach (string s in strArray) 
            {
                Console.WriteLine("Entry: {0}", s);
            }
            Console.ReadLine();
        }
Пример #31
0
 private System.Collections.ArrayList AddInNullItem(System.Collections.ArrayList toBeBindedList, bool isStandardList, out bool changedList)
 {
     changedList = false;
     if (isStandardList)
     {
         if (!_Nullable && Oranikle.Studio.Controls.CtrlNullableComboBox.StandardMap.ContainsKey(_ItemType))
         {
             return(Oranikle.Studio.Controls.CtrlNullableComboBox.StandardMap[_ItemType]);
         }
         if (_Nullable && System.String.IsNullOrEmpty(NullDisplay) && Oranikle.Studio.Controls.CtrlNullableComboBox.NullableMap.ContainsKey(_ItemType))
         {
             return(Oranikle.Studio.Controls.CtrlNullableComboBox.NullableMap[_ItemType]);
         }
     }
     System.Collections.ArrayList arrayList = new System.Collections.ArrayList();
     arrayList.AddRange(toBeBindedList);
     toBeBindedList = arrayList;
     if (_Nullable)
     {
         toBeBindedList = AddNullItem(toBeBindedList, out changedList);
     }
     if (isStandardList)
     {
         if (!_Nullable && !Oranikle.Studio.Controls.CtrlNullableComboBox.StandardMap.ContainsKey(_ItemType))
         {
             Oranikle.Studio.Controls.CtrlNullableComboBox.StandardMap.Add(_ItemType, toBeBindedList);
         }
         else if (_Nullable && System.String.IsNullOrEmpty(NullDisplay) && !Oranikle.Studio.Controls.CtrlNullableComboBox.NullableMap.ContainsKey(_ItemType))
         {
             Oranikle.Studio.Controls.CtrlNullableComboBox.NullableMap.Add(_ItemType, toBeBindedList);
         }
     }
     return(toBeBindedList);
 }
Пример #32
0
 public static string[] AllSites()
 {
     ArrayList allSites = new ArrayList();
     allSites.AddRange(BatchSearchSites);
     string[] allSitesArray = (string[]) allSites.ToArray(typeof (string));
     return allSitesArray;
 }
Пример #33
0
		private IList ObtainListableProperties(ActiveRecordModel model)
		{
			var properties = new ArrayList();
	
			ObtainPKProperty();

			if (model.Parent != null)
			{
				properties.AddRange( ObtainListableProperties(model.Parent) );
			}
	
			foreach(var propModel in model.Properties)
			{
				if (IsNotSupported(propModel.Property.PropertyType)) continue;

				properties.Add(propModel.Property);
			}
	
			foreach(var prop in model.NotMappedProperties)
			{
				if (IsNotSupported(prop.PropertyType)) continue;

				properties.Add(prop);
			}

			return properties;
		}
Пример #34
0
        //static void dump_collection(string collectionName)
        //{
        //    Tuple<bool, int, DateTime> col_cnt = getCollectionCount(collectionName);
        //    Tuple<bool, Dictionary<string, object>[]> records = getAllCollectDocuments(collectionName, 1000);
        //    Dictionary<string, object> local_data = new Dictionary<string, object>();
        //    local_data.Add("lastmodify", col_cnt.Item3.ToString("s"));
        //    local_data.Add("doc", records.Item2);
        //    var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
        //    System.IO.File.WriteAllText("test.json", jss.Serialize(local_data));
        //}
        static Tuple <bool, Dictionary <string, object>[], DateTime> getAllCollectDocuments(string collectionName, int size = 1000)
        {
            DateTime retT = DateTime.MinValue;
            bool     ret  = false;

            System.Collections.ArrayList retList = new System.Collections.ArrayList();
            try
            {
                int page = 1;
                while (!ret)
                {
                    NameValueCollection q = new NameValueCollection();
                    q.Add("page", page.ToString());
                    q.Add("pagesize", size.ToString());
                    WebClient wc = new WebClient();
                    wc.Credentials = new NetworkCredential("cmc", "cmc1234!");
                    wc.Headers.Add("Content-Type", "application/json");
                    wc.QueryString = q;
                    string s = wc.DownloadString($"http://dc.futuredial.com/cmc/{collectionName}");
                    if (!string.IsNullOrEmpty(s))
                    {
                        var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
                        Dictionary <string, object> data = jss.Deserialize <Dictionary <string, object> >(s);
                        if (DateTime.MinValue == retT && data.ContainsKey("_lastupdated_on") && data["_lastupdated_on"].GetType() == typeof(string))
                        {
                            DateTime t;
                            if (DateTime.TryParse(data["_lastupdated_on"].ToString(), out t))
                            {
                                retT = t;
                            }
                        }
                        if (data.ContainsKey("_returned") && data["_returned"].GetType() == typeof(int))
                        {
                            int i = (int)data["_returned"];
                            if (i == 0)
                            {
                                ret = true;
                            }
                            else
                            {
                                if (data.ContainsKey("_embedded") && data["_embedded"].GetType() == typeof(Dictionary <string, object>))
                                {
                                    Dictionary <string, object> d = (Dictionary <string, object>)data["_embedded"];
                                    if (d.ContainsKey("doc") && d["doc"].GetType() == typeof(System.Collections.ArrayList))
                                    {
                                        System.Collections.ArrayList al = (System.Collections.ArrayList)d["doc"];
                                        retList.AddRange(al);
                                    }
                                }
                                page++;
                            }
                        }
                    }
                }
            }
            catch (Exception) { }
            return(new Tuple <bool, Dictionary <string, object>[], DateTime>(ret, (Dictionary <string, object>[])retList.ToArray(typeof(Dictionary <string, object>)), retT));
        }
        /// <summary>
        /// Returns an ArrayList from a delimited string.
        /// </summary>
        /// <param name="st"></param>
        /// <returns></returns>
        private static ArrayList SettingArray(string st)
        {
            ArrayList result = new System.Collections.ArrayList();

            if (st.Length > 0)
            {
                result.AddRange(st.ToLower().Split(','));
            }
            return(result);
        }
Пример #36
0
        public string INSERT_DB(System.Data.SqlClient.SqlConnection dbCon, System.Data.SqlClient.SqlTransaction TRX, string tbName, string cols, string vals)
        {
            int i;

            string Result = "";

            StringBuilder strBuilder = new StringBuilder();

            System.Collections.ArrayList arrCols = new System.Collections.ArrayList();
            System.Collections.ArrayList arrVals = new System.Collections.ArrayList();

            arrCols.AddRange(objUtil.Split(cols, "|"));
            arrVals.AddRange(objUtil.Split(vals, "|"));

            strBuilder.Append("INSERT INTO " + tbName);
            strBuilder.Append(" (");
            for (i = 0; i < arrCols.Count; i++)
            {
                if (i > 0)
                {
                    strBuilder.Append(", ");
                }
                strBuilder.Append(objUtil.toDb(arrCols[i].ToString()));
            }
            strBuilder.Append(") VALUES (");
            for (i = 0; i < arrVals.Count; i++)
            {
                if (i > 0)
                {
                    strBuilder.Append(", ");
                }
                strBuilder.Append("'");
                strBuilder.Append(objUtil.toDb(arrVals[i].ToString().Replace("%/", "|")));
                strBuilder.Append("'");
            }
            strBuilder.Append(")");

            objUtil.writeLog("INSERT_DB QUERY : " + strBuilder.ToString());

            try
            {
                Result = objDB.ExecuteNonQuery(dbCon, TRX, strBuilder.ToString());
            }
            catch (Exception e)
            {
                objUtil.writeLog("ERR CMN INSERT [" + tbName + "] " + "[" + cols + "] " + "[" + vals + "]");
                objUtil.writeLog("ERR CMN INSERT QUERY : " + strBuilder.ToString());
                objUtil.writeLog("ERR CMN INSERT MSG : " + e.ToString());
                Result = "FAIL";
            }

            return(Result);
        }
Пример #37
0
        /// <summary>
        /// 创建申请单的报告组【3】
        /// </summary>
        private void m_mthGenerateAppReports()
        {
            clsAppSampleGroupCollection objSampleGroups = m_objGenerateAppSampleGroups();

            foreach (clsLIS_AppSampleGroup objAppSampleGroup in objSampleGroups)
            {
                bool blnAppReportGroupExist = false;

                clsReportGroup_VO objReportGroupVO = null;
                long lngRes = clsReportGroupSmp.s_obj.m_lngGetReportGoupVO(objAppSampleGroup.m_ObjDataVO.m_strSAMPLE_GROUP_ID_CHR, out objReportGroupVO);

                if (lngRes > 0 && objReportGroupVO != null)
                {
                    objAppSampleGroup.m_ObjDataVO.m_strREPORT_GROUP_ID_CHR = objReportGroupVO.strReportGroupID;
                    foreach (clsLIS_AppCheckItem objAppCheckItem in objAppSampleGroup.m_ObjAppCheckItems)
                    {
                        objAppCheckItem.m_ObjDataVO.m_strREPORT_GROUP_ID_CHR = objReportGroupVO.strReportGroupID;
                    }

                    foreach (clsLIS_AppCheckReport objAppCheckReport in this.m_objAppReports)
                    {
                        if (objAppCheckReport.m_ObjCheckReport.m_ObjDataVO.strReportGroupID == objReportGroupVO.strReportGroupID)
                        {
                            objAppCheckReport.m_ObjAppSampleGroups.Add(objAppSampleGroup);
                            System.Collections.ArrayList arlSGID = new System.Collections.ArrayList();
                            if (objAppCheckReport.m_ObjDataVO.m_strSampleGroupIDArr != null)
                            {
                                arlSGID.AddRange(objAppCheckReport.m_ObjDataVO.m_strSampleGroupIDArr);
                            }
                            arlSGID.Add(objAppSampleGroup.m_StrSampleGroupID);
                            objAppCheckReport.m_ObjDataVO.m_strSampleGroupIDArr = (string[])arlSGID.ToArray(typeof(string));
                            blnAppReportGroupExist = true;
                            break;
                        }
                    }
                    if (!blnAppReportGroupExist)
                    {
                        clsLIS_CheckReport objCheckReport = new clsLIS_CheckReport();
                        objCheckReport.m_ObjDataVO = objReportGroupVO;
                        clsT_OPR_LIS_APP_REPORT_VO objAppReportVO = new clsT_OPR_LIS_APP_REPORT_VO();
                        clsLIS_AppCheckReport      objAppReport   = new clsLIS_AppCheckReport(objAppReportVO);
                        objAppReport.m_ObjCheckReport   = objCheckReport;
                        objAppReport.m_StrReportGroupID = objCheckReport.m_ObjDataVO.strReportGroupID;
                        objAppReport.m_ObjAppSampleGroups.Add(objAppSampleGroup);
                        objAppReport.m_ObjDataVO.m_strSampleGroupIDArr = new string[] { objAppSampleGroup.m_StrSampleGroupID };
                        objAppReport.m_IntStatus = 1;

                        m_objAppReports.Add(objAppReport);
                    }
                }
            }
        }
            public override void execute3(RunTimeValueBase thisObj,FunctionDefine functionDefine,SLOT returnSlot,SourceToken token,StackFrame stackframe,out bool success)
            {
                System.Collections.ArrayList arraylist =
                    (System.Collections.ArrayList)((LinkObj <object>)((ASBinCode.rtData.rtObjectBase)thisObj).value).value;

                try
                {
                    object lo;
                    if (stackframe.player.linktypemapper.rtValueToLinkObject(
                            argements[0],

                            stackframe.player.linktypemapper.getLinkType(
                                functionDefine.signature.parameters[0].type
                                ),

                            bin,true,out lo
                            ))
                    {
                        arraylist.AddRange((ICollection)lo);

                        returnSlot.setValue(ASBinCode.rtData.rtUndefined.undefined);

                        success = true;
                    }
                    else
                    {
                        stackframe.throwCastException(token,argements[0].rtType,
                                                      functionDefine.signature.parameters[0].type
                                                      );
                        success = false;
                    }
                }
                catch (KeyNotFoundException)
                {
                    success = false;
                    stackframe.throwAneException(token,functionDefine.signature.parameters[0].type + "没有链接到脚本");
                }
                catch (ArgumentException a)
                {
                    success = false;
                    stackframe.throwAneException(token,a.Message);
                }
                catch (IndexOutOfRangeException i)
                {
                    success = false;
                    stackframe.throwAneException(token,i.Message);
                }
            }
Пример #39
0
        public string DELETE_DB(System.Data.SqlClient.SqlConnection dbCon, System.Data.SqlClient.SqlTransaction TRX, string tbName, string Wcols, string Wvals)
        {
            int i;

            string Result = "";

            StringBuilder strBuilder = new StringBuilder();

            libCommon.clsDB   objDB   = new libCommon.clsDB();
            libCommon.clsUtil objUtil = new libCommon.clsUtil();

            System.Collections.ArrayList arrWCols = new System.Collections.ArrayList();
            System.Collections.ArrayList arrWVals = new System.Collections.ArrayList();

            arrWCols.AddRange(objUtil.Split(Wcols, "|"));
            arrWVals.AddRange(objUtil.Split(Wvals, "|"));

            strBuilder.Append("DELETE FROM " + tbName);
            strBuilder.Append(" WHERE ");
            for (i = 0; i < arrWCols.Count; i++)
            {
                if (i > 0)
                {
                    strBuilder.Append(" AND ");
                }
                strBuilder.Append("[");
                strBuilder.Append(objUtil.toDb(arrWCols[i].ToString()));
                strBuilder.Append("]");
                strBuilder.Append(" = ");
                strBuilder.Append("'");
                strBuilder.Append(objUtil.toDb(arrWVals[i].ToString()));
                strBuilder.Append("'");
            }

            try
            {
                Result = objDB.ExecuteNonQuery(dbCon, TRX, strBuilder.ToString());
            }
            catch (Exception e)
            {
                objUtil.writeLog("ERR CMN DELETE [" + tbName + "] " + "[" + Wcols + "] " + "[" + Wvals + "]");
                objUtil.writeLog("ERR CMN DELETE QUERY : " + strBuilder.ToString());
                objUtil.writeLog("ERR CMN DELETE MSG : " + e.ToString());
                Result = "FAIL";
            }

            return(Result);
        }
Пример #40
0
        /// <summary>
        /// Get an arraylist of a configuration setting, based on the value split into
        /// an array on splitter.
        /// </summary>
        /// <param name="Key">The config string Key.</param>
        /// <param name="Splitter">The char to spit the string on.</param>
        /// <param name="ToLower">Set to true to change all values to lower case.</param>
        /// <param name="EncryptionKey">Encryption key to decrypt value</param>
        /// <returns>Array of Values in key.</returns>
        public static ArrayList SettingArray(string Key, char Splitter, bool ToLower, string EncryptionKey)
        {
            string delimlist = Config.Setting(Key, EncryptionKey);

            if (ToLower)
            {
                delimlist = delimlist.ToLower();
            }
            ArrayList aryApps = new System.Collections.ArrayList();

            if (delimlist.Length > 0)
            {
                aryApps.AddRange(delimlist.Split(Splitter));
            }

            return(aryApps);
        }
Пример #41
0
        public string getNewID(System.Data.SqlClient.SqlConnection dbCon, System.Data.SqlClient.SqlTransaction TRX, string tbName, string kcol, string Wcols, string Wvals, int len)
        {
            System.Data.DataSet DS         = new System.Data.DataSet();
            StringBuilder       strBuilder = new StringBuilder();
            int i;

            string Result;
            string dKey = "".PadLeft(len, '0');

            System.Collections.ArrayList arrWCols = new System.Collections.ArrayList();
            System.Collections.ArrayList arrWVals = new System.Collections.ArrayList();

            arrWCols.AddRange(objUtil.Split(Wcols, "|"));
            arrWVals.AddRange(objUtil.Split(Wvals, "|"));


            strBuilder.Append("SELECT ISNULL(MAX(" + kcol + "), '" + dKey + "') FROM " + tbName);
            strBuilder.Append(" WHERE 1 = 1");
            for (i = 0; i < arrWCols.Count; i++)
            {
                if (arrWCols[i].ToString().Length > 0)
                {
                    strBuilder.Append(" AND ");
                    strBuilder.Append("[");
                    strBuilder.Append(objUtil.toDb(arrWCols[i].ToString()));
                    strBuilder.Append("]");
                    strBuilder.Append(" = ");
                    strBuilder.Append("'");
                    strBuilder.Append(objUtil.toDb(arrWVals[i].ToString()));
                    strBuilder.Append("'");
                }
            }

            objUtil.writeLog("GET NEW ID QUERY : " + strBuilder.ToString());

            DS = objDB.ExecuteDSQuery(dbCon, TRX, strBuilder.ToString());

            Result = (objUtil.ToInt32(DS.Tables[0].Rows[0][0].ToString()) + 1).ToString().PadLeft(len, '0');

            objUtil.writeLog("GET NEW ID : " + Result);

            return(Result);
        }
Пример #42
0
        private void ucMetCasStatDead_Load(object sender, EventArgs e)
        {
            Neusoft.HISFC.Models.Base.Department objAll = new Neusoft.HISFC.Models.Base.Department();

            objAll.ID   = "ALL";
            objAll.Name = "全部";

            alDeptList.Add(objAll);

            ArrayList dept = new ArrayList();

            dept = deptManger.GetDeptment(Neusoft.HISFC.Models.Base.EnumDepartmentType.I);
            alDeptList.AddRange(dept);

            this.cboDeptCode.AddItems(alDeptList);
            this.cboDeptCode.SelectedIndex = 0;

            DateTime currentDateTime = this.deptManger.GetDateTimeFromSysDateTime();

            this.dtpBeginTime.Value = new DateTime(currentDateTime.Year, currentDateTime.Month, currentDateTime.Day, 00, 00, 00);
            this.dtpEndTime.Value   = new DateTime(currentDateTime.Year, currentDateTime.Month, currentDateTime.Day, 23, 59, 59);
        }
Пример #43
0
        /// <summary>
        /// 向发送客户端发送数据事情
        /// </summary>
        /// <param name="data">发送的数据</param>
        /// <param name="endResponse"></param>
        public void Send(WebMeta data, bool endResponse)
        {
            WebResponse response = this.Response;

            response.ClientEvent |= WebEvent.DataEvent;
            if (response.Headers.ContainsKey("DataEvent"))
            {
                var ts = response.Headers.GetDictionary()["DataEvent"];
                if (ts is WebMeta)
                {
                    response.Headers.Set("DataEvent", (WebMeta)ts, data);
                }
                else if (ts is IDictionary)
                {
                    response.Headers.Set("DataEvent", new WebMeta((IDictionary)ts), data);
                }
                else if (ts is Array)
                {
                    var ats = new System.Collections.ArrayList();
                    ats.AddRange((Array)ts);
                    ats.Add(data);

                    response.Headers.Set("DataEvent", (WebMeta[])ats.ToArray(typeof(WebMeta)));
                }
                else
                {
                    response.Headers.Set("DataEvent", data);
                }
            }
            else
            {
                response.Headers.Set("DataEvent", data);
            }
            if (endResponse)
            {
                response.ClientEvent ^= response.ClientEvent & WebEvent.Normal;
                this.End();
            }
        }
Пример #44
0
 private int nextInt(System.IO.StreamReader fr)
 {
     for (;;)
     {
         if (line.Count == 0)
         {
             string buf = fr.ReadLine();
             if (buf == null)
             {
                 GLPK.glp_cli_error("End of file reached");
             }
             line.AddRange(buf.Split(' '));
         }
         string token = (string)line [0];
         token = token.Trim();
         line.RemoveAt(0);
         if (token.Length > 0)
         {
             return(Convert.ToInt32(token));
         }
     }
 }
Пример #45
0
        /// <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);
        }
Пример #46
0
 public void Add(IBrowsableItem [] items)
 {
     list.AddRange(items);
     Reload();
 }
Пример #47
0
 public void AddPapers(params Paper[] AdditionalPapers)
 {
     Publications.AddRange(AdditionalPapers);
 }
Пример #48
0
 public void AddMembers(params Person[] AdditionalMembers)
 {
     Participants.AddRange(AdditionalMembers);
 }
Пример #49
0
        public static IEnumerable <UserLocation> Find_DomainUserLocation(Args_Find_DomainUserLocation args = null)
        {
            if (args == null)
            {
                args = new Args_Find_DomainUserLocation();
            }

            var ComputerSearcherArguments = new Args_Get_DomainComputer
            {
                Properties      = new[] { "dnshostname" },
                Domain          = args.Domain,
                LDAPFilter      = args.ComputerLDAPFilter,
                SearchBase      = args.ComputerSearchBase,
                Unconstrained   = args.Unconstrained,
                OperatingSystem = args.OperatingSystem,
                ServicePack     = args.ServicePack,
                SiteName        = args.SiteName,
                Server          = args.Server,
                SearchScope     = args.SearchScope,
                ResultPageSize  = args.ResultPageSize,
                ServerTimeLimit = args.ServerTimeLimit,
                Tombstone       = args.Tombstone,
                Credential      = args.Credential
            };

            if (!string.IsNullOrEmpty(args.ComputerDomain))
            {
                ComputerSearcherArguments.Domain = args.ComputerDomain;
            }

            var UserSearcherArguments = new Args_Get_DomainUser
            {
                Properties      = new[] { "samaccountname" },
                Identity        = args.UserIdentity,
                Domain          = args.Domain,
                LDAPFilter      = args.UserLDAPFilter,
                SearchBase      = args.UserSearchBase,
                AdminCount      = args.UserAdminCount,
                AllowDelegation = args.AllowDelegation,
                Server          = args.Server,
                SearchScope     = args.SearchScope,
                ResultPageSize  = args.ResultPageSize,
                ServerTimeLimit = args.ServerTimeLimit,
                Tombstone       = args.Tombstone,
                Credential      = args.Credential
            };

            if (!string.IsNullOrEmpty(args.UserDomain))
            {
                UserSearcherArguments.Domain = args.UserDomain;
            }

            string[] TargetComputers = null;

            // first, build the set of computers to enumerate
            if (args.ComputerName != null)
            {
                TargetComputers = args.ComputerName;
            }
            else
            {
                if (args.Stealth)
                {
                    Logger.Write_Verbose($@"[Find-DomainUserLocation] Stealth enumeration using source: {args.StealthSource}");
                    var TargetComputerArrayList = new System.Collections.ArrayList();

                    if (args.StealthSource.ToString().IsRegexMatch("File|All"))
                    {
                        Logger.Write_Verbose("[Find-DomainUserLocation] Querying for file servers");
                        var FileServerSearcherArguments = new Args_Get_DomainFileServer
                        {
                            Domain          = new[] { args.Domain },
                            SearchBase      = args.ComputerSearchBase,
                            Server          = args.Server,
                            SearchScope     = args.SearchScope,
                            ResultPageSize  = args.ResultPageSize,
                            ServerTimeLimit = args.ServerTimeLimit,
                            Tombstone       = args.Tombstone,
                            Credential      = args.Credential
                        };
                        if (!string.IsNullOrEmpty(args.ComputerDomain))
                        {
                            FileServerSearcherArguments.Domain = new[] { args.ComputerDomain }
                        }
                        ;
                        var FileServers = GetDomainFileServer.Get_DomainFileServer(FileServerSearcherArguments);
                        TargetComputerArrayList.AddRange(FileServers);
                    }
                    if (args.StealthSource.ToString().IsRegexMatch("DFS|All"))
                    {
                        Logger.Write_Verbose(@"[Find-DomainUserLocation] Querying for DFS servers");
                        // { TODO: fix the passed parameters to Get-DomainDFSShare
                        // $ComputerName += Get-DomainDFSShare -Domain $Domain -Server $DomainController | ForEach-Object {$_.RemoteServerName}
                    }
                    if (args.StealthSource.ToString().IsRegexMatch("DC|All"))
                    {
                        Logger.Write_Verbose(@"[Find-DomainUserLocation] Querying for domain controllers");
                        var DCSearcherArguments = new Args_Get_DomainController
                        {
                            LDAP       = true,
                            Domain     = args.Domain,
                            Server     = args.Server,
                            Credential = args.Credential
                        };
                        if (!string.IsNullOrEmpty(args.ComputerDomain))
                        {
                            DCSearcherArguments.Domain = args.ComputerDomain;
                        }
                        var DomainControllers = GetDomainController.Get_DomainController(DCSearcherArguments).Select(x => (x as LDAPProperty).dnshostname).ToArray();
                        TargetComputerArrayList.AddRange(DomainControllers);
                    }
                    TargetComputers = TargetComputerArrayList.ToArray() as string[];
                }
            }
            if (args.ComputerName != null)
            {
                TargetComputers = args.ComputerName;
            }
            else
            {
                if (args.Stealth)
                {
                    Logger.Write_Verbose($@"[Find-DomainUserLocation] Stealth enumeration using source: {args.StealthSource}");
                    var TargetComputerArrayList = new System.Collections.ArrayList();

                    if (args.StealthSource.ToString().IsRegexMatch("File|All"))
                    {
                        Logger.Write_Verbose("[Find-DomainUserLocation] Querying for file servers");
                        var FileServerSearcherArguments = new Args_Get_DomainFileServer
                        {
                            Domain          = new[] { args.Domain },
                            SearchBase      = args.ComputerSearchBase,
                            Server          = args.Server,
                            SearchScope     = args.SearchScope,
                            ResultPageSize  = args.ResultPageSize,
                            ServerTimeLimit = args.ServerTimeLimit,
                            Tombstone       = args.Tombstone,
                            Credential      = args.Credential
                        };
                        if (!string.IsNullOrEmpty(args.ComputerDomain))
                        {
                            FileServerSearcherArguments.Domain = new[] { args.ComputerDomain }
                        }
                        ;
                        var FileServers = GetDomainFileServer.Get_DomainFileServer(FileServerSearcherArguments);
                        TargetComputerArrayList.AddRange(FileServers);
                    }
                    if (args.StealthSource.ToString().IsRegexMatch("DFS|All"))
                    {
                        Logger.Write_Verbose(@"[Find-DomainUserLocation] Querying for DFS servers");
                        // { TODO: fix the passed parameters to Get-DomainDFSShare
                        // $ComputerName += Get-DomainDFSShare -Domain $Domain -Server $DomainController | ForEach-Object {$_.RemoteServerName}
                    }
                    if (args.StealthSource.ToString().IsRegexMatch("DC|All"))
                    {
                        Logger.Write_Verbose(@"[Find-DomainUserLocation] Querying for domain controllers");
                        var DCSearcherArguments = new Args_Get_DomainController
                        {
                            LDAP       = true,
                            Domain     = args.Domain,
                            Server     = args.Server,
                            Credential = args.Credential
                        };
                        if (!string.IsNullOrEmpty(args.ComputerDomain))
                        {
                            DCSearcherArguments.Domain = args.ComputerDomain;
                        }
                        var DomainControllers = GetDomainController.Get_DomainController(DCSearcherArguments).Select(x => (x as LDAPProperty).dnshostname).ToArray();
                        TargetComputerArrayList.AddRange(DomainControllers);
                    }
                    TargetComputers = TargetComputerArrayList.ToArray() as string[];
                }
                else
                {
                    Logger.Write_Verbose("[Find-DomainUserLocation] Querying for all computers in the domain");
                    TargetComputers = GetDomainComputer.Get_DomainComputer(ComputerSearcherArguments).Select(x => (x as LDAPProperty).dnshostname).ToArray();
                }
            }
            Logger.Write_Verbose($@"[Find-DomainUserLocation] TargetComputers length: {TargetComputers.Length}");
            if (TargetComputers.Length == 0)
            {
                throw new Exception("[Find-DomainUserLocation] No hosts found to enumerate");
            }

            // get the current user so we can ignore it in the results
            string CurrentUser;

            if (args.Credential != null)
            {
                CurrentUser = args.Credential.UserName;
            }
            else
            {
                CurrentUser = Environment.UserName.ToLower();
            }

            // now build the user target set
            string[] TargetUsers = null;
            if (args.ShowAll)
            {
                TargetUsers = new string[] { };
            }
            else if (args.UserIdentity != null || args.UserLDAPFilter != null || args.UserSearchBase != null || args.UserAdminCount || args.UserAllowDelegation)
            {
                TargetUsers = GetDomainUser.Get_DomainUser(UserSearcherArguments).Select(x => (x as LDAPProperty).samaccountname).ToArray();
            }
            else
            {
                var GroupSearcherArguments = new Args_Get_DomainGroupMember
                {
                    Identity        = args.UserGroupIdentity,
                    Recurse         = true,
                    Domain          = args.UserDomain,
                    SearchBase      = args.UserSearchBase,
                    Server          = args.Server,
                    SearchScope     = args.SearchScope,
                    ResultPageSize  = args.ResultPageSize,
                    ServerTimeLimit = args.ServerTimeLimit,
                    Tombstone       = args.Tombstone,
                    Credential      = args.Credential
                };
                TargetUsers = GetDomainGroupMember.Get_DomainGroupMember(GroupSearcherArguments).Select(x => x.MemberName).ToArray();
            }

            Logger.Write_Verbose($@"[Find-DomainUserLocation] TargetUsers length: {TargetUsers.Length}");
            if ((!args.ShowAll) && (TargetUsers.Length == 0))
            {
                throw new Exception("[Find-DomainUserLocation] No users found to target");
            }

            var LogonToken = IntPtr.Zero;

            if (args.Credential != null)
            {
                if (args.Delay != 0 || args.StopOnSuccess)
                {
                    LogonToken = InvokeUserImpersonation.Invoke_UserImpersonation(new Args_Invoke_UserImpersonation
                    {
                        Credential = args.Credential
                    });
                }
                else
                {
                    LogonToken = InvokeUserImpersonation.Invoke_UserImpersonation(new Args_Invoke_UserImpersonation
                    {
                        Credential = args.Credential,
                        Quiet      = true
                    });
                }
            }

            var rets = new List <UserLocation>();

            // only ignore threading if -Delay is passed
            if (args.Delay != 0 /* || args.StopOnSuccess*/)
            {
                Logger.Write_Verbose($@"[Find-DomainUserLocation] Total number of hosts: {TargetComputers.Count()}");
                Logger.Write_Verbose($@"[Find-DomainUserLocation] Delay: {args.Delay}, Jitter: {args.Jitter}");

                var Counter = 0;
                var RandNo  = new System.Random();

                foreach (var TargetComputer in TargetComputers)
                {
                    Counter = Counter + 1;

                    // sleep for our semi-randomized interval
                    System.Threading.Thread.Sleep(RandNo.Next((int)((1 - args.Jitter) * args.Delay), (int)((1 + args.Jitter) * args.Delay)) * 1000);

                    Logger.Write_Verbose($@"[Find-DomainUserLocation] Enumerating server {TargetComputer} ({Counter} of {TargetComputers.Count()})");
                    var Result = _Find_DomainUserLocation(new[] { TargetComputer }, TargetUsers, CurrentUser, args.Stealth, args.CheckAccess, LogonToken);
                    if (Result != null)
                    {
                        rets.AddRange(Result);
                    }
                    if (Result != null && args.StopOnSuccess)
                    {
                        Logger.Write_Verbose("[Find-DomainUserLocation] Target user found, returning early");
                        return(rets);
                    }
                }
            }
            else
            {
                Logger.Write_Verbose($@"[Find-DomainUserLocation] Using threading with threads: {args.Threads}");
                Logger.Write_Verbose($@"[Find-DomainUserLocation] TargetComputers length: {TargetComputers.Length}");

                // if we're using threading, kick off the script block with New-ThreadedFunction
                // if we're using threading, kick off the script block with New-ThreadedFunction using the $HostEnumBlock + params
                System.Threading.Tasks.Parallel.ForEach(
                    TargetComputers,
                    TargetComputer =>
                {
                    var Result = _Find_DomainUserLocation(new[] { TargetComputer }, TargetUsers, CurrentUser, args.Stealth, args.CheckAccess, LogonToken);
                    lock (rets)
                    {
                        if (Result != null)
                        {
                            rets.AddRange(Result);
                        }
                    }
                });
            }

            if (LogonToken != IntPtr.Zero)
            {
                InvokeRevertToSelf.Invoke_RevertToSelf(LogonToken);
            }
            return(rets);
        }
Пример #50
0
        /// <summary>
        /// 形成申请单报告组的标本组【4】
        /// </summary>
        /// <returns></returns>
        private clsAppSampleGroupCollection m_objGenerateAppSampleGroups()
        {
            m_objGenerateAppUnitItems();

            clsAppSampleGroupCollection objSampleGroups = new clsAppSampleGroupCollection();

            foreach (clsLIS_AppApplyUnit objAppUnit in m_objAppApplyUnits)
            {
                // 样本组是否存在
                bool blnAppSampleGroupExist = false;

                clsSampleGroup_VO objSampleGroupVO = null;
                long lngRes = clsSampleGroupSmp.s_obj.m_lngGetSampleGoupVO(objAppUnit.m_StrApplyUnitID, out objSampleGroupVO);

                if (lngRes > 0 && objSampleGroupVO != null)
                {
                    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;
                            objAppSampleGroup.m_ObjAppCheckItems.Add(objAppCheckItem);
                        }
                    }
                }
            }
            return(objSampleGroups);
        }
Пример #51
0
        /// <summary>
        /// Expande una consulta de usuario mediante MSEC (Modelo Semántico de Expansión de Consulta)
        /// </summary>
        /// <param name="consulta">Cadena de consulta digitada por el usuario</param>
        /// <param name="ontModel">Ontologia de dominio</param>
        /// <returns>Cadena de consulta expandida</returns>
        public string expandirConsulta(string consulta, OntModel ontModel, string tipoAnalizador, string strontologia)
        {
            //conversion a minusculas de la cadena de consulta
            consulta = consulta.ToLower();

            //Se crea un objeto de tipo AnalizadorLexico para eliminar los stopwords de la consulta de usuario, Libreria utilizada:Lucenet.Net
            AnalizadorLexico analizador = new AnalizadorLexico();

            //Obtencion de palabras clave de la consulta
            System.Collections.ArrayList ListKeyWords = new System.Collections.ArrayList();
            ListKeyWords = analizador.getKeywords(consulta, tipoAnalizador);

            //Cargar la Ontologia
            OntologiaDominio ontologia = new OntologiaDominio();

            ontologia.Model = ontModel;

            //Se almacenan los conceptos e individuos de la ontologia en la BD para su posterior uso
            //ontologia.AlamcenarConceptos(Conceptos);

            //identificacion de Conceptos
            ontologia.termsIdentification(ListKeyWords);
            System.Collections.ArrayList lcc = ontologia.ListConceptoCompuesto;
            System.Collections.ArrayList lcs = ontologia.ListConceptoSimple;
            lcc.AddRange(lcs);                                                   //Union de conceptos simples y compuestos
            System.Collections.ArrayList lcr = ontologia.ListRestrictionConceps; //conceptos de restricciones
            //Se extraen conceptos de similitud entre la combinatoria de pares de concepto de lcc
            //System.Collections.ArrayList lce = ontologia.similarityBetweenConcepts(lcc);

            //Añadimos los conceptos hijos e instancias para hacer la consulta más precisa

            string consultaExpandida = ontologia.CadenaExpandConsult;

            foreach (string concepto in lcc)
            {
                List <OntologyConceptCopy> hijos = new List <OntologyConceptCopy>();
                hijos = ontologia.ObtenerConceptosHijos(ontModel, concepto, tipoAnalizador, strontologia);
                foreach (OntologyConceptCopy oncp in hijos)
                {
                    if (!consultaExpandida.Contains(oncp.OntCopyNameConcept))
                    {
                        consultaExpandida += " + " + oncp.OntCopyNameConcept;
                    }
                }
            }

            //string consultaExpandida = ontologia.CadenaExpandConsult;
            int pos = consultaExpandida.IndexOf("+");

            consultaExpandida = consultaExpandida.Substring(pos + 1);

            //foreach (string similitudConcept in lce)
            //{
            //    if (similitudConcept != "" && !lcc.Contains(similitudConcept) && !lcr.Contains(similitudConcept))
            //        consultaExpandida += " + " + similitudConcept;
            //}

            string auxConsultaExpandida = consultaExpandida;

            auxConsultaExpandida = auxConsultaExpandida.Replace("|", " ");
            auxConsultaExpandida = auxConsultaExpandida.Replace(")", " ");
            auxConsultaExpandida = auxConsultaExpandida.Replace("(", " ");
            auxConsultaExpandida = auxConsultaExpandida.Replace("+", " ");
            auxConsultaExpandida = auxConsultaExpandida.Replace("     ", ",");
            auxConsultaExpandida = auxConsultaExpandida.Replace("    ", ",");
            auxConsultaExpandida = auxConsultaExpandida.Replace("   ", ",");
            auxConsultaExpandida = auxConsultaExpandida.Replace("  ", ",");
            auxConsultaExpandida = auxConsultaExpandida.Replace(" ", ",");

            string[]  token = auxConsultaExpandida.Split(',');
            ArrayList listKeywordsConsExp = new ArrayList();

            listKeywordsConsExp.AddRange(token);
            listKeywordsConsExp.RemoveAt(0);

            consultaExpandida  = consultaExpandida.Replace("_", " ");
            consultaExpandida += ontologia.ConceptSynonym;

            //Finalmente le añadimos los términos que no se encontraron en la ontología
            //Primero se hace una copia en minusculas para comparar con los términos originales en minusculas y así no repetir concepto
            System.Collections.ArrayList consultaExpandidaTemp = new System.Collections.ArrayList();
            consultaExpandidaTemp.AddRange(listKeywordsConsExp);
            int i = 0;

            foreach (string terminoexp in listKeywordsConsExp)
            {
                consultaExpandidaTemp[i] = terminoexp.ToLower();
                i++;
            }
            foreach (string termino in ListKeyWords)
            {
                if (!consultaExpandidaTemp.Contains(termino.ToLower()))
                {
                    consultaExpandida += " &" + termino;
                }
            }

            //Retornar la cadena de consulta expandida
            return(consultaExpandida);
        }
Пример #52
0
        static void Main(string[] args)
        {
            /* ArrayList类删除元素的四种方法:
             *      1、ArrayList(变量名).Remove(值);
             *      2、ArrayList(变量名).RemoveAt(索引值)
             *      3、ArrayList(变量名).RemoveRange(开始索引值,需要删除的元素个数)
             *      4、ArrayList(变量名).Clear()  //q清除所有元素
             */

            //ArrayList.Remove()
            System.Collections.ArrayList MyArrayList = new System.Collections.ArrayList();
            string[] MyStringArray = { "张三", "李四", "王五", "赵六" };
            MyArrayList.AddRange(MyStringArray);
            MyArrayList.Add(3.14);
            MyArrayList.Add(2298);
            MyArrayList.Add('A');

            //第一遍未进行删除 - 遍历数组
            foreach (object MyEach in MyArrayList)
            {
                Console.WriteLine(MyEach);
            }

            Console.WriteLine("============分割条===========");

            //删除元素
            MyArrayList.Remove("张三");

            //第二遍进行删除元素后 - 遍历数组
            foreach (object MyEach in MyArrayList)
            {
                Console.WriteLine(MyEach);
            }

            Console.WriteLine("============分割条===========");
            //ArrayList(变量名).RemoveAt(索引值)
            //删除元素
            MyArrayList.RemoveAt(0);

            //第三遍进行删除元素后 - 遍历数组
            foreach (object MyEach in MyArrayList)
            {
                Console.WriteLine(MyEach);
            }

            Console.WriteLine("============分割条===========");
            //ArrayList(变量名).RemoveRange(开始索引值,需要删除的元素个数)
            //删除元素
            MyArrayList.RemoveRange(0, 2);

            //第四遍进行删除元素后 - 遍历数组
            foreach (object MyEach in MyArrayList)
            {
                Console.WriteLine(MyEach);
            }

            Console.WriteLine("============分割条===========");
            //ArrayList(变量名).RemoveRange(开始索引值,需要删除的元素个数)
            //删除所有元素
            MyArrayList.Clear();

            //第五遍进行删除元素后 - 遍历数组
            foreach (object MyEach in MyArrayList)
            {
                Console.WriteLine(MyEach);
            }


            Console.ReadKey();
        }
Пример #53
0
        /// <summary>
        /// 向发送客户端发送数据事情
        /// </summary>
        /// <param name="data">发送的数据</param>
        /// <param name="endResponse"></param>
        public void Send(WebMeta data, bool endResponse)
        {
            WebResponse response = this.Response;

            if (data.ContainsKey("type") && data["type"] == "UI.Event")
            {
                if (runtime.Client.UIEvent != null)
                {
                    var click = runtime.Client.UIEvent;
                    var key   = data["key"];
                    if (String.Equals(key, "Click") && data.GetDictionary()["value"] is ListItem)
                    {
                        runtime.Client.UIEvent = null;
                        runtime.Client.Session.Storage(new Hashtable(), this);
                        var value    = data.GetDictionary()["value"] as ListItem;
                        var objValue = click.Send();
                        if (objValue is Hashtable)
                        {
                            var val = objValue as Hashtable;
                            var em  = val.GetEnumerator();

                            while (em.MoveNext())
                            {
                                if (String.Equals(em.Value, "Value"))
                                {
                                    val[em.Key] = value.Value;
                                    val[String.Format("{0}_Text", em.Key)] = value.Text;
                                    //val.Put(em.Key as string, value.Value);
                                    break;
                                }
                            }
                            response.Redirect(click.Model, click.Command, new WebMeta(val), false);
                        }
                        else if (objValue is WebMeta)
                        {
                            var val = objValue as WebMeta;
                            var em  = val.GetDictionary().GetEnumerator();

                            while (em.MoveNext())
                            {
                                if (String.Equals(em.Value, "Value"))
                                {
                                    val.Put(em.Key as string, value.Value);
                                    val[String.Format("{0}_Text", em.Key)] = value.Text;
                                    break;
                                }
                            }

                            response.Redirect(click.Model, click.Command, val, false);
                        }
                        else
                        {
                            response.Redirect(click.Model, click.Command, value.Value, false);
                        }
                    }
                }
            }
            response.ClientEvent |= WebEvent.DataEvent;
            if (response.Headers.ContainsKey("DataEvent"))
            {
                var ts = response.Headers.GetDictionary()["DataEvent"];
                if (ts is WebMeta)
                {
                    response.Headers.Set("DataEvent", (WebMeta)ts, data);
                }
                else if (ts is IDictionary)
                {
                    response.Headers.Set("DataEvent", new WebMeta((IDictionary)ts), data);
                }
                else if (ts is Array)
                {
                    var ats = new System.Collections.ArrayList();
                    ats.AddRange((Array)ts);
                    ats.Add(data);

                    response.Headers.Set("DataEvent", (WebMeta[])ats.ToArray(typeof(WebMeta)));
                }
                else
                {
                    response.Headers.Set("DataEvent", data);
                }
            }
            else
            {
                response.Headers.Set("DataEvent", data);
            }
            if (endResponse)
            {
                response.ClientEvent ^= response.ClientEvent & WebEvent.Normal;
                this.End();
            }
        }
Пример #54
0
 public void AddAuthors(params Person[] authors)
 {
     AuthList.AddRange(authors.ToList());
 }
Пример #55
0
        private static void LinqTests()
        {
            string[]             names         = { "Tom", "Dick", "Harry" };
            IEnumerable <string> filteredNames = System.Linq.Enumerable.Where(names, n => n.Length >= 4);

            foreach (string n in filteredNames)
            {
                Console.Write(n + "|");
            }
            IEnumerable <string> filteredNames2 = names.Where(n => n.Length >= 4);
            // Projecting
            IEnumerable <string> blee = names.Select(n => n.ToUpper());
            var query = names.Select(n => new
            {
                Name   = n,
                Length = n.Length
            });

            // Take and Skip
            int[]             numbers    = { 10, 9, 8, 7, 6 };
            IEnumerable <int> firstThree = numbers.Take(3);      // firstThree is { 10, 9 , 8 }
            IEnumerable <int> lastTwo    = numbers.Skip(3);
            // Element operators
            int firstNumber    = numbers.First();                     // 10
            int lastNumber     = numbers.Last();                      // 6
            int secondNumber   = numbers.ElementAt(2);                // 8
            int firstOddNumber = numbers.First(n => n % 2 == 1);      // 9
            // Aggregation operators
            int    count    = numbers.Count();                        // 5
            int    min      = numbers.Min();                          // 6
            int    max      = numbers.Max();                          // 10
            double avg      = numbers.Average();                      // 8
            int    evenNums = numbers.Count(n => n % 2 == 0);         // 3
            int    maxRemainderAfterDivBy5 = numbers.Max(n => n % 5); // 4
            // Quantitfiers
            bool hasTheNumberNine        = numbers.Contains(9);       // true
            bool hasMoreThanZeroElements = numbers.Any();             // true
            bool hasOddNum = numbers.Any(n => n % 2 == 1);            // true
            bool allOddNum = numbers.All(n => n % 2 == 1);            // false

            // Set operators
            int[]             seq1        = { 1, 2, 3 }, seq2 = { 3, 4, 5 };
            IEnumerable <int> concat      = seq1.Concat(seq2);      // { 1, 2, 3, 3, 4, 5 }
            IEnumerable <int> union       = seq1.Union(seq2);       // { 1, 2, 3, 4, 5 }
            IEnumerable <int> commonality = seq1.Intersect(seq2);   // { 3 }
            IEnumerable <int> difference1 = seq1.Except(seq2);      // { 1, 2 }
            IEnumerable <int> difference2 = seq2.Except(seq1);      // { 4, 5 }
            // Deferred Execution
            var numbers2 = new System.Collections.Generic.List <int> {
                1
            };
            IEnumerable <int> query2 = numbers.Select(n => n * 10);

            numbers2.Add(2);                                        // Sneak in an extra element
            // Deferred / Lazy (evaluation)
            foreach (int n in query2)
            {
                Console.Write(n + "|");
            }
            // Cache/freeze - avoid reexecution
            var numbers3 = new System.Collections.Generic.List <int>()
            {
                1, 2
            };

            System.Collections.Generic.List <int> timesTen = numbers.Select(n => n * 10).ToList(); // Executes immediately into a List<int>
            numbers3.Clear();
            Console.WriteLine(timesTen.Count);                                                     // Still 2
            names.Where(n => n.Length == names.Min(n2 => n2.Length));

            // Chaining Query Operators
            string[]             names3 = { "Tom", "Dick", "Harry", "Mary", "Jay" };
            IEnumerable <string> query3 = names3
                                          .Where(n => n.Contains("a"))
                                          .OrderBy(n => n.Length)
                                          .Select(n => n.ToUpper());

            foreach (string name in query3)
            {
                Console.Write(name + "|");                                              // Result: JAY|MARY|HARRY
            }
            // Query Expressions
            IEnumerable <string> query4 = from n in names3
                                          where n.Contains("a")
                                          orderby n.Length
                                          select n.ToUpper();

            IEnumerable <string> query5 = from n in names3
                                          where n.Length == names3.Min(n2 => n2.Length)
                                          select n;

            // The Let keyword
            IEnumerable <string> query6 = from n in names3
                                          let vowelless = Regex.Replace(n, "[aeiou]", "")
                                                          where vowelless.Length > 2
                                                          orderby vowelless
                                                          select n + " - " + vowelless;
            // Translates to
            IEnumerable <string> query6a = names3
                                           .Select(n => new
            {
                n         = n,
                vowelless = Regex.Replace(n, "[aeiou]", "")
            })
                                           .Where(temp0 => (temp0.vowelless.Length > 2))
                                           .OrderBy(temp0 => temp0.vowelless)
                                           .Select(temp0 => ((temp0.n + " - ") + temp0.vowelless));

            // Query Continuations
            IEnumerable <string> query7 = from c in "The quick brown tiger".Split()
                                          select c.ToUpper() into upper
                                              where upper.StartsWith("T")
                                          select upper;                                 // Result: "THE", "TIGER"

            // Translates to
            IEnumerable <string> query7a = "The quick brown tiger".Split()
                                           .Select(c => c.ToUpper())
                                           .Where(upper => upper.StartsWith("T"));

            // Multiple Generators
            int[]                numbersA = { 1, 2, 3 };
            string[]             lettersA = { "a", "b" };
            IEnumerable <string> query8   = from n in numbersA
                                            from l in lettersA
                                            select n.ToString() + l;

            IEnumerable <string> query8a = numbers.SelectMany(
                n => lettersA,
                (n, l) => (n.ToString() + l));

            string[]             players = { "Tom", "Jay", "Mary" };
            IEnumerable <string> query9  = from name1 in players
                                           from name2 in players
                                           where name1.CompareTo(name2) < 0
                                           orderby name1, name2
            select name1 + " vs " + name2;                                              // Result: { "Jay vs Mary", "Jay vs Tom", "Mary vs Tom" }

            string[]             fullNames = { "Anne Williams", "John Fred Smith", "Sue Green" };
            IEnumerable <string> query10   = from fullName in fullNames
                                             from name in fullName.Split()
                                             select name + " come from " + fullName;

            // Joining
            var customers = new[]
            {
                new { ID = 1, Name = "Tom" },
                new { ID = 2, Name = "Dick" },
                new { ID = 3, Name = "Harry" },
            };
            var purchases = new[]
            {
                new { CustomerID = 1, Product = "House" },
                new { CustomerID = 2, Product = "Boat" },
                new { CustomerID = 3, Product = "Car" },
                new { CustomerID = 4, Product = "Holiday" },
            };
            IEnumerable <string> query11 = from c in customers
                                           join p in purchases on c.ID equals p.CustomerID
                                           select c.Name + " bought a " + p.Product;
            // Translates to
            IEnumerable <string> query11a = customers
                                            .Join(purchases, c => c.ID, p => p.CustomerID, (c, p) => c.Name + " bought a " + p.Product);

            // GroupJoin
            Purchase[] purchases2 = new Purchase[]
            {
                new Purchase(1, "House"),
                new Purchase(2, "Boat"),
                new Purchase(3, "Car"),
                new Purchase(4, "Holiday")
            };

            IEnumerable <IEnumerable <Purchase> > query12 = from c in customers
                                                            join p in purchases2 on c.ID equals p.CustomerID into custPurchases
                                                            select custPurchases;         // custPurchases is a sequence

            foreach (IEnumerable <Purchase> purchaseSequence in query12)
            {
                foreach (Purchase p in purchaseSequence)
                {
                    Console.WriteLine(p.Description);
                }
            }
            var query13 = from c in customers
                          join p in purchases2 on c.ID equals p.CustomerID into custPurchases
                          select new { CustName = c.Name, custPurchases };
            var query14 = from c in customers
                          select new
            {
                CustName      = c.Name,
                custPurchases = purchases2.Where(p => c.ID == p.CustomerID)
            };

            // Zip
            int[]                numbersZip = { 3, 5, 7 };
            string[]             words      = { "three", "five", "seven", "ignored" };
            IEnumerable <string> zip        =
                numbersZip.Zip(words, (n, w) => n + "=" + w);

            // Ordering
            IEnumerable <string> query15 = from n in names
                                           orderby n.Length, n
            select n;
            // Translates to
            IEnumerable <string> query15a = names.OrderBy(n => n.Length).ThenBy(n => n);

            IEnumerable <string> query16 = from n in names
                                           orderby n.Length descending, n
            select n;
            // Translates to
            IEnumerable <string> query16a = names.OrderByDescending(n => n.Length).ThenBy(n => n);

            // Grouping
            var query17 = from name in names
                          group name by name.Length;
            // Translates to
            IEnumerable <IGrouping <int, string> > query17a = names.GroupBy(name => names.Length);

            foreach (IGrouping <int, string> grouping in query17)
            {
                Console.WriteLine("\r\n Length=" + grouping.Key + ":");
                foreach (string name in grouping)
                {
                    Console.WriteLine(" " + name);
                }
            }
            var query18 = from name in names group name.ToUpper() by name.Length;

            // Translates to
            var query18a = names.GroupBy(
                name => name.Length,
                name => name.ToUpper());

            var query19 = from name in names
                          group name.ToUpper() by name.Length into grouping
                          orderby grouping.Key
                          select grouping;

            var query19b = from name in names
                           group name.ToUpper() by name.Length into grouping
                               where grouping.Count() == 2
                           select grouping;

            // OfType and Cast
            var classicList = new System.Collections.ArrayList();

            classicList.AddRange(new int[] { 3, 4, 5 });
            IEnumerable <int> sequence1 = classicList.Cast <int>();
            var aaa = from int x in classicList select x;
            // Translates to
            var bbb = from x in classicList.Cast <int>() select x;
        }
Пример #56
0
        public void OutputHeader(UMC.Web.WebMeta header, int index)
        {
            if (this.OuterHeaders == null)
            {
                this.OuterHeaders = new Hashtable();;
            }

            var dic = header.GetDictionary();

            var em = dic.GetEnumerator();

            while (em.MoveNext())
            {
                var key = em.Key.ToString();
                if (key == "DataEvent")
                {
                    var value = em.Value;
                    if (this.OuterHeaders.ContainsKey(key))
                    {
                        var ats = new System.Collections.ArrayList();
                        var ts  = this.OuterHeaders[key];

                        if (ts is Array)
                        {
                            if (index == -1)
                            {
                                ats.AddRange((Array)ts);
                            }
                            else
                            {
                                ats.InsertRange(index, (Array)ts);
                            }
                        }
                        else
                        {
                            if (index == -1)
                            {
                                ats.Add(ts);
                            }
                            else
                            {
                                ats.Insert(index, ts);
                            }
                        }
                        if (value is Array)
                        {
                            if (index == -1)
                            {
                                ats.AddRange((Array)value);
                            }
                            else
                            {
                                ats.InsertRange(index, (Array)value);
                            }
                        }
                        else
                        {
                            if (index == -1)
                            {
                                ats.Add(value);
                            }
                            else
                            {
                                ats.Insert(index, value);
                            }
                        }
                        this.OuterHeaders[key] = ats.ToArray();
                    }
                    else
                    {
                        this.OuterHeaders[em.Key] = em.Value;
                    }
                }
                else
                {
                    this.OuterHeaders[em.Key] = em.Value;
                }
            }
        }
Пример #57
0
        void ComboBox1SelectedIndexChanged(object sender, EventArgs e)
        {
            perfobject.Items.Clear();
            string[] instanceNames;
            System.Collections.ArrayList counters = new System.Collections.ArrayList();
            if (comboBox1.SelectedIndex != -1)
            {
                bool IsFinded = false;
                System.Diagnostics.PerformanceCounterCategory mycat = new System.Diagnostics.PerformanceCounterCategory(comboBox1.SelectedItem.ToString());
                instanceNames = mycat.GetInstanceNames();
                int proccount = 0;
                for (int i = 0; i < instanceNames.Length; i++)
                {
                    string fortest  = instanceNames[i].ToLower();
                    int    lastdiez = fortest.LastIndexOf("#");
                    if (lastdiez != -1)
                    {
                        fortest = fortest.Remove(lastdiez, fortest.Length - lastdiez);
                    }
                    if (ProcessName.ToLower().Contains(fortest))
                    {
                        proccount++;
                        if (proccount >= 2)
                        {
                            break;
                        }
                    }
                }

                for (int i = 0; i < instanceNames.Length; i++)
                {
                    IsFinded = false;
                    System.Diagnostics.PerformanceCounterCategory mycattest = new System.Diagnostics.PerformanceCounterCategory(".NET CLR Memory");
                    System.Collections.ArrayList testcounters = new System.Collections.ArrayList();
                    testcounters.AddRange(mycattest.GetCounters(instanceNames[i]));

                    foreach (System.Diagnostics.PerformanceCounter tcounter in testcounters)
                    {
                        if (tcounter.CounterName == "Process ID")
                        {
                            if ((int)tcounter.RawValue == procid)
                            {
                                IsFinded = true;
                            }
                            else
                            {
                                IsFinded = false;
                            }
                        }
                    }


                    if (!IsFinded || proccount >= 2)
                    {
                        string fortest  = instanceNames[i];
                        int    lastdiez = fortest.LastIndexOf("#");
                        if (lastdiez != -1)
                        {
                            fortest = fortest.Remove(lastdiez, fortest.Length - lastdiez);
                        }
                        if (ProcessName.ToLower().Contains(fortest.ToLower()))
                        {
                            IsFinded = true;
                            string[]     prcdet   = new string[] { "" };
                            ListViewItem proctadd = new ListViewItem(prcdet);
                            perfobject.Items.Add(proctadd);
                            prcdet   = new string[] { instanceNames[i] };
                            proctadd = new ListViewItem(prcdet);
                            perfobject.Items.Add(proctadd);
                        }
                    }

                    if (IsFinded)
                    {
                        counters.AddRange(mycat.GetCounters(instanceNames[i]));
                        // Add the retrieved counters to the list.
                        foreach (System.Diagnostics.PerformanceCounter counter in counters)
                        {
                            string[]     prcdetails = new string[] { counter.CounterName, counter.RawValue.ToString() };
                            ListViewItem proc       = new ListViewItem(prcdetails);
                            perfobject.Items.Add(proc);
                        }
                    }
                    if (proccount < 2 && IsFinded)
                    {
                        break;
                    }
                }
            }
        }