/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages ) { errorMessages = new List<string>(); if ( entity is Model.BinaryFile ) { var binaryFile = (Model.BinaryFile) entity; if ( binaryFile.BinaryFileType.Guid != new Guid( SystemGuid.BinaryFiletype.CHECKIN_LABEL ) ) { errorMessages.Add( "Binary file is not a check-in label" ); action.AddLogEntry( "Binary file is not a check-in label", true ); return false; } StringBuilder sb = new StringBuilder(); var contentString = binaryFile.ContentsToString(); foreach ( Match match in Regex.Matches( contentString, @"(?<=\^FD)[^\^FS]*(?=\^FS)" ) ) { sb.AppendFormat( "{0}^|", match.Value ); } binaryFile.LoadAttributes(); var attributeValue = new AttributeValue(); attributeValue.Value = sb.ToString(); binaryFile.AttributeValues["MergeCodes"] = attributeValue; binaryFile.SaveAttributeValues( rockContext ); } return true; }
public double getDetailProbability(AttributeValue ATTRIBUTE_VALUE = AttributeValue.IsTrue) { string value; switch (ATTRIBUTE_VALUE) { case AttributeValue.IsFalse: value = "False"; break; case AttributeValue.IsMissing: value = "Missing"; break; case AttributeValue.IsNull: value = "0"; break; case AttributeValue.IsTrue: default: value = "True"; break; } try { return Node.DecisionTreeNodeDistributions.First(nd => nd.ATTRIBUTE_VALUE == value).PROBABILITY; } catch (Exception) { return 0; } }
private bool SatisfiesCondition(AttributeValue value) { if (m_bSearchForKey) { if (m_bFullText) { if (!value.Key.Contains(m_sSearchKey)) return false; } else if (value.Key != m_sSearchKey) return false; } if (m_bSearchForValue) { if (value.DataType != AttributeDataType.String) return false; if (m_bFullText) { if (!(value.Data as string).Contains(m_sSearchValue)) return false; } else if ((value.Data as string) != m_sSearchValue) return false; } return true; }
public ResolveResult ResolveAttributeValue(XamlContext context, AttributeValue value, out string typeNameString) { typeNameString = value.IsString ? value.StringValue : GetTypeNameFromTypeExtension(value.ExtensionValue, context); return ResolveExpression(typeNameString, context); }
public void TestAddingExistingAttribute() { bool exceptionThrown; AttributeCollection attributes = new AttributeCollection(); AttributeValue newAttributeValue = new AttributeValue("Test Value"); // Add attribute and attribute value attributes.Add("Test", newAttributeValue); Assert.AreEqual<string>(newAttributeValue.Value, attributes["Test"].Value); AttributeValue existingAttributeValue = new AttributeValue("Test Value"); try { attributes.Add("Test", existingAttributeValue); exceptionThrown = false; } catch (ArgumentException) { exceptionThrown = true; } Assert.IsTrue(exceptionThrown); }
public void AddEntry(AttributeValue[] Entry) { for (int i = 0; i < Entry.Length;++i) { _Values[i].Add(Entry[i]); } }
/// <summary> /// Job that updates the JobPulse setting with the current date/time. /// This will allow us to notify an admin if the jobs stop running. /// /// Called by the <see cref="IScheduler" /> when a /// <see cref="ITrigger" /> fires that is associated with /// the <see cref="IJob" />. /// </summary> public virtual void Execute(IJobExecutionContext context) { using ( new Rock.Data.UnitOfWorkScope() ) { AttributeService attribService = new AttributeService(); AttributeValueService attributeValueService = new AttributeValueService(); Rock.Core.Attribute jobPulseAttrib = attribService.GetGlobalAttribute( "JobPulse" ); Rock.Core.AttributeValue jobPulseAttribValue = jobPulseAttrib.AttributeValues.FirstOrDefault(); // create attribute value if one does not exist if ( jobPulseAttribValue == null ) { jobPulseAttribValue = new AttributeValue(); jobPulseAttribValue.AttributeId = jobPulseAttrib.Id; attributeValueService.Add( jobPulseAttribValue, null ); } // store todays date and time jobPulseAttribValue.Value = DateTime.Now.ToString(); // save attribute attributeValueService.Save( jobPulseAttribValue, null ); } }
/// <summary> /// Saves the specified item. /// </summary> /// <param name="item">The item.</param> /// <param name="personId">The person identifier.</param> /// <returns></returns> public override bool Save( AttributeValue item, int? personId ) { if ( item.Attribute != null ) { // ensure that the BinaryFile.IsTemporary flag is set to false for any BinaryFiles that are associated with this record var fieldTypeImage = Rock.Web.Cache.FieldTypeCache.Read( Rock.SystemGuid.FieldType.IMAGE.AsGuid() ); var fieldTypeBinaryFile = Rock.Web.Cache.FieldTypeCache.Read( Rock.SystemGuid.FieldType.BINARY_FILE.AsGuid() ); if ( item.Attribute.FieldTypeId == fieldTypeImage.Id || item.Attribute.FieldTypeId == fieldTypeBinaryFile.Id ) { int? binaryFileId = item.Value.AsInteger(); if ( binaryFileId.HasValue ) { BinaryFileService binaryFileService = new BinaryFileService( this.RockContext ); var binaryFile = binaryFileService.Get( binaryFileId.Value ); if ( binaryFile != null && binaryFile.IsTemporary ) { binaryFile.IsTemporary = false; } } } } return base.Save( item, personId ); }
public void TestCreateAttributeValueWithNullDisplayValue() { AttributeValue attributeValue = new AttributeValue("Value", null); Assert.AreEqual<string>("Value", attributeValue.Value); Assert.AreEqual<string>("Value", attributeValue.DisplayValue); }
public void TestChangingAttributeValueProperties() { AttributeValue attribute = new AttributeValue("Value"); object oldValue = null; object newValue = null; string propertyChanged = string.Empty; attribute.PropertyChanged += (object sender, PropertyChangedEventArgs<object> e) => { propertyChanged = e.PropertyName; oldValue = e.OldValue; newValue = e.NewValue; }; // Change Value EnqueueCallback(() => attribute.Value = "New Value"); EnqueueConditional(() => propertyChanged != string.Empty); EnqueueCallback(() => Assert.AreEqual<string>("Value", propertyChanged)); EnqueueCallback(() => Assert.AreEqual<string>("Value", (string)oldValue)); EnqueueCallback(() => Assert.AreEqual<string>("New Value", (string)newValue)); EnqueueCallback(() => propertyChanged = string.Empty); // Change DisplayValue EnqueueCallback(() => attribute.DisplayValue = "New Display Value"); EnqueueConditional(() => propertyChanged != string.Empty); EnqueueCallback(() => Assert.AreEqual<string>("DisplayValue", propertyChanged)); EnqueueCallback(() => Assert.AreEqual<string>(null, (string)oldValue)); EnqueueCallback(() => Assert.AreEqual<string>("New Display Value", (string)newValue)); EnqueueCallback(() => propertyChanged = string.Empty); EnqueueTestComplete(); }
public AttributeValue MakeDecision(AttributeValue[] Data, bool Print = false) { Dictionary<AttributeValue, int> P = new Dictionary<AttributeValue, int>(); foreach (DecisionTree D in _Trees) { AttributeValue V = D.MakeDecision(Data, Print); bool Found = false; foreach (AttributeValue Key in P.Keys.ToList()) { if (Key.CompareTo(V) == 0) { P[Key]++; Found = true; } } if (!Found) { P.Add(V, 1); } } AttributeValue M = null; int N = 0; foreach(KeyValuePair<AttributeValue, int> p in P) { if (p.Value > N) { N = p.Value; M = p.Key; } } return M; }
public Discriminator(int Index, AttributeValue Split, bool Equality) { _Index = Index; _Split = Split; _Equality = Equality; if (Split == null) _Function = delegate(AttributeValue[] E) { return E[_Index]; }; else _Function = delegate(AttributeValue[] E) { return new BooleanValue(E[_Index].CompareTo(Split) == (Equality ? 0: -1));}; }
public StringEqualIgnoreCaseMatch( AttributeDesignator designator, AttributeValue value) : base("urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case", designator, value) { }
public AttributeEventArgs(Attribute _attribute, AttributeValue _newValue, AttributeValue _oldValue, NotifyCollectionChangedAction _action) : base() { this.attribute = _attribute; this.newValue = _newValue; this.oldValue = _oldValue; this.action = _action; }
private void assertBooleanValue(AttributeValue attr, bool value) { Assert.IsInstanceOfType(attr.getValue(), typeof(PrimitiveObjectBlock)); PrimitiveObjectBlock pob = (PrimitiveObjectBlock)attr.getValue(); Assert.IsInstanceOfType(pob.getSimpleValue(), typeof(BooleanValue)); BooleanValue actual = (BooleanValue)pob.getSimpleValue(); java.lang.Boolean expected = new java.lang.Boolean(value); Assert.AreEqual(actual.getValue(), expected); }
public void TestAddingAttributeWithValue() { AttributeCollection attributes = new AttributeCollection(); AttributeValue comparisonAttributeValue = new AttributeValue("Value"); attributes.Add("Name", comparisonAttributeValue); Assert.AreEqual<string>(comparisonAttributeValue.Value, attributes["Name"].Value); }
private void assertCharacterValue(AttributeValue attr, char value) { Assert.IsInstanceOfType(attr.getValue(), typeof(PrimitiveObjectBlock)); PrimitiveObjectBlock pob = (PrimitiveObjectBlock)attr.getValue(); Assert.IsInstanceOfType(pob.getSimpleValue(), typeof(CharacterValue)); CharacterValue actual = (CharacterValue)pob.getSimpleValue(); Character expected = new Character(value); Assert.AreEqual(actual.getValue(), expected); }
private void assertDateValue(AttributeValue attr, string value) { Assert.IsInstanceOfType(attr.getValue(), typeof(PrimitiveObjectBlock)); PrimitiveObjectBlock pob = (PrimitiveObjectBlock)attr.getValue(); Assert.IsInstanceOfType(pob.getSimpleValue(), typeof(DateValue)); DateValue actual = (DateValue)pob.getSimpleValue(); DvDate expected = new DvDate(value); Assert.AreEqual(actual.getValue(), expected); }
public void TestAttributeAccessor() { GlobalAttributeCollection globalAttributeCollection = GlobalAttributeCollection.GetInstance("SnagL"); Attribute attribute = new Attribute("SnagL"); AttributeValue original = new AttributeValue("SnagL"); globalAttributeCollection.Clear(); globalAttributeCollection.Add(attribute, original); Assert.IsTrue(globalAttributeCollection[attribute].Contains("SnagL")); }
public void VerifyPlay(Card DownCard, Card Played, bool Valid) { AttributeValue[] Entry = new AttributeValue[5]; Entry[0] = new IntegerValue(DownCard.Number); Entry[1] = new IntegerValue(DownCard.Suit); Entry[2] = new IntegerValue(Played.Number); Entry[3] = new IntegerValue(Played.Suit); Entry[4] = new BooleanValue(Valid); if (_Forest == null) _Forest = new Forest(1, 1, delegate(int i) { DataSet D = new DataSet(5); D.AddEntry(Entry); return D; }, 4); else _Forest.AddEntry(Entry); }
public bool ValidatePlay(Card DownCard, Card Played, Player played) { AttributeValue[] Entry = new AttributeValue[5]; Entry[0] = new IntegerValue(DownCard.Number); Entry[1] = new IntegerValue(DownCard.Suit); Entry[2] = new IntegerValue(Played.Number); Entry[3] = new IntegerValue(Played.Suit); Entry[4] = new BooleanValue(false); if (_Forest == null) return true; else return Convert.ToBoolean(_Forest.MakeDecision(Entry).ToString()); }
public void Analyze(AttributeValue root) { Clear(); TreeNode t = m_trvTables.Nodes.Add("GameData"); t.Tag = root; foreach (var rbfData in (root.Data as AttributeTable)) { AddToTree(rbfData, t); } m_trvTables.Sort(); t.Expand(); }
protected void BtnAddValue_Click(object sender, EventArgs e) { LblErr.Text = ""; LblOk.Text = ""; // conrollo che non tutti i valori siano vuoti bool allEmpty = true; foreach (KeyValuePair<string, string> item in Config.CultureList) { TextBox t1 = new TextBox(); t1 = (TextBox)PanelTitle.FindControl("TxtTitle" + item.Value); if (!string.IsNullOrEmpty(t1.Text)) { allEmpty = false; break; } } if (allEmpty) { return; } try { var o1 = new AttributeValue(); if (string.IsNullOrEmpty(base.CurrentKey)) { values2obj(o1); o1 = new AttributeValuesManager().Insert(o1); } else { o1 = new AttributeValuesManager().GetByKey(Convert.ToInt32(base.CurrentKey)); //precarico i campi esistenti e nn gestiti dal form o1.ValueTranslations.Clear(); values2obj(o1); new AttributeValuesManager().Update(o1); } clearValues(); Grid1.DataBind(); GridValues.DataBind(); LblOk.Text = RenderSuccess(Utility.GetLabel("RECORD_SAVED_MSG")); } catch (Exception e1) { LblErr.Text = RenderError(Utility.GetLabel("RECORD_ERR_MSG") + "<br />" + e1.ToString()); } finally { } }
static AttributeValue[] GenerateEntry() { int DownNumber = Random.Next(1, 14); int DownSuit = Random.Next(1, 5); AttributeValue[] E = new AttributeValue[5]; E[0] = new IntegerValue(DownNumber); E[1] = new IntegerValue(DownSuit); int CardNumber = Random.Next(1, 14); int CardSuit = Random.Next(1, 5); E[2] = new IntegerValue(CardNumber); E[3] = new IntegerValue(CardSuit); E[4] = new BooleanValue(ValidPlay(DownNumber, DownSuit, CardNumber, CardSuit)); return E; }
public static List<AttributeValue> GetAttributesForType(TypeID typeId) { var query = @" SELECT ta.attributeID, valueInt, valueFloat, attributeName, at.description, at.displayName, at.categoryID, u.unitID, u.unitName, u.displayName, u.description FROM dgmTypeAttributes AS ta INNER JOIN dgmAttributeTypes AS at ON ta.attributeID = at.attributeID INNER JOIN eveUnits AS u ON at.unitID = u.unitID WHERE ta.typeID = "+typeId.ToInt()+@" LIMIT 100 "; using (var cnn = new SQLiteConnection(DefaultDatabase.dbConnection)) { cnn.Open(); var reader = DefaultDatabase.RunSQLTableQuery(query, cnn); var results = new List<AttributeValue>(); while (reader.Read()) { // todo: referencing columns by name doesn't seem to support names like at.description. There must be a better workaround for that var unitDesc = reader[10]; var unitDispName = reader[9]; var unit = Unit.Get(new UnitID((byte)reader[7]), (string)reader[8], unitDispName is DBNull ? "" : (string)unitDispName, unitDesc is DBNull ? "" : (string)unitDesc); var attrDispName = reader[5]; var attribute = new Attribute(new AttributeID((short)reader[0]), (string)reader[3], attrDispName is DBNull ? "" : (string)attrDispName, (string)reader[4], unit, AttributeCategory.Get((byte)reader[6])); AttributeValue value; if (reader["valueFloat"] is DBNull) { value = new AttributeValue(attribute, (int)reader[1]); } else { value = new AttributeValue(attribute, (float)(double)reader[2]); } results.Add(value); } return results; } }
public void ScanState() { Collection devCollection = (Collection)Application.Current.Properties["MonitorCollection"]; while (true) { using (Bus.DataBusServiceClient client = new Bus.DataBusServiceClient()) { DeviceSign[] devArr = devCollection.GetDeviceIDList(); DeviceDynamic device; foreach (var item in devArr) { device = devCollection.GetDevice(item.dev_id,item.mon_id); string [] statelist=device.GetStateName(); DynamicState state; Bus.AttributeValue attVal; foreach(var stateitem in statelist) { Bus.DeviceState busquerystate = new Bus.DeviceState(); busquerystate.AgentID = device.Monitor_ID; busquerystate.DevType = device.Dev_Type; busquerystate.DevID = device.Device_ID; busquerystate.Name = stateitem; attVal = client.QueryStateTest(busquerystate); if (attVal != null) { AttributeValue stateVal = new AttributeValue(attVal.Type, attVal.Value); state = new DynamicState(stateitem, device.Device_ID,device.Monitor_ID, device.Dev_Type); state.StateValue = stateVal; device.ChangeStateValue(state); } }/////单个设备所以状态扫描 }///所有设备集合扫描 } ///服务端口开 Thread.Sleep(scantime); }////线程循环 }
/// <summary> /// Saves the communication. /// </summary> /// <param name="newNumberList">The new number list.</param> /// <param name="updatedPersonList">The updated person list.</param> private static void SaveCommunication( List<PhoneNumber> newNumberList, Dictionary<int, Person> updatedPersonList ) { var rockContext = new RockContext(); rockContext.WrapTransaction( () => { rockContext.Configuration.AutoDetectChangesEnabled = false; if ( newNumberList.Any() ) { rockContext.PhoneNumbers.AddRange( newNumberList ); } if ( updatedPersonList.Any() ) { foreach ( var person in updatedPersonList.Values.Where( p => p.Attributes.Any() ) ) { // don't call LoadAttributes, it only rewrites existing cache objects // person.LoadAttributes( rockContext ); foreach ( var attributeCache in person.Attributes.Select( a => a.Value ) ) { var existingValue = rockContext.AttributeValues.FirstOrDefault( v => v.Attribute.Key == attributeCache.Key && v.EntityId == person.Id ); var newAttributeValue = person.AttributeValues[attributeCache.Key]; // set the new value and add it to the database if ( existingValue == null ) { existingValue = new AttributeValue(); existingValue.AttributeId = newAttributeValue.AttributeId; existingValue.EntityId = person.Id; existingValue.Value = newAttributeValue.Value; rockContext.AttributeValues.Add( existingValue ); } else { existingValue.Value = newAttributeValue.Value; rockContext.Entry( existingValue ).State = EntityState.Modified; } } } } rockContext.ChangeTracker.DetectChanges(); rockContext.SaveChanges( DisableAuditing ); } ); }
public void TestAddMethodThrowsExceptionIfNullAttribute() { bool exceptionCaught = false; GlobalAttributeCollection globalAttributeCollection = GlobalAttributeCollection.GetInstance("SnagL"); AttributeValue value = new AttributeValue("SnagL"); try { globalAttributeCollection.Add(null, value); } catch (System.ArgumentNullException) { exceptionCaught = true; } Assert.IsTrue(exceptionCaught); }
public void TestAddingWithNullAttribute() { bool exceptionThrown; AttributeCollection attributes = new AttributeCollection(); AttributeValue comparisonAttributeValue = new AttributeValue("Value"); try { attributes.Add(null, comparisonAttributeValue); exceptionThrown = false; } catch (ArgumentNullException) { exceptionThrown = true; } Assert.IsTrue(exceptionThrown); }
public AttributeValue MakeDecision(AttributeValue[] Data, bool Print = false) { if (_Children == null) { if (Print) Console.WriteLine(_Value); return _Value; } else { AttributeValue V = _Check.Function.Invoke(Data); if (Print) Console.WriteLine("{0} {1}", V, _Check); foreach (KeyValuePair<AttributeValue, DecisionTree> P in _Children) { if (V.CompareTo(P.Key) <= 0) return P.Value.MakeDecision(Data, Print); } return _Children[_Children.Count - 1].Value.MakeDecision(Data, Print); } }
public override int Get(AttributeValue value) => int.Parse(value.N);
public void Startup() { _uicConfiguartion = uicConfiguartionProvider.GetUicConfiguartion(); string serialId = "extract serial Id of the embedded device as asset identifier for the cloud applicaiton"; foreach (EmbeddedDriverModule edm in _uicConfiguartion.EmbeddedDriverModulesToLoad) { edm.Initialize(); } if (_uicConfiguartion.IsEdmSnychronizationEnabled) { foreach (EmbeddedDriverModule edm in _uicConfiguartion.EmbeddedDriverModulesToLoad) { EdmCapability edmCapability = edm.GetCapability(); // Synchronize edm with edm and project cloud } } UicProject project = null; if (_uicConfiguartion.IsRemoteProjectLoadingEnabled) { //Url EdmSnychronizationUrl { get; } //Url RemoteProjectConfigurationUrl(); //var projectConfigurationUrl = _uicConfiguartion.RemoteProjectConfigurationUrl(); //project = LoadProjectFromRemote(projectConfigurationUrl); } else { var serializedProjectFilepath = _uicConfiguartion.AbsoluteProjectConfigurationFilePath; project = LoadProjectFromFile(serializedProjectFilepath); } _communicationAgent.Synchronize(serialId, project); _communicationAgent.Connect(CloudAgentCommandHandler); // read and publish foreach (var attribtueDefinition in project.Attributes) { EmbeddedDriverModule edm = GetEdmFor(attribtueDefinition); AttributeValue attibutValue = edm.GetValueFor(attribtueDefinition); _communicationAgent.Push(attibutValue); //Set Asynchronous EDM Calbbacks if necessary edm.SetAttributeCallback(attribtueDefinition, attributeValue => _communicationAgent.Push(attributeValue)); } foreach (ProjectDatapointTask datapointTask in project.DatapointTasks) { EmbeddedDriverModule edm = GetEdmFor(datapointTask.Definition); //start Monitoring the DatapointTasks from the project StartDatapointMonitoring(datapointTask.Definition, datapointTask.PollIntervall, datapointTask.ReportingCondition, edm); //Set Asynchronous EDM Calbbacks if necessary edm.SetDatapointCallback(datapointTask, datapointValue => _communicationAgent.Push(datapointValue)); } }
protected virtual IEnumerator <KeyValuePair <AttributeValue, long> > EnumerateFrom(AttributeValue start) { try { return(MergeEnumerators(_tree.EnumerateFrom(start).GetEnumerator(), _transitionTree.EnumerateFrom(start).GetEnumerator())); } catch (Exception ex) { LoggerManager.Instance.IndexLogger.Error("BPlusIndex", "Index Enumeration Failure: " + ex.ToString()); throw; } }
public virtual IEnumerator <KeyValuePair <AttributeValue, long> > GetEnumeratorFrom(AttributeValue start) { if (order == SortOrder.ASC) { return(EnumerateFrom(start)); } return(EnumerateTo(start)); }
public void BatchSamples() { EnsureTables(); { #region BatchGet Sample 1 // Define attributes to get and keys to retrieve List <string> attributesToGet = new List <string> { "Author", "Title", "Year" }; List <Dictionary <string, AttributeValue> > sampleTableKeys = new List <Dictionary <string, AttributeValue> > { new Dictionary <string, AttributeValue> { { "Author", new AttributeValue { S = "Mark Twain" } }, { "Title", new AttributeValue { S = "The Adventures of Tom Sawyer" } } }, new Dictionary <string, AttributeValue> { { "Author", new AttributeValue { S = "Mark Twain" } }, { "Title", new AttributeValue { S = "Adventures of Huckleberry Finn" } } } }; // Construct get-request for first table KeysAndAttributes sampleTableItems = new KeysAndAttributes { AttributesToGet = attributesToGet, Keys = sampleTableKeys }; #endregion #region BatchGet Sample 2 // Define keys to retrieve List <Dictionary <string, AttributeValue> > authorsTableKeys = new List <Dictionary <string, AttributeValue> > { new Dictionary <string, AttributeValue> { { "Author", new AttributeValue { S = "Mark Twain" } }, }, new Dictionary <string, AttributeValue> { { "Author", new AttributeValue { S = "Booker Taliaferro Washington" } }, } }; // Construct get-request for second table // Skip setting AttributesToGet property to retrieve all attributes KeysAndAttributes authorsTableItems = new KeysAndAttributes { Keys = authorsTableKeys, }; #endregion #region BatchGet Sample 3 // Create a client AmazonDynamoDBClient client = new AmazonDynamoDBClient(); // Construct table-keys mapping Dictionary <string, KeysAndAttributes> requestItems = new Dictionary <string, KeysAndAttributes>(); requestItems["SampleTable"] = sampleTableItems; requestItems["AuthorsTable"] = authorsTableItems; // Construct request BatchGetItemRequest request = new BatchGetItemRequest { RequestItems = requestItems }; BatchGetItemResult result; do { // Issue request and retrieve items result = client.BatchGetItem(request); // Iterate through responses Dictionary <string, List <Dictionary <string, AttributeValue> > > responses = result.Responses; foreach (string tableName in responses.Keys) { // Get items for each table List <Dictionary <string, AttributeValue> > tableItems = responses[tableName]; // View items foreach (Dictionary <string, AttributeValue> item in tableItems) { Console.WriteLine("Item:"); foreach (var keyValuePair in item) { Console.WriteLine("{0} : S={1}, N={2}, SS=[{3}], NS=[{4}]", keyValuePair.Key, keyValuePair.Value.S, keyValuePair.Value.N, string.Join(", ", keyValuePair.Value.SS ?? new List <string>()), string.Join(", ", keyValuePair.Value.NS ?? new List <string>())); } } } // Some items may not have been retrieved! // Set RequestItems to the result's UnprocessedKeys and reissue request request.RequestItems = result.UnprocessedKeys; } while (result.UnprocessedKeys.Count > 0); #endregion } { #region BatchWrite Sample 1 // Create items to put into first table Dictionary <string, AttributeValue> item1 = new Dictionary <string, AttributeValue>(); item1["Author"] = new AttributeValue { S = "Mark Twain" }; item1["Title"] = new AttributeValue { S = "A Connecticut Yankee in King Arthur's Court" }; item1["Pages"] = new AttributeValue { N = "575" }; Dictionary <string, AttributeValue> item2 = new Dictionary <string, AttributeValue>(); item2["Author"] = new AttributeValue { S = "Booker Taliaferro Washington" }; item2["Title"] = new AttributeValue { S = "My Larger Education" }; item2["Pages"] = new AttributeValue { N = "313" }; item2["Year"] = new AttributeValue { N = "1911" }; // Create key for item to delete from first table // Hash-key of the target item is string value "Mark Twain" // Range-key of the target item is string value "Tom Sawyer, Detective" Dictionary <string, AttributeValue> keyToDelete1 = new Dictionary <string, AttributeValue> { { "Author", new AttributeValue { S = "Mark Twain" } }, { "Title", new AttributeValue { S = "Tom Sawyer, Detective" } } }; // Construct write-request for first table List <WriteRequest> sampleTableItems = new List <WriteRequest>(); sampleTableItems.Add(new WriteRequest { PutRequest = new PutRequest { Item = item1 } }); sampleTableItems.Add(new WriteRequest { PutRequest = new PutRequest { Item = item2 } }); sampleTableItems.Add(new WriteRequest { DeleteRequest = new DeleteRequest { Key = keyToDelete1 } }); #endregion #region BatchWrite Sample 2 // Create key for item to delete from second table // Hash-key of the target item is string value "Francis Scott Key Fitzgerald" Dictionary <string, AttributeValue> keyToDelete2 = new Dictionary <string, AttributeValue> { { "Author", new AttributeValue { S = "Francis Scott Key Fitzgerald" } }, }; // Construct write-request for first table List <WriteRequest> authorsTableItems = new List <WriteRequest>(); authorsTableItems.Add(new WriteRequest { DeleteRequest = new DeleteRequest { Key = keyToDelete2 } }); #endregion #region BatchWrite Sample 3 // Create a client AmazonDynamoDBClient client = new AmazonDynamoDBClient(); // Construct table-keys mapping Dictionary <string, List <WriteRequest> > requestItems = new Dictionary <string, List <WriteRequest> >(); requestItems["SampleTable"] = sampleTableItems; requestItems["AuthorsTable"] = authorsTableItems; BatchWriteItemRequest request = new BatchWriteItemRequest { RequestItems = requestItems }; BatchWriteItemResult result; do { // Issue request and retrieve items result = client.BatchWriteItem(request); // Some items may not have been processed! // Set RequestItems to the result's UnprocessedItems and reissue request request.RequestItems = result.UnprocessedItems; } while (result.UnprocessedItems.Count > 0); #endregion } }
/// <summary> /// Writes an attribute to the specified <see cref="TextWriter"/>. /// </summary> /// <param name="writer">The writer.</param> /// <param name="name">The name of the attribute to be written.</param> /// <param name="prefix"></param> /// <param name="suffix"></param> /// <param name="values"></param> public virtual void WriteAttributeTo(TextWriter writer, string name, PositionTagged <string> prefix, PositionTagged <string> suffix, params AttributeValue[] values) { bool first = true; bool wroteSomething = false; if (values.Length == 0) { // Explicitly empty attribute, so write the prefix and suffix WritePositionTaggedLiteral(writer, prefix); WritePositionTaggedLiteral(writer, suffix); } else { for (int i = 0; i < values.Length; i++) { AttributeValue attrVal = values[i]; PositionTagged <object> val = attrVal.Value; bool?boolVal = null; if (val.Value is bool) { boolVal = (bool)val.Value; } if (val.Value != null && (boolVal == null || boolVal.Value)) { string valStr = val.Value as string; string valToString = valStr; if (valStr == null) { valToString = val.Value.ToString(); } if (boolVal != null) { Debug.Assert(boolVal.Value); valToString = name; } if (first) { WritePositionTaggedLiteral(writer, prefix); first = false; } else { WritePositionTaggedLiteral(writer, attrVal.Prefix); } if (attrVal.Literal) { WriteLiteralTo(writer, valToString); } else { if (val.Value is IEncodedString && boolVal == null) { WriteTo(writer, val.Value); // Write value } else { WriteTo(writer, valToString); // Write value } } wroteSomething = true; } } if (wroteSomething) { WritePositionTaggedLiteral(writer, suffix); } } }
// TODO: ConvertToCommon handling bad values private object ConvertToCommon(AttributeValue argument, Func <AttributeValue, object> selector) { return(!argument.IsBadValue ? selector(argument) : "???"); }
public void Push(AttributeValue value) { Push(new [] { value }); }
internal static ISpanData ProfiledCommandToSpanData(ISpanContext context, string name, ISpanId parentSpanId, IProfiledCommand command) { var hasRemoteParent = false; // use https://github.com/opentracing/specification/blob/master/semantic_conventions.md for now // Timing example: // command.CommandCreated; //2019-01-10 22:18:28Z // command.CreationToEnqueued; // 00:00:32.4571995 // command.EnqueuedToSending; // 00:00:00.0352838 // command.SentToResponse; // 00:00:00.0060586 // command.ResponseToCompletion; // 00:00:00.0002601 // Total: // command.ElapsedTime; // 00:00:32.4988020 // TODO: make timestamp with the better precision Timestamp startTimestamp = Timestamp.FromMillis(new DateTimeOffset(command.CommandCreated).ToUnixTimeMilliseconds()); var timestamp = new DateTimeOffset(command.CommandCreated).Add(command.CreationToEnqueued); var annotations = TimedEvents <IAnnotation> .Create( new List <ITimedEvent <IAnnotation> >() { TimedEvent <IAnnotation> .Create(Timestamp.FromMillis(timestamp.ToUnixTimeMilliseconds()), Annotation.FromDescription("Enqueued")), TimedEvent <IAnnotation> .Create(Timestamp.FromMillis((timestamp = timestamp.Add(command.EnqueuedToSending)).ToUnixTimeMilliseconds()), Annotation.FromDescription("Sent")), TimedEvent <IAnnotation> .Create(Timestamp.FromMillis((timestamp = timestamp.Add(command.SentToResponse)).ToUnixTimeMilliseconds()), Annotation.FromDescription("ResponseRecieved")), }, droppedEventsCount : 0); Timestamp endTimestamp = Timestamp.FromMillis(new DateTimeOffset(command.CommandCreated.Add(command.ElapsedTime)).ToUnixTimeMilliseconds()); // TODO: deal with the re-transmission // command.RetransmissionOf; // command.RetransmissionReason; var attributesMap = new Dictionary <string, IAttributeValue>() { // TODO: pre-allocate constant attribute and reuse { "db.type", AttributeValue.StringAttributeValue("redis") }, // Example: "redis.flags": None, DemandMaster { "redis.flags", AttributeValue.StringAttributeValue(command.Flags.ToString()) }, }; if (command.Command != null) { // Example: "db.statement": SET; attributesMap.Add("db.statement", AttributeValue.StringAttributeValue(command.Command)); } if (command.EndPoint != null) { // Example: "db.instance": Unspecified/localhost:6379[0] attributesMap.Add("db.instance", AttributeValue.StringAttributeValue(command.EndPoint.ToString() + "[" + command.Db + "]")); } var attributes = Attributes.Create(attributesMap, 0); ITimedEvents <IMessageEvent> messageOrNetworkEvents = null; ILinks links = null; int? childSpanCount = 0; // TODO: this is strange that IProfiledCommand doesn't give the result Status status = Status.Ok; SpanKind kind = SpanKind.Client; return(SpanData.Create(context, parentSpanId, hasRemoteParent, name, startTimestamp, attributes, annotations, messageOrNetworkEvents, links, childSpanCount, status, kind, endTimestamp)); }
private IEnumerator <KeyValuePair <AttributeValue, long> > GetValueEnumerator(AttributeValue value) { IDictionary <long, byte> outRowIds, rowIds; if (_tree.TryGetValue(value, out outRowIds)) { rowIds = new HashVector <long, byte>(outRowIds); } else { rowIds = new HashVector <long, byte>(); } IDictionary <IndexOp <long>, byte> ops; if (_transitionTree.TryGetValue(value, out ops)) { foreach (var indexOp in ops.Keys) { indexOp.MergeWith(rowIds); } } foreach (var rowId in rowIds) { yield return(new KeyValuePair <AttributeValue, long>(value, rowId.Key)); } }
private static bool CompareAttributeValue(AttributeValue x, AttributeValue y) { if (AreBothNull(x, y)) { return(true); } if (IsEitherNull(x, y)) { return(false); } // Compare scalar properties of primary attributes. Primary attributes can only be scalar types. // http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html if (IsEitherNull(x.S, y.S) || IsEitherNull(x.N, y.N) || IsEitherNull(x.B, y.B)) { return(false); } if (!AreBothNull(x.S, y.S)) { if (!x.S.Equals(y.S, StringComparison.OrdinalIgnoreCase)) { return(false); } } if (!AreBothNull(x.N, y.N)) { if (!x.N.Equals(y.N, StringComparison.OrdinalIgnoreCase)) { return(false); } } if (!AreBothNull(x.B, y.B)) { if (x.B.Length != y.B.Length) { return(false); } long xPos = x.B.Position, yPos = y.B.Position; x.B.Position = 0; y.B.Position = 0; int valueX = 0, valueY = 0; do { if (valueX != valueY) { return(false); } valueX = x.B.ReadByte(); valueY = y.B.ReadByte(); } while (valueX != -1 && valueY != -1); x.B.Position = xPos; y.B.Position = yPos; } return(true); }
public AttributeEventArgs(Attribute _attribute, AttributeValue _newValue, NotifyCollectionChangedAction _action) : this(_attribute, _newValue, null, _action) { }
public IDictionary <long, byte> this[AttributeValue key] { get { return(_tree[key]); } }
public virtual AttributeValue Transform(AttributeValue source) { return(source); }
public void GoSpanData_EndedSpan() { ISpan span = Span.StartSpan( spanContext, recordSpanOptions, SPAN_NAME, parentSpanId, false, TraceParams.DEFAULT, startEndHandler, timestampConverter, testClock); span.PutAttribute( "MySingleStringAttributeKey", AttributeValue.StringAttributeValue("MySingleStringAttributeValue")); span.PutAttributes(attributes); testClock.AdvanceTime(Duration.Create(0, 100)); span.AddAnnotation(Annotation.FromDescription(ANNOTATION_DESCRIPTION)); testClock.AdvanceTime(Duration.Create(0, 100)); span.AddAnnotation(ANNOTATION_DESCRIPTION, attributes); testClock.AdvanceTime(Duration.Create(0, 100)); IMessageEvent networkEvent = MessageEvent.Builder(MessageEventType.RECEIVED, 1).SetUncompressedMessageSize(3).Build(); span.AddMessageEvent(networkEvent); ILink link = Link.FromSpanContext(spanContext, LinkType.CHILD_LINKED_SPAN); span.AddLink(link); testClock.AdvanceTime(Duration.Create(0, 100)); span.End(EndSpanOptions.Builder().SetStatus(Status.CANCELLED).Build()); ISpanData spanData = ((Span)span).ToSpanData(); Assert.Equal(spanContext, spanData.Context); Assert.Equal(SPAN_NAME, spanData.Name); Assert.Equal(parentSpanId, spanData.ParentSpanId); Assert.False(spanData.HasRemoteParent); Assert.Equal(0, spanData.Attributes.DroppedAttributesCount); Assert.Equal(expectedAttributes, spanData.Attributes.AttributeMap); Assert.Equal(0, spanData.Annotations.DroppedEventsCount); Assert.Equal(2, spanData.Annotations.Events.Count); Assert.Equal(timestamp.AddNanos(100), spanData.Annotations.Events[0].Timestamp); Assert.Equal(Annotation.FromDescription(ANNOTATION_DESCRIPTION), spanData.Annotations.Events[0].Event); Assert.Equal(timestamp.AddNanos(200), spanData.Annotations.Events[1].Timestamp); Assert.Equal(Annotation.FromDescriptionAndAttributes(ANNOTATION_DESCRIPTION, attributes), spanData.Annotations.Events[1].Event); Assert.Equal(0, spanData.MessageEvents.DroppedEventsCount); Assert.Equal(1, spanData.MessageEvents.Events.Count); Assert.Equal(timestamp.AddNanos(300), spanData.MessageEvents.Events[0].Timestamp); Assert.Equal(networkEvent, spanData.MessageEvents.Events[0].Event); Assert.Equal(0, spanData.Links.DroppedLinksCount); Assert.Equal(1, spanData.Links.Links.Count); Assert.Equal(link, spanData.Links.Links[0]); Assert.Equal(timestamp, spanData.StartTimestamp); Assert.Equal(Status.CANCELLED, spanData.Status); Assert.Equal(timestamp.AddNanos(400), spanData.EndTimestamp); var startEndMock = Mock.Get <IStartEndHandler>(startEndHandler); var spanBase = span as SpanBase; startEndMock.Verify(s => s.OnStart(spanBase), Times.Once); startEndMock.Verify(s => s.OnEnd(spanBase), Times.Once); }
protected virtual void OnApplyMultiply(AttributeValue attribute) { attribute.Value *= Amount.Value / 100f; }
public void SearchSamples() { RemoveTables(); CreateLSITable(); TableUtils.WaitUntilTableActive("SampleTable", TestClient); { // Create items to put into first table Dictionary <string, AttributeValue> item1 = new Dictionary <string, AttributeValue>(); item1["Author"] = new AttributeValue { S = "Mark Twain" }; item1["Title"] = new AttributeValue { S = "A Connecticut Yankee in King Arthur's Court" }; item1["Pages"] = new AttributeValue { N = "575" }; Dictionary <string, AttributeValue> item2 = new Dictionary <string, AttributeValue>(); item2["Author"] = new AttributeValue { S = "Booker Taliaferro Washington" }; item2["Title"] = new AttributeValue { S = "My Larger Education" }; item2["Pages"] = new AttributeValue { N = "313" }; item2["Year"] = new AttributeValue { N = "1911" }; // Construct write-request for first table List <WriteRequest> sampleTableItems = new List <WriteRequest>(); sampleTableItems.Add(new WriteRequest { PutRequest = new PutRequest { Item = item1 } }); sampleTableItems.Add(new WriteRequest { PutRequest = new PutRequest { Item = item2 } }); AmazonDynamoDBClient client = new AmazonDynamoDBClient(); client.BatchWriteItem(new BatchWriteItemRequest { RequestItems = new Dictionary <string, List <WriteRequest> > { { "SampleTable", sampleTableItems } } }); PutSample(); } { #region Query Sample // Create a client AmazonDynamoDBClient client = new AmazonDynamoDBClient(); // Define item hash-key to be string value "Mark Twain" AttributeValue hashKey = new AttributeValue { S = "Mark Twain" }; // Define query condition to search for range-keys that begin with the string "The Adventures" Condition condition = new Condition { ComparisonOperator = "BEGINS_WITH", AttributeValueList = new List <AttributeValue> { new AttributeValue { S = "The Adventures" } } }; // Create the key conditions from hashKey and condition Dictionary <string, Condition> keyConditions = new Dictionary <string, Condition> { // Hash key condition. ComparisonOperator must be "EQ". { "Author", new Condition { ComparisonOperator = "EQ", AttributeValueList = new List <AttributeValue> { hashKey } } }, // Range key condition { "Title", condition } }; // Define marker variable Dictionary <string, AttributeValue> startKey = null; do { // Create Query request QueryRequest request = new QueryRequest { TableName = "SampleTable", ExclusiveStartKey = startKey, KeyConditions = keyConditions }; // Issue request var result = client.Query(request); // View all returned items List <Dictionary <string, AttributeValue> > items = result.Items; foreach (Dictionary <string, AttributeValue> item in items) { Console.WriteLine("Item:"); foreach (var keyValuePair in item) { Console.WriteLine("{0} : S={1}, N={2}, SS=[{3}], NS=[{4}]", keyValuePair.Key, keyValuePair.Value.S, keyValuePair.Value.N, string.Join(", ", keyValuePair.Value.SS ?? new List <string>()), string.Join(", ", keyValuePair.Value.NS ?? new List <string>())); } } // Set marker variable startKey = result.LastEvaluatedKey; } while (startKey != null && startKey.Count > 0); #endregion } { #region Query Local Secondary Index Sample // Create a client AmazonDynamoDBClient client = new AmazonDynamoDBClient(); // Define item hash-key to be string value "Mark Twain" AttributeValue hashKey = new AttributeValue { S = "Mark Twain" }; // Define query condition to search for range-keys ("Year", in "YearsIndex") that are less than 1900 Condition condition = new Condition { ComparisonOperator = "LT", AttributeValueList = new List <AttributeValue> { new AttributeValue { N = "1900" } } }; // Create the key conditions from hashKey and condition Dictionary <string, Condition> keyConditions = new Dictionary <string, Condition> { // Hash key condition. ComparisonOperator must be "EQ". { "Author", new Condition { ComparisonOperator = "EQ", AttributeValueList = new List <AttributeValue> { hashKey } } }, // Range key condition { "Year", // Reference the correct range key when using indexes condition } }; // Define marker variable Dictionary <string, AttributeValue> startKey = null; do { // Create Query request QueryRequest request = new QueryRequest { TableName = "SampleTable", ExclusiveStartKey = startKey, KeyConditions = keyConditions, IndexName = "YearsIndex" // Specify the index to query against }; // Issue request var result = client.Query(request); // View all returned items List <Dictionary <string, AttributeValue> > items = result.Items; foreach (Dictionary <string, AttributeValue> item in items) { Console.WriteLine("Item:"); foreach (var keyValuePair in item) { Console.WriteLine("{0} : S={1}, N={2}, SS=[{3}], NS=[{4}]", keyValuePair.Key, keyValuePair.Value.S, keyValuePair.Value.N, string.Join(", ", keyValuePair.Value.SS ?? new List <string>()), string.Join(", ", keyValuePair.Value.NS ?? new List <string>())); } } // Set marker variable startKey = result.LastEvaluatedKey; } while (startKey != null && startKey.Count > 0); #endregion } { #region Scan Sample // Create a client AmazonDynamoDBClient client = new AmazonDynamoDBClient(); // Define scan conditions Dictionary <string, Condition> conditions = new Dictionary <string, Condition>(); // Title attribute should contain the string "Adventures" Condition titleCondition = new Condition(); titleCondition.ComparisonOperator = ComparisonOperator.CONTAINS; titleCondition.AttributeValueList.Add(new AttributeValue { S = "Adventures" }); conditions["Title"] = titleCondition; // Pages attributes must be greater-than the numeric value "200" Condition pagesCondition = new Condition(); pagesCondition.ComparisonOperator = ComparisonOperator.GT;; pagesCondition.AttributeValueList.Add(new AttributeValue { N = "200" }); conditions["Pages"] = pagesCondition; // Define marker variable Dictionary <string, AttributeValue> startKey = null; do { // Create Scan request ScanRequest request = new ScanRequest { TableName = "SampleTable", ExclusiveStartKey = startKey, ScanFilter = conditions }; // Issue request ScanResult result = client.Scan(request); // View all returned items List <Dictionary <string, AttributeValue> > items = result.Items; foreach (Dictionary <string, AttributeValue> item in items) { Console.WriteLine("Item:"); foreach (var keyValuePair in item) { Console.WriteLine("{0} : S={1}, N={2}, SS=[{3}], NS=[{4}]", keyValuePair.Key, keyValuePair.Value.S, keyValuePair.Value.N, string.Join(", ", keyValuePair.Value.SS ?? new List <string>()), string.Join(", ", keyValuePair.Value.NS ?? new List <string>())); } } // Set marker variable startKey = result.LastEvaluatedKey; } while (startKey != null && startKey.Count > 0); #endregion } { // Create lots of items to put into first table var table = Amazon.DynamoDBv2.DocumentModel.Table.LoadTable(TestClient, "SampleTable"); var batchWrite = table.CreateBatchWrite(); for (int i = 0; i < 100; i++) { var document = new Amazon.DynamoDBv2.DocumentModel.Document(); document["Author"] = "FakeAuthor" + i; document["Title"] = "Book" + i; document["Pages"] = (180 + i); document["Year"] = 1900 + i; batchWrite.AddDocumentToPut(document); } batchWrite.Execute(); } { #region Parallel Scan Sample // Create a client AmazonDynamoDBClient client = new AmazonDynamoDBClient(); // Define scan conditions Dictionary <string, Condition> conditions = new Dictionary <string, Condition>(); // Pages attributes must be greater-than the numeric value "200" Condition pagesCondition = new Condition(); pagesCondition.ComparisonOperator = ComparisonOperator.GT; pagesCondition.AttributeValueList.Add(new AttributeValue { N = "200" }); conditions["Pages"] = pagesCondition; // Setup 10 simultaneous threads, each thread calling Scan operation // with its own segment value. int totalSegments = 10; Parallel.For(0, totalSegments, segment => { // Define marker variable Dictionary <string, AttributeValue> startKey = null; do { // Create Scan request ScanRequest request = new ScanRequest { TableName = "SampleTable", ExclusiveStartKey = startKey, ScanFilter = conditions, // Total segments to split the table into TotalSegments = totalSegments, // Current segment to scan Segment = segment }; // Issue request var result = client.Scan(request); // Write returned items to file string path = string.Format("ParallelScan-{0}-of-{1}.txt", totalSegments, segment); List <Dictionary <string, AttributeValue> > items = result.Items; using (Stream stream = File.OpenWrite(path)) using (StreamWriter writer = new StreamWriter(stream)) { foreach (Dictionary <string, AttributeValue> item in items) { writer.WriteLine("Item:"); foreach (var keyValuePair in item) { writer.WriteLine("{0} : S={1}, N={2}, SS=[{3}], NS=[{4}]", keyValuePair.Key, keyValuePair.Value.S, keyValuePair.Value.N, string.Join(", ", keyValuePair.Value.SS ?? new List <string>()), string.Join(", ", keyValuePair.Value.NS ?? new List <string>())); } } } // Set marker variable startKey = result.LastEvaluatedKey; } while (startKey != null && startKey.Count > 0); }); #endregion } }
protected virtual void OnApplyAdd(AttributeValue attribute) { attribute.Value += Amount.Value; }
/// <summary> /// Job that will run quick SQL queries on a schedule. /// /// Called by the <see cref="IScheduler" /> when a /// <see cref="ITrigger" /> fires that is associated with /// the <see cref="IJob" />. /// </summary> public virtual void Execute(IJobExecutionContext context) { JobDataMap dataMap = context.JobDetail.JobDataMap; Guid?entryWorkflowType = dataMap.GetString("EraEntryWorkflow").AsGuidOrNull(); Guid?exitWorkflowType = dataMap.GetString("EraExitWorkflow").AsGuidOrNull(); bool updateVisitDates = dataMap.GetBooleanValue("SetVisitDates"); int commandTimeout = dataMap.GetString("CommandTimeout").AsIntegerOrNull() ?? 3600; // configuration // // giving int exitGivingCount = 1; // attendance int exitAttendanceCountShort = 1; int exitAttendanceCountLong = 8; // get era dataset from stored proc var resultContext = new RockContext(); var eraAttribute = AttributeCache.Get(SystemGuid.Attribute.PERSON_ERA_CURRENTLY_AN_ERA.AsGuid()); var eraStartAttribute = AttributeCache.Get(SystemGuid.Attribute.PERSON_ERA_START_DATE.AsGuid()); var eraEndAttribute = AttributeCache.Get(SystemGuid.Attribute.PERSON_ERA_END_DATE.AsGuid()); if (eraAttribute == null || eraStartAttribute == null || eraEndAttribute == null) { throw new Exception("Family analytic attributes could not be found"); } resultContext.Database.CommandTimeout = commandTimeout; context.UpdateLastStatusMessage("Getting Family Analytics Era Dataset..."); var results = resultContext.Database.SqlQuery <EraResult>("spCrm_FamilyAnalyticsEraDataset").ToList(); int personEntityTypeId = EntityTypeCache.Get("Rock.Model.Person").Id; int attributeEntityTypeId = EntityTypeCache.Get("Rock.Model.Attribute").Id; int eraAttributeId = eraAttribute.Id; int personAnalyticsCategoryId = CategoryCache.Get(SystemGuid.Category.HISTORY_PERSON_ANALYTICS.AsGuid()).Id; int progressPosition = 0; int progressTotal = results.Count; foreach (var result in results) { progressPosition++; // create new rock context for each family (https://weblog.west-wind.com/posts/2014/Dec/21/Gotcha-Entity-Framework-gets-slow-in-long-Iteration-Loops) RockContext updateContext = new RockContext(); updateContext.SourceOfChange = SOURCE_OF_CHANGE; updateContext.Database.CommandTimeout = commandTimeout; var attributeValueService = new AttributeValueService(updateContext); var historyService = new HistoryService(updateContext); // if era ensure it still meets requirements if (result.IsEra) { if (result.ExitGiftCountDuration < exitGivingCount && result.ExitAttendanceCountDurationShort < exitAttendanceCountShort && result.ExitAttendanceCountDurationLong < exitAttendanceCountLong) { // exit era (delete attribute value from each person in family) var family = new GroupService(updateContext).Queryable("Members, Members.Person").AsNoTracking().Where(m => m.Id == result.FamilyId).FirstOrDefault(); if (family != null) { foreach (var person in family.Members.Select(m => m.Person)) { // remove the era flag var eraAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraAttribute.Id && v.EntityId == person.Id).FirstOrDefault(); if (eraAttributeValue != null) { attributeValueService.Delete(eraAttributeValue); } // set end date var eraEndAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraEndAttribute.Id && v.EntityId == person.Id).FirstOrDefault(); if (eraEndAttributeValue == null) { eraEndAttributeValue = new AttributeValue(); eraEndAttributeValue.EntityId = person.Id; eraEndAttributeValue.AttributeId = eraEndAttribute.Id; attributeValueService.Add(eraEndAttributeValue); } eraEndAttributeValue.Value = RockDateTime.Now.ToString(); // add a history record if (personAnalyticsCategoryId != 0 && personEntityTypeId != 0 && attributeEntityTypeId != 0 && eraAttributeId != 0) { History historyRecord = new History(); historyService.Add(historyRecord); historyRecord.EntityTypeId = personEntityTypeId; historyRecord.EntityId = person.Id; historyRecord.CreatedDateTime = RockDateTime.Now; historyRecord.CreatedByPersonAliasId = person.PrimaryAliasId; historyRecord.Caption = "eRA"; historyRecord.Verb = "EXITED"; historyRecord.ChangeType = History.HistoryChangeType.Attribute.ConvertToString(); historyRecord.ValueName = "eRA"; historyRecord.NewValue = "Exited"; historyRecord.RelatedEntityTypeId = attributeEntityTypeId; historyRecord.RelatedEntityId = eraAttributeId; historyRecord.CategoryId = personAnalyticsCategoryId; historyRecord.SourceOfChange = SOURCE_OF_CHANGE; } updateContext.SaveChanges(); } // launch exit workflow if (exitWorkflowType.HasValue) { LaunchWorkflow(exitWorkflowType.Value, family); } } } } else { // entered era var family = new GroupService(updateContext).Queryable("Members").AsNoTracking().Where(m => m.Id == result.FamilyId).FirstOrDefault(); if (family != null) { foreach (var person in family.Members.Where(m => !m.Person.IsDeceased).Select(m => m.Person)) { // set era attribute to true var eraAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraAttribute.Id && v.EntityId == person.Id).FirstOrDefault(); if (eraAttributeValue == null) { eraAttributeValue = new AttributeValue(); eraAttributeValue.EntityId = person.Id; eraAttributeValue.AttributeId = eraAttribute.Id; attributeValueService.Add(eraAttributeValue); } eraAttributeValue.Value = bool.TrueString; // add start date var eraStartAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraStartAttribute.Id && v.EntityId == person.Id).FirstOrDefault(); if (eraStartAttributeValue == null) { eraStartAttributeValue = new AttributeValue(); eraStartAttributeValue.EntityId = person.Id; eraStartAttributeValue.AttributeId = eraStartAttribute.Id; attributeValueService.Add(eraStartAttributeValue); } eraStartAttributeValue.Value = RockDateTime.Now.ToString(); // delete end date if it exists var eraEndAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraEndAttribute.Id && v.EntityId == person.Id).FirstOrDefault(); if (eraEndAttributeValue != null) { attributeValueService.Delete(eraEndAttributeValue); } // add a history record if (personAnalyticsCategoryId != 0 && personEntityTypeId != 0 && attributeEntityTypeId != 0 && eraAttributeId != 0) { History historyRecord = new History(); historyService.Add(historyRecord); historyRecord.EntityTypeId = personEntityTypeId; historyRecord.EntityId = person.Id; historyRecord.CreatedDateTime = RockDateTime.Now; historyRecord.CreatedByPersonAliasId = person.PrimaryAliasId; historyRecord.Caption = "eRA"; historyRecord.Verb = "ENTERED"; historyRecord.ChangeType = History.HistoryChangeType.Attribute.ConvertToString(); historyRecord.RelatedEntityTypeId = attributeEntityTypeId; historyRecord.RelatedEntityId = eraAttributeId; historyRecord.CategoryId = personAnalyticsCategoryId; historyRecord.SourceOfChange = SOURCE_OF_CHANGE; } updateContext.SaveChanges(); } // launch entry workflow if (entryWorkflowType.HasValue) { LaunchWorkflow(entryWorkflowType.Value, family); } } } // update stats context.UpdateLastStatusMessage($"Updating eRA {progressPosition} of {progressTotal}"); } // load giving attributes context.UpdateLastStatusMessage("Updating Giving..."); resultContext.Database.ExecuteSqlCommand("spCrm_FamilyAnalyticsGiving"); // load attendance attributes context.UpdateLastStatusMessage("Updating Attendance..."); resultContext.Database.ExecuteSqlCommand("spCrm_FamilyAnalyticsAttendance"); // process visit dates if (updateVisitDates) { context.UpdateLastStatusMessage("Updating Visit Dates..."); resultContext.Database.ExecuteSqlCommand("spCrm_FamilyAnalyticsUpdateVisitDates"); } context.UpdateLastStatusMessage(""); }
public IRequest Marshall(DeleteItemRequest deleteItemRequest) { IRequest request = new DefaultRequest(deleteItemRequest, "AmazonDynamoDBv2"); string target = "DynamoDB_20120810.DeleteItem"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.0"; string uriResourcePath = ""; if (uriResourcePath.Contains("?")) { int queryPosition = uriResourcePath.IndexOf("?", StringComparison.OrdinalIgnoreCase); string queryString = uriResourcePath.Substring(queryPosition + 1); uriResourcePath = uriResourcePath.Substring(0, queryPosition); foreach (string s in queryString.Split('&', ';')) { string[] nameValuePair = s.Split('='); if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0) { request.Parameters.Add(nameValuePair[0], nameValuePair[1]); } else { request.Parameters.Add(nameValuePair[0], null); } } } request.ResourcePath = uriResourcePath; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); if (deleteItemRequest != null && deleteItemRequest.IsSetTableName()) { writer.WritePropertyName("TableName"); writer.Write(deleteItemRequest.TableName); } if (deleteItemRequest != null) { if (deleteItemRequest.Key != null && deleteItemRequest.Key.Count > 0) { writer.WritePropertyName("Key"); writer.WriteObjectStart(); foreach (string deleteItemRequestKeyKey in deleteItemRequest.Key.Keys) { AttributeValue keyListValue; bool keyListValueHasValue = deleteItemRequest.Key.TryGetValue(deleteItemRequestKeyKey, out keyListValue); writer.WritePropertyName(deleteItemRequestKeyKey); writer.WriteObjectStart(); if (keyListValue != null && keyListValue.IsSetS()) { writer.WritePropertyName("S"); writer.Write(keyListValue.S); } if (keyListValue != null && keyListValue.IsSetN()) { writer.WritePropertyName("N"); writer.Write(keyListValue.N); } if (keyListValue != null && keyListValue.IsSetB()) { writer.WritePropertyName("B"); writer.Write(StringUtils.FromMemoryStream(keyListValue.B)); } if (keyListValue != null && keyListValue.SS != null && keyListValue.SS.Count > 0) { List <string> sSList = keyListValue.SS; writer.WritePropertyName("SS"); writer.WriteArrayStart(); foreach (string sSListValue in sSList) { writer.Write(StringUtils.FromString(sSListValue)); } writer.WriteArrayEnd(); } if (keyListValue != null && keyListValue.NS != null && keyListValue.NS.Count > 0) { List <string> nSList = keyListValue.NS; writer.WritePropertyName("NS"); writer.WriteArrayStart(); foreach (string nSListValue in nSList) { writer.Write(StringUtils.FromString(nSListValue)); } writer.WriteArrayEnd(); } if (keyListValue != null && keyListValue.BS != null && keyListValue.BS.Count > 0) { List <MemoryStream> bSList = keyListValue.BS; writer.WritePropertyName("BS"); writer.WriteArrayStart(); foreach (MemoryStream bSListValue in bSList) { writer.Write(StringUtils.FromMemoryStream(bSListValue)); } writer.WriteArrayEnd(); } writer.WriteObjectEnd(); } writer.WriteObjectEnd(); } } if (deleteItemRequest != null) { if (deleteItemRequest.Expected != null && deleteItemRequest.Expected.Count > 0) { writer.WritePropertyName("Expected"); writer.WriteObjectStart(); foreach (string deleteItemRequestExpectedKey in deleteItemRequest.Expected.Keys) { ExpectedAttributeValue expectedListValue; bool expectedListValueHasValue = deleteItemRequest.Expected.TryGetValue(deleteItemRequestExpectedKey, out expectedListValue); writer.WritePropertyName(deleteItemRequestExpectedKey); writer.WriteObjectStart(); if (expectedListValue != null) { AttributeValue value = expectedListValue.Value; if (value != null) { writer.WritePropertyName("Value"); writer.WriteObjectStart(); if (value != null && value.IsSetS()) { writer.WritePropertyName("S"); writer.Write(value.S); } if (value != null && value.IsSetN()) { writer.WritePropertyName("N"); writer.Write(value.N); } if (value != null && value.IsSetB()) { writer.WritePropertyName("B"); writer.Write(StringUtils.FromMemoryStream(value.B)); } if (value != null && value.SS != null && value.SS.Count > 0) { List <string> sSList = value.SS; writer.WritePropertyName("SS"); writer.WriteArrayStart(); foreach (string sSListValue in sSList) { writer.Write(StringUtils.FromString(sSListValue)); } writer.WriteArrayEnd(); } if (value != null && value.NS != null && value.NS.Count > 0) { List <string> nSList = value.NS; writer.WritePropertyName("NS"); writer.WriteArrayStart(); foreach (string nSListValue in nSList) { writer.Write(StringUtils.FromString(nSListValue)); } writer.WriteArrayEnd(); } if (value != null && value.BS != null && value.BS.Count > 0) { List <MemoryStream> bSList = value.BS; writer.WritePropertyName("BS"); writer.WriteArrayStart(); foreach (MemoryStream bSListValue in bSList) { writer.Write(StringUtils.FromMemoryStream(bSListValue)); } writer.WriteArrayEnd(); } writer.WriteObjectEnd(); } } if (expectedListValue != null && expectedListValue.IsSetExists()) { writer.WritePropertyName("Exists"); writer.Write(expectedListValue.Exists); } writer.WriteObjectEnd(); } writer.WriteObjectEnd(); } } if (deleteItemRequest != null && deleteItemRequest.IsSetReturnValues()) { writer.WritePropertyName("ReturnValues"); writer.Write(deleteItemRequest.ReturnValues); } if (deleteItemRequest != null && deleteItemRequest.IsSetReturnConsumedCapacity()) { writer.WritePropertyName("ReturnConsumedCapacity"); writer.Write(deleteItemRequest.ReturnConsumedCapacity); } if (deleteItemRequest != null && deleteItemRequest.IsSetReturnItemCollectionMetrics()) { writer.WritePropertyName("ReturnItemCollectionMetrics"); writer.Write(deleteItemRequest.ReturnItemCollectionMetrics); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return(request); }
protected virtual IEnumerator <KeyValuePair <AttributeValue, long> > EnumerateTo(AttributeValue end) { try { var min = new BoundaryValueMask(end.DataType, Bound.Min); return(MergeEnumerators(_tree.EnumerateRange(min, end).GetEnumerator(), _transitionTree.EnumerateRange(min, end).GetEnumerator())); } catch (Exception ex) { LoggerManager.Instance.IndexLogger.Error("BPlusIndex", "Index Enumeration Failure: " + ex.ToString()); throw; } }
public void Push(AttributeValue value) { RESTClient.RESTClient.PostAsync(DataAndAttributeValueWrapper.GetJSON(value), _logger); }
public virtual IEnumerator <KeyValuePair <AttributeValue, long> > GetEnumerator(AttributeValue start, AttributeValue end) { try { if (order == SortOrder.DESC) { var temp = end; end = start; start = temp; } return(MergeEnumerators(_tree.EnumerateRange(start, end).GetEnumerator(), _transitionTree.EnumerateRange(start, end).GetEnumerator())); } catch (Exception ex) { LoggerManager.Instance.IndexLogger.Error("BPlusIndex", "Index Enumeration Failure: " + ex.ToString()); throw; } }
public static async Task Main(string[] args) { var configfile = "app.config"; var region = string.Empty; var table = string.Empty; var id = string.Empty; int i = 0; while (i < args.Length) { switch (args[i]) { case "-i": i++; id = args[i]; break; default: break; } i++; } if (id == string.Empty) { Console.WriteLine("You must supply an item ID (-i ID)"); return; } // Get default Region and table from config file var efm = new ExeConfigurationFileMap { ExeConfigFilename = configfile, }; Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(efm, ConfigurationUserLevel.None); if (configuration.HasFile) { AppSettingsSection appSettings = configuration.AppSettings; region = appSettings.Settings["Region"].Value; table = appSettings.Settings["Table"].Value; if ((region == string.Empty) || (table == string.Empty)) { Console.WriteLine($"You must specify Region and Table values in {configfile}"); return; } } else { Console.WriteLine("Could not find " + configfile); return; } var newRegion = RegionEndpoint.GetBySystemName(region); IAmazonDynamoDB client = new AmazonDynamoDBClient(newRegion); var keyValue = new AttributeValue(); keyValue.N = "201"; var key = new Dictionary <string, AttributeValue> { { "Id", keyValue }, }; var response = await GetItemAsync(client, table, key); foreach (var attr in response.Item) { Console.WriteLine($"{attr.Key}: {attr.Value}"); } }
public override decimal Get(AttributeValue value) => decimal.Parse(value.N);
public virtual IEnumerator <KeyValuePair <AttributeValue, long> > GetEnumerator(AttributeValue value) { try { return(GetValueEnumerator(value)); } catch (Exception ex) { LoggerManager.Instance.IndexLogger.Error("BPlusIndex", "Index Enumeration Failure: " + ex.ToString()); throw; } }
/// <summary> /// Job that will run quick SQL queries on a schedule. /// /// Called by the <see cref="IScheduler" /> when a /// <see cref="ITrigger" /> fires that is associated with /// the <see cref="IJob" />. /// </summary> public virtual void Execute(IJobExecutionContext context) { JobDataMap dataMap = context.JobDetail.JobDataMap; Guid?entryWorkflowType = dataMap.GetString("EraEntryWorkflow").AsGuidOrNull(); Guid?exitWorkflowType = dataMap.GetString("EraExitWorkflow").AsGuidOrNull(); bool updateVisitDates = dataMap.GetBooleanValue("SetVisitDates"); var groupTypeList = dataMap.GetString("GroupTypes"); // configuration // // giving int exitGivingCount = 1; // attendance int exitAttendanceCountShort = 1; int exitAttendanceCountLong = 8; // get era dataset from stored proc var resultContext = new RockContext(); var eraAttribute = AttributeCache.Read(SystemGuid.Attribute.PERSON_ERA_CURRENTLY_AN_ERA.AsGuid()); var eraStartAttribute = AttributeCache.Read(SystemGuid.Attribute.PERSON_ERA_START_DATE.AsGuid()); var eraEndAttribute = AttributeCache.Read(SystemGuid.Attribute.PERSON_ERA_END_DATE.AsGuid()); resultContext.Database.CommandTimeout = 3600; var results = resultContext.Database.SqlQuery <EraResult>("spCrm_FamilyAnalyticsEraDataset").ToList(); int personEntityTypeId = EntityTypeCache.Read("Rock.Model.Person").Id; int attributeEntityTypeId = EntityTypeCache.Read("Rock.Model.Attribute").Id; int eraAttributeId = AttributeCache.Read(SystemGuid.Attribute.PERSON_ERA_CURRENTLY_AN_ERA.AsGuid()).Id; int personAnalyticsCategoryId = CategoryCache.Read(SystemGuid.Category.HISTORY_PERSON_ANALYTICS.AsGuid()).Id; foreach (var result in results) { // create new rock context for each family (https://weblog.west-wind.com/posts/2014/Dec/21/Gotcha-Entity-Framework-gets-slow-in-long-Iteration-Loops) RockContext updateContext = new RockContext(); var attributeValueService = new AttributeValueService(updateContext); var historyService = new HistoryService(updateContext); // if era ensure it still meets requirements if (result.IsEra) { if (result.ExitGiftCountDuration < exitGivingCount && result.ExitAttendanceCountDurationShort < exitAttendanceCountShort && result.ExitAttendanceCountDurationLong < exitAttendanceCountLong) { // exit era (delete attribute value from each person in family) var family = new GroupService(updateContext).Queryable("Members, Members.Person").AsNoTracking().Where(m => m.Id == result.FamilyId).FirstOrDefault(); if (family != null) { foreach (var person in family.Members.Select(m => m.Person)) { // remove the era flag var eraAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraAttribute.Id && v.EntityId == person.Id).FirstOrDefault(); if (eraAttributeValue != null) { attributeValueService.Delete(eraAttributeValue); } // set end date var eraEndAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraEndAttribute.Id && v.EntityId == person.Id).FirstOrDefault(); if (eraEndAttributeValue == null) { eraEndAttributeValue = new AttributeValue(); eraEndAttributeValue.EntityId = person.Id; eraEndAttributeValue.AttributeId = eraEndAttribute.Id; attributeValueService.Add(eraEndAttributeValue); } eraEndAttributeValue.Value = RockDateTime.Now.ToString(); // add a history record if (personAnalyticsCategoryId != 0 && personEntityTypeId != 0 && attributeEntityTypeId != 0 && eraAttributeId != 0) { History historyRecord = new History(); historyService.Add(historyRecord); historyRecord.EntityTypeId = personEntityTypeId; historyRecord.EntityId = person.Id; historyRecord.CreatedDateTime = RockDateTime.Now; historyRecord.CreatedByPersonAliasId = person.PrimaryAliasId; historyRecord.Caption = "eRA"; historyRecord.Summary = "Exited eRA Status"; historyRecord.Verb = "EXITED"; historyRecord.RelatedEntityTypeId = attributeEntityTypeId; historyRecord.RelatedEntityId = eraAttributeId; historyRecord.CategoryId = personAnalyticsCategoryId; } updateContext.SaveChanges(); } // launch exit workflow if (exitWorkflowType.HasValue) { LaunchWorkflow(exitWorkflowType.Value, family); } } } } else { // entered era var family = new GroupService(updateContext).Queryable("Members").AsNoTracking().Where(m => m.Id == result.FamilyId).FirstOrDefault(); if (family != null) { foreach (var person in family.Members.Where(m => !m.Person.IsDeceased).Select(m => m.Person)) { // set era attribute to true var eraAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraAttribute.Id && v.EntityId == person.Id).FirstOrDefault(); if (eraAttributeValue == null) { eraAttributeValue = new AttributeValue(); eraAttributeValue.EntityId = person.Id; eraAttributeValue.AttributeId = eraAttribute.Id; attributeValueService.Add(eraAttributeValue); } eraAttributeValue.Value = bool.TrueString; // add start date var eraStartAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraStartAttribute.Id && v.EntityId == person.Id).FirstOrDefault(); if (eraStartAttributeValue == null) { eraStartAttributeValue = new AttributeValue(); eraStartAttributeValue.EntityId = person.Id; eraStartAttributeValue.AttributeId = eraStartAttribute.Id; attributeValueService.Add(eraStartAttributeValue); } eraStartAttributeValue.Value = RockDateTime.Now.ToString(); // delete end date if it exists var eraEndAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraEndAttribute.Id && v.EntityId == person.Id).FirstOrDefault(); if (eraEndAttributeValue != null) { attributeValueService.Delete(eraEndAttributeValue); } // add a history record if (personAnalyticsCategoryId != 0 && personEntityTypeId != 0 && attributeEntityTypeId != 0 && eraAttributeId != 0) { History historyRecord = new History(); historyService.Add(historyRecord); historyRecord.EntityTypeId = personEntityTypeId; historyRecord.EntityId = person.Id; historyRecord.CreatedDateTime = RockDateTime.Now; historyRecord.CreatedByPersonAliasId = person.PrimaryAliasId; historyRecord.Caption = "eRA"; historyRecord.Summary = "Entered eRA Status"; historyRecord.Verb = "ENTERED"; historyRecord.RelatedEntityTypeId = attributeEntityTypeId; historyRecord.RelatedEntityId = eraAttributeId; historyRecord.CategoryId = personAnalyticsCategoryId; } updateContext.SaveChanges(); } // launch entry workflow if (entryWorkflowType.HasValue) { LaunchWorkflow(entryWorkflowType.Value, family); } } } // update stats } // load giving attributes resultContext.Database.ExecuteSqlCommand("spCrm_FamilyAnalyticsGiving"); // load attendance attributes resultContext.Database.ExecuteSqlCommand("spCrm_FamilyAnalyticsAttendance"); // process history for group types if (!string.IsNullOrWhiteSpace(groupTypeList)) { string[] groupTypeGuids = groupTypeList.Split(','); var inactiveRecordValue = DefinedValueCache.Read(SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE); var groupTypeEntityTypeId = EntityTypeCache.Read("Rock.Model.GroupType").Id; foreach (var groupTypeGuid in groupTypeGuids) { var groupType = GroupTypeCache.Read(groupTypeGuid.AsGuid()); if (groupType != null) { // if the person is in a group of that type and the last history record for that group type isn't START write a start RockContext rockContext = new RockContext(); // get history for this group type var historyRecords = new HistoryService(rockContext).Queryable() .Where(h => h.EntityTypeId == personEntityTypeId && h.RelatedEntityTypeId == groupTypeEntityTypeId && h.RelatedEntityId == groupType.Id ) .GroupBy(h => h.EntityId) .Select(g => g.OrderByDescending(h => h.CreatedDateTime).Select(h => new { h.EntityId, h.Verb }).FirstOrDefault()) .ToList(); // get group member information var groupMemberInfo = new GroupMemberService(rockContext).Queryable() .Where(m => m.Group.GroupTypeId == groupType.Id && m.GroupMemberStatus == GroupMemberStatus.Active && m.Group.IsActive //&& m.Person.RecordStatusValueId != inactiveRecordValue.Id ) .GroupBy(m => m.PersonId) .Select(g => g.OrderBy(m => m.CreatedDateTime).Select(m => new { m.PersonId, m.CreatedDateTime, PersonAliasId = m.Person.Aliases.Select(p => p.Id).FirstOrDefault() }).FirstOrDefault()) .ToList(); var needsStartDate = groupMemberInfo.Where(m => !historyRecords.Any(h => h.EntityId == m.PersonId && h.Verb == "STARTED")); foreach (var startItem in needsStartDate) { using (RockContext updateContext = new RockContext()) { var historyService = new HistoryService(updateContext); History history = new History(); historyService.Add(history); history.EntityTypeId = personEntityTypeId; history.EntityId = startItem.PersonId; history.RelatedEntityTypeId = groupTypeEntityTypeId; history.RelatedEntityId = groupType.Id; history.Caption = groupType.Name; history.Summary = "Started Membership in Group Of Type"; history.Verb = "STARTED"; history.CreatedDateTime = startItem.CreatedDateTime; history.CreatedByPersonAliasId = startItem.PersonAliasId; history.CategoryId = personAnalyticsCategoryId; updateContext.SaveChanges(); } } var needsStoppedDate = historyRecords.Where(h => h.Verb == "STARTED" && !groupMemberInfo.Any(m => m.PersonId == h.EntityId)); foreach (var stopItem in needsStoppedDate) { using (RockContext updateContext = new RockContext()) { var person = new PersonService(updateContext).Get(stopItem.EntityId); if (person != null) { var historyService = new HistoryService(updateContext); History history = new History(); historyService.Add(history); history.EntityTypeId = personEntityTypeId; history.EntityId = person.Id; history.RelatedEntityTypeId = groupTypeEntityTypeId; history.RelatedEntityId = groupType.Id; history.Caption = groupType.Name; history.Summary = "Stopped Membership in Group Of Type"; history.Verb = "STOPPED"; history.CreatedDateTime = RockDateTime.Now; history.CreatedByPersonAliasId = person.PrimaryAliasId; history.CategoryId = personAnalyticsCategoryId; updateContext.SaveChanges(); } } } } } } // process visit dates if (updateVisitDates) { resultContext.Database.ExecuteSqlCommand("spCrm_FamilyAnalyticsUpdateVisitDates"); } }
public List <AttributeGroup> getFiltersByProducts(List <ProductDto> products) { var repo = Scope.Repository <ProductAttributeMetaData>(); var repo2 = Scope.Repository <ProductAttributeValue>(); //get all the attributes //var attributes = repo.GetAll(a => a.IsSearchable == true); //to do: issearchable must be true var attributes = repo.GetAll(); List <AttributeGroup> f = new List <AttributeGroup>(); // a list to store the attributes AttributeGroup attribute = null; foreach (var m in attributes)//get per attribute the attribute values and add it to the list { var attributeValues = repo2.GetAll(av => av.AttributeID == m.AttributeID).OrderBy(c => c.Value); List <string> tempValueList = new List <string>(); foreach (var p in products) { foreach (var item in attributeValues) { if (item.ProductID == p.ProductID) { if (!string.IsNullOrEmpty(item.Value)) { tempValueList.Add(item.Value); //als je een product hebt gevonden kun je stoppen in de attributeValues (je kan dan doorgaan met product nummer 2. break; } } } } tempValueList.Sort(); if (tempValueList.Count == 0) { continue;//dont save the attribute but go to new-one and check it that HAS attribute values } else { //there are attribute values, so make an attribute and atributevalueList attribute = new AttributeGroup(); attribute.AttributeName = m.AttributeCode; attribute.AttributeID = m.AttributeID; attribute.AttributeValueList = new List <AttributeValue>(); int count = 1;//count and checkvalue is for counting the same attribute values AttributeValue PrecedingAttributeValue = null; for (int i = 0; i < tempValueList.Count; i++) { AttributeValue NewAttributeValue = new AttributeValue();//sla de value op in de lijst en het aantal NewAttributeValue.AttributeValueName = tempValueList[i]; if (count == 1)//new attribute value { PrecedingAttributeValue = NewAttributeValue; count++; if (tempValueList.Count == 1) { attribute.AttributeValueList.Add(PrecedingAttributeValue); } else { continue; } } if ((string.Compare(PrecedingAttributeValue.AttributeValueName, NewAttributeValue.AttributeValueName, true) == 0)) //preceding value is the same as new value { if (i == tempValueList.Count - 1) //if the last value is the same as preceding, then store preceding { PrecedingAttributeValue.NumberPerAttribute = count; attribute.AttributeValueList.Add(PrecedingAttributeValue); } else { count++; continue; } } else //last value is not new value, so store the last value { PrecedingAttributeValue.NumberPerAttribute = count - 1; attribute.AttributeValueList.Add(PrecedingAttributeValue); //save checkvalue (the last value) PrecedingAttributeValue = NewAttributeValue; count = 2; if (i == tempValueList.Count - 1) { PrecedingAttributeValue.NumberPerAttribute = count - 1; attribute.AttributeValueList.Add(PrecedingAttributeValue); } } } attribute.ProductsPerAttribute = tempValueList.Count; f.Add(attribute); } } //sort the list and return only the first ten attributes f.Sort(delegate(AttributeGroup g1, AttributeGroup g2) { return(g1.ProductsPerAttribute.CompareTo(g2.ProductsPerAttribute)); }); f.Reverse(); if (f.Count > 10) { return(f.GetRange(0, 10)); } else { return(f); } }
public bool TryGetValue(AttributeValue key, out IDictionary <long, byte> values) { return(_tree.TryGetValue(key, out values)); }
public bool Contains(AttributeValue key) { return(_tree.ContainsKey(key)); }