public void SetCookie(string[] cookieList, string host) { if (cookieList == null) return; lock (this) { foreach (string cookieString in cookieList) { if (cookieString == "") continue; string[] cookies = cookieString.Trim().Split(SEM); Hashtable cookie = new Hashtable(); #if !dotNETMF string[] value = regex.Split(cookies[0].Trim(), 2); #else string[] value = cookies[0].Trim().Split(EQU, 2); #endif cookie["name"] = value[0]; if (value.Length == 2) cookie["value"] = value[1]; else cookie["value"] = ""; for (int i = 1; i < cookies.Length; ++i) { #if !dotNETMF value = regex.Split(cookies[i].Trim(), 2); #else value = cookies[i].Trim().Split(EQU, 2); #endif if (value.Length == 2) cookie[value[0].ToUpper()] = value[1]; else cookie[value[0].ToUpper()] = ""; } // Tomcat can return SetCookie2 with path wrapped in " if (cookie.Contains("PATH")) { string path = ((string)cookie["PATH"]); if (path[0] == '"') path = path.Substring(1); if (path[path.Length - 1] == '"') path = path.Substring(0, path.Length - 1); cookie["PATH"] = path; } else { cookie["PATH"] = "/"; } #if !dotNETMF if (cookie.Contains("EXPIRES")) { cookie["EXPIRES"] = DateTime.Parse((string)cookie["EXPIRES"]); } #endif if (cookie.Contains("DOMAIN")) { cookie["DOMAIN"] = ((string)cookie["DOMAIN"]).ToLower(); } else { cookie["DOMAIN"] = host; } cookie["SECURE"] = cookie.Contains("SECURE"); if (!container.Contains(cookie["DOMAIN"])) { container[cookie["DOMAIN"]] = new Hashtable(); } ((Hashtable)container[cookie["DOMAIN"]])[cookie["name"]] = cookie; } } }
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"; String strValue; Hashtable dic1; try { do { strLoc = "Loc_8345vdfv"; dic1 = new Hashtable(); for(int i=0; i<10; i++) { strValue = "String_" + i; dic1.Add(i, strValue); } iCountTestcases++; for(int i=0; i<10; i++) { if(!dic1.Contains(i)) { iCountErrors++; Console.WriteLine("Err_561dvs_" + i + "! Expected value not returned, " + dic1.Contains(i)); } } iCountTestcases++; if(dic1.IsReadOnly) { iCountErrors++; Console.WriteLine("Err_65323gdfgb! Expected value not returned, " + dic1.IsReadOnly); } dic1.Remove(0); iCountTestcases++; if(dic1.Contains(0)) { iCountErrors++; Console.WriteLine("Err_65323gdfgb! Expected value not returned, " + dic1.Contains(0)); } } 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; } }
public GameCenterPlayer( Hashtable ht ) { if( ht.Contains( "playerId" ) ) playerId = ht["playerId"] as string; if( ht.Contains( "alias" ) ) alias = ht["alias"] as string; if( ht.Contains( "isFriend" ) ) isFriend = (bool)ht["isFriend"]; }
public void TestContainsBasic() { StringBuilder sblMsg = new StringBuilder(99); Hashtable ht1 = null; string s1 = null; string s2 = null; int i = 0; ht1 = new Hashtable(); //default constructor Assert.False(ht1.Contains("No_Such_Key")); /// [] Testcase: add few key-val pairs ht1 = new Hashtable(); for (i = 0; i < 100; i++) { sblMsg = new StringBuilder(99); sblMsg.Append("key_"); sblMsg.Append(i); s1 = sblMsg.ToString(); sblMsg = new StringBuilder(99); sblMsg.Append("val_"); sblMsg.Append(i); s2 = sblMsg.ToString(); ht1.Add(s1, s2); } for (i = 0; i < ht1.Count; i++) { sblMsg = new StringBuilder(99); sblMsg.Append("key_"); sblMsg.Append(i); s1 = sblMsg.ToString(); Assert.True(ht1.Contains(s1)); } // // Remove a key and then check // sblMsg = new StringBuilder(99); sblMsg.Append("key_50"); s1 = sblMsg.ToString(); ht1.Remove(s1); //removes "Key_50" Assert.False(ht1.Contains(s1)); }
public static ReceiverColorTo create(GameObject gameObject, Hashtable hashtable) { ReceiverColorTo receiver = gameObject.AddComponent<ReceiverColorTo>(); setTween(receiver, hashtable); if (hashtable.Contains("color")) receiver._desiredColor = (Color)hashtable["color"]; if (hashtable.Contains("affect alpha")) receiver._affectAlpha = (bool)hashtable["affect alpha"]; if (hashtable.Contains("use shared material")) receiver._useSharedMaterial = (bool)hashtable["use shared material"]; receiver.play(gameObject, "destroy"); return receiver; }
public void start_import(Hashtable project) { if(project.Contains("Location") && project.Contains("Name")) { if(checkProject(project["Location"].ToString(),project["Name"].ToString())) { this.project = project; } else { menu.setRender(true); menu.console("Das Project ist beschädigt."); } } else { menu.setRender(true); menu.console("Es wurde kein Project ausgewählt."); } }
public void Populate (Photo [] photos) { Hashtable hash = new Hashtable (); if (photos != null) { foreach (Photo p in photos) { foreach (Tag t in p.Tags) { if (!hash.Contains (t.Id)) { hash.Add (t.Id, t); } } } } foreach (Widget w in this.Children) { w.Destroy (); } if (hash.Count == 0) { /* Fixme this should really set parent menu items insensitve */ MenuItem item = new MenuItem (Mono.Unix.Catalog.GetString ("(No Tags)")); this.Append (item); item.Sensitive = false; item.ShowAll (); return; } foreach (Tag t in hash.Values) { TagMenuItem item = new TagMenuItem (t); this.Append (item); item.ShowAll (); item.Activated += HandleActivate; } }
// Envia a conexao ao servidor public void send(GameJsonAuthConnection.ConnectionAnswerWithState callback) { if (!semaphore.WaitOne(0)) { //Debug.Log("Pero no."); return; } //Debug.Log("Yaarrrrr."); GameJsonAuthConnection conn = new GameJsonAuthConnection(url, callback); // Cria o header Hashtable table = new Hashtable(headers.Count); foreach (DictionaryEntry entry in headers) table.Add(entry.Key, entry.Value); // Decide se e uma conexao binaria string delimiter; if (!table.Contains("Content-Type")) delimiter = "&"; else { Match match = Regex.Match(table["Content-Type"].ToString(), @"boundary=\""(.*)"""); if (match.Success) delimiter = match.Groups[1].Value; else delimiter = "&"; } byte[] fdata = (byte[]) data.Clone(); string adata = null; if (delimiter == "&") { adata = ""; if (data.Length != 0) adata += "&"; adata += "device=" + WWW.EscapeURL(SystemInfo.deviceUniqueIdentifier.Replace("-","")) + "&token=" + WWW.EscapeURL(Save.GetString(PlayerPrefsKeys.TOKEN.ToString())); } else { adata = @" Content-Type: text/plain; charset=""utf-8"" Content-disposition: form-data; name=""device"" " + SystemInfo.deviceUniqueIdentifier.Replace("-","") + @" --" + delimiter + @" Content-Type: text/plain; charset=""utf-8"" Content-disposition: form-data; name=""token"" " + Save.GetString(PlayerPrefsKeys.TOKEN.ToString()) + @" --" + delimiter + @"-- "; System.Array.Resize<byte>(ref fdata, fdata.Length - 4); } byte[] bdata = System.Text.Encoding.ASCII.GetBytes(adata); int size = fdata.Length; System.Array.Resize<byte>(ref fdata, fdata.Length + bdata.Length); bdata.CopyTo(fdata, size); conn.connect(fdata, table, id); }
private static void ColectControlByType(Type ctrlType, Control parent, Hashtable list) { if (list == null) return; foreach (Control ctrl in parent.Controls) { if ((ctrl.GetType() == ctrlType) && (ctrl.ID != null) && (!list.Contains(ctrl.ID))) list.Add(ctrl.ID, ctrl); ColectControlByType(ctrlType, ctrl, list); } }
public CouplingType (Hashtable info) { if(info != null) { ID = Helpers.ToInt (info ["idTipoEnganche"]); Code = info ["codigo"].ToString (); if(info.Contains("activo")) IsActive = Helpers.ToBool(info["activo"]); } }
public ConfigCouplingRequired (Hashtable info) { if(info != null) { ID = Helpers.ToInt (info ["idConfigEngancheRequerido"]); Description = info ["descripcion"].ToString (); if( info.Contains("activo")) IsActive = Helpers.ToBool(info["activo"]); } }
public static ReceiverScaleAdd create(GameObject gameObject, Hashtable hashtable) { ReceiverScaleAdd receiver = gameObject.AddComponent<ReceiverScaleAdd>(); setTween(receiver, hashtable); if (hashtable.Contains("target")) receiver._target = (Vector3)hashtable["target"]; receiver.play(gameObject, "destroy"); return receiver; }
public static ReceiverRectMoveTo create(GameObject gameObject, Hashtable hashtable) { ReceiverRectMoveTo receiver = gameObject.GetComponent<ReceiverRectMoveTo>(); if (receiver == null) receiver = gameObject.AddComponent<ReceiverRectMoveTo>(); setTween(receiver, hashtable); if (hashtable.Contains("target")) receiver.target = (Vector2)hashtable["target"]; receiver.play(gameObject, "destroy"); return receiver; }
public GameCenterScore( Hashtable ht ) { if( ht.Contains( "category" ) ) category = ht["category"] as string; if( ht.Contains( "formattedValue" ) ) formattedValue = ht["formattedValue"] as string; if( ht.Contains( "value" ) ) value = Int64.Parse( ht["value"].ToString() ); if( ht.Contains( "context" ) ) context = Int64.Parse( ht["context"].ToString() ); if( ht.Contains( "playerId" ) ) playerId = ht["playerId"] as string; if( ht.Contains( "rank" ) ) rank = int.Parse( ht["rank"].ToString() ); if( ht.Contains( "isFriend" ) ) isFriend = (bool)ht["isFriend"]; if( ht.Contains( "alias" ) ) alias = ht["alias"] as string; else alias = "Anonymous"; if( ht.Contains( "maxRange" ) ) maxRange = int.Parse( ht["maxRange"].ToString() ); // grab and convert the date if( ht.Contains( "date" ) ) { double timeSinceEpoch = double.Parse( ht["date"].ToString() ); DateTime intermediate = new DateTime( 1970, 1, 1, 0, 0, 0, DateTimeKind.Utc ); date = intermediate.AddSeconds( timeSinceEpoch ); } }
public GameCenterAchievement( Hashtable ht ) { if( ht.Contains( "identifier" ) ) identifier = ht["identifier"] as string; if( ht.Contains( "hidden" ) ) isHidden = (bool)ht["hidden"]; if( ht.Contains( "completed" ) ) completed = (bool)ht["completed"]; if( ht.Contains( "percentComplete" ) ) percentComplete = float.Parse( ht["percentComplete"].ToString() ); // grab and convert the date if( ht.Contains( "lastReportedDate" ) ) { double timeSinceEpoch = double.Parse( ht["lastReportedDate"].ToString() ); DateTime intermediate = new DateTime( 1970, 1, 1, 0, 0, 0, DateTimeKind.Utc ); lastReportedDate = intermediate.AddSeconds( timeSinceEpoch ); } }
public void TestGetIsReadOnlyBasic() { string strValue; Hashtable dic1; //[] Vanila test case - Hashtable doesnt have means of getting a readonly HT dic1 = new Hashtable(); for (int i = 0; i < 10; i++) { strValue = "string_" + i; dic1.Add(i, strValue); } for (int i = 0; i < 10; i++) { Assert.True(dic1.Contains(i)); } Assert.False(dic1.IsReadOnly); //we'll make sure by doing a modifiable things!! dic1.Remove(0); Assert.False(dic1.Contains(0)); }
protected void BtDeal_Click(object sender, EventArgs e) { string redto=null; GetGirdViewInfo(ref itemID, ref funcID, ref mainType, ref status); Hashtable ht = new Hashtable(); if ("0".Equals(status)) ht = DataServ.OpraTellerWorkBenchPage; else ht = DataServ.AuditTellerWorkBenchPage; if (ht.Contains(funcID)) { redto = ht[funcID].ToString(); Response.Redirect(redto + "?ItemID=" + itemID + "&mainType="+ mainType + "&status="+ status + "&funcID="+funcID); } }
public static void Main(String[] args) { int SIZE = int.Parse(args[0]); IDictionary hash = new Hashtable(2*SIZE); IDictionary tree = new SortedList(); Random random = new Random(); int i = random.Next(5000000); for (int j = 0; j < SIZE; j++) { if(!hash.Contains(i)) hash.Add(i, i); if(!tree.Contains(i)) tree.Add(i, i); } Console.WriteLine("Hash for {0}", time(hash, TEST)); Console.WriteLine("Tree for {0}", time(tree, TEST)); }
public static void Main(String[] args) { int n = int.Parse(Console.ReadLine()), c = 0; Hashtable h = new Hashtable(); for (int i = 0; i < n; i++) { string s = Console.ReadLine(); if (h.Contains(s)) { ++c; } else { h.Add(s, null); } } Console.WriteLine(c); }
public static Vector6 createWithHashtable(Hashtable jsonHash, string type) { Vector6 v6 = new Vector6(); if(jsonHash.Contains(type+"_PHY")) v6.PHY = float.Parse(jsonHash[type + "_PHY"].ToString()); if(jsonHash.Contains(type+"_IMP")) v6.IMP = float.Parse(jsonHash[type + "_IMP"].ToString()); if(jsonHash.Contains(type+"_PSY")) v6.PSY = float.Parse(jsonHash[type + "_PSY"].ToString()); if(jsonHash.Contains(type+"_EXP")) v6.EXP = float.Parse(jsonHash[type + "_EXP"].ToString()); if(jsonHash.Contains(type+"_ENG")) v6.ENG = float.Parse(jsonHash[type + "_ENG"].ToString()); if(jsonHash.Contains(type+"_MAG")) v6.MAG = float.Parse(jsonHash[type + "_MAG"].ToString()); return v6; }
public void AssignmentRuleElement(Hashtable attrs) { String variable; SBase parameter = null; if (attrs.Contains("variable")) { variable = (String)attrs["variable"]; if (this.model.findObject(variable) != null) parameter = (SBase)this.model.findObject(variable); } // else throw exception on required attribute AssignmentRule assignmentRule = new AssignmentRule(this.model, parameter); this.model.listOfRules.Add(assignmentRule); elementStack.Push(assignmentRule); }
public GameCenterChallenge( Hashtable ht ) { if( ht.Contains( "issuingPlayerID" ) ) issuingPlayerID = ht["issuingPlayerID"] as string; if( ht.Contains( "receivingPlayerID" ) ) receivingPlayerID = ht["receivingPlayerID"] as string; if( ht.Contains( "state" ) ) { var intState = int.Parse( ht["state"].ToString() ); state = (GameCenterChallengeState)intState; } // grab and convert the dates if( ht.Contains( "issueDate" ) ) { var timeSinceEpoch = double.Parse( ht["issueDate"].ToString() ); var intermediate = new DateTime( 1970, 1, 1, 0, 0, 0, DateTimeKind.Utc ); issueDate = intermediate.AddSeconds( timeSinceEpoch ); } if( ht.Contains( "completionDate" ) ) { var timeSinceEpoch = double.Parse( ht["completionDate"].ToString() ); var intermediate = new DateTime( 1970, 1, 1, 0, 0, 0, DateTimeKind.Utc ); completionDate = intermediate.AddSeconds( timeSinceEpoch ); } if( ht.Contains( "message" ) ) message = ht["message"] as string; // do we have a score or an achievement? if( ht.Contains( "score" ) ) score = new GameCenterScore( ht["score"] as Hashtable ); if( ht.Contains( "achievement" ) ) achievement = new GameCenterAchievement( ht["achievement"] as Hashtable ); }
public static object Fun_DataModule_Name(BdoScriptwordFunctionScope scope) { string text = scope?.Scriptword?.Parameters?.GetObjectAtIndex(0)?.ToString(); if (scope?.Scriptword.Parent?.Item != null) { if (scope.Scope?.Context != null) { var datamoduleName = scope?.Scriptword.Parent.Item.ToString().ToUpper(); Hashtable dataModuleInstances = (Hashtable)scope.Scope.Context.GetSystemItem("DatabaseNames"); if (dataModuleInstances?.Contains(datamoduleName) == true) { text += dataModuleInstances[datamoduleName]; } } } return(text); }
private string GetSavedFileName(FileUpload f1) { string medical_id = DateTime.Now.ToString("yyyyMMddHmms"); string doc_code = "0000"; string immagefille = ""; string imagefile = null; string ext = System.IO.Path.GetExtension(f1.PostedFile.FileName); if (f1.HasFile) { Hashtable fed = new Hashtable(); fed.Add("0000", "0000"); if (fed.Contains(doc_code)) { if ((ext.ToUpper() == ".JPG") || (ext.ToUpper() == ".PNG")) { imagefile = medical_id + "_" + doc_code; //file.SaveAs(Page.MapPath("~/DOCUMENT_REPO/" + imagefile + ".jpg")); f1.SaveAs(Page.MapPath("/MemberPics/" + imagefile + ext)); string file = Page.MapPath("/MemberPics/" + imagefile + ext); immagefille = imagefile + ext; // Util.ResizeMemberImage(file, file, 0, 0, true); return immagefille; } else { //msgBox1.alert("Please Passport can not be in other format than .jpg"); return string.Empty; } } } else { imagefile = "no_image.jpg"; return imagefile; } return string.Empty; }
/// <summary> /// Similar to ScaleTo but incredibly less expensive for usage inside the Update function or similar looping situations involving a "live" set of changing values with FULL customization options. Does not utilize an EaseType. /// </summary> /// <param name="scale"> /// A <see cref="Transform"/> or <see cref="Vector3"/> for the final scale. /// </param> /// <param name="x"> /// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis. /// </param> /// <param name="y"> /// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis. /// </param> /// <param name="z"> /// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis. /// </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> public static void ScaleUpdate(GameObject target, Hashtable args) { CleanArgs(args); float time; Vector3[] vector3s = new Vector3[4]; //set smooth time: if(args.Contains("time")){ time=(float)args["time"]; time*=Defaults.updateTimePercentage; }else{ time=Defaults.updateTime; } //init values: vector3s[0] = vector3s[1] = target.transform.localScale; //to values: if (args.Contains("scale")) { if (args["scale"].GetType() == typeof(Transform)){ Transform trans = (Transform)args["scale"]; vector3s[1]=trans.localScale; }else if(args["scale"].GetType() == typeof(Vector3)){ vector3s[1]=(Vector3)args["scale"]; } }else{ if (args.Contains("x")) { vector3s[1].x=(float)args["x"]; } if (args.Contains("y")) { vector3s[1].y=(float)args["y"]; } if (args.Contains("z")) { vector3s[1].z=(float)args["z"]; } } //calculate: vector3s[3].x=Mathf.SmoothDamp(vector3s[0].x,vector3s[1].x,ref vector3s[2].x,time); vector3s[3].y=Mathf.SmoothDamp(vector3s[0].y,vector3s[1].y,ref vector3s[2].y,time); vector3s[3].z=Mathf.SmoothDamp(vector3s[0].z,vector3s[1].z,ref vector3s[2].z,time); //apply: target.transform.localScale=vector3s[3]; }
public static string GetVar(string a_key, string a_emptyReturn = "") { LoadConfig(); return((!m_cfgVars.Contains(a_key)) ? a_emptyReturn : ((string)m_cfgVars[a_key])); }
private void ExecuteThreadInAppDomain() { byte[] rawThread = null; try { logger.Info("Started ExecuteThreadInAppDomain..."); logger.Info(string.Format("executing grid thread # {0}.{1}", _CurTi.ApplicationId, _CurTi.ThreadId)); string appDir = GetApplicationDirectory(_CurTi.ApplicationId); logger.Debug("AppDir on executor=" + appDir); if (!_GridAppDomains.Contains(_CurTi.ApplicationId)) { lock (_GridAppDomains) { // make sure that by the time the lock was acquired the app domain is still not created if (!_GridAppDomains.Contains(_CurTi.ApplicationId)) { // create application domain for newly encountered grid application logger.Debug("app dir on executor: " + appDir); //before initializing clear dir.. foreach (string F in Directory.GetFiles(appDir)) { try //becoz exception should not be created for an issue as small as this { File.Delete(F); } catch (Exception ex) { } } FileDependencyCollection manifest = Manager.Executor_GetApplicationManifest(Credentials, _CurTi.ApplicationId); if (manifest != null) { foreach (FileDependency dep in manifest) { try //so that IO error does not occur if files already exist { logger.Debug("Unpacking file: " + dep.FileName + " to " + appDir); dep.UnPackToFolder(appDir); } catch (Exception ex) { } } } else { logger.Warn("Executor_GetApplicationManifest from the Manager returned null"); } initialize_GridThreadExecutor(); _GridAppDomains.Add( _CurTi.ApplicationId, new GridAppDomain(GridThreadApplicationDomain, GridThreadExecutor) ); logger.Info("Created app domain, policy, got instance of GridAppDomain and added to hashtable...all done once for this application"); } else { logger.Info("I got the lock but this app domain is already created."); } } } //get thread from manager GridAppDomain gad = (GridAppDomain)_GridAppDomains[_CurTi.ApplicationId]; //if we have an exception in the secondary appdomain, it will raise an exception in this method, since the cross-app-domain call //uses remoting internally, and it is just as if a remote method has caused an exception. we have a handler for that below anyway. rawThread = Manager.Executor_GetThread(Credentials, _CurTi); logger.Debug("Got thread from manager. executing it: " + _CurTi.ThreadId); //execute it byte[] finishedThread = gad.Executor.ExecuteThread(rawThread); logger.Info(string.Format("ExecuteThread returned for thread # {0}.{1}", _CurTi.ApplicationId, _CurTi.ThreadId)); //set its status to finished Manager.Executor_SetFinishedThread(Credentials, _CurTi, finishedThread, null); logger.Info(string.Format("Finished executing grid thread # {0}.{1}", _CurTi.ApplicationId, _CurTi.ThreadId)); } catch (ThreadAbortException) { if (_CurTi != null) { logger.Warn(string.Format("aborted grid thread # {0}.{1}", _CurTi.ApplicationId, _CurTi.ThreadId)); } else { logger.Warn(string.Format("aborted grid thread # {0}.{1}", null, null)); } Thread.ResetAbort(); } catch (Exception e) { logger.Warn(string.Format("grid thread # {0}.{1} failed ({2})", _CurTi.ApplicationId, _CurTi.ThreadId, e.GetType()), e); try { //some exceptions such as Win32Exception caused problems when passed directly into this method. //so better create another new exception object and send it over. Exception eNew = new Exception(e.ToString()); Manager.Executor_SetFinishedThread(Credentials, _CurTi, rawThread, eNew); } catch (Exception ex1) { if (_CurTi != null) { logger.Warn("Error trying to set failed thread for App: " + _CurTi.ApplicationId + ", thread=" + _CurTi.ThreadId + ". Original Exception = \n" + e.ToString(), ex1); } else { logger.Warn("Error trying to set failed thread: Original exception = " + e.ToString(), ex1); } } } finally { _CurTi = null; _ReadyToExecute.Set(); logger.Info("Exited ExecuteThreadInAppDomain..."); } }
private static void Main(string[] args) { // This local variable controls if the AnalyzeAllScans method is called bool analyzeScans = false; string rawDiagVersion = "0.0.35"; // Get the memory used at the beginning of processing Process processBefore = Process.GetCurrentProcess(); long memoryBefore = processBefore.PrivateMemorySize64 / 1024; try { // Check to see if the RAW file name was supplied as an argument to the program string filename = string.Empty; string mode = string.Empty; Hashtable hashtable = new Hashtable() { { "version", "print version information." }, { "info", "print the raw file's meta data." }, { "xic", "prints xic unfiltered." }, }; if (args.Length > 0) { filename = args[0]; if (args.Length == 1) { Console.WriteLine("rawDiag version = {}", rawDiagVersion); Console.WriteLine("missing mode argument. setting to mode = 'info'."); mode = "info"; } else { mode = args[1]; } if (!hashtable.Contains(mode)) { Console.WriteLine("rawDiag version = {}", rawDiagVersion); Console.WriteLine("mode '{0}' not allowed. Please use one of the following modes:", mode); foreach (var k in hashtable.Keys) { Console.WriteLine("{0} - {1}", k.ToString(), hashtable[k].ToString()); } Environment.Exit(1); } } if (string.IsNullOrEmpty(filename)) { Console.WriteLine("No RAW file specified!"); return; } // Check to see if the specified RAW file exists if (!File.Exists(filename)) { Console.WriteLine("rawDiag version = {}", rawDiagVersion); Console.WriteLine(@"The file doesn't exist in the specified location - " + filename); return; } // Create the IRawDataPlus object for accessing the RAW file var rawFile = RawFileReaderAdapter.FileFactory(filename); if (!rawFile.IsOpen || rawFile.IsError) { Console.WriteLine("Unable to access the RAW file using the RawFileReader class!"); return; } // Check for any errors in the RAW file if (rawFile.IsError) { Console.WriteLine("Error opening ({0}) - {1}", rawFile.FileError, filename); return; } // Check if the RAW file is being acquired if (rawFile.InAcquisition) { Console.WriteLine("RAW file still being acquired - " + filename); return; } if (mode == "info") { // Get the number of instruments (controllers) present in the RAW file and set the // selected instrument to the MS instrument, first instance of it Console.WriteLine("Number of instruments: {0}", rawFile.InstrumentCount); } rawFile.SelectInstrument(Device.MS, 1); //Console.WriteLine("DEBUG {0}", rawFile.GetInstrumentMethod(3).ToString()); // Get the first and last scan from the RAW file int firstScanNumber = rawFile.RunHeaderEx.FirstSpectrum; int lastScanNumber = rawFile.RunHeaderEx.LastSpectrum; // Get the start and end time from the RAW file double startTime = rawFile.RunHeaderEx.StartTime; double endTime = rawFile.RunHeaderEx.EndTime; if (mode == "systeminfo") { Console.WriteLine("raw file name: {0}", Path.GetFileName(filename)); // Print some OS and other information Console.WriteLine("System Information:"); Console.WriteLine(" OS Version: " + Environment.OSVersion); Console.WriteLine(" 64 bit OS: " + Environment.Is64BitOperatingSystem); Console.WriteLine(" Computer: " + Environment.MachineName); Console.WriteLine(" number Cores: " + Environment.ProcessorCount); Console.WriteLine(" Date: " + DateTime.Now); } if (mode == "info") { // Get some information from the header portions of the RAW file and display that information. // The information is general information pertaining to the RAW file. Console.WriteLine("General File Information:"); Console.WriteLine(" RAW file: " + Path.GetFileName(rawFile.FileName)); Console.WriteLine(" RAW file version: " + rawFile.FileHeader.Revision); Console.WriteLine(" Creation date: " + rawFile.FileHeader.CreationDate); Console.WriteLine(" Operator: " + rawFile.FileHeader.WhoCreatedId); Console.WriteLine(" Number of instruments: " + rawFile.InstrumentCount); Console.WriteLine(" Description: " + rawFile.FileHeader.FileDescription); Console.WriteLine(" Instrument model: " + rawFile.GetInstrumentData().Model); Console.WriteLine(" Instrument name: " + rawFile.GetInstrumentData().Name); // Console.WriteLine(" Instrument method: {0}", rawFile.GetAllInstrumentFriendlyNamesFromInstrumentMethod().Length); Console.WriteLine(" Serial number: " + rawFile.GetInstrumentData().SerialNumber); Console.WriteLine(" Software version: " + rawFile.GetInstrumentData().SoftwareVersion); Console.WriteLine(" Firmware version: " + rawFile.GetInstrumentData().HardwareVersion); Console.WriteLine(" Units: " + rawFile.GetInstrumentData().Units); Console.WriteLine(" Mass resolution: {0:F3} ", rawFile.RunHeaderEx.MassResolution); Console.WriteLine(" Number of scans: {0}", rawFile.RunHeaderEx.SpectraCount); Console.WriteLine(" Number of ms2 scans: {0}", Enumerable .Range(1, lastScanNumber - firstScanNumber) .Count(x => rawFile.GetFilterForScanNumber(x) .ToString() .Contains("Full ms2"))); Console.WriteLine(" Scan range: [{0}, {1}]", firstScanNumber, lastScanNumber); Console.WriteLine(" Time range: [{0:F2}, {1:F2}]", startTime, endTime); Console.WriteLine(" Mass range: [{0:F4}, {1:F4}]", rawFile.RunHeaderEx.LowMass, rawFile.RunHeaderEx.HighMass); Console.WriteLine(); // Get information related to the sample that was processed Console.WriteLine("Sample Information:"); Console.WriteLine(" Sample name: " + rawFile.SampleInformation.SampleName); Console.WriteLine(" Sample id: " + rawFile.SampleInformation.SampleId); Console.WriteLine(" Sample type: " + rawFile.SampleInformation.SampleType); Console.WriteLine(" Sample comment: " + rawFile.SampleInformation.Comment); Console.WriteLine(" Sample vial: " + rawFile.SampleInformation.Vial); Console.WriteLine(" Sample volume: " + rawFile.SampleInformation.SampleVolume); Console.WriteLine(" Sample injection volume: " + rawFile.SampleInformation.InjectionVolume); Console.WriteLine(" Sample row number: " + rawFile.SampleInformation.RowNumber); Console.WriteLine(" Sample dilution factor: " + rawFile.SampleInformation.DilutionFactor); Console.WriteLine(); // Read the first instrument method (most likely for the MS portion of the instrument). // NOTE: This method reads the instrument methods from the RAW file but the underlying code // uses some Microsoft code that hasn't been ported to Linux or MacOS. Therefore this // method won't work on those platforms therefore the check for Windows. if (Environment.OSVersion.ToString().Contains("Windows")) { var deviceNames = rawFile.GetAllInstrumentNamesFromInstrumentMethod(); foreach (var device in deviceNames) { Console.WriteLine("Instrument method: " + device); } Console.WriteLine(); } } // Display all of the trailer extra data fields present in the RAW file // Get the number of filters present in the RAW file int numberFilters = rawFile.GetFilters().Count; // Get the scan filter for the first and last spectrum in the RAW file var firstFilter = rawFile.GetFilterForScanNumber(firstScanNumber); var lastFilter = rawFile.GetFilterForScanNumber(lastScanNumber); if (mode == "info") { Console.WriteLine("Filter Information:"); Console.WriteLine(" Scan filter (first scan): " + firstFilter.ToString()); Console.WriteLine(" Scan filter (last scan): " + lastFilter.ToString()); Console.WriteLine(" Total number of filters: " + numberFilters); Console.WriteLine(); // ListTrailerExtraFields(rawFile); Environment.Exit(0); } if (mode == "version") { Console.WriteLine("version={}", rawDiagVersion); Environment.Exit(0); } if (mode == "xic") { try { var inputFilename = args[2]; double ppmError = Convert.ToDouble(args[3]); var outputFilename = args[4]; List <double> massList = new List <double>(); if (File.Exists(args[2])) { foreach (var line in File.ReadAllLines(inputFilename)) { massList.Add(Convert.ToDouble(line)); } GetXIC(rawFile, -1, -1, massList, ppmError, outputFilename); } return; } catch (Exception ex) { Console.Error.WriteLine("failed to catch configfile and itol"); Console.Error.WriteLine("{}", ex.Message); return; } } } catch (Exception ex) { Console.WriteLine("Error accessing RAWFileReader library! - " + ex.Message); } // Get the memory used at the end of processing Process processAfter = Process.GetCurrentProcess(); long memoryAfter = processAfter.PrivateMemorySize64 / 1024; Console.WriteLine(); Console.WriteLine("Memory Usage:"); Console.WriteLine(" Before {0} kb, After {1} kb, Extra {2} kb", memoryBefore, memoryAfter, memoryAfter - memoryBefore); }
private static void ProcesoDir(KnowledgeBase KB, string directoryArg, string newDir, string generator, IOutputService output) { string outputFile = KB.UserDirectory + @"\KBdoctorEv2.xslt"; XslTransform xslTransform = new XslTransform(); output.AddLine("Cargando archivo xslt: " + outputFile); xslTransform.Load(outputFile); output.AddLine("Archivo xslt cargado correctamente."); string fileWildcard = @"*.xml"; var searchSubDirsArg = System.IO.SearchOption.AllDirectories; string[] xFiles = System.IO.Directory.GetFiles(directoryArg, fileWildcard, searchSubDirsArg); Hashtable colisiones = new Hashtable(); HashSet <string> colisionesStr = new HashSet <string>(); //Busco colisiones en los nombres de los archivos foreach (string x in xFiles) { string filename = Path.GetFileNameWithoutExtension(x); if (!colisiones.Contains(filename)) { List <string> paths = new List <string>(); paths.Add(x); colisiones[filename] = paths; } else { List <string> paths = (List <string>)colisiones[filename]; paths.Add(x); colisiones[filename] = paths; if (!colisionesStr.Contains(filename)) { colisionesStr.Add(filename); } } } //Me quedo sólo con el archivo más nuevo y cambio el nombre de todos los demás. foreach (string name in colisionesStr) { FileInfo newestFile = null; DateTime newestDate = new DateTime(1891, 09, 28); List <string> paths = (List <string>)colisiones[name]; List <FileInfo> oldfiles = new List <FileInfo>(); output.AddLine("Colisión en archivos: "); foreach (string path in paths) { output.AddLine("-- -- -- -- -- -- -- -" + path); FileInfo file = new FileInfo(path); if (file.LastWriteTime >= newestDate) { if (newestFile != null) { oldfiles.Add(newestFile); } newestDate = file.LastWriteTime; newestFile = file; } else { oldfiles.Add(file); } } int i = 1; foreach (FileInfo fileToRename in oldfiles) { fileToRename.MoveTo(fileToRename.DirectoryName + '\\' + Path.GetFileNameWithoutExtension(fileToRename.Name) + i.ToString() + ".oldxml"); i++; } } xFiles = System.IO.Directory.GetFiles(directoryArg, fileWildcard, searchSubDirsArg); foreach (string x in xFiles) { if (!Path.GetFileNameWithoutExtension(x).StartsWith("Gx0")) { output.AddLine("Procesando archivo: " + x); string xTxt = newDir + generator + Path.GetFileNameWithoutExtension(x) + ".nvg"; string xmlstring = Utility.AddXMLHeader(x); string newXmlFile = x.Replace(".xml", ".xxx"); File.WriteAllText(newXmlFile, xmlstring); xslTransform.Transform(newXmlFile, xTxt); File.Delete(newXmlFile); } } }
public static bool UnderEffect(Mobile m) { return(m_Table.Contains(m)); }
public bool IsHandled(TreeNode node) { return(myNodes.Contains(node)); }
private void InitList(StringCollection initFields) { this.C_LBFields.Items.Clear(); this.C_LBSelFields.Items.Clear(); if (initFields != null) { foreach (string strField in initFields) { this.C_LBSelFields.Items.Add(strField); } } else { initFields = new StringCollection(); } HashCategories.Clear(); DataSet backDataSource = Webb.Reports.DataProvider.VideoPlayBackManager.DataSource; this.cmbCategory.Visible = true; this.cmbCategory.Items.Clear(); ArrayList fieldsInAllcategories; Webb.Reports.DataProvider.WebbDataProvider PublicDataProvider = Webb.Reports.DataProvider.VideoPlayBackManager.PublicDBProvider; if (backDataSource != null && PublicDataProvider != null && PublicDataProvider.DBSourceConfig != null && PublicDataProvider.DBSourceConfig.WebbDBType == WebbDBTypes.CoachCRM && backDataSource.Tables.Count > 1) { #region add categoryies from Table ArrayList categories = new ArrayList(); string strCategoriesName = backDataSource.Tables[0].TableName; categories.Add(strCategoriesName); fieldsInAllcategories = new ArrayList(); HashCategories.Add(strCategoriesName, fieldsInAllcategories); foreach (DataRow dr in backDataSource.Tables[1].Rows) { if (dr["CurrentField"] == null || (dr["CurrentField"] is System.DBNull)) { continue; } string strTableName = dr["Category"].ToString(); string strField = dr["CurrentField"].ToString(); ArrayList fieldList; if (HashCategories.Contains(strTableName)) { fieldList = (ArrayList)HashCategories[strTableName]; if (!fieldList.Contains(strField)) { fieldList.Add(strField); } } else { fieldList = new ArrayList(); fieldList.Add(strField); categories.Add(strTableName); HashCategories.Add(strTableName, fieldList); } if (!fieldsInAllcategories.Contains(strField)) { fieldsInAllcategories.Add(strField); } } #endregion this.cmbCategory.Text = string.Empty; foreach (string strKey in categories) { this.cmbCategory.Items.Add(strKey); } this.cmbCategory.SelectedIndex = 0; } else { #region Advantage /Victory Data fieldsInAllcategories = new ArrayList(); foreach (string strfield in Webb.Data.PublicDBFieldConverter.AvialableFields) { fieldsInAllcategories.Add(strfield); //if (this.C_LBSelFields.Items.Contains(strfield)) continue; //this.C_LBFields.Items.Add(strfield); } strCategory = "[All Avaliable Fields]"; HashCategories.Add(strCategory, fieldsInAllcategories); this.cmbCategory.Items.Add(strCategory); this.cmbCategory.SelectedIndex = 0; #endregion } }
/// <include file='doc\CodeIdentifiers.uex' path='docs/doc[@for="CodeIdentifiers.IsInUse"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool IsInUse(string identifier) { return(_identifiers.Contains(identifier) || _reservedIdentifiers.Contains(identifier)); }
private static bool IsTabPending(TabInfo objTab, DNNNode objParentNode, DNNNode objRootNode, int intDepth, Hashtable objBreadCrumbs, int intLastBreadCrumbId, bool blnPOD) { // //A //| //--B //| | //| --B-1 //| | | //| | --B-1-1 //| | | //| | --B-1-2 //| | //| --B-2 //| | //| --B-2-1 //| | //| --B-2-2 //| //--C // | // --C-1 // | | // | --C-1-1 // | | // | --C-1-2 // | // --C-2 // | // --C-2-1 // | // --C-2-2 //if we aren't restricting depth then its never pending if (intDepth == -1) { return(false); } //parents level + 1 = current node level //if current node level - (roots node level) <= the desired depth then not pending if (objParentNode.Level + 1 - objRootNode.Level <= intDepth) { return(false); } //--- These checks below are here so tree becomes expands to selected node --- if (blnPOD) { //really only applies to controls with POD enabled, since the root passed in may be some node buried down in the chain //and the depth something like 1. We need to include the appropriate parent's and parent siblings //Why is the check for POD required? Well to allow for functionality like RootOnly requests. We do not want any children //regardless if they are a breadcrumb //if tab is in the breadcrumbs then obviously not pending if (objBreadCrumbs.Contains(objTab.TabID)) { return(false); } //if parent is in the breadcrumb and it is not the last breadcrumb then not pending //in tree above say we our breadcrumb is (A, B, B-2) we want our tree containing A, B, B-2 AND B-1 AND C since A and B are expanded //we do NOT want B-2-1 and B-2-2, thus the check for Last Bread Crumb if (objBreadCrumbs.Contains(objTab.ParentId) && intLastBreadCrumbId != objTab.ParentId) { return(false); } } return(true); }
private void FastFilesChangeName() { var dialog = new System.Windows.Forms.FolderBrowserDialog(); Regex regex = new Regex("^(\\s|\\S)+\\.(jpg|png|JPG|PNG)+$"); int i = 1; if (dialog.ShowDialog() != System.Windows.Forms.DialogResult.OK) { return; } Hashtable hashtable = new Hashtable(); List <long> problemSize = new List <long>(); HashSet <string> md5Set = new HashSet <string>(); foreach (string file in Directory.GetFiles(dialog.SelectedPath)) { if (!regex.IsMatch(file)) { continue; } var t_f = File.OpenRead(file); var size = t_f.Length; t_f.Close(); if (hashtable.Contains(size)) { problemSize.Add(size); var list = (List <string>)hashtable[size]; list.Add(file); continue; } hashtable.Add(size, new List <string>() { file }); } foreach (var size in problemSize) { foreach (var name in (List <string>)hashtable[size]) { if (!md5Set.Add(MD5File(name))) { File.Delete(name); continue; } } } foreach (string file in Directory.GetFiles(dialog.SelectedPath)) { if (!regex.IsMatch(file)) { continue; } var fnS = file.Split('\\'); var filename = fnS[fnS.Length - 1]; var backname = filename.Split('.')[1]; var s = file.Replace(filename, "tmpFileByACN_" + i++.ToString() + "." + backname); File.Move(file, s); } foreach (string file in Directory.GetFiles(dialog.SelectedPath)) { File.Move(file, file.Replace("tmpFileByACN_", "")); } MessageBox.Show("修改了" + i.ToString() + "个数据"); }
void Update() { #if UNITY_EDITOR if (!Application.isPlaying) { // See if anything has changed since this gets called whenever anything gets touched. var fields = GetType().GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); bool modified = false; if (values == null) { modified = true; } else { foreach (var f in fields) { if (!values.Contains(f)) { modified = true; break; } var v0 = values[f]; var v1 = f.GetValue(this); if (v1 != null) { if (!v1.Equals(v0)) { modified = true; break; } } else if (v0 != null) { modified = true; break; } } } if (modified) { if (renderModelName != modelOverride) { renderModelName = modelOverride; SetModel(modelOverride); } values = new Hashtable(); foreach (var f in fields) { values[f] = f.GetValue(this); } } return; // Do not update transforms (below) when not playing in Editor (to avoid keeping OpenVR running all the time). } #endif // Update component transforms dynamically. if (updateDynamically) { UpdateComponents(OpenVR.RenderModels); } }
//catalog new tween and add component phase of iTween: static void Launch(GameObject target, Hashtable args) { if(!args.Contains("id")){ args["id"] = GenerateID(); } if(!args.Contains("target")){ args["target"] = target; } tweens.Insert(0,args); target.AddComponent("iTween"); }
/// ----------------------------------------------------------------------------- /// <summary> /// Assigns common properties from passed in tab to newly created DNNNode that is added to the passed in DNNNodeCollection. /// </summary> /// <param name="objTab">Tab to base DNNNode off of.</param> /// <param name="objNodes">Node collection to append new node to.</param> /// <param name="objBreadCrumbs">Hashtable of breadcrumb IDs to efficiently determine node's BreadCrumb property.</param> /// <param name="objPortalSettings">Portal settings object to determine if node is selected.</param> /// <param name="eToolTips"></param> /// <remarks> /// Logic moved to separate sub to make GetNavigationNodes cleaner. /// </remarks> /// ----------------------------------------------------------------------------- private static void AddNode(TabInfo objTab, DNNNodeCollection objNodes, Hashtable objBreadCrumbs, PortalSettings objPortalSettings, ToolTipSource eToolTips, IDictionary <string, DNNNode> nodesLookup) { var objNode = new DNNNode(); if (objTab.Title == "~") // NEW! { // A title (text) of ~ denotes a break objNodes.AddBreak(); } else { // assign breadcrumb and selected properties if (objBreadCrumbs.Contains(objTab.TabID)) { objNode.BreadCrumb = true; if (objTab.TabID == objPortalSettings.ActiveTab.TabID) { objNode.Selected = true; } } if (objTab.DisableLink) { objNode.Enabled = false; } objNode.ID = objTab.TabID.ToString(); objNode.Key = objNode.ID; objNode.Text = objTab.LocalizedTabName; objNode.NavigateURL = objTab.FullUrl; objNode.ClickAction = eClickAction.Navigate; objNode.Image = objTab.IconFile; objNode.LargeImage = objTab.IconFileLarge; switch (eToolTips) { case ToolTipSource.TabName: objNode.ToolTip = objTab.LocalizedTabName; break; case ToolTipSource.Title: objNode.ToolTip = objTab.Title; break; case ToolTipSource.Description: objNode.ToolTip = objTab.Description; break; } bool newWindow = false; if (objTab.TabSettings["LinkNewWindow"] != null && bool.TryParse((string)objTab.TabSettings["LinkNewWindow"], out newWindow) && newWindow) { objNode.Target = "_blank"; } objNodes.Add(objNode); if (!nodesLookup.ContainsKey(objNode.ID)) { nodesLookup.Add(objNode.ID, objNode); } } }
public void getLibPrivil() { try { string libcodecollection = ""; string coll_Code = Convert.ToString(ddlCollege.SelectedValue); string sql = ""; string GrpUserVal = ""; string GrpCode = ""; string LibCollection = ""; Hashtable hsLibcode = new Hashtable(); if (singleUser.ToLower() == "true") { sql = "SELECT DISTINCT lib_code from lib_privileges where user_code=" + userCode + " and lib_code in (select lib_code from library where college_code=" + coll_Code + ")"; ds.Clear(); ds = d2.select_method_wo_parameter(sql, "text"); } else { string[] groupUser = groupUserCode.Split(';'); if (groupUser.Length > 0) { if (groupUser.Length == 1) { sql = "SELECT DISTINCT lib_code from lib_privileges where group_code=" + groupUser[0] + ""; ds.Clear(); ds = d2.select_method_wo_parameter(sql, "text"); } if (groupUser.Length > 1) { for (int i = 0; i < groupUser.Length; i++) { GrpUserVal = groupUser[i]; if (!GrpCode.Contains(GrpUserVal)) { if (GrpCode == "") { GrpCode = GrpUserVal; } else { GrpCode = GrpCode + "','" + GrpUserVal; } } } sql = "SELECT DISTINCT lib_code from lib_privileges where group_code in ('" + GrpCode + "')"; ds.Clear(); ds = d2.select_method_wo_parameter(sql, "text"); } } } if (ds.Tables[0].Rows.Count == 0) { libcodecollection = "WHERE lib_code IN (-1)"; goto aa; } if (ds.Tables[0].Rows.Count > 0) { for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { string codeCollection = Convert.ToString(ds.Tables[0].Rows[i]["lib_code"]); if (!hsLibcode.Contains(codeCollection)) { hsLibcode.Add(codeCollection, "LibCode"); if (libcodecollection == "") { libcodecollection = codeCollection; } else { libcodecollection = libcodecollection + "','" + codeCollection; } } } } //libcodecollection = Left(libcodecollection, Len(libcodecollection) - 1); libcodecollection = "WHERE lib_code IN ('" + libcodecollection + "')"; aa: LibCollection = libcodecollection; Library(LibCollection); } catch (Exception ex) { } }
//生成试题 public static void a(int num, int quantity, int scope) { //利用哈希表进行数据的存储与查 Hashtable fourOperations = new Hashtable(); Console.WriteLine("正在生成题目,请稍等"); switch (num) { case 1: #region 四年级题目 for (int i = 0; i < quantity; i++) { string topic = (Class3.topicfour(scope)); string answer = (consequence(topic)); if (fourOperations.Contains(topic)) { i--; break; } if (Convert.ToDouble(answer) > 0) { fourOperations.Add(topic, answer); } else { i--; } } break; #endregion case 2: #region 五年级题目 for (int i = 0; i < quantity; i++) { string topic = (Class3.topicfive(scope)); string answer = (consequence(topic)); if (fourOperations.Contains(topic)) { i--; break; } if (Convert.ToDouble(answer) > 0) { fourOperations.Add(topic, answer); } else { i--; } } break; #endregion case 3: #region 六年级题目 for (int i = 0; i < quantity; i++) { Console.WriteLine(Class3.topicssix(scope)); } break; #endregion case 4: #region 混合运算题目 for (int i = 0; i < quantity; i++) { Console.WriteLine(Class3.mixture(scope)); } #endregion break; } #region 写入TXT //题目的TX FileStream fs = new FileStream("D:\\四则运算\\四则运算题目.txt", FileMode.Create); //答案的TXT FileStream da = new FileStream("D:\\四则运算\\四则运算的答案.txt", FileMode.Create); int plus = 1; foreach (string a in fourOperations.Keys) { //获得字节数组 byte[] data = System.Text.Encoding.Default.GetBytes("第" + plus + "题." + a + " =" + "\r\n"); //开始写入 fs.Write(data, 0, data.Length); plus++; } //清空缓冲区、关闭流 fs.Flush(); fs.Close(); plus = 1; foreach (string b in fourOperations.Values) { //获得字节数组 byte[] data = System.Text.Encoding.Default.GetBytes("第" + plus + "题:" + b + "\r\n"); //开始写入 da.Write(data, 0, data.Length); plus++; } //清空缓冲区、关闭流 da.Flush(); da.Close(); #endregion Console.WriteLine("生成完毕"); Console.ReadKey(); }
private void cutWord(List <string> Lterms, List <bool> Lrelevant) { if (month.Contains(w)) { b[2] = true; w = month[w] + ""; } if (lw.Length != 0) { if (lb[2] && b[1] && !b[4] && !b[5] && !b[6]) { if (w.Length == 2 && (w[0] == '0' || w[0] == '1' || w[0] == '2' || w[0] == '3')) { lw = w + "/" + lw; } else { lw = lw + "/" + w; } w = ""; } else if (b[2] && lb[1] && !lb[4]) { if (lw.Length == 2 && (lw[0] == '0' || lw[0] == '1' || lw[0] == '2' || lw[0] == '3')) { lw = lw + "/" + w; } else { lw = w + "/" + lw; } lb[0] = b[0]; lb[1] = b[1]; lb[2] = b[2]; lb[3] = b[3]; lb[4] = b[4]; w = ""; } else if (lb[1] && w.Length > 6 && w[0] == 'p' && w[1] == 'e' && w[2] == 'r' && w[3] == 'c' && w[4] == 'e' && w[5] == 'n' && w[6] == 't') { add(Lterms, Lrelevant, lw + " percent"); lw = ""; lb[1] = false; lb[4] = false;//rest(lb); w = ""; } else if (lb[3] && b[3]) { add(Lterms, Lrelevant, lw); add(Lterms, Lrelevant, w); add(Lterms, Lrelevant, lw + " " + w); lw = ""; lb[0] = false; lb[2] = false; lb[3] = false;//rest(lb); w = ""; } else { add(Lterms, Lrelevant, lw); lw = ""; lb[0] = false; lb[1] = false; lb[2] = false; lb[3] = false; lb[4] = false; } } if (w.Length == 0) { ; } else if (b[0]) { if (b[2] || b[3]) { lw = w; lb[0] = b[0]; lb[1] = b[1]; lb[2] = b[2]; lb[3] = b[3]; lb[4] = b[4]; } else { add(Lterms, Lrelevant, w); } } else if (b[1]) { if (b[4]) { try { double d = Convert.ToDouble(w); if ((int)(d * 1000) % 10 == 0) { lw = "" + ((double)((int)(d * 100))) / 100; } else { lw = "" + ((double)((int)(d * 100 + 1))) / 100; } lb[0] = b[0]; lb[1] = b[1]; lb[2] = b[2]; lb[3] = b[3]; lb[4] = b[4]; } catch (Exception) { add(Lterms, Lrelevant, w); } } else if (b[5]) { try { double d = Convert.ToDouble(w.Split('/')[0]) / Convert.ToDouble(w.Split('/')[1]); if ((int)(d * 1000) % 10 == 0) { add(Lterms, Lrelevant, "" + ((double)((int)(d * 100))) / 100); } else { add(Lterms, Lrelevant, "" + ((double)((int)(d * 100 + 1))) / 100); } } catch (Exception) { add(Lterms, Lrelevant, w); } } else if (b[6]) { add(Lterms, Lrelevant, w + " percent"); } else { lw = w; lb[0] = b[0]; lb[1] = b[1]; lb[2] = b[2]; lb[3] = b[3]; lb[4] = b[4]; } } rest(b); w = ""; }
/// <summary> /// Adds the table comparison for matching objects. /// </summary> /// <param name="hashtable">Left side table</param> /// <param name="hashtableCompare">Right side table</param> /// <param name="titleFormat">Title format string</param> /// <param name="attachments">If true, the HTML code is kept (attachment comparison)</param> /// <param name="renderOnlyFirstTitle">If true, only first title is rendered</param> protected void AddTableComparison(Hashtable hashtable, Hashtable hashtableCompare, string titleFormat, bool attachments, bool renderOnlyFirstTitle) { TableCell valueCell = new TableCell(); TableCell valueCompare = new TableCell(); TableCell labelCell = new TableCell(); TextComparison comparefirst = null; TextComparison comparesecond = null; bool firstTitle = true; // Go through left column regions if (hashtable != null) { foreach (DictionaryEntry entry in hashtable) { object value = entry.Value; if (value != null) { // Initialize comparators comparefirst = new TextComparison(); comparefirst.SynchronizedScrolling = false; comparesecond = new TextComparison(); comparesecond.SynchronizedScrolling = false; comparesecond.RenderingMode = TextComparisonTypeEnum.DestinationText; if (attachments) { comparefirst.IgnoreHTMLTags = true; comparefirst.ConsiderHTMLTagsEqual = true; comparesecond.IgnoreHTMLTags = true; } comparefirst.PairedControl = comparesecond; // Initialize cells valueCell = new TableCell(); valueCompare = new TableCell(); labelCell = new TableCell(); string key = ValidationHelper.GetString(entry.Key, null); string strValue = ValidationHelper.GetString(value, null); if (firstTitle || !renderOnlyFirstTitle) { labelCell.Text = String.Format(titleFormat, DictionaryHelper.GetFirstKey(key)); firstTitle = false; } if (attachments) { comparefirst.SourceText = strValue; } else { comparefirst.SourceText = HttpUtility.HtmlDecode(HTMLHelper.StripTags(strValue, false)); } if ((hashtableCompare != null) && hashtableCompare.Contains(key)) { // Compare to the existing other version string compareKey = ValidationHelper.GetString(hashtableCompare[key], null); if (attachments) { comparefirst.DestinationText = compareKey; } else { comparefirst.DestinationText = HttpUtility.HtmlDecode(HTMLHelper.StripTags(compareKey, false)); } hashtableCompare.Remove(key); } else { // Compare to an empty string comparefirst.DestinationText = ""; } // Do not balance content if too short if (attachments) { comparefirst.BalanceContent = false; } else if (Math.Max(comparefirst.SourceText.Length, comparefirst.DestinationText.Length) < 100) { comparefirst.BalanceContent = false; } // Create cell comparison valueCell.Controls.Add(comparefirst); valueCompare.Controls.Add(comparesecond); AddRow(labelCell, valueCell, valueCompare, false, null, even); even = !even; } } } // Go through right column regions which left if (hashtableCompare != null) { foreach (DictionaryEntry entry in hashtableCompare) { object value = entry.Value; if (value != null) { // Initialize comparators comparefirst = new TextComparison(); comparefirst.SynchronizedScrolling = false; comparesecond = new TextComparison(); comparesecond.SynchronizedScrolling = false; comparesecond.RenderingMode = TextComparisonTypeEnum.DestinationText; comparefirst.PairedControl = comparesecond; if (attachments) { comparefirst.IgnoreHTMLTags = true; comparefirst.ConsiderHTMLTagsEqual = true; comparesecond.IgnoreHTMLTags = true; } // Initialize cells valueCell = new TableCell(); valueCompare = new TableCell(); labelCell = new TableCell(); if (firstTitle || !renderOnlyFirstTitle) { labelCell.Text = String.Format(titleFormat, DictionaryHelper.GetFirstKey(ValidationHelper.GetString(entry.Key, null))); firstTitle = false; } comparefirst.SourceText = ""; string strValue = ValidationHelper.GetString(value, null); if (attachments) { comparefirst.DestinationText = strValue; } else { comparefirst.DestinationText = HttpUtility.HtmlDecode(HTMLHelper.StripTags(strValue, false)); } if (attachments) { comparefirst.BalanceContent = false; } else if (Math.Max(comparefirst.SourceText.Length, comparefirst.DestinationText.Length) < 100) { comparefirst.BalanceContent = false; } // Create cell comparison valueCell.Controls.Add(comparefirst); valueCompare.Controls.Add(comparesecond); AddRow(labelCell, valueCell, valueCompare, false, null, even); even = !even; } } } }
//--------------------------------------- Private Method private static void _OnPacketUdpAttrival(PacketUDP packet) { if (P2P.IsTerminate) { return; } that.DebugAndLog("PacketUDP Arrvial from: " + packet.IpAddress + ":" + packet.Port.ToString()); /* PreCheck if packet is JsonRPC or NOT? */ Hashtable hData = null; bool isResponse = false; try { JsonSerializerSettings jsetting = new JsonSerializerSettings(); jsetting.MaxDepth = 1; hData = JsonConvert.DeserializeObject <Hashtable>( Encoding.Default.GetString(packet.DataByteArray), jsetting); // Check Protocol Version if (!hData.Contains(KW.JsonRpc)) { return; } if (!hData[KW.JsonRpc].ToString().Trim().Equals(KW.RpcVersion20)) { return; } // Check ID if (!hData.Contains(KW.ID)) { return; } int id = int.Parse((string)hData[KW.ID]); if (id < 0) { return; } // Check Param or Result if (!hData.Contains(KW.Method)) { if (!hData.Contains(KW.Result)) { return; } else { isResponse = true; } // Response Must have Result } else if (!hData.Contains(KW.Params)) { return; } else { isResponse = false; } // Method Must have Param } catch (Exception ex) { that.DebugAndLog("Cannot decode packet to HashingTable"); that.DebugAndLog(ex.Message); return; } // Evertything OK, Can Push This Data/Packet to process that.DebugAndLog("Push PeerDataMessage to ProcessQueue"); lock (queDataMessage.SyncRoot) { queDataMessage.Enqueue(new PeerDataMessage(packet, hData, isResponse)); trickDataMessage.Set(); } }
public bool Contains(string ID) { return(userIDSet.Contains(ID)); }
public Type GetType(string name, bool throwOnError, bool ignoreCase) { Type result = null; // Check type cache first if (cachedTypes == null) { cachedTypes = Hashtable.Synchronized(new Hashtable(StringComparer.Ordinal)); } if (cachedTypes.Contains(name)) { result = cachedTypes[name] as Type; return(result); } // Missed in cache, try to resolve the type from the reference assemblies. if (name.IndexOf(',') != -1) { result = Type.GetType(name, false, ignoreCase); } if (result == null && names != null) { // // If the type is assembly qualified name, we sort the assembly names // to put assemblies with same name in the front so that they can // be searched first. int pos = name.IndexOf(','); if (pos > 0 && pos < name.Length - 1) { string fullName = name.Substring(pos + 1).Trim(); AssemblyName assemblyName = null; try { assemblyName = new AssemblyName(fullName); } catch { } if (assemblyName != null) { List <AssemblyName> assemblyList = new List <AssemblyName>(names.Length); foreach (AssemblyName asmName in names) { if (string.Compare(assemblyName.Name, asmName.Name, StringComparison.OrdinalIgnoreCase) == 0) { assemblyList.Insert(0, asmName); } else { assemblyList.Add(asmName); } } names = assemblyList.ToArray(); } } // Search each reference assembly foreach (AssemblyName asmName in names) { Assembly asm = GetAssembly(asmName, false); if (asm != null) { result = asm.GetType(name, false, ignoreCase); if (result == null) { int indexOfComma = name.IndexOf(','); if (indexOfComma != -1) { string shortName = name.Substring(0, indexOfComma); result = asm.GetType(shortName, false, ignoreCase); } } } if (result != null) { break; } } } if (result == null && throwOnError) { throw new ArgumentException(string.Format(SR.InvalidResXNoType, name)); } if (result != null) { // Only cache types from the shared framework because they don't need to update. // For simplicity, don't cache custom types if (IsDotNetAssembly(result.Assembly.Location)) { cachedTypes[name] = result; } } return(result); }
override public Result decodeRow(int rowNumber, BitArray row, Hashtable hints) { // Find out where the Middle section (payload) starts & ends int[] startRange = decodeStart(row); if (startRange == null) { return(null); } int[] endRange = decodeEnd(row); if (endRange == null) { return(null); } StringBuilder result = new StringBuilder(20); if (!decodeMiddle(row, startRange[1], endRange[0], result)) { return(null); } String resultString = result.ToString(); int[] allowedLengths = null; if (hints != null && hints.Contains(DecodeHintType.ALLOWED_LENGTHS)) { allowedLengths = (int[])hints[DecodeHintType.ALLOWED_LENGTHS]; } if (allowedLengths == null) { allowedLengths = DEFAULT_ALLOWED_LENGTHS; } // To avoid false positives with 2D barcodes (and other patterns), make // an assumption that the decoded string must be 6, 10 or 14 digits. int length = resultString.Length; bool lengthOK = false; foreach (int allowedLength in allowedLengths) { if (length == allowedLength) { lengthOK = true; break; } } if (!lengthOK) { return(null); } return(new Result( resultString, null, // no natural byte representation for these barcodes new ResultPoint[] { new ResultPoint(startRange[1], (float)rowNumber), new ResultPoint(endRange[0], (float)rowNumber) }, BarcodeFormat.ITF)); }
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 hsh3; String strValue; Thread[] workers; ThreadStart ts1; Int32 iNumberOfWorkers = 15; Boolean fLoopExit; try { do { iCountTestcases++; hsh1 = new Hashtable(); hsh2 = Hashtable.Synchronized(hsh1); if(hsh1.IsSynchronized) { iCountErrors++; Console.WriteLine("Err_4820fdf! Expected value not returned, " + hsh1.IsSynchronized); } if(!hsh2.IsSynchronized) { iCountErrors++; Console.WriteLine("Err_4820fdf! Expected value not returned, " + hsh2.IsSynchronized); } hsh3 = Hashtable.Synchronized(hsh2); if(!hsh3.IsSynchronized) { iCountErrors++; Console.WriteLine("Err_4820fdf! Expected value not returned, " + hsh2.IsSynchronized); } strLoc = "Loc_8345vdfv"; iCountTestcases++; 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; } if(hsh2.Count != iNumberOfElements*iNumberOfWorkers) { iCountErrors++; Console.WriteLine("Err_75630fvbdf! Expected value not returned, " + hsh2.Count); } 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; } if(hsh2.Count != 0) { iCountErrors++; Console.WriteLine("Err_6720fvdg! Expected value not returned, " + hsh2.Count); } } 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; } }
protected override void OnMoveDirectory(FilePath localSrcPath, FilePath localDestPath, bool force, IProgressMonitor monitor) { if (IsVersioned(localDestPath)) { VersionInfo vinfo = GetVersionInfo(localDestPath, VersionInfoQueryFlags.IgnoreCache); if (!vinfo.HasLocalChange(VersionStatus.ScheduledDelete) && Directory.Exists(localDestPath)) { throw new InvalidOperationException("Cannot move directory. Destination directory already exist."); } localSrcPath = localSrcPath.FullPath; // The target directory does not exist, but it is versioned. It may be because // it is scheduled to delete, or maybe it has been physicaly deleted. In any // case we are going to replace the old directory by the new directory. // Revert the old directory, so we can see which files were there so // we can delete or replace them Revert(localDestPath, true, monitor); // Get the list of files in the directory to be replaced ArrayList oldFiles = new ArrayList(); GetDirectoryFiles(localDestPath, oldFiles); // Get the list of files to move ArrayList newFiles = new ArrayList(); GetDirectoryFiles(localSrcPath, newFiles); // Move all new files to the new destination Hashtable copiedFiles = new Hashtable(); Hashtable copiedFolders = new Hashtable(); foreach (string file in newFiles) { string src = Path.GetFullPath(file); string dst = Path.Combine(localDestPath, src.Substring(((string)localSrcPath).Length + 1)); if (File.Exists(dst)) { File.Delete(dst); } // Make sure the target directory exists string destDir = Path.GetDirectoryName(dst); if (!Directory.Exists(destDir)) { Directory.CreateDirectory(destDir); } // If the source file is versioned, make sure the target directory // is also versioned. if (IsVersioned(src)) { MakeDirVersioned(destDir, monitor); } MoveFile(src, dst, true, monitor); copiedFiles [dst] = dst; string df = Path.GetDirectoryName(dst); copiedFolders [df] = df; } // Delete all old files which have not been replaced ArrayList foldersToDelete = new ArrayList(); foreach (string oldFile in oldFiles) { if (!copiedFiles.Contains(oldFile)) { DeleteFile(oldFile, true, monitor, false); string fd = Path.GetDirectoryName(oldFile); if (!copiedFolders.Contains(fd) && !foldersToDelete.Contains(fd)) { foldersToDelete.Add(fd); } } } // Delete old folders foreach (string folder in foldersToDelete) { Svn.Delete(folder, true, monitor); } // Delete the source directory DeleteDirectory(localSrcPath, true, monitor, false); } else { if (Directory.Exists(localDestPath)) { throw new InvalidOperationException("Cannot move directory. Destination directory already exist."); } VersionInfo srcInfo = GetVersionInfo(localSrcPath, VersionInfoQueryFlags.IgnoreCache); if (srcInfo != null && srcInfo.HasLocalChange(VersionStatus.ScheduledAdd)) { // If the directory is scheduled to add, cancel it, move the directory, and schedule to add it again MakeDirVersioned(Path.GetDirectoryName(localDestPath), monitor); Revert(localSrcPath, true, monitor); base.OnMoveDirectory(localSrcPath, localDestPath, force, monitor); Add(localDestPath, true, monitor); } else { if (IsVersioned(localSrcPath)) { MakeDirVersioned(Path.GetDirectoryName(localDestPath), monitor); Svn.Move(localSrcPath, localDestPath, force, monitor); } else { base.OnMoveDirectory(localSrcPath, localDestPath, force, monitor); } } } }
private void ProcessItems(XmlNode ndParent, XmlNode ndRow, XmlNodeList arrFields, XmlDocument doc) { XmlNode ndNew = doc.CreateNode(XmlNodeType.Element, "I", doc.NamespaceURI); XmlNodeList ndCells = ndRow.SelectNodes("cell"); try { if (ndRow.SelectSingleNode("row") != null) { string open = "0"; try { open = ndRow.Attributes["open"].Value; } catch { } XmlAttribute attr = doc.CreateAttribute("Expanded"); attr.Value = open; ndNew.Attributes.Append(attr); } } catch { } try { XmlAttribute attr = doc.CreateAttribute("siteid"); attr.Value = ndRow.SelectSingleNode("userdata[@name='siteid']").InnerText; ndNew.Attributes.Append(attr); } catch { } try { XmlAttribute attr = doc.CreateAttribute("webid"); attr.Value = ndRow.SelectSingleNode("userdata[@name='webid']").InnerText; ndNew.Attributes.Append(attr); } catch { } try { XmlAttribute attr = doc.CreateAttribute("itemid"); attr.Value = ndRow.SelectSingleNode("userdata[@name='itemid']").InnerText; ndNew.Attributes.Append(attr); } catch { } try { XmlAttribute attr = doc.CreateAttribute("wsurl"); attr.Value = ndRow.SelectSingleNode("userdata[@name='wsurl']").InnerText; ndNew.Attributes.Append(attr); } catch { } try { XmlAttribute attr = doc.CreateAttribute("listid"); attr.Value = ndRow.SelectSingleNode("userdata[@name='listid']").InnerText; ndNew.Attributes.Append(attr); } catch { } try { XmlAttribute attr = doc.CreateAttribute("SiteUrl"); attr.Value = ndRow.SelectSingleNode("userdata[@name='SiteUrl']").InnerText; ndNew.Attributes.Append(attr); } catch { } try { XmlAttribute attr = doc.CreateAttribute("viewMenus"); attr.Value = ndRow.SelectSingleNode("userdata[@name='viewMenus']").InnerText; ndNew.Attributes.Append(attr); } catch { } try { XmlAttribute attr = doc.CreateAttribute("HasComments"); attr.Value = ndRow.SelectSingleNode("userdata[@name='HasComments']").InnerText; ndNew.Attributes.Append(attr); } catch { } try { XmlAttribute attr = doc.CreateAttribute("HasPlan"); attr.Value = ndRow.SelectSingleNode("userdata[@name='HasPlan']").InnerText; ndNew.Attributes.Append(attr); } catch { } try { XmlAttribute attr = doc.CreateAttribute("id"); attr.Value = (curId++).ToString(); ndNew.Attributes.Append(attr); } catch { } for (int i = 0; i < ndCells.Count; i++) { try { string fieldName = arrFields[i].Attributes["id"].Value.Replace("<![CDATA[", "").Replace("]]>", ""); string val = getFieldValue(fieldName, ndCells[i].InnerText); if ((fieldName == StartDateField || fieldName == DueDateField) && val == "") { } else if (fieldName == DueDateField) { //val = DateTime.Parse(val).AddDays(1).AddSeconds(-1).ToString("yyyy-MM-dd HH:mm:ss"); XmlAttribute attr = doc.CreateAttribute(fieldName); attr.Value = val; ndNew.Attributes.Append(attr); } else if (fieldName == "Predecessors") { XmlAttribute attr = doc.CreateAttribute(fieldName); attr.Value = val; ndNew.Attributes.Append(attr); } else if (fieldName == "Title") { XmlAttribute attr = doc.CreateAttribute(fieldName); attr.Value = val; ndNew.Attributes.Append(attr); attr = doc.CreateAttribute(fieldName + "ButtonText"); if (ndRow.SelectSingleNode("userdata[@name='itemid']") != null && ndRow.SelectSingleNode("userdata[@name='itemid']").InnerText != "") { //attr.Value = "<div class=\"gridmenuspan\" style=\"position:relative;\"><a data-itemid=\"" + ndRow.SelectSingleNode("userdata[@name='itemid']").InnerText + "\" data-listid=\"" + ndRow.SelectSingleNode("userdata[@name='listid']").InnerText + "\" data-webid=\"" + ndRow.SelectSingleNode("userdata[@name='webid']").InnerText + "\" data-siteid=\"" + ndRow.SelectSingleNode("userdata[@name='siteid']").InnerText + "\" ></a></div>"; } ndNew.Attributes.Append(attr); } else { if (hshLookupEnums.Contains(fieldName)) { string newval = ""; if (val != "") { val = HttpUtility.HtmlDecode(val); SPFieldLookupValueCollection lvc = new SPFieldLookupValueCollection(val); foreach (SPFieldLookupValue lv in lvc) { if (!((ArrayList)hshLookupEnums[fieldName]).Contains(lv.LookupId)) { ((ArrayList)hshLookupEnums[fieldName]).Add(lv.LookupId); ((ArrayList)hshLookupEnumKeys[fieldName]).Add(lv.LookupValue.Replace(";", "")); } newval += ";" + lv.LookupId; } } val = newval.Trim(';'); } if (fieldName == "State") { fieldName = "FState"; } XmlAttribute attr = doc.CreateAttribute(fieldName); attr.Value = val; ndNew.Attributes.Append(attr); } } catch { } } ndParent.AppendChild(ndNew); XmlNodeList ndRows = ndRow.SelectNodes("row"); if (ndRows.Count > 0) { XmlAttribute attr = doc.CreateAttribute("Def"); attr.Value = "Summary"; ndNew.Attributes.Append(attr); for (int i = 0; i < ndRows.Count; i++) { ProcessItems(ndNew, ndRows[i], arrFields, doc); } } }
// 复制ClassFONT的参数 public void clone(ClassFont cFnt) { // if (cFnt.Name.Equals("")) // return; this.AllCaps = cFnt.AllCaps; // 复制ClassFONT的参数 this.Animations = (int)cFnt.Animation; // wdAnimationNone,// 复制ClassFONT的参数 this.Bold = cFnt.Bold; // 复制ClassFONT的参数 this.ColorRGB = "" + (int)cFnt.Color; // wdColorAutomatic,// 复制ClassFONT的参数 this.DoubleStrikeThrough = cFnt.DoubleStrikeThrough; // 复制ClassFONT的参数 this.Emboss = cFnt.Emboss; // 复制ClassFONT的参数 this.Engrave = cFnt.Engrave; // 复制ClassFONT的参数 this.FontHighAnsi = cFnt.NameAscii; //"Arial Unicode MS",// 复制ClassFONT的参数 //this.FontLowAnsi = cFnt.NameOther;//"Arial Unicode MS",// 复制ClassFONT的参数 this.FontMajor = cFnt.NameFarEast; //"微软雅黑",// 复制ClassFONT的参数 this.Font = cFnt.Name; // 复制ClassFONT的参数 this.Hidden = cFnt.Hidden; // 复制ClassFONT的参数 this.Italic = cFnt.Italic; // 复制ClassFONT的参数 if (m_hashPointsSize2Dialog.Contains(cFnt.Kerning)) // 复制ClassFONT的参数 { this.Kerning = 1; // 复制ClassFONT的参数 this.KerningMin = (String)m_hashPointsSize2Dialog[cFnt.Kerning]; // this.Kerning,// 复制ClassFONT的参数 } else { this.Kerning = 0; // 复制ClassFONT的参数 this.KerningMin = ""; // 复制ClassFONT的参数 } this.Outline = cFnt.Outline; // 复制ClassFONT的参数 this.Position = cFnt.Position + " 磅"; // 复制ClassFONT的参数 this.Scale = cFnt.Scaling + "%"; // 复制ClassFONT的参数 this.Shadow = cFnt.Shadow; // 复制ClassFONT的参数 this.SmallCaps = cFnt.SmallCaps; // 复制ClassFONT的参数 this.Spacing = cFnt.Spacing + " 磅"; // 复制ClassFONT的参数 this.StrikeThrough = cFnt.StrikeThrough; // 复制ClassFONT的参数 this.Subscript = cFnt.Subscript; // 复制ClassFONT的参数 this.Superscript = cFnt.Superscript; // 复制ClassFONT的参数 this.UnderlineColor = "" + (int)cFnt.UnderlineColor; // wdColorAutomatic,// 复制ClassFONT的参数 this.Underline = (int)WdUnderline.wdUnderlineNone; // 复制ClassFONT的参数 if (m_hashUnderlineWordFont2Dialog.Contains(cFnt.Underline)) // 复制ClassFONT的参数 { this.Underline = (int)m_hashUnderlineWordFont2Dialog[cFnt.Underline]; // wdUnderlineNone,// 复制ClassFONT的参数 } if (m_hashPointsSize2Dialog.Contains(cFnt.Size)) // 复制ClassFONT的参数 { this.Points = (String)m_hashPointsSize2Dialog[cFnt.Size]; // cFnt.point,// 复制ClassFONT的参数 } else { this.Points = "" + cFnt.Size;// 复制ClassFONT的参数 } this.CharacterWidthGrid = (cFnt.DisableCharacterSpaceGrid ? 1:0);// 复制ClassFONT的参数 //this.Color = cFnt.ColorDialog; //this.PointsBi = "11"; return; }
public Token(string _tokenText, ScannerState _state, bool quoteFlag) { state = _state; if (_tokenText == null)//|| _tokenText.Length == 0 ) { //tokenVal = TokenValue.Error; //errorMessage = "Bad Token String - 0 length"; _tokenText = ""; } //else //{ switch (state) { case ScannerState.ParseID: tokenText = _tokenText.ToLowerInvariant(); if (reservedWords.Contains(tokenText)) { tokenVal = (TokenValue)reservedWords[tokenText]; } else if (tokenText.StartsWith("x-")) { tokenVal = TokenValue.Xtension; tokenText = "x:" + tokenText.Substring(2); } else if (isID(tokenText)) // this check may be unnecessary by virute of the scanner.... { tokenVal = TokenValue.ID; } else { tokenVal = TokenValue.Error; errorMessage = "Illegal value for ID"; } if (isBeginEndValue()) { tokenText = CapsCamelCase(tokenText); } else { tokenText = CamelCase(tokenText); } break; case ScannerState.ParseParms: tokenText = _tokenText; if (quoteFlag) { tokenVal = TokenValue.QuotedString; } else { tokenVal = TokenValue.Parm; } break; case ScannerState.ParseValue: tokenText = _tokenText; tokenVal = TokenValue.Value; break; case ScannerState.ParseSimple: tokenVal = TokenValue.Error; errorMessage = "Bad constructor call - ParseSimple and text..."; break; } //} }
/// <summary> /// Retrieves the segment and scenario dimension nodes for display. /// </summary> internal bool TryGetDimensionNodesForDisplay(string currentLanguage, string currentLabelRole, Hashtable presentationLinks, bool isSegment, bool allDimensions, Dictionary <string, RoleType> roleTypesDt, out Dictionary <string, DimensionNode> dimensionNodes) { dimensionNodes = new Dictionary <string, DimensionNode>(); foreach (DefinitionLink dl in this.definitionLinks.Values) { string label = dl.Title; if (roleTypesDt != null) { RoleType rt; if (roleTypesDt.TryGetValue(label, out rt)) { if (!string.IsNullOrEmpty(rt.Definition)) { label = rt.Definition; } } } DimensionNode topLevelNode = new DimensionNode(label); topLevelNode.MyDefinitionLink = dl; if (isSegment) { foreach (string hypercubeHref in dl.HypercubeLocatorsHrefs) { if (!allDimensions) { if (presentationLinks != null && presentationLinks.Contains(dl.Role)) { //if the hyper cube is part of the segment list or //if it part of the scenario list do not show it here //as we are going to show it in the element pane.... if (dl.segmentHypercubesHRef.Contains(hypercubeHref) || dl.scenarioHypercubesHref.Contains(hypercubeHref)) { continue; } } } DimensionNode hyperCubeNode; if (dl.TryGetHypercubeNode(currentLanguage, currentLabelRole, this.definitionLinks, hypercubeHref, false, out hyperCubeNode)) { topLevelNode.AddChild(hyperCubeNode); } } } else { foreach (string hypercubeHref in dl.HypercubeLocatorsHrefs) { //we want to show all the scenario dimensions and //and all the dimensions that are not associated with the segment if (dl.scenarioHypercubesHref.Contains(hypercubeHref) || !dl.segmentHypercubesHRef.Contains(hypercubeHref)) { DimensionNode hyperCubeNode; if (dl.TryGetHypercubeNode(currentLanguage, currentLabelRole, this.definitionLinks, hypercubeHref, false, out hyperCubeNode)) { topLevelNode.AddChild(hyperCubeNode); } } } } if (topLevelNode.Children != null && topLevelNode.Children.Count > 0) { dimensionNodes.Add(dl.Role, topLevelNode); } } return(true); }
/// <summary> /// Changes a GameObject's scale over time with FULL customization options. /// </summary> /// <param name="scale"> /// A <see cref="Transform"/> or <see cref="Vector3"/> for the final scale. /// </param> /// <param name="x"> /// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the x axis. /// </param> /// <param name="y"> /// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the y axis. /// </param> /// <param name="z"> /// A <see cref="System.Single"/> or <see cref="System.Double"/> for the individual setting of the z axis. /// </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="speed"> /// A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed /// </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 ScaleTo(GameObject target, Hashtable args) { //clean args: args = iTween.CleanArgs(args); //additional property to ensure ConflictCheck can work correctly since Transforms are refrences: if(args.Contains("scale")){ if (args["scale"].GetType() == typeof(Transform)) { Transform transform = (Transform)args["scale"]; args["position"]=new Vector3(transform.position.x,transform.position.y,transform.position.z); args["rotation"]=new Vector3(transform.eulerAngles.x,transform.eulerAngles.y,transform.eulerAngles.z); args["scale"]=new Vector3(transform.localScale.x,transform.localScale.y,transform.localScale.z); } } //establish iTween: args["type"]="scale"; args["method"]="to"; Launch(target,args); }
private static Hashtable DnsQueryWrapper(string domainName, string siteName, long dcFlags) { Hashtable domainControllers = new Hashtable(); string recordName = "_ldap._tcp."; int result = 0; int options = 0; IntPtr dnsResults = IntPtr.Zero; // construct the record name if ((siteName != null) && (!(siteName.Length == 0))) { // only looking for domain controllers / global catalogs within a // particular site recordName = recordName + siteName + "._sites."; } // check if gc or dc if (((long)dcFlags & (long)(PrivateLocatorFlags.GCRequired)) != 0) { // global catalog recordName += "gc._msdcs."; } else if (((long)dcFlags & (long)(PrivateLocatorFlags.DSWriteableRequired)) != 0) { // domain controller recordName += "dc._msdcs."; } // now add the domainName recordName = recordName + domainName; // set the BYPASS CACHE option is specified if (((long)dcFlags & (long)LocatorOptions.ForceRediscovery) != 0) { options |= NativeMethods.DnsQueryBypassCache; } // Call DnsQuery result = NativeMethods.DnsQuery(recordName, NativeMethods.DnsSrvData, options, IntPtr.Zero, out dnsResults, IntPtr.Zero); if (result == 0) { try { IntPtr currentDnsRecord = dnsResults; while (currentDnsRecord != IntPtr.Zero) { // partial marshalling of dns record data PartialDnsRecord partialDnsRecord = new PartialDnsRecord(); Marshal.PtrToStructure(currentDnsRecord, partialDnsRecord); //check if the record is of type DNS_SRV_DATA if (partialDnsRecord.type == NativeMethods.DnsSrvData) { // remarshal to get the srv record data DnsRecord dnsRecord = new DnsRecord(); Marshal.PtrToStructure(currentDnsRecord, dnsRecord); string targetName = dnsRecord.data.targetName; string key = targetName.ToLowerInvariant(); if (!domainControllers.Contains(key)) { domainControllers.Add(key, null); } } // move to next record currentDnsRecord = partialDnsRecord.next; } } finally { // release the dns results buffer if (dnsResults != IntPtr.Zero) { NativeMethods.DnsRecordListFree(dnsResults, true); } } } else if (result != 0) { throw ExceptionHelper.GetExceptionFromErrorCode(result); } return(domainControllers); }
/// <summary> /// Returns a value to an 'oncallback' method interpolated between the supplied 'from' and 'to' values for application as desired. Requires an 'onupdate' callback that accepts the same type as the supplied 'from' and 'to' properties. /// </summary> /// <param name="from"> /// A <see cref="System.Single"/> or <see cref="System.Double"/> or <see cref="Vector3"/> or <see cref="Vector2"/> or <see cref="Color"/> or <see cref="Rect"/> for the starting value. /// </param> /// <param name="to"> /// A <see cref="System.Single"/> or <see cref="System.Double"/> or <see cref="Vector3"/> or <see cref="Vector2"/> or <see cref="Color"/> or <see cref="Rect"/> for the ending value. /// </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="speed"> /// A <see cref="System.Single"/> or <see cref="System.Double"/> can be used instead of time to allow animation based on speed (only works with Vector2, Vector3, and Floats) /// </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 ValueTo(GameObject target, Hashtable args) { //clean args: args = iTween.CleanArgs(args); if (!args.Contains("onupdate") || !args.Contains("from") || !args.Contains("to")) { Debug.LogError("iTween Error: ValueTo() requires an 'onupdate' callback function and a 'from' and 'to' property. The supplied 'onupdate' callback must accept a single argument that is the same type as the supplied 'from' and 'to' properties!"); return; }else{ //establish iTween: args["type"]="value"; if (args["from"].GetType() == typeof(Vector2)) { args["method"]="vector2"; }else if (args["from"].GetType() == typeof(Vector3)) { args["method"]="vector3"; }else if (args["from"].GetType() == typeof(Rect)) { args["method"]="rect"; }else if (args["from"].GetType() == typeof(Single)) { args["method"]="float"; }else if (args["from"].GetType() == typeof(Color)) { args["method"]="color"; }else{ Debug.LogError("iTween Error: ValueTo() only works with interpolating Vector3s, Vector2s, floats, ints, Rects and Colors!"); return; } //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); } Launch(target,args); } }
private static Hashtable DnsGetDcWrapper(string domainName, string siteName, long dcFlags) { Hashtable domainControllers = new Hashtable(); int optionFlags = 0; IntPtr retGetDcContext = IntPtr.Zero; IntPtr dcDnsHostNamePtr = IntPtr.Zero; int sockAddressCount = 0; IntPtr sockAddressCountPtr = new IntPtr(sockAddressCount); IntPtr sockAddressList = IntPtr.Zero; string dcDnsHostName = null; int result = 0; result = NativeMethods.DsGetDcOpen(domainName, (int)optionFlags, siteName, IntPtr.Zero, null, (int)dcFlags, out retGetDcContext); if (result == 0) { try { result = NativeMethods.DsGetDcNext(retGetDcContext, ref sockAddressCountPtr, out sockAddressList, out dcDnsHostNamePtr); if (result != 0 && result != NativeMethods.ERROR_FILE_MARK_DETECTED && result != NativeMethods.DNS_ERROR_RCODE_NAME_ERROR && result != NativeMethods.ERROR_NO_MORE_ITEMS) { throw ExceptionHelper.GetExceptionFromErrorCode(result); } while (result != NativeMethods.ERROR_NO_MORE_ITEMS) { if (result != NativeMethods.ERROR_FILE_MARK_DETECTED && result != NativeMethods.DNS_ERROR_RCODE_NAME_ERROR) { try { dcDnsHostName = Marshal.PtrToStringUni(dcDnsHostNamePtr); string key = dcDnsHostName.ToLowerInvariant(); if (!domainControllers.Contains(key)) { domainControllers.Add(key, null); } } finally { // what to do with the error? if (dcDnsHostNamePtr != IntPtr.Zero) { result = NativeMethods.NetApiBufferFree(dcDnsHostNamePtr); } } } result = NativeMethods.DsGetDcNext(retGetDcContext, ref sockAddressCountPtr, out sockAddressList, out dcDnsHostNamePtr); if (result != 0 && result != NativeMethods.ERROR_FILE_MARK_DETECTED && result != NativeMethods.DNS_ERROR_RCODE_NAME_ERROR && result != NativeMethods.ERROR_NO_MORE_ITEMS) { throw ExceptionHelper.GetExceptionFromErrorCode(result); } } } finally { NativeMethods.DsGetDcClose(retGetDcContext); } } else if (result != 0) { throw ExceptionHelper.GetExceptionFromErrorCode(result); } return(domainControllers); }
/// <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); }
// 复制到自定义FONT的参数 public void copy2(ClassFont fnt) { fnt.AllCaps = this.AllCaps; // 复制到自定义FONT的参数 fnt.Animation = (Word.WdAnimation) this.Animations; // wdAnimationNone// 复制到自定义FONT的参数 fnt.Bold = this.Bold; // 复制到自定义FONT的参数 fnt.BoldBi = this.BoldBi; // 复制到自定义FONT的参数 int nTmp = 0; fnt.Color = WdColor.wdColorAutomatic;// 复制到自定义FONT的参数 if (int.TryParse(this.ColorRGB, out nTmp)) { fnt.Color = (WdColor)nTmp;// 复制到自定义FONT的参数 } fnt.DoubleStrikeThrough = this.DoubleStrikeThrough; // 复制到自定义FONT的参数 fnt.Emboss = this.Emboss; // 复制到自定义FONT的参数 fnt.Engrave = this.Engrave; // 复制到自定义FONT的参数 fnt.NameAscii = this.FontHighAnsi; //"Arial Unicode MS"// 复制到自定义FONT的参数 //fnt.NameOther = this.FontLowAnsi;//"Arial Unicode MS"// 复制到自定义FONT的参数 fnt.NameFarEast = this.FontMajor; //"微软雅黑"// 复制到自定义FONT的参数 fnt.Name = this.FontMajor; // 复制到自定义FONT的参数 fnt.Hidden = this.Hidden; // 复制到自定义FONT的参数 fnt.Italic = this.Italic; // 复制到自定义FONT的参数 fnt.ItalicBi = this.ItalicBi; // 复制到自定义FONT的参数 if (this.Kerning > 0) { if (m_hashPointsDialog2Size.Contains(this.KerningMin)) { fnt.Kerning = (float)m_hashPointsDialog2Size[this.KerningMin];// this.point// 复制到自定义FONT的参数 } else { if (float.TryParse(this.KerningMin, out fnt.Kerning)) { } else { fnt.Kerning = 0.0f;// 复制到自定义FONT的参数 } } } else { fnt.Kerning = this.Kerning; // 0.0f// 复制到自定义FONT的参数 } fnt.Outline = this.Outline; // 复制到自定义FONT的参数 if (int.TryParse(this.Position, out nTmp)) // 复制到自定义FONT的参数 { fnt.Position = nTmp; // 复制到自定义FONT的参数 } else { fnt.Position = nTmp;// 复制到自定义FONT的参数 } if (int.TryParse(this.Scale.Replace("%", ""), out nTmp)) // 复制到自定义FONT的参数 { fnt.Scaling = nTmp; // 复制到自定义FONT的参数 } else { fnt.Scaling = 100;// 复制到自定义FONT的参数 } fnt.Shadow = this.Shadow; // 复制到自定义FONT的参数 fnt.SmallCaps = this.SmallCaps; // 复制到自定义FONT的参数 float fTmp = 0.0f; if (float.TryParse(this.Spacing, out fTmp)) // 复制到自定义FONT的参数 { fnt.Spacing = fTmp; // 复制到自定义FONT的参数 } else { fnt.Spacing = 0.0f;// 复制到自定义FONT的参数 } fnt.StrikeThrough = this.StrikeThrough; // 复制到自定义FONT的参数 fnt.Subscript = this.Subscript; // 复制到自定义FONT的参数 fnt.Superscript = this.Superscript; // 复制到自定义FONT的参数 fnt.UnderlineColor = WdColor.wdColorAutomatic; // 复制到自定义FONT的参数 if (int.TryParse(this.UnderlineColor, out nTmp)) // 复制到自定义FONT的参数 { fnt.UnderlineColor = (WdColor)nTmp; // 复制到自定义FONT的参数 } fnt.Underline = WdUnderline.wdUnderlineNone; // 复制到自定义FONT的参数 if (m_hashUnderlineDialog2WordFont.Contains(this.Underline)) // 复制到自定义FONT的参数 { fnt.Underline = (WdUnderline)m_hashUnderlineDialog2WordFont[this.Underline]; // wdUnderlineNone } if (m_hashPointsDialog2Size.Contains(this.Points)) // 复制到自定义FONT的参数 { fnt.Size = (float)m_hashPointsDialog2Size[this.Points]; // this.point } else { float.TryParse(this.Points, out fnt.Size);// 复制到自定义FONT的参数 } if (m_hashPointsDialog2Size.Contains(this.PointsBi)) // 复制到自定义FONT的参数 { fnt.SizeBi = (float)m_hashPointsDialog2Size[this.PointsBi]; // this.PointsBi } else { float.TryParse(this.PointsBi, out fnt.SizeBi);// 复制到自定义FONT的参数 } fnt.DisableCharacterSpaceGrid = (this.CharacterWidthGrid != 0);// 复制到自定义FONT的参数 return; }
protected static void setTween(ReceiverTween tween, Hashtable hashtable) { if (hashtable.Count == 0) return; if (hashtable.Contains("speed")) tween._speed = (float)hashtable["speed"]; if (hashtable.Contains("delay")) tween._delay = (float)hashtable["delay"]; if (hashtable.Contains("curve")) tween._curve = (AnimationCurve)hashtable["curve"]; }
/* * C# includes Hashtable collection in System.Collections namespace, * which is similar to generic Dictionary collection. The Hashtable collection * stores key-value pairs. It optimizes lookups by computing the hash code of * each key and stores it in a different bucket internally and then matches the * hash code of the specified key at the time of accessing values. */ //Hashtable stores key-value pairs of any datatype where the Key must be unique. //The Hashtable key cannot be null whereas the value can be null. //Hashtable retrieves an item by comparing the hashcode of keys.So it is slower in performance than Dictionary collection. //Hashtable uses the default hashcode provider which is object.GetHashCode(). You can also use a custom hashcode provider. //Use DictionaryEntry with foreach statement to iterate Hashtable. public void Hashtable_Check() { // add Hashtable ht = new Hashtable(); ht.Add(1, "One"); ht.Add(2, "Two"); ht.Add(3, "Three"); ht.Add(4, "Four"); ht.Add(5, null); ht.Add("Fv", "Five"); ht.Add(8.5, 8.5); //Hashtable can include all the elements of Dictionary as shown below. Dictionary <int, string> dict = new Dictionary <int, string>(); dict.Add(1, "one"); dict.Add(2, "two"); dict.Add(3, "three"); Hashtable ht2 = new Hashtable(dict); string strValue1 = (string)ht[2]; string strValue2 = (string)ht["Fv"]; float fValue = (float)ht[8.5]; Console.WriteLine(strValue1); // Two Console.WriteLine(strValue2); // Five Console.WriteLine(fValue); //8.5 //Iterate Hashtable foreach (DictionaryEntry item in ht) { Console.WriteLine("key:{0}, value:{1}", item.Key, item.Value); } //Key: Fv, Value: Five //Key: 8.5, Value: 8.5 //Key: 5, Value: //Key: 4, Value: Four //Key: 3, Value: Three //Key: 2, Value: Two //Key: 1, Value: One //Access Hashtable using Keys & Values foreach (var key in ht.Keys) { Console.WriteLine("Key:{0}, Value:{1}", key, ht[key]); } Console.WriteLine("***All Values***"); foreach (var value in ht.Values) { Console.WriteLine("Value:{0}", value); } //Remove() ht.Remove("Fv"); // removes {"Fv", "Five"} //Contains(), ContainsKey() and ContainsValue() Hashtable ht3 = new Hashtable() { { 1, "One" }, { 2, "Two" }, { 3, "Three" }, { 4, "Four" } }; ht3.Contains(2); // returns true ht3.ContainsKey(2); // returns true ht3.Contains(5); //returns false ht3.ContainsValue("One"); // returns true //Clear() ht.Clear(); // removes all elements #endregion #region BitArray #endregion }