/// <summary> /// Reads all necessary mesh information /// </summary> public void ReadMesh() { Hashtable Hash=new Hashtable(); List<Vector3> pts = new List<Vector3>(); if (Mesh != mOldMesh || Transform.rotation != mOldRot || Scale != mOldScale) { if (Mesh) { int[] tris = Mesh.sharedMesh.triangles; Vector3[] verts = Mesh.sharedMesh.vertices; for (int i = 0; i < verts.Length; i++) verts[i].Scale(Scale); for (int t = 0; t < tris.Length; t += 3) { if (!Hash.ContainsKey(Key(tris[t], tris[t + 1]))) { Hash.Add(Key(tris[t], tris[t + 1]), null); pts.Add(verts[tris[t]]); pts.Add(verts[tris[t + 1]]); } if (!Hash.ContainsKey(Key(tris[t + 1], tris[t + 2]))) { Hash.Add(Key(tris[t + 1], tris[t + 2]), null); pts.Add(verts[tris[t + 1]]); pts.Add(verts[tris[t + 2]]); } if (!Hash.ContainsKey(Key(tris[t + 2], tris[t]))) { Hash.Add(Key(tris[t + 2], tris[t]), null); pts.Add(verts[tris[t + 2]]); pts.Add(verts[tris[t]]); } } } mOldMesh = Mesh; mOldRot = Transform.rotation; mOldScale = Scale; Points = pts.ToArray(); } }
// grabs the contents of the plist and sets them in the ivar public void getPlistContents() { // initialize the hashtable and plistKeys plistContents = new Hashtable(); // get the contents of the plist file if it exists filePath = Path.Combine( Application.dataPath, "Editor/Prime31/" + plistFileName ); if( File.Exists( filePath ) ) { PListEditor.loadPlistFromFile( filePath, plistContents ); // set any keys that we have present var t = typeof( Prime31PlistHelperWizard ); foreach( var info in t.GetFields() ) { if( plistContents.ContainsKey( info.Name ) ) { info.SetValue( this, plistContents[info.Name] ); } else if( plistContents.ContainsKey( "CFBundleURLTypes" ) ) // special case for url schemes { var values = (ArrayList)plistContents["CFBundleURLTypes"]; var ht = values[0] as Hashtable; var listOfSchemes = ht["CFBundleURLSchemes"] as ArrayList; var extractedSchemes = new List<string>(); foreach( string scheme in listOfSchemes ) extractedSchemes.Add( scheme ); CFBundleURLSchemes = extractedSchemes.ToArray(); } } } }
public int whichOrder(String[] available, String[] orders) { Hashtable set = new Hashtable(); int k = 0; foreach (String s in available) { if(!set.ContainsKey(s)) set.Add(s, k++); } for (int i = 0; i < orders.Length; ++i) { string[] ins = orders[i].Split(new char[] { ' ' }); bool isOk = true; foreach (String ss in ins) { if (!set.ContainsKey(ss)) { isOk = false; break; } } if (isOk) { return i; } } return -1; }
public void SetData(Hashtable ht) { if(ht.ContainsKey("itemchance")) { this.stealItem = true; this.itemChance = int.Parse((string)ht["itemchance"]); this.itemBonus = float.Parse((string)ht["itembonus"]); if(ht.ContainsKey("item")) { this.fixItem = true; this.itemType = (ItemDropType)System.Enum.Parse( typeof(ItemDropType), (string)ht["itemtype"]); this.itemID = int.Parse((string)ht["item"]); } } if(ht.ContainsKey("moneychance")) { this.stealMoney = true; this.moneyChance = int.Parse((string)ht["moneychance"]); this.moneyBonus = float.Parse((string)ht["moneybonus"]); if(ht.ContainsKey("money")) { this.fixMoney = true; this.money = int.Parse((string)ht["money"]); } } }
public void TestGetKeyValueList() { var dic1 = new SortedList(); for (int i = 0; i < 100; i++) dic1.Add("Key_" + i, "Value_" + i); var ilst1 = dic1.GetKeyList(); var hsh1 = new Hashtable(); DoIListTests(dic1, ilst1, hsh1, DicType.Key); Assert.False(hsh1.Count != 2 || !hsh1.ContainsKey("IsReadOnly") || !hsh1.ContainsKey("IsFixedSize"), "Error, KeyList"); dic1 = new SortedList(); for (int i = 0; i < 100; i++) dic1.Add("Key_" + i, "Value_" + i); ilst1 = dic1.GetValueList(); hsh1 = new Hashtable(); DoIListTests(dic1, ilst1, hsh1, DicType.Value); Assert.False(hsh1.Count != 2 || !hsh1.ContainsKey("IsReadOnly") || !hsh1.ContainsKey("IsFixedSize"), "Error, ValueList"); }
public void SetData(Hashtable ht) { if(ht.ContainsKey("player")) this.isPlayer = true; if(ht.ContainsKey("showname")) this.showName = true; this.dialogName = new string[DataHolder.Languages().GetDataCount()]; for(int i=0; i<this.dialogName.Length; i++) { this.dialogName[i] = ""; } if(ht.ContainsKey(XMLHandler.NODES)) { if(this.isPlayer) this.overrideName = true; ArrayList subs2 = ht[XMLHandler.NODES] as ArrayList; foreach(Hashtable ht2 in subs2) { if(ht2[XMLHandler.NODE_NAME] as string == "name") { int id = int.Parse((string)ht2["id"]); if(id < this.dialogName.Length) this.dialogName[id] = ht2[XMLHandler.CONTENT] as string; } } } }
////////////////////////////////////////// /// ID_SimilarityBucket() ////////////////////////////////////////// public ID_Audio( string i_strID, Hashtable hashData, List<IXMLNode> listElements, string strError ) { if ( hashData.ContainsKey( "Volume" ) ) m_fVolume = float.Parse(hashData["Volume"].ToString()); if ( hashData.ContainsKey( "Loop" ) ) m_bLoop = bool.Parse(hashData["Loop"].ToString()); }
public void TestCtorDictionarySingle() { // No exception var hash = new Hashtable(new Hashtable(), 1f); // No exception hash = new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable()), 1f), 1f), 1f), 1f); // []test to see if elements really get copied from old dictionary to new hashtable Hashtable tempHash = new Hashtable(); // this for assumes that MinValue is a negative! for (long i = long.MinValue; i < long.MinValue + 100; i++) { tempHash.Add(i, i); } hash = new Hashtable(tempHash, 1f); // make sure that new hashtable has the elements in it that old hashtable had for (long i = long.MinValue; i < long.MinValue + 100; i++) { Assert.True(hash.ContainsKey(i)); Assert.True(hash.ContainsValue(i)); } //[]make sure that there are no connections with the old and the new hashtable tempHash.Clear(); for (long i = long.MinValue; i < long.MinValue + 100; i++) { Assert.True(hash.ContainsKey(i)); Assert.True(hash.ContainsValue(i)); } }
public static SceneData.SceneNodeData CreateNodeData( Hashtable attrTable ) { SceneData.SceneNodeData data = new SceneData.SceneNodeData(); data.name = attrTable["name"] as string; data.parentname = attrTable["parentname"] as string; ParamUtil.SetFloatAttr( out data.posX , "posX" , attrTable , 0f ); ParamUtil.SetFloatAttr( out data.posY , "posY" , attrTable , 0f ); ParamUtil.SetFloatAttr( out data.posZ , "posZ" , attrTable , 0f ); ParamUtil.SetFloatAttr( out data.rotX , "rotX" , attrTable , 0f ); ParamUtil.SetFloatAttr( out data.rotY , "rotY" , attrTable , 0f ); ParamUtil.SetFloatAttr( out data.rotZ , "rotZ" , attrTable , 0f ); ParamUtil.SetFloatAttr( out data.sclX , "sclX" , attrTable , 1f ); ParamUtil.SetFloatAttr( out data.sclY , "sclY" , attrTable , 1f ); ParamUtil.SetFloatAttr( out data.sclZ , "sclZ" , attrTable , 1f ); data.uiAtlasName = attrTable["uiAtlasName"] as string; data.texturePath = attrTable["texturePath"] as string; ParamUtil.SetFloatAttr( out data.alpha , "alpha" , attrTable , 1f ); if( attrTable.ContainsKey( "show") ){ data.show = ViNoStringExtensions.IsTrueOrYes( attrTable["show"] as string ); } if( attrTable.ContainsKey( "makePixelPerfect") ){ data.makePixelPerfect = ViNoStringExtensions.IsTrueOrYes( attrTable["makePixelPerfect"] as string ); } return data; }
public void Populate (Hashtable data) { if(data == null) return; if(data.ContainsKey("listAutomotor")) SetVehicles (data ["listAutomotor"] as ArrayList); if(data.ContainsKey("grupoAutomotores")) SetVehiclesGroup (data ["grupoAutomotores"] as ArrayList); }
public static StoreKitDownload downloadFromHashtable( Hashtable ht ) { var download = new StoreKitDownload(); if( ht.ContainsKey( "downloadState" ) ) download.downloadState = (StoreKitDownloadState)int.Parse( ht["downloadState"].ToString() ); if( ht.ContainsKey( "contentLength" ) ) download.contentLength = double.Parse( ht["contentLength"].ToString() ); if( ht.ContainsKey( "contentIdentifier" ) ) download.contentIdentifier = ht["contentIdentifier"].ToString(); if( ht.ContainsKey( "contentURL" ) ) download.contentURL = ht["contentURL"].ToString(); if( ht.ContainsKey( "contentVersion" ) ) download.contentVersion = ht["contentVersion"].ToString(); if( ht.ContainsKey( "error" ) ) download.error = ht["error"].ToString(); if( ht.ContainsKey( "progress" ) ) download.progress = float.Parse( ht["progress"].ToString() ); if( ht.ContainsKey( "timeRemaining" ) ) download.timeRemaining = double.Parse( ht["timeRemaining"].ToString() ); if( ht.ContainsKey( "transaction" ) ) download.transaction = StoreKitTransaction.transactionFromHashtable( ht["transaction"] as Hashtable ); return download; }
public void HashContain() { Hashtable<string, int> phonebook = new Hashtable<string, int>(100); phonebook.Add("Razvan Hidan", 0744596712); phonebook.Add("Ionut Marin", 076653421); phonebook.Add("Bogdan Dragos", 07111111); phonebook.Add("Maria Marioara", 0783442); phonebook.ContainsKey("Razvan Hidan"); phonebook.ContainsKey("Bogdan Dragos"); phonebook.ContainsKey("Razvan").ShouldBeFalse(); }
public void TestContainKeyBasic() { 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.ContainsKey("No_Such_Key")); // 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.ContainsKey(s1)); } // // [] Remove a key and then check // sblMsg = new StringBuilder(99); sblMsg.Append("key_50"); s1 = sblMsg.ToString(); ht1.Remove(s1); //removes "Key_50" //check whether the key is removed or not Assert.False(ht1.ContainsKey(s1)); }
/* ["creatorName"] ["position"] ["rotation"] */ public void create(Hashtable p) { Vector3 position = new Vector3(); Quaternion rotation = new Quaternion(); if (p.ContainsKey("position")) position = (Vector3)p["position"] ; if (p.ContainsKey("rotation")) rotation = (Quaternion)p["rotation"]; GameObject clone = zzCreatorUtility.Instantiate((GameObject)creatorMap[p["creatorName"]], position, rotation, 0); Debug.Log(p["creatorName"] + " " + clone.name); zzGameObjectInit initObject = clone.GetComponent<zzGameObjectInit>(); initObject.init(p); }
public void SetData(Hashtable ht) { this.name = ht[XMLHandler.CONTENT] as string; if(ht.ContainsKey("id")) { this.layer = int.Parse((string)ht["id"]); } if(ht.ContainsKey("speed")) { this.setSpeed = true; this.speedFormula = int.Parse((string)ht["speed"]); } }
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(new char[] { ';' }); Hashtable cookie = new Hashtable(); string[] value = regex.Split(cookies[0].Trim(), 2); cookie["name"] = value[0]; if (value.Length == 2) cookie["value"] = value[1]; else cookie["value"] = ""; for (int i = 1; i < cookies.Length; ++i) { value = regex.Split(cookies[i].Trim(), 2); 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.ContainsKey("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 (cookie.ContainsKey("EXPIRES")) { cookie["EXPIRES"] = DateTime.Parse((string)cookie["EXPIRES"]); } if (cookie.ContainsKey("DOMAIN")) { cookie["DOMAIN"] = ((string)cookie["DOMAIN"]).ToLower(); } else { cookie["DOMAIN"] = host; } cookie["SECURE"] = cookie.ContainsKey("SECURE"); if (!container.ContainsKey(cookie["DOMAIN"])) { container[cookie["DOMAIN"]] = new Hashtable(); } ((Hashtable)container[cookie["DOMAIN"]])[cookie["name"]] = cookie; } } }
public static StoreKitTransaction transactionFromHashtable( Hashtable ht ) { var transaction = new StoreKitTransaction(); if( ht.ContainsKey( "productIdentifier" ) ) transaction.productIdentifier = ht["productIdentifier"].ToString(); if( ht.ContainsKey( "base64EncodedReceipt" ) ) transaction.base64EncodedTransactionReceipt = ht["base64EncodedReceipt"].ToString(); if( ht.ContainsKey( "quantity" ) ) transaction.quantity = int.Parse( ht["quantity"].ToString() ); return transaction; }
/* ============================================================================ Hashtable functions ============================================================================ */ public static void FromHashtable(Hashtable ht, string key, ref float data) { if(ht.ContainsKey(key)) { data = float.Parse((string)ht[key]); } }
static void Main() { Hashtable artists = new Hashtable(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load("../../../albums.xml"); string xPathQuery = "/albums/album/artist"; XmlNodeList artistsList = xmlDoc.SelectNodes(xPathQuery); foreach (XmlNode artistNode in artistsList) { string artistName = artistNode.InnerText; if (artists.ContainsKey(artistName)) { artists[artistName] = (int) artists[artistName] + 1; } else { artists.Add(artistName, 1); } } var artistsEnumerator = artists.GetEnumerator(); while (artistsEnumerator.MoveNext()) { Console.WriteLine(artistsEnumerator.Key + " " + artistsEnumerator.Value); } }
static PHPSerializer() { __ns = new Hashtable(); Assembly[] assem = AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < assem.Length; i++) { Module[] m = assem[i].GetModules(); for (int j = 0; j < m.Length; j++) { try { Type[] t = m[j].GetTypes(); for (int k = 0; k < t.Length; k++) { if (t[k].Namespace != null && !__ns.ContainsKey(t[k].Namespace)) { __ns[t[k].Namespace] = assem[i].FullName; } } } catch { } } } }
void Start() { int i = 0; var cubeSize = cubePrefab.transform.localScale.x; int width = images [0].width; int height = images [0].height; var materials = new Hashtable (); frames = new GameObject[images.Length]; foreach (var image in images) { Color32[] pixels = image.GetPixels32 (); GameObject container = Instantiate (containerPrefab); var px = 0; container.transform.parent = gameObject.transform; container.transform.localPosition = new Vector3 (0f, 0f, 0f); for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { var pixel = pixels [px]; px++; if (pixel.a == 0) continue; // pixel.a = (byte)((float)pixel.a / 2); var cube = (GameObject)Instantiate (cubePrefab); var hash = pixel.GetHashCode (); Material material; if (!materials.ContainsKey (hash)) { material = cube.GetComponent<Renderer> ().material; material.SetColor ("_Color", pixel); material.SetColor ("_EmissionColor", pixel); materials.Add (hash, material); } else { material = (Material)materials [hash]; } cube.transform.parent = container.transform; cube.GetComponent<Renderer> ().material = material; cube.transform.localPosition = new Vector3 ((float)x * cubeSize, (float)y * cubeSize, 0); } } container.transform.localScale = new Vector3 (1f, 1f, 1f); frames [i] = container; if (i != 0) setVisiblity (container, false); i++; } InvokeRepeating ("nextFrame", timePerFrame, timePerFrame); }
public override string Process() { Hashtable ps = Core.Utility.ParseJson(Data as string) as Hashtable; string action = ps["Action"] as string; AccountInfo cu = ServerImpl.Instance.GetCurrentUser(Context); if (action == "GetTempGroups") { DataRowCollection items = ServerImpl.Instance.CommonStorageImpl.GetTempGroups(cu.ID); Hashtable temp_groups = new Hashtable(); foreach (DataRow item in items) { AccountInfo ginfo = AccountImpl.Instance.GetUserInfo(Convert.ToInt32(item["ID"])); if (!temp_groups.ContainsKey(ginfo.ID)) { temp_groups[ginfo.ID] = ginfo.DetailsJson; } } return Utility.RenderHashJson( "TempGroups", temp_groups ); } else if (action == "GetCommFriends") { DataRowCollection items = ServerImpl.Instance.CommonStorageImpl.GetCommFriends(cu.ID); List<AccountInfo.Details> comm_friends = new List<AccountInfo.Details>(); foreach (DataRow item in items) { comm_friends.Add(AccountImpl.Instance.GetUserInfo(Convert.ToInt32(item["CommFriendID"])).DetailsJson); } return Utility.RenderHashJson( "CommFriends", comm_friends ); } throw new NotImplementedException(String.Format("Command \"{0}\" isn't implemented", action)); }
public void TestAddRemoveLargeAmountNumbers() { Hashtable ht = new Hashtable(); //[] Read all of the doubles from the file and store them into the hashtable int count = 0; foreach (var number in s_AddStressInputData) { ht.Add(number, count++); } //[] Read all of the doubles from the file and make sure they exist in the hashtable hashtable count = 0; foreach (var tempLong in s_AddStressInputData) { Assert.Equal((int)ht[tempLong], count); Assert.True(ht.ContainsKey(tempLong)); ++count; } //[] Remove all of the entries foreach (var tempLong in s_AddStressInputData) { ht.Remove(tempLong); } Assert.Equal(0, ht.Count); }
public void SetData(Hashtable ht) { this.spawnID = int.Parse((string)ht["spawn"]); if(ht.ContainsKey("outtime")) { this.fadeOutTime = float.Parse((string)ht["outtime"]); this.fadeOutInterpolate = (EaseType)System.Enum.Parse( typeof(EaseType), (string)ht["outtype"]); } if(ht.ContainsKey("intime")) { this.fadeInTime = float.Parse((string)ht["intime"]); this.fadeInInterpolate = (EaseType)System.Enum.Parse( typeof(EaseType), (string)ht["intype"]); } if(ht.ContainsKey(XMLHandler.NODES)) { ArrayList s = ht[XMLHandler.NODES] as ArrayList; foreach(Hashtable ht2 in s) { if(ht2[XMLHandler.NODE_NAME] as string == TeleportTarget.SCENE) { this.sceneName = ht2[XMLHandler.CONTENT] as string; } else if(ht2[XMLHandler.NODE_NAME] as string == TeleportTarget.VARIABLES) { this.variables.SetData(ht2); } } } }
static void Main() { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load("../../../catalog.xml"); string xPathQuery = "/catalog/album"; XmlNodeList albumsList = xmlDoc.SelectNodes(xPathQuery); Hashtable hash = new Hashtable(); List<string> autors = new List<string>(); foreach (XmlNode node in albumsList) { string autorName = node.SelectSingleNode("artist").InnerText; if (!hash.ContainsKey(autorName)) { hash.Add(autorName,1); autors.Add(autorName); } else { int count = (int)hash[autorName]; hash[autorName] = count + 1; } } foreach (var autor in autors) { Console.WriteLine("Autor: {0} have {1} albums in the catalog.", autor, hash[autor]); } }
public static void enablePromptAfterInstall( bool enable ) { // find all the config.plist files in plugin directories string basePath = Path.Combine( Application.dataPath, "Editor" ); var dirInfo = new DirectoryInfo( basePath ); var pluginDirs = from dir in dirInfo.GetDirectories() let files = dir.GetFiles( "config.plist" ) where files.Length == 1 select files[0]; // loop through our pluginDirs foreach( var dir in pluginDirs ) { if( !File.Exists( dir.FullName ) ) continue; // initialize the hashtable and plistKeys Hashtable plistContents = new Hashtable(); PListEditor.loadPlistFromFile( dir.FullName, plistContents ); if( plistContents.ContainsKey( "neverShowCompletedMessage" ) ) { plistContents["neverShowCompletedMessage"] = !enable; PListEditor.savePlistToFile( dir.FullName, plistContents ); } } }
//执行圆球范围的伤害,伤害随离中心距离增加而递减 public static void impSphereAreaHarm(Vector3 pCenterPos, float pHarmRadius,float pMinRate, float pHarmValueInCentre, int pHarmLayerMask, canHarmFunc pCanHarmFunc, Life.HarmType pHarmType) { //现在用于存储有生命的物体,离爆炸点的最近距离 Hashtable lInjuredLifeMinDistance = new Hashtable(); Collider[] lColliderList = Physics.OverlapSphere(pCenterPos, pHarmRadius, pHarmLayerMask); //搜寻范围内的Life,并寻找最短距离 foreach (Collider i in lColliderList) { //Trigger 也会被探测到 if (i.isTrigger) continue; Life lLife = Life.getLifeFromTransform(i.transform); if (lLife) { //lLife.injure(harmValueInCentre); //获得物体离中心pCenterPos的最近距离 Vector3 lClosestPoint = i.ClosestPointOnBounds(pCenterPos); float lDistance = Vector3.Distance(lClosestPoint, pCenterPos); //因为一个有Life的物体上,可能有多个Collider if (lInjuredLifeMinDistance.ContainsKey(lLife)) { float lObjectDistance = (float)lInjuredLifeMinDistance[lLife]; if (lObjectDistance > lDistance) { //相同Life时,若距离比之前获得的Collider物体小,则替换 //print(""+lInjuredLifeMinDistance[lLife]+">"+lDistance); lInjuredLifeMinDistance[lLife] = lDistance; } } else lInjuredLifeMinDistance[lLife] = lDistance; } } //执行伤害 foreach (System.Collections.DictionaryEntry lifeToDistance in lInjuredLifeMinDistance) { // The hit points we apply fall decrease with distance from the explosion point Life lLifeImp = (Life)lifeToDistance.Key; //判断是否可以执行伤害 if(pCanHarmFunc(lLifeImp)) { float lDistanceImp = (float)lifeToDistance.Value; float lHarmRange = Mathf.Lerp(pMinRate, 1f, 1.0f - Mathf.Clamp01(lDistanceImp / pHarmRadius)); //print(lDistanceImp); //print(lHarmRange); //print(lHarmRange *harmValueInCentre ); lLifeImp.injure((int)(lHarmRange * pHarmValueInCentre), pHarmType); } } //lInjuredLifeMinDistance.Clear(); }
private List<long> GetTreeChecked() { if (TreeView1.CheckedNodes.Count == 0) return null; Hashtable parentNodes = new Hashtable(); AuthorityManager authMgr = new AuthorityManager(userInfo); List<PermissionInfo> lstAll = authMgr.accountRoleEx.GetOwnPermissionByLoginApplication(userInfo.Login, portalName); foreach (PermissionInfo ai in lstAll) { if (string.IsNullOrEmpty(ai.Privilege.Privilege)) parentNodes.Add(ai.Id.ToString(), null); } List<long> lst = new List<long>(); for (int i = 0; i < TreeView1.CheckedNodes.Count; i++) { if (TreeView1.CheckedNodes[i].Value.Equals("Root")) continue; if (parentNodes.ContainsKey(TreeView1.CheckedNodes[i].Value)) continue; lst.Add( Convert.ToInt32( TreeView1.CheckedNodes[i].Value ) ); } return lst; }
public void DeleteKey() { Hashtable<string, int> phonebook = new Hashtable<string, int>(100); phonebook.Add("Razvan Hidan", 0744596712); phonebook.Add("Ionut Marin", 076653421); phonebook.Add("Bogdan Dragos", 07111111); phonebook.Add("Maria Marioara", 0783442); phonebook.Add("Ana Blandiana", 09883773); phonebook.Add("Mihai Eminescu", 0038874); phonebook.Remove("Razvan Hidan"); phonebook.ContainsKey("Razvan Hidan").ShouldBeFalse(); phonebook.Remove("Maria Marioara"); phonebook.ContainsKey("Maria Marioara").ShouldBeFalse(); phonebook.Remove("Mihai Eminescu"); phonebook.ContainsKey("Mihai Eminescu").ShouldBeFalse(); }
/// <summary>Called by PUN when new properties for the room were set (by any client in the room).</summary> public void OnPhotonCustomRoomPropertiesChanged(Hashtable propertiesThatChanged) { if (propertiesThatChanged.ContainsKey(StartTimeKey)) { StartTime = (double)propertiesThatChanged[StartTimeKey]; } }
/// <summary> /// Verify items in the group are not in the table /// Assumes all items in the group have the same, specified, type /// </summary> private void MustNotBeInTable(Hashtable table, string name, BuildItemGroup group) { if (table?.ContainsKey(name) == true) { BuildItemGroup existing = (BuildItemGroup)table[name]; if (existing != null) { foreach (BuildItem item in group) { ErrorUtilities.VerifyThrowNoAssert(!existing.Items.Contains(item), "Item should not be in table"); } } } }
public static bool Contains(Mobile sender) { return(m_KeyedBySender.ContainsKey(sender)); }
public static bool IsHandling(Mobile check) { return(m_KeyedByHandler.ContainsKey(check)); }
protected void BindData(DateTime?startDate, DateTime?endDate) { DateTime?timezoneStartDate = new DateTime(); DateTime?timezoneEndDate = new DateTime(); if (OrderHelper.IsReportEST()) { timezoneStartDate = DateTimeUtil.GetEastCoastStartDate(rangeDateControlCriteria.StartDateValueLocal); timezoneEndDate = DateTimeUtil.GetEastCoastDate(rangeDateControlCriteria.EndDateValueLocal); } else//PST { timezoneStartDate = rangeDateControlCriteria.StartDateValueLocal; timezoneEndDate = DateTimeUtil.GetEndDate(rangeDateControlCriteria.EndDateValueLocal); liSubHeader.Text = DateTime.Now.DayOfWeek + " " + DateTime.Now.ToShortTimeString() + " (PST)"; } List <ReportFields> ItemList = new OrderManager().GetOrderCustomFieldReport(timezoneStartDate, timezoneEndDate, 2, false); try { Data rptData = new ReportWSSoapClient().GetDataFromTimeframe(hitsLinkUserName, hitsLinkPassword, ReportsEnum.eCommerceActivitySummary, TimeFrameEnum.Daily, Convert.ToDateTime(startDate), Convert.ToDateTime(endDate), 100000000, 0, 0); for (int i = 0; i <= rptData.Rows.GetUpperBound(0); i++) { HitLinkVisitor.Add(rptData.Rows[i].Columns[0].Value.ToLower(), rptData.Rows[i].Columns[7].Value); } } catch (Exception ex) { } //Update Version List information foreach (ReportFields item in ItemList) { if (HitLinkVisitor.ContainsKey(item.Title)) { decimal visitor = Convert.ToDecimal(HitLinkVisitor[item.Title].ToString()); visitor = Math.Abs(visitor); item.UniqueVisitors = visitor; if (visitor > 0) { item.Conversion = Math.Round((Convert.ToDecimal(item.TotalOrders) * 100) / visitor, 1); item.RevenuePerVisit = Convert.ToDecimal(item.TotalRevenue) / visitor; } else { item.UniqueVisitors = 0; item.Conversion = 0; item.RevenuePerVisit = 0; } } else { item.UniqueVisitors = 0; item.Conversion = 0; item.RevenuePerVisit = 0; } } dlVersionList.DataSource = ItemList; dlVersionList.DataBind(); //FCLiteral.Text = CreateCharts(dtCollectionList[1dtCollectionList }
public bool CheckAjaxAuthKey(Guid key) { return(usersByKey.ContainsKey(key)); }
public long m_lngGetCheckItemTree(System.Security.Principal.IPrincipal p_objPrincipal, out clsLISUserGroupNode root) { long lngRes = 0; root = null; clsPrivilegeHandleService objPrivilege = new clsPrivilegeHandleService(); lngRes = objPrivilege.m_lngCheckCallPrivilege (p_objPrincipal, "com.digitalwave.iCare.middletier.clsSchBaseInfoSvc", "m_lngGetCheckItemTree"); if (lngRes <= 0) { return(-1); } com.digitalwave.iCare.middletier.HRPService.clsHRPTableService objHRPSvc = new clsHRPTableService(); #region SQL string strSQL1 = @"SELECT t1.check_item_id_chr, t1.check_item_name_vchr FROM t_bse_lis_check_item t1"; string strSQL2 = @"SELECT t1.apply_unit_id_chr, t1.apply_unit_name_vchr FROM t_aid_lis_apply_unit t1"; string strSQL3 = @"SELECT t1.user_group_id_chr, t1.user_group_name_vchr FROM t_aid_lis_appuser_group t1"; string strSQL4 = @"select check_item_id_chr, apply_unit_id_chr, print_seq_int from t_aid_lis_apply_unit_detail"; string strSQL5 = @"SELECT user_group_id_chr, apply_unit_id_chr FROM t_aid_lis_appuser_group_detail"; string strSQL6 = @"SELECT user_group_id_chr, child_user_group_id_chr FROM t_aid_lis_appuser_group_relate"; #endregion DataTable dtbResultItem = null; DataTable dtbResultUnit = null; DataTable dtbResultUnitDetail = null; DataTable dtbResultGroup = null; DataTable dtbResultGroupDetail = null; DataTable dtbResultGroupRelate = null; try { lngRes = objHRPSvc.lngGetDataTableWithoutParameters(strSQL1, ref dtbResultItem); lngRes = objHRPSvc.lngGetDataTableWithoutParameters(strSQL2, ref dtbResultUnit); lngRes = objHRPSvc.lngGetDataTableWithoutParameters(strSQL3, ref dtbResultGroup); lngRes = objHRPSvc.lngGetDataTableWithoutParameters(strSQL4, ref dtbResultUnitDetail); lngRes = objHRPSvc.lngGetDataTableWithoutParameters(strSQL5, ref dtbResultGroupDetail); lngRes = objHRPSvc.lngGetDataTableWithoutParameters(strSQL6, ref dtbResultGroupRelate); System.Collections.Hashtable hasItem = new Hashtable(); System.Collections.Hashtable hasUnit = new Hashtable(); System.Collections.Hashtable hasGroup = new Hashtable(); System.Collections.Hashtable hasTopGroup = new Hashtable(); if (dtbResultItem != null) { foreach (DataRow dtrItem in dtbResultItem.Rows) { clsLISCheckItemNode node = new clsLISCheckItemNode(); node.strID = dtrItem["check_item_id_chr"].ToString(); node.strName = dtrItem["check_item_name_vchr"].ToString(); hasItem.Add(node.strID, node); } } if (dtbResultUnit != null) { foreach (DataRow dtrUnit in dtbResultUnit.Rows) { clsLISApplyUnitNode node = new clsLISApplyUnitNode(); node.strID = dtrUnit["APPLY_UNIT_ID_CHR"].ToString(); node.Name = dtrUnit["APPLY_UNIT_NAME_VCHR"].ToString(); hasUnit.Add(node.strID, node); } } if (dtbResultGroup != null) { foreach (DataRow dtrGroup in dtbResultGroup.Rows) { clsLISUserGroupNode node = new clsLISUserGroupNode(); node.strID = dtrGroup["USER_GROUP_ID_CHR"].ToString(); node.strName = dtrGroup["USER_GROUP_NAME_VCHR"].ToString(); hasGroup.Add(node.strID, node); hasTopGroup.Add(node.strID, node); } } if (dtbResultUnitDetail != null) { foreach (DataRow dtrUnitDetail in dtbResultUnitDetail.Rows) { string strUnitID = dtrUnitDetail["APPLY_UNIT_ID_CHR"].ToString(); string strItemID = dtrUnitDetail["CHECK_ITEM_ID_CHR"].ToString(); if (hasUnit.ContainsKey(strUnitID) && hasItem.ContainsKey(strItemID)) { if (((clsLISApplyUnitNode)hasUnit[strUnitID]).objItems == null) { ((clsLISApplyUnitNode)hasUnit[strUnitID]).objItems = new System.Collections.Generic.List <clsLISCheckItemNode>(); } ((clsLISApplyUnitNode)hasUnit[strUnitID]).objItems.Add((clsLISCheckItemNode)hasItem[strItemID]); } } } hasItem = null; if (dtbResultGroupDetail != null) { foreach (DataRow dtrGroupDetail in dtbResultGroupDetail.Rows) { string strGroupID = dtrGroupDetail["USER_GROUP_ID_CHR"].ToString(); string strUnitID = dtrGroupDetail["APPLY_UNIT_ID_CHR"].ToString(); if (hasGroup.ContainsKey(strGroupID) && hasUnit.ContainsKey(strUnitID)) { if (((clsLISUserGroupNode)hasGroup[strGroupID]).objUnitNodes == null) { ((clsLISUserGroupNode)hasGroup[strGroupID]).objUnitNodes = new System.Collections.Generic.List <clsLISApplyUnitNode>(); } ((clsLISUserGroupNode)hasGroup[strGroupID]).objUnitNodes.Add((clsLISApplyUnitNode)hasUnit[strUnitID]); } } } hasUnit = null; if (dtbResultGroupRelate != null) { foreach (DataRow dtrGroupRelate in dtbResultGroupRelate.Rows) { string strGroupID1 = dtrGroupRelate["USER_GROUP_ID_CHR"].ToString(); string strGroupID2 = dtrGroupRelate["CHILD_USER_GROUP_ID_CHR"].ToString(); if (hasGroup.ContainsKey(strGroupID1) && hasGroup.ContainsKey(strGroupID2)) { if (((clsLISUserGroupNode)hasGroup[strGroupID1]).objChildNodes == null) { ((clsLISUserGroupNode)hasGroup[strGroupID1]).objChildNodes = new System.Collections.Generic.List <clsLISUserGroupNode>(); } ((clsLISUserGroupNode)hasGroup[strGroupID1]).objChildNodes.Add((clsLISUserGroupNode)hasGroup[strGroupID2]); hasTopGroup.Remove(strGroupID2); } } } hasGroup = null; root = new clsLISUserGroupNode(); root.objChildNodes = new System.Collections.Generic.List <clsLISUserGroupNode>(); foreach (clsLISUserGroupNode groupNode in hasTopGroup.Values) { root.objChildNodes.Add(groupNode); } hasTopGroup = null; } catch (Exception objEx) { com.digitalwave.Utility.clsLogText objLogger = new clsLogText(); objLogger.LogError(objEx); lngRes = 0; root = null; } return(lngRes); }
internal FinderPatternInfo Find(Hashtable hints) { bool tryHarder = hints?.ContainsKey(DecodeHintType.TRY_HARDER) == true; int maxI = Image.Height; int maxJ = Image.Width; // We are looking for black/white/black/white/black modules in // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far // Let's assume that the maximum version QR Code we support takes up 1/4 the height of the // image, and then account for the center being 3 modules in size. This gives the smallest // number of pixels the center could be, so skip this often. When trying harder, look for all // QR versions regardless of how dense they are. int iSkip = (3 * maxI) / (4 * MAX_MODULES); if (iSkip < MIN_SKIP || tryHarder) { iSkip = MIN_SKIP; } bool done = false; int[] stateCount = new int[5]; for (int i = iSkip - 1; i < maxI && !done; i += iSkip) { // Get a row of black/white values stateCount[0] = 0; stateCount[1] = 0; stateCount[2] = 0; stateCount[3] = 0; stateCount[4] = 0; int currentState = 0; for (int j = 0; j < maxJ; j++) { if (Image.Get_Renamed(j, i)) { // Black pixel if ((currentState & 1) == 1) { // Counting white pixels currentState++; } stateCount[currentState]++; } else { // White pixel if ((currentState & 1) == 0) { // Counting black pixels if (currentState == 4) { // A winner? if (FoundPatternCross(stateCount)) { // Yes bool confirmed = HandlePossibleCenter(stateCount, i, j); if (confirmed) { // Start examining every other line. Checking each line turned out to be too // expensive and didn't improve performance. iSkip = 2; if (hasSkipped) { done = HaveMultiplyConfirmedCenters(); } else { int rowSkip = FindRowSkip(); if (rowSkip > stateCount[2]) { // Skip rows between row of lower confirmed center // and top of presumed third confirmed center // but back up a bit to get a full chance of detecting // it, entire width of center of finder pattern // Skip by rowSkip, but back off by stateCount[2] (size of last center // of pattern we saw) to be conservative, and also back off by iSkip which // is about to be re-added i += rowSkip - stateCount[2] - iSkip; j = maxJ - 1; } } } else { // Advance to next black pixel do { j++; }while (j < maxJ && !Image.Get_Renamed(j, i)); j--; // back up to that last white pixel } // Clear state to start looking again currentState = 0; stateCount[0] = 0; stateCount[1] = 0; stateCount[2] = 0; stateCount[3] = 0; stateCount[4] = 0; } else { // No, shift counts back by two stateCount[0] = stateCount[2]; stateCount[1] = stateCount[3]; stateCount[2] = stateCount[4]; stateCount[3] = 1; stateCount[4] = 0; currentState = 3; } } else { stateCount[++currentState]++; } } else { // Counting white pixels stateCount[currentState]++; } } } if (FoundPatternCross(stateCount)) { bool confirmed = HandlePossibleCenter(stateCount, i, maxJ); if (confirmed) { iSkip = stateCount[0]; if (hasSkipped) { // Found a third one done = HaveMultiplyConfirmedCenters(); } } } } FinderPattern[] patternInfo = SelectBestPatterns(); ResultPoint.OrderBestPatterns(patternInfo); return(new FinderPatternInfo(patternInfo)); }
public static void Import(XmlNode n, bool ImportStructure) { if (n == null) { throw new ArgumentNullException("Node cannot be null"); } // // using xmlHelper not XmlHelper because GetNodeValue has gone all // Internall on us, this function probibly does belong in the core // (umbraco.cms.buisnesslogic.packageInstaller) so that packages // can also do media types, but at the mo, it's uSync's until i read // about contributing to the core. // // using user 0 will come unstuck oneday User u = new User(0); // does this media type already exist ? string alias = xmlHelper.GetNodeValue(n.SelectSingleNode("Info/Alias")); if (String.IsNullOrEmpty(alias)) { throw new Exception("no alias in sync file"); } MediaType mt = null; try { mt = MediaType.GetByAlias(alias); } catch (Exception ex) { LogHelper.Debug <SyncMediaTypes>("Media type corrupt? {0}", () => ex.ToString()); } if (mt == null) { // we are new mt = MediaType.MakeNew(u, xmlHelper.GetNodeValue(n.SelectSingleNode("Info/Name"))); mt.Alias = xmlHelper.GetNodeValue(n.SelectSingleNode("Info/Alias")); } else { mt.Text = xmlHelper.GetNodeValue(n.SelectSingleNode("Info/Name")); } // core mt.IconUrl = xmlHelper.GetNodeValue(n.SelectSingleNode("Info/Icon")); mt.Thumbnail = xmlHelper.GetNodeValue(n.SelectSingleNode("Info/Thumbnail")); mt.Description = xmlHelper.GetNodeValue(n.SelectSingleNode("Info/Description")); // v6 you can have allow at root. // Allow at root (check for node due to legacy) bool allowAtRoot = false; string allowAtRootNode = xmlHelper.GetNodeValue(n.SelectSingleNode("Info/AllowAtRoot")); if (!String.IsNullOrEmpty(allowAtRootNode)) { bool.TryParse(allowAtRootNode, out allowAtRoot); } mt.AllowAtRoot = allowAtRoot; //Master content type string master = xmlHelper.GetNodeValue(n.SelectSingleNode("Info/Master")); if (!String.IsNullOrEmpty(master)) { // throw new System.Exception(String.Format("Throwing in {0}, master {1}", mt.Text, master)); try { MediaType pmt = MediaType.GetByAlias(master); if (pmt != null) { mt.MasterContentType = pmt.Id; } } catch (Exception ex) { LogHelper.Debug <SyncMediaTypes>("Media type corrupt? {0}", () => ex.ToString()); } } //tabs ContentType.TabI[] tabs = mt.getVirtualTabs; // load the current tabs string tabnames = ";"; for (int t = 0; t < tabs.Length; t++) { tabnames += tabs[t].Caption + ";"; } Hashtable ht = new Hashtable(); foreach (XmlNode t in n.SelectNodes("Tabs/Tab")) { // is this a new tab? // if ( tabnames.IndexOf(";" + xmlHelper.GetNodeValue(t.SelectSingleNode("Caption")) + ";" == -1) if (!tabnames.Contains(";" + xmlHelper.GetNodeValue(t.SelectSingleNode("Caption")) + ";")) { ht.Add(int.Parse(xmlHelper.GetNodeValue(t.SelectSingleNode("Id"))), mt.AddVirtualTab(xmlHelper.GetNodeValue(t.SelectSingleNode("Caption")))); } } // clear cache mt.ClearVirtualTabs(); // put tabs in a hashtable, so we can check they exist when we add properties. Hashtable tabList = new Hashtable(); foreach (ContentType.TabI t in mt.getVirtualTabs.ToList()) { if (!tabList.ContainsKey(t.Caption)) { tabList.Add(t.Caption, t.Id); } } // properties.. global::umbraco.cms.businesslogic.datatype.controls.Factory f = new global::umbraco.cms.businesslogic.datatype.controls.Factory(); foreach (XmlNode gp in n.SelectNodes("GenericProperties/GenericProperty")) { int dfId = 0; Guid dtId = new Guid(xmlHelper.GetNodeValue(gp.SelectSingleNode("Type"))); if (gp.SelectSingleNode("Definition") != null && !string.IsNullOrEmpty(xmlHelper.GetNodeValue(gp.SelectSingleNode("Definition")))) { Guid dtdId = new Guid(xmlHelper.GetNodeValue(gp.SelectSingleNode("Definition"))); if (CMSNode.IsNode(dtdId)) { dfId = new CMSNode(dtdId).Id; } } if (dfId == 0) { try { dfId = findDataTypeDefinitionFromType(ref dtId); } catch { throw new Exception(String.Format("Cound not find datatype with id {0}.", dtId)); } } //fix for ritch text editor if (dfId == 0 && dtId == new Guid("a3776494-0574-4d93-b7de-efdfdec6f2d1")) { dtId = new Guid("83722133-f80c-4273-bdb6-1befaa04a612"); dfId = findDataTypeDefinitionFromType(ref dtId); } if (dfId != 0) { PropertyType pt = mt.getPropertyType(xmlHelper.GetNodeValue(gp.SelectSingleNode("Alias"))); if (pt == null) { mt.AddPropertyType( global::umbraco.cms.businesslogic.datatype.DataTypeDefinition.GetDataTypeDefinition(dfId), xmlHelper.GetNodeValue(gp.SelectSingleNode("Alias")), xmlHelper.GetNodeValue(gp.SelectSingleNode("Name")) ); pt = mt.getPropertyType(xmlHelper.GetNodeValue(gp.SelectSingleNode("Alias"))); } else { pt.DataTypeDefinition = global::umbraco.cms.businesslogic.datatype.DataTypeDefinition.GetDataTypeDefinition(dfId); pt.Name = xmlHelper.GetNodeValue(gp.SelectSingleNode("Name")); } pt.Mandatory = bool.Parse(xmlHelper.GetNodeValue(gp.SelectSingleNode("Mandatory"))); pt.ValidationRegExp = xmlHelper.GetNodeValue(gp.SelectSingleNode("Validation")); pt.Description = xmlHelper.GetNodeValue(gp.SelectSingleNode("Description")); // tab try { if (tabList.ContainsKey(xmlHelper.GetNodeValue(gp.SelectSingleNode("Tab")))) { pt.TabId = (int)tabList[xmlHelper.GetNodeValue(gp.SelectSingleNode("Tab"))]; } } catch (Exception ee) { LogHelper.Debug <SyncMediaTypes>("Packager: Error assigning property to tab: {0}", () => ee.ToString()); } pt.Save(); } } if (ImportStructure) { if (mt != null) { ArrayList allowed = new ArrayList(); foreach (XmlNode structure in n.SelectNodes("Structure/MediaType")) { try { MediaType dtt = MediaType.GetByAlias(xmlHelper.GetNodeValue(structure)); if (dtt != null) { allowed.Add(dtt.Id); } } catch (Exception ex) { LogHelper.Info <uSync>("Can't find structure mediatype - so skipping"); } } int[] adt = new int[allowed.Count]; for (int i = 0; i < allowed.Count; i++) { adt[i] = (int)allowed[i]; } mt.AllowedChildContentTypeIDs = adt; } } mt.Save(); /* * foreach (MediaType.TabI t in mt.getVirtualTabs.ToList()) * { * MediaType.FlushTabCache(t.Id, mt.Id); * } * * // need to do this more i think * MediaType.FlushFromCache(mt.Id); */ }
/// <summary> /// Difunde el mensaje de un usuario a todos los usuarios conectados a la sala. /// </summary> /// <param name="mensaje">Mensaje del Usuario</param> /// <param name="nombre">Nombre del usuario</param> /// <param name="flag">Bandera que se utiliza para determinar si se agrega el texto /// "dice" al mensaje enviado por el usuario</param> /// public void iniciarServidor() { try { //Inicalizamos nuestro hashtable clientes_conectados = new Hashtable(); //Inicializamos un nuevo servidor en la IP y puerto seleccionado. servidor = new TcpListener(IPAddress.Parse(txtIP.Text), int.Parse(txtPuerto.Text)); //Iniciamos el servidor servidor.Start(); //Indicamos que el servidor esta listo para aceptar peticiones de los clientes mensajeChat = "Ha iniciado el Servidor"; Mensaje(); //definimos la variable de acepcacion de clientes TcpClient cliente; //Sólo aceptaremos mensajes de máximo 256 caracteres Byte[] bytesCliente = new Byte[256]; NetworkStream streamCliente; Chat chat; while (true) { //Acepta la petición de un cliente cliente = servidor.AcceptTcpClient(); //Leemos el mensaje del cliente streamCliente = cliente.GetStream(); //bytesCliente sólo acepta mensajes de máximo 160 caracteres streamCliente.Read(bytesCliente, 0, bytesCliente.Length); //Traducimos el stream de bytes a un string en codificación ASCII mensajeCliente = Encoding.ASCII.GetString(bytesCliente, 0, bytesCliente.Length); mensajeCliente = mensajeCliente.Substring(0, mensajeCliente.IndexOf("$")); //Verificamos si ya existe ese nombre de usuario. while (clientes_conectados.ContainsKey(mensajeCliente)) { Byte[] bytes = Encoding.ASCII.GetBytes("/*usuario duplicado*/"); //transmitimos el mensaje streamCliente.Write(bytes, 0, bytes.Length); streamCliente.Flush(); mensajeCliente = mensajeCliente + "1"; } //Realmente no hacemos ninguna validación posterior ni se manda un mensaje al //usuario pero por funcionalidad agregaremos esta condición. clientes_conectados.Add(mensajeCliente, cliente); try { switch (mensajeCliente.Substring(0, (mensajeCliente.IndexOf(" ")))) { case "Amistad": contadorAmistad++; break; case "Amor": contadorAmor++; break; case "Culinaria": contadorCulinaria++; break; case "Conocimiento": contadorConocimiento++; break; } }catch (Exception ex) {} mensajeChat = string.Format("{0} se ha unido al servidor", mensajeCliente); Mensaje(); //Mandamos el mensaje a todos los clientes el mensaje DifundirATodos(mensajeCliente, mensajeCliente, false); //Ciclamos el proceso para que se quede el servidor en espera de nuevas conexiones o mensajes chat = new Chat(cliente, mensajeCliente); } } catch (Exception ex) { } finally { if (servidor != null) { servidor.Stop(); } } }
public static bool ContainsData(string sessionKey, string controlID) { Hashtable ht = HttpContext.Current.Session[sessionKey] as Hashtable; return(ht != null && ht.ContainsKey(controlID)); }
private TypeMetadata ReadTypeMetadata(BinaryReader reader, bool isRuntimeObject, bool hasTypeInfo) { TypeMetadata metadata = new TypeMetadata(); string className = reader.ReadString(); int fieldCount = reader.ReadInt32(); Type[] types = new Type[fieldCount]; string[] names = new string[fieldCount]; for (int n = 0; n < fieldCount; n++) { names [n] = reader.ReadString(); } if (hasTypeInfo) { TypeTag[] codes = new TypeTag[fieldCount]; for (int n = 0; n < fieldCount; n++) { codes [n] = (TypeTag)reader.ReadByte(); } for (int n = 0; n < fieldCount; n++) { types [n] = ReadType(reader, codes[n]); } } // Gets the type if (!isRuntimeObject) { long assemblyId = (long)reader.ReadUInt32(); metadata.Type = GetDeserializationType(assemblyId, className); } else { metadata.Type = Type.GetType(className, true); } metadata.MemberTypes = types; metadata.MemberNames = names; metadata.FieldCount = names.Length; // Now check if this objects needs a SerializationInfo struct for deserialziation. // SerializationInfo is needed if the object has to be deserialized using // a serialization surrogate, or if it implements ISerializable. if (_surrogateSelector != null) { // check if the surrogate selector handles objects of the given type. ISurrogateSelector selector; ISerializationSurrogate surrogate = _surrogateSelector.GetSurrogate(metadata.Type, _context, out selector); metadata.NeedsSerializationInfo = (surrogate != null); } if (!metadata.NeedsSerializationInfo) { // Check if the object is marked with the Serializable attribute if (!metadata.Type.IsSerializable) { throw new SerializationException("Serializable objects must be marked with the Serializable attribute"); } metadata.NeedsSerializationInfo = typeof(ISerializable).IsAssignableFrom(metadata.Type); if (!metadata.NeedsSerializationInfo) { metadata.MemberInfos = new MemberInfo [fieldCount]; for (int n = 0; n < fieldCount; n++) { FieldInfo field = null; string memberName = names[n]; int i = memberName.IndexOf('+'); if (i != -1) { string baseTypeName = names[n].Substring(0, i); memberName = names[n].Substring(i + 1); Type t = metadata.Type.BaseType; while (t != null) { if (t.Name == baseTypeName) { field = t.GetField(memberName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); break; } else { t = t.BaseType; } } } else { field = metadata.Type.GetField(memberName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } if (field == null) { throw new SerializationException("Field \"" + names[n] + "\" not found in class " + metadata.Type.FullName); } metadata.MemberInfos [n] = field; if (!hasTypeInfo) { types [n] = field.FieldType; } } metadata.MemberNames = null; // Info now in MemberInfos } } // Registers the type's metadata so it can be reused later if // a RefTypeObject element is found if (!_typeMetadataCache.ContainsKey(metadata.Type)) { _typeMetadataCache [metadata.Type] = metadata; } return(metadata); }
/// <summary> /// 添加材质 /// </summary> /// <param name="renderer">Renderer.</param> /// <param name="shader">Shader.</param> /// <param name="materialName">Material name.</param> private static void SetMaterial(Renderer renderer, Shader shader, string materialName, Hashtable shaderParams) { if (renderer == null || shader == null || string.IsNullOrEmpty(materialName)) { return; } if (GetMaterial(renderer, materialName) == null) { Material[] sharedMaterials = renderer.sharedMaterials; int materialLength = sharedMaterials.Length; Material[] materialList = new Material[materialLength * 2]; for (int index = 0; index < materialLength; index++) { materialList[index] = sharedMaterials[index]; Material material = new Material(shader); material.name = materialName; if (material.HasProperty("_MainTex")) { if (shaderParams != null && shaderParams.ContainsKey("_MainTex")) { material.SetTexture("_MainTex", (Texture)shaderParams["_MainTex"]); } else { if (sharedMaterials[index].HasProperty("_MainTex")) { Texture mainTexture = sharedMaterials[index].GetTexture("_MainTex"); if (mainTexture != null) { material.SetTexture("_MainTex", mainTexture); } } } } if (material.HasProperty("_BumpMap")) { if (shaderParams != null && shaderParams.ContainsKey("_BumpMap")) { material.SetTexture("_BumpMap", (Texture)shaderParams["_BumpMap"]); } else { if (sharedMaterials[index].HasProperty("_BumpMap")) { Texture bumpMap = sharedMaterials[index].GetTexture("_BumpMap"); if (bumpMap != null) { material.SetTexture("_BumpMap", bumpMap); } } } } if (shaderParams != null) { foreach (DictionaryEntry dictionaryEntry in shaderParams) { if (material.HasProperty(dictionaryEntry.Key.ToString())) { if (dictionaryEntry.Value.GetType() == typeof(float)) { material.SetFloat(dictionaryEntry.Key.ToString(), (float)dictionaryEntry.Value); } else if (dictionaryEntry.Value.GetType() == typeof(Color)) { material.SetColor(dictionaryEntry.Key.ToString(), (Color)dictionaryEntry.Value); } } } } materialList[index + materialLength] = material; } renderer.sharedMaterials = materialList; } }
public bool Exists(string containerName) { return(contCollection.ContainsKey(containerName)); }
public Hashtable ProcessGetMesh(Hashtable request, UUID AgentId, Caps cap) { Hashtable responsedata = new Hashtable(); responsedata["int_response_code"] = 400; //501; //410; //404; responsedata["content_type"] = "text/plain"; responsedata["int_bytes"] = 0; string meshStr = string.Empty; if (request.ContainsKey("mesh_id")) { meshStr = request["mesh_id"].ToString(); } UUID meshID = UUID.Zero; if (!String.IsNullOrEmpty(meshStr) && UUID.TryParse(meshStr, out meshID)) { if (m_assetService == null) { responsedata["int_response_code"] = 404; //501; //410; //404; responsedata["keepalive"] = false; responsedata["str_response_string"] = "The asset service is unavailable. So is your mesh."; return(responsedata); } AssetBase mesh = m_assetService.Get(meshID.ToString()); if (mesh != null) { if (mesh.Type == (SByte)AssetType.Mesh) { Hashtable headers = new Hashtable(); responsedata["headers"] = headers; string range = String.Empty; if (((Hashtable)request["headers"])["range"] != null) { range = (string)((Hashtable)request["headers"])["range"]; } else if (((Hashtable)request["headers"])["Range"] != null) { range = (string)((Hashtable)request["headers"])["Range"]; } if (!String.IsNullOrEmpty(range)) // Mesh Asset LOD // Physics { // Range request int start, end; if (TryParseRange(range, out start, out end)) { // Before clamping start make sure we can satisfy it in order to avoid // sending back the last byte instead of an error status if (start >= mesh.Data.Length) { responsedata["int_response_code"] = 404; //501; //410; //404; responsedata["content_type"] = "text/plain"; responsedata["str_response_string"] = "This range doesnt exist."; return(responsedata); } else { end = Utils.Clamp(end, 0, mesh.Data.Length - 1); start = Utils.Clamp(start, 0, end); int len = end - start + 1; //m_log.Debug("Serving " + start + " to " + end + " of " + texture.Data.Length + " bytes for texture " + texture.ID); if (start == 0 && len == mesh.Data.Length) // well redudante maybe { responsedata["int_response_code"] = (int)System.Net.HttpStatusCode.OK; responsedata["bin_response_data"] = mesh.Data; responsedata["int_bytes"] = mesh.Data.Length; } else { responsedata["int_response_code"] = (int)System.Net.HttpStatusCode.PartialContent; headers["Content-Range"] = String.Format("bytes {0}-{1}/{2}", start, end, mesh.Data.Length); byte[] d = new byte[len]; Array.Copy(mesh.Data, start, d, 0, len); responsedata["bin_response_data"] = d; responsedata["int_bytes"] = len; } } } else { m_log.Warn("[GETMESH]: Failed to parse a range from GetMesh request, sending full asset: " + (string)request["uri"]); responsedata["str_response_string"] = Convert.ToBase64String(mesh.Data); responsedata["content_type"] = "application/vnd.ll.mesh"; responsedata["int_response_code"] = 200; } } else { responsedata["str_response_string"] = Convert.ToBase64String(mesh.Data); responsedata["content_type"] = "application/vnd.ll.mesh"; responsedata["int_response_code"] = 200; } } // Optionally add additional mesh types here else { responsedata["int_response_code"] = 404; //501; //410; //404; responsedata["content_type"] = "text/plain"; responsedata["str_response_string"] = "Unfortunately, this asset isn't a mesh."; return(responsedata); } } else { responsedata["int_response_code"] = 404; //501; //410; //404; responsedata["content_type"] = "text/plain"; responsedata["str_response_string"] = "Your Mesh wasn't found. Sorry!"; return(responsedata); } } return(responsedata); }
//this method is used accept employee invoice public static void EmployeeInvoice() { Console.WriteLine("Invoices"); Console.WriteLine("*************************\n"); if (invoice_collection.Count <= 0) { Console.WriteLine("No Invoices..\nhit return to continue.."); return; } else { Invoice invoice = new Invoice(); EmployeeInfo employee = new EmployeeInfo(); Hashtable temp_collection = new Hashtable(); int i = 1; Console.WriteLine("Sr. No. Employee Id Employee Name Amount Month"); Console.WriteLine("******* *********** ************* ****** *****"); foreach (DictionaryEntry dict_entry in invoice_collection) { invoice = (Invoice)dict_entry.Value; if (invoice.accepted == true) { continue; } else { employee = (EmployeeInfo)employee_collection[dict_entry.Key]; char[] value_array = i.ToString().ToCharArray(); AlignOutput(value_array, 11); value_array = invoice.id.ToCharArray(); AlignOutput(value_array, 15); value_array = employee.name.ToCharArray(); AlignOutput(value_array, 17); value_array = (invoice.amt + "").ToCharArray(); AlignOutput(value_array, 10); value_array = invoice.mnth.ToCharArray(); AlignOutput(value_array, 14); Console.Write("\n"); temp_collection.Add(i, invoice.id); i++; } } if (i == 1) { Console.WriteLine("No Invoice Found.."); return; } Console.Write("\nInput Employee Invoice No. To Accept :: "); int invoiceNo = 0; try { invoiceNo = int.Parse(Console.ReadLine()); } catch { Console.WriteLine("Incorrect Invoice No. \nNo Match.."); return; } if (!temp_collection.ContainsKey(invoiceNo)) { Console.WriteLine("Incorrect Invoice No. \nNo Match.."); return; } invoice = (Invoice)invoice_collection[(String)temp_collection[invoiceNo]]; invoice.accepted = true; invoice_collection.Remove(invoice.id); invoice_collection.Add(invoice.id, invoice); Console.WriteLine("Accepted..\nhit return to continue.."); } }
/// <summary> /// Reduce the transform sequence tables. /// </summary> /// <param name="sequenceList">ArrayList of tables to be reduced</param> /// <param name="oldSections">Hashtable contains section id should be kept in the baseline wixout.</param> /// <param name="newSections">Hashtable contains section id should be kept in the target wixout.</param> /// <param name="customAction">Hashtable contains all the rows in the CustomAction table.</param> /// <param name="tablesToDelete">ArrayList contains tables that should be deleted.</param> /// <returns>Number of rows left</returns> private int ReduceTransformSequenceTable(ArrayList sequenceList, Hashtable oldSections, Hashtable newSections, Hashtable customAction, ArrayList tablesToDelete) { int keptRows = 0; foreach (Table currentTable in sequenceList) { for (int i = 0; i < currentTable.Rows.Count; i++) { Row row = currentTable.Rows[i]; string actionName = row.Fields[0].Data.ToString(); string[] sections = row.SectionId.Split('/'); bool isSectionIdEmpty = (sections[0] == string.Empty && sections[1] == string.Empty); if (row.Operation == RowOperation.None) { // ignore the rows without section id. if (isSectionIdEmpty) { currentTable.Rows.RemoveAt(i); i--; } else if (IsInPatchFamily(sections[0], sections[1], oldSections, newSections)) { keptRows++; } else { currentTable.Rows.RemoveAt(i); i--; } } else if (row.Operation == RowOperation.Modify) { bool sequenceChanged = row.Fields[2].Modified; bool conditionChanged = row.Fields[1].Modified; if (sequenceChanged && !conditionChanged) { keptRows++; } else if (!sequenceChanged && conditionChanged) { if (isSectionIdEmpty) { currentTable.Rows.RemoveAt(i); i--; } else if (IsInPatchFamily(sections[0], sections[1], oldSections, newSections)) { keptRows++; } else { currentTable.Rows.RemoveAt(i); i--; } } else if (sequenceChanged && conditionChanged) { if (isSectionIdEmpty) { row.Fields[1].Modified = false; keptRows++; } else if (IsInPatchFamily(sections[0], sections[1], oldSections, newSections)) { keptRows++; } else { row.Fields[1].Modified = false; keptRows++; } } } else if (row.Operation == RowOperation.Delete) { if (isSectionIdEmpty) { // it is a stardard action which is added by wix, we should keep this action. row.Operation = RowOperation.None; keptRows++; } else if (IsInPatchFamily(sections[0], sections[1], oldSections, newSections)) { keptRows++; } else { if (customAction.ContainsKey(actionName)) { currentTable.Rows.RemoveAt(i); i--; } else { // it is a stardard action, we should keep this action. row.Operation = RowOperation.None; keptRows++; } } } else if (row.Operation == RowOperation.Add) { if (isSectionIdEmpty) { keptRows++; } else if (IsInPatchFamily(sections[0], sections[1], oldSections, newSections)) { keptRows++; } else { if (customAction.ContainsKey(actionName)) { currentTable.Rows.RemoveAt(i); i--; } else { keptRows++; } } } } if (currentTable.Rows.Count == 0) { tablesToDelete.Add(currentTable.Name); } } return(keptRows); }
public static void tlog(string logfile) { List <MLArray> mlList = new List <MLArray>(); MAVLinkInterface mine = new MAVLinkInterface(); try { mine.logplaybackfile = new BinaryReader(File.Open(logfile, FileMode.Open, FileAccess.Read, FileShare.Read)); } catch (Exception ex) { CustomMessageBox.Show("Log Can not be opened. Are you still connected?"); return; } mine.logreadmode = true; mine.MAV.packets.Initialize(); // clear Hashtable datappl = new Hashtable(); while (mine.logplaybackfile.BaseStream.Position < mine.logplaybackfile.BaseStream.Length) { byte[] packet = mine.readPacket(); object data = mine.GetPacket(packet); if (data == null) { continue; } if (data is MAVLink.mavlink_heartbeat_t) { if (((MAVLink.mavlink_heartbeat_t)data).type == (byte)MAVLink.MAV_TYPE.GCS) { continue; } } Type test = data.GetType(); DateTime time = mine.lastlogread; try { foreach (var field in test.GetFields()) { // field.Name has the field's name. object fieldValue = field.GetValue(data); // Get value if (field.FieldType.IsArray) { } else { if (!datappl.ContainsKey(field.Name + " " + field.DeclaringType.Name)) { datappl[field.Name + " " + field.DeclaringType.Name] = new List <double[]>(); } List <double[]> list = ((List <double[]>)datappl[field.Name + " " + field.DeclaringType.Name]); object value = fieldValue; if (value.GetType() == typeof(Single)) { list.Add(new double[] { time.ToFileTime(), (double)(Single)field.GetValue(data) }); } else if (value.GetType() == typeof(short)) { list.Add(new double[] { time.ToFileTime(), (double)(short)field.GetValue(data) }); } else if (value.GetType() == typeof(ushort)) { list.Add(new double[] { time.ToFileTime(), (double)(ushort)field.GetValue(data) }); } else if (value.GetType() == typeof(byte)) { list.Add(new double[] { time.ToFileTime(), (double)(byte)field.GetValue(data) }); } else if (value.GetType() == typeof(sbyte)) { list.Add(new double[] { time.ToFileTime(), (double)(sbyte)field.GetValue(data) }); } else if (value.GetType() == typeof(Int32)) { list.Add(new double[] { time.ToFileTime(), (double)(Int32)field.GetValue(data) }); } else if (value.GetType() == typeof(UInt32)) { list.Add(new double[] { time.ToFileTime(), (double)(UInt32)field.GetValue(data) }); } else if (value.GetType() == typeof(ulong)) { list.Add(new double[] { time.ToFileTime(), (double)(ulong)field.GetValue(data) }); } else if (value.GetType() == typeof(long)) { list.Add(new double[] { time.ToFileTime(), (double)(long)field.GetValue(data) }); } else if (value.GetType() == typeof(double)) { list.Add(new double[] { time.ToFileTime(), (double)(double)field.GetValue(data) }); } else { Console.WriteLine("Unknown data type"); } } } } catch { } } mine.logreadmode = false; mine.logplaybackfile.Close(); mine.logplaybackfile = null; foreach (string item in datappl.Keys) { double[][] temp = ((List <double[]>)datappl[item]).ToArray(); MLArray dbarray = new MLDouble(item, temp); mlList.Add(dbarray); } try { MatFileWriter mfw = new MatFileWriter(logfile + ".mat", mlList, true); } catch (Exception err) { MessageBox.Show("There was an error when creating the MAT-file: \n" + err.ToString(), "MAT-File Creation Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } }
protected override void OnRun(DebuggerStartInfo startInfo) { var mfStartInfo = startInfo as MicroFrameworkDebuggerStartInfo; if (mfStartInfo == null) //This should never happen... { throw new InvalidOperationException(); } VsPackage.MessageCentre.Session = this; var command = mfStartInfo.MFCommand; var portDefinition = ((MicroFrameworkExecutionTarget)command.Target).PortDefinition; try { using (var engine = new Engine(portDefinition)) { engine.Start(); var systemAssemblies = new Hashtable(); string newCommand = "/CorDebug_DeployDeviceName:" + portDefinition.PersistName; ArrayList assemblies = new ArrayList(); if (IsDeviceInInitializeState(engine)) { engine.ResumeExecution(); Thread.Sleep(200); while (IsDeviceInInitializeState(engine)) { VsPackage.MessageCentre.DeploymentMsg(DiagnosticStrings.WaitingInitialize); //need to break out of this or timeout or something? Thread.Sleep(200); } } var assms = engine.ResolveAllAssemblies(); // find out which are the system assemblies // we will insert each system assemblies in a hash table where the value will be the assembly version foreach (var resolvedAssembly in assms) { VsPackage.MessageCentre.DeploymentMsg(String.Format(DiagnosticStrings.FoundAssembly, resolvedAssembly.m_reply.Name, resolvedAssembly.m_reply.m_version.ToString())); if ((resolvedAssembly.m_reply.m_flags & Commands.Debugging_Resolve_Assembly.Reply.c_Deployed) == 0) { systemAssemblies[resolvedAssembly.m_reply.Name.ToLower()] = resolvedAssembly.m_reply.m_version; } } var refs = command.ReferencedAssemblies.Result.ToList(); refs.AddRange(Directory.GetFiles(command.OutputDirectory, "*.dll")); foreach (var reference in refs.ToArray()) { ResursiveAddReferences(refs, reference); } refs.AddRange(Directory.GetFiles(command.OutputDirectory, "*.exe")); refs = refs.Distinct(new CompareAssemblyName()).ToList(); string[] pes = GetDependencies(refs.ToArray(), true, true, engine.IsTargetBigEndian, "v4.3"); string[] dlls = GetDependencies(refs.ToArray(), true, false, engine.IsTargetBigEndian, "v4.3"); Debug.Assert(pes.Length == dlls.Length); // now we will re-deploy all system assemblies for (int i = 0; i < pes.Length; ++i) { string assemblyPath = pes[i]; string dllPath = dlls[i]; //is this a system assembly? string fileName = Path.ChangeExtension(Path.GetFileName(assemblyPath), null).ToLower(); bool fDeployNewVersion = true; if (systemAssemblies.ContainsKey(fileName)) { // get the version of the assembly on the device var deviceVer = (Microsoft.SPOT.Debugger.WireProtocol.Commands.Debugging_Resolve_Assembly.Version)systemAssemblies[fileName]; // get the version of the assembly of the project // We need to load the bytes for the assembly because other Load methods can override the path // with gac or recently used paths. This is the only way we control the exact assembly that is loaded. byte[] asmData = null; using (FileStream sr = new FileStream(dllPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { asmData = new byte[sr.Length]; sr.Read(asmData, 0, (int)sr.Length); } var assm = Assembly.Load(asmData); var deployVer = assm.GetName().Version; // compare versions strictly, and deploy whatever assembly does not match the version on the device if (TargetFrameworkExactMatch(deviceVer, deployVer)) { fDeployNewVersion = false; } else { //////////////////////////////////////////////// // !!! SPECIAL CASE !!! // // // // MSCORLIB cannot be deployed more than once // //////////////////////////////////////////////// if (assm.GetName().Name.ToLower().Contains("mscorlib")) { fDeployNewVersion = false; //HACK!!! //This is because of bug in Mono, even if we do Assembly.Load("microFrameworkMSCorLib"); //it actually loads Mono mscorlib which has version 4.0.0.0 instead of 4.3.1.0(or w/e version microframework is) // string message = string.Format("Cannot deploy the base assembly '{9}', or any of his satellite assemblies, to device - {0} twice. Assembly '{9}' on the device has version {1}.{2}.{3}.{4}, while the program is trying to deploy version {5}.{6}.{7}.{8} ", "DeployDeviceDescription", deviceVer.iMajorVersion, deviceVer.iMinorVersion, deviceVer.iBuildNumber, deviceVer.iRevisionNumber, deployVer.Major, deployVer.Minor, deployVer.Build, deployVer.Revision, assm.GetName().Name); // //TODO: SetDeployFailure(message); // return; } } } // append the assembly whose version does not match, or that still is not on the device, to the blob to deploy if (fDeployNewVersion) { newCommand = "/load:" + assemblyPath + " " + newCommand; using (FileStream fs = File.Open(assemblyPath, FileMode.Open, FileAccess.Read)) { VsPackage.MessageCentre.DeploymentMsg(String.Format(DiagnosticStrings.AddingPEtoBundle, assemblyPath)); long length = (fs.Length + 3) / 4 * 4; byte[] buf = new byte[length]; fs.Read(buf, 0, (int)fs.Length); assemblies.Add(buf); } } } VsPackage.MessageCentre.DeploymentMsg("Attempting deployment..."); if (!engine.Deployment_Execute(assemblies, false, VsPackage.MessageCentre.DeploymentMsg)) { VsPackage.MessageCentre.DeploymentMsg(DiagnosticStrings.DeployFailed); //SetDeployFailure(); return; } startInfo.Command = newCommand; engine.RebootDevice(Engine.RebootOption.RebootClrWaitForDebugger); } try { CorDebugProcess process = CorDebugProcess.CreateProcess(new DebugPortSupplier().FindPort("USB"), startInfo.Command); process.StartDebugging(this, false); // StartDebugging() will either get a connected device into a debuggable state and start the dispatch thread, or throw. } catch (ProcessExitException) { VsPackage.MessageCentre.DeploymentMsg(DiagnosticStrings.InitializeProcessFailedProcessDied); } catch (Exception ex) { VsPackage.MessageCentre.DeploymentMsg(DiagnosticStrings.InitializeProcessFailed); VsPackage.MessageCentre.InternalErrorMsg(false, ex.Message); } } catch (Exception e) { VsPackage.MessageCentre.DeploymentMsg(DiagnosticStrings.DeployFailed); VsPackage.MessageCentre.InternalErrorMsg(false, e.ToString()); } }
void HandlePostData(string strData, HttpListenerContext ctx) { byte[] bFrame = new byte[20]; int iDataLen = 20; string strConcenAddr = ""; string strDeviceID = ""; if ((strData.IndexOf("Reportframe") != -1 && strData.IndexOf("deviceDataChanged") != -1) || (strData.ToUpper().IndexOf("RESPONSEFRAME") != -1)) { bool bRestoHttpSvrNBCtrlCmd = false; if (strData.IndexOf("Reportframe") != -1) { DevReportCmd drc = new DevReportCmd(); drc = JsonConvert.DeserializeObject <DevReportCmd>(strData); if (drc.deviceId != "") { if (drc.service.data.Reportframe != null) { string strReportFrame = drc.service.data.Reportframe.Trim(); iDataLen = strReportFrame.Length / 2; bFrame = new byte[iDataLen]; for (int i = 0; i < iDataLen; i++) { bFrame[i] = DevTcpClient.GetByteFromstrHex(strReportFrame.Substring(2 * i, 2)); } strConcenAddr = DevTcpClient.GetStrFromHex(bFrame[8]) + DevTcpClient.GetStrFromHex(bFrame[7]) + DevTcpClient.GetStrFromHex(bFrame[10]) + DevTcpClient.GetStrFromHex(bFrame[9]); if ((bFrame[0] == 0x68) && (bFrame[1] == 0x10) && ((bFrame[9] == 0x81) || (bFrame[9] == 0x06))) { strConcenAddr = DevTcpClient.GetStrFromHex(bFrame[8]) + DevTcpClient.GetStrFromHex(bFrame[7]) + DevTcpClient.GetStrFromHex(bFrame[6]) + DevTcpClient.GetStrFromHex(bFrame[5]) + DevTcpClient.GetStrFromHex(bFrame[4]) + DevTcpClient.GetStrFromHex(bFrame[3]) + DevTcpClient.GetStrFromHex(bFrame[2]); } strDeviceID = drc.deviceId.Trim(); } } } else if (strData.ToUpper().IndexOf("RESPONSEFRAME") != -1) { DevResponse drp = new DevResponse(); drp = JsonConvert.DeserializeObject <DevResponse>(strData); if (drp.result.resultDetail.Responseframe != null) { string strResponseFrame = drp.result.resultDetail.Responseframe.Trim(); iDataLen = strResponseFrame.Length / 2; bFrame = new byte[iDataLen]; for (int i = 0; i < iDataLen; i++) { bFrame[i] = DevTcpClient.GetByteFromstrHex(strResponseFrame.Substring(2 * i, 2)); } strConcenAddr = DevTcpClient.GetStrFromHex(bFrame[8]) + DevTcpClient.GetStrFromHex(bFrame[7]) + DevTcpClient.GetStrFromHex(bFrame[10]) + DevTcpClient.GetStrFromHex(bFrame[9]); if ((bFrame[0] == 0x68) && (bFrame[1] == 0x10) && ((bFrame[9] == 0x81) || (bFrame[9] == 0x06))) { strConcenAddr = DevTcpClient.GetStrFromHex(bFrame[8]) + DevTcpClient.GetStrFromHex(bFrame[7]) + DevTcpClient.GetStrFromHex(bFrame[6]) + DevTcpClient.GetStrFromHex(bFrame[5]) + DevTcpClient.GetStrFromHex(bFrame[4]) + DevTcpClient.GetStrFromHex(bFrame[3]) + DevTcpClient.GetStrFromHex(bFrame[2]); } strDeviceID = drp.deviceId.Trim(); //////// if (GlbData.NBCtrlCmdList.ContainsKey(strConcenAddr)) { NBCtrlCmd NCC = (NBCtrlCmd)GlbData.NBCtrlCmdList[strConcenAddr]; NCC.strReturnFrame = strResponseFrame; GlbData.NBCtrlCmdList[strConcenAddr] = NCC; bRestoHttpSvrNBCtrlCmd = true; } } } if (strConcenAddr.Length == 8) { DevTcpClient duc; string strIPPort = GlbData.ServerIPPort; if (TcpClientList.ContainsKey(strConcenAddr)) { duc = (DevTcpClient)(TcpClientList[strConcenAddr]); if (DateTime.Now.Subtract(duc.LastRcvTime) > new TimeSpan(0, 5, 0)) { duc.iLastSendState = 0; } if (duc.iLastSendState == 0) { TcpClientList.Remove(strConcenAddr); duc = new DevTcpClient(strIPPort); duc.deviceID = strDeviceID; duc.OpenDevice(); if (!(bFrame.Length == 20 && bFrame[12] == 0x02)) { byte[] bFrame1 = new byte[20]; bFrame1[0] = 0x68; bFrame1[1] = 0x32; bFrame1[2] = 0x00; bFrame1[3] = 0x32; bFrame1[4] = 0x00; bFrame1[5] = 0x68; bFrame1[6] = 0xC9; bFrame1[7] = DevTcpClient.GetByteFromstrHex(strConcenAddr.Substring(2, 2)); bFrame1[8] = DevTcpClient.GetByteFromstrHex(strConcenAddr.Substring(0, 2)); bFrame1[9] = DevTcpClient.GetByteFromstrHex(strConcenAddr.Substring(6, 2)); bFrame1[10] = DevTcpClient.GetByteFromstrHex(strConcenAddr.Substring(4, 2)); bFrame1[11] = 0x00; bFrame1[12] = 0x02; bFrame1[13] = 0x70; bFrame1[14] = 0x00; bFrame1[15] = 0x00; bFrame1[16] = 0x01; bFrame1[17] = 0x00; bFrame1[18] = DevTcpClient.CheckSum(bFrame1, 6, 12); bFrame1[19] = 0x16; duc.WriteDevice(bFrame1, 0, 20); } if (!TcpClientList.ContainsKey(strConcenAddr)) { TcpClientList.Add(strConcenAddr, duc); } } else { if (duc.deviceID.Trim() != strDeviceID.Trim()) { duc.deviceID = strDeviceID.Trim(); TcpClientList[strConcenAddr] = duc; } } } else { duc = new DevTcpClient(strIPPort); duc.deviceID = strDeviceID; duc.OpenDevice(); Thread.Sleep(500); if (!(bFrame.Length == 20 && bFrame[12] == 0x02)) { byte[] bFrame1 = new byte[20]; bFrame1[0] = 0x68; bFrame1[1] = 0x32; bFrame1[2] = 0x00; bFrame1[3] = 0x32; bFrame1[4] = 0x00; bFrame1[5] = 0x68; bFrame1[6] = 0xC9; bFrame1[7] = DevTcpClient.GetByteFromstrHex(strConcenAddr.Substring(2, 2)); bFrame1[8] = DevTcpClient.GetByteFromstrHex(strConcenAddr.Substring(0, 2)); bFrame1[9] = DevTcpClient.GetByteFromstrHex(strConcenAddr.Substring(6, 2)); bFrame1[10] = DevTcpClient.GetByteFromstrHex(strConcenAddr.Substring(4, 2)); bFrame1[11] = 0x00; bFrame1[12] = 0x02; bFrame1[13] = 0x70; bFrame1[14] = 0x00; bFrame1[15] = 0x00; bFrame1[16] = 0x01; bFrame1[17] = 0x00; bFrame1[18] = DevTcpClient.CheckSum(bFrame1, 6, 12); bFrame1[19] = 0x16; duc.WriteDevice(bFrame1, 0, 20); } if (!TcpClientList.ContainsKey(strConcenAddr)) { TcpClientList.Add(strConcenAddr, duc); } } if (!bRestoHttpSvrNBCtrlCmd) { duc.WriteDevice(bFrame, 0, iDataLen); } } else if (strConcenAddr.Length == 14) { DevTcpClient duc; string strIPPort = GlbData.ServerIPPort; if (TcpClientList.ContainsKey(strConcenAddr)) { duc = (DevTcpClient)(TcpClientList[strConcenAddr]); if (duc.iLastSendState == 0) { TcpClientList.Remove(strConcenAddr); duc = new DevTcpClient(strIPPort); duc.deviceID = strDeviceID; duc.OpenDevice(); if (!TcpClientList.ContainsKey(strConcenAddr)) { TcpClientList.Add(strConcenAddr, duc); } } else { if (duc.deviceID.Trim() != strDeviceID.Trim()) { duc.deviceID = strDeviceID.Trim(); TcpClientList[strConcenAddr] = duc; } } } else { duc = new DevTcpClient(strIPPort); duc.deviceID = strDeviceID; duc.OpenDevice(); Thread.Sleep(500); if (!TcpClientList.ContainsKey(strConcenAddr)) { TcpClientList.Add(strConcenAddr, duc); } } if (!bRestoHttpSvrNBCtrlCmd) { duc.WriteDevice(bFrame, 0, iDataLen); } } else { } } ///////////////130协议水表数据上送 else if (strData.IndexOf("DeliverySchedule") != -1 && strData.IndexOf("deviceDatasChanged") != -1) { DevReportCmd_Water drc = new DevReportCmd_Water(); drc = JsonConvert.DeserializeObject <DevReportCmd_Water>(strData); if (drc.deviceId != "") { int iIndex = -1; if (drc.services.Length > 0) { for (int i = 0; i < drc.services.Length; i++) { if (drc.services[i].serviceType == "DeliverySchedule") { iIndex = i; break; } } } if (iIndex < 0) { return; } if (drc.services[iIndex].data != null) { string strReportFrame = drc.services[iIndex].data.transpond.Trim(); iDataLen = strReportFrame.Length / 2; bFrame = new byte[iDataLen]; for (int i = 0; i < iDataLen; i++) { bFrame[i] = DevTcpClient.GetByteFromstrHex(strReportFrame.Substring(2 * i, 2)); } string strAddr = (bFrame[9] + bFrame[10] * 256).ToString().PadLeft(5, '0'); strConcenAddr = DevTcpClient.GetStrFromHex(bFrame[8]) + DevTcpClient.GetStrFromHex(bFrame[7]) + strAddr; strDeviceID = drc.deviceId.Trim(); } } DevTcpClient duc; string strIPPort = GlbData.ServerIPPort; if (TcpClientList.ContainsKey(strConcenAddr)) { duc = (DevTcpClient)(TcpClientList[strConcenAddr]); if (DateTime.Now.Subtract(duc.LastSendTime) > new TimeSpan(0, 5, 0)) { TcpClientList.Remove(strConcenAddr); duc = new DevTcpClient(strIPPort); duc.deviceID = strDeviceID; duc.OpenDevice(); Thread.Sleep(500); if (!TcpClientList.ContainsKey(strConcenAddr)) { TcpClientList.Add(strConcenAddr, duc); } } else { if (duc.deviceID.Trim() != strDeviceID.Trim()) { duc.deviceID = strDeviceID.Trim(); TcpClientList[strConcenAddr] = duc; } } //if (duc.iLastSendState == 0) //{ // TcpClientList.Remove(strConcenAddr); // duc = new DevTcpClient(strIPPort); // duc.deviceID = strDeviceID; // duc.OpenDevice(); // TcpClientList.Add(strConcenAddr, duc); //} //else //{ // if (duc.deviceID.Trim() != strDeviceID.Trim()) // { // duc.deviceID = strDeviceID.Trim(); // TcpClientList[strConcenAddr] = duc; // } //} duc.WriteDevice(bFrame, 0, iDataLen); } else { duc = new DevTcpClient(strIPPort); duc.deviceID = strDeviceID; duc.OpenDevice(); Thread.Sleep(500); if (!TcpClientList.ContainsKey(strConcenAddr)) { TcpClientList.Add(strConcenAddr, duc); } duc.WriteDevice(bFrame, 0, iDataLen); } } else if (strData.IndexOf("NBConcenAddr") != -1) { string[] strs = strData.Split(','); string[] strs1 = strs[0].Split(':'); string[] strs2 = strs[1].Split(':'); string strTermAddr = strs1[1]; string strCmdFrame = strs2[1]; //主站主动下发 List <CommandPara> lsCmdPars = new List <CommandPara>(); CommandPara currCmdPara = new CommandPara(); currCmdPara.isNum = false; currCmdPara.paraName = "CmdFrame"; currCmdPara.paraValue = strCmdFrame; lsCmdPars.Add(currCmdPara); currCmdPara = new CommandPara(); currCmdPara.isNum = true; currCmdPara.paraName = "TimeOut"; currCmdPara.paraValue = "30"; lsCmdPars.Add(currCmdPara); string strCTIOTID = ""; string strDeviceID1 = GlbData.GetDeviceID(strTermAddr, ref strCTIOTID); if (strDeviceID1 == "") { return; } if (strCTIOTID == "") { return; } if (GlbData.CTIOTAppParaList.Contains(strCTIOTID)) { CTIOT_APP_PARA ctiot_app_para = (CTIOT_APP_PARA)(GlbData.CTIOTAppParaList[strCTIOTID]); if (ctiot_app_para != null) { NASDK currsdk = new NASDK(ctiot_app_para.SVR_IP, ctiot_app_para.SVR_PORT, ctiot_app_para.APP_ID, ctiot_app_para.APP_PWD, ctiot_app_para.CERT_FILE, ctiot_app_para.CERT_PWD); string strToken = ctiot_app_para.TOKEN; DateTime dtLastgetTokenTime; try { dtLastgetTokenTime = DateTime.Parse(ctiot_app_para.LAST_GETTOKEN_TIME); } catch { dtLastgetTokenTime = new DateTime(2000, 1, 1); } DateTime dtNow = DateTime.Now; if (strToken == "" || (dtLastgetTokenTime < dtNow.AddMinutes(-30))) { TokenResult tr = currsdk.getToken(); if (tr == null) { return; } strToken = tr.accessToken.Trim(); string strLastgetTokenTime = dtNow.ToString("yyyy-MM-dd HH:mm:ss"); //存储 string strSQL = "update CT_IOT_APP_PARA set TOKEN='{0}',LAST_GETTOKEN_TIME='{1}' where ID=" + strCTIOTID; strSQL = string.Format(strSQL, strToken, strLastgetTokenTime); if (GlbData.DBConn.ExeSQL(strSQL)) { ctiot_app_para.TOKEN = strToken; ctiot_app_para.LAST_GETTOKEN_TIME = strLastgetTokenTime; GlbData.CTIOTAppParaList[strCTIOTID] = ctiot_app_para; } } string result = currsdk.sendCommand(strToken, strDeviceID1, ctiot_app_para.CALLBACKURL, "CmdService", "Cmd_Down", lsCmdPars); NBCtrlCmdSendResult NCCSR = new NBCtrlCmdSendResult(); NCCSR.NBConcenAddr = strTermAddr; if (result == null) { NCCSR.SendTime = ""; } else { NBCtrlCmd NCC = new NBCtrlCmd(); NCC.NBConcenAddr = strTermAddr; NCC.SendTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); NCC.strReturnFrame = ""; if (!GlbData.NBCtrlCmdList.ContainsKey(strTermAddr)) { GlbData.NBCtrlCmdList.Add(strTermAddr, NCC); } else { GlbData.NBCtrlCmdList[strTermAddr] = NCC; } TimeSpan outTimeSpan = new TimeSpan(0, 1, 0); //超时时间60秒 NCC = (NBCtrlCmd)GlbData.NBCtrlCmdList[strTermAddr]; NCCSR.NBConcenAddr = strTermAddr; NCCSR.SendTime = NCC.SendTime; while (NCC.strReturnFrame == "") { if ((DateTime.Now - DateTime.Parse(NCC.SendTime)) > outTimeSpan) { //返回超时 NCCSR.strReturnFrame = ""; break; } } if (NCC.strReturnFrame != "") { NCCSR.strReturnFrame = NCC.strReturnFrame; } } string strResult = JsonConvert.SerializeObject(NCCSR); //将消息转成jason格式返回 GlbData.NBCtrlCmdList.Remove(strTermAddr); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(strResult); //对客户端输出相应信息. try { ctx.Response.ContentLength64 = buffer.Length; System.IO.Stream output = ctx.Response.OutputStream; output.Write(buffer, 0, buffer.Length); //关闭输出流,释放相应资源 output.Close(); } catch { } } } else { return; } } }
public bool HasKey(string key) { return(myHash.ContainsKey(key)); }
/// <summary> /// Determines if given type id is a scalar /// </summary> /// <param name="typeId">Type id</param> /// <returns>True if scalar</returns> public bool IsScalarType(Guid typeId) { return scalarTypesTable.ContainsKey(typeId); }
public static void log(string fn) { // read the file string[] filelines = File.ReadAllLines(fn); // store all the arrays List <MLArray> mlList = new List <MLArray>(); // store data to putinto the arrays Dictionary <string, List <double[]> > data = new Dictionary <string, List <double[]> >(); // store line item lengths Hashtable len = new Hashtable(); // store whats we have seen in the log Hashtable seen = new Hashtable(); // store the params seen SortedDictionary <string, double> param = new SortedDictionary <string, double>(); // keep track of line no int a = 0; foreach (var line in filelines) { a++; Console.Write(a + "\r"); string strLine = line.Replace(", ", ","); strLine = strLine.Replace(": ", ":"); string[] items = strLine.Split(',', ':'); // process the fmt messages if (line.StartsWith("FMT")) { // +1 for line no string[] names = new string[items.Length - 5 + 1]; names[0] = "LineNo"; Array.ConstrainedCopy(items, 5, names, 1, names.Length - 1); MLArray format = CreateCellArray(items[3] + "_label", names); if (items[3] == "PARM") { } else { mlList.Add(format); } len[items[3]] = names.Length; } // process param messages else if (line.StartsWith("PARM")) { param[items[1]] = double.Parse(items[2]); }// everyting else is generic else { // make sure the line is long enough if (items.Length < 2) { continue; } // check we have a valid fmt message for this message type if (!len.ContainsKey(items[0])) { continue; } // check the fmt length matchs what the log has if (items.Length != (int)len[items[0]]) { continue; } // make it as being seen seen[items[0]] = 1; double[] dbarray = new double[items.Length]; // set line no dbarray[0] = a; for (int n = 1; n < items.Length; n++) { try { dbarray[n] = double.Parse(items[n]); } catch { } } if (!data.ContainsKey(items[0])) { data[items[0]] = new List <double[]>(); } data[items[0]].Add(dbarray); } } foreach (var item in data) { double[][] temp = item.Value.ToArray(); MLArray dbarray = new MLDouble(item.Key, temp); mlList.Add(dbarray); } MLCell cell = new MLCell("PARM", new int[] { param.Keys.Count, 2 }); int m = 0; foreach (var item in param.Keys) { cell[m, 0] = new MLChar(null, item.ToString()); cell[m, 1] = new MLDouble(null, new double[] { (double)param[item] }, 1); m++; } mlList.Add(cell); MLArray seenmsg = CreateCellArray("Seen", seen.Keys.Cast <string>().ToArray()); mlList.Add(seenmsg); try { MatFileWriter mfw = new MatFileWriter(fn + ".mat", mlList, true); } catch (Exception err) { MessageBox.Show("There was an error when creating the MAT-file: \n" + err.ToString(), "MAT-File Creation Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } }
/// <summary> /// Given a Hashtable with field-value pairs, it updates the fields of this SM /// with the values listed in the Hashtable. Note that only the fields contained /// in the Hashtable will be updated and the rest will remain the same. /// </summary> /// <param name="table"></param> public void UpdateFrom(Hashtable table) { if (table.ContainsKey("uuid")) { uuid = Marshalling.ParseString(table, "uuid"); } if (table.ContainsKey("name_label")) { name_label = Marshalling.ParseString(table, "name_label"); } if (table.ContainsKey("name_description")) { name_description = Marshalling.ParseString(table, "name_description"); } if (table.ContainsKey("type")) { type = Marshalling.ParseString(table, "type"); } if (table.ContainsKey("vendor")) { vendor = Marshalling.ParseString(table, "vendor"); } if (table.ContainsKey("copyright")) { copyright = Marshalling.ParseString(table, "copyright"); } if (table.ContainsKey("version")) { version = Marshalling.ParseString(table, "version"); } if (table.ContainsKey("required_api_version")) { required_api_version = Marshalling.ParseString(table, "required_api_version"); } if (table.ContainsKey("configuration")) { configuration = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "configuration")); } if (table.ContainsKey("capabilities")) { capabilities = Marshalling.ParseStringArray(table, "capabilities"); } if (table.ContainsKey("features")) { features = Maps.convert_from_proxy_string_long(Marshalling.ParseHashTable(table, "features")); } if (table.ContainsKey("other_config")) { other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); } if (table.ContainsKey("driver_filename")) { driver_filename = Marshalling.ParseString(table, "driver_filename"); } if (table.ContainsKey("required_cluster_stack")) { required_cluster_stack = Marshalling.ParseStringArray(table, "required_cluster_stack"); } }
/// <summary> /// write output bibliography tex file, according to the specified sorting method /// </summary> public bool WriteBibFile() { StreamWriter sw = new StreamWriter(filePath + outputBibFile, false, Encoding.Default); try { //write document's preamble sw.Write(preamble + "\n\n"); switch (bibStyle) { //write bibliography in the same order it was previously read //it may seem quite dumb but it can be used to write the bibliography //enclosed by different pre and post ambles case BibStyles.PLAIN: //we simply write the \bibitems in the file WriteBibitems(sw); //v3-01 break; //write bibliography in alphabetical order of the content of the \bibitems case BibStyles.ALPHA: //sort bibitems and write them in the file aBibitems.Sort(); WriteBibitems(sw); //v3-01 break; //write bibliography in the order of the appearance of cites case BibStyles.UNSRT: //write \bibitems in the order of appearance of cites //remember cites can be repeated must \bibitem must not be written more than once even for (int i = 0; i < aCites.Count; i++) { try { var key = aCites[i].ToString(); if (hBibitems.ContainsKey(key)) //v4-01 { string value = hBibitems[key].ToString(); if (aBibitems.Contains(value)) { sw.Write("\t\\bibitem{" + aCites[i].ToString() + "} " + value + "\n\n"); aBibitems.Remove(value); } } } catch (Exception ex) { throw ex; } } //when we've written all the cited \bibitems, there might still be some \bibitems to write (these //have not been cited in document). We then write the left \bibtems in the order they were previously read WriteBibitems(sw); //v3-01 break; } //write document's postamble sw.Write("\n" + postamble); sw.Close(); System.Diagnostics.Process.Start("wordpad", "\"" + filePath + outputBibFile + "\""); return(true); } catch (Exception ex) { sw.Write("\n" + postamble); sw.Close(); } return(false); }
public void Export(string RulesFile, string TargetFile) { // Load the rules Hashtable rules = loadRules(RulesFile); if (File.Exists(TargetFile)) { File.Delete(TargetFile); } FileStream fs = new FileStream(TargetFile, FileMode.Create, FileAccess.Write); BinaryWriter bw = new BinaryWriter(fs); if (rules.ContainsKey("SETVERSION")) { bw.Write(Convert.ToInt16((string)rules["SETVERSION"])); } else { MessageBox.Show("Rules file is missing parameter\n\nSETVERSION:", "Export Failed"); bw.Close(); fs.Close(); return; } if (rules.ContainsKey("SETSIGNATURE")) { bw.Write(Convert.ToInt16((string)rules["SETSIGNATURE"])); } else { MessageBox.Show("Rules file is missing parameter\n\nSETSIGNATURE:", "Export Failed"); bw.Close(); fs.Close(); return; } // go through all lists for (int l = 0; l < Lists.Length; l++) { if (Convert.ToInt16((string)rules["SETCONVERSATIONLISTINDEX"]) == l) { for (int e = 0; e < Lists[ConversationListIndex].elementValues.Length; e++) { // go through all fields of an element for (int f = 0; f < Lists[ConversationListIndex].elementValues[e].Length; f++) { System.Windows.Forms.Application.DoEvents(); writeValue(bw, Lists[ConversationListIndex].elementValues[e][f], Lists[ConversationListIndex].elementTypes[f]); } } } if (l != ConversationListIndex) { if (!rules.ContainsKey("REMOVELIST:" + l)) { if (rules.ContainsKey("REPLACEOFFSET:" + l)) { // Convert from Hex to byte[] string[] hex = ((string)rules["REPLACEOFFSET:" + l]).Split(new char[] { '-', ' ' }); if (hex.Length > 1) { byte[] b = new byte[hex.Length]; for (int i = 0; i < hex.Length; i++) { b[i] = Convert.ToByte(hex[i], 16); } if (b.Length > 0) { bw.Write(b); } } } else { if (Lists[l].listOffset.Length > 0) { bw.Write(Lists[l].listOffset); } } if (Convert.ToInt16((string)rules["SETVERSION"]) >= 191) { bw.Write(Lists[l].listType); } bw.Write(Lists[l].elementValues.Length); if (Convert.ToInt16((string)rules["SETVERSION"]) >= 191) { bw.Write(Lists[l].elementSize); } // go through all elements of a list for (int e = 0; e < Lists[l].elementValues.Length; e++) { // go through all fields of an element for (int f = 0; f < Lists[l].elementValues[e].Length; f++) { System.Windows.Forms.Application.DoEvents(); if (!rules.ContainsKey("REMOVEVALUE:" + l + ":" + f)) { writeValue(bw, Lists[l].elementValues[e][f], Lists[l].elementTypes[f]); } } } } } } bw.Close(); fs.Close(); }
public static bool IsStopword(string str) { //int index=Array.BinarySearch(stopWordsList, str) return(_stopwords.ContainsKey(str.ToLower())); }
public override void ConvertToDataPC(GENERAL_INSTRUCTION dataPC, Demand dataIPSP) { var sCode = GetCode(dataIPSP); dataPC.PID = DateTime.Now.ToString("yyyyMMdd_HHmmss_ffffff"); if (string.IsNullOrWhiteSpace(sCode)) { SyncResultInfoSet.AddWarning(InfoString.ToSkipInfo("代码", dataIPSP.n_ID, sCode + " " + dataIPSP.s_Description)); return; } dataPC.CLIENT_NO = sCode; if (dataIPSP.dt_ReceiptDate <= new DateTime(1900, 1, 1)) { SyncResultInfoSet.AddWarning(InfoString.ToSkipInfo("收到日", dataIPSP.n_ID, sCode + " " + dataIPSP.s_Description)); return; } dataPC.RECEIVED = dataIPSP.dt_ReceiptDate; if (string.IsNullOrWhiteSpace(dataIPSP.s_ReceiptMethod)) { SyncResultInfoSet.AddWarning(InfoString.ToSkipInfo("收到方式", dataIPSP.n_ID, sCode + " " + dataIPSP.s_Description)); return; } if (dataIPSP.s_ReceiptMethod.ToLower().Contains("fax") || dataIPSP.s_ReceiptMethod.ToLower().Contains("传真")) { dataPC.RECEIVED_BY = "fax"; } else if (dataIPSP.s_ReceiptMethod.ToLower().Contains("mail") || dataIPSP.s_ReceiptMethod.ToLower().Contains("信")) { dataPC.RECEIVED_BY = "mail"; } else if (dataIPSP.s_ReceiptMethod.ToLower().Contains("email") || dataIPSP.s_ReceiptMethod.ToLower().Contains("邮件") || dataIPSP.s_ReceiptMethod.ToLower().Contains("邮箱")) { dataPC.RECEIVED_BY = "email"; } else { dataPC.RECEIVED_BY = "other"; } dataPC.RELATES_TO = htDemandType.ContainsKey(dataIPSP.s_Title) ? htDemandType[dataIPSP.s_Title].ToString() : "other"; dataPC.CONTENT_CN = dataIPSP.s_Description; dataPC.INSTRUCTOR = dataIPSP.s_Assignor; dataPC.STATUS = "valid"; //dataPC.EXPIRE_DATE //dataPC.COMMENTS FillDefaultValue(); if (!IsExistDataPC.HasValue) { return; } if (IsExistDataPC.Value) { new PC.BLL.GENERAL_INSTRUCTION().Update(dataPC); } else { new PC.BLL.GENERAL_INSTRUCTION().Add(dataPC); } }
protected virtual void GetProperties(Hashtable propertyDescriptors) { IntPtr hscp; Bid.ScopeEnter(out hscp, "<comm.DbConnectionStringBuilder.GetProperties|API> %d#", ObjectID); try { // show all strongly typed properties (not already added) // except ConnectionString iff BrowsableConnectionString Attribute[] attributes; foreach (PropertyDescriptor reflected in TypeDescriptor.GetProperties(this, true)) { if (ADP.ConnectionString != reflected.Name) { string displayName = reflected.DisplayName; if (!propertyDescriptors.ContainsKey(displayName)) { attributes = GetAttributesFromCollection(reflected.Attributes); PropertyDescriptor descriptor = new DbConnectionStringBuilderDescriptor(reflected.Name, reflected.ComponentType, reflected.PropertyType, reflected.IsReadOnly, attributes); propertyDescriptors[displayName] = descriptor; } // else added by derived class first } else if (BrowsableConnectionString) { propertyDescriptors[ADP.ConnectionString] = reflected; } else { propertyDescriptors.Remove(ADP.ConnectionString); } } // all keywords in Keys list that do not have strongly typed property, ODBC case // ignore 'Workaround Oracle if (!IsFixedSize) { attributes = null; foreach (string keyword in Keys) { if (!propertyDescriptors.ContainsKey(keyword)) { object value = this[keyword]; Type vtype; if (null != value) { vtype = value.GetType(); if (typeof(string) == vtype) { int tmp1; if (Int32.TryParse((string)value, out tmp1)) { vtype = typeof(Int32); } else { bool tmp2; if (Boolean.TryParse((string)value, out tmp2)) { vtype = typeof(Boolean); } } } } else { vtype = typeof(string); } Attribute[] useAttributes = attributes; if (StringComparer.OrdinalIgnoreCase.Equals(DbConnectionStringKeywords.Password, keyword) || StringComparer.OrdinalIgnoreCase.Equals(DbConnectionStringSynonyms.Pwd, keyword)) { useAttributes = new Attribute[] { BrowsableAttribute.Yes, PasswordPropertyTextAttribute.Yes, new ResCategoryAttribute(Res.DataCategory_Security), RefreshPropertiesAttribute.All, }; } else if (null == attributes) { attributes = new Attribute[] { BrowsableAttribute.Yes, RefreshPropertiesAttribute.All, }; useAttributes = attributes; } PropertyDescriptor descriptor = new DbConnectionStringBuilderDescriptor(keyword, this.GetType(), vtype, false, useAttributes); propertyDescriptors[keyword] = descriptor; } } } } finally { Bid.ScopeLeave(ref hscp); } }
public static void ProcessFeatureXml(XmlNode featureNode, Hashtable features) { FeatureDescription description = new FeatureDescription(); string feature = NodeText(featureNode.Attributes["name"]); Feature thisFeature; switch (feature) { case "Writer Blog": thisFeature = Feature.TeamBlog; break; case "Insert Maps": thisFeature = Feature.Maps; break; case "Terms of Use": thisFeature = Feature.TermsOfUse; break; case "Privacy": thisFeature = Feature.Privacy; break; case "Help": thisFeature = Feature.Help; break; case "FTP Help": thisFeature = Feature.FTPHelp; break; case "Gallery": thisFeature = Feature.WLGallery; break; case "Live Clipboard": thisFeature = Feature.LiveClipboard; break; case "Blog Providers": thisFeature = Feature.BlogProviders; break; case "Insert Video": thisFeature = Feature.VideoProviders; break; case "Tag Providers": thisFeature = Feature.TagProviders; break; case "Video Copyright Link": thisFeature = Feature.VideoCopyright; break; case "YouTube Video": thisFeature = Feature.YouTubeVideo; break; case "Allow Multiselect Images": thisFeature = Feature.AllowMultiSelectImage; break; case "Wordpress": thisFeature = Feature.Wordpress; break; default: return; } string enabled = NodeText(featureNode.Attributes["enabled"]); description.Enabled = (enabled == "true") ? true : false; //check for parameters XmlNodeList parameters = featureNode.SelectNodes("parameter"); foreach (XmlNode param in parameters) { description.AddParam(param.Attributes["name"].Value, param.Attributes["value"].Value); } if (features.ContainsKey(thisFeature)) { features[thisFeature] = description; } else { features.Add(thisFeature, description); } }
//check if a person has access to the page or functions of a page protected bool isYN(string key) { return(TaskSec.ContainsKey(key) && Convert.ToBoolean(TaskSec[key])); }