Example #1
0
 public override ArrayList GetCardsInOrder()
 {
     ArrayList cards = new ArrayList(pair1);
     cards.AddRange(pair2);
     cards.AddRange(kickers);
     return cards;
 }
Example #2
0
    void OnGUI()
    {
        ArrayList textToDisplay = new ArrayList();
        string[] normalText = { "Score " + myGame.score,
                                "Max lvl " + myGame.playerLvl,
                                "Build points " + myGame.buildPoints,
                                "Herbivores " + myGame.herbovores.Count,
                                "Plants " + myGame.plants.Count + " out of " + myGame.maxPlants,
                                "Next enemy in " + (1 + (int)(EnemySpawner.enemySpawnTime - EnemySpawner.enemyTime)),
                                "Next plant in " + (1 + (int)(PlantSpawner.plantSpawnTime - PlantSpawner.plantTime)),
                            };

        string[] debugText = {
                                "Time scale " + Time.timeScale,
                            };

        textToDisplay.AddRange(normalText);
        if (myGame.debug)
        {
            textToDisplay.AddRange(debugText);
        }

        for (int i = 0; i < textToDisplay.Count; i++)
        {
            GUI.Box(new Rect(10, y_start + (line_height + line_offset) * i, line_width, line_height), textToDisplay[i].ToString());
        }
    }
Example #3
0
    public static ArrayList findDetachedVoxels(int [,,] mapData, int stopCode, IntVector3 point)
    {
        /*
        where i,j,k is a recently destroyed block, returns a list of IntVector3s of all blocks that should
        be detached, as well as the size of the blob that would contain them.
        */
        ArrayList detachedVoxels = new ArrayList ();

        allVisitedVoxels = new ArrayList ();
        ArrayList seeds = MDView.getNeighbors (mapData, point);

        for (int index=0; index<seeds.Count; index++) {

            IntVector3 seedPoint = (IntVector3)seeds [index];

            if (allVisitedVoxels.Contains (seedPoint)) {
                seeds.Remove (seedPoint);
                index--;
                continue;
            }

            ArrayList newVoxels = getBlob (mapData, stopCode, seedPoint);

            if (newVoxels.Count > 0) {
                detachedVoxels.AddRange (newVoxels);

            }

        }
        return detachedVoxels;
    }
Example #4
0
    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag ("Paddle")) {
            GameObject[] bricks = BrickController.GetBricks ();
            ArrayList hitBricks = new ArrayList ();

            if (bricks.Length <= destroyBlockCount) {
                //Just break all the bricks if we only have as many bricks left as we should hit
                hitBricks.AddRange (bricks);
            } else {
                //Select some random bricks.
                for (int i = 0; i < destroyBlockCount; i++) {
                    while (hitBricks.Count < i + 1) {
                        int index = Random.Range (0, bricks.Length - 1);
                        GameObject b = bricks [index];
                        if (!hitBricks.Contains (b)) {
                            hitBricks.Add (b);
                        }
                    }
                }
            }

            //Destroy some Bricks!
            foreach (GameObject b in hitBricks) {
                BrickController.HitBrick (b);
            }
            //Remove the carrot
            Destroy (this.gameObject);
        }
    }
		/// <summary>
		/// Retorna uma lista de arquivos, pesquisando em todos os diretórios.
		/// </summary>
		/// <param name="filter">O filtro</param>
		public override HoloFile[] GetFiles(string filter)
		{
			ArrayList files = new ArrayList();
			foreach (HoloDirectory dir in dirs)
				files.AddRange(dir.GetFiles(filter));
			return (HoloFile[]) CollectionUtils.ToArray(typeof(HoloFile), files);
		}
Example #6
0
File: test.cs Project: mono/gert
	static int RunTest (SqlConnection conn)
	{
		ArrayList persons = new ArrayList ();
		Person personA = new Person ("de Icaza", "Miguel",
			new DateTime (1925, 1, 31, 5, 8, 29, 998),
			new DateTime (1925, 1, 31, 5, 8, 0),
			new DateTime (2004, 4, 20, 3, 43, 55, 567));
		Person personB = new Person ("Pobst", "Jonathan",
			new DateTime (2007, 12, 01, 7, 9, 29, 999),
			new DateTime (2007, 12, 01, 7, 10, 0),
			new DateTime (2006, 12, 30, 23, 05, 1, 3));
		Person personC = new Person ("Toshok", "Chris",
			new DateTime (1973, 8, 13, 0, 0, 0),
			new DateTime (1973, 8, 13, 0, 0, 0),
			new DateTime (2004, 4, 20, 3, 43, 55, 563));
		Person personD = new Person ("Harper", "Jackson",
			new DateTime (1973, 8, 13, 0, 0, 59, 2),
			new DateTime (1973, 8, 13, 0, 1, 0),
			new DateTime (2004, 4, 20, 3, 43, 54, 0));
		persons.AddRange (new Person [] { personA, personB, personC, personD });

		SqlCommand cmd = new SqlCommand (create_table, conn);
		cmd.ExecuteNonQuery ();
		cmd.Dispose ();

		cmd = new SqlCommand ("INSERT INTO bug323646 VALUES (@name, @firstName, @birthDate, @created)", conn);
		foreach (Person person in persons) {
			cmd.Parameters.Add (CreateParameter ("@name", person.Name));
			cmd.Parameters.Add (CreateParameter ("@firstName", person.FirstName));
			cmd.Parameters.Add (CreateParameter ("@BirthdatE", person.BirthDate));
			cmd.Parameters.Add (CreateParameter ("@created", person.Created));
			cmd.ExecuteNonQuery ();
			cmd.Parameters.Clear ();
		}
		cmd.Dispose ();

		cmd = new SqlCommand ("SELECT * FROM bug323646 WHERE Created = @created", conn);
		cmd.Parameters.Add (CreateParameter ("@created", DateTime.Now));

		using (SqlDataReader dr = cmd.ExecuteReader ()) {
			Assert.IsFalse (dr.Read (), "#A");
		}

		foreach (Person person in persons) {
			cmd.Parameters ["@created"].Value = person.Created;

			using (SqlDataReader dr = cmd.ExecuteReader ()) {
				Assert.IsTrue (dr.Read (), "#B1");
				Assert.AreEqual (person.Name, dr.GetString (0), "#B2");
				Assert.AreEqual (person.FirstName, dr.GetString (1), "#B3");

				DateTime birthDate = (DateTime) dr.GetValue (2);
				Assert.AreEqual (person.ExpectedBirthDate, birthDate, "#B4");
				Assert.AreEqual (person.Created, dr.GetDateTime (3), "#B5");
				Assert.IsFalse (dr.Read (), "#B6");
			}
		}

		return 0;
	}
 public static EvaluatedHand EvaluateHand(ArrayList hand, ArrayList board)
 {
     ArrayList cards = new ArrayList(hand);
     cards.AddRange(board);
     Card[][] cardArray = GenerateCardArray(cards);
     EvaluatedHand evaluatedHand = CreateStraightFlush(cardArray);
     if (evaluatedHand == null){
         evaluatedHand = CreateFourOfAKind(cardArray);
     }
     if (evaluatedHand == null){
         evaluatedHand = CreateFullHouse(cardArray);
     }
     if (evaluatedHand == null){
         evaluatedHand = CreateFlush(cardArray);
     }
     if (evaluatedHand == null){
         evaluatedHand = CreateStraight(cardArray);
     }
     if (evaluatedHand == null){
         evaluatedHand = CreateThreeOfAKind(cardArray);
     }
     if (evaluatedHand == null){
         evaluatedHand = CreateTwoPair(cardArray);
     }
     if (evaluatedHand == null){
         evaluatedHand = CreateOnePair(cardArray);
     }
     if (evaluatedHand == null){
         evaluatedHand = CreateHighCards(cardArray);
     }
     return evaluatedHand;
 }
 public void AddText( string pText, int pIndex )
 {
     ArrayList list = new ArrayList();
     list.AddRange( mContents);
     list.Insert( pIndex, new GUIContent( pText));
     mContents = list.ToArray( typeof(GUIContent)) as GUIContent[];
 }
	protected void initAxeMan()
	{
		// Get the main camera
		Camera mainCam = Camera.main;
		// Play sound from main camera when axeman spawns
		mainCam.audio.PlayOneShot((AudioClip)axemanIntroSounds[Random.Range (0, bopperIdleSounds.Length)]);

		SpriteRenderer[] sceneObjects = FindObjectsOfType<SpriteRenderer>();
		treeList = new ArrayList ();
		if (player == null)
			player = GameObject.Find("Player");

		treeList.AddRange (getAllPlayerTrees ());

		foreach (SpriteRenderer sceneObject in sceneObjects)
		{
			if (sceneObject.sprite == null)
				continue;
			
			string name = sceneObject.sprite.name;
			if (name.Equals("cw_tree_2") || name.Equals("cw_tree_3") || name.Equals ("cw_tree_4") || name.Equals("cw_tree_5") || name.Equals("cw_tree_6"))
			{
				if (Vector3.Distance(panickedNPCPosition, sceneObject.gameObject.transform.position) < wanderRadius) {
					treeList.Add (sceneObject.gameObject);
				}
			}
		}
		
		this.SkinType = NPCSkinType.AxeMan;
	}
    /// Destroy child blocks
    public ArrayList DestroyChildBlocks()
    {
        var childCubes = from Transform cube in this.transform
            where cube.name == "Cube"
            select cube.gameObject;

        if (childCubes == null) return new ArrayList();

        // sum up child cube score to set into parent score
        this.gameObject.GetComponent<CubeInfo>().score +=
            childCubes
            .Select(cube => cube.GetComponent<CubeInfo>().score)
            .Sum();

        // store child cubes position
        ArrayList destroyPositions = new ArrayList();
        destroyPositions.AddRange(
            childCubes
            .Select(childCube => childCube.transform.position)
            .ToList()
        );

        // destroy child cubes
        childCubes
            .ToList()
            .ForEach(MonoBehaviour.Destroy);

        // perform event
        if (WhenDestroyChild != null) {
            WhenDestroyChild(this, EventArgs.Empty);
        }

        return destroyPositions;
    }
Example #11
0
    public void initialize(int numCharacters)
    {
        spawnPoints = new ArrayList ();

        for (int i = 1; i <= 40; i++) {
            GameObject tempObject = GameObject.Find("SpawnPoint" + i);

            if(tempObject)
                spawnPoints.Add(tempObject);
        }

        ArrayList initialSpawnPoints = new ArrayList();
        initialSpawnPoints.AddRange (spawnPoints);

        characterList = new ArrayList ();

        int randomSpawnIndex = Random.Range (0, initialSpawnPoints.Count - 1);
        makeCharacter("Player", "Materials/Player1Color", "Player", ((GameObject)initialSpawnPoints[randomSpawnIndex]).transform.position, new Color (0, 1, 0));
        initialSpawnPoints.RemoveAt (randomSpawnIndex);

        for(int j = 1; j < numCharacters; j++) {
            randomSpawnIndex = Random.Range (0, initialSpawnPoints.Count - 1);
            makeCharacter ("Player", "Materials/EnemyColor", "MediumAI", ((GameObject)initialSpawnPoints[randomSpawnIndex]).transform.position, new Color (1, 0, 0));
            initialSpawnPoints.RemoveAt (randomSpawnIndex);
        }
    }
    public static ArrayList GetAllChildren(GameObject parentGameObject, string[] excludeSubstrings, bool includeParent = false)
    {
        //returns an arraylist of all children, grandchildren, etc.
        //excludes all objects and their children if their name contains any string in excludeSubstrings

        ArrayList children = new ArrayList();

        if (includeParent)
            children.Add(parentGameObject);

        for (int i = 0; i < parentGameObject.transform.childCount; i++)
        {
            GameObject child = parentGameObject.transform.GetChild(i).gameObject;
            bool excludeChild = false;
            foreach (string substring in excludeSubstrings)
            {
                if (child.name.Contains(substring))
                {
                    excludeChild = true;
                    break;
                }
            }
            if (excludeChild)
                continue;

            children.Add(child);
            if (child.transform.childCount > 0)
                children.AddRange(GetAllChildren(child, excludeSubstrings, false));
        }
        return children;
    }
 /// <summary>
 /// 指定されたフォルダ以下にあるすべてのファイルを取得する(サブフォルダは含まれない)
 /// </summary>
 /// <param name="folder">ファイルを検索するフォルダ名。</param>
 /// <param name="searchPattern">ファイル名検索文字列
 /// ワイルドカード指定子(*, ?)を使用する。</param>
 /// <param name="files">見つかったファイル名のリスト</param>
 public static void GetDirectoryFiles(string folder, string searchPattern, ref ArrayList files)
 {
     //folderにあるファイルを取得する
     string[] fs = System.IO.Directory.GetFiles (folder, searchPattern);
     //ArrayListに追加する
     files.AddRange (fs);
 }
Example #14
0
 public void InsertionSortArrayListTest(int[] toSortInts, int[] expectedSortedInts)
 {
     ArrayList<int> toSort = new ArrayList<int>();
     toSort.AddRange(toSortInts);
     toSort.InsertionSort();
     CollectionAssert.AreEqual(toSort, expectedSortedInts);
 }
Example #15
0
 public void moveTowards(GameObject selectedTile)
 {
     if (!selectedTile) return;
     path = new ArrayList();
     ArrayList newPath = aStar(playerTile, selectedTile);
     if(newPath != null)
         path.AddRange(newPath);
 }
Example #16
0
    protected void Button_AddShow_Click(object sender, EventArgs e)
    {
        if (TextBox_Name.Text != "")
        {
            BindData();
            DataSet ds = new DataSet();
            ds.ReadXml(Server.MapPath("App_Data/Shows.xml"));
            ds.Tables[0].Rows.InsertAt(ds.Tables[0].NewRow(), ds.Tables[0].Rows.Count); //the new row is the last one in the dataset
            int i = ds.Tables[0].Rows.Count - 1; //Gets index of the last row

            //Sets the latest episode data to the local season/episode so user doesn't have to look it up on tvrage.com
            ArrayList tvRageArray = new ArrayList();
            WebClient quickInfoClient = new WebClient();
            String localSeason = "";
            String localEpisode = "";

            var tvRageHtml = quickInfoClient.DownloadString("http://www.tvrage.com/quickinfo.php?show=" + TextBox_Name.Text);
            tvRageArray.AddRange(tvRageHtml.Split(new char[] { '^', '@', '\n' }));

            for (int x = 0; x < tvRageArray.Count; x++)
            {
                if (Convert.ToString(tvRageArray[x]) == "Latest Episode")
                {
                    localSeason = Convert.ToString(tvRageArray[x + 1]).Substring(0, 2);
                    localEpisode = Convert.ToString(tvRageArray[x + 1]).Substring(3, 2);
                }
            }

            ds.Tables[0].Rows[i]["Name"] = TextBox_Name.Text.Trim();
            ds.Tables[0].Rows[i]["LocalSeason"] = localSeason;
            ds.Tables[0].Rows[i]["LocalEpisode"] = localEpisode;
            ds.Tables[0].Rows[i]["LatestSeason"] = "";
            ds.Tables[0].Rows[i]["LatestEpisode"] = "";
            ds.Tables[0].Rows[i]["LatestAirtime"] = "";
            ds.Tables[0].Rows[i]["LatestAbsoluteEpisode"] = "";
            ds.Tables[0].Rows[i]["LatestTitle"] = "";
            ds.Tables[0].Rows[i]["NextEpisode"] = "";
            ds.Tables[0].Rows[i]["NextAirtime"] = "";
            ds.Tables[0].Rows[i]["NextTitle"] = "";
            ds.Tables[0].Rows[i]["NextAbsoluteEpisode"] = "";
            ds.Tables[0].Rows[i]["Format"] = "";
            ds.Tables[0].Rows[i]["Language"] = "";
            ds.Tables[0].Rows[i]["SearchBy"] = DropDownList_NewSearchBy.SelectedValue;
            ds.Tables[0].Rows[i]["ShowURL"] = "";
            ds.Tables[0].Rows[i]["WeeklyAirtime"] = "";
            ds.Tables[0].Rows[i]["LastUpdate"] = "";
            ds.Tables[0].Rows[i]["NextSeason"] = "";

            //Removes entries in the textboxes
            TextBox_Name.Text = "";
            DropDownList_NewSearchBy.SelectedIndex = 0;

            ds.WriteXml(Server.MapPath("App_Data/Shows.xml"));
            gv.DataBind();
            BindData();
        }
    }
Example #17
0
 static void FilteringDataUsingOfType()
 {
     Console.WriteLine("***** LINQ Filtering Data using OfType *****");
     ArrayList myStuff = new ArrayList(); // non-generic holds objects
     myStuff.AddRange(new object[] {10, 400, 8, false, new Car(), "string data"});
     // now filter out the numeric data
     var myInts = myStuff.OfType<int>();
     foreach (var i in myInts) {
         Console.WriteLine("Int value: {0}", i);
     }
 }
Example #18
0
    public static void Main(string[] args)
    {
        if (args.Length == 0 || (args.Length == 1 && (args[0] == "?" || args[0] == "/?" || args[0] == "-?" || args[0].ToLower() == "help")))
        {
            Console.WriteLine(usage);
        }
        else
        {
            ArrayList namespaces = new ArrayList();
            namespaces.Add("System");
            namespaces.Add("System.Windows.Forms");
            namespaces.Add("System.Xml");
            namespaces.Add("System.IO");
            namespaces.Add("System.Diagnostics");
            namespaces.Add("System.Text");
            //add more default namespaces if required

            StringBuilder builder = new StringBuilder();
            foreach(string statement in args)
            {
                if (statement.StartsWith("/ns:"))
                    namespaces.AddRange(statement.Substring("/ns:".Length).Split(";".ToCharArray()));
                else
                {
                    builder.Append(" ");
                    builder.Append(statement);
                }
            }

            string scriptText = ComposeScript(builder.ToString(), (string[])namespaces.ToArray(typeof(string)));
            scriptText = scriptText.Replace("{$34}", "\"");

            string fileName = Path.GetTempFileName();
            try
            {
                if (File.Exists(fileName))
                    File.Delete(fileName);
                fileName = Path.ChangeExtension(fileName, ".cs");
                using (StreamWriter sw = new StreamWriter(fileName))
                {
                    sw.Write(scriptText);
                }
                RunScript(fileName);
            }
            finally
            {
                if (File.Exists(fileName))
                    File.Delete(fileName);
            }
        }
    }
Example #19
0
		public PropertyModel[] GetProperties(Type arType)
		{
			ArrayList props = new ArrayList();
			ActiveRecordModel model = ActiveRecordModel.GetModel(arType);
			
			props.AddRange(model.Properties);
			
			foreach (BelongsToModel belong in model.BelongsTo)
			{
				props.Add(new PropertyModel(belong.Property, new PropertyAttribute()));
			}
			
			return (PropertyModel[]) props.ToArray(typeof(PropertyModel));
		}
    /// <summary>
    /// 指定されたフォルダ以下にあるすべてのファイルを取得する
    /// </summary>
    /// <param name="folder">ファイルを検索するフォルダ名。</param>
    /// <param name="searchPattern">ファイル名検索文字列
    /// ワイルドカード指定子(*, ?)を使用する。</param>
    /// <param name="files">見つかったファイル名のリスト</param>
    public static void GetAllFiles(string folder, string searchPattern, ref ArrayList files)
    {
        //folderにあるファイルを取得する
        string[] fs = System.IO.Directory.GetFiles (folder, searchPattern);
        //ArrayListに追加する
        files.AddRange (fs);

        //folderのサブフォルダを取得する
        string[] ds = System.IO.Directory.GetDirectories (folder);
        //サブフォルダにあるファイルも調べる
        foreach (string d in ds) {
            GetAllFiles (d, searchPattern, ref files);
        }
    }
Example #21
0
        private static object toObject(object o)
        {
            if (o == null) return null;

            if (o.GetType() == typeof(string))
            {
                //判断是否符合2010-09-02T10:00:00的格式
                string s = o.ToString();
                if (s.Length == 19 && s[10] == 'T' && s[4] == '-' && s[13] == ':')
                {
                    o = System.Convert.ToDateTime(o);
                }
            }
            else if (o is JObject)
            {
                JObject jo = o as JObject;

                Hashtable h = new Hashtable();

                foreach (KeyValuePair<string, JToken> entry in jo)
                {
                    h[entry.Key] = toObject(entry.Value);
                }

                o = h;
            }
            else if (o is IList)
            {

                ArrayList list = new ArrayList();
                list.AddRange((o as IList));
                int i = 0, l = list.Count;
                for (; i < l; i++)
                {
                    list[i] = toObject(list[i]);
                }
                o = list;

            }
            else if (typeof(JValue) == o.GetType())
            {
                JValue v = (JValue)o;
                o = toObject(v.Value);
            }
            else
            {
            }
            return o;
       }
Example #22
0
 public static ArrayList getChildrenWithTag(GameObject parent, string tag)
 {
     ArrayList childrenByTag = new ArrayList ();
     if (parent != null && parent.transform != null) {
         foreach (Transform child in parent.transform) {
             if (child.CompareTag (tag)) {
                 childrenByTag.Add (child.gameObject);
             }
             ArrayList childChildren = Utils.getChildrenWithTag (child.gameObject, tag);
             if (childChildren != null)
                 childrenByTag.AddRange (childChildren);
         }
     }
     return childrenByTag;
 }
    public override UnityEngine.Object[] Evaluate(GameObject parent)
    {
        if (parent == null)
        {
            return GameObject.FindObjectsOfType(compType);
        }
        else
        {
            ArrayList result = new ArrayList();
            result.AddRange(parent.GetComponents(compType));
            //result.AddRange(parent.GetComponents(compType));

            return (UnityEngine.Object[])result.ToArray(compType);
        }
    }
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!IsPostBack)
     {
         ArrayList dllData = new ArrayList();
         FpSite newStie = new FpSite();
         newStie.ID = 0;
         newStie.NAME = "全部";
         dllData.Add(newStie);
         ArrayList listSite = SimpleOrmOperator.QueryConditionList<FpSite>("");
         dllData.AddRange(listSite);
         dllSite.DataSource = dllData;
         dllSite.DataTextField = "NAME";
         dllSite.DataValueField = "ID";
         dllSite.DataBind();
     }
 }
Example #25
0
    // Use this for initialization
    void Start()
    {
        //creates an array of an undetermined size and type
        ArrayList aList = new ArrayList();

        //create an array of all objects in the scene
        Object[] AllObjects = GameObject.FindObjectsOfType(typeof(Object)) as Object[];

        //iterate through all objects
        foreach (Object o in AllObjects)
        {
            if (o.GetType() == typeof(GameObject))
            {
                aList.Add(o);
            }
        }

        if (aList.Contains(SpecificObject))
        {
            Debug.Log(aList.IndexOf(SpecificObject));
        }

        if (aList.Contains(gameObject))
        {
            aList.Remove(gameObject);
        }

        //initialize the AllGameObjects array
        AllGameObjects = new GameObject[aList.Count];

        //copy the list to the array
        DistanceComparer dc = new DistanceComparer();
        dc.Target = gameObject;
        aList.Sort(dc);

        aList.CopyTo(AllGameObjects);
        ArrayList sorted = new ArrayList();
        sorted.AddRange(messyInts);
        sorted.Sort();
        sorted.Reverse();
        sorted.CopyTo(messyInts);
    }
Example #26
0
    /*
    ═══════════════════════════════════════════════════════════════
    Create a new read it object which handles all data access in
    this example
    ═══════════════════════════════════════════════════════════════
    */
    public void ReadCOMSET(String strFilename)
    {
        //übergebenen Dateiname einlesen
        string strContent = "";
        ArrayList dataList = new ArrayList();

        if (File.Exists(strFilename))
        {
            StreamReader myFile = new StreamReader(strFilename, System.Text.Encoding.Default);
            strContent = myFile.ReadToEnd();
            myFile.Close();
            if
            (!string.IsNullOrEmpty(sContent ))
        { //hier werden die Zeilen "separiert"
            dataList.AddRange(strContent.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries));
        }

        // deshalb hier umwandlung auf 0 bei none , die Parität steht in der
        // zweiten Zeile der COMM.Set  --> 2ter Listeneintrag von datalist.

        if (dataList[2].ToString() == "NONE")
        { dataList[2] = 0; }
        if (dataList[2].ToString() == "ODD")
        { dataList[2] = 1; }
        if (dataList[2].ToString() == "EVEN")
        { dataList[2] = 2; }
        if (dataList[2].ToString() == "MARK")
        { dataList[2] = 3; }
        if (dataList[2].ToString() == "SPACE")
        { dataList[2] = 4; }

            strCOM = dataList[0].ToString();
            intBaudrate = Convert.ToInt32(dataList[1]);
            byparitycheck = Convert.ToByte(dataList[2]);
            byDatabits = Convert.ToByte(dataList[3]);
            byStopbit = Convert.ToByte(dataList[4]);

        }
    }
Example #27
0
	public string createScrollView(ArrayList myBusyo_list, string minBusyoId, GameObject mainController){
		//Scroll View
		string myBusyoString = PlayerPrefs.GetString ("myBusyo");
		char[] delimiterChars = {','};
		myBusyo_list.AddRange (myBusyoString.Split (delimiterChars));
		
		//Instantiate scroll view
		string scrollPath = "Prefabs/Busyo/Slot";	
		
		
		for (int j=0; j<myBusyo_list.Count; j++) {
			//Slot
			GameObject prefab = Instantiate (Resources.Load (scrollPath)) as GameObject;
			prefab.transform.SetParent(GameObject.Find ("Content").transform);
			prefab.transform.localScale = new Vector3 (1, 1, 1);
			prefab.transform.localPosition = new Vector3(330,-75,0);

			//Busyo
			string busyoPath = "Prefabs/Player/Unit/" + myBusyo_list [j];
			GameObject busyo = Instantiate (Resources.Load (busyoPath)) as GameObject;
			busyo.transform.SetParent(prefab.transform);
			busyo.transform.localScale = new Vector3 (4, 4, 4);
			busyo.transform.localPosition = new Vector3(100,-75,0);
			busyo.name = myBusyo_list [j].ToString ();
			prefab.name = "Slot" + busyo.name;
			
			busyo.GetComponent<DragHandler> ().enabled = false;				
		}
		
		minBusyoId = myBusyo_list[0].ToString();
		mainController.GetComponent<NowOnBusyo>().OnBusyo = myBusyo_list[0].ToString();

		//Busyo Qty Limit
		int stockLimit = PlayerPrefs.GetInt ("stockLimit");
		GameObject.Find ("LimitBusyoQtyValue").GetComponent<Text>().text = stockLimit.ToString ();
		GameObject.Find ("NowBusyoQtyValue").GetComponent<Text>().text = myBusyo_list.Count.ToString ();

		return minBusyoId;
	}
Example #28
0
 protected override void RunImpl()
 {
     if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
             + Path.DirectorySeparatorChar + "Linasa"))
     {
         Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
             + Path.DirectorySeparatorChar + "Linasa");
     }
     if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
         + Path.DirectorySeparatorChar + "Linasa" + Path.DirectorySeparatorChar + "Ranking.txt"))
     {
         File.Create(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
             + Path.DirectorySeparatorChar + "Linasa" + Path.DirectorySeparatorChar + "Ranking.txt").Close();
     }
     string[] ranking = File.ReadAllLines(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
         + Path.DirectorySeparatorChar + "Linasa" + Path.DirectorySeparatorChar + "Ranking.txt");
     ArrayList saveRanking = new ArrayList();
     saveRanking.AddRange(ranking);
     saveRanking.Add(n + "-" + s[1]);
     string[] array = (string[])saveRanking.ToArray(typeof(string));
     File.WriteAllLines(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
     + Path.DirectorySeparatorChar + "Linasa" + Path.DirectorySeparatorChar + "Ranking.txt", array);
 }
Example #29
0
 static void BlackDot(string line)
 {
     int pos = line.IndexOf('|');
     string[] playersStr = line.Substring(0,pos).Trim().Split(' ');
     int dot = Convert.ToInt32(line.Substring(pos + 1).Trim());
     ArrayList players = new ArrayList();
     players.AddRange(playersStr);
     while(players.Count>1){
         int dotCounter = 1;
         int index = 0;
         while(true){
             if(dot!=dotCounter){
                 index++;
                 dotCounter++;
                 if(index==players.Count)index=0;
             }else {
                 players.RemoveAt(index);
                 break;
             }
         }
     }
     Console.WriteLine(players[0]);
 }
Example #30
0
    public static ArrayList getFractalSquares(Square square, int minFractalSpacing)
    {
        /*
        shatters the given space into a list of non-overlapping 2D squares, suitable for
        greeble generation. leaves spacingSize space between squares so greeble isn't glued together.
        */

        ArrayList squares = new ArrayList ();
        int minFractalSize = 5;

        if (square.width < minFractalSize || square.height < minFractalSize) {
            //Debug.Log ("width or depth less than minStepSize");
            return squares;
        }

        float ratio = (float)square.width / square.height;
        bool isUp;
        if (ratio < 0.5) {
            isUp = true;
        } else if (ratio > 2) {
            isUp = false;
        } else {
            if (square.width + square.height < 35 && Random.Range (0, square.width + square.height) < minFractalSize * 3) {
                squares.Add (new Square (square.x, square.y, square.width, square.height));
                return squares;
            }

            isUp = Random.Range (0, square.width + square.height) > square.width;
        }

        foreach (Square iterSquare in getSplitSquares(square.x,square.y,square.width,square.height,isUp,minFractalSize,minFractalSpacing)) {
            //Debug.Log ("running fractals recursively");
            squares.AddRange (getFractalSquares (iterSquare, minFractalSpacing));
        }

        return squares;
    }
Example #31
0
        private IEnumerable OrderChanges(Change[] changes)
        {
            ArrayList undelete = new ArrayList();
            ArrayList edit     = new ArrayList();
            ArrayList rename   = new ArrayList();
            ArrayList branch   = new ArrayList();
            ArrayList add      = new ArrayList();
            ArrayList delete   = new ArrayList();
            /* Gestion of file swapping */
            ArrayList editRename_FS = new ArrayList();
            ArrayList add_FS        = new ArrayList();
            ArrayList delete_FS     = new ArrayList();

            foreach (Change change in changes)
            {
                switch (change.ChangeType & TfsClientProvider.FullMask)
                {
                case ChangeType.SourceRename | ChangeType.Delete:
                    delete_FS.Add(change);
                    break;

                case ChangeType.SourceRename | ChangeType.Edit:
                case ChangeType.SourceRename | ChangeType.Rename:
                case ChangeType.SourceRename | ChangeType.Rename | ChangeType.Edit:
                    editRename_FS.Add(change);
                    break;

                case ChangeType.SourceRename | ChangeType.Add:
                case ChangeType.SourceRename | ChangeType.Add | ChangeType.Edit:
                    add_FS.Add(change);
                    break;

                // fin de la gestion du file swapping
                case ChangeType.Undelete:
                case ChangeType.Undelete | ChangeType.Edit:
                    undelete.Add(change);
                    break;

                case ChangeType.Rename:
                case ChangeType.Rename | ChangeType.Edit:
                case ChangeType.Rename | ChangeType.Delete:
                    rename.Add(change);

                    // no need to handle the edit here, rename will add the modified file to SVN
                    break;

                case ChangeType.Branch:
                case ChangeType.Branch | ChangeType.Edit:
                    branch.Add(change);
                    break;

                case ChangeType.Add:
                case ChangeType.Add | ChangeType.Edit:
                    add.Add(change);
                    break;

                case ChangeType.Delete:
                    delete.Add(change);
                    break;

                case ChangeType.Edit:
                    edit.Add(change);
                    break;

                case ChangeType.None:
                case 0:     // ChangeType.None different from 0 ?
                    break;

                default:
                    throw new Exception(string.Format("Unmanaged change to order: {0}, minus mask : {1} ", change.ChangeType, change.ChangeType & TfsClientProvider.FullMask));
                }
            }

            ArrayList l = new ArrayList();

            // add the elements in the order of the following commands
            l.AddRange(rename);
            l.AddRange(undelete);
            l.AddRange(add);
            l.AddRange(delete);
            l.AddRange(edit);
            l.AddRange(branch);

            l.AddRange(delete_FS);
            l.AddRange(editRename_FS);
            l.AddRange(add_FS);

            LOG.Info("Ordered Changes - Begin");
            foreach (Change change in l)
            {
                LOG.Info(string.Format("Change - Item: {0} ChangeType: {1}", change.Item, change.ChangeType));
            }

            LOG.Info("Ordered Changes - End");
            return(l);
        }
        public FileInfo[] Filter(DirectoryInfo Dir)
        {
            //Get all the files that match the filters
            ArrayList arFiles = new ArrayList();

            foreach (string strFilter in m_arFilters)
            {
                FileInfo[] arFilterFiles = Dir.GetFiles(strFilter);
                arFiles.AddRange(arFilterFiles);
            }

            //Sort them
            arFiles.Sort(FileSystemInfoComparer.Comparer);

            //Throw out duplicates
            FileInfo PreviousFile = null;

            for (int i = 0; i < arFiles.Count; /*Incremented in the loop*/)
            {
                FileInfo CurrentFile = (FileInfo)arFiles[i];
                if (PreviousFile != null && FileSystemInfoComparer.Comparer.Compare(CurrentFile, PreviousFile) == 0)
                {
                    arFiles.RemoveAt(i);
                    //Don't increment i;
                }
                else
                {
                    PreviousFile = CurrentFile;
                    i++;
                }
            }

            //Exclude these files if necessary
            if (m_bInclude)
            {
                return((FileInfo[])arFiles.ToArray(typeof(FileInfo)));
            }
            else
            {
                FileInfo[] arAllFiles = Dir.GetFiles();
                Array.Sort(arAllFiles, FileSystemInfoComparer.Comparer);

                ArrayList arFilesToInclude = new ArrayList();
                int       iNumExcludes     = arFiles.Count;
                int       iNumTotal        = arAllFiles.Length;
                int       e = 0;
                for (int a = 0; a < iNumTotal; a++)
                {
                    int      iCompareResult = -1;
                    FileInfo A = arAllFiles[a];
                    if (e < iNumExcludes)
                    {
                        FileInfo E = (FileInfo)arFiles[e];
                        iCompareResult = FileSystemInfoComparer.Comparer.Compare(A, E);
                    }

                    if (iCompareResult == 0)
                    {
                        //Don't put this match in the results.
                        e++;
                    }
                    else
                    {
                        arFilesToInclude.Add(A);
                    }
                }

                return((FileInfo[])arFilesToInclude.ToArray(typeof(FileInfo)));
            }
        }
        /// <devdoc>
        /// Gets the properties for a given Com2 Object.  The returned Com2Properties
        /// Object contains the properties and relevant data about them.
        /// </devdoc>
        public static Com2Properties GetProperties(object obj)
        {
            Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "Com2TypeInfoProcessor.GetProperties");

            if (obj == null || !Marshal.IsComObject(obj))
            {
                Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "Com2TypeInfoProcessor.GetProperties returning null: Object is not a com Object");
                return(null);
            }

            UnsafeNativeMethods.ITypeInfo[] typeInfos = FindTypeInfos(obj, false);

            // oops, looks like this guy doesn't surface any type info
            // this is okay, so we just say it has no props
            if (typeInfos == null || typeInfos.Length == 0)
            {
                Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "Com2TypeInfoProcessor.GetProperties :: Didn't get typeinfo");
                return(null);
            }


            int       defaultProp = -1;
            int       temp        = -1;
            ArrayList propList    = new ArrayList();

            Guid[] typeGuids = new Guid[typeInfos.Length];

            for (int i = 0; i < typeInfos.Length; i++)
            {
                UnsafeNativeMethods.ITypeInfo ti = typeInfos[i];

                if (ti == null)
                {
                    continue;
                }

                int[] versions             = new int[2];
                Guid  typeGuid             = GetGuidForTypeInfo(ti, versions);
                PropertyDescriptor[] props = null;
                bool dontProcess           = typeGuid != Guid.Empty && processedLibraries != null && processedLibraries.Contains(typeGuid);

                if (dontProcess)
                {
                    CachedProperties cp = (CachedProperties)processedLibraries[typeGuid];

                    if (versions[0] == cp.MajorVersion && versions[1] == cp.MinorVersion)
                    {
                        props = cp.Properties;
                        if (i == 0 && cp.DefaultIndex != -1)
                        {
                            defaultProp = cp.DefaultIndex;
                        }
                    }
                    else
                    {
                        dontProcess = false;
                    }
                }

                if (!dontProcess)
                {
                    props = InternalGetProperties(obj, ti, NativeMethods.MEMBERID_NIL, ref temp);

                    // only save the default property from the first type Info
                    if (i == 0 && temp != -1)
                    {
                        defaultProp = temp;
                    }

                    if (processedLibraries == null)
                    {
                        processedLibraries = new Hashtable();
                    }

                    if (typeGuid != Guid.Empty)
                    {
                        processedLibraries[typeGuid] = new CachedProperties(props, i == 0 ? defaultProp : -1, versions[0], versions[1]);
                    }
                }

                if (props != null)
                {
                    propList.AddRange(props);
                }
            }

            Debug.WriteLineIf(DbgTypeInfoProcessorSwitch.TraceVerbose, "Com2TypeInfoProcessor.GetProperties : returning " + propList.Count.ToString(CultureInfo.InvariantCulture) + " properties");

            // done!
            Com2PropertyDescriptor[] temp2 = new Com2PropertyDescriptor[propList.Count];
            propList.CopyTo(temp2, 0);

            return(new Com2Properties(obj, temp2, defaultProp));
        }
 /// <summary>
 /// Adds the elements of an array of PropertySpec objects to the end of the PropertySpecCollection.
 /// </summary>
 /// <param name="array">The PropertySpec array whose elements should be added to the end of the
 /// PropertySpecCollection.</param>
 public void AddRange(PropertySpec[] array)
 {
     _innerArray.AddRange(array);
 }
        public CustomTypeDescriptor(Type type, MemberInfo[] members, string[] names)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            if (members == null)
            {
                FieldInfo[]    fields     = type.GetFields(BindingFlags.Instance | BindingFlags.Public);
                PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
                ArrayList      arrayList  = new ArrayList(fields.Length + properties.Length);
                arrayList.AddRange(fields);
                arrayList.AddRange(properties);
                for (int i = 0; i < arrayList.Count; i++)
                {
                    MemberInfo memberInfo = (MemberInfo)arrayList[i];
                    if (memberInfo.IsDefined(typeof(JsonIgnoreAttribute), inherit: true))
                    {
                        arrayList.RemoveAt(i--);
                    }
                }
                members = (MemberInfo[])arrayList.ToArray(typeof(MemberInfo));
            }
            PropertyDescriptorCollection propertyDescriptorCollection = new PropertyDescriptorCollection(null);
            int num = 0;

            MemberInfo[] array = members;
            foreach (MemberInfo memberInfo2 in array)
            {
                FieldInfo fieldInfo = memberInfo2 as FieldInfo;
                string    name      = (names != null && num < names.Length) ? names[num] : null;
                if (fieldInfo != null)
                {
                    if (fieldInfo.DeclaringType != type && fieldInfo.ReflectedType != type)
                    {
                        throw new ArgumentException("fields");
                    }
                    if (!fieldInfo.IsInitOnly && !fieldInfo.IsLiteral)
                    {
                        propertyDescriptorCollection.Add(new TypeFieldDescriptor(fieldInfo, name));
                    }
                }
                else
                {
                    PropertyInfo propertyInfo = memberInfo2 as PropertyInfo;
                    if (propertyInfo == null)
                    {
                        throw new ArgumentException("members");
                    }
                    if (propertyInfo.DeclaringType != type && propertyInfo.ReflectedType != type)
                    {
                        throw new ArgumentException("properties");
                    }
                    if (propertyInfo.CanRead && propertyInfo.CanWrite)
                    {
                        propertyDescriptorCollection.Add(new TypePropertyDescriptor(propertyInfo, name));
                    }
                }
                num++;
            }
            _properties = propertyDescriptorCollection;
        }
Example #36
0
        public void Add(params CacheDependency [] dependencies)
        {
            DateTime utcLastModified = DateTime.MinValue;

            if (dependencies == null)
            {
                throw new ArgumentNullException("dependencies");
            }

            // copy array argument contents so they can't be changed beneath us
            dependencies = (CacheDependency [])dependencies.Clone();

            // validate contents
            foreach (CacheDependency d in dependencies)
            {
                if (d == null)
                {
                    throw new ArgumentNullException("dependencies");
                }

                if (!d.Use())
                {
                    throw new InvalidOperationException(SR.GetString(SR.Cache_dependency_used_more_that_once));
                }
            }

            // add dependencies, and check if any have changed
            bool hasChanged = false;

            lock (this) {
                if (!_disposed)
                {
                    if (_dependencies == null)
                    {
                        _dependencies = new ArrayList();
                    }

                    _dependencies.AddRange(dependencies);

                    foreach (CacheDependency d in dependencies)
                    {
                        d.SetCacheDependencyChanged(this);

                        if (d.UtcLastModified > utcLastModified)
                        {
                            utcLastModified = d.UtcLastModified;
                        }

                        if (d.HasChanged)
                        {
                            hasChanged = true;
                            break;
                        }
                    }
                }
            }

            SetUtcLastModified(utcLastModified);

            // if a dependency has changed, notify others that we have changed.
            if (hasChanged)
            {
                NotifyDependencyChanged(this, EventArgs.Empty);
            }
        }
        /// <summary>Main</summary>
        static void Main(string[] args)
        {
            // コマンドラインをバラす関数がある。
            List <string> valsLst = null;
            Dictionary <string, string> argsDic = null;

            PubCmnFunction.GetCommandArgs('/', out argsDic, out valsLst);

            // 引数クラス値(B層実行用)
            string     screenId   = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string     controlId  = "-";
            string     actionType = "SQL"; // argsDic["/DAP"] + "%" + argsDic["/MODE1"] + "%" + argsDic["/MODE2"] + "%" + argsDic["/EXROLLBACK"];
            MyUserInfo myUserInfo = new MyUserInfo("userName", "ipAddress");

            // B層クラス
            LayerB layerB = new LayerB();

            // ↓B層実行:主キー値を全て検索(ORDER BY 主キー)-----------------------------------------------------

            // 引数クラスを生成
            VoidParameterValue selectPkListParameterValue = new VoidParameterValue(screenId, controlId, "SelectPkList", actionType, myUserInfo);

            // B層呼出し
            SelectPkListReturnValue selectPkReturnValue = (SelectPkListReturnValue)layerB.DoBusinessLogic(selectPkListParameterValue, DbEnum.IsolationLevelEnum.ReadCommitted);

            // 実行結果確認
            if (selectPkReturnValue.ErrorFlag == true)
            {
                // 結果(業務続行可能なエラー)
                string error = "ErrorMessageID:" + selectPkReturnValue.ErrorMessageID + "\r\n";
                error += "ErrorMessage:" + selectPkReturnValue.ErrorMessage + "\r\n";
                error += "ErrorInfo:" + selectPkReturnValue.ErrorInfo + "\r\n";

                Console.WriteLine(error);
                Console.ReadKey();
                return; //バッチ処理終了
            }

            // 戻り値取得
            ArrayList pkList = selectPkReturnValue.PkList;

            // ↑B層実行:主キー値を全て検索(ORDER BY 主キー)-----------------------------------------------------

            int recordCount      = pkList.Count;                                                                                      // 全レコード数
            int initialIndex     = 0;                                                                                                 // 処理開始インデックス ※ todo:リラン時に途中から再開する場合は初期値を変更する
            int transactionCount = Convert.ToInt32(Math.Ceiling(((double)(recordCount - initialIndex)) / INTERMEDIATE_COMMIT_COUNT)); // 更新B層実行回数

            // 性能測定
            // 性能測定 - 開始
            PerformanceRecorder pr = new PerformanceRecorder();

            pr.StartsPerformanceRecord();

            for (int transactionIndex = 0; transactionIndex < transactionCount; transactionIndex++)
            {
                ArrayList subPkList;       // 主キー一覧(1トランザクション分)
                int       subPkStartIndex; // 主キー(1トランザクション分)の開始位置
                int       subPkCount;      // 主キー数(1トランザクション分)

                // 取り出す主キーの開始、数を取得
                subPkStartIndex = initialIndex + (transactionIndex * INTERMEDIATE_COMMIT_COUNT);
                if (subPkStartIndex + INTERMEDIATE_COMMIT_COUNT - 1 > recordCount - 1)
                {
                    subPkCount = (recordCount - initialIndex) % INTERMEDIATE_COMMIT_COUNT;
                }
                else
                {
                    subPkCount = INTERMEDIATE_COMMIT_COUNT;
                }

                // 主キー一覧(1トランザクション分)を取り出す
                subPkList = new ArrayList();
                subPkList.AddRange(pkList.GetRange(subPkStartIndex, subPkCount));

                // ↓B層実行:バッチ処理を実行(1トランザクション分)----------------------------------------------------

                // 引数クラスを生成
                ExecuteBatchProcessParameterValue executeBatchProcessParameterValue = new ExecuteBatchProcessParameterValue(screenId, controlId, "ExecuteBatchProcess", actionType, myUserInfo);
                executeBatchProcessParameterValue.SubPkList = subPkList;

                // B層呼出し
                VoidReturnValue executeBatchProcessReturnValue = (VoidReturnValue)layerB.DoBusinessLogic(executeBatchProcessParameterValue, DbEnum.IsolationLevelEnum.ReadCommitted);

                // 実行結果確認
                if (selectPkReturnValue.ErrorFlag == true)
                {
                    // 結果(業務続行可能なエラー)
                    string error = "ErrorMessageID:" + selectPkReturnValue.ErrorMessageID + "\r\n";
                    error += "ErrorMessage:" + selectPkReturnValue.ErrorMessage + "\r\n";
                    error += "ErrorInfo:" + selectPkReturnValue.ErrorInfo + "\r\n";

                    Console.WriteLine(error);
                    Console.ReadKey();
                    return; // バッチ処理終了
                }

                // ↑B層実行:バッチ処理を実行(1トランザクション分)----------------------------------------------------
            }

            // 性能測定 - 終了
            Console.WriteLine(pr.EndsPerformanceRecord());
            Console.ReadKey();
        }
        public object DetectTemplate(IProgressHost progress)
        {
            // if our context has not been set then just return without doing anything
            // (supports this being an optional step at the end of a chain of
            // other progress operations)
            if (_contextSet == false)
            {
                return(this);
            }

            using (BlogClientUIContextScope uiContextScope = new BlogClientUIContextScope(_uiContext))
            {
                // initial progress
                progress.UpdateProgress(Res.Get(StringId.ProgressDetectingWeblogEditingStyle));

                // build list of detected templates
                ArrayList blogTemplateFiles = new ArrayList();

                // build list of template types that we need to auto-detect
                ArrayList detectionTargetTypes      = new ArrayList();
                ArrayList detectionTargetStrategies = new ArrayList();

                // try explicit detection of templates
                BlogEditingTemplateFiles templateFiles = SafeGetTemplates(new ProgressTick(progress, 50, 100));

                // see if we got the FramedTempalte
                if (templateFiles.FramedTemplate != null)
                {
                    blogTemplateFiles.Add(templateFiles.FramedTemplate);
                }
                else
                {
                    detectionTargetTypes.Add(BlogEditingTemplateType.Framed);
                    detectionTargetStrategies.Add(BlogEditingTemplateStrategies.GetTemplateStrategy(BlogEditingTemplateStrategies.StrategyType.NoSiblings));
                }

                // see if we got the WebPageTemplate
                if (templateFiles.WebPageTemplate != null)
                {
                    blogTemplateFiles.Add(templateFiles.WebPageTemplate);
                }
                else
                {
                    detectionTargetTypes.Add(BlogEditingTemplateType.Webpage);
                    detectionTargetStrategies.Add(BlogEditingTemplateStrategies.GetTemplateStrategy(BlogEditingTemplateStrategies.StrategyType.Site));
                }

                // perform detection if we have detection targets
                if (detectionTargetTypes.Count > 0)
                {
                    BlogEditingTemplateFile[] detectedBlogTemplateFiles = DetectTemplates(new ProgressTick(progress, 50, 100),
                                                                                          detectionTargetTypes.ToArray(typeof(BlogEditingTemplateType)) as BlogEditingTemplateType[],
                                                                                          detectionTargetStrategies.ToArray(typeof(BlogEditingTemplateStrategy)) as BlogEditingTemplateStrategy[]);
                    if (detectedBlogTemplateFiles != null)
                    {
                        blogTemplateFiles.AddRange(detectedBlogTemplateFiles);
                    }
                }

                // updates member if we succeeded
                if (blogTemplateFiles.Count > 0)
                {
                    // capture template files
                    _blogTemplateFiles = blogTemplateFiles.ToArray(typeof(BlogEditingTemplateFile)) as BlogEditingTemplateFile[];

                    // if we got at least one template by some method then clear any exception
                    // that occurs so we can at least update that tempalte
                    _exception = null;
                }

                foreach (BlogEditingTemplateFile file in blogTemplateFiles)
                {
                    if (file.TemplateType == BlogEditingTemplateType.Webpage)
                    {
                        _postBodyBackgroundColor = BackgroundColorDetector.DetectColor(UrlHelper.SafeToAbsoluteUri(new Uri(file.TemplateFile)), _postBodyBackgroundColor);
                    }
                }

                // return
                return(this);
            }
        }
Example #39
0
        protected override void OnAfterSelect(TreeViewEventArgs e)
        {
            base.OnAfterSelect(e);

            bool bControl = (ModifierKeys == Keys.Control);
            bool bShift   = (ModifierKeys == Keys.Shift);

            try
            {
                if (bControl)
                {
                    if (!m_selectNode.Contains(e.Node))                     // new node ?
                    {
                        m_selectNode.Add(e.Node);

                        Node_Color_Tag node_color;
                        node_color.fore = e.Node.ForeColor;
                        node_color.back = e.Node.BackColor;
                        m_selectNodeColor.Add(node_color);
                    }
                    else                  // not new, remove it from the collection
                    {
                        removePaintFromNodes();

                        int i_index = m_selectNode.IndexOf(e.Node);
                        m_selectNodeColor.RemoveAt(i_index);

                        m_selectNode.Remove(e.Node);
                    }
                    paintSelectedNodes();
                }
                else
                {
                    // SHIFT is pressed
                    if (bShift)
                    {
                        Queue myQueue = new Queue();

                        TreeNode uppernode  = m_firstNode;
                        TreeNode bottomnode = e.Node;
                        // case 1 : begin and end nodes are parent
                        bool bParent = isParent(m_firstNode, e.Node);                     // is m_firstNode parent (direct or not) of e.Node
                        if (!bParent)
                        {
                            bParent = isParent(bottomnode, uppernode);
                            if (bParent)                         // swap nodes
                            {
                                TreeNode t = uppernode;
                                uppernode  = bottomnode;
                                bottomnode = t;
                            }
                        }
                        if (bParent)
                        {
                            TreeNode n = bottomnode;
                            while (n != uppernode.Parent)
                            {
                                if (!m_selectNode.Contains(n))                                 // new node ?
                                {
                                    myQueue.Enqueue(n);
                                }

                                n = n.Parent;
                            }
                        }
                        // case 2 : nor the begin nor the end node are descendant one another
                        else
                        {
                            if ((uppernode.Parent == null && bottomnode.Parent == null) || (uppernode.Parent != null && uppernode.Parent.Nodes.Contains(bottomnode)))                       // are they siblings ?
                            {
                                int nIndexUpper  = uppernode.Index;
                                int nIndexBottom = bottomnode.Index;
                                if (nIndexBottom < nIndexUpper)                             // reversed?
                                {
                                    TreeNode t = uppernode;
                                    uppernode    = bottomnode;
                                    bottomnode   = t;
                                    nIndexUpper  = uppernode.Index;
                                    nIndexBottom = bottomnode.Index;
                                }

                                TreeNode n = uppernode;
                                while (nIndexUpper <= nIndexBottom)
                                {
                                    if (!m_selectNode.Contains(n))                                     // new node ?
                                    {
                                        myQueue.Enqueue(n);
                                    }

                                    n = n.NextNode;

                                    nIndexUpper++;
                                }                             // end while
                            }
                            else
                            {
                                if (!m_selectNode.Contains(uppernode))
                                {
                                    myQueue.Enqueue(uppernode);
                                }
                                if (!m_selectNode.Contains(bottomnode))
                                {
                                    myQueue.Enqueue(bottomnode);
                                }
                            }
                        }

                        m_selectNode.AddRange(myQueue);

                        Node_Color_Tag node_color;
                        foreach (TreeNode n1 in myQueue)
                        {
                            node_color.fore = n1.ForeColor;
                            node_color.back = n1.BackColor;
                            m_selectNodeColor.Add(node_color);
                        }

                        paintSelectedNodes();
                        m_firstNode = e.Node; // let us chain several SHIFTs if we like it
                    }                         // end if m_bShift
                    else
                    {
                        // in the case of a simple click, just add this item
                        if (m_selectNode != null && m_selectNode.Count > 0)
                        {
                            removePaintFromNodes();
                            m_selectNode.Clear();

                            m_selectNodeColor.Clear();
                        }
                        m_selectNode.Add(e.Node);

                        Node_Color_Tag node_color;
                        node_color.fore = e.Node.ForeColor;
                        node_color.back = e.Node.BackColor;
                        m_selectNodeColor.Add(node_color);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Example #40
0
        public ObjectPropertyList(UOEntity owner)
        {
            m_Owner = owner;

            m_StringNums.AddRange(m_DefaultStringNums);
        }
Example #41
0
        public static CodeGenerationResult GenerateProjectCode(GenerationOptions options, ProjectBackend[] projects)
        {
            ArrayList warningList = new ArrayList();

            List <SteticCompilationUnit> units      = new List <SteticCompilationUnit> ();
            SteticCompilationUnit        globalUnit = new SteticCompilationUnit("");

            units.Add(globalUnit);

            if (options == null)
            {
                options = new GenerationOptions();
            }
            CodeNamespace globalNs = new CodeNamespace(options.GlobalNamespace);

            globalUnit.Namespaces.Add(globalNs);

            // Global class

            CodeTypeDeclaration globalType = new CodeTypeDeclaration("Gui");

            globalType.Attributes     = MemberAttributes.Private;
            globalType.TypeAttributes = TypeAttributes.NestedAssembly;
            globalNs.Types.Add(globalType);

            // Create the project initialization method
            // This method will only be added at the end if there
            // is actually something to initialize

            CodeMemberMethod initMethod = new CodeMemberMethod();

            initMethod.Name       = "Initialize";
            initMethod.ReturnType = new CodeTypeReference(typeof(void));
            initMethod.Attributes = MemberAttributes.Assembly | MemberAttributes.Static;
            initMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Gtk.Widget), "iconRenderer"));

            GeneratorContext initContext = new ProjectGeneratorContext(globalNs, globalType, initMethod.Statements, options);

            initContext.RootObject = new CodeArgumentReferenceExpression("iconRenderer");

            // Generate icon factory creation

            foreach (ProjectBackend gp in projects)
            {
                if (gp.IconFactory.Icons.Count > 0)
                {
                    gp.IconFactory.GenerateBuildCode(initContext);
                }
            }
            warningList.AddRange(initContext.Warnings);

            // Generate the code

            if (options.UsePartialClasses)
            {
                CodeGeneratorPartialClass.GenerateProjectGuiCode(globalUnit, globalNs, globalType, options, units, projects, warningList);
            }
            else
            {
                CodeGeneratorInternalClass.GenerateProjectGuiCode(globalUnit, globalNs, globalType, options, units, projects, warningList);
            }

            GenerateProjectActionsCode(globalNs, options, projects);

            // Final step. If there is some initialization code, add all needed infrastructure

            globalType.Members.Add(initMethod);

            CodeMemberField initField = new CodeMemberField(typeof(bool), "initialized");

            initField.Attributes = MemberAttributes.Private | MemberAttributes.Static;
            globalType.Members.Add(initField);

            CodeFieldReferenceExpression initVar = new CodeFieldReferenceExpression(
                new CodeTypeReferenceExpression(globalNs.Name + ".Gui"),
                "initialized"
                );

            CodeConditionStatement initCondition = new CodeConditionStatement();

            initCondition.Condition = new CodeBinaryOperatorExpression(
                initVar,
                CodeBinaryOperatorType.IdentityEquality,
                new CodePrimitiveExpression(false)
                );
            initCondition.TrueStatements.Add(new CodeAssignStatement(
                                                 initVar,
                                                 new CodePrimitiveExpression(true)
                                                 ));
            initCondition.TrueStatements.AddRange(initMethod.Statements);
            initMethod.Statements.Clear();
            initMethod.Statements.Add(initCondition);

            return(new CodeGenerationResult(units.ToArray(), (string[])warningList.ToArray(typeof(string))));
        }
        public void RegenerateColorRanges()
        {
            if (this.UseCustomColors)
            {
                foreach (CustomColor customColor10 in this.CustomColors)
                {
                    customColor10.AffectedElements.Clear();
                }
            }
            MapCore mapCore = base.GetMapCore();

            if (mapCore != null && mapCore.Groups.Count != 0 && (!this.UseCustomColors || this.CustomColors.Count != 0))
            {
                if (!this.UseCustomColors)
                {
                    this.CustomColors.Clear();
                }
                if (this.GroupField == "(Name)")
                {
                    if (this.UseCustomColors)
                    {
                        int num = 0;
                        foreach (Group group4 in mapCore.Groups)
                        {
                            if (num == this.CustomColors.Count)
                            {
                                break;
                            }
                            CustomColor customColor2 = this.CustomColors[num++];
                            customColor2.FromValueInt = group4.Name;
                            customColor2.ToValueInt   = group4.Name;
                        }
                    }
                    else
                    {
                        Color[] colors = base.GetColors(this.ColoringMode, this.ColorPalette, this.FromColor, this.MiddleColor, this.ToColor, mapCore.Groups.Count);
                        int     num3   = 0;
                        foreach (Group group5 in mapCore.Groups)
                        {
                            if (group5.Category == this.Category)
                            {
                                CustomColor customColor3 = this.CustomColors.Add(string.Empty);
                                customColor3.Color          = colors[num3++];
                                customColor3.SecondaryColor = this.SecondaryColor;
                                customColor3.BorderColor    = this.BorderColor;
                                customColor3.GradientType   = this.GradientType;
                                customColor3.HatchStyle     = this.HatchStyle;
                                customColor3.FromValueInt   = group5.Name;
                                customColor3.ToValueInt     = group5.Name;
                                customColor3.Text           = this.Text;
                                customColor3.ToolTip        = this.ToolTip;
                            }
                        }
                    }
                    this.UpdateColorSwatchAndLegend();
                }
                else
                {
                    Field field = this.GetField();
                    if (field != null)
                    {
                        if (field.IsNumeric())
                        {
                            int    intervalCount = (!this.UseCustomColors) ? this.ColorCount : this.CustomColors.Count;
                            object obj           = null;
                            object obj2          = null;
                            if (this.FromValue != string.Empty)
                            {
                                obj = field.Parse(this.FromValue);
                            }
                            if (this.ToValue != string.Empty)
                            {
                                obj2 = field.Parse(this.ToValue);
                            }
                            if (obj == null || obj2 == null)
                            {
                                this.GetRangeFromGroups(field, intervalCount, ref obj, ref obj2);
                            }
                            object[] array  = null;
                            object[] array2 = null;
                            if (this.DataGrouping == DataGrouping.EqualInterval)
                            {
                                base.GetEqualIntervals(field, obj, obj2, intervalCount, ref array, ref array2);
                            }
                            else if (this.DataGrouping == DataGrouping.EqualDistribution)
                            {
                                ArrayList sortedValues = this.GetSortedValues(field, obj, obj2);
                                base.GetEqualDistributionIntervals(field, sortedValues, obj, obj2, intervalCount, ref array, ref array2);
                            }
                            else if (this.DataGrouping == DataGrouping.Optimal)
                            {
                                ArrayList sortedValues2 = this.GetSortedValues(field, obj, obj2);
                                base.GetOptimalIntervals(field, sortedValues2, obj, obj2, intervalCount, ref array, ref array2);
                            }
                            if (this.UseCustomColors)
                            {
                                int num5 = 0;
                                foreach (CustomColor customColor11 in this.CustomColors)
                                {
                                    if (num5 < array.Length)
                                    {
                                        customColor11.FromValueInt = AspNetCore.Reporting.Map.WebForms.Field.ToStringInvariant(array[num5]);
                                        customColor11.ToValueInt   = AspNetCore.Reporting.Map.WebForms.Field.ToStringInvariant(array2[num5]);
                                        customColor11.VisibleInt   = true;
                                    }
                                    else
                                    {
                                        customColor11.FromValueInt = AspNetCore.Reporting.Map.WebForms.Field.ToStringInvariant(array2[array2.Length - 1]);
                                        customColor11.ToValueInt   = AspNetCore.Reporting.Map.WebForms.Field.ToStringInvariant(array2[array2.Length - 1]);
                                        customColor11.VisibleInt   = false;
                                    }
                                    num5++;
                                }
                            }
                            else
                            {
                                Color[] colors2 = base.GetColors(this.ColoringMode, this.ColorPalette, this.FromColor, this.MiddleColor, this.ToColor, array.Length);
                                for (int i = 0; i < array.Length; i++)
                                {
                                    CustomColor customColor5 = this.CustomColors.Add(string.Empty);
                                    customColor5.Color          = colors2[i];
                                    customColor5.SecondaryColor = this.SecondaryColor;
                                    customColor5.BorderColor    = this.BorderColor;
                                    customColor5.GradientType   = this.GradientType;
                                    customColor5.HatchStyle     = this.HatchStyle;
                                    customColor5.FromValueInt   = AspNetCore.Reporting.Map.WebForms.Field.ToStringInvariant(array[i]);
                                    customColor5.ToValueInt     = AspNetCore.Reporting.Map.WebForms.Field.ToStringInvariant(array2[i]);
                                    customColor5.Text           = this.Text;
                                    customColor5.ToolTip        = this.ToolTip;
                                }
                            }
                        }
                        else if (field.Type == typeof(string))
                        {
                            Hashtable hashtable = new Hashtable();
                            foreach (Group group6 in base.GetMapCore().Groups)
                            {
                                if (group6.Category == this.Category)
                                {
                                    string text = (string)group6[field.Name];
                                    if (text != null)
                                    {
                                        hashtable[text] = 0;
                                    }
                                }
                            }
                            if (this.UseCustomColors)
                            {
                                ArrayList arrayList = new ArrayList();
                                arrayList.AddRange(hashtable.Keys);
                                arrayList.Sort();
                                int num6 = 0;
                                foreach (object item in arrayList)
                                {
                                    if (num6 == this.CustomColors.Count)
                                    {
                                        break;
                                    }
                                    CustomColor customColor6 = this.CustomColors[num6++];
                                    customColor6.FromValueInt = (string)item;
                                    customColor6.ToValueInt   = (string)item;
                                }
                            }
                            else
                            {
                                Color[] colors3 = base.GetColors(this.ColoringMode, this.ColorPalette, this.FromColor, this.MiddleColor, this.ToColor, hashtable.Keys.Count);
                                int     num8    = 0;
                                foreach (object key in hashtable.Keys)
                                {
                                    CustomColor customColor7 = this.CustomColors.Add(string.Empty);
                                    customColor7.Color          = colors3[num8++];
                                    customColor7.SecondaryColor = this.SecondaryColor;
                                    customColor7.BorderColor    = this.BorderColor;
                                    customColor7.GradientType   = this.GradientType;
                                    customColor7.HatchStyle     = this.HatchStyle;
                                    customColor7.FromValueInt   = (string)key;
                                    customColor7.ToValueInt     = (string)key;
                                    customColor7.Text           = this.Text;
                                    customColor7.ToolTip        = this.ToolTip;
                                }
                            }
                        }
                        else if (this.UseCustomColors)
                        {
                            this.CustomColors[0].FromValueInt = "False";
                            this.CustomColors[0].ToValueInt   = "False";
                            if (this.CustomColors.Count > 1)
                            {
                                this.CustomColors[1].FromValueInt = "True";
                                this.CustomColors[1].ToValueInt   = "True";
                            }
                        }
                        else
                        {
                            CustomColor customColor8 = this.CustomColors.Add(string.Empty);
                            customColor8.Color          = this.FromColor;
                            customColor8.SecondaryColor = this.SecondaryColor;
                            customColor8.BorderColor    = this.BorderColor;
                            customColor8.GradientType   = this.GradientType;
                            customColor8.HatchStyle     = this.HatchStyle;
                            customColor8.FromValueInt   = "False";
                            customColor8.ToValueInt     = "False";
                            customColor8.Text           = this.Text;
                            customColor8.ToolTip        = this.ToolTip;
                            CustomColor customColor9 = this.CustomColors.Add(string.Empty);
                            customColor9.Color          = this.ToColor;
                            customColor9.SecondaryColor = this.SecondaryColor;
                            customColor9.BorderColor    = this.BorderColor;
                            customColor9.GradientType   = this.GradientType;
                            customColor9.HatchStyle     = this.HatchStyle;
                            customColor9.FromValueInt   = "True";
                            customColor9.ToValueInt     = "True";
                            customColor9.Text           = this.Text;
                            customColor9.ToolTip        = this.ToolTip;
                        }
                        this.UpdateColorSwatchAndLegend();
                    }
                }
            }
        }
Example #43
0
        private void SettingForm_Load(object sender, System.EventArgs e)
        {
            #region 設定の読み込み

            stationNameTextBox.Text = setting.ParentHeadline.ParentStation.Name;

            headlineDatV2TextBox.Text  = ((setting.HeadlineDatV2Url != null) ? setting.HeadlineDatV2Url.ToString() : string.Empty);
            headlineCsvUrlTextBox.Text = ((setting.HeadlineCsvUrl != null) ? setting.HeadlineCsvUrl.ToString() : string.Empty);
            headlineXmlUrlTextBox.Text = ((setting.HeadlineXmlUrl != null) ? setting.HeadlineXmlUrl.ToString() : string.Empty);
            switch (setting.HeadlineGetWay)
            {
            case UserSetting.HeadlineGetType.Cvs:
                headlineGetWayCvsRadioButton.Checked   = true;
                headlineGetWayXmlRadioButton.Checked   = false;
                headlineGetWayDatV2RadioButton.Checked = false;
                break;

            case UserSetting.HeadlineGetType.Xml:
                headlineGetWayCvsRadioButton.Checked   = false;
                headlineGetWayXmlRadioButton.Checked   = true;
                headlineGetWayDatV2RadioButton.Checked = false;
                break;

            case UserSetting.HeadlineGetType.DatV2:
                headlineGetWayCvsRadioButton.Checked   = false;
                headlineGetWayXmlRadioButton.Checked   = false;
                headlineGetWayDatV2RadioButton.Checked = true;
                break;

            default:
                headlineGetWayCvsRadioButton.Checked   = false;
                headlineGetWayXmlRadioButton.Checked   = false;
                headlineGetWayDatV2RadioButton.Checked = false;
                break;
            }
            headlineViewTypeTextBox.Text = setting.HeadlineViewType;

            // フィルターリストに単語フィルターの内容を追加する
            alFilterMatchWords.AddRange(setting.GetFilterMatchWords());
            foreach (string word in setting.GetFilterMatchWords())
            {
                filterListBox.Items.Add("+ " + word);
            }

            // フィルターリストに単語フィルターの内容を追加する
            alFilterExclusionWords.AddRange(setting.GetFilterExclusionWords());
            foreach (string word in setting.GetFilterExclusionWords())
            {
                filterListBox.Items.Add("- " + word);
            }

            // ビットレートフィルターを読み込む
            filterAboveBitRateUseCheckBox.Checked = setting.FilterAboveBitRateUse;
            filterAboveBitRateTextBox.Text        = setting.FilterAboveBitRate.ToString();
            filterBelowBitRateUseCheckBox.Checked = setting.FilterBelowBitRateUse;
            filterBelowBitRateTextBox.Text        = setting.FilterBelowBitRate.ToString();

            // ソート種類を読み込む
            if (setting.SortKind == Headline.SortKinds.None)
            {
                sortKindComboBox.SelectedIndex = 0;
            }
            else if (setting.SortKind == Headline.SortKinds.Nam)
            {
                sortKindComboBox.SelectedIndex = 1;
            }
            else if (setting.SortKind == Headline.SortKinds.Tims)
            {
                sortKindComboBox.SelectedIndex = 2;
            }
            else if (setting.SortKind == Headline.SortKinds.Cln)
            {
                sortKindComboBox.SelectedIndex = 3;
            }
            else if (setting.SortKind == Headline.SortKinds.Clns)
            {
                sortKindComboBox.SelectedIndex = 4;
            }
            else if (setting.SortKind == Headline.SortKinds.Bit)
            {
                sortKindComboBox.SelectedIndex = 5;
            }
            else
            {
                // ここに到達することはあり得ない
                Trace.Assert(false, "想定外の動作のため、終了します");
            }

            if (setting.SortScending == Headline.SortScendings.Ascending)
            {
                sortDescendingRadioButton.Checked = false;
                sortAscendingRadioButton.Checked  = true;
            }
            else if (setting.SortScending == Headline.SortScendings.Descending)
            {
                sortAscendingRadioButton.Checked  = false;
                sortDescendingRadioButton.Checked = true;
            }
            else
            {
                // ここに到達することはあり得ない
                Trace.Assert(false, "想定外の動作のため、終了します");
            }

            #endregion
        }
Example #44
0
        public string GetLayout()
        {
            ArrayList fl = new ArrayList();

            if (_fieldList != null)
            {
                fl.AddRange(_fieldList);
            }

            int           i  = 0;
            StringBuilder sb = new StringBuilder();

            sb.Append(LayoutBuilder.GetHeader());

            if (fl.Contains("IdTipoAjuste") || _fieldList == null)
            {
                sb.Append(LayoutBuilder.GetRow(i++, "IdTipoAjuste", "IdTipoAjuste"));
            }
            if (fl.Contains("Descripcion") || _fieldList == null)
            {
                sb.Append(LayoutBuilder.GetRow(i++, "Descripcion", "Descripcion"));
            }
            if (fl.Contains("Sistema") || _fieldList == null)
            {
                sb.Append(LayoutBuilder.GetRow(i++, "Sistema", "Sistema"));
            }
            if (fl.Contains("FechaCreacion") || _fieldList == null)
            {
                sb.Append(LayoutBuilder.GetRow(i++, "FechaCreacion", "FechaCreacion"));
            }
            if (fl.Contains("IdConexionCreacion") || _fieldList == null)
            {
                sb.Append(LayoutBuilder.GetRow(i++, "IdConexionCreacion", "IdConexionCreacion"));
            }
            if (fl.Contains("UltimaModificacion") || _fieldList == null)
            {
                sb.Append(LayoutBuilder.GetRow(i++, "UltimaModificacion", "UltimaModificacion"));
            }
            if (fl.Contains("IdConexionUltimaModificacion") || _fieldList == null)
            {
                sb.Append(LayoutBuilder.GetRow(i++, "IdConexionUltimaModificacion", "IdConexionUltimaModificacion"));
            }
            if (fl.Contains("IdReservado") || _fieldList == null)
            {
                sb.Append(LayoutBuilder.GetRow(i++, "IdReservado", "IdReservado"));
            }
            if (fl.Contains("RowId") || _fieldList == null)
            {
                sb.Append(LayoutBuilder.GetRow(i++, "RowId", "RowId"));
            }
            if (fl.Contains("IdSucursal") || _fieldList == null)
            {
                sb.Append(LayoutBuilder.GetRow(i++, "IdSucursal", "IdSucursal"));
            }
            if (fl.Contains("IdEmpresa") || _fieldList == null)
            {
                sb.Append(LayoutBuilder.GetRow(i++, "IdEmpresa", "IdEmpresa"));
            }
            if (fl.Contains("IdEstadoDeStock") || _fieldList == null)
            {
                sb.Append(LayoutBuilder.GetRow(i++, "IdEstadoDeStock", "IdEstadoDeStock"));
            }
            if (fl.Contains("OldIdTipoAjuste") || _fieldList == null)
            {
                sb.Append(LayoutBuilder.GetRow(i++, "OldIdTipoAjuste", "OldIdTipoAjuste"));
            }

            sb.Append(LayoutBuilder.GetFooter());

            return(sb.ToString());
        }
Example #45
0
        private void DataConsumerLoop()
        {
            while (true)
            {
                try
                {
                    _cancelSource.Token.ThrowIfCancellationRequested();
                    Task.Delay(50).Wait(_cancelSource.Token);
                }
                catch (OperationCanceledException)
                {
                    IncomingData?.Clear();
                    throw;
                }

                lock (IncomingQueue)
                {
                    if (IncomingQueue.Count <= 0)
                    {
                        continue;
                    }
                    while (IncomingQueue.TryDequeue(out var frame))
                    {
                        IncomingData.AddRange(frame);
                    }
                }

                do
                {
                    try
                    {
                        var raw = IncomingData.OfType <byte>().ToArray();

                        foreach (var hook in ScriptManager.Instance.RawStreamHooks)
                        {
                            hook?.OnRawDataAvailable(ref raw);
                        }

                        var msg = SPPMessage.DecodeMessage(raw);

                        Log.Verbose($">> Incoming: {msg}");

                        foreach (var hook in ScriptManager.Instance.MessageHooks)
                        {
                            hook?.OnMessageAvailable(ref msg);
                        }

                        MessageReceived?.Invoke(this, msg);

                        if (msg.TotalPacketSize >= IncomingData.Count)
                        {
                            IncomingData.Clear();
                            break;
                        }

                        IncomingData.RemoveRange(0, msg.TotalPacketSize);

                        if (ByteArrayUtils.IsBufferZeroedOut(IncomingData))
                        {
                            /* No more data remaining */
                            break;
                        }
                    }
                    catch (InvalidPacketException e)
                    {
                        InvalidDataReceived?.Invoke(this, e);
                        break;
                    }
                } while (IncomingData.Count > 0);
            }
        }
Example #46
0
 public StringList AddRange(StringList sl)
 {
     m_alMain.AddRange(sl.m_alMain);
     return(null);
 }
Example #47
0
        /// <summary>
        /// Recherche les informations sur les comptes en mode DBA
        /// </summary>
        /// <param name="userConnected"></param>
        /// <returns></returns>
        private bool SelectArchiDBA(AccountMgmt.DataAccess.ConnectedUser userConnected)
        {
            //project
            AccessProject listProject = new AccessProject();

            if (!listProject.Select(userConnected.Connection, "", "project"))
            {
                return(false);
            }
            m_listProject = ((ArrayList)listProject.ListProject.Clone());

            //application
            for (int numProject = 0; numProject < listProject.ListProject.Count; numProject++)
            {
                AccessApplication listApplication = new AccessApplication();
                if (!listApplication.Select(userConnected.Connection, "id_project=" + ((Project)listProject.ListProject[numProject]).Id.ToString("0"), "application"))
                {
                    return(false);
                }

                //module
                for (int numApp = 0; numApp < listApplication.ListApplication.Count; numApp++)
                {
                    AccessModule listModule = new AccessModule();
                    if (!listModule.Select(userConnected.Connection, "id_application=" + ((Application)listApplication.ListApplication[numApp]).Id.ToString("0"), "module"))
                    {
                        return(false);
                    }

                    //profile
                    for (int numModule = 0; numModule < listModule.ListModule.Count; numModule++)
                    {
                        AccessProfile listProfile = new AccessProfile();
                        if (!listProfile.Select(userConnected.Connection, "id_module=" + ((Module)listModule.ListModule[numModule]).Id.ToString("0"), "profile"))
                        {
                            return(false);
                        }

                        //role
                        for (int numProfile = 0; numProfile < listProfile.ListProfile.Count; numProfile++)
                        {
                            AccessRole listRole = new AccessRole();
                            if (!listRole.SelectRight(userConnected.Connection, "ro.id_role = ri.id_role AND ri.id_profile=" + ((Profile)listProfile.ListProfile[numProfile]).Id.ToString("0"), "role"))
                            {
                                return(false);
                            }
                            m_listRole.AddRange((ArrayList)listRole.ListRole.Clone());
                            listRole.Dispose();
                        }
                        m_listProfile.AddRange((ArrayList)listProfile.ListProfile.Clone());
                        listProfile.Dispose();
                    }
                    m_listModule.AddRange((ArrayList)listModule.ListModule.Clone());
                    listModule.Dispose();
                }
                m_listApplication.AddRange((ArrayList)listApplication.ListApplication.Clone());
                listApplication.Dispose();
            }

            return(true);
        }
Example #48
0
 public void AddData(short aValue)
 {
     data.AddRange(BitConverter.GetBytes(aValue));
 }
Example #49
0
        static void Main(string[] args)
        {
            //第一行:创建一个数组类型,并使用
            //第二行:对Animal进行实例化此处的数组大小要根据内容设定,不然会报错
            //第三行:对Cow实例化,使用带参函数,体现出了面向对象开发的多态性
            //第四行:

            /*分别对数组对象复制,第一个将myCow1(一个对象,经过Cow实例化后得到的返回值)
             *派生类(Cow)
             *  public Cow(string newName): base(newName){}
             *基类
             *  public Animal(string newName)
             *   {
             *       name = newName;
             *   }
             * 赋值给数组第一个变量
             * 结果:Deirdre
             */
            //第五行:

            /*
             * 此处直接获得Chicken里的带一个参数的返回值对象
             * public Chicken(string newName): base(newName){}
             * 结果:Ken
             */
            Console.WriteLine("Create an Array type collection of Animal object and use it:");
            Animal[] animalArray = new Animal[2];
            Cow      myCow1      = new Cow("Deirdre");

            animalArray[0] = myCow1;
            animalArray[1] = new Chicken("Ken");
            //第一行:使用迭代循环,并定义了myAnimal类型为Animal类型
            //第二行:输出myAnimal的类型和所带属性
            //第三行:输出animalArray数组长度
            //第四行:调用Animal自带的Feed()函数
            //第五行:调用Chicken里的LayEgg()方法,由于animalArray本来是Animal类型,所以调用Chicken的方法,要进行强制类型转换
            foreach (Animal myAnimal in animalArray)
            {
                Console.WriteLine("New {0} object added to Array collection Name = {1}", myAnimal.ToString(), myAnimal.Name);
            }
            Console.WriteLine("Array collection contains {0} objects.", animalArray.Length);
            animalArray[0].Feed();
            ((Chicken)animalArray[1]).LayEgg();
            Console.WriteLine();
            //第二个集合是System.Collection.ArrayList类
            Console.WriteLine("Create an ArrayList type collection of Animal objects and use it:");
            ArrayList animalArrayList = new ArrayList();
            Cow       myCow2          = new Cow("Hayley");

            animalArrayList.Add(myCow2);
            animalArrayList.Add(new Chicken("Roy"));
            foreach (Animal myAnimal in animalArrayList)
            {
                Console.WriteLine("New {0} object added to ArrayList collection Name = {1}", myAnimal.ToString(), myAnimal.Name);
            }
            Console.WriteLine("ArrayList colleciton contains {0} objects.", animalArrayList.Count);
            ((Animal)animalArrayList[0]).Feed();
            ((Chicken)animalArrayList[1]).LayEgg();
            Console.WriteLine();
            //利用了一些ArrayList集合功能超出了Array集合的功能范围
            Console.WriteLine("Additional manipulation of ArrayList:");
            animalArrayList.RemoveAt(0);
            ((Animal)animalArrayList[0]).Feed();
            animalArrayList.AddRange(animalArray);
            ((Chicken)animalArrayList[2]).LayEgg();
            Console.WriteLine("The animal called{0} is at index {1}.", myCow1.Name, animalArrayList.IndexOf(myCow1));
            myCow1.Name = "Janice";
            Console.WriteLine("The animal is now called {0}.", ((Cow)animalArrayList[1]).Name);



            Console.ReadKey();
        }
Example #50
0
 public CutCommand(ArrayList graphicsList, ArrayList inMemory)
 {
     _graphicsList = graphicsList;
     _itemsToBeCut = new ArrayList();
     _itemsToBeCut.AddRange(inMemory);
 }
Example #51
0
        /// <summary>
        /// Writes the file system.
        /// </summary>
        /// <param name="stream">the OutputStream to which the filesystem will be
        /// written</param>
        public void WriteFileSystem(Stream stream)
        {
            // Get the property table Ready
            _property_table.PreWrite();

            // Create the small block store, and the SBAT
            SmallBlockTableWriter sbtw =
                new SmallBlockTableWriter(bigBlockSize, _documents, _property_table.Root);

            // Create the block allocation table
            BlockAllocationTableWriter bat =
                new BlockAllocationTableWriter(bigBlockSize);

            // Create a list of BATManaged objects: the documents plus the
            // property table and the small block table
            ArrayList bm_objects = new ArrayList();

            bm_objects.AddRange(_documents);
            bm_objects.Add(_property_table);
            bm_objects.Add(sbtw);
            bm_objects.Add(sbtw.SBAT);

            // walk the list, allocating space for each and assigning each
            // a starting block number
            IEnumerator iter = bm_objects.GetEnumerator();

            while (iter.MoveNext())
            {
                BATManaged bmo         = ( BATManaged )iter.Current;
                int        block_count = bmo.CountBlocks;

                if (block_count != 0)
                {
                    bmo.StartBlock = bat.AllocateSpace(block_count);
                }
                else
                {
                    // Either the BATManaged object is empty or its data
                    // is composed of SmallBlocks; in either case,
                    // allocating space in the BAT is inappropriate
                }
            }

            // allocate space for the block allocation table and take its
            // starting block
            int batStartBlock = bat.CreateBlocks();

            // Get the extended block allocation table blocks
            HeaderBlockWriter header_block_Writer = new HeaderBlockWriter(bigBlockSize);

            BATBlock[] xbat_blocks =
                header_block_Writer.SetBATBlocks(bat.CountBlocks,
                                                 batStartBlock);

            // Set the property table start block
            header_block_Writer.PropertyStart = _property_table.StartBlock;

            // Set the small block allocation table start block
            header_block_Writer.SBATStart = sbtw.SBAT.StartBlock;

            // Set the small block allocation table block count
            header_block_Writer.SBATBlockCount = sbtw.SBATBlockCount;

            // the header is now properly initialized. Make a list of
            // Writers (the header block, followed by the documents, the
            // property table, the small block store, the small block
            // allocation table, the block allocation table, and the
            // extended block allocation table blocks)
            ArrayList Writers = new ArrayList();

            Writers.Add(header_block_Writer);
            Writers.AddRange(_documents);
            Writers.Add(_property_table);
            Writers.Add(sbtw);
            Writers.Add(sbtw.SBAT);
            Writers.Add(bat);
            for (int j = 0; j < xbat_blocks.Length; j++)
            {
                Writers.Add(xbat_blocks[j]);
            }

            // now, Write everything out
            iter = Writers.GetEnumerator();
            while (iter.MoveNext())
            {
                BlockWritable Writer = ( BlockWritable )iter.Current;

                Writer.WriteBlocks(stream);
            }

            Writers = null;
            iter    = null;
        }
        internal override PropertyDescriptorCollection GetProperties(esEntity entity, esEntityCollectionBase baseCollection)
        {
            bool weHaveData  = false;
            int  lastOrdinal = 0;

            esColumnMetadataCollection esMetaCols = entity.es.Meta.Columns;

            esEntityCollectionBase theBaseCollection = baseCollection != null ? baseCollection : entity.Collection;

            bool enableHierarchcialBinding = theBaseCollection != null ? theBaseCollection.EnableHierarchicalBinding : true;

            if (theBaseCollection != null)
            {
                if (theBaseCollection.GetList() != null)
                {
                    // Do we have any entities?
                    weHaveData = theBaseCollection.GetList().Count > 0;

                    if (weHaveData == false)
                    {
                        // If selectedColumns has data then they attempted a load and we know the columns based on thier select statement
                        weHaveData = theBaseCollection.selectedColumns != null && theBaseCollection.selectedColumns.Keys.Count > 0;
                    }
                }
            }

            //------------------------------------------------------------
            // First we deal with Properties from the DataTable.Columns
            // or from the esColumnMetadataCollection.
            //------------------------------------------------------------
            ArrayList collNested = new ArrayList();
            SortedList <int, PropertyDescriptor> coll = new SortedList <int, PropertyDescriptor>();

            PropertyDescriptorCollection props = TypeDescriptor.GetProperties(entity, true);

            // Note, we check for selectedColumns because we might be a deserialized collection in which
            // case there will not be any selectedColumns
            if (weHaveData && theBaseCollection.selectedColumns != null)
            {
                SortedList list = GetSortedListOfProperties(entity, baseCollection);

                for (int i = 0; i < list.Count; i++)
                {
                    string column = (string)list.GetByIndex(i);

                    if (column == "ESRN")
                    {
                        continue;
                    }

                    esColumnMetadata esCol = entity.es.Meta.Columns.FindByColumnName(column);

                    if (esCol != null)
                    {
                        PropertyDescriptor prop = props[esCol.PropertyName];

                        if (prop != null)
                        {
                            coll.Add(lastOrdinal++, prop);
                        }
                    }
                    else
                    {
                        esCol = theBaseCollection.extraColumnMetadata[column];

                        if (esCol != null)
                        {
                            // Extra or Extended Properties
                            esPropertyDescriptor dpd = new esPropertyDescriptor
                                                       (
                                typeof(T),
                                column,
                                esCol != null ? esCol.Type : typeof(string),
                                delegate(object p)
                            {
                                return(((esEntity)p).currentValues[column]);
                            },
                                delegate(object p, object data)
                            {
                                ((esEntity)p).currentValues[column] = data;
                                ((esEntity)p).OnPropertyChanged(column);
                            }
                                                       );

                            coll.Add(lastOrdinal++, dpd);
                        }
                    }
                }
            }
            else
            {
                foreach (esColumnMetadata esCol in esMetaCols)
                {
                    coll.Add(lastOrdinal++, props[esCol.PropertyName]);
                }
            }

            //------------------------------------------------------------
            // Now we deal with extended properties that are using the
            // esExtendedPropertyAttribute technique
            //------------------------------------------------------------
#if (!WindowsCE)
            foreach (PropertyDescriptor prop in props)
            {
                if (prop.Attributes.Contains(esEntityCollection <T> .extendedPropertyAttribute))
                {
                    coll.Add(lastOrdinal++, prop);
                }
            }
#endif

            //------------------------------------------------------------
            // Now we deal with any local properties. Local properties are
            // properties that users may want to bind with that are
            // NOT backed by data in the DataTable
            //------------------------------------------------------------
            List <esPropertyDescriptor> localProps = entity.GetLocalBindingProperties();
            if (localProps != null)
            {
                foreach (esPropertyDescriptor esProp in localProps)
                {
                    // We check this incase they add a local based property for a DataColumn
                    // based property, they would do this so it appears in design time, and
                    // we don't want to add a duplicate
                    bool exists = coll.ContainsValue(props[esProp.Name]);

                    if (!exists)
                    {
                        if (props[esProp.Name] != null)
                        {
                            coll.Add(lastOrdinal++, props[esProp.Name]);
                        }
                        else
                        {
                            coll.Add(lastOrdinal++, esProp);
                        }
                    }
                }
            }

            ArrayList tempColl = new ArrayList();

            if (enableHierarchcialBinding)
            {
                List <esPropertyDescriptor> hierProps = entity.GetHierarchicalProperties();
                if (hierProps != null)
                {
                    foreach (esPropertyDescriptor esProp in hierProps)
                    {
                        esProp.TrueDescriptor = props[esProp.Name];
                        //  coll.Add(lastOrdinal++, esProp);

                        tempColl.Add(esProp);
                    }
                }
            }

            // Create the collection
            foreach (PropertyDescriptor p in coll.Values)
            {
                tempColl.Add(p);
            }
            tempColl.AddRange(collNested);

            PropertyDescriptorCollection theProps =
                new PropertyDescriptorCollection((PropertyDescriptor[])tempColl.ToArray(typeof(PropertyDescriptor)));

            return(theProps);
        }
        public System.ComponentModel.PropertyDescriptorCollection GetProperties(System.Attribute[] attributes)
        {
            PropertyDescriptorCollection Properties = new PropertyDescriptorCollection(null);
            CustomProperty CustomProp;

            foreach (CustomProperty tempLoopVar_CustomProp in base.List)
            {
                CustomProp = tempLoopVar_CustomProp;
                if (CustomProp.Visible)
                {
                    ArrayList attrs = new ArrayList();

                    // Expandable Object Converter
                    if (CustomProp.IsBrowsable)
                    {
                        attrs.Add(new TypeConverterAttribute(typeof(BrowsableTypeConverter)));
                    }

                    // The Filename Editor
                    if (CustomProp.UseFileNameEditor == true)
                    {
                        attrs.Add(new EditorAttribute(typeof(UIFilenameEditor), typeof(UITypeEditor)));
                    }

                    // Custom Choices Type Converter
                    if (CustomProp.Choices != null)
                    {
                        attrs.Add(new TypeConverterAttribute(typeof(CustomChoices.CustomChoicesTypeConverter)));
                    }

                    // Password Property
                    if (CustomProp.IsPassword)
                    {
                        attrs.Add(new PasswordPropertyTextAttribute(true));
                    }

                    // Parenthesize Property
                    if (CustomProp.Parenthesize)
                    {
                        attrs.Add(new ParenthesizePropertyNameAttribute(true));
                    }

                    // Datasource
                    if (CustomProp.Datasource != null)
                    {
                        attrs.Add(new EditorAttribute(typeof(UIListboxEditor), typeof(UITypeEditor)));
                    }

                    // Custom Editor
                    if (CustomProp.CustomEditor != null)
                    {
                        attrs.Add(new EditorAttribute(CustomProp.CustomEditor.GetType(), typeof(UITypeEditor)));
                    }

                    // Custom Type Converter
                    if (CustomProp.CustomTypeConverter != null)
                    {
                        attrs.Add(new TypeConverterAttribute(CustomProp.CustomTypeConverter.GetType()));
                    }

                    // Is Percentage
                    if (CustomProp.IsPercentage)
                    {
                        attrs.Add(new TypeConverterAttribute(typeof(OpacityConverter)));
                    }

                    // 3-dots button event delegate
                    if (CustomProp.OnClick != null)
                    {
                        attrs.Add(new EditorAttribute(typeof(UICustomEventEditor), typeof(UITypeEditor)));
                    }

                    // Default value attribute
                    if (CustomProp.DefaultValue != null)
                    {
                        attrs.Add(new DefaultValueAttribute(CustomProp.Type, CustomProp.Value.ToString()));
                    }
                    else
                    {
                        // Default type attribute
                        if (CustomProp.DefaultType != null)
                        {
                            attrs.Add(new DefaultValueAttribute(CustomProp.DefaultType, null));
                        }
                    }

                    // Extra Attributes
                    if (CustomProp.Attributes != null)
                    {
                        attrs.AddRange(CustomProp.Attributes);
                    }

                    // Add my own attributes
                    Attribute[] attrArray = (System.Attribute[])attrs.ToArray(typeof(Attribute));
                    Properties.Add(new CustomProperty.CustomPropertyDescriptor(CustomProp, attrArray));
                }
            }
            return(Properties);
        }
Example #54
0
        public static void Display()
        {
            // (1) - ArrayList
            // ArrayList are resizable arrays that can have different types
            ArrayList list = new ArrayList();

            list.Add("Bob");
            list.Add(40);

            Console.WriteLine($"list count: {list.Count}");
            Console.WriteLine($"capacity: {list.Capacity}");

            // add ArrayList to another ArrayList
            ArrayList list2 = new ArrayList(new object[] { "Spencer", "Joseph", "Savannah" });

            list.AddRange(list2);

            Console.Write("list + list2: ");
            foreach (var item in list)
            {
                Console.Write($"{item} ");
            }
            Console.WriteLine();

            // sort ArrayList that contains like types
            list2.Sort();
            Console.Write("sort: ");
            foreach (var item in list2)
            {
                Console.Write($"{item} ");
            }
            Console.WriteLine();

            list2.Reverse();
            Console.Write("reverse: ");
            foreach (var item in list2)
            {
                Console.Write($"{item} ");
            }
            Console.WriteLine();

            // insert at index of ArrayList
            list2.Insert(2, "Ed");
            Console.Write("insert: ");
            foreach (var item in list2)
            {
                Console.Write($"{item} ");
            }
            Console.WriteLine();

            // get range from list (index, length)
            ArrayList list3 = list2.GetRange(0, 2);

            Console.WriteLine("contains Spencer: {0}", list2.Contains("Spencer"));

            Console.WriteLine("index of Savannah: {0}", list2.IndexOf("Savannah", 0));

            // (2) - dictionary
            // dictionary is a key <-> value container
            // use the key to retrieve the value associated with it
            Dictionary <string, string> chairs = new Dictionary <string, string>();

            chairs.Add("BSIS", "Corey");
            chairs.Add("BSWD", "Beatty");
            chairs["BSGD"] = "Maple";

            // number of keys
            Console.WriteLine("dictionary count: {0}", chairs.Count);

            // check if key is present
            Console.WriteLine("contains BSGD: {0}", chairs.ContainsKey("BSGD"));

            // get value from key, returns true or false if it exists
            chairs.TryGetValue("BSIS", out string bsis);
            Console.WriteLine($"get value BSIS: {bsis}");
            Console.WriteLine($"get value BSWD: {chairs["BSWD"]}");

            // cycle through key value pairs
            foreach (KeyValuePair <string, string> item in chairs)
            {
                Console.WriteLine("{0} : {1}", item.Key, item.Value);
            }

            // remove a key / value
            chairs.Remove("BSGD");

            // clear out dictionary
            chairs.Clear();

            // (3) - queue
            // FIFO - first in first out container
            // 3 -> 2 -> 1
            Queue queue = new Queue();

            // add to queue
            queue.Enqueue(1);
            queue.Enqueue(2);
            queue.Enqueue(3);

            foreach (object o in queue)
            {
                Console.WriteLine($"queue : {o}");
            }

            // peek but don't remove
            Console.WriteLine("queue peek: {0}", queue.Peek());
            // dequeue (remove) from the front of the queue
            Console.WriteLine("queue dequeue: {0}", queue.Dequeue());
            Console.WriteLine("queue peek: {0}", queue.Peek());

            // check if queue contains a value
            Console.WriteLine("queue contains 1: {0}", queue.Contains(1));

            // convert to array
            object[] queueArray = queue.ToArray();

            // convenient way to display array
            Console.WriteLine(string.Join(",", queueArray));

            // remove all elements from the queue
            queue.Clear();

            // (4) - stack
            // FILO - first in last out
            // 3
            // v
            // 2
            // v
            // 1
            Stack stack = new Stack();

            // add to stack
            stack.Push(1);
            stack.Push(2);
            stack.Push(3);

            foreach (object o in stack)
            {
                Console.WriteLine($"stack : {o}");
            }

            // peek but don't remove
            Console.WriteLine("stack peek: {0}", stack.Peek());
            // pop off the top of the stack
            Console.WriteLine("stack pop: {0}", stack.Pop());
            Console.WriteLine("stack peek: {0}", stack.Peek());

            // check if stack contains a value
            Console.WriteLine("contains 1: {0}", stack.Contains(1));

            // convert to array
            object[] stackArray = stack.ToArray();

            // convenient way to display array
            Console.WriteLine(string.Join(",", stackArray));

            // remove all elements from the stack
            stack.Clear();
        }
Example #55
0
//		private ArrayList AtomListByType(ArrayList alist, ArrayList typelist)
        private ArrayList AtomListByType(IList alist, IList typelist)
        {
            ArrayList atomListByType = new ArrayList();

            ArrayList CList  = new ArrayList();
            ArrayList NList  = new ArrayList();
            ArrayList OList  = new ArrayList();
            ArrayList SList  = new ArrayList();
            ArrayList PList  = new ArrayList();
            ArrayList HList  = new ArrayList();
            ArrayList NOList = new ArrayList();

            ArrayList COrderList  = new ArrayList();
            ArrayList NOrderList  = new ArrayList();
            ArrayList OOrderList  = new ArrayList();
            ArrayList SOrderList  = new ArrayList();
            ArrayList POrderList  = new ArrayList();
            ArrayList HOrderList  = new ArrayList();
            ArrayList NOOrderList = new ArrayList();

            if (atomOrderList != null)
            {
                atomOrderList.Clear();
                atomOrderList = null;
            }
            if (atomOrderListArray != null)
            {
                atomOrderListArray.Clear();
                atomOrderListArray = null;
            }
            atomOrderList      = new ArrayList();
            atomOrderListArray = new ArrayList();

            for (int i = 0; i < alist.Count; i++)
            {
                string type = (typelist[i] as AtomModel).type;
                switch (type)
                {
                case "C":
                    CList.Add(alist[i] as float[]);
                    COrderList.Add(i);
                    break;

                case "N":
                    NList.Add(alist[i] as float[]);
                    NOrderList.Add(i);

                    break;

                case "O":
                    OList.Add(alist[i] as float[]);
                    OOrderList.Add(i);

                    break;

                case "S":
                    SList.Add(alist[i] as float[]);
                    SOrderList.Add(i);

                    break;

                case "P":
                    PList.Add(alist[i] as float[]);
                    POrderList.Add(i);

                    break;

                case "H":
                    HList.Add(alist[i] as float[]);
                    HOrderList.Add(i);

                    break;

                default:
                    NOList.Add(alist[i] as float[]);
                    NOOrderList.Add(i);

                    break;
                }
            }
            atomListByType.Add(CList);
            atomListByType.Add(NList);
            atomListByType.Add(OList);
            atomListByType.Add(SList);
            atomListByType.Add(PList);
            atomListByType.Add(HList);
            atomListByType.Add(NOList);

            atomOrderList.AddRange(COrderList);
            atomOrderList.AddRange(NOrderList);
            atomOrderList.AddRange(OOrderList);
            atomOrderList.AddRange(SOrderList);
            atomOrderList.AddRange(POrderList);
            atomOrderList.AddRange(HOrderList);
            atomOrderList.AddRange(NOOrderList);

            atomOrderListArray.Add(COrderList);
            atomOrderListArray.Add(NOrderList);
            atomOrderListArray.Add(OOrderList);
            atomOrderListArray.Add(SOrderList);
            atomOrderListArray.Add(POrderList);
            atomOrderListArray.Add(HOrderList);
            atomOrderListArray.Add(NOOrderList);

            MoleculeModel.carbonNumber     = CList.Count.ToString();
            MoleculeModel.nitrogenNumber   = NList.Count.ToString();
            MoleculeModel.oxygenNumber     = OList.Count.ToString();
            MoleculeModel.sulphurNumber    = SList.Count.ToString();
            MoleculeModel.phosphorusNumber = PList.Count.ToString();
            MoleculeModel.hydrogenNumber   = HList.Count.ToString();
            MoleculeModel.unknownNumber    = NOList.Count.ToString();

            return(atomListByType);
        }
Example #56
0
        static void Main(string[] args)
        {
            string[] Names    = { "Abby", "Bobby", "Charity", "Debby", "Emma", "Falicia", "Gabriel", "Heather", "Inga", "Jazel", "Kammy", "Luise", "Margeret", "Naomi", "Oprah", "Penelope", "Quan", "Rebecca", "Shay", "Tammy" };
            string[] hometown = { "Ann arbor", "Bardoux", "Cincinatti", "Detroit", "Esexville", "Farwell", "Gaylord", "Hamilton", "Ingum", "Jarusalem", "Kansas City", "Langdon", "Monroe", "Nashville", "Omar", "Park City", "Quebec City", "Reno", "Saginaw", "Tempe" };
            string[] fFood    = { "Apple", "Banana", "Cherry", "Durian", "Elderberry", "Focaccia", "Grape", "Hummus", "Ice cream", "Jack fruit", "Kuarma", "Lemonade", "Mango", "Nori", "Orzo", "Pumpkin Pie", "Quinoa", "Radish", "Spaghetti", "Tuna" };
            string[] fColor   = { "Amarilo", "Blue", "Cyan", "Deep Purple", "Elving Green", "Forest Brown", "Grey", "Hip Pink", "Indigo", "Jamming Black", "Kimchi Red", "Lemonade Yellow", "Magenta", "Nothing", "Orange", "Pea Grean", "Quiet Blue", "Red", "Superman Blue", "Tuna Pink" };

            ArrayList NamesArrayList = new ArrayList();

            NamesArrayList.AddRange(Names);

            ArrayList HometownArrayList = new ArrayList();

            HometownArrayList.AddRange(hometown);

            ArrayList fFoodArrayList = new ArrayList();

            fFoodArrayList.AddRange(fFood);

            ArrayList fFColorArrayList = new ArrayList();

            fFColorArrayList.AddRange(fColor);

            Console.WriteLine();
            Console.WriteLine("Hello, Welcome to your new school.");
            Console.WriteLine();

            Console.WriteLine("Some students said they would like you to know a little about them");
            Console.WriteLine("If you've met anyone maybe you would like to tell us about them.");
            Console.WriteLine();

            bool AnotherStudent = true;

            while (AnotherStudent)
            {
                Console.WriteLine("Would you like to know about a student or would you like to tell us about a classmate?");
                Console.WriteLine();

                bool IncorrectAnswer = true;
                while (IncorrectAnswer)
                {
                    Console.WriteLine("If you'd like to konw about a student type \"know\" if you would like to tell us about a student type \"tell\"");
                    string TellKnow = Console.ReadLine().ToLower();
                    if (TellKnow == "tell")
                    {
                        Console.WriteLine("OK, tell us about a student");

                        Console.Write("Please tell us their name: ");
                        string newName = Console.ReadLine();
                        NamesArrayList.Add(newName);

                        Console.Write("Please tell us their hometown: ");
                        string newHomtown = Console.ReadLine();
                        HometownArrayList.Add(newHomtown);

                        Console.Write("Please tell us their favorite food: ");
                        string newFavoriteFood = Console.ReadLine();
                        fFoodArrayList.Add(newFavoriteFood);

                        Console.Write("Please tell us their favorite color: ");
                        string newFavoriteColor = Console.ReadLine();
                        fFColorArrayList.Add(newFavoriteColor);


                        bool MoreStudents = true;
                        while (MoreStudents)
                        {
                            Console.WriteLine("Would you like to tell us about another student? yes or no?");
                            string TellMore = Console.ReadLine().ToLower();
                            if (TellMore == "yes")
                            {
                                MoreStudents    = false;
                                IncorrectAnswer = true;
                            }
                            else if (TellMore == "no")
                            {
                                MoreStudents    = false;
                                IncorrectAnswer = false;
                            }
                            else
                            {
                                MoreStudents = true;
                                Console.WriteLine("That wasn't the answer we were looking for");
                            }
                        }
                    }
                    else if (TellKnow == "know")
                    {
                        Console.WriteLine("Ok, lets get to know a student");
                        IncorrectAnswer = false;
                    }
                    else
                    {
                        Console.WriteLine("I'm sorry thats not an answer we're looking for");
                        IncorrectAnswer = true;
                    }
                }



                int counter = 0;
                foreach (string StudentNumber in NamesArrayList)
                {
                    counter++;
                    Console.WriteLine($"{counter}. {StudentNumber}");
                }



                Console.Write("Please choose a student ID number from the list: ");


                string input = Console.ReadLine();
                int    index;
                bool   Success = int.TryParse(input, out index);
                index--;

                if (index >= 0 && index < NamesArrayList.Count)
                {
                    if (Success)
                    {
                        bool GoOn = true;
                        while (GoOn)
                        {
                            Console.WriteLine($"What would you like to know about {NamesArrayList[index]}?");
                            while (GoOn)
                            {
                                Console.WriteLine("If you would like to know where she is from type \"Hometown\"");
                                Console.WriteLine("If you would like to know what her favorite food is type \"Favorite Food\"");
                                Console.WriteLine("If you would like to know what their favorite color is type \"Favorite Color\"");
                                Console.WriteLine();
                                string choice = Console.ReadLine().ToLower();
                                if (choice == "hometown")
                                {
                                    Console.WriteLine();
                                    Console.WriteLine(HometownArrayList[index]);
                                    GoOn = false;
                                }
                                else if (choice == "favorite food")
                                {
                                    Console.WriteLine();
                                    Console.WriteLine(fFoodArrayList[index]);
                                    GoOn = false;
                                }
                                else if (choice == "favorite color")
                                {
                                    Console.WriteLine();
                                    Console.WriteLine(fFColorArrayList[index]);
                                    GoOn = false;
                                }

                                else
                                {
                                    Console.WriteLine("I'm not sure what you're asking nor do we have that type of information.");
                                }
                            }
                        }
                    }

                    else
                    {
                        Console.WriteLine("There is no student by that label");
                    }
                }

                else
                {
                    Console.WriteLine("We don't have that many students");
                    continue;
                }
                bool WrongEntry = true;
                while (WrongEntry)
                {
                    Console.WriteLine("Would you like to know about another student");
                    string again = Console.ReadLine().ToUpper();
                    if (again == "YES")
                    {
                        WrongEntry     = false;
                        AnotherStudent = true;
                    }
                    else if (again == "NO")
                    {
                        WrongEntry     = false;
                        AnotherStudent = false;
                    }
                    else
                    {
                        Console.WriteLine("Sorry I didn't understand your answer");
                        WrongEntry = true;
                    }
                }
            }
        }
Example #57
0
        private void CreateLinkPieces()
        {
            if (Text.Length == 0)
            {
                SetStyle(ControlStyles.Selectable, false);
                TabStop          = false;
                link_area.Start  = 0;
                link_area.Length = 0;
                return;
            }

            if (Links.Count == 1 && Links[0].Start == 0 && Links[0].Length == -1)
            {
                Links[0].Length = Text.Length;
            }

            SortLinks();

            // Set the LinkArea values based on first link.
            if (Links.Count > 0)
            {
                link_area.Start  = Links[0].Start;
                link_area.Length = Links[0].Length;
            }
            else
            {
                link_area.Start  = 0;
                link_area.Length = 0;
            }

            TabStop = (LinkArea.Length > 0);
            SetStyle(ControlStyles.Selectable, TabStop);

            /* don't bother doing the rest if our handle hasn't been created */
            if (!IsHandleCreated)
            {
                return;
            }

            ArrayList pieces_list = new ArrayList();

            int current_end = 0;

            for (int l = 0; l < sorted_links.Length; l++)
            {
                int new_link_start = sorted_links[l].Start;

                if (new_link_start > current_end)
                {
                    /* create/push a piece
                     * containing the text between
                     * the previous/new link */
                    ArrayList text_pieces = CreatePiecesFromText(current_end, new_link_start - current_end, null);
                    pieces_list.AddRange(text_pieces);
                }

                /* now create a group of pieces for
                 * the new link (split up by \n's) */
                ArrayList link_pieces = CreatePiecesFromText(new_link_start, sorted_links[l].Length, sorted_links[l]);
                pieces_list.AddRange(link_pieces);
                sorted_links[l].pieces.AddRange(link_pieces);

                current_end = sorted_links[l].Start + sorted_links[l].Length;
            }
            if (current_end < Text.Length)
            {
                ArrayList text_pieces = CreatePiecesFromText(current_end, Text.Length - current_end, null);
                pieces_list.AddRange(text_pieces);
            }

            pieces = new Piece[pieces_list.Count];
            pieces_list.CopyTo(pieces, 0);

            CharacterRange[] ranges = new CharacterRange[pieces.Length];

            for (int i = 0; i < pieces.Length; i++)
            {
                ranges[i] = new CharacterRange(pieces[i].start, pieces[i].length);
            }

            string_format.SetMeasurableCharacterRanges(ranges);

            Region[] regions = TextRenderer.MeasureCharacterRanges(Text,
                                                                   ThemeEngine.Current.GetLinkFont(this),
                                                                   PaddingClientRectangle,
                                                                   string_format);

            for (int i = 0; i < pieces.Length; i++)
            {
                pieces[i].region = regions[i];
                pieces[i].region.Translate(Padding.Left, Padding.Top);
            }

            Invalidate();
        }
        PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
        {
            // Rather than passing this function on to the default TypeDescriptor,
            // which would return the actual properties of UpdateValuePropertyBag, I construct
            // a list here that contains property descriptors for the elements of the
            // Properties list in the bag.

            var props = new ArrayList();

            foreach (PropertySpec property in _properties)
            {
                var attrs = new ArrayList();

                // If a category, description, editor, or type converter are specified
                // in the PropertySpec, create attributes to define that relationship.
                if (property.Category != null)
                {
                    attrs.Add(new CategoryAttribute(property.Category));
                }

                if (property.Description != null)
                {
                    attrs.Add(new DescriptionAttribute(property.Description));
                }

                if (property.EditorTypeName != null)
                {
                    attrs.Add(new EditorAttribute(property.EditorTypeName, typeof(UITypeEditor)));
                }

                if (property.ConverterTypeName != null)
                {
                    attrs.Add(new TypeConverterAttribute(property.ConverterTypeName));
                }

                // Additionally, append the custom attributes associated with the
                // PropertySpec, if any.
                if (property.Attributes != null)
                {
                    attrs.AddRange(property.Attributes);
                }

                if (property.DefaultValue != null)
                {
                    attrs.Add(new DefaultValueAttribute(property.DefaultValue));
                }

                attrs.Add(new BrowsableAttribute(property.Browsable));
                attrs.Add(new ReadOnlyAttribute(property.ReadOnly));
                attrs.Add(new BindableAttribute(property.Bindable));

                var attrArray = (Attribute[])attrs.ToArray(typeof(Attribute));

                // Create a new property descriptor for the property item, and add
                // it to the list.
                var pd = new PropertySpecDescriptor(property,
                                                    this, property.Name, attrArray);
                props.Add(pd);
            }

            // Convert the list of PropertyDescriptors to a collection that the
            // ICustomTypeDescriptor can use, and return it.
            var propArray = (PropertyDescriptor[])props.ToArray(
                typeof(PropertyDescriptor));

            return(new PropertyDescriptorCollection(propArray));
        }
Example #59
0
        public string[] GetActualExtensions()
        {
            ArrayList extensions = new ArrayList();

            if (JPEG)
            {
                extensions.AddRange(s_jpegExtensions);
            }
            if (TIFF)
            {
                extensions.AddRange(s_tiffExtensions);
            }
            if (BMP)
            {
                extensions.AddRange(s_bmpExtensions);
            }
            if (GIF)
            {
                extensions.AddRange(s_gifExtensions);
            }
            if (PNG)
            {
                extensions.AddRange(s_pngExtensions);
            }
            if (EMF)
            {
                extensions.AddRange(s_emfExtensions);
            }
            if (WMF)
            {
                extensions.AddRange(s_wmfExtensions);
            }
            if (ICON)
            {
                extensions.AddRange(s_iconExtensions);
            }
            if (JP2)
            {
                extensions.AddRange(s_jp2Extensions);
            }
            if (PSD)
            {
                extensions.AddRange(s_psdExtensions);
            }
            if (DDS)
            {
                extensions.AddRange(s_ddsExtensions);
            }
            if (TGA)
            {
                extensions.AddRange(s_tgaExtensions);
            }
            return((string[])extensions.ToArray(typeof(string)));
        }
        /// <summary>
        /// Parse a standard object definition into a
        /// <see cref="Spring.Objects.Factory.Config.ObjectDefinitionHolder"/>,
        /// including object name and aliases.
        /// </summary>
        /// <param name="element">The element containing the object definition.</param>
        /// <param name="containingDefinition">The containing object definition if <paramref name="element"/> is a nested element.</param>
        /// <returns>
        /// The parsed object definition wrapped within an
        /// <see cref="Spring.Objects.Factory.Config.ObjectDefinitionHolder"/>
        /// instance.
        /// </returns>
        /// <remarks>
        /// <para>
        /// Object elements specify their canonical name via the "id" attribute
        /// and their aliases as a delimited "name" attribute.
        /// </para>
        /// <para>
        /// If no "id" is specified, uses the first name in the "name" attribute
        /// as the canonical name, registering all others as aliases.
        /// </para>
        /// </remarks>
        public ObjectDefinitionHolder ParseObjectDefinitionElement(XmlElement element, IObjectDefinition containingDefinition)
        {
            string    id       = GetAttributeValue(element, ObjectDefinitionConstants.IdAttribute);
            string    nameAttr = GetAttributeValue(element, ObjectDefinitionConstants.NameAttribute);
            ArrayList aliases  = new ArrayList();

            if (StringUtils.HasText(nameAttr))
            {
                aliases.AddRange(GetObjectNames(nameAttr));
            }

            // if we ain't got an id, check if object is page definition or assign any existing (first) alias...
            string objectName = id;

            if (StringUtils.IsNullOrEmpty(objectName))
            {
                if (aliases.Count > 0)
                {
                    objectName = (string)aliases[0];
                    aliases.RemoveAt(0);
                    if (log.IsDebugEnabled)
                    {
                        log.Debug(string.Format("No XML 'id' specified using '{0}' as object name and '{1}' as aliases", objectName, string.Join(",", (string[])aliases.ToArray(typeof(string)))));
                    }
                }
            }

            objectName = PostProcessObjectNameAndAliases(objectName, aliases, element, containingDefinition);

            if (containingDefinition == null)
            {
                CheckNameUniqueness(objectName, aliases, element);
            }

            ParserContext parserContext = new ParserContext(this, containingDefinition);
            IConfigurableObjectDefinition definition = objectsNamespaceParser.ParseObjectDefinitionElement(element, objectName, parserContext);

            if (definition != null)
            {
                if (StringUtils.IsNullOrEmpty(objectName))
                {
                    if (containingDefinition != null)
                    {
                        objectName =
                            ObjectDefinitionReaderUtils.GenerateObjectName(definition, readerContext.Registry, true);
                    }
                    else
                    {
                        objectName = readerContext.GenerateObjectName(definition);
                        // Register an alias for the plain object type name, if possible.
                        string objectTypeName = definition.ObjectTypeName;
                        if (objectTypeName != null &&
                            objectName.StartsWith(objectTypeName) &&
                            objectName.Length > objectTypeName.Length &&
                            !readerContext.Registry.IsObjectNameInUse(objectTypeName))
                        {
                            aliases.Add(objectTypeName);
                        }
                    }

                    #region Instrumentation

                    if (log.IsDebugEnabled)
                    {
                        log.Debug(string.Format(
                                      "Neither XML '{0}' nor '{1}' specified - using generated object name [{2}]",
                                      ObjectDefinitionConstants.IdAttribute, ObjectDefinitionConstants.NameAttribute, objectName));
                    }

                    #endregion
                }
                string[] aliasesArray = (string[])aliases.ToArray(typeof(string));
                return(CreateObjectDefinitionHolder(element, definition, objectName, aliasesArray));
            }
            return(null);
        }