static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
 {
     foreach (var ass in importedAssets)
     {
         if (ass.EndsWith(".txt"))
         {
             StreamReader sr = new StreamReader(ass);
             var s = sr.ReadLine();
             if (s == "[Terrain Importer]")
             {
                 var baseparam = new Hashtable();
                 baseparam["terrainWidth"] = "1000";
                 baseparam["terrainHeight"] = "200";
                 baseparam["terrainLength"] = "1000";
                 baseparam["terrainTileX"] = "0";
                 baseparam["terrainTileY"] = "0";
                 baseparam["equalizeLayers"] = 0;
                 baseparam["heightFormat"] = "r16littleendian";
                 var param = (Hashtable)baseparam.Clone();
                 var currentoutput = "";
                 while (sr.Peek() >= 0)
                 {
                     s = sr.ReadLine();
                     if (s.StartsWith("[") && s.EndsWith("]"))
                     {
                         if (currentoutput == "")
                         {
                             baseparam = (Hashtable)param.Clone();
                         }
                         else
                         {
                             GenerateTerrain(currentoutput, param, Path.GetDirectoryName(ass));
                         }
                         currentoutput = s.Substring(1, s.Length - 2);
                         param = (Hashtable)baseparam.Clone();
                     }
                     else if (s == "" || s.StartsWith("//") || s.StartsWith("#"))
                     {
                         
                     }
                     else
                     {
                         var kv = s.Split("="[0]);
                         param[kv[0]] = kv[1];
                     }
                 }
                 if (currentoutput == "")
                 {
                     GenerateTerrain(Path.GetFileNameWithoutExtension(ass) + "-terrain", param, Path.GetDirectoryName(ass));
                 }
                 else
                 {
                     GenerateTerrain(currentoutput, param, Path.GetDirectoryName(ass));
                 }
             }
             sr.Close();
         }
     }
 }
Exemple #2
0
        public void TestCloneShallowCopyReferenceTypes()
        {
            //[]Clone is a shallow copy, so the objects of the objets reference should be the same
            string strValue;

            var hsh1 = new Hashtable();
            for (int i = 0; i < 10; i++)
            {
                hsh1.Add(i, new Foo());
            }

            var hsh2 = (Hashtable)hsh1.Clone();
            for (int i = 0; i < 10; i++)
            {
                strValue = "Hello World";
                Assert.True(strValue.Equals(((Foo)hsh2[i]).strValue), "Error, Expected value not returned, " + strValue);
            }

            strValue = "Good Bye";
            ((Foo)hsh1[0]).strValue = strValue;
            Assert.True(strValue.Equals(((Foo)hsh1[0]).strValue), "Error, Expected value not returned, " + strValue);

            //da test
            Assert.True(strValue.Equals(((Foo)hsh2[0]).strValue), "Error, Expected value not returned, " + strValue);

            //if we change the object, of course, the previous should not happen
            hsh2[0] = new Foo();

            strValue = "Good Bye";
            Assert.True(strValue.Equals(((Foo)hsh1[0]).strValue), "Error, Expected value not returned, " + strValue);

            strValue = "Hello World";
            Assert.True(strValue.Equals(((Foo)hsh2[0]).strValue), "Error, Expected value not returned, " + strValue);
        }
Exemple #3
0
    void Start(){
    	playerDelegate = gameObject.GetComponent<PlayerDelegate>();

    	inputList = new Hashtable();
    	inputList.Add("X thrust", "X thrust");
    	inputList.Add("Z thrust", "Z thrust");
    	inputList.Add("Roll thrust", "Roll thrust");
    	inputList.Add("Mouse X", "Mouse X");
    	inputList.Add("Mouse Y", "Mouse Y");
    	inputList.Add("Fire left", "Fire left");
    	inputList.Add("Fire right", "Fire right");
    	inputList.Add("Shield left", "Shield left");
    	inputList.Add("Shield right", "Shield right");
    	inputList.Add("Camera select", "Camera select");
    	inputList.Add("Boost left", "Boost left");
    	inputList.Add("Boost right", "Boost right");
    	inputList.Add("Boost up", "Boost up");
    	inputList.Add("Boost down", "Boost down");
    	inputList.Add("Pause", "Pause");
    	foreach(string key in ((Hashtable)inputList.Clone()).Keys){
    		if(player2){
    			inputList[key] = inputList[key] + " 2";
    		}
    	}

		if(player2){
    		controllerName = Input.GetJoystickNames()[1];
    	}
    	else{
    		controllerName = Input.GetJoystickNames()[0];
    	}
    	if(controllerName == "Controller (Xbox 360 Wireless Receiver for Windows)"){
    		isXboxController = true;
    		isPs4Controller = false;
    		Debug.Log("Xbox controller");
    	}else if(controllerName == "Ps4 controller name"){
    		isXboxController = false;
    		isPs4Controller = true;
    		Debug.Log("Ps4 controller");
    	}else{
    		isXboxController = false;
    		isPs4Controller = false;
    		Debug.Log("Some other controller");
    	}
    	if(player2){
    		joystickNumber = 2;
    	}else{
    		joystickNumber = 1;
    	}

    	dpadThreshold = 0.1f;
    	fireThreshold = 0.1f;
    	
    	leftWeaponFiring = false;
    	rightWeaponFiring = false;

    	boosting = false;
    }
Exemple #4
0
        public void TestCloneBasic()
        {
            Hashtable hsh1;
            Hashtable hsh2;

            string strKey;
            string strValue;

            //[] empty Hashtable clone
            hsh1 = new Hashtable();
            hsh2 = (Hashtable)hsh1.Clone();

            Assert.Equal(0, hsh2.Count);
            Assert.False(hsh2.IsReadOnly, "Error, Expected value not returned, <<" + hsh1.IsReadOnly + ">> <<" + hsh2.IsReadOnly + ">>");
            Assert.False(hsh2.IsSynchronized, "Error, Expected value not returned, <<" + hsh1.IsSynchronized + ">> <<" + hsh2.IsSynchronized + ">>");

            //[] Clone should exactly replicate a collection to another object reference
            //afterwards these 2 should not hold the same object references
            hsh1 = new Hashtable();
            for (int i = 0; i < 10; i++)
            {
                strKey = "Key_" + i;
                strValue = "string_" + i;
                hsh1.Add(strKey, strValue);
            }

            hsh2 = (Hashtable)hsh1.Clone();
            for (int i = 0; i < 10; i++)
            {
                strValue = "string_" + i;

                Assert.True(strValue.Equals((string)hsh2["Key_" + i]), "Error, Expected value not returned, " + strValue);
            }

            //now we remove an object from the original list
            hsh1.Remove("Key_9");
            Assert.Equal(hsh1["Key_9"], null);

            strValue = "string_" + 9;
            Assert.True(strValue.Equals((string)hsh2["Key_9"]), "Error, Expected value not returned, <<" + hsh1[9] + ">>");

            //[]now we try other test cases
            //are all the 'other' properties of the Hashtable the same?
            hsh1 = new Hashtable(1000);
            hsh2 = (Hashtable)hsh1.Clone();

            Assert.Equal(hsh1.Count, hsh2.Count);
            Assert.Equal(hsh1.IsReadOnly, hsh2.IsReadOnly);
            Assert.Equal(hsh1.IsSynchronized, hsh2.IsSynchronized);
        }
Exemple #5
0
        public static void PerformActionOnAllHashtableWrappers(Hashtable hashtable, Action<Hashtable> action)
        {
            // Synchronized returns a slightly different version of Hashtable
            Hashtable[] hashtableTypes =
            {
                (Hashtable)hashtable.Clone(),
                Hashtable.Synchronized(hashtable)
            };

            foreach (Hashtable hashtableType in hashtableTypes)
            {
                action(hashtableType);
            }
        }
        public void UpdateUsersOnline()
        {
            // Get a Current User List
            Hashtable userList = this.GetUserList();

            // Create a shallow copy of the list to Process
            var listToProcess = (Hashtable)userList.Clone();

            // Clear the list
            this.ClearUserList();

            // Persist the current User List
            try
            {
                memberProvider.UpdateUsersOnline(listToProcess);
            }
            catch (Exception exc)
            {
                Logger.Error(exc);
            }

            // Remove users that have expired
            memberProvider.DeleteUsersOnline(this.GetOnlineTimeWindow());
        }
Exemple #7
0
        public ActionResult Delete()
        {
            var         oldParam    = new Hashtable();
            BaseResult  br          = new BaseResult();
            Hashtable   param       = base.GetParameters();
            Hashtable   param_model = null;
            ParamVessel pv          = new ParamVessel();

            param.Add("id_masteruser", id_user_master);
            pv.Add("id_masteruser", string.Empty, HandleType.ReturnMsg);
            pv.Add("id", string.Empty, HandleType.ReturnMsg);
            try
            {
                param_model = param.Trim(pv);
                oldParam    = (Hashtable)param_model.Clone();
                br          = BusinessFactory.Td_Fk_1.Delete(param);
            }
            catch (Exception ex)
            {
                br.Message.Add(ex.Message);
            }
            WriteDBLog("进货付款-删除", oldParam, br);
            return(JsonString(br, 1));
        }
Exemple #8
0
        public ActionResult Sh()
        {
            BaseResult  br    = new BaseResult();
            Hashtable   param = base.GetParameters();
            ParamVessel pv    = new ParamVessel();

            pv.Add("id", string.Empty, HandleType.ReturnMsg);
            var oldParam = new Hashtable();

            try
            {
                param = param.Trim(pv);
                param.Add("id_masteruser", id_user_master);
                param.Add("id_user", id_user);
                oldParam = (Hashtable)param.Clone();
                br       = BusinessFactory.Td_Xs_Dd_1.Active(param);
            }
            catch (Exception ex)
            {
                br.Message.Add(ex.Message);
            }
            WriteDBLog("销售订单-审核", oldParam, br);
            return(JsonString(br, 1));
        }
Exemple #9
0
        public object Clone()
        {
            DistributionMaps maps = new DistributionMaps(_result);

            if (_hashmap != null)
            {
                maps.Hashmap = _hashmap.Clone() as ArrayList;
            }
            if (_bucketsOwnershipMap != null)
            {
                maps.BucketsOwnershipMap = _bucketsOwnershipMap.Clone() as Hashtable;
            }
            if (_specialBucketOwners != null)
            {
                maps.SpecialBucketOwners = _specialBucketOwners.Clone() as Hashtable;
            }
            if (_orphanedBuckets != null)
            {
                maps.OrphanedBuckets = _orphanedBuckets.Clone() as Hashtable;
            }
            maps.LeavingNode = _leavingNode;

            return(maps);
        }
    private static Hashtable mergeData(Hashtable mainData, Hashtable addition)
    {
        Hashtable mergeProduct = (Hashtable)mainData.Clone();

        foreach (DictionaryEntry entry in addition)
        {
            var value = mergeProduct[entry.Key];
            // if there's already such an entry in the global config
            //System.Type type = value.GetType();
            if (value != null && value is IList &&
                entry.Value is IList)
            {
                List <object> dedupOutput = new List <object>((List <object>)value);
                if (dedupOutput.Count == 0)
                {
                    dedupOutput.Add("");
                }
                foreach (var obj in (IList)(entry.Value))
                {
                    if (!dedupOutput.Contains(obj))
                    {
                        dedupOutput.Add(obj);
                    }
                }



                mergeProduct[entry.Key] = dedupOutput;
            }
            else if (value == null)
            {
                mergeProduct.Add(entry.Key, entry.Value);
            }
        }
        return(mergeProduct);
    }
        public void SyncRoot()
        {
            // Different hashtables have different SyncRoots
            var hash1 = new Hashtable();
            var hash2 = new Hashtable();

            Assert.NotSame(hash1.SyncRoot, hash2.SyncRoot);
            Assert.Equal(typeof(Hashtable), hash1.SyncRoot.GetType());

            // Cloned hashtables have different SyncRoots
            hash1 = new Hashtable();
            hash2 = Hashtable.Synchronized(hash1);
            Hashtable hash3 = (Hashtable)hash2.Clone();

            Assert.NotSame(hash2.SyncRoot, hash3.SyncRoot);
            Assert.NotSame(hash1.SyncRoot, hash3.SyncRoot);

            // Testing SyncRoot is not as simple as its implementation looks like. This is the working
            // scenario we have in mind.
            // 1) Create your Down to earth mother Hashtable
            // 2) Get a synchronized wrapper from it
            // 3) Get a Synchronized wrapper from 2)
            // 4) Get a synchronized wrapper of the mother from 1)
            // 5) all of these should SyncRoot to the mother earth

            var hashMother = new Hashtable();

            for (int i = 0; i < NumberOfElements; i++)
            {
                hashMother.Add("Key_" + i, "Value_" + i);
            }

            Hashtable hashSon = Hashtable.Synchronized(hashMother);

            _hashGrandDaughter = Hashtable.Synchronized(hashSon);
            _hashDaughter      = Hashtable.Synchronized(hashMother);

            Assert.Same(hashSon.SyncRoot, hashMother.SyncRoot);
            Assert.Equal(hashSon.SyncRoot, hashMother.SyncRoot);
            Assert.Same(_hashGrandDaughter.SyncRoot, hashMother.SyncRoot);
            Assert.Same(_hashDaughter.SyncRoot, hashMother.SyncRoot);
            Assert.Same(hashSon.SyncRoot, hashMother.SyncRoot);

            // We are going to rumble with the Hashtables with some threads
            int iNumberOfWorkers = 30;
            var workers          = new Task[iNumberOfWorkers];
            var ts2 = new Action(RemoveElements);

            for (int iThreads = 0; iThreads < iNumberOfWorkers; iThreads += 2)
            {
                var name = "Thread_worker_" + iThreads;
                var ts1  = new Action(() => AddMoreElements(name));

                workers[iThreads]     = Task.Run(ts1);
                workers[iThreads + 1] = Task.Run(ts2);
            }

            Task.WaitAll(workers);

            // Check:
            // Either there should be some elements (the new ones we added and/or the original ones) or none
            var hshPossibleValues = new Hashtable();

            for (int i = 0; i < NumberOfElements; i++)
            {
                hshPossibleValues.Add("Key_" + i, "Value_" + i);
            }

            for (int i = 0; i < iNumberOfWorkers; i++)
            {
                hshPossibleValues.Add("Key_Thread_worker_" + i, "Thread_worker_" + i);
            }

            IDictionaryEnumerator idic = hashMother.GetEnumerator();

            while (idic.MoveNext())
            {
                Assert.True(hshPossibleValues.ContainsKey(idic.Key));
                Assert.True(hshPossibleValues.ContainsValue(idic.Value));
            }
        }
Exemple #12
0
 public WaitForSeconds By(System.Object obj, float duration, Hashtable _properties, Hashtable _options) {
     properties = (Hashtable)_properties.Clone();
     options = (Hashtable)_options.Clone();
     options = ExtractOptions(ref options);
     CreateAnimations(obj, properties, duration, options, AniType.By);
     return new WaitForSeconds(duration);
 }
Exemple #13
0
 public void Params(Hashtable args)
 {
     questParams = args.Clone() as Hashtable;
 }
Exemple #14
0
    private void Populate_ViewBlogPostsByCategoryGrid(EkContentCol contentdata, Hashtable commenttally)
    {
        System.Web.UI.WebControls.BoundColumn colBound = new System.Web.UI.WebControls.BoundColumn();
        string strTag;
        string strtag1;

        strTag = "<a href=\"content.aspx?LangType=" + _ContentApi.ContentLanguage + "&action=" + _PageAction + "&orderby=";
        strtag1 = "&id=" + _Id + (_ContentTypeQuerystringParam != "" ? "&" + _ContentTypeUrlParam + "=" + _ContentTypeQuerystringParam : "") + "\" title=\"" + _MessageHelper.GetMessage("click to sort msg") + "\">";

        colBound.DataField = "TITLE";
        colBound.HeaderText = _MessageHelper.GetMessage("generic Title");
        colBound.HeaderStyle.CssClass = "title-header";
        colBound.ItemStyle.CssClass = "left";
        FolderDataGrid.Columns.Add(colBound);

        colBound = new System.Web.UI.WebControls.BoundColumn();
        colBound.DataField = "LANGUAGE";
        colBound.HeaderText = _MessageHelper.GetMessage("generic language");
        colBound.HeaderStyle.CssClass = "title-header center";
        colBound.ItemStyle.CssClass = "center";
        FolderDataGrid.Columns.Add(colBound);

        colBound = new System.Web.UI.WebControls.BoundColumn();
        colBound.DataField = "ID";
        colBound.HeaderText = _MessageHelper.GetMessage("generic ID");
        colBound.HeaderStyle.CssClass = "title-header center";
        colBound.ItemStyle.CssClass = "center";
        FolderDataGrid.Columns.Add(colBound);

        colBound = new System.Web.UI.WebControls.BoundColumn();
        colBound.DataField = "STATUS";
        colBound.HeaderText = _MessageHelper.GetMessage("generic Status");
        colBound.HeaderStyle.CssClass = "title-header center";
        colBound.ItemStyle.CssClass = "center";
        FolderDataGrid.Columns.Add(colBound);

        colBound = new System.Web.UI.WebControls.BoundColumn();
        colBound.DataField = "DATEMODIFIED";
        colBound.HeaderText = _MessageHelper.GetMessage("generic Date Modified");
        colBound.HeaderStyle.CssClass = "title-header";
        colBound.ItemStyle.CssClass = "left";
        FolderDataGrid.Columns.Add(colBound);

        colBound = new System.Web.UI.WebControls.BoundColumn();
        colBound.DataField = "EDITORNAME";
        colBound.HeaderText = _MessageHelper.GetMessage("generic Last Editor");
        colBound.HeaderStyle.CssClass = "title-header";
        colBound.ItemStyle.CssClass = "left";
        FolderDataGrid.Columns.Add(colBound);

        colBound = new System.Web.UI.WebControls.BoundColumn();
        colBound.DataField = "COMMENTS";
        colBound.HeaderText = _MessageHelper.GetMessage("comments label");
        colBound.HeaderStyle.CssClass = "title-header center";
        colBound.ItemStyle.CssClass = "center";
        FolderDataGrid.Columns.Add(colBound);

        DataTable dt = new DataTable();
        DataRow dr;
        dt.Columns.Add(new DataColumn("TITLE", typeof(string)));
        dt.Columns.Add(new DataColumn("LANGUAGE", typeof(string)));
        dt.Columns.Add(new DataColumn("ID", typeof(long)));
        dt.Columns.Add(new DataColumn("STATUS", typeof(string)));
        dt.Columns.Add(new DataColumn("DATEMODIFIED", typeof(string)));
        dt.Columns.Add(new DataColumn("EDITORNAME", typeof(string)));
        dt.Columns.Add(new DataColumn("COMMENTS", typeof(string)));

        int i;
        string[] aValues;
        for (i = 0; i <= contentdata.Count - 1; i++)
        {
            commenttally = (Hashtable)commenttally.Clone();
            dr = dt.NewRow();

            dr[0] += "<img src=\"" + _ContentApi.ApplicationPath + "images/ui/icons/blog.png\" style=\"margin-right:.25em;\" />";
            dr[0] += "<a href=\"content.aspx?action=View&folder_id=" + _Id + "&id=" + contentdata.get_Item(i).Id + "&mode=1&LangType=" + contentdata.get_Item(i).Language + "&callerpage=content.aspx&origurl=" + EkFunctions.UrlEncode(Request.ServerVariables["QUERY_STRING"]) + "\"" + " title=\'" + _MessageHelper.GetMessage("generic View") + " \"" + Strings.Replace((string)(contentdata.get_Item(i).Title + "\""), "\'", "`", 1, -1, 0) + "\'" + ">";
            dr[0] += contentdata.get_Item(i).Title;
            dr[0] += "</a>";

            string LanguageDescription = Ektron.Cms.API.JS.Escape(contentdata.get_Item(i).LanguageDescription);
            dr[1] = "<a href=\"#ShowTip\" onmouseover=\"ddrivetip(\'" + LanguageDescription + "\',\'ADC5EF\', 100);\" onmouseout=\"hideddrivetip()\" style=\"text-decoration:none;\">" + "<img src=\'" + _LocalizationApi.GetFlagUrlByLanguageID(contentdata.get_Item(i).Language) + "\' border=\"0\" />" + "</a>";
            dr[2] = contentdata.get_Item(i).Id;
            dr[3] = _StyleHelper.StatusWithToolTip(contentdata.get_Item(i).ContentStatus);
            dr[4] = contentdata.get_Item(i).DateModified.ToString();
            dr[5] = contentdata.get_Item(i).LastEditorLname + ", " + contentdata.get_Item(i).LastEditorFname;
            if (commenttally.ContainsKey((contentdata.get_Item(i).Id.ToString()) + "-" + contentdata.get_Item(i).Language.ToString()))
            {
                aValues = (string[])commenttally[(contentdata.get_Item(i).Id.ToString()) + "-" + contentdata.get_Item(i).Language.ToString()];
                string actionRequired = "";

                // let's do some math to see if any of the comments are pending admin interaction.
                // if the comment_sum/aValues(1) value is less than the number of comments times "7"
                // (the value of blog comment status complete), then at least one must be pending action.
                if (Convert.ToInt32(aValues[1]) < (Convert.ToInt32(aValues[0]) * 7))
                {
                    actionRequired = "class=\"blogCommentStatusPending\" title=\"" + _MessageHelper.GetMessage("moderator action required") + "\" ";
                }
                dr[6] += "<a " + actionRequired + "href=\"content.aspx?id=" + _Id + "&action=ViewContentByCategory&LangType=" + _ContentLanguage.ToString() + "&ContType=" + Ektron.Cms.Common.EkConstants.CMSContentType_BlogComments + "&contentid=" + contentdata.get_Item(i).Id.ToString() + "&viewin=" + contentdata.get_Item(i).Language.ToString() + "\">" + aValues[0].ToString() + "</a>";
            }
            else
            {
                dr[6] += "<a href=\"content.aspx?id=" + _Id + "&action=ViewContentByCategory&LangType=" + _ContentLanguage.ToString() + "&ContType=" + Ektron.Cms.Common.EkConstants.CMSContentType_BlogComments + "&contentid=" + contentdata.get_Item(i).Id.ToString() + "&viewin=" + contentdata.get_Item(i).Language.ToString() + "\">" + 0 + "</a>";
            }

            dt.Rows.Add(dr);
        }
        DataView dv = new DataView(dt);
        FolderDataGrid.DataSource = dv;
        FolderDataGrid.DataBind();
    }
Exemple #15
0
 public bool runTest()
 {
     Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer);
     int iCountErrors = 0;
     int iCountTestcases = 0;
     String strLoc = "Loc_000oo";
     Hashtable hsh1;
     String strValue;
     Thread[] workers;
     ThreadStart ts1;
     Int32 iNumberOfWorkers = 15;
     Boolean fLoopExit;
     DictionaryEntry[] strValueArr;
     String[] strKeyArr;
     Hashtable hsh3;
     Hashtable hsh4;
     IDictionaryEnumerator idic;
     MemoryStream ms1;
     Boolean fPass;
     Object oValue;
     try 
     {
         do
         {
             hsh1 = new Hashtable();
             for(int i=0; i<iNumberOfElements; i++)
             {
                 hsh1.Add("Key_" + i, "Value_" + i);
             }
             hsh2 = Hashtable.Synchronized(hsh1);
             fPass = true;
             iCountTestcases++;
             if(hsh2.Count != hsh1.Count) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_742dsf! Expected value not returned, " + hsh2.Count);
             }
             for(int i=0; i<iNumberOfElements; i++)
             {
                 if(!((String)hsh2["Key_" + i]).Equals("Value_" + i))
                 {
                     Console.WriteLine(hsh2["Key_" + i]);
                     fPass = false;
                 }
             }
             try
             {
                 oValue = hsh2[null];
                 fPass = false;
             }
             catch(ArgumentNullException)
             {
             }
             catch(Exception)
             {
                 fPass = false;
             }
             hsh2.Clear();
             for(int i=0; i<iNumberOfElements; i++)
             {
                 hsh2["Key_" + i] =  "Value_" + i;
             }
             if(!fPass)
             {
                 iCountErrors++;
                 Console.WriteLine("Err_752dsgf! Oh man! This is busted!!!!");
             }
             strValueArr = new DictionaryEntry[hsh2.Count];
             hsh2.CopyTo(strValueArr, 0);
             hsh3 = new Hashtable();
             for(int i=0; i<iNumberOfElements; i++)
             {
                 if(!hsh2.Contains("Key_" + i)) 
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_742ds8f! Expected value not returned, " + hsh2.Contains("Key_" + i));
                 }				
                 if(!hsh2.ContainsKey("Key_" + i)) 
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_742389dsaf! Expected value not returned, " + hsh2.ContainsKey("Key_" + i));
                 }				
                 if(!hsh2.ContainsValue("Value_" + i)) 
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_563fgd! Expected value not returned, " + hsh2.ContainsValue("Value_" + i));
                 }				
                 if(!hsh1.ContainsValue(((DictionaryEntry)strValueArr[i]).Value)) 
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_87429dsfd! Expected value not returned, " + ((DictionaryEntry)strValueArr[i]).Value);
                 }				
                 try
                 {
                     hsh3.Add(strValueArr[i], null);
                 }
                 catch(Exception)
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_74298dsd! Exception thrown for  " + strValueArr[i]);
                 }
             }
             hsh4 = (Hashtable)hsh2.Clone();
             if(hsh4.Count != hsh1.Count) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_342342! Expected value not returned, " + hsh4.Count);
             }				
             strValueArr = new DictionaryEntry[hsh4.Count];
             hsh4.CopyTo(strValueArr, 0);
             hsh3 = new Hashtable();
             for(int i=0; i<iNumberOfElements; i++)
             {
                 if(!hsh4.Contains("Key_" + i)) 
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_742ds8f! Expected value not returned, " + hsh4.Contains("Key_" + i));
                 }				
                 if(!hsh4.ContainsKey("Key_" + i)) 
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_742389dsaf! Expected value not returned, " + hsh4.ContainsKey("Key_" + i));
                 }				
                 if(!hsh4.ContainsValue("Value_" + i)) 
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_6-4142dsf! Expected value not returned, " + hsh4.ContainsValue("Value_" + i));
                 }				
                 if(!hsh1.ContainsValue(((DictionaryEntry)strValueArr[i]).Value)) 
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_87429dsfd! Expected value not returned, " + ((DictionaryEntry)strValueArr[i]).Value);
                 }				
                 try
                 {
                     hsh3.Add(((DictionaryEntry)strValueArr[i]).Value, null);
                 }
                 catch(Exception)
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_74298dsd! Exception thrown for  " + ((DictionaryEntry)strValueArr[i]).Value);
                 }
             }
             if(hsh4.IsReadOnly) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_723sadf! Expected value not returned, " + hsh4.IsReadOnly);
             }
             if(!hsh4.IsSynchronized) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_723sadf! Expected value not returned, " + hsh4.IsSynchronized);
             }
             idic = hsh2.GetEnumerator();
             hsh3 = new Hashtable();
             hsh4 = new Hashtable();
         while(idic.MoveNext())
         {
             if(!hsh2.ContainsKey(idic.Key)) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_4532sfds! Expected value not returned");
             }				
             if(!hsh2.ContainsValue(idic.Value)) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_682wm! Expected value not returned");
             }				
             try
             {
                 hsh3.Add(idic.Key, null);
             }
             catch(Exception)
             {
                 iCountErrors++;
                 Console.WriteLine("Err_5243sfd! Exception thrown for  " + idic.Key);
             }
             try
             {
                 hsh4.Add(idic.Value, null);
             }
             catch(Exception)
             {
                 iCountErrors++;
                 Console.WriteLine("Err_25sfs! Exception thrown for  " + idic.Value);
             }
         }
             BinaryFormatter formatter = new BinaryFormatter();
             ms1 = new MemoryStream();
             formatter.Serialize(ms1, hsh2);
             ms1.Position = 0;
             hsh4 = (Hashtable)formatter.Deserialize(ms1);
             if(hsh4.Count != hsh1.Count) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_072xsf! Expected value not returned, " + hsh4.Count);
             }				
             strValueArr = new DictionaryEntry[hsh4.Count];
             hsh4.CopyTo(strValueArr, 0);
             hsh3 = new Hashtable();
             for(int i=0; i<iNumberOfElements; i++)
             {
                 if(!hsh4.Contains("Key_" + i)) 
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_742ds8f! Expected value not returned, " + hsh4.Contains("Key_" + i));
                 }				
                 if(!hsh4.ContainsKey("Key_" + i)) 
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_742389dsaf! Expected value not returned, " + hsh4.ContainsKey("Key_" + i));
                 }				
                 if(!hsh4.ContainsValue("Value_" + i)) 
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_0672esfs! Expected value not returned, " + hsh4.ContainsValue("Value_" + i));
                 }				
                 if(!hsh1.ContainsValue(((DictionaryEntry)strValueArr[i]).Value)) 
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_87429dsfd! Expected value not returned, " + ((DictionaryEntry)strValueArr[i]).Value);
                 }				
                 try
                 {
                     hsh3.Add(((DictionaryEntry)strValueArr[i]).Value, null);
                 }
                 catch(Exception)
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_74298dsd! Exception thrown for  " + strValueArr[i]);
                 }
             }
             if(hsh4.IsReadOnly) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_723sadf! Expected value not returned, " + hsh4.IsReadOnly);
             }
             if(!hsh4.IsSynchronized) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_723sadf! Expected value not returned, " + hsh4.IsSynchronized);
             }
             if(hsh2.IsReadOnly) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_723sadf! Expected value not returned, " + hsh2.IsReadOnly);
             }
             if(!hsh2.IsSynchronized) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_723sadf! Expected value not returned, " + hsh2.IsSynchronized);
             }
             if(hsh2.SyncRoot != hsh1) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_7428dsafd! Expected value not returned, ");
             }
             String[] strValueArr11 = new String[hsh1.Count];
             strKeyArr = new String[hsh1.Count];
             hsh2.Keys.CopyTo(strKeyArr, 0);
             hsh2.Values.CopyTo(strValueArr11, 0);
             hsh3 = new Hashtable();
             hsh4 = new Hashtable();
             for(int i=0; i<iNumberOfElements; i++)
             {
                 if(!hsh2.ContainsKey(strKeyArr[i])) 
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_4532sfds! Expected value not returned");
                 }				
                 if(!hsh2.ContainsValue(strValueArr11[i])) 
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_074dsd! Expected value not returned, " + strValueArr11[i]);
                 }				
                 try
                 {
                     hsh3.Add(strKeyArr[i], null);
                 }
                 catch(Exception)
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_5243sfd! Exception thrown for  " + idic.Key);
                 }
                 try
                 {
                     hsh4.Add(strValueArr11[i], null);
                 }
                 catch(Exception)
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_25sfs! Exception thrown for  " + idic.Value);
                 }
             }
             hsh2.Remove("Key_1");
             if(hsh2.ContainsKey("Key_1")) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_423ewd! Expected value not returned, ");
             }				
             if(hsh2.ContainsValue("Value_1")) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_64q213d! Expected value not returned, ");
             }				
             hsh2.Add("Key_1", "Value_1");
             if(!hsh2.ContainsKey("Key_1")) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_423ewd! Expected value not returned, ");
             }				
             if(!hsh2.ContainsValue("Value_1")) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_74523esf! Expected value not returned, ");
             }				
             hsh2["Key_1"] = "Value_Modified_1";
             if(!hsh2.ContainsKey("Key_1")) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_423ewd! Expected value not returned, ");
             }				
             if(hsh2.ContainsValue("Value_1")) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_74523esf! Expected value not returned, ");
             }				
             if(!hsh2.ContainsValue("Value_Modified_1")) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_342fs! Expected value not returned, ");
             }		
             hsh3 = Hashtable.Synchronized(hsh2);
             if(hsh3.Count != hsh1.Count) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_742dsf! Expected value not returned, " + hsh3.Count);
             }				
             if(!hsh3.IsSynchronized) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_723sadf! Expected value not returned, " + hsh3.IsSynchronized);
             }
             hsh2.Clear();		
             if(hsh2.Count != 0) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_742dsf! Expected value not returned, " + hsh2.Count);
             }				
             strLoc = "Loc_8345vdfv";
             hsh1 = new Hashtable();
             hsh2 = Hashtable.Synchronized(hsh1);
             workers = new Thread[iNumberOfWorkers];
             ts1 = new ThreadStart(AddElements);
             for(int i=0; i<workers.Length; i++)
             {
                 workers[i] = new Thread(ts1);
                 workers[i].Name = "Thread worker " + i;
                 workers[i].Start();
             }
         while(true)
         {
             fLoopExit=false;
             for(int i=0; i<iNumberOfWorkers;i++)
             {
                 if(workers[i].IsAlive)
                     fLoopExit=true;
             }
             if(!fLoopExit)
                 break;
         }
             iCountTestcases++;
             if(hsh2.Count != iNumberOfElements*iNumberOfWorkers) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_75630fvbdf! Expected value not returned, " + hsh2.Count);
             }
             iCountTestcases++;
             for(int i=0; i<iNumberOfWorkers; i++)
             {
                 for(int j=0; j<iNumberOfElements; j++)
                 {
                     strValue = "Thread worker " + i + "_" + j;
                     if(!hsh2.Contains(strValue))
                     {
                         iCountErrors++;
                         Console.WriteLine("Err_452dvdf_" + i + "_" + j + "! Expected value not returned, " + strValue);
                     }
                 }
             }
             workers = new Thread[iNumberOfWorkers];
             ts1 = new ThreadStart(RemoveElements);
             for(int i=0; i<workers.Length; i++)
             {
                 workers[i] = new Thread(ts1);
                 workers[i].Name = "Thread worker " + i;
                 workers[i].Start();
             }
         while(true)
         {
             fLoopExit=false;
             for(int i=0; i<iNumberOfWorkers;i++)
             {
                 if(workers[i].IsAlive)
                     fLoopExit=true;
             }
             if(!fLoopExit)
                 break;
         }
             iCountTestcases++;
             if(hsh2.Count != 0) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_6720fvdg! Expected value not returned, " + hsh2.Count);
             }
             iCountTestcases++;
             if(hsh1.IsSynchronized) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_4820fdf! Expected value not returned, " + hsh1.IsSynchronized);
             }
             iCountTestcases++;
             if(!hsh2.IsSynchronized) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_4820fdf! Expected value not returned, " + hsh2.IsSynchronized);
             }
         } while (false);
     } 
     catch (Exception exc_general ) 
     {
         ++iCountErrors;
         Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy!  strLoc=="+ strLoc +", exc_general==\n"+exc_general.ToString());
     }
     if ( iCountErrors == 0 )
     {
         Console.WriteLine( "paSs.   "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases);
         return true;
     }
     else
     {
         Console.WriteLine("FAiL!   "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums );
         return false;
     }
 }
Exemple #16
0
        static void Main(string[] args)
        {
            /*Hashtable ht = new Hashtable();
             *
             * //Добавление элементов в хеш-таблицу
             * // первый параметр - ключ, второй параметр - значение
             * ht.Add("здание", "house");
             * ht.Add("машина", "machine");
             * ht.Add("книга", "book");
             * ht.Add("яблоко", "apple");*/

            Hashtable ht = new Hashtable
            {
                //Добавление элементов в хеш-таблицу
                { "здание", "house" },
                { "машина", "machine" },
                { "книга", "book" },
                { "яблоко", "apple" }
            };

            // вызывает исключение для повторяющихся ключей
            //ht.Add("здание", "something");

            // Добавление элемента с помощью индексатора (или перезапись уже существующего ключа)
            ht["здание"] = "building";

            // Удаление элемента по ключу
            ht.Remove("книга");

            //Получение коллекции ключей
            ArrayList с = new ArrayList(ht.Keys);

            //Используем ключи для получения значений
            foreach (string str in с)
            {
                Console.WriteLine(str + " : " + ht[str]);
            }

            Console.WriteLine("");

            // Получение кол-ва элементов
            Console.WriteLine(ht.Count);

            Console.WriteLine("");

            //Получение коллекции значений
            ArrayList v = new ArrayList(ht.Values);

            foreach (string str in v)
            {
                Console.WriteLine(str);
            }

            Console.WriteLine("");

            // создание копии хэш-таблицы
            Hashtable ht2 = (Hashtable)ht.Clone();

            // Определение содержания значения
            Console.WriteLine(ht2.ContainsKey("книга"));
            Console.WriteLine(ht2.ContainsKey("яблоко"));

            // быстрый поиск для Value не поддерживатся
            Console.WriteLine(ht2.ContainsValue("apple"));

            Dictionary <char, long> dict = new Dictionary <char, long>
            {
                { 'A', 45 },
                { 'B', 345 },
                { 'C', 4656 }
            };

            foreach (var item in dict)
            {
                Console.WriteLine(@"{0} : {1}", item.Key, item.Value);
            }

            if (dict.ContainsKey('z'))
            {
                long size = dict['z'];
                Console.WriteLine(size);
            }

            // Происходит сортировка ключа
            // Сортирующий словарь на основе отсортированного массива (дихотомический поиск)
            // Быстрее работает чтение и запись значений существующих элементов
            SortedList <string, int> list = new SortedList <string, int>();

            // Происходит сортировка ключа
            // Сортирующий словарь на основе бинарного дерева (дихотомический поиск)
            // Быстрее работает вставка нового элемента и удаление существующих элементов
            SortedDictionary <string, int> sorted_dict = new SortedDictionary <string, int>();
        }
Exemple #17
0
 public void RestoreState()
 {
     seatPanel.RemoveAllSelected();
     seatPanel.selectedSeat     = selectedSeatBak.Clone() as Hashtable;
     seatPanel.selectedSeatLine = selectedSeatLineBak.Clone() as ArrayList;
 }
 public ResSet Clone()
 {
     return(new ResSet((Hashtable)items.Clone()));
 }
Exemple #19
0
 public virtual void addAction(Action<Hashtable> actionFunction, Hashtable actArg)
 {
     this.actionFunction = actionFunction.Clone() as Action<Hashtable>;
     actionFunctionArgs = actArg.Clone() as Hashtable;
 }
Exemple #20
0
        public ActionResult Add(Tb_Gysfl model)
        {
            #region 获取参数
            var       oldParam = new Hashtable();
            Hashtable param    = base.GetParameters();
            param.Add("id_masteruser", id_user_master);
            Hashtable  param_model = null;
            BaseResult br          = new BaseResult();
            Tb_Gysfl   model_gysfl = new Tb_Gysfl();                           //新增对象

            #endregion
            #region 执行操作

            try
            {
                ParamVessel pv = new ParamVessel();
                pv.Add("mc", string.Empty, HandleType.ReturnMsg);              //名称
                pv.Add("bm", string.Empty, HandleType.DefaultValue);           //编码
                pv.Add("id_masteruser", id_user_master, HandleType.ReturnMsg); //用户Id
                pv.Add("parent_id", string.Empty, HandleType.ReturnMsg);       //父节点Id

                param_model = param.Trim(pv);
                oldParam    = (Hashtable)param_model.Clone();
                if (TryUpdateModel(model_gysfl))
                {
                    model_gysfl.id_farther    = param_model["parent_id"].ToString();
                    model_gysfl.id_masteruser = id_user_master;
                    model_gysfl.id_create     = model_gysfl.id_edit = id_user;
                    br = BusinessFactory.Tb_Gysfl.Add(model_gysfl);
                }
                else
                {
                    br.Message.Add("参数有误!");
                }
            }
            catch (Exception ex)
            {
                br.Message.Add(ex.Message);
            }
            #endregion

            WriteDBLog("供应商分类-新增", oldParam, br);

            if (br.Success)
            {
                return(JsonString(new
                {
                    status = "success",
                    message = "执行成功,正在载入页面...",
                    gysfl = new
                    {
                        id = model_gysfl.id,
                        is_default = "F",
                        name = model_gysfl.mc,
                        pid = model_gysfl.id_farther
                    }
                }));
            }
            else
            {
                return(JsonString(new
                {
                    status = "false",
                    message = br.Message[0].ToString()
                }));
            }
        }
Exemple #21
0
        public void TestSynchronizedBasic()
        {
            Hashtable hsh1;

            string strValue;

            Task[] workers;
            Action ts1;
            int iNumberOfWorkers = 3;
            DictionaryEntry[] strValueArr;
            string[] strKeyArr;
            Hashtable hsh3;
            Hashtable hsh4;
            IDictionaryEnumerator idic;

            object oValue;

            //[]Vanila - Syncronized returns a wrapped HT. We must make sure that all the methods
            //are accounted for here for the wrapper
            hsh1 = new Hashtable();
            for (int i = 0; i < _iNumberOfElements; i++)
            {
                hsh1.Add("Key_" + i, "Value_" + i);
            }

            _hsh2 = Hashtable.Synchronized(hsh1);
            //Count
            Assert.Equal(_hsh2.Count, hsh1.Count);

            //get/set item
            for (int i = 0; i < _iNumberOfElements; i++)
            {
                Assert.True(((string)_hsh2["Key_" + i]).Equals("Value_" + i));
            }

            Assert.Throws<ArgumentNullException>(() =>
                {
                    oValue = _hsh2[null];
                });

            _hsh2.Clear();
            for (int i = 0; i < _iNumberOfElements; i++)
            {
                _hsh2["Key_" + i] = "Value_" + i;
            }

            strValueArr = new DictionaryEntry[_hsh2.Count];
            _hsh2.CopyTo(strValueArr, 0);
            //ContainsXXX
            hsh3 = new Hashtable();
            for (int i = 0; i < _iNumberOfElements; i++)
            {
                Assert.True(_hsh2.Contains("Key_" + i));
                Assert.True(_hsh2.ContainsKey("Key_" + i));
                Assert.True(_hsh2.ContainsValue("Value_" + i));

                //we still need a way to make sure that there are all these unique values here -see below code for that
                Assert.True(hsh1.ContainsValue(((DictionaryEntry)strValueArr[i]).Value));

                hsh3.Add(strValueArr[i], null);
            }

            hsh4 = (Hashtable)_hsh2.Clone();

            Assert.Equal(hsh4.Count, hsh1.Count);
            strValueArr = new DictionaryEntry[hsh4.Count];
            hsh4.CopyTo(strValueArr, 0);
            //ContainsXXX
            hsh3 = new Hashtable();
            for (int i = 0; i < _iNumberOfElements; i++)
            {
                Assert.True(hsh4.Contains("Key_" + i));
                Assert.True(hsh4.ContainsKey("Key_" + i));
                Assert.True(hsh4.ContainsValue("Value_" + i));

                //we still need a way to make sure that there are all these unique values here -see below code for that
                Assert.True(hsh1.ContainsValue(((DictionaryEntry)strValueArr[i]).Value));

                hsh3.Add(((DictionaryEntry)strValueArr[i]).Value, null);
            }

            Assert.False(hsh4.IsReadOnly);
            Assert.True(hsh4.IsSynchronized);

            //Phew, back to other methods
            idic = _hsh2.GetEnumerator();
            hsh3 = new Hashtable();
            hsh4 = new Hashtable();
            while (idic.MoveNext())
            {
                Assert.True(_hsh2.ContainsKey(idic.Key));
                Assert.True(_hsh2.ContainsValue(idic.Value));
                hsh3.Add(idic.Key, null);
                hsh4.Add(idic.Value, null);
            }

            hsh4 = (Hashtable)_hsh2.Clone();
            strValueArr = new DictionaryEntry[hsh4.Count];
            hsh4.CopyTo(strValueArr, 0);
            hsh3 = new Hashtable();
            for (int i = 0; i < _iNumberOfElements; i++)
            {
                Assert.True(hsh4.Contains("Key_" + i));
                Assert.True(hsh4.ContainsKey("Key_" + i));
                Assert.True(hsh4.ContainsValue("Value_" + i));

                //we still need a way to make sure that there are all these unique values here -see below code for that
                Assert.True(hsh1.ContainsValue(((DictionaryEntry)strValueArr[i]).Value));

                hsh3.Add(((DictionaryEntry)strValueArr[i]).Value, null);
            }

            Assert.False(hsh4.IsReadOnly);
            Assert.True(hsh4.IsSynchronized);

            //Properties
            Assert.False(_hsh2.IsReadOnly);
            Assert.True(_hsh2.IsSynchronized);
            Assert.Equal(_hsh2.SyncRoot, hsh1.SyncRoot);

            //we will test the Keys & Values
            string[] strValueArr11 = new string[hsh1.Count];
            strKeyArr = new string[hsh1.Count];
            _hsh2.Keys.CopyTo(strKeyArr, 0);
            _hsh2.Values.CopyTo(strValueArr11, 0);

            hsh3 = new Hashtable();
            hsh4 = new Hashtable();
            for (int i = 0; i < _iNumberOfElements; i++)
            {
                Assert.True(_hsh2.ContainsKey(strKeyArr[i]));
                Assert.True(_hsh2.ContainsValue(strValueArr11[i]));

                hsh3.Add(strKeyArr[i], null);
                hsh4.Add(strValueArr11[i], null);
            }

            //now we test the modifying methods
            _hsh2.Remove("Key_1");
            Assert.False(_hsh2.ContainsKey("Key_1"));
            Assert.False(_hsh2.ContainsValue("Value_1"));

            _hsh2.Add("Key_1", "Value_1");
            Assert.True(_hsh2.ContainsKey("Key_1"));
            Assert.True(_hsh2.ContainsValue("Value_1"));

            _hsh2["Key_1"] = "Value_Modified_1";
            Assert.True(_hsh2.ContainsKey("Key_1"));
            Assert.False(_hsh2.ContainsValue("Value_1"));
            ///////////////////////////

            Assert.True(_hsh2.ContainsValue("Value_Modified_1"));
            hsh3 = Hashtable.Synchronized(_hsh2);

            //we are not going through all of the above again:) we will just make sure that this syncrnized and that 
            //values are there
            Assert.Equal(hsh3.Count, hsh1.Count);
            Assert.True(hsh3.IsSynchronized);

            _hsh2.Clear();
            Assert.Equal(_hsh2.Count, 0);

            //[] Synchronized returns a HT that is thread safe
            // We will try to test this by getting a number of threads to write some items
            // to a synchronized IList
            hsh1 = new Hashtable();
            _hsh2 = Hashtable.Synchronized(hsh1);

            workers = new Task[iNumberOfWorkers];
            for (int i = 0; i < workers.Length; i++)
            {
                var name = "Thread worker " + i;
                ts1 = new Action(() => AddElements(name));
                workers[i] = Task.Run(ts1);
            }

            Task.WaitAll(workers);

            //checking time
            Assert.Equal(_hsh2.Count, _iNumberOfElements * iNumberOfWorkers);

            for (int i = 0; i < iNumberOfWorkers; i++)
            {
                for (int j = 0; j < _iNumberOfElements; j++)
                {
                    strValue = "Thread worker " + i + "_" + j;
                    Assert.True(_hsh2.Contains(strValue));
                }
            }

            //I dont think that we can make an assumption on the order of these items though
            //now we are going to remove all of these
            workers = new Task[iNumberOfWorkers];
            for (int i = 0; i < workers.Length; i++)
            {
                var name = "Thread worker " + i;
                ts1 = new Action(() => RemoveElements(name));
                workers[i] = Task.Run(ts1);
            }

            Task.WaitAll(workers);

            Assert.Equal(_hsh2.Count, 0);
            Assert.False(hsh1.IsSynchronized);
            Assert.True(_hsh2.IsSynchronized);

            //[] Tyr calling Synchronized with null
            Assert.Throws<ArgumentNullException>(() =>
                             {
                                 Hashtable.Synchronized(null);
                             }
            );
        }
Exemple #22
0
 public bool runTest()
 {
     Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer);
     int iCountErrors = 0;
     int iCountTestcases = 0;
     String strLoc = "Loc_000oo";
     Hashtable arrSon;
     Hashtable arrMother;
     Thread[] workers;
     ThreadStart ts1;
     ThreadStart ts2;
     Int32 iNumberOfWorkers = 30;
     Boolean fLoopExit;
     Hashtable hshPossibleValues;
     IDictionaryEnumerator idic;
     Hashtable hsh1;
     Hashtable hsh2;
     Hashtable hsh3;
     try 
     {
         do
         {
             hsh1 = new Hashtable();
             hsh2 = new Hashtable();
             iCountTestcases++;
             if(hsh1.SyncRoot == hsh2.SyncRoot) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_47235fsd! Expected value not returned, ");
             }
             hsh1 = new Hashtable();
             hsh2 = Hashtable.Synchronized(hsh1);
             hsh3 = (Hashtable)hsh2.Clone();
             iCountTestcases++;
             if(hsh2.SyncRoot == hsh3.SyncRoot) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_47235fsd! Expected value not returned, ");
             }
             if(hsh1.SyncRoot == hsh3.SyncRoot) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_47235fsd! Expected value not returned, ");
             }
             strLoc = "Loc_8345vdfv";
             arrMother = new Hashtable();
             for(int i=0; i<iNumberOfElements; i++)
             {
                 arrMother.Add("Key_" + i, "Value_" + i);
             }
             arrSon = Hashtable.Synchronized(arrMother);
             arrGrandDaughter = Hashtable.Synchronized(arrSon);
             arrDaughter = Hashtable.Synchronized(arrMother);
             iCountTestcases++;
             if(arrSon.SyncRoot != arrMother.SyncRoot) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_234dnvf! Expected value not returned, " + (arrSon.SyncRoot==arrMother.SyncRoot));
             }
             iCountTestcases++;
             if(arrSon.SyncRoot!=arrMother) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_8230fvbd! Expected value not returned, " + (arrSon.SyncRoot==arrMother));
             }
             iCountTestcases++;
             if(arrGrandDaughter.SyncRoot!=arrMother) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_4927fd0fd! Expected value not returned, " + (arrGrandDaughter.SyncRoot==arrMother));
             }
             iCountTestcases++;
             if(arrDaughter.SyncRoot!=arrMother) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_85390gfg! Expected value not returned, " + (arrDaughter.SyncRoot==arrMother));
             }
             iCountTestcases++;
             if(arrSon.SyncRoot != arrMother.SyncRoot) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_234dnvf! Expected value not returned, " + (arrSon.SyncRoot==arrMother.SyncRoot));
             }
             strLoc = "Loc_845230fgdg";
             workers = new Thread[iNumberOfWorkers];
             ts1 = new ThreadStart(AddMoreElements);
             ts2 = new ThreadStart(RemoveElements);
             for(int iThreads=0; iThreads<iNumberOfWorkers;iThreads+=2)
             {
                 strLoc = "Loc_74329fd_" + iThreads;
                 workers[iThreads] = new Thread(ts1);
                 workers[iThreads].Name = "Thread_worker_" + iThreads;
                 workers[iThreads+1] = new Thread(ts2);
                 workers[iThreads+1].Name = "Thread_worker_" + iThreads + 1;
                 workers[iThreads].Start();
                 workers[iThreads+1].Start();
             }
         while(true)
         {
             fLoopExit=false;
             for(int i=0; i<iNumberOfWorkers;i++)
             {
                 if(workers[i].IsAlive)
                     fLoopExit=true;
             }
             if(!fLoopExit)
                 break;
         }
             strLoc = "Loc_7539vfdg";
             iCountTestcases++;
             hshPossibleValues = new Hashtable();
             for(int i=0; i<iNumberOfElements; i++)
             {
                 hshPossibleValues.Add("Key_" + i, "Value_" + i);
             }
             for(int i=0; i<iNumberOfWorkers; i++)
             {
                 hshPossibleValues.Add("Key_Thread_worker_" + i, "Thread_worker_" + i);
             }
             if(arrMother.Count>0)
                 Console.WriteLine("Loc_7428fdsg! Adds have it");
             idic = arrMother.GetEnumerator();
         while(idic.MoveNext())
         {
             if(!hshPossibleValues.ContainsKey(idic.Key))
             {
                 iCountErrors++;
                 Console.WriteLine("Err_7429dsf! Expected value not returned, " + idic.Key);
             }
             if(!hshPossibleValues.ContainsValue(idic.Value))
             {
                 iCountErrors++;
                 Console.WriteLine("Err_2487dsf! Expected value not returned, " + idic.Value);
             }
         }
         } while (false);
     } 
     catch (Exception exc_general ) 
     {
         ++iCountErrors;
         Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy!  strLoc=="+ strLoc +", exc_general==\n"+exc_general.ToString());
     }
     if ( iCountErrors == 0 )
     {
         Console.WriteLine( "paSs.   "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases);
         return true;
     }
     else
     {
         Console.WriteLine("FAiL!   "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums );
         return false;
     }
 }
Exemple #23
0
    // ---------------------------------------- //
    // CREATE NEW ANIMATION

    public WaitForSeconds To(UnityEngine.Object obj, float duration, Hashtable _properties) {
        properties = (Hashtable)_properties.Clone();
        options = ExtractOptions(ref properties);
        CreateAnimations(obj, properties, duration, options, AniType.To);
        return new WaitForSeconds(duration);
    }
Exemple #24
0
    /// <summary>
    /// Changes a GameObject's color values over time with FULL customization options.  If a GUIText or GUITexture component is attached, they will become the target of the animation.
    /// </summary>
    /// <param name="color">
    /// A <see cref="Color"/> to change the GameObject's color to.
    /// </param>
    /// <param name="r">
    /// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the color red.
    /// </param>
    /// <param name="g">
    /// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the color green.
    /// </param>
    /// <param name="b">
    /// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the color green.
    /// </param>
    /// <param name="a">
    /// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the alpha.
    /// </param> 
    /// <param name="namedcolorvalue">
    /// A <see cref="NamedColorValue"/> or <see cref="System.String"/> for the individual setting of the alpha.
    /// </param> 
    /// <param name="includechildren">
    /// A <see cref="System.Boolean"/> for whether or not to include children of this GameObject. True by default.
    /// </param>
    /// <param name="time">
    /// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
    /// </param>
    /// <param name="delay">
    /// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
    /// </param>
    /// <param name="easetype">
    /// A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.
    /// </param>   
    /// <param name="looptype">
    /// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.
    /// </param>
    /// <param name="onstart">
    /// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
    /// </param>
    /// <param name="onstarttarget">
    /// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
    /// </param>
    /// <param name="onstartparams">
    /// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
    /// </param>
    /// <param name="onupdate"> 
    /// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
    /// </param>
    /// <param name="onupdatetarget">
    /// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
    /// </param>
    /// <param name="onupdateparams">
    /// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
    /// </param> 
    /// <param name="oncomplete">
    /// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
    /// </param>
    /// <param name="oncompletetarget">
    /// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
    /// </param>
    /// <param name="oncompleteparams">
    /// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
    /// </param>
    public static void ColorTo(GameObject target, Hashtable args)
    {
        //clean args:
        args = iTween.CleanArgs(args);

        //handle children:
        if(!args.Contains("includechildren") || (bool)args["includechildren"]){
            foreach(Transform child in target.transform){
                Hashtable argsCopy = (Hashtable)args.Clone();
                argsCopy["ischild"]=true;
                ColorTo(child.gameObject,argsCopy);
            }
        }

        //set a default easeType of linear if none is supplied since eased color interpolation is nearly unrecognizable:
        if (!args.Contains("easetype")) {
            args.Add("easetype",EaseType.linear);
        }

        //establish iTween:
        args["type"]="color";
        args["method"]="to";
        Launch(target,args);
    }
        private void quitarTansicionesVacias(Automata automata)
        {
            //crearemos a partir de nuestro alfabeto la tabla de trancisiones
            int contadorparatablanoString = 0;

            foreach (Object key in alfabeto.Keys)
            {
                if (key is System.Collections.Hashtable)
                {
                    contadorparatablanoString++;
                }
                else
                {
                    Console.WriteLine(key);
                }
            }

            List <int>      tran;
            SortedSet <int> clau;
            LinkedList <SortedSet <int> > clau2;
            Hashtable alfabetoTemp = (Hashtable)alfabeto.Clone();

            alfabetoTemp.Remove(AnalizadorTexto.AnalizadorTexto.EPSILON);
            LinkedList <int> [,] tablatransicionesTemp = new LinkedList <int> [numestados, alfabetoTemp.Keys.Count - contadorparatablanoString];

            for (int a = 0; a < alfabetoTemp.Keys.Count - contadorparatablanoString; a++)
            {
                for (int q = 0; q < numestados; q++)
                {
                    tablatransicionesTemp[q, a] = new LinkedList <int>();
                }
            }
            foreach (Object key in alfabeto.Keys)
            {
                if (key is System.Collections.Hashtable)
                {
                    contadorparatablanoString++;
                }
                else
                {
                    if (!((String)key).Equals(AnalizadorTexto.AnalizadorTexto.EPSILON))
                    {
                        for (int cont = 0; cont < numestados; cont++)
                        {
                            //System.out.print(cont + " "+s+" -");
                            ///aqui va a ir por numero de estados del automata que es el count
                            tran  = new List <int>();
                            clau  = cerrarVacias(cont);
                            clau2 = new LinkedList <SortedSet <int> >();
                            foreach (int i in clau)
                            {
                                LinkedList <int> temp = obtenerTransicion(i, (String)key);

                                tran.AddRange(obtenerTransicion(i, (String)key));
                            }

                            int contaa = 0;
                            foreach (int i in tran)
                            {
                                clau2.AddLast(cerrarVacias(i));

                                LinkedList <Object> a = new LinkedList <Object>();
                                a.AddLast(alfabetoTemp);
                                int contador = 0;
                                foreach (Object llave in alfabeto.Keys)
                                {
                                    if (llave is System.Collections.Hashtable)
                                    {
                                    }
                                    else
                                    {
                                        if (llave is String)
                                        {
                                            if (llave.Equals(key))
                                            {
                                                break;
                                            }
                                        }
                                        contador++;
                                    }
                                }
                                if (clau2.ElementAt(contaa).Count() > 1)
                                {
                                    int aux1 = 0;
                                    foreach (int auxil in clau2.ElementAt(contaa))
                                    {
                                        if (tablatransicionesTemp[cont, contador].Contains(auxil))
                                        {
                                        }
                                        else
                                        {
                                            tablatransicionesTemp[cont, contador].AddLast(auxil);
                                        }
                                    }
                                }
                                else
                                {
                                    if (tablatransicionesTemp[cont, contador].Contains(clau2.ElementAt(contaa).ElementAt(0)))
                                    {
                                    }
                                    else
                                    {
                                        tablatransicionesTemp[cont, contador].AddLast(clau2.ElementAt(contaa).ElementAt(0));
                                    }
                                }
                                contaa++;
                            }
                        }
                    }
                }
            }
            SortedSet <int> f    = cerrarVacias(estadoInicial);
            bool            cq0F = false;

            foreach (Estado i in estadoFinal)
            {
                //int
                if (f.Contains(i.getId()))
                {
                    cq0F = true;
                }
            }
            if (cq0F)
            {
                estadoFinal.AddLast(automata.getEstadoInicial());
            }
            alfabeto = alfabetoTemp;
            tabtrans = tablatransicionesTemp;
        }
Exemple #26
0
 public UntypedSet Clone()
 {
     return(new UntypedSet((Hashtable)hashtable.Clone()));
 }
Exemple #27
0
        static void MainMenu()
        {
            //Флаг правильности ввода
            bool ok = true;
            //Флаг завершения работы
            bool Finish = false;

            // Хеш-таблица элементов иерархии
            Hashtable ExamsTable = new Hashtable();
            // Вспомогательная переменная для заполнения таблицы
            Random    rnd          = new Random();
            Challenge ElementToAdd = null;

            // Первоначальное заполнение таблицы
            for (ushort i = 0; i < 1000; i++)
            {
                do
                {
                    switch (rnd.Next(4))
                    {
                    case 0: ElementToAdd = new Challenge();
                        break;

                    case 1:
                        ElementToAdd = new Test();
                        break;

                    case 2:
                        ElementToAdd = new Exam();
                        break;

                    case 3:
                        ElementToAdd = new GraduateExam();
                        break;
                    }
                }while (ExamsTable.ContainsKey(ElementToAdd.GetName));

                ExamsTable.Add(ElementToAdd.GetName, ElementToAdd);
            }

            do
            {
                do
                {
                    Console.Clear();
                    //Вывод меню
                    Console.WriteLine();
                    Console.WriteLine("1 - Создание новой хеш-таблицы");
                    Console.WriteLine("2 - Печать хеш-таблицы");
                    Console.WriteLine("3 - Удалить элемент");
                    Console.WriteLine("4 - Добавить новый элемент");
                    Console.WriteLine("5 - Поиск количества студентов, получивших за работу оценку не ниже заданной");
                    Console.WriteLine("6 - Поиск студентов, получивших за работу оценку не ниже заданной");
                    Console.WriteLine("7 - Поиск студентов, получивших за экзамен оценку не ниже заданной");
                    Console.WriteLine("8 - Клонирование коллекции");
                    Console.WriteLine("9 - Поиск элемента с заданным ключом");
                    Console.WriteLine("10 - Выход");

                    //Выбор пункта меню и вызов соответствующих функций
                    int ChosenOption = Int32.Parse(Console.ReadLine());
                    Console.WriteLine();

                    switch (ChosenOption)
                    {
                    // Создание новой таблицы
                    case 1:

                        ExamsTable.Clear();
                        // Ввод количества элементов
                        int NumberToAdd = InputOutput.InputNumber(10, 1000);

                        for (ushort i = 0; i < NumberToAdd; i++)
                        {
                            do
                            {
                                switch (rnd.Next(4))
                                {
                                case 0:
                                    ElementToAdd = new Challenge();
                                    break;

                                case 1:
                                    ElementToAdd = new Test();
                                    break;

                                case 2:
                                    ElementToAdd = new Exam();
                                    break;

                                case 3:
                                    ElementToAdd = new GraduateExam();
                                    break;
                                }
                            }while (ExamsTable.ContainsKey(ElementToAdd.GetName));

                            ExamsTable.Add(ElementToAdd.GetName, ElementToAdd);
                        }

                        Console.WriteLine("Новая таблица успешно создана.");
                        ok = true;
                        break;

                    // Печать таблицы
                    case 2:
                        foreach (DictionaryEntry DE in ExamsTable)
                        {
                            Challenge Element = DE.Value as Challenge;
                            Element.Show();
                        }
                        ok = true;
                        break;

                    // Удаление элемента
                    case 3:
                        Console.Write("Введите ключ (ФИО) элемента, который Вы хотите удалить: ");
                        string KeyToDelete = Console.ReadLine();
                        if (ExamsTable.ContainsKey(KeyToDelete))
                        {
                            ExamsTable.Remove(KeyToDelete);
                            Console.WriteLine("Элемент с указанным ключом удален.");
                        }
                        else
                        {
                            Console.WriteLine("Элемента с таким ключом не найдено.");
                        }
                        ok = true;
                        break;

                    // Создание элемента
                    case 4:
                        // Тип создаваемого объекта
                        int Option = 0;
                        ChooseTypeMenu(out Option);

                        switch (Option)
                        {
                        case 1:
                            string Name = "";
                            do
                            {
                                Console.Write("Введите ФИО студента: ");
                                Name = Console.ReadLine();
                                if (ExamsTable.ContainsKey(Name))
                                {
                                    Console.WriteLine("В таблице уже есть элемент с таким ключом.");
                                }
                            } while (ExamsTable.ContainsKey(Name));
                            Console.Write("Введите общее количество задач: ");
                            ushort TasksTotal = UInt16.Parse(Console.ReadLine());
                            Console.Write("Введите количество решенных задач: ");
                            ushort TasksDone = UInt16.Parse(Console.ReadLine());

                            ExamsTable.Add(Name, new Challenge(Name, TasksTotal, TasksDone));
                            break;

                        case 2:
                            do
                            {
                                Console.Write("Введите ФИО студента: ");
                                Name = Console.ReadLine();
                                if (ExamsTable.ContainsKey(Name))
                                {
                                    Console.WriteLine("В таблице уже есть элемент с таким ключом.");
                                }
                            } while (ExamsTable.ContainsKey(Name));
                            Console.Write("Введите общее количество задач: ");
                            TasksTotal = UInt16.Parse(Console.ReadLine());
                            Console.Write("Введите количество решенных задач: ");
                            TasksDone = UInt16.Parse(Console.ReadLine());

                            ExamsTable.Add(Name, new Test(Name, TasksTotal, TasksDone));
                            break;

                        case 3:
                            do
                            {
                                Console.Write("Введите ФИО студента: ");
                                Name = Console.ReadLine();
                                if (ExamsTable.ContainsKey(Name))
                                {
                                    Console.WriteLine("В таблице уже есть элемент с таким ключом.");
                                }
                            } while (ExamsTable.ContainsKey(Name));
                            Console.Write("Введите общее количество задач: ");
                            TasksTotal = UInt16.Parse(Console.ReadLine());
                            Console.Write("Введите количество решенных задач: ");
                            TasksDone = UInt16.Parse(Console.ReadLine());
                            Console.Write("Введите предмет, по которому был экзамен: ");
                            string Subject = Console.ReadLine();

                            ExamsTable.Add(Name, new Exam(Name, Subject, TasksTotal, TasksDone));
                            break;

                        case 4:
                            do
                            {
                                Console.Write("Введите ФИО студента: ");
                                Name = Console.ReadLine();
                                if (ExamsTable.ContainsKey(Name))
                                {
                                    Console.WriteLine("В таблице уже есть элемент с таким ключом.");
                                }
                            } while (ExamsTable.ContainsKey(Name));
                            Console.Write("Введите общее количество задач: ");
                            TasksTotal = UInt16.Parse(Console.ReadLine());
                            Console.Write("Введите количество решенных задач: ");
                            TasksDone = UInt16.Parse(Console.ReadLine());
                            Console.Write("Введите предмет, по которому был экзамен: ");
                            Subject = Console.ReadLine();
                            Console.Write("Введите учебное заведение, откуда выпускается студент: ");
                            string Organisation = Console.ReadLine();

                            ExamsTable.Add(Name, new GraduateExam(Name, Subject, Organisation, TasksTotal, TasksDone));
                            break;
                        }

                        ok = true;
                        break;

                    case 5:
                        // Счетчик
                        int Counter = 0;
                        // Ввод оценки
                        double MarkToFind = InputOutput.InputMark();
                        // Перебор элементов
                        foreach (DictionaryEntry DE in ExamsTable)
                        {
                            if ((DE.Value as Challenge).GetMark >= MarkToFind)
                            {
                                Counter++;
                            }
                        }
                        Console.WriteLine("{0} студентов получили за работу оценку не менее {1}.", Counter, MarkToFind);

                        ok = true;
                        break;

                    case 6:
                        // Ввод оценки
                        MarkToFind = InputOutput.InputMark();
                        Console.WriteLine("Студенты, получившие за работу оценку не менее {0}:", MarkToFind);
                        // Перебор элементов
                        foreach (DictionaryEntry DE in ExamsTable)
                        {
                            if ((DE.Value as Challenge).GetMark >= MarkToFind)
                            {
                                (DE.Value as Challenge).Show();
                            }
                        }

                        ok = true;
                        break;

                    case 7:
                        // Ввод оценки
                        MarkToFind = InputOutput.InputMark();
                        Console.WriteLine("Студенты, получившие за экзамен оценку не менее {0}:", MarkToFind);
                        // Перебор элементов
                        foreach (DictionaryEntry DE in ExamsTable)
                        {
                            // Если экзамен и удовлетворяет условию
                            if ((DE.Value is Exam) || (DE.Value is GraduateExam) &&
                                ((DE.Value as Challenge).GetMark >= MarkToFind))
                            {
                                (DE.Value as Challenge).Show();
                            }
                        }

                        ok = true;
                        break;

                    // Клонирование таблицы
                    case 8:
                        Hashtable ClonedTable = ExamsTable.Clone() as Hashtable;
                        foreach (DictionaryEntry DE in ClonedTable)
                        {
                            (DE.Value as Challenge).Show();
                        }
                        ok = true;
                        break;

                    // Поиск элемента по ключу
                    case 9:
                        Console.Write("Введите ключ (ФИО) элемента, который Вы хотите найти: ");
                        string KeyToFind = Console.ReadLine();
                        if (!ExamsTable.ContainsKey(KeyToFind))
                        {
                            Console.WriteLine("Элемента с таким ключом не найдено.");
                        }
                        else
                        {
                            (ExamsTable[KeyToFind] as Challenge).Show();
                        }
                        ok = true;
                        break;

                    case 10:
                        Finish = ok = true;
                        break;

                    default:
                        ok = false;
                        break;
                    }
                } while (!ok);

                if (!Finish && ok)
                {
                    Console.WriteLine("Нажмите любую клавишу...");
                    Console.ReadKey();
                }
            } while (!Finish);
        }
        public object Clone()
        {
            BlogPostExtensionData exdata =
                new BlogPostExtensionData(Guid.NewGuid().ToString(), (BlogPostSettingsBag)_settings.Clone(), _fileService, (Hashtable)_fileIds.Clone());

            exdata.RefreshCallBack = RefreshCallBack;
            exdata.ObjectState     = ObjectState;
            return(exdata);
        }
Exemple #29
0
        public static void TestClone_IsShallowCopy()
        {
            var hash = new Hashtable();
            for (int i = 0; i < 10; i++)
            {
                hash.Add(i, new Foo());
            }

            Hashtable clone = (Hashtable)hash.Clone();
            for (int i = 0; i < clone.Count; i++)
            {
                Assert.Equal("Hello World", ((Foo)clone[i]).StringValue);
                Assert.Same(hash[i], clone[i]);
            }

            // Change object in original hashtable
            ((Foo)hash[1]).StringValue = "Goodbye";
            Assert.Equal("Goodbye", ((Foo)clone[1]).StringValue);

            // Removing an object from the original hashtable doesn't change the clone
            hash.Remove(0);
            Assert.True(clone.Contains(0));
        }
        public void TestGetSyncRootBasic()
        {
            Hashtable arrSon;
            Hashtable arrMother;

            Task[]                workers;
            Action                ts1;
            Action                ts2;
            Int32                 iNumberOfWorkers = 30;
            Hashtable             hshPossibleValues;
            IDictionaryEnumerator idic;

            Hashtable hsh1;
            Hashtable hsh2;
            Hashtable hsh3;

            //[] we will create different HT and make sure that they return different SyncRoot values
            hsh1 = new Hashtable();
            hsh2 = new Hashtable();

            Assert.NotEqual(hsh1.SyncRoot, hsh2.SyncRoot);
            Assert.Equal(hsh1.SyncRoot.GetType(), typeof(object));

            //[] a clone of a Syncronized HT should not be pointing to the same SyncRoot
            hsh1 = new Hashtable();
            hsh2 = Hashtable.Synchronized(hsh1);
            hsh3 = (Hashtable)hsh2.Clone();

            Assert.NotEqual(hsh2.SyncRoot, hsh3.SyncRoot);

            Assert.NotEqual(hsh1.SyncRoot, hsh3.SyncRoot);

            //[] testing SyncRoot is not as simple as its implementation looks like. This is the working
            //scenrio we have in mind.
            //1) Create your Down to earth mother Hashtable
            //2) Get a synchronized wrapper from it
            //3) Get a Synchronized wrapper from 2)
            //4) Get a synchronized wrapper of the mother from 1)
            //5) all of these should SyncRoot to the mother earth

            arrMother = new Hashtable();
            for (int i = 0; i < _iNumberOfElements; i++)
            {
                arrMother.Add("Key_" + i, "Value_" + i);
            }

            arrSon            = Hashtable.Synchronized(arrMother);
            _arrGrandDaughter = Hashtable.Synchronized(arrSon);
            _arrDaughter      = Hashtable.Synchronized(arrMother);

            Assert.Equal(arrSon.SyncRoot, arrMother.SyncRoot);
            Assert.Equal(arrSon.SyncRoot, arrMother.SyncRoot);
            Assert.Equal(_arrGrandDaughter.SyncRoot, arrMother.SyncRoot);
            Assert.Equal(_arrDaughter.SyncRoot, arrMother.SyncRoot);
            Assert.Equal(arrSon.SyncRoot, arrMother.SyncRoot);

            //we are going to rumble with the Hashtables with some threads
            workers = new Task[iNumberOfWorkers];
            ts2     = new Action(RemoveElements);
            for (int iThreads = 0; iThreads < iNumberOfWorkers; iThreads += 2)
            {
                var name = "Thread_worker_" + iThreads;
                ts1 = new Action(() => AddMoreElements(name));

                workers[iThreads]     = Task.Run(ts1);
                workers[iThreads + 1] = Task.Run(ts2);
            }

            Task.WaitAll(workers);

            //checking time
            //Now lets see how this is done.
            //Either there should be some elements (the new ones we added and/or the original ones) or none
            hshPossibleValues = new Hashtable();
            for (int i = 0; i < _iNumberOfElements; i++)
            {
                hshPossibleValues.Add("Key_" + i, "Value_" + i);
            }

            for (int i = 0; i < iNumberOfWorkers; i++)
            {
                hshPossibleValues.Add("Key_Thread_worker_" + i, "Thread_worker_" + i);
            }

            idic = arrMother.GetEnumerator();

            while (idic.MoveNext())
            {
                Assert.True(hshPossibleValues.ContainsKey(idic.Key), "Error, Expected value not returned, " + idic.Key);
                Assert.True(hshPossibleValues.ContainsValue(idic.Value), "Error, Expected value not returned, " + idic.Value);
            }
        }
    /// <summary>
    /// Shows correct properties according to the settings.
    /// </summary>
    private void ShowProperties()
    {
        this.Properties.Config = this.Config;

        // Save session data before shoving properties
        Hashtable dialogParameters = SessionHelper.GetValue("DialogSelectedParameters") as Hashtable;

        if (dialogParameters != null)
        {
            dialogParameters = (Hashtable)dialogParameters.Clone();
        }

        DisplayProperties();

        MediaItem mi = new MediaItem();

        mi.Url = this.txtUrl.Text;
        if (this.mWidth > 0)
        {
            mi.Width = this.mWidth;
        }
        if (this.mHeight > 0)
        {
            mi.Height = this.mHeight;
        }

        // Try get source type from URL extension
        string ext   = null;
        int    index = this.txtUrl.Text.LastIndexOf('.');

        if (index > 0)
        {
            ext = this.txtUrl.Text.Substring(index);
        }

        if (this.Config.OutputFormat == OutputFormatEnum.HTMLMedia)
        {
            switch (this.drpMediaType.SelectedValue)
            {
            case "image":
                this.propMedia.ViewMode = MediaTypeEnum.Image;
                mi.Extension            = String.IsNullOrEmpty(ext) ? "jpg" : ext;
                break;

            case "av":
                this.propMedia.ViewMode = MediaTypeEnum.AudioVideo;
                mi.Extension            = String.IsNullOrEmpty(ext) ? "avi" : ext;
                break;

            case "flash":
                this.propMedia.ViewMode = MediaTypeEnum.Flash;
                mi.Extension            = String.IsNullOrEmpty(ext) ? "swf" : ext;
                break;

            default:
                this.plcHTMLMediaProp.Visible = false;
                break;
            }
            if (URLHelper.IsPostback())
            {
                this.Properties.LoadSelectedItems(mi, dialogParameters);
            }
        }
        else if ((this.Config.OutputFormat == OutputFormatEnum.BBMedia) && (URLHelper.IsPostback()))
        {
            mi.Extension = String.IsNullOrEmpty(ext) ? "jpg" : ext;
            this.Properties.LoadSelectedItems(mi, dialogParameters);
        }
        else if ((this.Config.OutputFormat == OutputFormatEnum.URL) && (URLHelper.IsPostback()))
        {
            this.Properties.LoadSelectedItems(mi, dialogParameters);
        }
        // Set saved session data back into session
        if (dialogParameters != null)
        {
            SessionHelper.SetValue("DialogSelectedParameters", dialogParameters);
        }
    }
Exemple #32
0
        public void TestCanCastClonedHashtableToInterfaces()
        {
            ICollection icol1;
            IDictionary idic1;
            Hashtable iclone1;

            //[]we try to cast the returned object from Clone() to different types
            var hsh1 = new Hashtable();

            icol1 = (ICollection)hsh1.Clone();
            Assert.Equal(hsh1.Count, icol1.Count);

            idic1 = (IDictionary)hsh1.Clone();
            Assert.Equal(hsh1.Count, idic1.Count);

            iclone1 = (Hashtable)hsh1.Clone();
            Assert.Equal(hsh1.Count, iclone1.Count);
        }
Exemple #33
0
        private static void WritePairs(Hashtable pairs, string path, bool includeFonts)
        {
            if (includeFonts)
            {
                pairs = (Hashtable)pairs.Clone();

                // HACK: hard-code invariant font resource values
                pairs.Add("Font", new Values("Segoe UI", "The font to be used to render all text in the product in Windows Vista and later. DO NOT specify more than one font!"));
                pairs.Add("Font.Size.Normal", new Values("9", "The default font size used throughout the product in Windows Vista and later"));
                pairs.Add("Font.Size.Large", new Values("10", "The size of titles in some error dialogs in Windows Vista and later"));
                pairs.Add("Font.Size.XLarge", new Values("11", "The size of titles in some error dialogs in Windows Vista and later.  Also used for the text that shows an error on the video publish place holder."));
                pairs.Add("Font.Size.XXLarge", new Values("12", "The size of panel titles in the Preferences dialog in Windows Vista and later.  Also the size of the text used to show the status on the video before publish."));
                pairs.Add("Font.Size.Heading", new Values("12", "The size of the header text in the Add Weblog wizard and Welcome wizard in Windows Vista and later"));
                pairs.Add("Font.Size.GiantHeading", new Values("15.75", "The size of the header text in the Add Weblog wizard and Welcome wizard in Windows Vista and later"));
                pairs.Add("Font.Size.ToolbarFormatButton", new Values("15", "The size of the font used to draw the edit toolbar's B(old), I(talic), U(nderline), and S(trikethrough) in Windows Vista and later. THIS SIZE IS IN PIXELS, NOT POINTS! Example: 14.75"));
                pairs.Add("Font.Size.PostSplitCaption", new Values("7", "The size of the font used to draw the 'More...' divider when using the Format | Split Post feature in Windows Vista and later."));
                pairs.Add("Font.Size.Small", new Values("7", "The size used for small messages, such as please respect copyright, in Windows Vista and later.  "));

                // HACK: hard-code default sidebar size
                pairs.Add("Sidebar.WidthInPixels", new Values("200", "The width of the sidebar, in pixels."));

                // HACK: hard-code wizard height
                pairs.Add("ConfigurationWizard.Height", new Values("380", "The height of the configuration wizard, in pixels."));
            }

            pairs.Add("Culture.UseItalics", new Values("True", "Whether or not the language uses italics"));

            ArrayList keys = new ArrayList(pairs.Keys);

            keys.Sort(new CaseInsensitiveComparer(CultureInfo.InvariantCulture));

            //using (TextWriter tw = new StreamWriter(path, false))
            StringBuilder xmlBuffer = new StringBuilder();

            using (TextWriter tw = new StringWriter(xmlBuffer))
            {
                ResXResourceWriter writer = new ResXResourceWriter(tw);
                foreach (string key in keys)
                {
                    writer.AddResource(key, ((Values)pairs[key]).Val);
                }
                writer.Close();
            }

            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(xmlBuffer.ToString());
            foreach (XmlElement dataNode in xmlDoc.SelectNodes("/root/data"))
            {
                string name = dataNode.GetAttribute("name");
                if (pairs.ContainsKey(name))
                {
                    string comment = ((Values)pairs[name]).Comment;
                    if (comment != null && comment.Length > 0)
                    {
                        XmlElement commentEl = xmlDoc.CreateElement("comment");
                        XmlText    text      = xmlDoc.CreateTextNode(comment);
                        commentEl.AppendChild(text);
                        dataNode.AppendChild(commentEl);
                    }
                }
            }
            xmlDoc.Save(path);
        }
Exemple #34
0
        public void TestClonedHashtableSameAsOriginal()
        {
            string strKey;
            string strValue;

            //1) create a HT, add elements
            //2) create another HT out of the first
            //3) Remove elements from 2) and add
            //4) Clone 3)
            var hsh1 = new Hashtable();
            for (int i = 0; i < 10; i++)
            {
                strKey = "Key_" + i;
                strValue = "string_" + i;
                hsh1.Add(strKey, strValue);
            }

            var hsh2 = new Hashtable(hsh1);
            hsh2.Remove("Key_0");
            hsh2.Remove("Key_1");
            hsh2.Remove("Key_2");

            Assert.Equal(hsh2.Count, 7);
            hsh2["Key_10"] = "string_10";
            hsh2["Key_11"] = "string_11";
            hsh2["Key_12"] = "string_12";

            var hsh3 = (Hashtable)hsh2.Clone();

            Assert.Equal(10, hsh3.Count);

            for (int i = 3; i < 13; i++)
            {
                Assert.True(hsh3.Contains("Key_" + i));
                Assert.True(hsh3.ContainsKey("Key_" + i));
                Assert.True(hsh3.ContainsValue("string_" + i));
            }
        }
Exemple #35
0
        public static void buildIndex(CheckedListBox.ObjectCollection sharedFoldersList, BackgroundWorker indexWorker, DoWorkEventArgs e)
        {
            Utils.writeLog("buildIndex: Started indexing!");

            int  numFoldersIndexed = 0;
            bool newFile           = false;

            DateTime timeOfLastSave = DateTime.Now; //Keeps track of when to persist stuff in the middle of indexing

            List <string> folders = new List <string>();

            foreach (string sharedFolderPath in sharedFoldersList)
            {
                folders.Add(sharedFolderPath);
            }

            /* INDEXING
             * --------
             *
             * The idea is to maintain add/remove lists accurately until a successful sync
             * occurs. At this point we will nullify add/remove list and update fileIndex.
             *
             * Add/remove lists:
             * It turns out that determining removed files is super-fast, because there is
             * no hash computation involved. The most accurate time to get the list of
             * removed files is after the computationally-expensive add list is computed.
             *
             * So what we do is:
             * 1. Compare against updatedIndex to determine added files - if new, add to
             *    updatedIndex and addedFiles. If old, do nothing.
             * 2. After all adds we have an updatedIndex with some removed files as well
             * 3. Every so often, write everything to disk so that we can pick up where we
             *    left off.
             * 4. So then we compute removed files by checking against updatedIndex. If
             *    removed, remove from updatedIndex and add to removedFiles
             * 5. Attempt to sync, if successful nullify add/remove and fileIndex=updated
             *    FileIndex
             *
             */

            while (folders.Count > 0)
            {
                // Persist data from time to time so that we can eventually index very large sets
                if ((DateTime.Now - timeOfLastSave).TotalMinutes > 2)
                {
                    Utils.writeLog("buildIndex : Time exceeded 2 minutes, writing indices to disk..");
                    serializeHashTables();
                    timeOfLastSave = DateTime.Now;
                }

                DirectoryInfo   di               = new DirectoryInfo(folders[0]);
                FileInfo[]      fileInfoArr      = null;
                DirectoryInfo[] directoryInfoArr = null;
                try
                {
                    fileInfoArr      = di.GetFiles();
                    directoryInfoArr = di.GetDirectories();
                }
                catch (Exception u)
                {
                    folders.RemoveAt(0);
                    Utils.writeLog("ERROR! buildIndex: Exception while indexing " + di.FullName + " Error: " + u);
                    continue;
                }

                // Add all the sub folders to the processing queue
                if (directoryInfoArr != null)
                {
                    foreach (DirectoryInfo currentDirectory in directoryInfoArr)
                    {
                        folders.Add(currentDirectory.FullName);
                    }
                }

                if (fileInfoArr != null)
                {
                    foreach (FileInfo fi in fileInfoArr)
                    {
                        if (modifiedIndex.ContainsKey(fi.FullName))
                        {
                            // If file has not been modified, it's already in updatedIndex
                            if ((DateTime)modifiedIndex[fi.FullName] == fi.LastWriteTime)
                            {
                                //Utils.writeLog("buildIndex: Old file not modified : " + fi.FullName);
                                continue;
                            }
                            else
                            {
                                Utils.writeLog("buildIndex: Old file modified : " + fi.FullName);
                            }
                        }
                        else
                        {
                            newFile = true;
                        }

                        // Get file details, including hash and keywords
                        LocalFile currentFile = getFileInfo(fi.FullName);

                        if (currentFile == null)
                        {
                            //Utils.writeLog("buildIndex: Didn't process file :" + fi.FullName);
                            continue;
                        }

                        if (newFile)
                        {
                            Utils.writeLog("buildIndex: New file seen : " + fi.FullName);
                        }

                        newFile = false;

                        hashIndex[fi.FullName]     = currentFile.hash;
                        modifiedIndex[fi.FullName] = fi.LastWriteTime;

                        addedFiles[currentFile.hash]   = currentFile;
                        updatedIndex[currentFile.hash] = currentFile;

                        if (indexWorker.CancellationPending)
                        {
                            e.Cancel = true;
                            Utils.writeLog("buildIndex: Cancelled indexing. All changes lost.");
                            return;
                        }
                    }

                    folders.Remove(folders[0]);
                    numFoldersIndexed++;
                }
            }

            // Addition is complete, now check for removed files..
            Utils.writeLog("buildIndex: File addition complete..");

            removedFiles = (Hashtable)fileIndex.Clone();

            foreach (string sharedFolderPath in sharedFoldersList)
            {
                folders.Add(sharedFolderPath);
            }

            while (folders.Count > 0)
            {
                DirectoryInfo   di               = new DirectoryInfo(folders[0]);
                FileInfo[]      fileInfoArr      = null;
                DirectoryInfo[] directoryInfoArr = null;
                try
                {
                    fileInfoArr      = di.GetFiles();
                    directoryInfoArr = di.GetDirectories();
                }
                catch (Exception u)
                {
                    folders.RemoveAt(0);
                    Utils.writeLog("ERROR! buildIndex: Exception while indexing " + di.FullName + " Error: " + u);
                    continue;
                }

                // Add all the sub folders to the processing queue
                if (directoryInfoArr != null)
                {
                    foreach (DirectoryInfo currentDirectory in directoryInfoArr)
                    {
                        folders.Add(currentDirectory.FullName);
                    }
                }

                if (fileInfoArr != null)
                {
                    foreach (FileInfo fi in fileInfoArr)
                    {
                        // If file hash was found in hashIndex, remove from removedFiles
                        if (hashIndex.ContainsKey(fi.FullName) && updatedIndex.ContainsKey(hashIndex[fi.FullName]))
                        {
                            removedFiles.Remove(hashIndex[fi.FullName]);
                        }
                    }
                    folders.Remove(folders[0]);
                }
            }

            // At this point removedFiles contains list of files in the index that don't
            // correspond to any files on disk..

            // Make sure removed files are gone from the appropriate places
            foreach (String key in removedFiles.Keys)
            {
                String path = ((LocalFile)removedFiles[key]).location;
                Utils.writeLog("buildIndex: Removed file : " + path);

                if (addedFiles.ContainsKey(key))
                {
                    addedFiles.Remove(key);
                }

                if (updatedIndex.ContainsKey(key))
                {
                    Utils.writeLog("buildIndex: Found out-of-date key in updatedIndex");
                    updatedIndex.Remove(key);
                }

                if (modifiedIndex.ContainsKey(path))
                {
                    modifiedIndex.Remove(path);
                }
            }

            Utils.writeLog("buildIndex: " + removedFiles.Keys.Count + " files removed");
            Utils.writeLog("buildIndex: " + addedFiles.Keys.Count + " files added");

            serializeHashTables();
            Utils.writeLog("buildIndex: Completed indexing of " + numFoldersIndexed + " folders.");
        }
 private SettingsPropertyCollection(Hashtable h)
 {
     _hashtable = (Hashtable)h.Clone();
 }
Exemple #37
0
 public WaitForSeconds From(System.Object obj, float duration, Hashtable _properties)
 {
     Hashtable properties = (Hashtable)_properties.Clone();
     Hashtable options = ExtractOptions(ref properties);
     CreateAnimations(obj, properties, duration, options, AniType.From);
     return new WaitForSeconds(duration);
 }
    /// <summary>
    /// Loads selected item parameters into the selector.
    /// </summary>
    /// <param name="properties">Name-value collection representing item to load</param>
    public void LoadSelectedItem(Hashtable properties)
    {
        if ((properties != null) && (properties.Count > 0))
        {
            Hashtable temp = (Hashtable)properties.Clone();

            if ((properties[DialogParameters.AV_URL] != null) && ((properties[DialogParameters.LAST_TYPE] == null) || ((MediaTypeEnum)properties[DialogParameters.LAST_TYPE] == MediaTypeEnum.AudioVideo)))
            {
                drpMediaType.SelectedValue = "av";
                txtUrl.Text = properties[DialogParameters.AV_URL].ToString();
            }
            else if ((properties[DialogParameters.FLASH_URL] != null) && ((properties[DialogParameters.LAST_TYPE] == null) || ((MediaTypeEnum)properties[DialogParameters.LAST_TYPE] == MediaTypeEnum.Flash)))
            {
                drpMediaType.SelectedValue = "flash";
                txtUrl.Text = properties[DialogParameters.FLASH_URL].ToString();
            }
            else if ((properties[DialogParameters.IMG_URL] != null) && ((properties[DialogParameters.LAST_TYPE] == null) || ((MediaTypeEnum)properties[DialogParameters.LAST_TYPE] == MediaTypeEnum.Image)))
            {
                drpMediaType.SelectedValue = "image";

                /*int width = ValidationHelper.GetInteger(temp[DialogParameters.IMG_WIDTH], 0);
                int height = ValidationHelper.GetInteger(temp[DialogParameters.IMG_HEIGHT], 0);

                int originalWidth = ValidationHelper.GetInteger(temp[DialogParameters.IMG_ORIGINALWIDTH], 0);
                int originalHeight = ValidationHelper.GetInteger(temp[DialogParameters.IMG_ORIGINALHEIGHT], 0);*/
                // Update URL
                string url = ValidationHelper.GetString(properties[DialogParameters.IMG_URL], "");
                txtUrl.Text = url;
            }
            else if ((properties[DialogParameters.URL_URL] != null) && ((properties[DialogParameters.LAST_TYPE] == null) || ((MediaTypeEnum)properties[DialogParameters.LAST_TYPE] == MediaTypeEnum.Unknown)))
            {
                txtUrl.Text = properties[DialogParameters.URL_URL].ToString();
            }
            if (!String.IsNullOrEmpty(txtUrl.Text))
            {
                ShowProperties();
                // Load temp properties because ShowProperties() change original properties
                Properties.LoadItemProperties(temp);
            }
        }
    }
Exemple #39
0
        public ActionResult Add(Td_Sk_1 model)
        {
            BaseResult br = new BaseResult();

            var oldParam = new Hashtable();


            try
            {
                #region 获取参数
                Hashtable param = base.GetParameters();

                ParamVessel p = new ParamVessel();
                p.Add("skList", string.Empty, HandleType.ReturnMsg);                       //skList
                p.Add("flag_sklx", (int)Enums.FlagSKLX.YingShou, HandleType.DefaultValue); //收款类型
                p.Add("remark", string.Empty, HandleType.DefaultValue);                    //备注
                p.Add("id_kh", string.Empty, HandleType.ReturnMsg);                        //id_kh
                p.Add("id_shop", string.Empty, HandleType.ReturnMsg);                      //id_shop
                p.Add("id_jbr", string.Empty, HandleType.ReturnMsg);                       //id_jbr
                p.Add("dh", string.Empty, HandleType.ReturnMsg);                           //dh
                p.Add("rq", string.Empty, HandleType.ReturnMsg);                           //rq
                p.Add("type", string.Empty, HandleType.Remove);                            //type
                p.Add("id", string.Empty, HandleType.Remove);                              //id
                p.Add("je_pre", string.Empty, HandleType.DefaultValue);                    //je_pre
                param = param.Trim(p);
                param.Add("id_masteruser", id_user_master);
                param.Add("id_user", id_user);
                oldParam = (Hashtable)param.Clone();
                #endregion

                List <Td_Sk_2> skList = JSON.Deserialize <List <Td_Sk_2> >(param["skList"].ToString()) ?? new List <Td_Sk_2>();

                #region 验证数据
                if (param["flag_sklx"].ToString() == ((int)Enums.FlagSKLX.YingShou).ToString() && (skList == null || skList.Count() <= 0))
                {
                    br.Success = false;
                    br.Message.Add("类型为应收款时收款体不能为空!");
                    WriteDBLog("收款-Post新增/编辑", oldParam, br);
                    return(base.JsonString(new
                    {
                        status = "error",
                        message = string.Join(";", br.Message)
                    }));
                }

                if (string.IsNullOrEmpty(param["je_pre"].ToString()) || !CyVerify.IsNumeric(param["je_pre"].ToString()))
                {
                    br.Success = false;
                    br.Message.Add("收支金额不符合要求!");
                    WriteDBLog("收款-Post新增/编辑", oldParam, br);
                    return(base.JsonString(new
                    {
                        status = "error",
                        message = string.Join(";", br.Message)
                    }));
                }

                foreach (var item in skList)
                {
                    #region 收款体参数验证
                    if (item.je_origin == null ||
                        item.je_ws == null ||
                        item.je_ys == null ||
                        item.je_sk == null
                        )
                    {
                        br.Success = false;
                        br.Message.Add("必要金额不能为空 请重新刷新页面!");
                        WriteDBLog("收款-Post新增/编辑", oldParam, br);
                        return(base.JsonString(new
                        {
                            status = "error",
                            message = string.Join(";", br.Message)
                        }));
                    }



                    if (item.je_ws + item.je_ys != item.je_origin)
                    {
                        br.Success = false;
                        br.Message.Add("已收金额 + 未付金额不等于原单总金额 请重新刷新页面!");
                        WriteDBLog("收款-Post新增/编辑", oldParam, br);
                        return(base.JsonString(new
                        {
                            status = "error",
                            message = string.Join(";", br.Message)
                        }));
                    }

                    if (item.je_sk + item.je_yh > item.je_ws)
                    {
                        br.Success = false;
                        br.Message.Add("优惠金额 + 本次收款金额不能超过未收款金额!");
                        WriteDBLog("收款-Post新增/编辑", oldParam, br);
                        return(base.JsonString(new
                        {
                            status = "error",
                            message = string.Join(";", br.Message)
                        }));
                    }
                    #endregion
                }

                var digitHashtable = GetParm();

                param.Remove("skList");
                param.Add("skList", skList);
                param.Add("DigitHashtable", digitHashtable);
                param.Add("autoAudit", AutoAudit());
                #endregion

                if (param.ContainsKey("type") && param["type"].ToString() == "edit")
                {
                    //插入表
                    br = BusinessFactory.Td_Sk_1.Update(param);
                    WriteDBLog("收款-Post编辑", oldParam, br);
                }
                else
                {
                    //插入表
                    br = BusinessFactory.Td_Sk_1.Add(param);
                    WriteDBLog("收款-Post新增", oldParam, br);
                }


                if (br.Success)
                {
                    return(base.JsonString(new
                    {
                        status = "success",
                        message = string.Join(";", br.Message)
                    }));
                }
                else
                {
                    return(base.JsonString(br, 1));
                }
            }
            catch (CySoftException ex)
            {
                br.Success = false;
                br.Data    = "";
                br.Message.Add(ex.Message);
                br.Level = ErrorLevel.Warning;
                WriteDBLog("收款-Post新增/编辑", oldParam, br);
                return(base.JsonString(new
                {
                    status = "error",
                    message = string.Join(";", br.Message)
                }));
            }
            catch (Exception ex)
            {
                br.Success = false;
                br.Data    = "";
                br.Message.Add("数据不符合要求_e!");
                br.Level = ErrorLevel.Warning;
                WriteDBLog("收款-Post新增/编辑", oldParam, br);
                return(base.JsonString(new
                {
                    status = "error",
                    message = string.Join(";", br.Message)
                }));
            }
        }
Exemple #40
0
        public void TestSyncRoot()
        {
            // Different hashtables have different SyncRoots
            var hash1 = new Hashtable();
            var hash2 = new Hashtable();

            Assert.NotEqual(hash1.SyncRoot, hash2.SyncRoot);
            Assert.Equal(hash1.SyncRoot.GetType(), typeof(object));

            // Cloned hashtables have different SyncRoots
            hash1 = new Hashtable();
            hash2 = Hashtable.Synchronized(hash1);
            Hashtable hash3 = (Hashtable)hash2.Clone();

            Assert.NotEqual(hash2.SyncRoot, hash3.SyncRoot);
            Assert.NotEqual(hash1.SyncRoot, hash3.SyncRoot);

            // Testing SyncRoot is not as simple as its implementation looks like. This is the working
            // scenrio we have in mind.
            // 1) Create your Down to earth mother Hashtable
            // 2) Get a synchronized wrapper from it
            // 3) Get a Synchronized wrapper from 2)
            // 4) Get a synchronized wrapper of the mother from 1)
            // 5) all of these should SyncRoot to the mother earth

            var hashMother = new Hashtable();
            for (int i = 0; i < _iNumberOfElements; i++)
            {
                hashMother.Add("Key_" + i, "Value_" + i);
            }

            Hashtable hashSon = Hashtable.Synchronized(hashMother);
            _hashGrandDaughter = Hashtable.Synchronized(hashSon);
            _hashDaughter = Hashtable.Synchronized(hashMother);

            Assert.Equal(hashSon.SyncRoot, hashMother.SyncRoot);
            Assert.Equal(hashSon.SyncRoot, hashMother.SyncRoot);
            Assert.Equal(_hashGrandDaughter.SyncRoot, hashMother.SyncRoot);
            Assert.Equal(_hashDaughter.SyncRoot, hashMother.SyncRoot);
            Assert.Equal(hashSon.SyncRoot, hashMother.SyncRoot);

            // We are going to rumble with the Hashtables with some threads
            int iNumberOfWorkers = 30;
            var workers = new Task[iNumberOfWorkers];
            var ts2 = new Action(RemoveElements);
            for (int iThreads = 0; iThreads < iNumberOfWorkers; iThreads += 2)
            {
                var name = "Thread_worker_" + iThreads;
                var ts1 = new Action(() => AddMoreElements(name));

                workers[iThreads] = Task.Run(ts1);
                workers[iThreads + 1] = Task.Run(ts2);
            }

            Task.WaitAll(workers);

            // Check:
            // Either there should be some elements (the new ones we added and/or the original ones) or none
            var hshPossibleValues = new Hashtable();
            for (int i = 0; i < _iNumberOfElements; i++)
            {
                hshPossibleValues.Add("Key_" + i, "Value_" + i);
            }

            for (int i = 0; i < iNumberOfWorkers; i++)
            {
                hshPossibleValues.Add("Key_Thread_worker_" + i, "Thread_worker_" + i);
            }

            IDictionaryEnumerator idic = hashMother.GetEnumerator();

            while (idic.MoveNext())
            {
                Assert.True(hshPossibleValues.ContainsKey(idic.Key));
                Assert.True(hshPossibleValues.ContainsValue(idic.Value));
            }
        }
Exemple #41
0
        static public string CreatePropertiesXml2(IDictionary properties, int indent, bool format)
        {
            IDictionaryEnumerator it        = properties.GetEnumerator();
            StringBuilder         returnStr = new StringBuilder(8096);
            StringBuilder         nestedStr = new StringBuilder(8096);

            string preStr = format ? "".PadRight(indent * 2) : "";
            string endStr = format ? "\n" : "";

            while (it.MoveNext())
            {
                DictionaryEntry pair = (DictionaryEntry)it.Current;

                string keyName    = pair.Key as String;
                string attributes = "";
                string cacheName  = "";

                if (pair.Value is Hashtable)
                {
                    Hashtable subproperties = (Hashtable)pair.Value;

                    //if (keyName == "cluster" && OnConfigUpdated != null)
                    //{
                    //    OnConfigUpdated(subproperties["group-id"].ToString(), pair);
                    //}
                    if (subproperties.Contains("type") && subproperties.Contains("name"))
                    {
                        cacheName = subproperties["name"] as string;
                        keyName   = (string)subproperties["type"];

                        subproperties = (Hashtable)subproperties.Clone();
                        subproperties.Remove("type");
                    }

                    nestedStr.Append(preStr).Append("<" + keyName + BuildAttributes(subproperties));
                    if (subproperties.Count == 0)
                    {
                        nestedStr.Append("/>").Append(endStr);
                    }
                    else
                    {
                        if (subproperties.Count == 1)
                        {
                            IDictionaryEnumerator ide = subproperties.GetEnumerator();
                            while (ide.MoveNext())
                            {
                                if (((string)ide.Key).ToLower().CompareTo(cacheName) == 0 && ide.Value is IDictionary)
                                {
                                    subproperties = ide.Value as Hashtable;
                                }
                            }
                        }
                        nestedStr.Append(">").Append(endStr);
                        nestedStr.Append(CreatePropertiesXml2(subproperties, indent + 1, format)).Append(preStr).Append("</" + keyName + ">").Append(endStr);
                    }
                }
                //else
                //{
                //    returnStr.Append(preStr).Append("<" + keyName + ">").Append(pair.Value).Append("</" + keyName + ">").Append(endStr);
                //}
            }
            returnStr.Append(nestedStr.ToString());

            return(returnStr.ToString());
        }
    /// <summary>
    /// Loads selected properties into the child controls and ensures displaying correct values.
    /// </summary>
    /// <param name="properties">Properties collection</param>
    public override void LoadProperties(Hashtable properties)
    {
        if (properties != null)
        {
            if (properties[DialogParameters.LAST_TYPE] != null)
            {
                // Setup view mode if necessary
                Hashtable temp = (Hashtable)properties.Clone();
                ViewMode = (MediaTypeEnum)properties[DialogParameters.LAST_TYPE];
                properties = temp;
            }

            // Display the properties
            pnlEmpty.Visible = false;
            pnlTabs.CssClass = "Dialog_Tabs";

            if ((properties[DialogParameters.LAST_TYPE] == null) || ((MediaTypeEnum)properties[DialogParameters.LAST_TYPE] == MediaTypeEnum.Image))
            {
                #region "Image general tab"

                int width = ValidationHelper.GetInteger(properties[DialogParameters.IMG_WIDTH], 0);
                int height = ValidationHelper.GetInteger(properties[DialogParameters.IMG_HEIGHT], 0);

                OriginalWidth = ValidationHelper.GetInteger(properties[DialogParameters.IMG_ORIGINALWIDTH], 0);
                OriginalHeight = ValidationHelper.GetInteger(properties[DialogParameters.IMG_ORIGINALHEIGHT], 0);

                string url = ValidationHelper.GetString(properties[DialogParameters.IMG_URL], "");

                // Image URL is missing, look at A/V/F URLs in case that item was inserted from the Web tab with manually selected media type
                if (url == "")
                {
                    url = ValidationHelper.GetString(properties[DialogParameters.AV_URL], "");
                    if (url == "")
                    {
                        url = ValidationHelper.GetString(properties[DialogParameters.FLASH_URL], "");
                        if (url == "")
                        {
                            url = ValidationHelper.GetString(properties[DialogParameters.URL_URL], "");
                            width = ValidationHelper.GetInteger(properties[DialogParameters.URL_WIDTH], 0);
                            height = ValidationHelper.GetInteger(properties[DialogParameters.URL_HEIGHT], 0);
                        }
                        else
                        {
                            width = ValidationHelper.GetInteger(properties[DialogParameters.FLASH_WIDTH], 0);
                            height = ValidationHelper.GetInteger(properties[DialogParameters.FLASH_HEIGHT], 0);
                        }
                    }
                    else
                    {
                        width = ValidationHelper.GetInteger(properties[DialogParameters.AV_WIDTH], 0);
                        height = ValidationHelper.GetInteger(properties[DialogParameters.AV_HEIGHT], 0);
                    }
                    properties[DialogParameters.IMG_EXT] = ValidationHelper.GetString(properties[DialogParameters.URL_EXT], "");
                }
                else
                {
                    OriginalUrl = url;
                }
                url = CMSDialogHelper.UpdateUrl(width, height, OriginalWidth, OriginalHeight, url, SourceType);

                string imgLink = ValidationHelper.GetString(properties[DialogParameters.IMG_LINK], "");
                string imgTarget = ValidationHelper.GetString(properties[DialogParameters.IMG_TARGET], "");
                string imgBehavior = ValidationHelper.GetString(properties[DialogParameters.IMG_BEHAVIOR], "");

                bool isLink = false;
                if (!String.IsNullOrEmpty(imgLink))
                {
                    if (imgBehavior == "hover")
                    {
                        isLink = true;
                    }
                    else
                    {
                        isLink = CMSDialogHelper.IsImageLink(url, imgLink, OriginalWidth, OriginalHeight, imgTarget);
                    }
                }

                if (tabImageGeneral.Visible)
                {
                    string color = ValidationHelper.GetString(properties[DialogParameters.IMG_BORDERCOLOR], "");
                    string alt = ValidationHelper.GetString(properties[DialogParameters.IMG_ALT], "");
                    string align = ValidationHelper.GetString(properties[DialogParameters.IMG_ALIGN], "");
                    int border = -1;
                    if (properties[DialogParameters.IMG_BORDERWIDTH] != null)
                    {
                        // Remove 'px' from definition of border width
                        border = ValidationHelper.GetInteger(properties[DialogParameters.IMG_BORDERWIDTH].ToString().Replace("px", ""), -1);
                    }
                    int hspace = -1;
                    if (properties[DialogParameters.IMG_HSPACE] != null)
                    {
                        // Remove 'px' from definition of hspace
                        hspace = ValidationHelper.GetInteger(properties[DialogParameters.IMG_HSPACE].ToString().Replace("px", ""), -1);
                    }
                    int vspace = -1;
                    if (properties[DialogParameters.IMG_VSPACE] != null)
                    {
                        // Remove 'px' from definition of vspace
                        vspace = ValidationHelper.GetInteger(properties[DialogParameters.IMG_VSPACE].ToString().Replace("px", ""), -1);
                    }

                    DefaultWidth = OriginalWidth;
                    DefaultHeight = OriginalHeight;

                    widthHeightElem.Width = width;
                    widthHeightElem.Height = height;
                    txtAlt.Text = HttpUtility.HtmlDecode(alt);
                    colorElem.SelectedColor = color;
                    txtBorderWidth.Text = (border < 0 ? "" : border.ToString());
                    txtHSpace.Text = (hspace < 0 ? "" : hspace.ToString());
                    txtVSpace.Text = (vspace < 0 ? "" : vspace.ToString());

                    CurrentUrl = URLHelper.ResolveUrl(url);

                    // Initialize media file URLs
                    if (SourceType == MediaSourceEnum.MediaLibraries)
                    {
                        OriginalUrl = (string.IsNullOrEmpty(OriginalUrl) ? ValidationHelper.GetString(properties[DialogParameters.URL_DIRECT], "") : OriginalUrl);
                        PermanentUrl = (string.IsNullOrEmpty(PermanentUrl) ? ValidationHelper.GetString(properties[DialogParameters.URL_PERMANENT], "") : PermanentUrl);
                    }

                    ListItem li = drpAlign.Items.FindByValue(align);
                    if (li != null)
                    {
                        drpAlign.ClearSelection();
                        li.Selected = true;
                    }

                    ViewState[DialogParameters.IMG_EXT] = ValidationHelper.GetString(properties[DialogParameters.IMG_EXT], "");
                    ViewState[DialogParameters.IMG_SIZETOURL] = ValidationHelper.GetBoolean(properties[DialogParameters.IMG_SIZETOURL], false);
                    ViewState[DialogParameters.IMG_DIR] = ValidationHelper.GetString(properties[DialogParameters.IMG_DIR], "");
                    ViewState[DialogParameters.IMG_USEMAP] = ValidationHelper.GetString(properties[DialogParameters.IMG_USEMAP], "");
                    ViewState[DialogParameters.IMG_LANG] = ValidationHelper.GetString(properties[DialogParameters.IMG_LANG], "");
                    ViewState[DialogParameters.IMG_LONGDESCRIPTION] = ValidationHelper.GetString(properties[DialogParameters.IMG_LONGDESCRIPTION], "");
                }

                #endregion

                #region "Image link tab"

                if (tabImageLink.Visible)
                {
                    if (isLink)
                    {
                        txtLinkUrl.Text = imgLink;

                        ListItem liTarget = drpLinkTarget.Items.FindByValue(imgTarget);
                        if (liTarget != null)
                        {
                            drpLinkTarget.ClearSelection();
                            liTarget.Selected = true;
                        }
                    }
                }

                #endregion

                #region "Image advanced tab"

                if (tabImageAdvanced.Visible)
                {
                    string imgId = ValidationHelper.GetString(properties[DialogParameters.IMG_ID], "");
                    string imgTooltip = ValidationHelper.GetString(properties[DialogParameters.IMG_TOOLTIP], "");
                    string imgStyleClass = ValidationHelper.GetString(properties[DialogParameters.IMG_CLASS], "");
                    string imgStyle = ValidationHelper.GetString(properties[DialogParameters.IMG_STYLE], "");

                    txtImageAdvId.Text = HttpUtility.HtmlDecode(imgId);
                    txtImageAdvTooltip.Text = HttpUtility.HtmlDecode(imgTooltip);
                    txtImageAdvClass.Text = HttpUtility.HtmlDecode(imgStyleClass);
                    txtImageAdvStyle.Text = HttpUtility.HtmlDecode(imgStyle);
                }

                #endregion

                #region "Image behavior tab"

                if (tabImageBehavior.Visible)
                {
                    if ((!isLink) || (imgBehavior == "hover"))
                    {
                        // Process target
                        string target = null;
                        if (!String.IsNullOrEmpty(imgBehavior))
                        {
                            target = imgBehavior;
                        }
                        else
                        {
                            target = imgTarget;
                        }
                        switch (target.ToLower())
                        {
                            case "_self":
                                radImageSame.Checked = true;
                                break;

                            case "_blank":
                                radImageNew.Checked = true;
                                break;

                            case "hover":
                                radImageLarger.Checked = true;
                                break;

                            default:
                                radImageNone.Checked = true;
                                break;
                        }
                    }

                    // Process behavior
                    int imgBehaviorWidth = ValidationHelper.GetInteger(properties[DialogParameters.IMG_MOUSEOVERWIDTH], 0);
                    int imgBehaviorHeight = ValidationHelper.GetInteger(properties[DialogParameters.IMG_MOUSEOVERHEIGHT], 0);
                    if (imgBehaviorWidth == 0)
                    {
                        imgBehaviorWidth = width;
                    }
                    if (imgBehaviorHeight == 0)
                    {
                        imgBehaviorHeight = height;
                    }
                    if (imgBehaviorWidth > 0)
                    {
                        imgWidthHeightElem.Width = imgBehaviorWidth;
                    }

                    if (imgBehaviorHeight > 0)
                    {
                        imgWidthHeightElem.Height = imgBehaviorHeight;
                    }

                    // Add image tag for preview
                    LoadImagePreview();
                }

                #endregion
            }

            if ((properties[DialogParameters.LAST_TYPE] == null) || ((MediaTypeEnum)properties[DialogParameters.LAST_TYPE] == MediaTypeEnum.AudioVideo))
            {
                #region "Video general tab"

                if (tabVideoGeneral.Visible)
                {
                    string vidExt = ValidationHelper.GetString(properties[DialogParameters.AV_EXT], "");

                    int vidWidth = ValidationHelper.GetInteger(properties[DialogParameters.AV_WIDTH], 300);
                    int vidHeight = ValidationHelper.GetInteger(properties[DialogParameters.AV_HEIGHT], 200);

                    bool vidAutoplay = ValidationHelper.GetBoolean(properties[DialogParameters.AV_AUTOPLAY], false);
                    bool vidLoop = ValidationHelper.GetBoolean(properties[DialogParameters.AV_LOOP], false);
                    bool vidControls = ValidationHelper.GetBoolean(properties[DialogParameters.AV_CONTROLS], true);
                    string vidUrl = ValidationHelper.GetString(properties[DialogParameters.AV_URL], "");

                    DefaultWidth = vidWidth;
                    DefaultHeight = vidHeight;

                    vidWidthHeightElem.Width = vidWidth;
                    vidWidthHeightElem.Height = vidHeight;
                    chkVidAutoPlay.Checked = vidAutoplay;
                    chkVidLoop.Checked = vidLoop;
                    chkVidShowControls.Checked = vidControls;

                    CurrentUrl = URLHelper.ResolveUrl(vidUrl);

                    // Initialize media file URLs
                    if (SourceType == MediaSourceEnum.MediaLibraries)
                    {
                        OriginalUrl = (string.IsNullOrEmpty(OriginalUrl) ? ValidationHelper.GetString(properties[DialogParameters.URL_DIRECT], "") : OriginalUrl);
                        PermanentUrl = (string.IsNullOrEmpty(PermanentUrl) ? ValidationHelper.GetString(properties[DialogParameters.URL_PERMANENT], "") : PermanentUrl);
                    }

                    ViewState[DialogParameters.AV_EXT] = vidExt;

                    LoadVideoPreview();
                }

                #endregion
            }

            if ((properties[DialogParameters.LAST_TYPE] == null) || ((MediaTypeEnum)properties[DialogParameters.LAST_TYPE] == MediaTypeEnum.Flash))
            {
                #region "Flash general tab"

                if (tabFlashGeneral.Visible)
                {

                    int flashWidth = ValidationHelper.GetInteger(properties[DialogParameters.FLASH_WIDTH], 300);
                    int flashHeight = ValidationHelper.GetInteger(properties[DialogParameters.FLASH_HEIGHT], 200);
                    bool flashAutoplay = ValidationHelper.GetBoolean(properties[DialogParameters.FLASH_AUTOPLAY], false);
                    bool flashLoop = ValidationHelper.GetBoolean(properties[DialogParameters.FLASH_LOOP], false);
                    bool flashEnableMenu = ValidationHelper.GetBoolean(properties[DialogParameters.FLASH_MENU], false);
                    string flashExt = ValidationHelper.GetString(properties[DialogParameters.FLASH_EXT], "");
                    if (String.IsNullOrEmpty(flashExt))
                    {
                        // Try to get flash extension from url if not found
                        flashExt = ValidationHelper.GetString(properties[DialogParameters.URL_EXT], "");
                    }
                    string flashUrl = ValidationHelper.GetString(properties[DialogParameters.FLASH_URL], "");

                    // Update extension in URL
                    flashUrl = URLHelper.UpdateParameterInUrl(flashUrl, "ext", "." + flashExt.TrimStart('.'));

                    DefaultWidth = flashWidth;
                    DefaultHeight = flashHeight;

                    flashWidthHeightElem.Width = flashWidth;
                    flashWidthHeightElem.Height = flashHeight;
                    chkFlashAutoplay.Checked = flashAutoplay;
                    chkFlashLoop.Checked = flashLoop;
                    chkFlashEnableMenu.Checked = flashEnableMenu;

                    CurrentUrl = URLHelper.ResolveUrl(flashUrl);

                    // Initialize media file URLs
                    if (SourceType == MediaSourceEnum.MediaLibraries)
                    {
                        OriginalUrl = (string.IsNullOrEmpty(OriginalUrl) ? ValidationHelper.GetString(properties[DialogParameters.URL_DIRECT], "") : OriginalUrl);
                        PermanentUrl = (string.IsNullOrEmpty(PermanentUrl) ? ValidationHelper.GetString(properties[DialogParameters.URL_PERMANENT], "") : PermanentUrl);
                    }

                    ViewState[DialogParameters.FLASH_EXT] = flashExt;
                }

                #endregion

                #region "Flash advanced tab"

                if (tabFlashAdvanced.Visible)
                {
                    string flashId = ValidationHelper.GetString(properties[DialogParameters.FLASH_ID], "");
                    string flashTitle = ValidationHelper.GetString(properties[DialogParameters.FLASH_TITLE], "");
                    string flashClass = ValidationHelper.GetString(properties[DialogParameters.FLASH_CLASS], "");
                    string flashStyle = ValidationHelper.GetString(properties[DialogParameters.FLASH_STYLE], "");
                    string flashScale = ValidationHelper.GetString(properties[DialogParameters.FLASH_SCALE], "");
                    string flashVars = ValidationHelper.GetString(properties[DialogParameters.FLASH_FLASHVARS], "");

                    txtFlashId.Text = HttpUtility.HtmlDecode(flashId);
                    txtFlashTitle.Text = HttpUtility.HtmlDecode(flashTitle);
                    txtFlashClass.Text = HttpUtility.HtmlDecode(flashClass);
                    txtFlashStyle.Text = HttpUtility.HtmlDecode(flashStyle);
                    txtFlashVars.Text = HttpUtility.HtmlDecode(flashVars);

                    ListItem liFlashScale = drpFlashScale.Items.FindByValue(flashScale);
                    if (liFlashScale != null)
                    {
                        drpFlashScale.ClearSelection();
                        liFlashScale.Selected = true;
                    }
                    LoadFlashPreview();
                }

                #endregion
            }

            #region "General items"

            EditorClientID = ValidationHelper.GetString(properties[DialogParameters.EDITOR_CLIENTID], "");

            #endregion
        }
    }
        public void TestGetSyncRootBasic()
        {
            Hashtable arrSon;
            Hashtable arrMother;

            Task[] workers;
            Action ts1;
            Action ts2;
            Int32 iNumberOfWorkers = 30;
            Hashtable hshPossibleValues;
            IDictionaryEnumerator idic;

            Hashtable hsh1;
            Hashtable hsh2;
            Hashtable hsh3;

            //[] we will create different HT and make sure that they return different SyncRoot values
            hsh1 = new Hashtable();
            hsh2 = new Hashtable();

            Assert.NotEqual(hsh1.SyncRoot, hsh2.SyncRoot);
            Assert.Equal(hsh1.SyncRoot.GetType(), typeof(object));

            //[] a clone of a Syncronized HT should not be pointing to the same SyncRoot
            hsh1 = new Hashtable();
            hsh2 = Hashtable.Synchronized(hsh1);
            hsh3 = (Hashtable)hsh2.Clone();

            Assert.NotEqual(hsh2.SyncRoot, hsh3.SyncRoot);

            Assert.NotEqual(hsh1.SyncRoot, hsh3.SyncRoot);

            //[] testing SyncRoot is not as simple as its implementation looks like. This is the working
            //scenrio we have in mind.
            //1) Create your Down to earth mother Hashtable
            //2) Get a synchronized wrapper from it
            //3) Get a Synchronized wrapper from 2)
            //4) Get a synchronized wrapper of the mother from 1)
            //5) all of these should SyncRoot to the mother earth

            arrMother = new Hashtable();
            for (int i = 0; i < _iNumberOfElements; i++)
            {
                arrMother.Add("Key_" + i, "Value_" + i);
            }

            arrSon = Hashtable.Synchronized(arrMother);
            _arrGrandDaughter = Hashtable.Synchronized(arrSon);
            _arrDaughter = Hashtable.Synchronized(arrMother);

            Assert.Equal(arrSon.SyncRoot, arrMother.SyncRoot);
            Assert.Equal(arrSon.SyncRoot, arrMother.SyncRoot);
            Assert.Equal(_arrGrandDaughter.SyncRoot, arrMother.SyncRoot);
            Assert.Equal(_arrDaughter.SyncRoot, arrMother.SyncRoot);
            Assert.Equal(arrSon.SyncRoot, arrMother.SyncRoot);

            //we are going to rumble with the Hashtables with some threads
            workers = new Task[iNumberOfWorkers];
            ts2 = new Action(RemoveElements);
            for (int iThreads = 0; iThreads < iNumberOfWorkers; iThreads += 2)
            {
                var name = "Thread_worker_" + iThreads;
                ts1 = new Action(() => AddMoreElements(name));

                workers[iThreads] = Task.Run(ts1);
                workers[iThreads + 1] = Task.Run(ts2);
            }

            Task.WaitAll(workers);

            //checking time
            //Now lets see how this is done.
            //Either there should be some elements (the new ones we added and/or the original ones) or none
            hshPossibleValues = new Hashtable();
            for (int i = 0; i < _iNumberOfElements; i++)
            {
                hshPossibleValues.Add("Key_" + i, "Value_" + i);
            }

            for (int i = 0; i < iNumberOfWorkers; i++)
            {
                hshPossibleValues.Add("Key_Thread_worker_" + i, "Thread_worker_" + i);
            }

            idic = arrMother.GetEnumerator();

            while (idic.MoveNext())
            {
                Assert.True(hshPossibleValues.ContainsKey(idic.Key), "Error, Expected value not returned, " + idic.Key);
                Assert.True(hshPossibleValues.ContainsValue(idic.Value), "Error, Expected value not returned, " + idic.Value);
            }
        }
Exemple #44
0
        public ActionResult Add(Tb_Shopsp model)
        {
            BaseResult br = new BaseResult();

            var oldParam = new Hashtable();


            try
            {
                #region 获取参数
                Hashtable param = base.GetParameters();

                ParamVessel p = new ParamVessel();
                p.Add("shopspList", string.Empty, HandleType.ReturnMsg); //商品List
                p.Add("remark", string.Empty, HandleType.DefaultValue);  //备注
                p.Add("id_gys", string.Empty, HandleType.ReturnMsg);     //id_gys
                p.Add("id_shop", string.Empty, HandleType.ReturnMsg);    //id_shop
                p.Add("id_jbr", string.Empty, HandleType.ReturnMsg);     //id_jbr
                p.Add("dh", string.Empty, HandleType.ReturnMsg);
                p.Add("rq", string.Empty, HandleType.ReturnMsg);
                p.Add("je_sf", string.Empty, HandleType.ReturnMsg);//je_sf
                p.Add("dh_origin", string.Empty, HandleType.DefaultValue);
                p.Add("bm_djlx_origin", string.Empty, HandleType.DefaultValue);
                p.Add("id_bill_origin", string.Empty, HandleType.DefaultValue);

                p.Add("type", string.Empty, HandleType.Remove); //type
                p.Add("id", string.Empty, HandleType.Remove);   //id

                param = param.Trim(p);
                param.Add("id_masteruser", id_user_master);
                param.Add("id_user", id_user);
                oldParam = (Hashtable)param.Clone();
                #endregion

                List <Td_Jh_Th_2> shopspList = JSON.Deserialize <List <Td_Jh_Th_2> >(param["shopspList"].ToString()) ?? new List <Td_Jh_Th_2>();

                #region 验证数据
                if (shopspList == null || shopspList.Count() <= 0)
                {
                    br.Success = false;
                    br.Message.Add("商品不能为空!");
                    br.Level = ErrorLevel.Warning;
                    br.Data  = "shopspList";
                    WriteDBLog("退货-Post新增/编辑", oldParam, br);
                    return(base.JsonString(new
                    {
                        status = "error",
                        message = string.Join(";", br.Message)
                    }));
                }

                var digitHashtable = GetParm();
                foreach (var item in shopspList)
                {
                    item.sl = CySoft.Utility.DecimalExtension.Digit(item.sl, int.Parse(digitHashtable["sl_digit"].ToString()));
                    item.dj = CySoft.Utility.DecimalExtension.Digit(item.dj, int.Parse(digitHashtable["dj_digit"].ToString()));
                    item.je = CySoft.Utility.DecimalExtension.Digit(item.je, int.Parse(digitHashtable["je_digit"].ToString()));

                    if (item.sl == 0)
                    {
                        if (string.IsNullOrEmpty(param["id_bill_origin"].ToString()))
                        {
                            br.Success = false;
                            br.Message.Add("商品[" + item.barcode + "]数量不允许为0!");
                            br.Level = ErrorLevel.Warning;
                            br.Data  = "shopspList";
                            WriteDBLog("退货-Post新增/编辑", oldParam, br);
                            return(base.JsonString(new
                            {
                                status = "error",
                                message = string.Join(";", br.Message)
                            }));
                        }
                        else
                        {
                            item.je = 0;
                            continue;
                        }
                    }

                    //此处验证数据是否符合
                    var tempJe = CySoft.Utility.DecimalExtension.Digit(item.sl * item.dj, int.Parse(digitHashtable["je_digit"].ToString()));
                    var tempDj = CySoft.Utility.DecimalExtension.Digit(item.je / item.sl, int.Parse(digitHashtable["dj_digit"].ToString()));
                    if (tempJe == item.je || tempDj == item.dj)
                    {
                        continue;
                    }
                    else
                    {
                        br.Success = false;
                        br.Message.Add("商品中存在 单价*数量不等于金额的数据!");
                        WriteDBLog("退货-Post新增/编辑", oldParam, br);
                        return(base.JsonString(new
                        {
                            status = "error",
                            message = string.Join(";", br.Message)
                        }));
                    }
                }

                param.Remove("shopspList");
                param.Add("shopspList", shopspList);
                param.Add("DigitHashtable", digitHashtable);
                param.Add("autoAudit", AutoAudit());
                #endregion

                if (param.ContainsKey("type") && param["type"].ToString() == "edit")
                {
                    br = BusinessFactory.Td_Jh_Th_1.Update(param);
                    WriteDBLog("退货-Post编辑", oldParam, br);
                }
                else
                {
                    //插入表
                    br = BusinessFactory.Td_Jh_Th_1.Add(param);
                    WriteDBLog("退货-Post新增", oldParam, br);
                }

                if (br.Success)
                {
                    return(base.JsonString(new
                    {
                        status = "success",
                        message = string.Join(";", br.Message)
                    }));
                }
                else
                {
                    return(base.JsonString(br, 1));
                }
            }
            catch (CySoftException brEx)
            {
                br.Success = false;
                br.Data    = "";
                br.Message.Clear();
                br.Message.Add(brEx.Message.ToString());
                br.Level = ErrorLevel.Warning;
                WriteDBLog("退货-Post新增/编辑", oldParam, br);
                return(base.JsonString(new
                {
                    status = "error",
                    message = string.Join(";", br.Message)
                }));
            }
            catch (Exception ex)
            {
                br.Success = false;
                br.Data    = "";
                br.Message.Clear();
                br.Message.Add("数据不符合要求!");
                br.Level = ErrorLevel.Warning;
                WriteDBLog("退货-Post新增/编辑", oldParam, br);
                return(base.JsonString(new
                {
                    status = "error",
                    message = string.Join(";", br.Message)
                }));
            }
        }
 public bool runTest()
 {
     Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer);
     int iCountErrors = 0;
     int iCountTestcases = 0;
     String strLoc = "Loc_000oo";
     Hashtable hsh1;
     Hashtable hsh2;
     Hashtable hsh3;
     String strKey;
     String strValue;
     ICollection icol1;
     IDictionary idic1;
     ICloneable iclone1;
     try 
     {
         do
         {
             hsh1 = new Hashtable();
             hsh2 = (Hashtable)hsh1.Clone();
             if(hsh2.Count != 0) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_453gfd! Expected value not returned, <<" + hsh1.Count + ">> <<"+ hsh2.Count + ">>");
             }
             iCountTestcases++;
             if(hsh2.IsReadOnly) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_5234vsfd! Expected value not returned, <<" + hsh1.IsReadOnly + ">> <<"+ hsh2.IsReadOnly + ">>");
             }
             iCountTestcases++;
             if(hsh2.IsSynchronized) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_5234vsfd! Expected value not returned, <<" + hsh1.IsSynchronized + ">> <<"+ hsh2.IsSynchronized + ">>");
             }
             strLoc = "Loc_8345vdfv";
             hsh1 = new Hashtable();
             for(int i=0; i<10; i++)
             {
                 strKey = "Key_" + i;
                 strValue = "String_" + i;
                 hsh1.Add(strKey, strValue);
             }
             hsh2 = (Hashtable)hsh1.Clone();
             iCountTestcases++;
             for(int i=0; i<10; i++)
             {
                 strValue = "String_" + i;
                 if(!strValue.Equals((String)hsh2["Key_" + i])) 
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_561dvs_" + i + "! Expected value not returned, " + strValue);
                 }
             }
             hsh1.Remove("Key_9");
             iCountTestcases++;
             if(hsh1["Key_9"]!=null) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_563vdf! Expected value not returned, <<" + hsh1["Key_9"] + ">>");
             }
             strValue = "String_" + 9;
             iCountTestcases++;
             if(!strValue.Equals((String)hsh2["Key_9"])) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_563vdf! Expected value not returned, <<" + hsh1[9] + ">>");
             }
             strLoc = "Loc_625fd";
             hsh1 = new Hashtable(1000);
             hsh2 = (Hashtable)hsh1.Clone();
             iCountTestcases++;
             if(hsh1.Count != hsh2.Count) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_453gfd! Expected value not returned, <<" + hsh1.Count + ">> <<"+ hsh2.Count + ">>");
             }
             iCountTestcases++;
             if(hsh1.IsReadOnly != hsh2.IsReadOnly) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_5234vsfd! Expected value not returned, <<" + hsh1.IsReadOnly + ">> <<"+ hsh2.IsReadOnly + ">>");
             }
             iCountTestcases++;
             if(hsh1.IsSynchronized != hsh2.IsSynchronized) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_5234vsfd! Expected value not returned, <<" + hsh1.IsSynchronized + ">> <<"+ hsh2.IsSynchronized + ">>");
             }
             strLoc = "Loc_8345vdfv";
             hsh1 = new Hashtable();
             for(int i=0; i<10; i++)
             {
                 hsh1.Add(i, new Foo());
             }
             hsh2 = (Hashtable)hsh1.Clone();
             iCountTestcases++;
             for(int i=0; i<10; i++)
             {
                 strValue = "Hello World";
                 if(!strValue.Equals(((Foo)hsh2[i]).strValue)) 
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_5623rvsdf_" + i + "! Expected value not returned, " + strValue);
                 }
             }
             strValue = "Good Bye";
             ((Foo)hsh1[0]).strValue = strValue;
             iCountTestcases++;
             if(!strValue.Equals(((Foo)hsh1[0]).strValue)) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_7453bvdf! Expected value not returned, " + strValue);
             }
             iCountTestcases++;
             if(!strValue.Equals(((Foo)hsh2[0]).strValue)) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_7453bvdf! Expected value not returned, " + strValue);
             }
             hsh2[0] = new Foo();
             strValue = "Good Bye";
             iCountTestcases++;
             if(!strValue.Equals(((Foo)hsh1[0]).strValue)) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_525vdf! Expected value not returned, " + strValue);
             }
             strValue = "Hello World";
             iCountTestcases++;
             if(!strValue.Equals(((Foo)hsh2[0]).strValue)) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_54363fgdf! Expected value not returned, " + strValue);
             }
             hsh1 = new Hashtable();
             for(int i=0; i<10; i++)
             {
                 strKey = "Key_" + i;
                 strValue = "String_" + i;
                 hsh1.Add(strKey, strValue);
             }
             hsh2 = new Hashtable(hsh1);
             hsh2.Remove("Key_0");
             hsh2.Remove("Key_1");
             hsh2.Remove("Key_2");
             if(hsh2.Count != 7)
             {
                 iCountErrors++;
                 Console.WriteLine("Err_45235w! Expected value not returned");
             }
             hsh2["Key_10"] = "String_10";
             hsh2["Key_11"] = "String_11";
             hsh2["Key_12"] = "String_12";
             hsh3 = (Hashtable)hsh2.Clone();
             if(hsh3.Count != 10) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_453gfd! Expected value not returned, <<" + hsh1.Count + ">> <<"+ hsh2.Count + ">>");
             }
             for(int i=3; i<13; i++)
             {
                 if(!hsh3.Contains("Key_" + i)) 
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_742ds8f! Expected value not returned, " + hsh3.Contains("Key_" + i));
                 }				
                 if(!hsh3.ContainsKey("Key_" + i)) 
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_742389dsaf! Expected value not returned, " + hsh3.ContainsKey("Key_" + i));
                 }				
                 if(!hsh3.ContainsValue("String_" + i)) 
                 {
                     iCountErrors++;
                     Console.WriteLine("Err_6243dsf! Expected value not returned, " + hsh3.ContainsValue("Value_" + i));
                 }				
             }
             iCountTestcases++;
             hsh1 = new Hashtable();
             try
             {
                 icol1= (ICollection)hsh1.Clone();
             }
             catch(Exception ex)
             {
                 iCountErrors++;
                 Console.WriteLine("Err_5734sfs! Unexpected exception thrown, " + ex);
             }
             try
             {
                 idic1= (IDictionary )hsh1.Clone();
             }
             catch(Exception ex)
             {
                 iCountErrors++;
                 Console.WriteLine("Err_5734sfs! Unexpected exception thrown, " + ex);
             }
             try
             {
                 iclone1= (ICloneable)hsh1.Clone();
             }
             catch(Exception ex)
             {
                 iCountErrors++;
                 Console.WriteLine("Err_5734sfs! Unexpected exception thrown, " + ex);
             }
         } while (false);
     } 
     catch (Exception exc_general ) 
     {
         ++iCountErrors;
         Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy!  strLoc=="+ strLoc +", exc_general==\n"+exc_general.ToString());
     }
     if ( iCountErrors == 0 )
     {
         Console.WriteLine( "paSs.   "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases);
         return true;
     }
     else
     {
         Console.WriteLine("FAiL!   "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums );
         return false;
     }
 }
Exemple #46
0
        private void BUT_writePIDS_Click(object sender, EventArgs e)
        {
            var temp = (Hashtable)changes.Clone();

            foreach (string value in temp.Keys)
            {
                try
                {
                    if ((float)changes[value] > (float)MainV2.comPort.MAV.param[value] * 2.0f)
                    {
                        if (
                            CustomMessageBox.Show(value + " has more than doubled the last input. Are you sure?",
                                                  "Large Value", MessageBoxButtons.YesNo) == (int)DialogResult.No)
                        {
                            try
                            {
                                // set control as well
                                var textControls = Controls.Find(value, true);
                                if (textControls.Length > 0)
                                {
                                    // restore old value
                                    textControls[0].Text      = MainV2.comPort.MAV.param[value].Value.ToString();
                                    textControls[0].BackColor = Color.FromArgb(0x43, 0x44, 0x45);
                                }
                            }
                            catch
                            {
                            }
                            return;
                        }
                    }

                    if (MainV2.comPort.BaseStream == null || !MainV2.comPort.BaseStream.IsOpen)
                    {
                        CustomMessageBox.Show("You are not connected", Strings.ERROR);
                        return;
                    }

                    MainV2.comPort.setParam(value, (float)changes[value]);

                    changes.Remove(value);

                    try
                    {
                        // set control as well
                        var textControls = Controls.Find(value, true);
                        if (textControls.Length > 0)
                        {
                            textControls[0].BackColor = Color.FromArgb(0x43, 0x44, 0x45);
                        }
                    }
                    catch
                    {
                    }
                }
                catch
                {
                    CustomMessageBox.Show(string.Format(Strings.ErrorSetValueFailed, value), Strings.ERROR);
                }
            }
        }
Exemple #47
0
 public static void ColorFrom(GameObject target, Hashtable args)
 {
     Color color = default(Color);
     Color color2 = default(Color);
     args = iTween.CleanArgs(args);
     if (!args.Contains("includechildren") || (bool)args["includechildren"])
     {
         foreach (Transform transform in target.transform)
         {
             Hashtable hashtable = (Hashtable)args.Clone();
             hashtable["ischild"] = true;
             iTween.ColorFrom(transform.gameObject, hashtable);
         }
     }
     if (!args.Contains("easetype"))
     {
         args.Add("easetype", iTween.EaseType.linear);
     }
     if (target.GetComponent(typeof(GUITexture)))
     {
         color = (color2 = target.GetComponent<GUITexture>().color);
     }
     else if (target.GetComponent(typeof(GUIText)))
     {
         color = (color2 = target.GetComponent<GUIText>().material.color);
     }
     else if (target.GetComponent<Renderer>())
     {
         color = (color2 = target.GetComponent<Renderer>().material.color);
     }
     else if (target.GetComponent<Light>())
     {
         color = (color2 = target.GetComponent<Light>().color);
     }
     if (args.Contains("color"))
     {
         color = (Color)args["color"];
     }
     else
     {
         if (args.Contains("r"))
         {
             color.r = (float)args["r"];
         }
         if (args.Contains("g"))
         {
             color.g = (float)args["g"];
         }
         if (args.Contains("b"))
         {
             color.b = (float)args["b"];
         }
         if (args.Contains("a"))
         {
             color.a = (float)args["a"];
         }
     }
     if (args.Contains("amount"))
     {
         color.a = (float)args["amount"];
         args.Remove("amount");
     }
     else if (args.Contains("alpha"))
     {
         color.a = (float)args["alpha"];
         args.Remove("alpha");
     }
     if (target.GetComponent(typeof(GUITexture)))
     {
         target.GetComponent<GUITexture>().color = color;
     }
     else if (target.GetComponent(typeof(GUIText)))
     {
         target.GetComponent<GUIText>().material.color = color;
     }
     else if (target.GetComponent<Renderer>())
     {
         target.GetComponent<Renderer>().material.color = color;
     }
     else if (target.GetComponent<Light>())
     {
         target.GetComponent<Light>().color = color;
     }
     args["color"] = color2;
     args["type"] = "color";
     args["method"] = "to";
     iTween.Launch(target, args);
 }
Exemple #48
0
        public ActionResult Edit(Tb_Hy model)
        {
            BaseResult br       = new BaseResult();
            var        oldParam = new Hashtable();

            try
            {
                #region 获取参数
                Hashtable   param = base.GetParameters();
                ParamVessel p     = new ParamVessel();
                p.Add("name", string.Empty, HandleType.ReturnMsg);          //name
                p.Add("membercard", string.Empty, HandleType.DefaultValue); //membercard
                p.Add("phone", string.Empty, HandleType.DefaultValue);      //phone
                p.Add("qq", string.Empty, HandleType.DefaultValue);         //qq
                p.Add("email", string.Empty, HandleType.DefaultValue);      //email
                p.Add("tel", string.Empty, HandleType.DefaultValue);        //tel
                p.Add("address", string.Empty, HandleType.DefaultValue);    //address
                p.Add("MMno", string.Empty, HandleType.DefaultValue);       //MMno
                p.Add("zipcode", string.Empty, HandleType.DefaultValue);    //zipcode
                p.Add("birthday", string.Empty, HandleType.DefaultValue);   //birthday
                p.Add("flag_nl", "0", HandleType.DefaultValue);             //flag_nl 是否农历
                p.Add("id_shop_create", string.Empty, HandleType.Remove);   //id_shop_create
                p.Add("id_hyfl", string.Empty, HandleType.ReturnMsg);       //id_hyfl
                p.Add("rq_b", string.Empty, HandleType.ReturnMsg);          //rq_b
                p.Add("rq_b_end", string.Empty, HandleType.ReturnMsg);      //rq_b_end
                p.Add("birth_month", "", HandleType.DefaultValue);          //birth_month
                p.Add("birth_day", "", HandleType.DefaultValue);            //birth_day
                p.Add("zk", "0.00", HandleType.DefaultValue);               //zk
                p.Add("flag_sex", "1", HandleType.DefaultValue);            //flag_sex
                p.Add("flag_yhlx", "1", HandleType.DefaultValue);           //flag_yhlx
                p.Add("password", "", HandleType.Remove);                   //password


                p.Add("id", "", HandleType.ReturnMsg);//id
                param = param.Trim(p);
                param.Add("id_masteruser", id_user_master);
                param.Add("id_user", id_user);
                param.Add("rq_e", param["rq_b_end"].ToString());
                param.Remove("rq_b_end");
                oldParam = (Hashtable)param.Clone();
                #endregion
                #region 参数验证
                if (string.IsNullOrEmpty(param["membercard"].ToString()) && string.IsNullOrEmpty(param["phone"].ToString()))
                {
                    br.Success = false;
                    br.Message.Add("会员卡号和手机号必须二选一!");
                    WriteDBLog("会员-编辑", oldParam, br);
                    return(base.JsonString(br, 1));
                }

                if (string.IsNullOrEmpty(param["zk"].ToString()) || !CyVerify.IsNumeric(param["zk"].ToString()) || decimal.Parse(param["zk"].ToString()) < 0 || decimal.Parse(param["zk"].ToString()) > 1)
                {
                    br.Success = false;
                    br.Message.Add("会员折扣不符合要求 折扣必须在0-1之间!");
                    WriteDBLog("会员-编辑", oldParam, br);
                    return(base.JsonString(br, 1));
                }

                if (!string.IsNullOrEmpty(param["flag_yhlx"].ToString()) && param["flag_yhlx"].ToString() == "2" && decimal.Parse(param["zk"].ToString()) != 1)
                {
                    br.Success = false;
                    br.Message.Add("优惠类型为会员价 折扣只能为1!");
                    WriteDBLog("会员-编辑", oldParam, br);
                    return(base.JsonString(br, 1));
                }

                if (!string.IsNullOrEmpty(param["birthday"].ToString()))
                {
                    //计算生日
                    DateTime birthday = DateTime.Parse(param["birthday"].ToString());
                    string   hysr     = birthday.ToString("MMdd");
                    param.Add("hysr", hysr);
                }
                else
                {
                    if (!string.IsNullOrEmpty(param["birth_month"].ToString()) && !string.IsNullOrEmpty(param["birth_day"].ToString()))
                    {
                        var month = param["birth_month"].ToString();
                        if (month.Length > 2 || month.Length < 1)
                        {
                            month = "00";
                        }
                        else if (month.Length == 1)
                        {
                            month = "0" + month;
                        }
                        var day = param["birth_day"].ToString();
                        if (day.Length > 2 || day.Length < 1)
                        {
                            day = "00";
                        }
                        else if (day.Length == 1)
                        {
                            day = "0" + day;
                        }
                        param.Add("hysr", month + day);
                    }
                }
                #endregion
                #region 判断是否共享的处理
                if (param.ContainsKey("id_shop_create"))
                {
                    var br_Hy_ShopShare = BusinessFactory.Account.GetHy_ShopShare(param["id_shop_create"].ToString(), id_user_master);// GetHy_ShopShare(param["id_shop_create"].ToString());
                    if (!br_Hy_ShopShare.Success)
                    {
                        return(base.JsonString(br, 1));
                    }
                    var param_Hy_ShopShare = (Hashtable)br_Hy_ShopShare.Data;
                    param.Add("id_shop", param_Hy_ShopShare["id_shop"].ToString());
                }
                else
                {
                    param.Add("id_shop", id_shop);
                    param.Add("id_shop_create", id_shop);
                }
                #endregion
                #region 新增
                br = BusinessFactory.Tb_Hy_Shop.Update(param);
                #endregion
                #region 返回
                WriteDBLog("会员-编辑", oldParam, br);
                return(base.JsonString(br, 1));

                #endregion
            }
            catch (Exception ex)
            {
                #region 异常返回
                br.Success = false;
                br.Data    = "";
                br.Message.Add("数据不符合要求!");
                br.Level = ErrorLevel.Warning;
                WriteDBLog("会员-编辑", oldParam, br);
                return(base.JsonString(br, 1));

                #endregion
            }
        }
Exemple #49
0
 public static void ColorTo(GameObject target, Hashtable args)
 {
     args = iTween.CleanArgs(args);
     if (!args.Contains("includechildren") || (bool)args["includechildren"])
     {
         foreach (Transform transform in target.transform)
         {
             Hashtable hashtable = (Hashtable)args.Clone();
             hashtable["ischild"] = true;
             iTween.ColorTo(transform.gameObject, hashtable);
         }
     }
     if (!args.Contains("easetype"))
     {
         args.Add("easetype", iTween.EaseType.linear);
     }
     args["type"] = "color";
     args["method"] = "to";
     iTween.Launch(target, args);
 }
Exemple #50
0
        /// <summary>
        /// Clones the into.
        /// </summary>
        /// <param name="clone">The clone.</param>
        /// <param name="cloneHandlers">if set to <c>true</c> [clone handlers].</param>
        public void CloneInto(Row <TFields> clone,
                              bool cloneHandlers)
        {
            clone.IgnoreConstraints = IgnoreConstraints;

            foreach (var field in fields)
            {
                field.Copy(this, clone);
            }

            clone.tracking = tracking;
            if (tracking && assignedFields != null)
            {
                clone.assignedFields = new bool[assignedFields.Length];
                Array.Copy(assignedFields, clone.assignedFields, assignedFields.Length);
            }
            else
            {
                clone.assignedFields = null;
            }

            clone.trackWithChecks = trackWithChecks;

            clone.originalValues = originalValues;

            if (dictionaryData != null)
            {
                clone.dictionaryData = (Hashtable)dictionaryData.Clone();
            }
            else
            {
                clone.dictionaryData = null;
            }

            if (indexedData != null)
            {
                clone.indexedData = new object[indexedData.Length];
                for (var i = 0; i < indexedData.Length; i++)
                {
                    clone.indexedData[i] = indexedData[i];
                }
            }
            else
            {
                clone.indexedData = null;
            }

            if (previousValues != null)
            {
                clone.previousValues = previousValues.CloneRow();
            }
            else
            {
                clone.previousValues = null;
            }

            if (cloneHandlers)
            {
                clone.postHandler     = postHandler;
                clone.propertyChanged = propertyChanged;

                if (validationErrors != null)
                {
                    clone.validationErrors = new Dictionary <string, string>(validationErrors);
                }
                else
                {
                    clone.validationErrors = null;
                }
            }
        }
 public HashSet(Hashtable ht)
 {
     this.ht = (Hashtable)ht.Clone();
 }
Exemple #52
0
    /// <summary>
    /// Changes a GameObject's color values instantly then returns them to the provided properties over time with FULL customization options.  If a GUIText or GUITexture component is attached, it will become the target of the animation.
    /// </summary>
    /// <param name="color">
    /// A <see cref="Color"/> to change the GameObject's color to.
    /// </param>
    /// <param name="r">
    /// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the color red.
    /// </param>
    /// <param name="g">
    /// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the color green.
    /// </param>
    /// <param name="b">
    /// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the color green.
    /// </param>
    /// <param name="a">
    /// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the alpha.
    /// </param> 
    /// <param name="namedcolorvalue">
    /// A <see cref="NamedColorValue"/> or <see cref="System.String"/> for the individual setting of the alpha.
    /// </param> 
    /// <param name="includechildren">
    /// A <see cref="System.Boolean"/> for whether or not to include children of this GameObject. True by default.
    /// </param>
    /// <param name="time">
    /// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will take to complete.
    /// </param>
    /// <param name="delay">
    /// A <see cref="System.Single"/> or <see cref="System.Double"/> for the time in seconds the animation will wait before beginning.
    /// </param>
    /// <param name="easetype">
    /// A <see cref="EaseType"/> or <see cref="System.String"/> for the shape of the easing curve applied to the animation.
    /// </param>   
    /// <param name="looptype">
    /// A <see cref="LoopType"/> or <see cref="System.String"/> for the type of loop to apply once the animation has completed.
    /// </param>
    /// <param name="onstart">
    /// A <see cref="System.String"/> for the name of a function to launch at the beginning of the animation.
    /// </param>
    /// <param name="onstarttarget">
    /// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onstart" method.
    /// </param>
    /// <param name="onstartparams">
    /// A <see cref="System.Object"/> for arguments to be sent to the "onstart" method.
    /// </param>
    /// <param name="onupdate"> 
    /// A <see cref="System.String"/> for the name of a function to launch on every step of the animation.
    /// </param>
    /// <param name="onupdatetarget">
    /// A <see cref="GameObject"/> for a reference to the GameObject that holds the "onupdate" method.
    /// </param>
    /// <param name="onupdateparams">
    /// A <see cref="System.Object"/> for arguments to be sent to the "onupdate" method.
    /// </param> 
    /// <param name="oncomplete">
    /// A <see cref="System.String"/> for the name of a function to launch at the end of the animation.
    /// </param>
    /// <param name="oncompletetarget">
    /// A <see cref="GameObject"/> for a reference to the GameObject that holds the "oncomplete" method.
    /// </param>
    /// <param name="oncompleteparams">
    /// A <see cref="System.Object"/> for arguments to be sent to the "oncomplete" method.
    /// </param>
    public static void ColorFrom(GameObject target, Hashtable args)
    {
        Color fromColor = new Color();
        Color tempColor = new Color();

        //clean args:
        args = iTween.CleanArgs(args);

        //handle children:
        if(!args.Contains("includechildren") || (bool)args["includechildren"]){
            foreach(Transform child in target.transform){
                Hashtable argsCopy = (Hashtable)args.Clone();
                argsCopy["ischild"]=true;
                ColorFrom(child.gameObject,argsCopy);
            }
        }

        //set a default easeType of linear if none is supplied since eased color interpolation is nearly unrecognizable:
        if (!args.Contains("easetype")) {
            args.Add("easetype",EaseType.linear);
        }

        //set tempColor and base fromColor:
        if(target.GetComponent(typeof(GUITexture))){
            tempColor=fromColor=target.guiTexture.color;
        }else if(target.GetComponent(typeof(GUIText))){
            tempColor=fromColor=target.guiText.material.color;
        }else if(target.renderer){
            tempColor=fromColor=target.renderer.material.color;
        }else if(target.light){
            tempColor=fromColor=target.light.color;
        }

        //set augmented fromColor:
        if(args.Contains("color")){
            fromColor=(Color)args["color"];
        }else{
            if (args.Contains("r")) {
                fromColor.r=(float)args["r"];
            }
            if (args.Contains("g")) {
                fromColor.g=(float)args["g"];
            }
            if (args.Contains("b")) {
                fromColor.b=(float)args["b"];
            }
            if (args.Contains("a")) {
                fromColor.a=(float)args["a"];
            }
        }

        //alpha or amount?
        if(args.Contains("amount")){
            fromColor.a=(float)args["amount"];
            args.Remove("amount");
        }else if(args.Contains("alpha")){
            fromColor.a=(float)args["alpha"];
            args.Remove("alpha");
        }

        //apply fromColor:
        if(target.GetComponent(typeof(GUITexture))){
            target.guiTexture.color=fromColor;
        }else if(target.GetComponent(typeof(GUIText))){
            target.guiText.material.color=fromColor;
        }else if(target.renderer){
            target.renderer.material.color=fromColor;
        }else if(target.light){
            target.light.color=fromColor;
        }

        //set new color arg:
        args["color"]=tempColor;

        //establish iTween:
        args["type"]="color";
        args["method"]="to";
        Launch(target,args);
    }
Exemple #53
0
 private void SaveNodeList_Click(object sender, EventArgs e)
 {
     MainForm.pMainForm.mapdoc.nodeinfoMap = (Hashtable)NodeInfo.Clone();
     MainForm.pMainForm.mapdoc.SaveInit();
 }
Exemple #54
0
        public static RecallableState?SerializeState(List <WorldEntity> Skip)
        {
            ArrayList         UpdateIDs     = new ArrayList();
            ArrayList         RenderIDs     = new ArrayList();
            ArrayList         SerializedIDs = new ArrayList();
            IFormatter        SerFormatter  = new BinaryFormatter();
            ArrayList         Streams       = new ArrayList();
            SurrogateSelector SS            = new SurrogateSelector();

            Surrogates.Vector2SS    V2SS  = new Surrogates.Vector2SS();
            Surrogates.PointSS      PSS   = new Surrogates.PointSS();
            Surrogates.RectangleSS  RSS   = new Surrogates.RectangleSS();
            Surrogates.Texture2DSS  T2DSS = new Surrogates.Texture2DSS();
            Surrogates.ColorSS      CSS   = new Surrogates.ColorSS();
            Surrogates.SpriteFontSS SFSS  = new Surrogates.SpriteFontSS();
            SS.AddSurrogate(typeof(Vector2), new StreamingContext(StreamingContextStates.All), V2SS);
            SS.AddSurrogate(typeof(Point), new StreamingContext(StreamingContextStates.All), PSS);
            SS.AddSurrogate(typeof(Rectangle), new StreamingContext(StreamingContextStates.All), RSS);
            SS.AddSurrogate(typeof(Texture2D), new StreamingContext(StreamingContextStates.All), T2DSS);
            SS.AddSurrogate(typeof(Color), new StreamingContext(StreamingContextStates.All), CSS);
            SS.AddSurrogate(typeof(SpriteFont), new StreamingContext(StreamingContextStates.All), SFSS);
            SerFormatter.SurrogateSelector = SS;
            try
            {
                foreach (WorldEntity W in UpdateQueue)
                {
                    if (Skip.Contains(W))
                    {
                        continue;
                    }
                    UpdateIDs.Add(W.EntityID);
                    W.OnSerializeDo();
                    MemoryStream EntityStream = new MemoryStream();
                    SerFormatter.Serialize(EntityStream, W);
                    EntityStream.Close();
                    Streams.Add(EntityStream.ToArray());
                    SerializedIDs.Add(W.EntityID);
                }
                foreach (WorldEntity W in RenderQueue)
                {
                    if (Skip.Contains(W))
                    {
                        continue;
                    }
                    RenderIDs.Add(W.EntityID);
                    if (!SerializedIDs.Contains(W.EntityID))
                    {
                        W.OnSerializeDo();
                        MemoryStream EntityStream = new MemoryStream();
                        SerFormatter.Serialize(EntityStream, W);
                        EntityStream.Close();
                        Streams.Add(EntityStream.ToArray());
                        SerializedIDs.Add(W.EntityID);
                    }
                }
            }
            catch (Exception e)
            {
                WriteLine("Failed to serialize state due to " + e.GetType().Name + ": " + e.Message);
                return(null);
            }
            RecallableState Out = new RecallableState();

            Out.RenderIDs      = RenderIDs.ToArray().Select(x => (ulong)x).ToArray();
            Out.UpdateIDs      = UpdateIDs.ToArray().Select(x => (ulong)x).ToArray();
            Out.SerializedEnts = Streams.ToArray().Select(x => (byte[])x).ToArray();
            Out.LabelEntity    = ScriptProcessor.LabelEntity;
            Out.SongCom        = ScriptProcessor.SongCom;
            Out.Flags          = (Hashtable)Flags.Clone();
            return(Out);
        }
Exemple #55
0
        public static Hashtable[] GetComboCaches(string key, DBCustomClass dbClass)
        {
            if (m_htComboCaches[key] == null)
            {
                Hashtable[] htReturn = new Hashtable[3];

                string[] keys            = key.Split(new Char[] { ',' });
                string   strlisttable    = keys[0];
                string   strliscondition = keys[1];
                string   strlistf        = keys[2];
                string   strlistk        = keys[3];
                string   strlistfex      = keys[4];

                string sql = "SELECT * FROM " + strlisttable;
                if (strliscondition.Length > 0)
                {
                    sql += " WHERE " + strliscondition;
                }
                /*DataTable tbl = Helper.GetDataTable(sql, Conn);*/
                DataTable tbl = GetDataTableWithKeyProxy(strlisttable, strliscondition, null);

                Hashtable comhashkeys          = new Hashtable();
                Hashtable comhashvalues        = new Hashtable();
                Hashtable comhashfieldsex      = dbClass.GetListFieldExArray(strlistfex); // 下拉框可以获取一些额外的字段,以便于脚本访问从表字段内容
                Hashtable modihash             = comhashfieldsex == null ? null : (Hashtable)comhashfieldsex.Clone();
                Hashtable comfieldsexContainer = new Hashtable();
                foreach (DataRow comborow in tbl.Rows)
                {
                    string strkey      = dbClass.GetFieldStrNoLower(comborow, strlistk);
                    string newStrListF = dbClass.GetFieldStr(comborow, strlistf) + "[" + strkey + "]";

                    comhashkeys[newStrListF] = strkey;
                    comhashvalues[strkey]    = newStrListF;
                    if (comhashfieldsex != null)
                    {
                        foreach (string eachkey in comhashfieldsex.Keys)
                        {
                            if (comborow[eachkey] != null)
                            {
                                modihash[eachkey] = comborow[eachkey].ToString();
                            }
                            else
                            {
                                modihash[eachkey] = "";
                            }
                        }
                        if (comhashfieldsex.Count > 0 && !comfieldsexContainer.ContainsKey(strkey))
                        {
                            comfieldsexContainer[strkey] = modihash.Clone(); // 每一行形成一个HASHTABLE
                        }
                    }
                }

                htReturn[0] = comhashkeys;
                htReturn[1] = comhashvalues;
                htReturn[2] = comfieldsexContainer; // 每一行记录形成一个HASHTABLE,容器的KEY值中listfieldID值

                if (m_htComboCaches.Keys.Count > comboCacheSize)
                {
                    m_htComboCaches.Clear();
                }

                m_htComboCaches[key] = htReturn;
            }

            return((Hashtable[])(m_htComboCaches[key]));
        }