/// <summary> /// Appends a parameter to the given url as a query string /// </summary> /// <param name="path">url</param> /// <param name="queryStringParameter">parameter to append</param> /// <returns>url appended with the query string</returns> public static string AppendQueryString(string path, KeyValue queryStringParameter) { if (!string.IsNullOrEmpty(path) && queryStringParameter != null) { if (path.Contains(CommonStrings.QuestionSymbol.ToString())) { return (string.Concat(path, CommonStrings.AndSymbol, queryStringParameter.Key, CommonStrings.EqualSymbol, Convert.ToString(queryStringParameter.Value))); } else { return (string.Concat(path, CommonStrings.QuestionSymbol, queryStringParameter.Key, CommonStrings.EqualSymbol, Convert.ToString(queryStringParameter.Value))); } } else { throw new ArgumentException(); } }
public override void LoadFromKeyValues(KeyValue kv) { base.LoadFromKeyValues(kv); ActionList = new AbilityActionCollection(); foreach(string key in ActionList.Actions.Keys) { KeyValue kvActions = kv[key]; if (kvActions == null) continue; //We don't have any actions there so skip foreach(KeyValue actionChild in kvActions.Children) { if (!actionChild.HasChildren) continue; //TODO: Handle the Dontdestroy key BaseAction action = DotaActionFactory.CreateNewAction(actionChild.Key); if(action == null) { MessageBox.Show("WARNING: Action " + actionChild.Key + " not found in factory when creating ability: " + this.ClassName, "Loading Warning", MessageBoxButtons.OK); continue; } action.LoadFromKeyValues(actionChild); ActionList.Actions[key].Add(action); } } }
public void Add(KeyCode key, string descr, KeyCode alt = KeyCode.None) { var keyValue = new KeyValue() { descr = descr, keyCodeAlt = new[] { key, alt }, main = key }; keyValue.Load(); keys.Add(keyValue); m_alternatives[(int)key] = keyValue; }
public void Import(KeyValue root) { this.Data = new MemoryStream(); this.FileVersion = 0; long newOffset = this.Structures[0].DataSize; this.ImportStructure(this.Structures[0], root, 0, ref newOffset, new ImportState()); }
public KeyValue ToKV(string key) { KeyValue parent = new KeyValue(key); parent += new KeyValue("var_type") + Type.ToString(); parent += new KeyValue(Name) + DefaultValue; return parent; }
public void Load() { HeroesKV = LoadValveKVFile(HEROES_FILE); UnitsKV = LoadValveKVFile(UNITS_FILE); GameItemsKV = LoadValveKVFile(ITEMS_FILE); ActiveData = this; }
public virtual void LoadFromKeyValues(KeyValue kv) { PropertyInfo[] properties = this.GetType().GetProperties(); ClassName = kv.Key; foreach(PropertyInfo info in properties) { if (info.Name == "ClassName") continue; if (info.Name == "WasModified") continue; KeyValue subkey = kv[info.Name]; if (subkey == null) { continue; } if (subkey.HasChildren) continue; //TODO parse children because this is AbilitySpecial object data = null; if(info.PropertyType == typeof(int)) { data = subkey.GetInt(); } if(info.PropertyType == typeof(float)) { data = subkey.GetFloat(); } if(info.PropertyType == typeof(bool)) { data = subkey.GetBool(); } if(info.PropertyType == typeof(string)) { data = subkey.GetString(); } if (typeof(Enum).IsAssignableFrom(info.PropertyType) && subkey.GetString() != "") { if (info.PropertyType.GetCustomAttribute(typeof(FlagsAttribute)) != null) { string[] flags = subkey.GetString().Replace(" ", "").Split('|').Where(x => x != "").ToArray(); string p = String.Join(", ", flags); data = Enum.Parse(info.PropertyType, p); } else { data = Enum.Parse(info.PropertyType, subkey.GetString()); } } if (info.PropertyType == typeof(PerLevel)) { data = new PerLevel(subkey.GetString().Trim()); } if(data != null) info.SetMethod.Invoke(this, new object[] { data }); } }
static void Main() { var value = new KeyValue { Key = "Key1", Value = "Value1" }; Db.Main.KeyValues.InsertOnSubmit(value); Db.Main.SubmitChanges(); System.Console.WriteLine(Db.Main.KeyValues.Where(p => p.Key == "Key1").Count()); System.Console.ReadLine(); }
public KeyValue getKV() { KeyValue root = new KeyValue("Return Value"); KeyValue type = new KeyValue("Type"); type.Set(this.type); KeyValue desc = new KeyValue("Description"); desc.Set(description); root.AddChild(type); root.AddChild(desc); return root; }
static void generateKV() { KeyValue root = new KeyValue("Dota2Functions"); string currClass = "Global"; foreach (var kv in funcs) { kv.Value.processStats(); KeyValue func_kv = kv.Value.getKV(); root.AddChild(func_kv); } File.WriteAllText("d2functions.txt", root.ToString()); }
public void Add(KeyCode key, string descr, params KeyCode[] alt) { var l = new List<KeyCode>(alt.Take(1)); l.Insert(0, key); foreach (KeyCode a in l) KeyBack[a] = key; var keyValue = new KeyValue() { descr = descr, keyCodeAlt = l.ToArray(), main = key }; keyValue.Load(); keys.Add(keyValue); m_alternatives[(int)key] = keyValue; }
public KeyValue ToKV() { KeyValue kv = new KeyValue("Actions"); foreach (KeyValuePair<string, ActionCollection> k in Actions) { KeyValue child = k.Value.ToKV(k.Key); kv += child; } return kv; }
public KeyValue ToKV(string Key) { KeyValue doc = new KeyValue(Key); foreach(BaseAction action in this.List.Cast<BaseAction>()) { KeyValue child = new KeyValue(action.ClassName); doc += action.SaveToKV(); } return doc; }
/// <summary> /// /// </summary> /// <param name="kvs"></param> public KeyValueBuilder(Dictionary<string, string> kvs) { if (kvs == null) { throw new ArgumentNullException(); } foreach (var item in kvs) { var infoValue = new KeyValue {Key = item.Key, Value = item.Value}; _list.Add(infoValue); } }
public static void Move(string space, string oldKey, string newKey) { KeysList l; if (!_instance._storage.TryGetValue(space, out l)) { throw new Exception("Unsupported space: " + space); } var i = l.FindIndex(x => x.Item1 == oldKey); if (i == -1) return; l[i] = new KeyValue(newKey, l[i].Item2); _instance.Save(space); }
private static IEnumerable<KeyValue> BuildUniqueSources() { var result = new List<KeyValue>(); for (int i = 0; i < 10000; i++) { for (int j = 65; j < 91; j++) { var obj = new KeyValue() { Key = string.Format("{0}{0}{0}-{1}", (char)j, i), Value = i }; result.Add(obj); } } return result; }
/// <summary> /// /// </summary> /// <param name="keys"></param> /// <param name="values"></param> public KeyValueBuilder(string[] keys, string[] values) { if (keys == null || values == null) { throw new ArgumentNullException(); } if (keys.Length != values.Length) { throw new ArgumentException(); } for (var i = 0; i < keys.Length; i++) { var infoValue = new KeyValue {Key = keys[i], Value = values[i]}; _list.Add(infoValue); } }
public void TestDeepCopy() { KeyValue kv = new KeyValue("Test"); kv += new KeyValue("Key1") + "Some Value"; kv += new KeyValue("Key2") + 3.14f; KeyValue child = new KeyValue("Child"); child += new KeyValue("ChildKey") + true; kv += child; KeyValue clone = kv.Clone() as KeyValue; Assert.AreEqual("Test", clone.Key); Assert.AreEqual("Some Value", clone["Key1"].GetString()); Assert.AreEqual("Child", clone["Child"].Key); Assert.AreEqual(true, clone["Child"]["ChildKey"].GetBool()); }
public static IEnumerable<KeyValue> GetErrorsFromModelState(ViewDataDictionary ViewData) { List<KeyValue> keyValue = new List<KeyValue>(); foreach (var item in ViewData.ModelState) { if (item.Value.Errors.Any()) { KeyValue keyVal = new KeyValue(); keyVal.Key = item.Key; keyVal.Value = item.Value.Errors[0].ErrorMessage; keyValue.Add(keyVal); } } return keyValue; }
public static void Write( Func<string> msgBuilder, LogLevel level, params KeyValue[] attrs) { KeyValue[] arr; if (attrs != null) { arr = new KeyValue[attrs.Length + 1]; attrs.CopyTo(arr, 0); arr[arr.Length - 1] = new KeyValue { Key = key, Value = value }; } else { arr = new[] { new KeyValue { Key = key, Value = value } }; } Logger.Write(msgBuilder, level, arr); }
internal KeyValue getKV() { KeyValue root = new KeyValue(name); KeyValue funcClass = new KeyValue("Parent class"); funcClass.Set(this.funcClass); KeyValue desc = new KeyValue("Description"); desc.Set(description); KeyValue d2params = new KeyValue("Parameters"); root.AddChild(funcClass); root.AddChild(desc); root.AddChild(d2params); root.AddChild(ret.getKV()); foreach (var p in this.d2params) { KeyValue kv = p.getKV(); d2params.AddChild(kv); } return root; }
public static void Set(string space, string key, string value) { KeysList l; if (!_instance._storage.TryGetValue(space, out l)) { throw new Exception("Unsupported space: " + space); } var i = l.FindIndex(x => x.Item1 == key); if (i != -1) { if (value == null) { l.RemoveAt(i); } else { l[i] = new KeyValue(key, value); } } else if (value != null){ l.Enqueue(new KeyValue(key, value)); } _instance.Save(space); }
public static void Write( string message, LogLevel level, string title = null, params KeyValue[] attrs) { KeyValue[] arr; if (attrs != null) { arr = new KeyValue[attrs.Length + 1]; attrs.CopyTo(arr, 0); arr[arr.Length - 1] = new KeyValue { Key = key, Value = value }; } else { arr = new[] { new KeyValue { Key = key, Value = value } }; } Logger.Write(message, level, title, arr); }
public string FetchKeyValue(KeyValue value, string index) { string valueret = "Not available"; for (int i = 0; i <= 30; i++) { if (value.Children[i] == null) { break; } if (value.Children[i].Name == index) { valueret = value.Children[i].Value; break; } } return valueret; }
public static BaseAction CreateNewAction(string name, KeyValue kv = null) { if (!FactoryDictionary.ContainsKey(name)) return null; Type actionType = FactoryDictionary[name]; BaseAction action = null; if(kv == null) { action = actionType.GetConstructor(new Type[] { typeof(string) }).Invoke(new object[] { name }) as BaseAction; } else { action = actionType.GetConstructor(new Type[] { typeof(KeyValue) }).Invoke(new object[] { kv }) as BaseAction; } action.KeyValue.MakeEmptyParent(); return action; }
public void AddOrReplace_WithDuplicates_ShouldWorkCorrectly() { // Arrange var dictionary = new DictionaryDataStructure.Dictionary<string, int>(); // Act dictionary.AddOrReplace("Peter", 555); dictionary.AddOrReplace("Maria", 999); dictionary.AddOrReplace("Maria", 123); dictionary.AddOrReplace("Maria", 6); dictionary.AddOrReplace("Peter", 5); // Assert var expectedElements = new KeyValue<string, int>[] { new KeyValue<string, int>("Peter", 5), new KeyValue<string, int>("Maria", 6) }; var actualElements = dictionary.ToList(); CollectionAssert.AreEquivalent(expectedElements, actualElements); }
public void AddOrReplace_WithDuplicates_ShouldWorkCorrectly() { // Arrange var hashTable = new HashTable<string, int>(); // Act hashTable.AddOrReplace("Peter", 555); hashTable.AddOrReplace("Maria", 999); hashTable.AddOrReplace("Maria", 123); hashTable.AddOrReplace("Maria", 6); hashTable.AddOrReplace("Peter", 5); // Assert var expectedElements = new KeyValue<string, int>[] { new KeyValue<string, int>("Peter", 5), new KeyValue<string, int>("Maria", 6) }; var actualElements = hashTable.ToList(); CollectionAssert.AreEquivalent(expectedElements, actualElements); }
/// <summary> /// 转化为数据传输对象数组。 /// </summary> /// <param name="source"></param> /// <returns></returns> public static KeyValue[] ToKeyValueArray(this DataItem[] source) { if (source == null) { return new KeyValue[0]; } var data = new KeyValue[source.Length]; for (int i = 0; i < source.Length; i++) { if (source[i] != null) { data[i] = new KeyValue { Key = source[i].Key, Value = source[i].Value }; } } return data; }
public void Add_EmptyHashTable_NoDuplicates_ShouldAddElement() { // Arrange var hashTable = new HashTable<string, int>(); // Act var elements = new KeyValue<string, int>[] { new KeyValue<string, int>("Peter", 5), new KeyValue<string, int>("Maria", 6), new KeyValue<string, int>("George", 4), new KeyValue<string, int>("Kiril", 5) }; foreach (var element in elements) { hashTable.Add(element.Key, element.Value); } // Assert var actualElements = hashTable.ToList(); CollectionAssert.AreEquivalent(elements, actualElements); }
public void Add_EmptyDictionary_NoDuplicates_ShouldAddElement() { // Arrange var dictionary = new DictionaryDataStructure.Dictionary<string, int>(); // Act var elements = new KeyValue<string, int>[] { new KeyValue<string, int>("Peter", 5), new KeyValue<string, int>("Maria", 6), new KeyValue<string, int>("George", 4), new KeyValue<string, int>("Kiril", 5) }; foreach (var element in elements) { dictionary.Add(element.Key, element.Value); } // Assert var actualElements = dictionary.ToList(); CollectionAssert.AreEquivalent(elements, actualElements); }
static void Main(string[] args) { // in order to interact with the Web APIs, you must first acquire an interface // for a certain API using (dynamic steamNews = WebAPI.GetInterface("ISteamNews")) { // note the usage of c#'s dynamic feature, which can be used // to make the api a breeze to use // the ISteamNews WebAPI has only 1 function: GetNewsForApp, // so we'll be using that // when making use of dynamic, we call the interface function directly // and pass any parameters as named arguments KeyValue kvNews = steamNews.GetNewsForApp(appid: 440); // get news for tf2 // the return of every WebAPI call is a KeyValue class that contains the result data // for this example we'll iterate the results and display the title foreach (KeyValue news in kvNews["newsitems"]["newsitem"].Children) { Console.WriteLine("News: {0}", news["title"].AsString()); } // for functions with multiple versions, the version can be specified by // adding a number after the function name when calling the API kvNews = steamNews.GetNewsForApp2(appid: 570); // if a number is not specified, version 1 is assumed by default // notice that the output of this version differs from the first version foreach (KeyValue news in kvNews["newsitems"].Children) { Console.WriteLine("News: {0}", news["title"].AsString()); } // note that the interface functions can throw WebExceptions when the API // is otherwise inaccessible (networking issues, server downtime, etc) // and these should be handled appropriately try { kvNews = steamNews.GetNewsForApp002(appid: 730, maxlength: 100, count: 5); } catch (WebException ex) { Console.WriteLine("Unable to make API request: {0}", ex.Message); } } // for WebAPIs that require an API key, the key can be specified in the GetInterface function using (dynamic steamUserAuth = WebAPI.GetInterface("ISteamUserAuth", "APIKEYGOESHERE")) { // as the interface functions are synchronous, it may be beneficial to specify a timeout for calls steamUserAuth.Timeout = ( int )TimeSpan.FromSeconds(5).TotalMilliseconds; // additionally, if the API you are using requires you to POST or use an SSL connection, you may specify // these settings with the "method" and "secure" reserved parameters steamUserAuth.AuthenticateUser(someParam: "someValue", method: HttpMethod.Get, secure: true); } // if you are using a language that does not have dynamic object support, or you otherwise don't wish to use it // you can call interface functions through a Call method using (WebAPI.Interface steamNews = WebAPI.GetInterface("ISteamNews")) { Dictionary <string, string> newsArgs = new Dictionary <string, string>(); newsArgs["appid"] = "440"; KeyValue results = steamNews.Call("GetNewsForApp", /* version */ 1, newsArgs); } }
public static List<KeyValue> getImageList(String cFileName, int iMinVal, int iMaxVal, int iGrayMinVal, int iGrayMaxVal) { try { Image<Bgr, Byte> BgrImage = null; Image<Gray, Byte> GrayImage = null; List<KeyValue> ImageList = new List<KeyValue>(); String cExportDir = Application.StartupPath + "\\export\\"; ResetDirectory(cExportDir); //调取图片 BgrImage = new Image<Bgr, byte>(cFileName); GrayImage = new Image<Gray, byte>(BgrImage.Width, BgrImage.Height); //转灰度 CvInvoke.CvtColor(BgrImage, GrayImage, Emgu.CV.CvEnum.ColorConversion.Rgb2Gray); //转黑白 Image<Gray, byte> BinaryImage = GrayImage.ThresholdToZeroInv(new Gray(iGrayMinVal)); BinaryImage.Save("D:\\IMG03.jpg"); String cREC_ID = Path.GetFileName(cFileName).Replace(".jpg", ""); VectorOfVectorOfPoint rvs = new VectorOfVectorOfPoint(); CvInvoke.FindContours(BinaryImage, rvs, null, RetrType.List, ChainApproxMethod.ChainApproxSimple); int j = 10001; for (int i = 0; i < rvs.Size; i++) { var contour = rvs[i]; Rectangle BoundingBox = CvInvoke.BoundingRectangle(contour); if ((BoundingBox.Width < iMinVal) || (BoundingBox.Height < iMinVal)) continue; if ((BoundingBox.Width > iMaxVal) || (BoundingBox.Height > iMaxVal)) continue; j++; CvInvoke.Rectangle(BgrImage, BoundingBox, new MCvScalar(255, 0, 0, 0), 3); Image<Bgr, Byte> vResult = BgrImage.GetSubRect(BoundingBox); String cExportFileName = cREC_ID + "_" + j.ToString() + ".jpg"; vResult.Save(cExportDir + cExportFileName); KeyValue rowKey = new KeyValue(); rowKey.Text = cExportDir + cExportFileName; rowKey.Val = JsonLib.ToJSON(BoundingBox); ImageList.Add(rowKey); } String cZipFileName = Application.StartupPath + "\\" + cREC_ID + ".zip"; Zip vo = new Zip(); vo.ZipDir(cExportDir, cZipFileName); BgrImage.Save("D:\\IMG04.jpg"); return ImageList; } catch (Exception ex) { log4net.WriteLogFile("报错,原因为:" + ex); return null; } }
/// <summary>Rebuilds the KeyValueFormat cache.</summary> public void RefreshCache() { KeyValue.Clear(); LookupTable.Clear(); Generate(); }
protected override void InsertItem(int index, KeyValue <TKey, TValue> item) { Dictionary.Add(item.Key, item.Value); base.InsertItem(index, item); }
private async Task <bool> ProcessKey(string keyName, string displayName, string value, KeyValue newKv = null) { if (keyName.Length > 90) { Log.WriteError(nameof(AppProcessor), $"Key {keyName} for AppID {AppID} is too long, not inserting info."); return(false); } // All keys in PICS are supposed to be lower case keyName = keyName.ToLowerInvariant().Trim(); if (!CurrentData.ContainsKey(keyName)) { CurrentData[keyName] = new PICSInfo { Processed = true, }; var key = KeyNameCache.GetAppKeyID(keyName); if (key == 0) { var type = newKv != null ? 86 : 0; // 86 is a hardcoded const for the website key = await KeyNameCache.CreateAppKey(keyName, displayName, type); if (key == 0) { // We can't insert anything because key wasn't created Log.WriteError(nameof(AppProcessor), $"Failed to create key {keyName} for AppID {AppID}, not inserting info."); return(false); } IRC.Instance.SendOps($"New app keyname: {Colors.BLUE}{keyName} {Colors.LIGHTGRAY}(ID: {key}) ({displayName}) - {SteamDB.GetAppUrl(AppID, "history")}"); } await DbConnection.ExecuteAsync("INSERT INTO `AppsInfo` (`AppID`, `Key`, `Value`) VALUES (@AppID, @Key, @Value)", new { AppID, Key = key, Value = value }); await MakeHistory("created_key", key, string.Empty, value); if ((keyName == "extended_developer" || keyName == "extended_publisher") && value == "Valve") { IRC.Instance.SendOps($"New {displayName}=Valve app: {Colors.BLUE}{Steam.GetAppName(AppID)}{Colors.NORMAL} -{Colors.DARKBLUE} {SteamDB.GetAppUrl(AppID, "history")}"); } if (keyName == "common_oslist" && value.Contains("linux")) { PrintLinux(); } return(true); } var data = CurrentData[keyName]; if (data.Processed) { Log.WriteWarn(nameof(AppProcessor), $"Duplicate key {keyName} in AppID {AppID}"); return(false); } data.Processed = true; CurrentData[keyName] = data; if (data.Value == value) { return(false); } await DbConnection.ExecuteAsync("UPDATE `AppsInfo` SET `Value` = @Value WHERE `AppID` = @AppID AND `Key` = @Key", new { AppID, data.Key, Value = value }); if (newKv != null) { await MakeHistoryForJson(data.Key, data.Value, newKv); } else { await MakeHistory("modified_key", data.Key, data.Value, value); } if (keyName == "common_oslist" && value.Contains("linux") && !data.Value.Contains("linux")) { PrintLinux(); } return(true); }
public static void RequestFromPackage(uint subId, KeyValue kv) { if ((EBillingType)kv["billingtype"].AsInteger() != EBillingType.FreeOnDemand) { return; } if (kv["appids"].Children.Count == 0) { Log.WriteDebug(nameof(FreeLicense), $"Package {subId} has no apps"); return; } // TODO: Put LicenseList.OwnedApps.ContainsKey() in First() search var appId = kv["appids"].Children[0].AsUnsignedInteger(); if (LicenseList.OwnedApps.ContainsKey(appId)) { return; } if (kv["status"].AsInteger() != 0) // EPackageStatus.Available { Log.WriteDebug(nameof(FreeLicense), $"Package {subId} is not available"); return; } if ((ELicenseType)kv["licensetype"].AsInteger() != ELicenseType.SinglePurchase) { Log.WriteDebug(nameof(FreeLicense), $"Package {subId} is not single purchase"); return; } var dontGrantIfAppIdOwned = kv["extended"]["dontgrantifappidowned"].AsUnsignedInteger(); if (dontGrantIfAppIdOwned > 0 && LicenseList.OwnedApps.ContainsKey(dontGrantIfAppIdOwned)) { Log.WriteDebug(nameof(FreeLicense), $"Package {subId} already owns app {dontGrantIfAppIdOwned}"); return; } if (kv["extended"]["curatorconnect"].AsInteger() == 1) { Log.WriteDebug(nameof(FreeLicense), $"Package {subId} is a curator package"); return; } var allowPurchaseFromRestrictedCountries = kv["extended"]["allowpurchasefromrestrictedcountries"].AsBoolean(); var purchaseRestrictedCountries = kv["extended"]["purchaserestrictedcountries"].AsString(); if (purchaseRestrictedCountries != null && purchaseRestrictedCountries.Contains(AccountInfo.Country) != allowPurchaseFromRestrictedCountries) { Log.WriteDebug(nameof(FreeLicense), $"Package {subId} is not available in {AccountInfo.Country}"); return; } var startTime = kv["extended"]["starttime"].AsUnsignedLong(); var expiryTime = kv["extended"]["expirytime"].AsUnsignedLong(); var now = DateUtils.DateTimeToUnixTime(DateTime.UtcNow); if (expiryTime > 0 && expiryTime < now) { Log.WriteDebug(nameof(FreeLicense), $"Package {subId} has already expired"); return; } if (startTime > now) { AddToQueue(subId, appId); Log.WriteDebug(nameof(FreeLicense), $"Package {subId} has not reached starttime yet, added to queue"); return; } uint parentAppId; bool available; using (var db = Database.Get()) { available = db.ExecuteScalar <bool>("SELECT IFNULL(`Value`, \"\") = \"released\" FROM `Apps` LEFT JOIN `AppsInfo` ON `Apps`.`AppID` = `AppsInfo`.`AppID` AND `Key` = (SELECT `ID` FROM `KeyNames` WHERE `Name` = \"common_releasestate\") WHERE `Apps`.`AppID` = @AppID", new { AppID = appId }); parentAppId = db.ExecuteScalar <uint>("SELECT `Value` FROM `Apps` JOIN `AppsInfo` ON `Apps`.`AppID` = `AppsInfo`.`AppID` WHERE `Key` = (SELECT `ID` FROM `KeyNames` WHERE `Name` = \"common_parent\") AND `Apps`.`AppID` = @AppID AND `AppType` != 3", new { AppID = appId }); } if (!available) { Log.WriteDebug(nameof(FreeLicense), $"Package {subId} (app {appId}) did not pass release check"); return; } if (parentAppId > 0 && !LicenseList.OwnedApps.ContainsKey(parentAppId)) { Log.WriteDebug(nameof(FreeLicense), $"Parent app {parentAppId} is not owned to get {appId}"); return; } Log.WriteDebug(nameof(FreeLicense), $"Requesting apps in package {subId}"); QueueRequest(subId, appId); }
private void PopulateValues(IDictionary from, System.Collections.Generic.List <KeyValue> to) { IDictionaryEnumerator ide = from.GetEnumerator(); ValueWithType valueWithType = null; KeyValue keyValue = null; while (ide.MoveNext()) { keyValue = new KeyValue(); keyValue.key = ide.Key.ToString(); if (ide.Value == null) { throw new ArgumentException("NCache query does not support null values"); } if (ide.Value is ArrayList) { ArrayList list = (ArrayList)ide.Value; foreach (object value in list) { Type type = value.GetType(); bool isTag = CommandHelper.IsTag(type); if (!(CommandHelper.IsIndexable(type) || isTag)) { throw new ArgumentException("The provided type is not indexable. ", type.Name); } valueWithType = new ValueWithType(); valueWithType.value = GetValueString(value); if (isTag) { valueWithType.type = typeof(string).FullName; } else { valueWithType.type = value.GetType().FullName; } keyValue.value.Add(valueWithType); } } else { Type type = ide.Value.GetType(); bool isTag = CommandHelper.IsTag(type); if (!(CommandHelper.IsIndexable(type) || isTag)) { throw new ArgumentException("The provided type is not indexable. ", type.Name); } valueWithType = new ValueWithType(); valueWithType.value = GetValueString(ide.Value); if (isTag) { valueWithType.type = typeof(string).FullName; } else { valueWithType.type = ide.Value.GetType().FullName; } keyValue.value.Add(valueWithType); } to.Add(keyValue); } }
public static void DownloadApp(int appId, int depotId, string branch, bool bListOnly = false) { if (steam3 != null) { steam3.RequestAppInfo((uint)appId); } if (!AccountHasAccess(appId, true)) { string contentName = GetAppOrDepotName(-1, appId); Console.WriteLine("App {0} ({1}) is not available from this account.", appId, contentName); return; } List <int> depotIDs = null; if (AppIsSteam3(appId)) { depotIDs = new List <int>(); KeyValue depots = GetSteam3AppSection(appId, EAppInfoSection.Depots); if (depots != null) { foreach (var child in depots.Children) { int id = -1; if (int.TryParse(child.Name, out id) && child.Children.Count > 0 && (depotId == -1 || id == depotId)) { depotIDs.Add(id); } } } } else { // steam2 path depotIDs = CDRManager.GetDepotIDsForApp(appId, Config.DownloadAllPlatforms); } if (depotIDs == null || (depotIDs.Count == 0 && depotId == -1)) { Console.WriteLine("Couldn't find any depots to download for app {0}", appId); return; } else if (depotIDs.Count == 0) { Console.WriteLine("Depot {0} not listed for app {1}", depotId, appId); return; } if (bListOnly) { Console.WriteLine("\n {0} Depots:", appId); foreach (var depot in depotIDs) { var depotName = CDRManager.GetDepotName(depot); Console.WriteLine("{0} - {1}", depot, depotName); } return; } var infos2 = new List <DepotDownloadInfo2>(); var infos3 = new List <DepotDownloadInfo3>(); foreach (var depot in depotIDs) { int depotVersion = 0; if (!AppIsSteam3(appId)) { // Steam2 dependency depotVersion = CDRManager.GetLatestDepotVersion(depot, Config.PreferBetaVersions); if (depotVersion == -1) { Console.WriteLine("Error: Unable to find DepotID {0} in the CDR!", depot); return; } } IDepotDownloadInfo info = GetDepotInfo(depot, depotVersion, appId, branch); if (info != null) { if (info.GetDownloadType() == DownloadSource.Steam2) { infos2.Add((DepotDownloadInfo2)info); } else if (info.GetDownloadType() == DownloadSource.Steam3) { infos3.Add((DepotDownloadInfo3)info); } } } if (infos2.Count() > 0) { DownloadSteam2(infos2); } if (infos3.Count() > 0) { DownloadSteam3(infos3); } }
private void AddSpecial(KeyValue special) { Thickness margin = new Thickness(0, 0, 3, 0); Grid grid = new Grid(); ComboBox type = new ComboBox(); TextBox name = new TextBox(); TextBox value = new TextBox(); Button delete = new Button(); type.Margin = margin; name.Margin = margin; value.Margin = margin; type.ToolTip = "Type"; name.ToolTip = "Name"; value.ToolTip = "Value"; type.VerticalAlignment = VerticalAlignment.Center; name.VerticalAlignment = VerticalAlignment.Center; value.VerticalAlignment = VerticalAlignment.Center; delete.VerticalAlignment = VerticalAlignment.Center; for (int i = 0; i < specialType_combobox_base.Items.Count; i++) { type.Items.Add(specialType_combobox_base.Items[i]); } try { for (int i = 0; i < special.children.Count; i++) { if (String.Equals("var_type", special.children[i].Key)) { type.SelectedItem = special.children[i].Value; } else { name.Text = special.children[i].Key; value.Text = special.children[i].Value; } } } catch { type.SelectedItem = type.Items[0]; } //name.Text = if(String.Equals() delete.Content = "X"; delete.Background = x_button_base.Background; delete.Click += RemoveSpecial_Click; Grid.SetColumn(type, 0); Grid.SetColumn(name, 1); Grid.SetColumn(value, 2); Grid.SetColumn(delete, 3); grid.ColumnDefinitions.Add(new ColumnDefinition()); grid.ColumnDefinitions.Add(new ColumnDefinition()); grid.ColumnDefinitions.Add(new ColumnDefinition()); grid.ColumnDefinitions.Add(new ColumnDefinition()); grid.ColumnDefinitions[0].Width = new GridLength(1, GridUnitType.Star); grid.ColumnDefinitions[1].Width = new GridLength(1, GridUnitType.Star); grid.ColumnDefinitions[2].Width = new GridLength(1, GridUnitType.Star); grid.ColumnDefinitions[3].Width = GridLength.Auto; grid.Children.Add(type); grid.Children.Add(name); grid.Children.Add(value); grid.Children.Add(delete); s.Children.Insert(s.Children.Count - 1, grid); }
public async Task <Dictionary <ulong, PublishedItemDetails> > GetPublishedFileDetails(IEnumerable <ulong> workshopIds) { //if (!IsReady) // throw new Exception("SteamWorkshopService not initialized!"); using (dynamic remoteStorage = SteamKit2.WebAPI.GetInterface("ISteamRemoteStorage")) { KeyValue allFilesDetails = null; remoteStorage.Timeout = TimeSpan.FromSeconds(30); allFilesDetails = await Task.Run(delegate { try { return(remoteStorage.GetPublishedFileDetails1( itemcount: workshopIds.Count(), publishedfileids: workshopIds, method: HttpMethod.Post)); } catch (HttpRequestException e) { Log.Error($"Fetching File Details failed: {e.Message}"); return(null); } }); if (allFilesDetails == null) { return(null); } //fileDetails = remoteStorage.Call(HttpMethod.Post, "GetPublishedFileDetails", 1, new Dictionary<string, string>() { { "itemcount", workshopIds.Count().ToString() }, { "publishedfileids", workshopIds.ToString() } }); var detailsList = allFilesDetails?.Children.Find((KeyValue kv) => kv.Name == "publishedfiledetails")?.Children; var resultCount = allFilesDetails?.GetValueOrDefault <int>("resultcount"); if (detailsList == null || resultCount == null) { Log.Error("Received invalid data: "); #if DEBUG if (allFilesDetails != null) { PrintKeyValue(allFilesDetails); } return(null); #endif } if (detailsList.Count != workshopIds.Count() || resultCount != workshopIds.Count()) { Log.Error($"Received unexpected number of fileDetails. Expected: {workshopIds.Count()}, Received: {resultCount}"); return(null); } var result = new Dictionary <ulong, PublishedItemDetails>(); for (int i = 0; i < resultCount; i++) { var fileDetails = detailsList[i]; var tagContainer = fileDetails.Children.Find(item => item.Name == "tags"); List <string> tags = new List <string>(); if (tagContainer != null) { foreach (var tagKv in tagContainer.Children) { var tag = tagKv.Children.Find(item => item.Name == "tag")?.Value; if (tag != null) { tags.Add(tag); } } } result[workshopIds.ElementAt(i)] = new PublishedItemDetails() { PublishedFileId = fileDetails.GetValueOrDefault <ulong>("publishedfileid"), Views = fileDetails.GetValueOrDefault <uint>("views"), Subscriptions = fileDetails.GetValueOrDefault <uint>("subscriptions"), TimeUpdated = Util.DateTimeFromUnixTimeStamp(fileDetails.GetValueOrDefault <ulong>("time_updated")), TimeCreated = Util.DateTimeFromUnixTimeStamp(fileDetails.GetValueOrDefault <ulong>("time_created")), Description = fileDetails.GetValueOrDefault <string>("description"), Title = fileDetails.GetValueOrDefault <string>("title"), FileUrl = fileDetails.GetValueOrDefault <string>("file_url"), FileSize = fileDetails.GetValueOrDefault <long>("file_size"), FileName = fileDetails.GetValueOrDefault <string>("filename"), ConsumerAppId = fileDetails.GetValueOrDefault <ulong>("consumer_app_id"), CreatorAppId = fileDetails.GetValueOrDefault <ulong>("creator_app_id"), Creator = fileDetails.GetValueOrDefault <ulong>("creator"), Tags = tags.ToArray() }; } return(result); } }
public static void KeyValue(KeyValue request) { }
protected override async Task ProcessData() { await LoadData(); ChangeNumber = ProductInfo.ChangeNumber; if (Settings.IsFullRun) { await DbConnection.ExecuteAsync("INSERT INTO `Changelists` (`ChangeID`) VALUES (@ChangeNumber) ON DUPLICATE KEY UPDATE `Date` = `Date`", new { ProductInfo.ChangeNumber }); await DbConnection.ExecuteAsync("INSERT INTO `ChangelistsSubs` (`ChangeID`, `SubID`) VALUES (@ChangeNumber, @SubID) ON DUPLICATE KEY UPDATE `SubID` = `SubID`", new { SubID, ProductInfo.ChangeNumber }); } await ProcessKey("root_changenumber", "changenumber", ChangeNumber.ToString()); var appAddedToThisPackage = false; var hasPackageInfo = ProductInfo.KeyValues.Children.Count > 0; var packageOwned = LicenseList.OwnedSubs.ContainsKey(SubID); var newPackageName = ProductInfo.KeyValues["name"].AsString() ?? string.Concat("Steam Sub ", SubID); var apps = (await DbConnection.QueryAsync <PackageApp>("SELECT `AppID`, `Type` FROM `SubsApps` WHERE `SubID` = @SubID", new { SubID })).ToDictionary(x => x.AppID, x => x.Type); var alreadySeenAppIds = new HashSet <uint>(); if (!hasPackageInfo) { ProductInfo.KeyValues.Children.Add(new KeyValue("steamdb_requires_token", "1")); } if (string.IsNullOrEmpty(PackageName)) { await DbConnection.ExecuteAsync("INSERT INTO `Subs` (`SubID`, `Name`, `LastKnownName`) VALUES (@SubID, @Name, @Name)", new { SubID, Name = newPackageName }); await MakeHistory("created_sub"); await MakeHistory("created_info", SteamDB.DatabaseNameType, string.Empty, newPackageName); } else if (PackageName != newPackageName) { if (newPackageName.StartsWith("Steam Sub ", StringComparison.Ordinal)) { await DbConnection.ExecuteAsync("UPDATE `Subs` SET `Name` = @Name WHERE `SubID` = @SubID", new { SubID, Name = newPackageName }); } else { await DbConnection.ExecuteAsync("UPDATE `Subs` SET `Name` = @Name, `LastKnownName` = @Name WHERE `SubID` = @SubID", new { SubID, Name = newPackageName }); } await MakeHistory("modified_info", SteamDB.DatabaseNameType, PackageName, newPackageName); } foreach (var section in ProductInfo.KeyValues.Children) { var sectionName = section.Name.ToLowerInvariant(); if (string.IsNullOrEmpty(sectionName) || sectionName == "packageid" || sectionName == "changenumber" || sectionName == "name") { // Ignore common keys continue; } if (sectionName == "appids" || sectionName == "depotids") { // Remove "ids", so we get "app" from appids and "depot" from depotids var type = sectionName.Replace("ids", string.Empty); var isAppSection = type == "app"; var typeID = (uint)(isAppSection ? 0 : 1); // 0 = app, 1 = depot; can't store as string because it's in the `key` field foreach (var childrenApp in section.Children) { if (!uint.TryParse(childrenApp.Value, out var appID)) { Log.WriteWarn(nameof(SubProcessor), $"Package {SubID} has an invalid uint: {childrenApp.Value}"); continue; } if (alreadySeenAppIds.Contains(appID)) { Log.WriteWarn(nameof(SubProcessor), $"Package {SubID} has a duplicate app: {appID}"); continue; } alreadySeenAppIds.Add(appID); // Is this appid already in this package? if (apps.ContainsKey(appID)) { // Is this appid's type the same? if (apps[appID] != type) { await DbConnection.ExecuteAsync("UPDATE `SubsApps` SET `Type` = @Type WHERE `SubID` = @SubID AND `AppID` = @AppID", new { SubID, AppID = appID, Type = type }); await MakeHistory("added_to_sub", typeID, apps[appID] == "app"? "0" : "1", childrenApp.Value); appAddedToThisPackage = true; // Log relevant add/remove history events for depot and app var appHistory = new PICSHistory { ID = appID, ChangeID = ChangeNumber, }; if (isAppSection) { appHistory.NewValue = SubID.ToString(); appHistory.Action = "added_to_sub"; } else { appHistory.OldValue = SubID.ToString(); appHistory.Action = "removed_from_sub"; } await DbConnection.ExecuteAsync(AppProcessor.HistoryQuery, appHistory); var depotHistory = new DepotHistory { DepotID = appID, ManifestID = 0, ChangeID = ChangeNumber, OldValue = SubID, Action = isAppSection ? "removed_from_sub" : "added_to_sub" }; if (isAppSection) { depotHistory.OldValue = SubID; depotHistory.Action = "removed_from_sub"; } else { depotHistory.NewValue = SubID; depotHistory.Action = "added_to_sub"; } await DbConnection.ExecuteAsync(DepotProcessor.HistoryQuery, depotHistory); } apps.Remove(appID); } else { await DbConnection.ExecuteAsync("INSERT INTO `SubsApps` (`SubID`, `AppID`, `Type`) VALUES(@SubID, @AppID, @Type)", new { SubID, AppID = appID, Type = type }); await MakeHistory("added_to_sub", typeID, string.Empty, childrenApp.Value); if (isAppSection) { await DbConnection.ExecuteAsync(AppProcessor.HistoryQuery, new PICSHistory { ID = appID, ChangeID = ChangeNumber, NewValue = SubID.ToString(), Action = "added_to_sub" } ); } else { await DbConnection.ExecuteAsync(DepotProcessor.HistoryQuery, new DepotHistory { DepotID = appID, ManifestID = 0, ChangeID = ChangeNumber, NewValue = SubID, Action = "added_to_sub" } ); } appAddedToThisPackage = true; if (packageOwned && !LicenseList.OwnedApps.ContainsKey(appID)) { LicenseList.OwnedApps.Add(appID, 1); } } } } else if (sectionName == "extended") { foreach (var children in section.Children) { var keyName = $"{sectionName}_{children.Name}"; if (children.Value != null) { await ProcessKey(keyName, children.Name, children.Value); } else { await ProcessKey(keyName, children.Name, Utils.JsonifyKeyValue(children), true); } } } else if (sectionName == "appitems" && section.Children.Count > 1) { sectionName = $"root_{sectionName}"; var fixedAppItems = new KeyValue(section.Name); // Valve for some reason creates a new children for each item, // instead of actually making it an array. // This causes json_decode in php override the key, thus lose data. foreach (var item in section.Children) { var appItem = fixedAppItems.Children.Find(s => s.Name == item.Name); if (appItem == default) { appItem = new KeyValue(item.Name); fixedAppItems.Children.Add(appItem); } foreach (var itemId in item.Children) { appItem.Children.Add(new KeyValue(itemId.Name, itemId.Value)); } } await ProcessKey(sectionName, sectionName, Utils.JsonifyKeyValue(fixedAppItems), true); } else if (section.Value != null) { sectionName = $"root_{sectionName}"; await ProcessKey(sectionName, sectionName, section.Value); } else if (section.Children.Count > 0) // Check count so we don't store empty appitems { sectionName = $"root_{sectionName}"; await ProcessKey(sectionName, sectionName, Utils.JsonifyKeyValue(section), true); } } // If this package no longer returns any package info, keep the existing info we have if (hasPackageInfo) { foreach (var data in CurrentData.Values.Where(data => !data.Processed && !data.KeyName.StartsWith("website", StringComparison.Ordinal))) { await DbConnection.ExecuteAsync("DELETE FROM `SubsInfo` WHERE `SubID` = @SubID AND `Key` = @Key", new { SubID, data.Key }); await MakeHistory("removed_key", data.Key, data.Value); } var appsRemoved = apps.Count > 0; foreach (var(appid, type) in apps) { await DbConnection.ExecuteAsync("DELETE FROM `SubsApps` WHERE `SubID` = @SubID AND `AppID` = @AppID AND `Type` = @Type", new { SubID, AppID = appid, Type = type }); var isAppSection = type == "app"; var typeID = (uint)(isAppSection ? 0 : 1); // 0 = app, 1 = depot; can't store as string because it's in the `key` field await MakeHistory("removed_from_sub", typeID, appid.ToString()); if (isAppSection) { await DbConnection.ExecuteAsync(AppProcessor.HistoryQuery, new PICSHistory { ID = appid, ChangeID = ChangeNumber, OldValue = SubID.ToString(), Action = "removed_from_sub" } ); } else { await DbConnection.ExecuteAsync(DepotProcessor.HistoryQuery, new DepotHistory { DepotID = appid, ManifestID = 0, ChangeID = ChangeNumber, OldValue = SubID, Action = "removed_from_sub" } ); } } if (packageOwned && appsRemoved) { LicenseList.RefreshApps(); } if (!packageOwned && SubID != 17906 && Settings.IsMillhaven) { Steam.Instance.FreeLicense.RequestFromPackage(SubID, ProductInfo.KeyValues); } } // Re-queue apps in this package so we can update depots and whatnot if (appAddedToThisPackage && !Settings.IsFullRun && !string.IsNullOrEmpty(PackageName)) { var appsToRequest = ProductInfo.KeyValues["appids"].Children.Select(x => (uint)x.AsInteger()).ToList(); JobManager.AddJob( () => Steam.Instance.Apps.PICSGetAccessTokens(appsToRequest, Enumerable.Empty <uint>()), new PICSTokens.RequestedTokens { Apps = appsToRequest }); } if (ProductInfo.MissingToken && PICSTokens.HasPackageToken(SubID)) { Log.WriteError(nameof(PICSTokens), $"Overridden token for subid {SubID} is invalid?"); IRC.Instance.SendOps($"[Tokens] Looks like the overridden token for subid {SubID} ({newPackageName}) is invalid"); } }
static ulong GetSteam3DepotManifest(uint depotId, uint appId, string branch) { KeyValue depots = GetSteam3AppSection(appId, EAppInfoSection.Depots); KeyValue depotChild = depots[depotId.ToString()]; if (depotChild == KeyValue.Invalid) { return(INVALID_MANIFEST_ID); } // Shared depots can either provide manifests, or leave you relying on their parent app. // It seems that with the latter, "sharedinstall" will exist (and equals 2 in the one existance I know of). // Rather than relay on the unknown sharedinstall key, just look for manifests. Test cases: 111710, 346680. if (depotChild["manifests"] == KeyValue.Invalid && depotChild["depotfromapp"] != KeyValue.Invalid) { uint otherAppId = depotChild["depotfromapp"].AsUnsignedInteger(); if (otherAppId == appId) { // This shouldn't ever happen, but ya never know with Valve. Don't infinite loop. Console.WriteLine("App {0}, Depot {1} has depotfromapp of {2}!", appId, depotId, otherAppId); return(INVALID_MANIFEST_ID); } steam3.RequestAppInfo(otherAppId); return(GetSteam3DepotManifest(depotId, otherAppId, branch)); } var manifests = depotChild["manifests"]; var manifests_encrypted = depotChild["encryptedmanifests"]; if (manifests.Children.Count == 0 && manifests_encrypted.Children.Count == 0) { return(INVALID_MANIFEST_ID); } var node = manifests[branch]; if (branch != "Public" && node == KeyValue.Invalid) { var node_encrypted = manifests_encrypted[branch]; if (node_encrypted != KeyValue.Invalid) { string password = Config.BetaPassword; if (password == null) { Console.Write("Please enter the password for branch {0}: ", branch); Config.BetaPassword = password = Console.ReadLine(); } var encrypted_v1 = node_encrypted["encrypted_gid"]; var encrypted_v2 = node_encrypted["encrypted_gid_2"]; if (encrypted_v1 != KeyValue.Invalid) { byte[] input = Util.DecodeHexString(encrypted_v1.Value); byte[] manifest_bytes = CryptoHelper.VerifyAndDecryptPassword(input, password); if (manifest_bytes == null) { Console.WriteLine("Password was invalid for branch {0}", branch); return(INVALID_MANIFEST_ID); } return(BitConverter.ToUInt64(manifest_bytes, 0)); } else if (encrypted_v2 != KeyValue.Invalid) { // Submit the password to Steam now to get encryption keys steam3.CheckAppBetaPassword(appId, Config.BetaPassword); if (!steam3.AppBetaPasswords.ContainsKey(branch)) { Console.WriteLine("Password was invalid for branch {0}", branch); return(INVALID_MANIFEST_ID); } byte[] input = Util.DecodeHexString(encrypted_v2.Value); byte[] manifest_bytes; try { manifest_bytes = CryptoHelper.SymmetricDecryptECB(input, steam3.AppBetaPasswords[branch]); } catch (Exception e) { Console.WriteLine("Failed to decrypt branch {0}: {1}", branch, e.Message); return(INVALID_MANIFEST_ID); } return(BitConverter.ToUInt64(manifest_bytes, 0)); } else { Console.WriteLine("Unhandled depot encryption for depotId {0}", depotId); return(INVALID_MANIFEST_ID); } } return(INVALID_MANIFEST_ID); } if (node.Value == null) { return(INVALID_MANIFEST_ID); } return(UInt64.Parse(node.Value)); }
public LinearProjectile(KeyValue kv) : base(kv) { }
public static async Task DownloadAppAsync(uint appId, uint depotId, ulong manifestId, string branch, string os, string arch, string language, bool lv, bool isUgc) { // Load our configuration data containing the depots currently installed string configPath = ContentDownloader.Config.InstallDirectory; if (string.IsNullOrWhiteSpace(configPath)) { configPath = DEFAULT_DOWNLOAD_DIR; } Directory.CreateDirectory(Path.Combine(configPath, CONFIG_DIR)); DepotConfigStore.LoadFromFile(Path.Combine(configPath, CONFIG_DIR, "depot.config")); if (steam3 != null) { steam3.RequestAppInfo(appId); } if (!AccountHasAccess(appId)) { if (steam3.RequestFreeAppLicense(appId)) { Console.WriteLine("Obtained FreeOnDemand license for app {0}", appId); // Fetch app info again in case we didn't get it fully without a license. steam3.RequestAppInfo(appId, true); } else { string contentName = GetAppOrDepotName(INVALID_DEPOT_ID, appId); throw new ContentDownloaderException(String.Format("App {0} ({1}) is not available from this account.", appId, contentName)); } } var depotIDs = new List <uint>(); KeyValue depots = GetSteam3AppSection(appId, EAppInfoSection.Depots); if (isUgc) { var workshopDepot = depots["workshopdepot"].AsUnsignedInteger(); if (workshopDepot != 0) { depotId = workshopDepot; } depotIDs.Add(depotId); } else { Console.WriteLine("Using app branch: '{0}'.", branch); if (depots != null) { foreach (var depotSection in depots.Children) { uint id = INVALID_DEPOT_ID; if (depotSection.Children.Count == 0) { continue; } if (!uint.TryParse(depotSection.Name, out id)) { continue; } if (depotId != INVALID_DEPOT_ID && id != depotId) { continue; } if (depotId == INVALID_DEPOT_ID) { var depotConfig = depotSection["config"]; if (depotConfig != KeyValue.Invalid) { if (!Config.DownloadAllPlatforms && depotConfig["oslist"] != KeyValue.Invalid && !string.IsNullOrWhiteSpace(depotConfig["oslist"].Value)) { var oslist = depotConfig["oslist"].Value.Split(','); if (Array.IndexOf(oslist, os ?? Util.GetSteamOS()) == -1) { continue; } } if (depotConfig["osarch"] != KeyValue.Invalid && !string.IsNullOrWhiteSpace(depotConfig["osarch"].Value)) { var depotArch = depotConfig["osarch"].Value; if (depotArch != (arch ?? Util.GetSteamArch())) { continue; } } if (!Config.DownloadAllLanguages && depotConfig["language"] != KeyValue.Invalid && !string.IsNullOrWhiteSpace(depotConfig["language"].Value)) { var depotLang = depotConfig["language"].Value; if (depotLang != (language ?? "english")) { continue; } } if (!lv && depotConfig["lowviolence"] != KeyValue.Invalid && depotConfig["lowviolence"].AsBoolean()) { continue; } } } depotIDs.Add(id); } } if (depotIDs == null || (depotIDs.Count == 0 && depotId == INVALID_DEPOT_ID)) { throw new ContentDownloaderException(String.Format("Couldn't find any depots to download for app {0}", appId)); } else if (depotIDs.Count == 0) { throw new ContentDownloaderException(String.Format("Depot {0} not listed for app {1}", depotId, appId)); } } var infos = new List <DepotDownloadInfo>(); foreach (var depot in depotIDs) { var info = GetDepotInfo(depot, appId, manifestId, branch); if (info != null) { infos.Add(info); } } try { await DownloadSteam3Async(appId, infos).ConfigureAwait(false); } catch (OperationCanceledException) { Console.WriteLine("App {0} was not completely downloaded.", appId); throw; } }
public DataTable GetMaterialBinNumberByPN(string partNumber, string compName, string setupLoc, string stationNo) { DataTable dt = new DataTable(); dt.Columns.Add(new DataColumn("MaterialBinNum", typeof(string))); dt.Columns.Add(new DataColumn("PartNumber", typeof(string))); dt.Columns.Add(new DataColumn("Qty", typeof(string))); dt.Columns.Add(new DataColumn("FIFOTime", typeof(string))); dt.Columns.Add(new DataColumn("QtyUsed", typeof(string))); dt.Columns.Add(new DataColumn("QtytoPick", typeof(string))); dt.Columns.Add(new DataColumn("Location", typeof(string))); dt.Columns.Add(new DataColumn("CompName", typeof(string))); dt.Columns.Add(new DataColumn("SetupLoc", typeof(string))); dt.Columns.Add(new DataColumn("PStationNo", typeof(string))); //dt.Columns.Add(new DataColumn("Status", typeof(string))); KeyValue[] materialBinFilters = new KeyValue[] { new KeyValue("MATERIAL_BIN_PART_NUMBER", partNumber), new KeyValue("MAX_ROWS", "100"), new KeyValue("MATERIAL_BIN_STATE", "F,R,S") }; string[] materialBinResultKeys = new string[] { "MATERIAL_BIN_NUMBER", "MATERIAL_BIN_PART_NUMBER", "MATERIAL_BIN_QTY_ACTUAL", "STORAGE_NUMBER" }; string[] materialBinResultValues = new string[] { }; AttributeInfo[] attributes = new AttributeInfo[] { };//new AttributeInfo("FIFOAttrib", "*") LogHelper.Info("begin api mlGetMaterialBinData (Part Number:" + partNumber + ")"); int error = imsapi.mlGetMaterialBinData(sessionContext, init.configHandler.StationNumber, materialBinFilters, attributes, materialBinResultKeys, out materialBinResultValues); LogHelper.Info("end api mlGetMaterialBinData (errorcode = " + error + ")"); if (error != 0 && error != 3) { //view.errorHandler(2, init.lang.ERROR_API_CALL_ERROR + " mlGetMaterialBinData " + error, ""); return(null); } else { int loop = materialBinResultKeys.Length; int count = materialBinResultValues.Length; for (int i = 0; i < count; i += loop) { //get material bin number attribute "PickListQtyAttrib","FIFOAttrib","PickListStatusAttrib" Dictionary <string, string> dicValues = new Dictionary <string, string>(); string[] attributeCodeArray = new string[] { };//"PickListQtyAttrib", string[] attributeResultKeys = new string[] { "ATTRIBUTE_CODE", "ATTRIBUTE_VALUE", "ERROR_CODE" }; string[] attributeResultValues = new string[] { }; LogHelper.Info("begin api attribGetAttributeValues (material bin number =" + materialBinResultValues[i].ToString() + ")"); int error1 = imsapi.attribGetAttributeValues(sessionContext, init.configHandler.StationNumber, 2, materialBinResultValues[i].ToString(), "-1", attributeCodeArray, 0, attributeResultKeys, out attributeResultValues); LogHelper.Info("end api attribGetAttributeValues (errorcode = " + error1 + ")"); if (error1 == 0) { int loop1 = attributeResultKeys.Length; int count1 = attributeResultValues.Length; for (int j = 0; j < count1; j += loop1) { dicValues[attributeResultValues[j]] = attributeResultValues[j + 1]; } } if (dicValues.ContainsKey("PickListStatusAttrib") && dicValues["PickListStatusAttrib"] == "1")// it will not pick the material that has been booked. { continue; } DataRow row = dt.NewRow(); row["MaterialBinNum"] = materialBinResultValues[i].ToString(); row["PartNumber"] = materialBinResultValues[i + 1].ToString(); row["Qty"] = materialBinResultValues[i + 2].ToString(); row["Location"] = materialBinResultValues[i + 3].ToString(); row["FIFOTime"] = dicValues.ContainsKey("FIFOAttrib") ? dicValues["FIFOAttrib"] : ""; //string strValue = dicValues.ContainsKey("PickListQtyAttrib") ? dicValues["PickListQtyAttrib"] : ""; row["QtyUsed"] = 0;//GetMaterialBinUsedQty(strValue); row["CompName"] = compName; row["SetupLoc"] = setupLoc; row["PStationNo"] = stationNo; dt.Rows.Add(row); } //view.errorHandler(0, init.lang.ERROR_API_CALL_ERROR + " mlGetMaterialBinData " + error, ""); } return(dt); }
internal PurchaseResponseCallback([JetBrains.Annotations.NotNull] JobID jobID, [JetBrains.Annotations.NotNull] CMsgClientPurchaseResponse msg) { if ((jobID == null) || (msg == null)) { throw new ArgumentNullException(nameof(jobID) + " || " + nameof(msg)); } JobID = jobID; PurchaseResultDetail = (EPurchaseResultDetail)msg.purchase_result_details; Result = (EResult)msg.eresult; if (msg.purchase_receipt_info == null) { ASF.ArchiLogger.LogNullError(nameof(msg.purchase_receipt_info)); return; } KeyValue receiptInfo = new KeyValue(); using (MemoryStream ms = new MemoryStream(msg.purchase_receipt_info)) { if (!receiptInfo.TryReadAsBinary(ms)) { ASF.ArchiLogger.LogNullError(nameof(ms)); return; } } List <KeyValue> lineItems = receiptInfo["lineitems"].Children; if (lineItems.Count == 0) { return; } Items = new Dictionary <uint, string>(lineItems.Count); foreach (KeyValue lineItem in lineItems) { uint packageID = lineItem["PackageID"].AsUnsignedInteger(); if (packageID == 0) { // Coupons have PackageID of -1 (don't ask me why) // We'll use ItemAppID in this case packageID = lineItem["ItemAppID"].AsUnsignedInteger(); if (packageID == 0) { ASF.ArchiLogger.LogNullError(nameof(packageID)); return; } } string gameName = lineItem["ItemDescription"].Value; if (string.IsNullOrEmpty(gameName)) { ASF.ArchiLogger.LogNullError(nameof(gameName)); return; } // Apparently steam expects client to decode sent HTML gameName = WebUtility.HtmlDecode(gameName); Items[packageID] = gameName; } }
//Convenience method for getting a record using a KeyValue record identifier public static FieldTripOptionsRecord GetRecord(KeyValue id, bool bMutable) { return((FieldTripOptionsRecord)FieldTripOptionsTable.Instance.GetRecordData(id, bMutable)); }
public DotaBaseUnit(KeyValue kv) : base(kv) { }
/// <summary> /// This method deletes a specified record /// </summary> /// <param name="kv">Keyvalue of the record to be deleted.</param> public static void DeleteRecord(KeyValue kv) { FieldTripOptionsTable.Instance.DeleteOneRecord(kv); }
public CreateThinker(KeyValue kv) : base(kv) { }
protected KeyOpValue NewKeyValue(int n, object v) { KeyValue value2 = this.kvc[n]; return(new KeyOpValue(value2.Key, v, value2.ValueType)); }
/// <summary> /// 获取班级信息 /// </summary> /// <returns></returns> public IEnumerator getClassInfo() { // 广播会从自身开始查找这个DestoryMe方法,查找完自身后会查找所有子物体 //BroadcastMessage("DestoryMe"); KeyValue kv = new KeyValue("stuNo", sin.no); UnityWebRequest uw = wsb.PostWithParams(servelets.getClasses, kv); message.text = "正在获取服务器数据······"; messagePanel.SetActive(true); yield return(uw.Send()); Debug.Log(uw.responseCode); Debug.Log(uw.downloadHandler.text); if (uw.isNetworkError) { message.text = "连接失败"; Debug.Log(uw.error); } else { if (uw.downloadHandler.text.Contains("200")) { message.text = "连接成功,正在加载数据!"; WebServicesBase.addedClassId.Clear(); ResponseJson rj = new ResponseJson(); JObject jsonText = JObject.Parse(uw.downloadHandler.text); // get JSON result objects into a list rj.stateCode = jsonText["stateCode"].Value <string>(); Debug.Log(jsonText["classesList"]); classes = JsonConvert.DeserializeObject <ClassInfo[]>(jsonText["classesList"].ToString()); //Debug.Log(jsonText["classesList"].Value<string>()); //List<JToken> list = jsonText["classesList"].Children().ToList(); //Debug.Log(list.Count()); //classes = list.Values<ClassInfo>().ToArray(); //List<JToken> list //.Children().ToList() //classes = list.Values<ClassInfo>().ToArray(); //classes = //ClassInfo[] tmpclass = new ClassInfo[4]; //tmpclass[0] = new ClassInfo("1", "比尔`盖茨", "Windows从入门到放弃"); //tmpclass[1] = new ClassInfo("2", "史蒂夫·乔布斯", "IOS从入门到放弃"); //tmpclass[2] = new ClassInfo("3", "安迪·罗宾", "Android从入门到放弃"); //tmpclass[3] = new ClassInfo("4", "林纳斯·托瓦兹", "Linux从入门到放弃"); //MyArrays<ClassInfo> ma = new MyArrays<ClassInfo>(); //ma.Items = tmpclass; //string jsonData = JsonUtility.ToJson(ma); ////uw.downloadHandler.text //Debug.Log(jsonData); //classes = JsonUtility.FromJson<MyArrays<ClassInfo>>(jsonData).Items; if (classes.Length == 0) { message.text = "没有加入班级?点击右上方加入!"; } else { yield return(resetClassList()); } } } yield return(wait(1.5f)); messagePanel.SetActive(false); }
/// <summary> /// 是否Mysql端注册 /// </summary> /// <returns></returns> public IEnumerator isMySqlRegister() { messagePanel.SetActive(true); message.text = "正在获取服务器数据······"; //当网络不可用时 if (Application.internetReachability == NetworkReachability.NotReachable) { //message.text = "网络不可达,请稍后再试。"; yield return(StartCoroutine(requestFailed())); Debug.Log("网络不可用!"); } else { KeyValue[] kv = new KeyValue[1]; kv[0] = new KeyValue("uuid", MemberId); UnityWebRequest uw = wsb.PostWithParams(servelets.isStudentExists, kv); yield return(uw.Send()); string jsonData = uw.downloadHandler.text; if (!uw.isNetworkError) { Debug.Log(uw.downloadHandler.text); ResponseJson rj = new ResponseJson(); //ResponseJson rj = JsonConvert.DeserializeObject<ResponseJson>(uw.downloadHandler.text); //var v = JsonConvert.DeserializeObject<dynamic>(uw.downloadHandler.text); try { rj = JsonConvert.DeserializeObject <ResponseJson>(uw.downloadHandler.text); //JObject jsonText = JObject.Parse(uw.downloadHandler.text); // get JSON result objects into a list // rj.stateCode = jsonText["stateCode"].Value<string>(); // rj.message = jsonText["result"].Value<bool>().ToString(); //List<Newtonsoft.Json.Linq.JToken> listJToken = googleSearch["responseData"]["results"].Children().ToList(); //Debug.Log(JsonConvert.SerializeObject(rj)); Debug.Log(rj.stateCode); Debug.Log(rj.message); Debug.Log(rj.stuInfo); Debug.Log(rj.result); if (rj.stateCode == WebServicesBase.GetEnumDescription(stateCode.access) && (rj.message == "True" || rj.result == "true")) { Debug.Log("用户存在====="); isReg = true; sin = rj.stuInfo[0]; Debug.Log(sin.no); StartCoroutine(getClassInfo()); } else if (rj.stateCode == "409") { messagePanel.SetActive(false); Debug.Log("开始注册协程"); //schoolListParent.DetachChildren(); clearToggle(); selectSchoolFlag = true; if (rj.school != null && rj.school.Length != 0) { foreach (schoolInfo tmpInfo in rj.school) { addSchoolListItem(tmpInfo.name, tmpInfo.code); } } else { addSchoolListItem("西安欧亚学院", "OYXY"); addSchoolListItem("西安培华学院", "PHXY"); } RegisterPanel.SetActive(true); //StartCoroutine(sendRegisterParams()); } else { StartCoroutine(requestFailed()); } } catch (Exception e) { Debug.Log(e.Message); Debug.Log(e.StackTrace); StartCoroutine(requestFailed()); } } else { StartCoroutine(requestFailed()); } } }
public void RebuildRecordAsync() { Console.WriteLine("Index Rebuild Started"); Guid languageId = TSM.Model.TSMContext.CurrentLanguageID; List <Record> record = new List <Record>(); List <Guid> listRecordsID = RecordService.GetAllRecordID(); List <ExportRecordData> ExportdataList = new List <ExportRecordData>(); if (listRecordsID != null) { SearchAttributes searchParam = GetSearchParam(); record = SearchServices.GetFilterRecordInformation(listRecordsID, 20000, searchParam); ExportRecordData ExportRecordData = new ExportRecordData(); ExportRecordData.Records = new List <ExportRecord>(); #region [If Not Null Record] if (record != null) { #region [Data Load] //Get Variable Items List <Variable_Language> variableItems = new List <Variable_Language>(); variableItems = SearchServices.GetVariableLanguageForVariable(languageId).ToList(); //Get Get All Country With Region List <Country> listofAllCountries = new List <Country>(); listofAllCountries = SearchServices.GetAllCountryWithRegion(); //Get list of All Region List <Region_Language> listofAllRegion = new List <Region_Language>(); listofAllRegion = SearchServices.GetAllRegionWithLanguage(); //Get list of All Country with language List <Country_Language> lstCountryLang = new List <Country_Language>(); lstCountryLang = SearchServices.GetAllCountry(languageId); //Get Sector Language List <Sector_Language> lstSectorLanguage = new List <Sector_Language>(); lstSectorLanguage = SearchServices.GetAllSectorNames(languageId); //Get Sector List <TSMSector> lstTSMSector = new List <TSMSector>(); lstTSMSector = SearchServices.GetAllSector(); // Get Record Variable List <Record_Variable> recordVariables = new List <Record_Variable>(); recordVariables = SearchServices.GetAllRecordVariable(); #endregion TotalRecord = record.Count; Console.WriteLine("Total Records: " + TotalRecord.ToString()); foreach (var exportRecordData in record) { try { ExportRecordData.Variables = new List <KeyValue>(); foreach (var keyValue in variableItems) { KeyValue keyValuevariableLanguageItem = new KeyValue { Key = keyValue.ID.ToString(), Value = keyValue.Name }; ExportRecordData.Variables.Add(keyValuevariableLanguageItem); } ExportRecord exportRecord = null; #region [sector = 0 && country = 1] if ((exportRecordData.Countries.Count == 1) && (exportRecordData.Sectors.Count == 0)) { exportRecord = new ExportRecord(); //document try { if (exportRecordData.Documents.Count > 0) { exportRecord.Document = exportRecordData.Documents[0].Path.Split('.')[0].ToString(); } else { exportRecord.Document = null; } } catch { exportRecord.Document = ""; } //ID exportRecord.RecordID = exportRecordData.ID; //Name exportRecord.Name = exportRecordData.Record_Languages.FirstOrDefault().Name.ToString(); //Regions start var selectedRegion = new List <Region>(); Country tmpCountry = listofAllCountries.Where(c => c.ID == exportRecordData.Countries[0].ID).FirstOrDefault(); if (tmpCountry != null) { foreach (var r in tmpCountry.Regions) { selectedRegion.Add(r); } } var regionLanguageList = (from rl in listofAllRegion join r in selectedRegion on rl.ID equals r.ID where r.Type == TSM.Entity.RegionType.Geographical && rl.LanguageID == languageId select rl.Name).ToList(); if (regionLanguageList.Count > 0) { exportRecord.Regions = regionLanguageList[0].ToString(); } //Region end //Country start Country_Language countryLanguage = lstCountryLang.Where(cl => cl.ID == exportRecordData.Countries[0].ID).FirstOrDefault(); exportRecord.Countries = countryLanguage.Name; //country end exportRecord.CountryCode = exportRecordData.Countries[0].ISOCode; //variable values exportRecord.VariableValues = new List <string>(); List <string> recordVariableKey = new List <string>(); foreach (var variableValue in ExportRecordData.Variables) { if (variableValue != null && variableValue.Value != null && !string.IsNullOrEmpty(variableValue.Value) && variableValue.Value != "") { recordVariableKey.Add(variableValue.Key); exportRecord.VariableValues.Add(SearchServices.GetVariableValueByVariableIdFromList(languageId, exportRecordData.ID, recordVariableKey, variableValue.Key, recordVariables)); } } if (exportRecord != null) { ExportRecordData.Records.Add(exportRecord); ExportRecordData.RecID = exportRecord.RecordID; } } #endregion #region [sector > 0 && country = 1] else if ((exportRecordData.Countries.Count == 1) && (exportRecordData.Sectors.Count > 0)) { foreach (var sec in exportRecordData.Sectors) { exportRecord = new ExportRecord(); //document try { if (exportRecordData.Documents.Count > 0) { exportRecord.Document = exportRecordData.Documents[0].Path.Split('.')[0].ToString(); } else { exportRecord.Document = null; } } catch { exportRecord.Document = ""; } //ID exportRecord.RecordID = exportRecordData.ID; //Name exportRecord.Name = exportRecordData.Record_Languages.FirstOrDefault().Name.ToString(); //Regions start var selectedRegion = new List <Region>(); Country tmpCountry = listofAllCountries.Where(c => c.ID == exportRecordData.Countries[0].ID).FirstOrDefault(); if (tmpCountry != null) { foreach (var r in tmpCountry.Regions) { selectedRegion.Add(r); } } var regionLanguageList = (from rl in listofAllRegion join r in selectedRegion on rl.ID equals r.ID where r.Type == TSM.Entity.RegionType.Geographical && rl.LanguageID == languageId select rl.Name).ToList(); if (regionLanguageList.Count > 0) { exportRecord.Regions = regionLanguageList[0].ToString(); } //Region end //Country start Country_Language countryLanguage = lstCountryLang.Where(cl => cl.ID == exportRecordData.Countries[0].ID).FirstOrDefault(); exportRecord.Countries = countryLanguage.Name; //country end exportRecord.CountryCode = exportRecordData.Countries[0].ISOCode; //variable values exportRecord.VariableValues = new List <string>(); List <string> recordVariableKey = new List <string>(); foreach (var variableValue in ExportRecordData.Variables) { if (variableValue != null && variableValue.Value != null && !string.IsNullOrEmpty(variableValue.Value) && variableValue.Value != "") { recordVariableKey.Add(variableValue.Key); exportRecord.VariableValues.Add(SearchServices.GetVariableValueByVariableIdFromList(languageId, exportRecordData.ID, recordVariableKey, variableValue.Key, recordVariables)); } } //sector Sector_Language secLang = lstSectorLanguage.Where(sl => sl.ID == sec.ID).FirstOrDefault(); exportRecord.Sectors = secLang.Name; exportRecord.SectorType = sec.Type.ToString(); var intSec = exportRecord.Sectors; //International Nomenclature Code string intNId = ""; if (sec.International_NomenclatureID != Guid.Empty) { try { var interNid = sec.International_NomenclatureID.Value; TSMSector INT_Nom = new TSMSector(); INT_Nom = lstTSMSector.Where(u => u.ID == interNid && u.NomenclatureType == NomenclatureType.International && u.Type == sec.Type).FirstOrDefault(); if (INT_Nom != null) { intNId = INT_Nom.Code; } } catch { } } if (intNId == "") { TSMSector INT_Nom = new TSMSector(); INT_Nom = lstTSMSector.Where(u => u.Name == intSec && u.NomenclatureType == NomenclatureType.International && u.Type == sec.Type).FirstOrDefault(); if (INT_Nom != null) { intNId = INT_Nom.Code; } } //ITC Nomenclature Code string itcNid = ""; if (sec.ITC_NomenclatureID != Guid.Empty) { try { var itcid = sec.ITC_NomenclatureID.Value; TSMSector ITC_Nom = new TSMSector(); ITC_Nom = lstTSMSector.Where(u => u.ID == itcid && u.NomenclatureType == NomenclatureType.ITC && u.Type == sec.Type).FirstOrDefault(); if (ITC_Nom != null) { itcNid = ITC_Nom.Code; } } catch { } } if (itcNid == "") { TSMSector ITC_Nom = new TSMSector(); ITC_Nom = lstTSMSector.Where(u => u.Name == intSec && u.NomenclatureType == NomenclatureType.ITC && u.Type == sec.Type).FirstOrDefault(); if (ITC_Nom != null) { itcNid = ITC_Nom.Code; } } exportRecord.ITCCode = itcNid; exportRecord.INTCode = intNId; if (exportRecord != null) { ExportRecordData.Records.Add(exportRecord); ExportRecordData.RecID = exportRecord.RecordID; } } } #endregion #region [sector > 0 && country > 1] else if ((exportRecordData.Countries.Count > 1) && (exportRecordData.Sectors.Count > 0)) { foreach (var cnt in exportRecordData.Countries) { Country_Language countryLanguage = lstCountryLang.Where(cl => cl.ID == cnt.ID).FirstOrDefault(); var selectedRegion = new List <Region>(); Country tmpCountry = listofAllCountries.Where(c => c.ID == exportRecordData.Countries[0].ID).FirstOrDefault(); if (tmpCountry != null) { foreach (var r in tmpCountry.Regions) { selectedRegion.Add(r); } } var regionLanguageList = (from rl in listofAllRegion join r in selectedRegion on rl.ID equals r.ID where r.Type == TSM.Entity.RegionType.Geographical && rl.LanguageID == languageId select rl.Name).ToList(); foreach (var sec in exportRecordData.Sectors) { exportRecord = new ExportRecord(); //document try { if (exportRecordData.Documents.Count > 0) { exportRecord.Document = exportRecordData.Documents[0].Path.Split('.')[0].ToString(); } else { exportRecord.Document = null; } } catch { exportRecord.Document = ""; } //ID exportRecord.RecordID = exportRecordData.ID; //Name exportRecord.Name = exportRecordData.Record_Languages.FirstOrDefault().Name.ToString(); //Regions if (regionLanguageList.Count > 0) { exportRecord.Regions = regionLanguageList[0].ToString(); } //Country exportRecord.Countries = countryLanguage.Name; exportRecord.CountryCode = cnt.ISOCode; //variable values exportRecord.VariableValues = new List <string>(); List <string> recordVariableKey = new List <string>(); foreach (var variableValue in ExportRecordData.Variables) { if (variableValue != null && variableValue.Value != null && !string.IsNullOrEmpty(variableValue.Value) && variableValue.Value != "") { recordVariableKey.Add(variableValue.Key); exportRecord.VariableValues.Add(SearchServices.GetVariableValueByVariableIdFromList(languageId, exportRecordData.ID, recordVariableKey, variableValue.Key, recordVariables)); } } //sector Sector_Language secLang = lstSectorLanguage.Where(sl => sl.ID == sec.ID).FirstOrDefault(); exportRecord.Sectors = secLang.Name; exportRecord.SectorType = sec.Type.ToString(); var intSec = exportRecord.Sectors; //International Nomenclature Code string intNId = ""; if (sec.International_NomenclatureID != Guid.Empty) { try { var interNid = sec.International_NomenclatureID.Value; TSMSector INT_Nom = new TSMSector(); INT_Nom = lstTSMSector.Where(u => u.ID == interNid && u.NomenclatureType == NomenclatureType.International && u.Type == sec.Type).FirstOrDefault(); if (INT_Nom != null) { intNId = INT_Nom.Code; } } catch { } } if (intNId == "") { TSMSector INT_Nom = new TSMSector(); INT_Nom = lstTSMSector.Where(u => u.Name == intSec && u.NomenclatureType == NomenclatureType.International && u.Type == sec.Type).FirstOrDefault(); if (INT_Nom != null) { intNId = INT_Nom.Code; } } //ITC Nomenclature Code string itcNid = ""; if (sec.ITC_NomenclatureID != Guid.Empty) { try { var itcid = sec.ITC_NomenclatureID.Value; TSMSector ITC_Nom = new TSMSector(); ITC_Nom = lstTSMSector.Where(u => u.ID == itcid && u.NomenclatureType == NomenclatureType.ITC && u.Type == sec.Type).FirstOrDefault(); if (ITC_Nom != null) { itcNid = ITC_Nom.Code; } } catch { } } if (itcNid == "") { TSMSector ITC_Nom = new TSMSector(); ITC_Nom = lstTSMSector.Where(u => u.Name == intSec && u.NomenclatureType == NomenclatureType.ITC && u.Type == sec.Type).FirstOrDefault(); if (ITC_Nom != null) { itcNid = ITC_Nom.Code; } } exportRecord.ITCCode = itcNid; exportRecord.INTCode = intNId; if (exportRecord != null) { ExportRecordData.Records.Add(exportRecord); ExportRecordData.RecID = exportRecord.RecordID; } } } } #endregion #region [sector = 0 && country > 1] else if ((exportRecordData.Countries.Count > 1) && (exportRecordData.Sectors.Count == 0)) { foreach (var cnt in exportRecordData.Countries) { Country_Language countryLanguage = lstCountryLang.Where(cl => cl.ID == cnt.ID).FirstOrDefault(); var selectedRegion = new List <Region>(); Country tmpCountry = listofAllCountries.Where(c => c.ID == exportRecordData.Countries[0].ID).FirstOrDefault(); if (tmpCountry != null) { foreach (var r in tmpCountry.Regions) { selectedRegion.Add(r); } } var regionLanguageList = (from rl in listofAllRegion join r in selectedRegion on rl.ID equals r.ID where r.Type == TSM.Entity.RegionType.Geographical && rl.LanguageID == languageId select rl.Name).ToList(); exportRecord = new ExportRecord(); //document try { if (exportRecordData.Documents.Count > 0) { exportRecord.Document = exportRecordData.Documents[0].Path.Split('.')[0].ToString(); } else { exportRecord.Document = null; } } catch { exportRecord.Document = ""; } //ID exportRecord.RecordID = exportRecordData.ID; //Name exportRecord.Name = exportRecordData.Record_Languages.FirstOrDefault().Name.ToString(); //Regions if (regionLanguageList.Count > 0) { exportRecord.Regions = regionLanguageList[0].ToString(); } //Country exportRecord.Countries = countryLanguage.Name; exportRecord.CountryCode = cnt.ISOCode; //variable values exportRecord.VariableValues = new List <string>(); List <string> recordVariableKey = new List <string>(); foreach (var variableValue in ExportRecordData.Variables) { if (variableValue != null && variableValue.Value != null && !string.IsNullOrEmpty(variableValue.Value) && variableValue.Value != "") { recordVariableKey.Add(variableValue.Key); exportRecord.VariableValues.Add(SearchServices.GetVariableValueByVariableIdFromList(languageId, exportRecordData.ID, recordVariableKey, variableValue.Key, recordVariables)); } } if (exportRecord != null) { ExportRecordData.Records.Add(exportRecord); ExportRecordData.RecID = exportRecord.RecordID; } } } #endregion recordProcessed++; int percentRecord = (recordProcessed / TotalRecord) * 100; //Console.Clear(); Console.WriteLine(recordProcessed.ToString() + " of " + TotalRecord.ToString() + " records done. Plese wait..."); } catch (Exception ee) { recordNotProcessed++; Console.WriteLine(recordNotProcessed.ToString() + " of " + TotalRecord.ToString()); ErrorLog.WriteLog("Import", "Import", ee, ""); } } } ExportdataList.Add(ExportRecordData); if (DeleteFile()) { Console.WriteLine("Delete Success"); if (SaveXMLToData(ExportdataList)) { Console.WriteLine("Save Success"); } else { Console.WriteLine("Save Error!"); } } else { Console.Write("Delete Error!"); } #endregion } Console.WriteLine(recordProcessed.ToString() + " of " + TotalRecord.ToString() + " & " + recordNotProcessed.ToString() + " fail(s)."); }
/// <summary> /// 发送注册参数 /// </summary> /// <returns></returns> public IEnumerator sendRegisterParams() { messagePanel.SetActive(true); message.text = "正在获取服务器数据······"; //Dictionary<string, string> tmp = new Dictionary<string, string>(); //MyArrays<KeyValue> myArrays = new MyArrays<KeyValue>(); //myArrays.Items = new KeyValue[RegisterParams.Length]; KeyValue[] kvs = new KeyValue[3 + RegisterParams.Length]; kvs[0] = new KeyValue("uuid", MemberId); kvs[1] = new KeyValue("phone", phoneNumber); kvs[2] = new KeyValue("email", email); //从注册表单获取数据代码,直接发送手机号邮箱和识别码,暂不用注册 int i = 3; foreach (Text tmpT in RegisterParams) { KeyValue kv = new KeyValue(); kv.key = tmpT.name.Trim(); kv.value = tmpT.name == "no" ? selectSchool + tmpT.text.Trim(): tmpT.text.Trim(); kvs[i++] = kv; //tmp.Add(tmpT.name,tmpT.text); //JsonUtility.FromJson<Serialization<String, bool>>(jsonStr).ToDictionary(); } string jsonData = JsonConvert.SerializeObject(kvs); Debug.Log(jsonData); UnityWebRequest uw = wsb.PostWithParams(servelets.studentRegister, kvs); yield return(uw.Send()); Debug.Log(uw.downloadHandler.text); if (!uw.isNetworkError) { Debug.Log(uw.downloadHandler.text); ResponseJson rj = new ResponseJson(); //ResponseJson rj = JsonConvert.DeserializeObject<ResponseJson>(uw.downloadHandler.text); //var v = JsonConvert.DeserializeObject<dynamic>(uw.downloadHandler.text); JObject jsonText = JObject.Parse(uw.downloadHandler.text); // get JSON result objects into a list rj.stateCode = jsonText["stateCode"].Value <string>(); rj.message = jsonText["result"].Value <string>(); Debug.Log(rj.stateCode); if (rj.stateCode == "500") { StartCoroutine(requestFailed("该学号已注册")); Debug.Log(rj.stateCode); } else if (rj.stateCode == WebServicesBase.GetEnumDescription(stateCode.access) && rj.message == "学生信息注册成功") { Debug.Log("注册成功!"); RegisterPanel.SetActive(false); RegisterInfoPanel.SetActive(false); refeshClass(); } else { StartCoroutine(requestFailed("注册失败,请重试")); } } else { StartCoroutine(requestFailed()); } //messagePanel.SetActive(false); //JsonConvert.DeserializeObject<Product>(output); }
/// <summary> /// Gets the path where mod files should be installed. /// </summary> /// <returns>The path where mod files should be installed, or /// <c>null</c> if the path could not be determined.</returns> public string GetInstallationPath() { var registryKey = @"HKEY_CURRENT_USER\Software\Valve\Steam\Apps\275850"; Trace.TraceInformation(@"Checking for steam install: {0}\Installed", registryKey); Trace.Indent(); string strValue = null; try { Trace.TraceInformation("Getting Steam install folder."); var steamPath = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Valve\Steam", "SteamPath", null).ToString(); // convert path to windows path. (steam uses C:/x/y we want C:\\x\\y steamPath = Path.GetFullPath(steamPath); var appPath = Path.Combine(steamPath, @"steamapps\common\No Man's Sky"); // check if game is installed in the default directory if (!Directory.Exists(appPath)) { Trace.TraceInformation( "NoMansSky is not installed in standard directory. Checking steam config.vdf..."); // second try, check steam config.vdf // if any of this fails, no problem... just drop through the catch var steamConfig = Path.Combine(Path.Combine(steamPath, "config"), "config.vdf"); var kv = KeyValue.LoadAsText(steamConfig); var node = kv.Children[0].Children[0].Children[0].Children.Single(x => x.Name == "apps") .Children.Single(x => x.Name == "275850"); if (node != null) { appPath = node.Children.Single(x => x.Name == "installdir").Value; if (Directory.Exists(appPath) && File.Exists(Path.Combine(appPath, "Binaries", @"NMS.exe"))) { strValue = appPath; } } } else { strValue = appPath; } } catch { //if we can't read the registry or config.vdf, just return null } try { if (string.IsNullOrWhiteSpace(strValue)) { Trace.TraceInformation("Getting install folder from Uninstall."); var uniPath = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Steam App 275850", "InstallLocation", null).ToString(); if (Directory.Exists(uniPath)) { strValue = uniPath; } } } catch { } Trace.TraceInformation("Found {0}", strValue); Trace.Unindent(); return(strValue); }
public List <GameInfo> GetCategorizedGames(ulong steamId) { var id = new SteamID(steamId); var result = new List <GameInfo>(); var vdf = Path.Combine(Steam.InstallationPath, "userdata", id.AccountID.ToString(), "7", "remote", "sharedconfig.vdf"); var sharedconfig = new KeyValue(); sharedconfig.ReadFileAsText(vdf); var apps = sharedconfig["Software"]["Valve"]["Steam"]["apps"]; foreach (var app in apps.Children) { if (app.Children.Count == 0) { continue; } var appData = new List <string>(); var isFavorite = false; foreach (var tag in app["tags"].Children) { if (tag.Value == "favorite") { isFavorite = true; } else { appData.Add(tag.Value); } } string gameId = app.Name; if (app.Name.Contains('_')) { // Mods are keyed differently, "<appId>_<modId>" // Ex. 215_2287856061 string[] parts = app.Name.Split('_'); if (uint.TryParse(parts[0], out uint appId) && uint.TryParse(parts[1], out uint modId)) { var gid = new GameID() { AppID = appId, AppType = GameID.GameType.GameMod, ModID = modId }; gameId = gid; } else { // Malformed app id? continue; } } result.Add(new GameInfo() { Source = "Steam", GameId = gameId, Categories = new List <string>(appData), Hidden = app["hidden"].AsInteger() == 1, Favorite = isFavorite }); } return(result); }
public Knockback(KeyValue kv) : base(kv) { }
unsafe static DbType() { #region 数据类型集合 sqlTypeNames = new string[Sql.DbType.MaxEnumValue]; sqlTypeNames[(int)SqlDbType.BigInt] = "BIGINT"; //SqlTypeNames[(int)SqlDbType.Binary] = typeof(byte[]); sqlTypeNames[(int)SqlDbType.Bit] = "BIT"; sqlTypeNames[(int)SqlDbType.Char] = "CHAR"; sqlTypeNames[(int)SqlDbType.DateTime] = "DATETIME"; sqlTypeNames[(int)SqlDbType.Decimal] = "DECIMAL"; sqlTypeNames[(int)SqlDbType.Float] = "DOUBLE"; //SqlTypeNames[(int)SqlDbType.Image] = typeof(byte[]); sqlTypeNames[(int)SqlDbType.Int] = "INT"; sqlTypeNames[(int)SqlDbType.Money] = "DECIMAL"; sqlTypeNames[(int)SqlDbType.NChar] = "CHAR"; sqlTypeNames[(int)SqlDbType.NText] = "TEXT"; sqlTypeNames[(int)SqlDbType.NVarChar] = "VARCHAR"; sqlTypeNames[(int)SqlDbType.Real] = "FLOAT"; //SqlTypeNames[(int)SqlDbType.UniqueIdentifier] = typeof(Guid); sqlTypeNames[(int)SqlDbType.SmallDateTime] = "DATETIME"; sqlTypeNames[(int)SqlDbType.SmallInt] = "SMALLINT"; sqlTypeNames[(int)SqlDbType.SmallMoney] = "DECIMAL"; sqlTypeNames[(int)SqlDbType.Text] = "TEXT"; //SqlTypeNames[(int)SqlDbType.Timestamp] = typeof(byte[]); sqlTypeNames[(int)SqlDbType.TinyInt] = "TINYINT UNSIGNED"; //SqlTypeNames[(int)SqlDbType.VarBinary] = typeof(byte[]); sqlTypeNames[(int)SqlDbType.VarChar] = "VARCHAR"; //SqlTypeNames[(int)SqlDbType.Variant] = typeof(object); #endregion #region 默认值集合 defaultValues = new string[Sql.DbType.MaxEnumValue]; defaultValues[(int)SqlDbType.BigInt] = "0"; defaultValues[(int)SqlDbType.Bit] = "0"; defaultValues[(int)SqlDbType.Char] = "''"; defaultValues[(int)SqlDbType.DateTime] = "now()"; defaultValues[(int)SqlDbType.Decimal] = "0"; defaultValues[(int)SqlDbType.Float] = "0"; defaultValues[(int)SqlDbType.Int] = "0"; defaultValues[(int)SqlDbType.Money] = "0"; defaultValues[(int)SqlDbType.NChar] = "''"; defaultValues[(int)SqlDbType.NText] = "''"; defaultValues[(int)SqlDbType.NVarChar] = "''"; defaultValues[(int)SqlDbType.Real] = "0"; defaultValues[(int)SqlDbType.SmallDateTime] = "now()"; defaultValues[(int)SqlDbType.SmallInt] = "0"; defaultValues[(int)SqlDbType.SmallMoney] = "0"; defaultValues[(int)SqlDbType.Text] = "''"; defaultValues[(int)SqlDbType.TinyInt] = "0"; defaultValues[(int)SqlDbType.VarChar] = "''"; #endregion #region 数据类型集合唯一哈希 KeyValue <TypeName, KeyValue <SqlDbType, int> >[] names = new KeyValue <TypeName, KeyValue <SqlDbType, int> > [12]; names[0].Set((TypeName)"bigint", new KeyValue <SqlDbType, int>(SqlDbType.BigInt, sizeof(long))); names[1].Set((TypeName)"bit", new KeyValue <SqlDbType, int>(SqlDbType.Bit, sizeof(bool))); names[2].Set((TypeName)"char", new KeyValue <SqlDbType, int>(SqlDbType.Char, sizeof(char))); names[3].Set((TypeName)"datetime", new KeyValue <SqlDbType, int>(SqlDbType.DateTime, sizeof(DateTime))); names[4].Set((TypeName)"decimal", new KeyValue <SqlDbType, int>(SqlDbType.Decimal, sizeof(decimal))); names[5].Set((TypeName)"double", new KeyValue <SqlDbType, int>(SqlDbType.Float, sizeof(double))); names[6].Set((TypeName)"int", new KeyValue <SqlDbType, int>(SqlDbType.Int, sizeof(int))); names[7].Set((TypeName)"text", new KeyValue <SqlDbType, int>(SqlDbType.Text, int.MinValue)); names[8].Set((TypeName)"varchar", new KeyValue <SqlDbType, int>(SqlDbType.VarChar, int.MinValue)); names[9].Set((TypeName)"float", new KeyValue <SqlDbType, int>(SqlDbType.Real, sizeof(float))); names[10].Set((TypeName)"smallint", new KeyValue <SqlDbType, int>(SqlDbType.SmallInt, sizeof(short))); names[11].Set((TypeName)"tinyint", new KeyValue <SqlDbType, int>(SqlDbType.TinyInt, sizeof(byte))); sqlTypes = new UniqueDictionary <TypeName, KeyValue <SqlDbType, int> >(names, 16); #endregion }