public void IsNullOrEmptyTest() { List <int> list1 = null; Assert.IsTrue(list1.IsNullOrEmpty()); int[] ints = null; Assert.IsTrue(ints.IsNullOrEmpty()); Dictionary <char, int> dict1 = null; Assert.IsTrue(dict1.IsNullOrEmpty()); list1 = new List <int>(); Assert.IsTrue(list1.IsNullOrEmpty()); ints = new int[0]; Assert.IsTrue(ints.IsNullOrEmpty()); dict1 = new Dictionary <char, int>(); Assert.IsTrue(dict1.IsNullOrEmpty()); list1.Add(1); Assert.IsFalse(list1.IsNullOrEmpty()); ints = new[] { 0 }; Assert.IsFalse(ints.IsNullOrEmpty()); dict1['a'] = 1; Assert.IsFalse(dict1.IsNullOrEmpty()); }
private void Awake() { if (fallbackMessages.IsNullOrEmpty()) { UpdateCurrentLanguageAndTranslations(); } }
/// <summary> /// Cleanups this instance. /// </summary> private void Cleanup() { if (_listeners.IsNullOrEmpty()) { return; } var res = GetDeadListeners(); if (res.IsNullOrEmpty()) { return; } // NOTE: Workaround for iOS var keys = new DelegateReference[res.Length]; for (var i = 0; i < keys.Length; i++) { keys[i] = res[i]; } foreach (var key in keys) { Loggers.Default.ConsoleLogger.Write("Listener_Cleanup [{0}=\"{1}\"]", key, key.Id); _listeners.Remove(key); } }
protected virtual void Awake() { InitSingleInstance(); if (instance != this) { return; } if (fallbackMessages.IsNullOrEmpty()) { ReloadTranslationsAndUpdateScene(); } }
public static void AddDist(this ComboBox cmb) { if (cmb.Items.Count > 0) { (cmb.DataSource as BindingSource).Clear(); } if (!_DicDistrict.IsNullOrEmpty()) { cmb.DataSource = new BindingSource(_DicDistrict, null); cmb.DisplayMember = "Value"; cmb.ValueMember = "Key"; cmb.SelectedIndex = -1; } }
public void IsNullOrEmpty_Returns_True_When_Dictionary_Is_Not_Null_But_Emtpy() { Dictionary <string, string> testValue = new Dictionary <string, string>(); bool result = testValue.IsNullOrEmpty(); Assert.True(result); }
private static void WebViewDayCheck() { if (VALUES.IsNullOrEmpty() == true) { return; } uint nowDay = TimeManager.Instance.ConvertDay(TimeManager.Instance.m_TimeNow); List <uint> dellist = new List <uint>(); dellist.Clear(); foreach (KeyValuePair <uint, uint> dic in VALUES) { if (dic.Value <= nowDay) { dellist.Add(dic.Key); } } foreach (uint key in dellist) { VALUES.Remove(key); } }
public override string ToString() { var dic = new Dictionary <string, int>(); Simplify(); if (!NormalArmers.IsNullOrEmpty()) { foreach (var(Name, Count) in NormalArmers) { dic.Add(Name, Count); } } if (!EscapeArmers.IsNullOrEmpty()) { foreach (var(Name, Count) in EscapeArmers) { dic.Add(Name, Count); } } if (Golds != 0) { dic.Add("金币", Golds); } return(dic.IsNullOrEmpty() ? "" : string.Join("\r\n", dic.Select(p => $"{p.Key} * {p.Value}"))); }
/// <summary> /// 定义 MetadataTypeAttribute 类。 /// </summary> private void DefineMetadataType() { if (validations.IsNullOrEmpty() && eValidations.IsNullOrEmpty()) { return; } var metadataType = assemblyBuilder.DefineType("<Metadata>__" + TypeName); if (validations != null) { foreach (var property in validations.Keys) { var propertyBuilder = metadataType.DefineProperty(property.Name, typeof(IProperty)); propertyBuilder.DefineGetSetMethods(); foreach (var expression in validations[property]) { propertyBuilder.SetCustomAttribute(expression); } } } if (eValidations != null) { foreach (var expression in eValidations) { metadataType.SetCustomAttribute(expression); } } InnerBuilder.SetCustomAttribute <MetadataTypeAttribute>(metadataType.CreateType()); }
private void OnRecyclingDataUpdate() { if (!Singleton <Game> .IsInstance()) { return; } AIProject.SaveData.Environment environment = Singleton <Game> .Instance.Environment; Dictionary <int, RecyclingData> source = environment == null ? (Dictionary <int, RecyclingData>)null : environment.RecyclingDataTable; if (source.IsNullOrEmpty <int, RecyclingData>()) { return; } foreach (KeyValuePair <int, RecyclingData> keyValuePair in source) { RecyclingData data = keyValuePair.Value; if (data != null) { if (!data.CreateCountEnabled) { data.CreateCounter = 0.0f; } else if ((double)this.CountLimit <= (double)data.CreateCounter) { this.CreateItem(keyValuePair.Key, data); } } } }
/// <summary> /// 根据中奖概率随机取出一条中奖信息 /// </summary> /// <param name="orignalRates"></param> /// <returns></returns> public Dictionary <Guid, int> Lottery(Dictionary <Guid, int> orignalRates) { var resultDic = new Dictionary <Guid, int>(); if (orignalRates == null || orignalRates.IsNullOrEmpty()) { return(null); } var maxSize = orignalRates.Count(); var maxProbabilityNum = 0; var dic = new Dictionary <Guid, string>(); foreach (var rate in orignalRates) { dic.Add(rate.Key, maxProbabilityNum + "-" + (maxProbabilityNum + rate.Value)); maxProbabilityNum += rate.Value; } var random = new Random().Next(maxProbabilityNum) + 1; foreach (var d in dic) { var min = int.Parse(d.Value.Split('-')[0]); var max = int.Parse(d.Value.Split('-')[1]); if (random > min && random <= max) { resultDic.Add(d.Key, orignalRates[d.Key].ToInt16() / 100); return(resultDic); } } return(resultDic); }
/// <summary> /// Returns all types of all current assemblies /// </summary> public static List <Type> GetFullTypes() { List <Type> types = new List <Type>(); if (cache_types.IsNullOrEmpty()) { cache_types = new Dictionary <string, Type>(); foreach (Assembly assembly in GetFullAssemblies()) { foreach (Type type in assembly.GetTypes()) { if (type != null && type.IsPublic) { cache_types[type.GetTypeName(true)] = type; } } } types = cache_types.Values.ToList(); types.Sort((t1, t2) => string.Compare((t1.FullName ?? t1.Name), (t2.FullName ?? t2.Name))); return(types); } else { types = cache_types.Values.ToList(); return(types); } }
protected override void Start() { base.Start(); if (Singleton <Game> .IsInstance()) { Dictionary <int, float> pointCoolTimeTable = Singleton <Game> .Instance.Environment?.DropSearchActionPointCoolTimeTable; float num; if (!pointCoolTimeTable.IsNullOrEmpty <int, float>() && pointCoolTimeTable.TryGetValue(this.RegisterID, out num)) { if ((double)num <= 0.0) { pointCoolTimeTable.Remove(this.RegisterID); } else { this._coolTime = num; this._isCoolTime = true; if (((Component)this).get_gameObject().get_activeSelf()) { ((Component)this).get_gameObject().SetActive(false); } } } } if (this._updateDisposable != null) { this._updateDisposable.Dispose(); } this._updateDisposable = ObservableExtensions.Subscribe <long>(Observable.TakeUntilDestroy <long>(Observable.TakeUntilDestroy <long>((IObservable <M0>)Observable.EveryUpdate(), ((Component)this).get_gameObject()), (Component)this), (Action <M0>)(_ => this.OnUpdate())); }
public override void OnInspectorGUI() { // When some shit happened. Mostly my fault. if (_fields.IsNullOrEmpty()) { GUILayout.Label("This component does not have any properties to edit."); return; } // Detect changes and repaint them only when detect changes. // Thanks for unity forum to alert me this EditorGUI.BeginChangeCheck(); DrawCustomInspector(); if (EditorGUI.EndChangeCheck()) { UpdateInspector(); } // It will restore gui layout as possible. if (GUIEvent == null) { return; } DoEvent(); GUIEvent = null; }
public static IEnumerable <DeliveryModeViewModel> CreateDeliveryModes(Dictionary <string, long?> trainingOptionsAggregation, IEnumerable <string> selectedTrainingOptions) { var viewModels = new List <DeliveryModeViewModel>(); if (trainingOptionsAggregation.IsNullOrEmpty()) { return(viewModels); } foreach (var item in trainingOptionsAggregation) { viewModels.Add(new DeliveryModeViewModel { Title = GetName(item.Key), Count = item.Value ?? 0L, Checked = selectedTrainingOptions?.Contains(item.Key.ToLower()) ?? false, Value = item.Key.ToLower() }); } var orderList = new List <string> { "dayrelease", "blockrelease", "100percentemployer" }; return(orderList.Select(i => viewModels.SingleOrDefault(m => m.Value.ToLower() == i)).WhereNotNull()); }
private bool LoadMaterial() { if (_materials.IsNullOrEmpty()) { _materials = new Dictionary <string, Material>(); } else { _materials.Clear(); } AssetBundle.UnloadAllAssetBundles(false); foreach (var bundlePath in bundles) { var bundle = AssetBundleManager.GetBundle(Path.Combine(Directory.GetCurrentDirectory(), bundlePath)); foreach (var path in bundle.GetAllAssetNames()) { var material = bundle.LoadAsset <Material>(path); if (material == null) { continue; } if (_materials.ContainsKey(material.name)) { continue; } _materials.Add(material.name, Instantiate(material)); } } return(true); }
/// <summary> /// 重新整理 /// </summary> public void Refresh() { if (Session["UserID"] == null) { divEdit.Visible = false; labErrMsg.Visible = true; labErrMsg.Text = Util.getHtmlMessage(Util.HtmlMessageKind.Error, SinoPac.WebExpress.Common.Properties.Resources.CommPhrase_SessionNotFound); return; } labEdit.Text = RS.Resources.CommPhrase_labEdit; btnSave.Text = RS.Resources.CommPhrase_btnSave; txtPhrase.ucTextData = string.Empty; Dictionary <string, string> dicPhrase = Util.getDictionary(UserInfo.getUserProperty(UserInfo.getUserInfo().UserID, _PropKind, _PropID)["PropJSON"]); if (!dicPhrase.IsNullOrEmpty()) { string strTextData = string.Empty; foreach (var pair in dicPhrase) { if (strTextData.Length > 0) { strTextData += "\n"; } strTextData += pair.Value; } txtPhrase.ucTextData = strTextData; } }
private void Awake() { if (themeNameToTheme.IsNullOrEmpty()) { ReloadThemes(); } }
/// <summary> /// Given existing template Program.cs Syntax Tree, Add configurations and generate new Syntax Tree. /// </summary> /// <param name="programTree">Syntax Tree for existing Program.cs Template</param> /// <returns>New root with updated Program.cs</returns> public SyntaxNode ReplaceProgramFile(SyntaxTree programTree) { Dictionary <string, int> transportPort = new Dictionary <string, int>(); Dictionary <string, BindingConfiguration> bindingModeMap = new Dictionary <string, BindingConfiguration>(); if (_projectType == ProjectType.WCFConfigBasedService) { string projectDir = _analyzerResult.ProjectResult.ProjectRootPath; bindingModeMap = GetBindingsTransportMap(projectDir); AddBinding(bindingModeMap, transportPort); } else { ProjectWorkspace project = _analyzerResult.ProjectResult; bindingModeMap = GetBindingsTransportMap(project); AddBinding(bindingModeMap, transportPort); } if (transportPort.IsNullOrEmpty()) { return(programTree.GetRoot()); } var containsTransportRelatedMode = bindingModeMap.Any(b => b.Value.Mode.ToLower() == Constants.TransportMessageCredentialsMode.ToLower() || b.Value.Mode.ToLower() == Constants.TransportMode.ToLower()); var newRoot = ReplaceProgramNode(transportPort, programTree, containsTransportRelatedMode); return(newRoot); }
/// <summary> /// 重新整理 /// </summary> public void Refresh() { if (Session["UserID"] == null) { divPick.Visible = false; labErrMsg.Visible = true; labErrMsg.Text = Util.getHtmlMessage(Util.HtmlMessageKind.Error, RS.Resources.Msg_SessionNotFound); return; } if (string.IsNullOrEmpty(ucTargetClientID)) { divPick.Visible = false; return; } //btnAppend btnAppend.CssClass = ucBtnCssClass; btnAppend.Text = RS.Resources.CommPhrase_btnAppend; btnAppend.OnClientClick = string.Format("Util_DropDownListItemToTextBox('{0}','{1}','{2}','N');return false;", ddlPhrase.ClientID + "_ddlSourceList", ucTargetClientID, (ucIsParentTarget) ? "Y" : "N"); //btnReplace 2017.06.09 btnReplace.CssClass = ucBtnCssClass; btnReplace.Text = RS.Resources.CommPhrase_btnReplace; btnReplace.OnClientClick = string.Format("Util_DropDownListItemToTextBox('{0}','{1}','{2}','Y');return false;", ddlPhrase.ClientID + "_ddlSourceList", ucTargetClientID, (ucIsParentTarget) ? "Y" : "N"); //ddlPhrase ddlPhrase.ucCaption = ucCaption; ddlPhrase.ucCaptionWidth = ucCaptionWidth; ddlPhrase.ucCaptionHorizontalAlign = ucCaptionHorizontalAlign; ddlPhrase.ucDropDownSourceListWidth = ucDropDownSourceListWidth; ddlPhrase.ucIsSearchEnabled = ucIsSearchEnabled; ddlPhrase.ucSearchBoxWidth = ucSearchBoxWidth; ddlPhrase.ucSearchBoxWaterMarkText = ucSearchBoxWaterMarkText; Dictionary <string, string> dicPhrase = new Dictionary <string, string>(); if (ucPKKind == "User" && ucPropID == "CommPhrase") { dicPhrase = Util.getDictionary(UserInfo.getUserProperty(UserInfo.getUserInfo().UserID, ucPKKind, ucPropID)["PropJSON"]); } else { dicPhrase = Util.getDictionary(Util.getCustProperty(ucDBName, ucPKID, ucPKKind, ucPropID)["PropJSON"]); } ddlPhrase.ucSourceDictionary = dicPhrase; ddlPhrase.ucSelectedID = ""; ddlPhrase.Refresh(); //判斷顯示與否 if (!ucIsVisibleWhenNoData && dicPhrase.IsNullOrEmpty()) { this.Visible = false; } else { this.Visible = true; } }
public virtual TaskStatus OnUpdate() { PointManager pointManager = !Singleton <Manager.Map> .IsInstance() ? (PointManager)null : Singleton <Manager.Map> .Instance.PointAgent; if ((!Object.op_Inequality((Object)pointManager, (Object)null) ? (Waypoint[])null : pointManager.Waypoints).IsNullOrEmpty <Waypoint>()) { bool flag = false; Dictionary <int, List <Waypoint> > source = !Object.op_Inequality((Object)pointManager, (Object)null) ? (Dictionary <int, List <Waypoint> >)null : pointManager.HousingWaypointTable; if (!source.IsNullOrEmpty <int, List <Waypoint> >()) { foreach (KeyValuePair <int, List <Waypoint> > keyValuePair in source) { if (flag = !keyValuePair.Value.IsNullOrEmpty <Waypoint>()) { break; } } } if (!flag) { return((TaskStatus)3); } } if (this._agent.SearchAnimalEmpty) { return((TaskStatus)1); } if (this._agent.LivesAnimalCalc) { return((TaskStatus)3); } return(this._agent.SearchAnimalRoute.Count == 0 && Object.op_Equality((Object)this._agent.DestWaypoint, (Object)null) || !this._agent.LivesAnimalPatrol ? (TaskStatus)2 : (TaskStatus)3); }
public void ItShouldBeFalse() { IDictionary <string, bool> blah = new Dictionary <string, bool>(); blah.Add(Guid.NewGuid().ToString(), true); Assert.IsFalse(blah.IsNullOrEmpty()); }
/// <summary>构造带查询串的URL(类似http://www.temp.com/Index?a=***&b=***)</summary> public static string GetQueryUrl(this string url, Dictionary <string, object> queryParams) { if (queryParams.IsNullOrEmpty()) { return(url); } var url2 = new StringBuilder(url); url2.Append("?"); foreach (var pair in queryParams) { var values = pair.Value.As <IEnumerable>(); if (values == null) { var value = HttpUtility.UrlEncode(pair.Value.ToString()); url2.Append(pair.Key) .Append("=") .Append(value) .Append("&"); continue; } foreach (var value in values) { url2.Append(pair.Key) .Append("=") .Append(HttpUtility.UrlEncode(value.ToString())) .Append("&"); } } url2.Length -= 1; return(url2.ToString()); }
/// <summary> /// Recursively traverse the schema's extends to verify that it or one of it's parents /// has at least one property /// </summary> /// <param name="properties">The schema's properties</param> /// <param name="extends">The schema's extends</param> /// <returns>True if one or more properties found in this schema or in it's ancestors. False otherwise</returns> private bool AncestorsHaveProperties(Dictionary <string, Schema> properties, string extends) { if (properties.IsNullOrEmpty() && string.IsNullOrEmpty(extends)) { return(false); } if (!properties.IsNullOrEmpty()) { return(true); } Debug.Assert(!string.IsNullOrEmpty(extends) && ServiceDefinition.Definitions.ContainsKey(extends)); return(AncestorsHaveProperties(ServiceDefinition.Definitions[extends].Properties, ServiceDefinition.Definitions[extends].Extends)); }
public async Task <IActionResult> collectionList(int retrievalID) { List <dynamic> pd_collectionList = new List <dynamic>(); string status = "PendingDelivery"; List <Request> pendingDeliveryRequests = new List <Request>(); Dictionary <int, DateTime> retrievalID_CollectionTime = new Dictionary <int, DateTime>(); CollectionPoint cp = new CollectionPoint(); int user_CPId = (int)HttpContext.Session.GetInt32("CPId"); int deptID = (int)HttpContext.Session.GetInt32("DeptId"); using (var httpClient = new HttpClient()) { using (var response = await httpClient.GetAsync(api_url_rqst + "/GetRequestByStatusByDept/" + status + "/" + deptID)) { string apiResponse = await response.Content.ReadAsStringAsync(); pendingDeliveryRequests = JsonConvert.DeserializeObject <List <Request> >(apiResponse); } using (var response = await httpClient.GetAsync(api_url + "/" + user_CPId)) { string apiResponse = await response.Content.ReadAsStringAsync(); cp = JsonConvert.DeserializeObject <CollectionPoint>(apiResponse); } } foreach (var r in pendingDeliveryRequests) { int? key = r.RetrievalID; DateTime value = r.CollectionTime; if (!retrievalID_CollectionTime.ContainsKey((int)key)) { retrievalID_CollectionTime.Add((int)key, value); } } if (retrievalID != 0) { using (var httpClient = new HttpClient()) { using (var response = await httpClient.GetAsync(api_url_rqst + "/GetItemByStatus/" + status + "/" + retrievalID + "/" + deptID)) { string apiResponse = await response.Content.ReadAsStringAsync(); pd_collectionList = JsonConvert.DeserializeObject <List <dynamic> >(apiResponse); } } } if (pd_collectionList.IsNullOrEmpty() || retrievalID_CollectionTime.IsNullOrEmpty()) { ViewData["collectionRequest"] = null; } ViewData["collectionRequest"] = pd_collectionList; ViewData["retrieval_time"] = retrievalID_CollectionTime; ViewData["collectionPoint"] = cp; return(View()); }
/// <summary> /// Saves the prediction values to entity. /// </summary> /// <typeparam name="T">The type of predicted values.</typeparam> /// <param name="schemaUId">The entity schema's identifier, which should be saved.</param> /// <param name="entityId">The entity identifier.</param> /// <param name="predictedValues">The predicted values of entity for the several models.</param> /// <param name="valueTransformer"> /// Optional mapping function, that should be applied to predicted value before saving. /// </param> /// <returns> /// <c>true</c> if the entity was saved, otherwise - <c>false</c>. /// </returns> protected virtual bool SaveEntityPredictedValues <T>(Guid schemaUId, Guid entityId, Dictionary <MLModelConfig, T> predictedValues, Func <T, object> valueTransformer) { if (predictedValues.IsNullOrEmpty()) { return(false); } Entity entity = GetEntity(schemaUId, entityId); if (entity == null) { return(false); } foreach (KeyValuePair <MLModelConfig, T> prediction in predictedValues) { MLModelConfig model = prediction.Key; EntitySchemaColumn column = entity.FindEntityColumnValue(model.PredictedResultColumnName).Column; if (valueTransformer != null) { object transformedPredictionValue = valueTransformer(prediction.Value); entity.SetColumnValue(column, transformedPredictionValue); } else { entity.SetColumnValue(column, prediction.Value); } } return(entity.Save()); }
public static NationalProviderViewModel GetNationalProvidersAmount(Dictionary <string, long?> nationalProvidersAggregation, bool selectedNationalProvider) { var viewModel = new NationalProviderViewModel(); if (nationalProvidersAggregation.IsNullOrEmpty()) { return(new NationalProviderViewModel()); } foreach (var item in nationalProvidersAggregation) { if (item.Key == "true") { viewModel = new NationalProviderViewModel { Title = "only national", Count = item.Value ?? 0L, Checked = selectedNationalProvider, Value = item.Key }; } } return(viewModel); }
/// <summary> /// Asynchronous export item's properties /// </summary> /// <returns>An <see cref="ExportableCI"/> instance containing all relevant properties</returns> public Task <ExportableGroupCI> ExportAsync() { var cr = new Dictionary <string, string>(); if (!CompetitorsReferences.IsNullOrEmpty()) { foreach (var competitorsReference in CompetitorsReferences) { try { if (!competitorsReference.Value.ReferenceIds.IsNullOrEmpty()) { var refs = string.Join(",", competitorsReference.Value.ReferenceIds.Select(s => $"{s.Key}={s.Value}")); cr.Add(competitorsReference.Key.ToString(), refs); } } catch (Exception e) { SdkLoggerFactory.GetLoggerForExecution(typeof(GroupCI)).Error("Exporting GroupCI", e); } } } return(Task.FromResult(new ExportableGroupCI { Id = Id, Name = Name, Competitors = CompetitorsIds?.Select(s => s.ToString()).ToList(), CompetitorsReferences = cr.IsNullOrEmpty() ? null : cr })); }
void IJsonSerializable.WriteProperties(Utf8JsonWriter json) { if (Enabled.HasValue) { json.WriteStartObject(s_attributesPropertyNameBytes); json.WriteBoolean(s_enabledPropertyNameBytes, Enabled.Value); json.WriteEndObject(); } if (!_tags.IsNullOrEmpty()) { json.WriteStartObject(s_tagsPropertyNameBytes); foreach (KeyValuePair <string, string> kvp in _tags) { json.WriteString(kvp.Key, kvp.Value); } json.WriteEndObject(); } if (X509Certificates != null) { json.WriteStartArray(s_x5cPropertyNameBytes); foreach (byte[] x509certificate in X509Certificates) { json.WriteBase64StringValue(x509certificate); } json.WriteEndArray(); } }
public static bool GetOrderNos(this ListBox lst, string ledgerid) { Dictionary <string, string> dicOrderno = new Dictionary <string, string>(); string query = "select SlNo,CustomerOrderNo,OrderDate from SalesOrder Where Ledgerid='" + ledgerid + "'"; DataTable dt = SQLHelper.GetInstance().ExcuteNonQuery(query, out msg); if (dt.IsValidDataTable()) { foreach (DataRow item in dt.Rows) { string orderdate = DateTime.Parse(item["OrderDate"].ToString()).ToString("dd-MMM-yyy"); string customerorderno = item["CustomerOrderNo"].ToString(); string id = item["SlNo"].ToString(); string name = id + " #" + customerorderno + " # " + orderdate; dicOrderno.Add(id, name); } if (!dicOrderno.IsNullOrEmpty()) { lst.DataSource = new BindingSource(dicOrderno, null); lst.DisplayMember = "Value"; lst.ValueMember = "Key"; lst.SelectedIndex = -1; return(true); } } return(false); }
public void Returns_false_when_items_exist() { var dict = new Dictionary<string, object>() { ["foo"] = new object() }; dict.IsNullOrEmpty().ShouldBeFalse(); }
public void NotifyEverybodyInChatAboutProfileChanges(int playerId, Dictionary<string, object> properties) { if (properties.IsNullOrEmpty()) return; var info = new UserPropertiesChangedInfo(); info.Properties = properties.Select(i => new PropertyValuePair(i.Key, i.Value)).ToArray(); info.UserId = playerId; _sessionManager.SendToEachChatSessions(info); }
public Generator(Project project, Dictionary<Template, List<TemplateOutputDefinitionFilenameResult>> templateOutputs) { if (project == null) throw new ArgumentNullException("project"); if (templateOutputs.IsNullOrEmpty()) throw new ArgumentNullException("templateOutputs"); this.Project = project; this.TemplateOutputs = templateOutputs; this.CancellationTokenSource = new CancellationTokenSource(); }
public void Returns_true_when_empty() { var dict = new Dictionary<string, object>(); dict.IsNullOrEmpty().ShouldBeTrue(); }
/// <summary> /// Creates a new DBObject of a given GraphType inserts its UUID into all indices of the given GraphType. /// </summary> /// <param name="myGraphDBType">The GraphType of the DBObject to create</param> /// <param name="myDBObjectAttributes">A dictionary of attributes for the new DBObject</param> /// <param name="mySpecialTypeAttributes">Special values which should be set to a object</param> /// <param name="myCheckUniqueness">check for unique constraints</param> /// <returns>The UUID of the new DBObject</returns> public Exceptional<DBObjectStream> CreateNewDBObjectStream(GraphDBType myGraphDBType, Dictionary<AttributeUUID, IObject> myDBObjectAttributes, Dictionary<String, IObject> myUndefAttributes, Dictionary<ASpecialTypeAttribute, Object> mySpecialTypeAttributes, SessionSettings mySessionSettings, Boolean myCheckUniqueness) { #region Input validation if (myGraphDBType == null) return new Exceptional<DBObjectStream>(new Error_ArgumentNullOrEmpty("The parameter myGraphType must not be null!")); if (myDBObjectAttributes == null) return new Exceptional<DBObjectStream>(new Error_ArgumentNullOrEmpty("The parameter myDBObjectAttributes must not be null!")); #endregion #region Check uniqueness if (myCheckUniqueness) { var parentTypes = _DBContext.DBTypeManager.GetAllParentTypes(myGraphDBType, true, false); var CheckVal = _DBContext.DBIndexManager.CheckUniqueConstraint(myGraphDBType, parentTypes, myDBObjectAttributes); if (CheckVal.Failed()) return new Exceptional<DBObjectStream>(CheckVal); } #endregion #region Create a new DBObjectStream DBObjectStream _NewDBObjectStream = null; ObjectUUID _NewObjectUUID = null; ASpecialTypeAttribute _SpecialTypeAttribute_UUID_Key = new SpecialTypeAttribute_UUID(); Object _SpecialTypeAttribute_UUID_Value = null; #region Search for an user-defined ObjectUUID if (mySpecialTypeAttributes != null) { if (mySpecialTypeAttributes.TryGetValue(_SpecialTypeAttribute_UUID_Key, out _SpecialTypeAttribute_UUID_Value)) { // User-defined ObjectUUID of type UInt64 var _ValueAsUInt64 = _SpecialTypeAttribute_UUID_Value as UInt64?; if (_ValueAsUInt64 != null) _NewObjectUUID = new ObjectUUID(_ValueAsUInt64.Value); // User-defined ObjectUUID of type String or anything else... else { var _String = _SpecialTypeAttribute_UUID_Value.ToString(); if (_String == null || _String == "") return new Exceptional<DBObjectStream>(new Error_InvalidAttributeValue(SpecialTypeAttribute_UUID.AttributeName, _String)); _NewObjectUUID = new ObjectUUID(_SpecialTypeAttribute_UUID_Value.ToString()); } mySpecialTypeAttributes[_SpecialTypeAttribute_UUID_Key] = _NewObjectUUID; } } #endregion // If _NewObjectUUID == null a new one will be generated! _NewDBObjectStream = new DBObjectStream(_NewObjectUUID, myGraphDBType, myDBObjectAttributes); _NewDBObjectStream.ObjectLocation = new ObjectLocation(_NewDBObjectStream.ObjectPath, _NewDBObjectStream.ObjectUUID.ToString()); #endregion #region Check for duplicate ObjectUUIDs... maybe resolve duplicates! var _DBObjectStreamAlreadyExistsResult = ObjectExistsOnFS(_NewDBObjectStream); if (_DBObjectStreamAlreadyExistsResult.Failed()) return new Exceptional<DBObjectStream>(_DBObjectStreamAlreadyExistsResult); while (_DBObjectStreamAlreadyExistsResult.Value == Trinary.TRUE) { if (_NewObjectUUID != null) return new Exceptional<DBObjectStream>(new Error_DBObjectCollision(_NewDBObjectStream)); _NewDBObjectStream = new DBObjectStream(ObjectUUID.NewUUID, myGraphDBType, myDBObjectAttributes); _NewDBObjectStream.ObjectLocation = new ObjectLocation(_NewDBObjectStream.ObjectPath, _NewDBObjectStream.ObjectUUID.ToString()); _DBObjectStreamAlreadyExistsResult = ObjectExistsOnFS(_NewDBObjectStream); if (_DBObjectStreamAlreadyExistsResult.Failed()) return new Exceptional<DBObjectStream>(_DBObjectStreamAlreadyExistsResult); } #endregion #region Check for ExtractSetting attributes unlike UUID if (mySpecialTypeAttributes != null && mySpecialTypeAttributes.Any()) { foreach (var _SpecialAttribute in mySpecialTypeAttributes) { // Skip SpecialTypeAttribute_UUID! if (!(_SpecialAttribute.Key is SpecialTypeAttribute_UUID)) { var result = _SpecialAttribute.Key.ApplyTo(_NewDBObjectStream, _SpecialAttribute.Value); if (result.Failed()) { return new Exceptional<DBObjectStream>(result); } } } } #endregion // Flush new DBObject var flushResult = FlushDBObject(_NewDBObjectStream); if (flushResult.Failed()) return new Exceptional<DBObjectStream>(flushResult); #region Check for existing object - might be removed at some time //var exists = ObjectExistsOnFS(_NewDBObjectStream); //if (exists.Failed()) // return new Exceptional<DBObjectStream>(exists); //if (exists.Value != Trinary.TRUE) //{ // return new Exceptional<DBObjectStream>(new Error_UnknownDBError("DBObject with path " + _NewDBObjectStream.ObjectLocation + " does not exist.")); //} #endregion #region Add UUID of the new DBObject to all indices of myGraphType foreach (var _GraphDBType in _DBContext.DBTypeManager.GetAllParentTypes(myGraphDBType, true, false)) { foreach (var _AAttributeIndex in _GraphDBType.GetAllAttributeIndices(false)) { //Find out if the dbobject carries all necessary attributes if (_NewDBObjectStream.HasAtLeastOneAttribute(_AAttributeIndex.IndexKeyDefinition.IndexKeyAttributeUUIDs, _GraphDBType, mySessionSettings)) { //valid dbo for idx _AAttributeIndex.Insert(_NewDBObjectStream, _GraphDBType, _DBContext); } } } #endregion #region add undefined attributes to the object if (!myUndefAttributes.IsNullOrEmpty()) { foreach (var item in myUndefAttributes) { var addExcept = _NewDBObjectStream.AddUndefinedAttribute(item.Key, item.Value, this); if (addExcept.Failed()) { return new Exceptional<DBObjectStream>(addExcept); } } } #endregion return new Exceptional<DBObjectStream>(_NewDBObjectStream); }
public void ItShouldBeFalse() { IDictionary<string, bool> blah = new Dictionary<string, bool>(); blah.Add(Guid.NewGuid().ToString(), true); Assert.IsFalse(blah.IsNullOrEmpty()); }
/// <summary> /// 统计停车次数,过滤停车时长小于指定值的次数 /// </summary> /// <param name="dicCodeAndLicenceNumber"></param> /// <param name="beginTime"></param> /// <param name="endTime"></param> /// <param name="second"></param> /// <param name="tenantCode"></param> /// <returns></returns> public Dictionary<Guid, VCountStopCar> Count(Dictionary<Guid, string> dicCodeAndLicenceNumber, DateTime beginTime, DateTime endTime, int second, string tenantCode) { if (dicCodeAndLicenceNumber.IsNullOrEmpty()) { return new Dictionary<Guid, VCountStopCar>(); } IList<Guid> ltVehicleCode = dicCodeAndLicenceNumber.Keys.ToList(); return Count(ltVehicleCode, beginTime, endTime, second, tenantCode); }
public IEnumerable<IVertexView> GetTypeIndependendResult(SecurityToken mySecurityToken, Int64 myTransactionToken) { //_DBOs = new IEnumerable<Vertex>(); var Attributes = new Dictionary<string, object>(); #region Go through all _SelectionElementsTypeIndependend foreach (var selection in _SelectionElementsTypeIndependend) { if (selection is SelectionElementFunction) { var func = ((SelectionElementFunction)selection); FuncParameter funcResult = null; var alias = func.Alias; object CallingObject = null; while (func != null) { var parameter = func.Function.Execute(null, null, null, _pluginManager, _graphdb, mySecurityToken, myTransactionToken); funcResult = func.Function.Function.ExecFunc(null, CallingObject, null, _graphdb, mySecurityToken, myTransactionToken, parameter.ToArray()); if (funcResult.Value == null) { break; // no result for this object because of not set attribute value } else { func = func.FollowingFunction; if (func != null) { CallingObject = funcResult.Value; } } } if (funcResult.Value == null) { continue; // no result for this object because of not set attribute value } Attributes.Add(alias, funcResult.Value); } } #endregion if (!Attributes.IsNullOrEmpty()) { yield return new VertexView(Attributes, null); } }
public IEnumerable<Vertex> GetTypeIndependendResult() { //_DBOs = new IEnumerable<Vertex>(); var Attributes = new Dictionary<string, object>(); #region Go through all _SelectionElementsTypeIndependend foreach (var selection in _SelectionElementsTypeIndependend) { if (selection is SelectionElementFunction) { var func = ((SelectionElementFunction)selection); Exceptional<FuncParameter> funcResult = null; var alias = func.Alias; while (func != null) { funcResult = func.Function.Execute(null, null, null, _DBContext); if (funcResult.Success()) { if (funcResult.Value.Value == null) { break; // no result for this object because of not set attribute value } else { func = func.FollowingFunction; if (func != null) { func.Function.Function.CallingObject = funcResult.Value.Value; } } } else { //return new Exceptional<IEnumerable<Vertex>>(res.Errors); throw new GraphDBException(funcResult.IErrors); } } if (funcResult.Value.Value == null) { continue; // no result for this object because of not set attribute value } Attributes.Add(alias, ((FuncParameter)funcResult.Value).Value.GetReadoutValue()); } } #endregion if (!Attributes.IsNullOrEmpty()) { yield return new Vertex(Attributes); } }
/// <summary> /// Create a readout based on the passed <paramref name="attributes"/>, <paramref name="undefinedAttributes"/>, <paramref name="specialTypeAttributes"/> which are all optional /// </summary> /// <param name="myDBObjectStreamExceptional"></param> /// <param name="attributes"></param> /// <param name="undefinedAttributes"></param> /// <param name="specialTypeAttributes"></param> /// <returns></returns> private Exceptional<Vertex> GetManipulationResultSet(DBContext myDBContext, Exceptional<DBObjectStream> myDBObjectStreamExceptional, GraphDBType myGraphDBType, Dictionary<TypeAndAttributeDefinition, IObject> attributes = null, Dictionary<String, IObject> undefinedAttributes = null, Dictionary<ASpecialTypeAttribute, Object> specialTypeAttributes = null) { Vertex _Vertex = null; #region Return inserted attributes #region attributes if (!attributes.IsNullOrEmpty()) { _Vertex = new Vertex(attributes.ToDictionary(key => key.Key.Definition.Name, value => value.Value.GetReadoutValue())); } else { _Vertex = new Vertex(); } #endregion #region UndefinedAttributes if (!undefinedAttributes.IsNullOrEmpty()) { foreach (var undefAttr in undefinedAttributes) { _Vertex.AddAttribute(undefAttr.Key, undefAttr.Value.GetReadoutValue()); } } #endregion #region SpecialTypeAttributes if (!specialTypeAttributes.IsNullOrEmpty()) { foreach (var specAttr in specialTypeAttributes) { _Vertex.AddAttribute(specAttr.Key.Name, specAttr.Value); } } #endregion #region UUID if (!_Vertex.HasAttribute(SpecialTypeAttribute_UUID.AttributeName)) { var extractedValue = new SpecialTypeAttribute_UUID().ExtractValue(myDBObjectStreamExceptional.Value, myGraphDBType, myDBContext); if (extractedValue.Failed()) { return new Exceptional<Vertex>(extractedValue); } _Vertex.AddAttribute(SpecialTypeAttribute_UUID.AttributeName, extractedValue.Value.GetReadoutValue()); } #endregion #region REVISION if (!_Vertex.HasAttribute(SpecialTypeAttribute_REVISION.AttributeName)) // If it was updated by SpecialTypeAttributes we do not need to add them again { var extractedValue = new SpecialTypeAttribute_REVISION().ExtractValue(myDBObjectStreamExceptional.Value, myGraphDBType, myDBContext); if (extractedValue.Failed()) { return new Exceptional<Vertex>(extractedValue); } _Vertex.AddAttribute(SpecialTypeAttribute_REVISION.AttributeName, extractedValue.Value.GetReadoutValue()); } #endregion #endregion return new Exceptional<Vertex>(_Vertex); }
public void ItShouldBeTrue() { IDictionary<string, bool> blah = new Dictionary<string, bool>(); Assert.IsTrue(blah.IsNullOrEmpty()); }
/// <summary> /// Recursively traverse the schema's extends to verify that it or one of it's parents /// has at least one property /// </summary> /// <param name="properties">The schema's properties</param> /// <param name="extends">The schema's extends</param> /// <returns>True if one or more properties found in this schema or in it's ancestors. False otherwise</returns> private bool AncestorsHaveProperties(Dictionary<string, Schema> properties, string extends) { if (properties.IsNullOrEmpty() && string.IsNullOrEmpty(extends)) { return false; } if (!properties.IsNullOrEmpty()) { return true; } Debug.Assert(!string.IsNullOrEmpty(extends) && ServiceDefinition.Definitions.ContainsKey(extends)); return AncestorsHaveProperties(ServiceDefinition.Definitions[extends].Properties, ServiceDefinition.Definitions[extends].Extends); }