private bool UnsubscribeData(TopicData topicData) { var result = false; if (isSolaceConnected) { try { Task <bool> subTask = Task.Run(async() => await solaceConnection.UnsubscribeAsync(topicData.SolaceTopic).ConfigureAwait(false)); result = subTask.Result; if (result) { logger.Info("Removed Solace subscription to topic - {0}", topicData.SolaceTopic); } else { logger.Error("Failed to remove subscription on Solace for topic - {0}", topicData.SolaceTopic); } } catch (Exception ex) { logger.Error(ex, "Exception while unsubscribing for topic - {0}", topicData.SolaceTopic); } } else { logger.Trace("SolaceRTD is not connected to a Solace PubSub+ Broker - {0}", topicData.ToString()); } return(result); }
private object SubscribeData(TopicData topicData) { if (isSolaceConnected) { try { Task <bool> subTask = Task.Run(async() => await solaceConnection.SubscribeAsync(topicData.SolaceTopic).ConfigureAwait(false)); var subResult = subTask.Result; if (subResult) { solaceTopics.Add(topicData.SolaceTopic, 1); logger.Info("Subscription added for - {0}", topicData.ToString()); return(GetData(topicData)); } else { logger.Error("Failed to add subscription on Solace for data - {0}", topicData.ToString()); return(ERROR_STATUS); } } catch (Exception ex) { logger.Error(ex, "Exception while subscribing for data - {0}", topicData.ToString()); return(ERROR_STATUS); } } else { logger.Trace("SolaceRTD is not connected to a Solace PubSub+ Broker - {0}", topicData.ToString()); return(NOT_CONNECTED_STATUS); } }
public static TopicData CreateNewTopic() { // Configure Topic Settings. string topicName = "chat-" + StaticResources.sessionCode; TopicDescription td = new TopicDescription(topicName); td.MaxSizeInMB = 5120; td.DefaultMessageTimeToLive = new TimeSpan(0, 1, 0); // Create the topic if it does not exist already. string connectionString = ServiceBusData.ConnectionString; var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString); if (!namespaceManager.TopicExists(topicName)) { namespaceManager.CreateTopic(topicName); foreach (Subscriptions subscription in (Subscriptions[])Enum.GetValues(typeof(Subscriptions))) { // convert subscription emum to string string subscriptionName = Enum.GetName(typeof(Subscriptions), subscription); CreateSubscription(topicName, subscriptionName); } } TopicData data = new TopicData() { TopicConnectionString = connectionString, topic = topicName }; return(data); }
public async Task <IActionResult> ProcessSendActivationUserMailTopic([FromBody] TopicData <User> topicData) { User?user = topicData.Data; if (user?.Id != null) { _logger.LogInformation($"Receive send activation user mail topic, user id: {user.Id}"); var secretValues = await _daprClient.GetSecretAsync(ConfigConstant.CodexKey, ConfigConstant.MicroserviceApiKey); var microserviceApiKey = secretValues[ConfigConstant.MicroserviceApiKey]; await _daprClient.InvokeMethodAsync(ApiNameConstant.UserApi, $"UserMail/activation", data : user, httpExtension : new HTTPExtension() { Verb = HTTPVerb.Post, Headers = { { HttpHeaderConstant.TenantId, topicData.TenantId }, { HttpHeaderConstant.ApiKey, $"{topicData.TenantId}.{microserviceApiKey}" } } } ); } else { _logger.LogWarning($"Receive user topic without id"); } return(Ok()); }
public Task <CancellationToken> SendTopicDataImmediately(TopicData topicData) { byte[] buffer = topicData.ToByteArray(); socket.SendFrame(buffer); return(Task.FromResult(new CancellationToken(false))); }
public void Publish(TopicData topicData) { if (IS_NOT_NULL(ubiiClient)) { ubiiClient.Publish(topicData); } }
private void FlushRecordsToPublish() { if (recordsToPublish.IsEmpty) { return; } RepeatedField <TopicDataRecord> repeatedField = new RepeatedField <TopicDataRecord>(); while (!recordsToPublish.IsEmpty) { if (recordsToPublish.TryTake(out TopicDataRecord record)) { repeatedField.Add(record); } } TopicDataRecordList recordList = new TopicDataRecordList() { Elements = { repeatedField }, }; TopicData topicData = new TopicData() { TopicDataRecordList = recordList }; SendTopicDataImmediately(topicData); }
public void CreateTopicConnection(TopicData data) { if (topic == null) { topic = new TopicConnectionHandler(data); } }
internal TopicQosWrapper ToNative() { var data = new TopicQosWrapper { Durability = Durability, DurabilityService = DurabilityService, Deadline = Deadline, LatencyBudget = LatencyBudget, Liveliness = Liveliness, Reliability = Reliability, DestinationOrder = DestinationOrder, History = History, ResourceLimits = ResourceLimits, TransportPriority = TransportPriority, Lifespan = Lifespan, Ownership = Ownership, }; if (TopicData != null) { data.TopicData = TopicData.ToNative(); } return(data); }
public void Import_BaseTopic_MapsBaseTopic() { var rootTopic = TopicFactory.Create("Root", "Container"); var topic = TopicFactory.Create("Test", "Container", rootTopic); var baseTopic = TopicFactory.Create("BaseTopic", "Container", rootTopic); var topicData = new TopicData() { Key = topic.Key, UniqueKey = topic.GetUniqueKey(), ContentType = topic.ContentType }; var referencedTopicData = new RecordData() { Key = "BaseTopic", Value = $"{baseTopic.GetUniqueKey()}" }; topicData.References.Add(referencedTopicData); topic.Import(topicData); Assert.IsNotNull(topic.BaseTopic); Assert.AreEqual<Topic?>(baseTopic, topic.BaseTopic); }
private static async Task <TopicData> CreateNewTopic(string connectionString, string topicName) { var managementClient = new ManagementClient(connectionString); TopicDescription td = new TopicDescription(topicName); td.MaxSizeInMB = 5120; td.DefaultMessageTimeToLive = new TimeSpan(0, 1, 0); if ((await managementClient.TopicExistsAsync(topicName)) == false) { await managementClient.CreateTopicAsync(topicName); foreach (Subscriptions subscription in (Subscriptions[])Enum.GetValues(typeof(Subscriptions))) { // convert subscription emum to string string subscriptionName = Enum.GetName(typeof(Subscriptions), subscription); await CreateSubscription(managementClient, topicName, subscriptionName); } } data = new TopicData() { TopicConnectionString = connectionString, topic = topicName }; return(data); }
private async void Initialize() { client_websocket = new ClientWebSocket(); Uri url = new Uri("ws://" + this.host + ":" + this.port + "?clientID=" + this.client_id); CancellationToken cancellation_token_connect = new CancellationToken(); await client_websocket.ConnectAsync(url, cancellation_token_connect); running = true; cancellation_token_process_incoming_msgs = new CancellationToken(); process_incoming_msgs = Task.Run(async() => { while (running) { ArraySegment <Byte> buffer = new ArraySegment <Byte>(); await client_websocket.ReceiveAsync(buffer, cancellation_token_process_incoming_msgs); TopicData topicdata = TopicData.Parser.ParseFrom(buffer.Array); Debug.Log(topicdata); if (topicdata.TopicDataRecord != null) { topicdata_callbacks[topicdata.TopicDataRecord.Topic]?.Invoke(topicdata.TopicDataRecord); } else if (topicdata.Error != null) { Debug.LogError(topicdata.Error.ToString()); } } }); }
public void Import_InvalidBaseTopic_MaintainsExistingValue() { var rootTopic = TopicFactory.Create("Root", "Container"); var topic = TopicFactory.Create("Test", "Container", rootTopic); var baseTopic = TopicFactory.Create("Base", "Container", rootTopic, 5); topic.BaseTopic = baseTopic; var topicData = new TopicData() { Key = topic.Key, UniqueKey = topic.GetUniqueKey(), ContentType = topic.ContentType }; var baseTopicReference = new RecordData() { Key = "BaseTopic", Value = $"{topicData.UniqueKey}:BaseTopic" }; topicData.References.Add(baseTopicReference); topic.Import(topicData); Assert.IsNotNull(topic.BaseTopic); Assert.AreEqual(baseTopic, topic.BaseTopic); }
public void ImportAsReplace_TopicDataWithChild_DeletedOrphanedChildren() { var topic = TopicFactory.Create("Test", "Container"); _ = TopicFactory.Create("Child1", "Container", topic); _ = TopicFactory.Create("Child2", "Container"); var topicData = new TopicData() { Key = topic.Key, UniqueKey = topic.GetUniqueKey(), ContentType = topic.ContentType }; topicData.Children.Add( new() { Key = "Child2", UniqueKey = topic.GetUniqueKey() + ":Child2", ContentType = topic.ContentType } ); topic.Import( topicData, new() { Strategy = ImportStrategy.Replace } ); Assert.AreEqual<int>(1, topic.Children.Count); Assert.AreEqual(topicData.Children.FirstOrDefault().UniqueKey, topic.Children.FirstOrDefault().GetUniqueKey()); Assert.AreEqual(topicData.Children.FirstOrDefault().ContentType, topic.Children.FirstOrDefault().ContentType); }
public void Import_TopicDataWithRelationships_MaintainsExisting() { var rootTopic = TopicFactory.Create("Root", "Container"); var topic = TopicFactory.Create("Test", "Container", rootTopic); var relatedTopic1 = TopicFactory.Create("Related1", "Container", rootTopic); var relatedTopic2 = TopicFactory.Create("Related2", "Container", rootTopic); var topicData = new TopicData() { Key = topic.Key, UniqueKey = topic.GetUniqueKey(), ContentType = topic.ContentType }; var relationshipData = new KeyValuesPair() { Key = "Related" }; topic.Relationships.SetValue("Related", relatedTopic1); topicData.Relationships.Add(relationshipData); relationshipData.Values.Add(relatedTopic2.GetUniqueKey()); topic.Import(topicData); Assert.AreEqual(relatedTopic1, topic.Relationships.GetValues("Related")?.FirstOrDefault()); Assert.AreEqual(relatedTopic2, topic.Relationships.GetValues("Related")?.LastOrDefault()); }
public DialogueManager() { NodeCurrent = null; TopicCurrent = null; State = DialogueState.INACTIVE; }
public async Task <IActionResult> ProcessApiKeyTopic([FromBody] TopicData <ApiKey> apiKeyTopicData) { if (!string.IsNullOrWhiteSpace(apiKeyTopicData.Data.Id)) { _logger.LogInformation($"Receive apiKey topic type {apiKeyTopicData.TopicType} id: {apiKeyTopicData.Data.Id}"); string cacheKey = $"{CacheConstant.ApiKey_}{apiKeyTopicData.Data.Id}"; switch (apiKeyTopicData.TopicType) { case TopicType.Remove: await _apiKeyCacheService.ClearCacheAsync(_daprClient, cacheKey); break; case TopicType.Modify: await _apiKeyCacheService.UpdateCacheAsync(_daprClient, cacheKey, apiKeyTopicData.Data); break; } } else { _logger.LogWarning($"Receive apiKey topic without id"); } return(Ok()); }
public void ImportAsMerge_TopicDataWithAttributes_SkipsNewerValues() { var topic = TopicFactory.Create("Test", "Container"); var topicData = new TopicData() { Key = topic.Key, UniqueKey = topic.GetUniqueKey(), ContentType = topic.ContentType }; topic.Attributes.SetValue("Attribute", "Original Value"); topicData.Attributes.Add( new() { Key = "Attribute", Value = "New Value", LastModified = DateTime.Now.AddSeconds(-5) } ); topic.Import( topicData, new() { Strategy = ImportStrategy.Merge } ); Assert.AreEqual<string?>("Original Value", topic.Attributes.GetValue("Attribute")); }
public static TopicData UnityToProto(string topic, Matrix4x4 m4x4) { TopicData td = new TopicData { TopicDataRecord = new TopicDataRecord { Topic = topic, Bool = true, Matrix4X4 = new Ubii.DataStructure.Matrix4x4 { M00 = m4x4.m00, M01 = m4x4.m01, M02 = m4x4.m02, M03 = m4x4.m03, M10 = m4x4.m10, M11 = m4x4.m11, M12 = m4x4.m12, M13 = m4x4.m13, M20 = m4x4.m20, M21 = m4x4.m21, M22 = m4x4.m21, M23 = m4x4.m23, M30 = m4x4.m30, M31 = m4x4.m31, M32 = m4x4.m32, M33 = m4x4.m33 }, } }; return(td); }
public IFacadeUpdateResult <TopicData> CreateTopic(TopicInfoDto topic, PostInfoDto post) { // Save topic UnitOfWork.BeginTransaction(); FacadeUpdateResult <TopicData> result = TopicSystem.SaveNewTopic(topic); if (result.IsSuccessful) { UnitOfWork.CommitTransaction(); TopicData savedTopic = result.Result; // set post.TopicId post.TopicId = savedTopic.Id; // Save Post PostSystem postSystem = new PostSystem(UnitOfWork); UnitOfWork.BeginTransaction(); IFacadeUpdateResult <PostData> resultPost = postSystem.SaveNewPost(post); if (resultPost.IsSuccessful) { UnitOfWork.CommitTransaction(); } else { UnitOfWork.RollbackTransaction(); } } else { UnitOfWork.RollbackTransaction(); } return(result); }
public void ImportAsReplace_TopicDataWithRelationships_DeletesOrphanedRelationships() { var rootTopic = TopicFactory.Create("Root", "Container"); var topic = TopicFactory.Create("Test", "Container", rootTopic); var relatedTopic1 = TopicFactory.Create("Related1", "Container", rootTopic); var relatedTopic2 = TopicFactory.Create("Related2", "Container", rootTopic); var relatedTopic3 = TopicFactory.Create("Related3", "Container", rootTopic); var topicData = new TopicData() { Key = topic.Key, UniqueKey = topic.GetUniqueKey(), ContentType = topic.ContentType }; var relationshipData = new KeyValuesPair() { Key = "Related" }; topic.Relationships.SetValue("Related", relatedTopic1); topic.Relationships.SetValue("Related", relatedTopic2); topic.Relationships.SetValue("Cousin", relatedTopic3); topicData.Relationships.Add(relationshipData); relationshipData.Values.Add(relatedTopic1.GetUniqueKey()); topic.Import( topicData, new() { Strategy = ImportStrategy.Replace } ); Assert.AreEqual(relatedTopic1, topic.Relationships.GetValues("Related")?.FirstOrDefault()); Assert.AreEqual<int>(1, topic.Relationships.GetValues("Related").Count); Assert.AreEqual<int>(0, topic.Relationships.GetValues("Cousin").Count); }
internal List <CategoryData> GetCategoryDataApi() { List <Forum> cat; var local = new List <CategoryData>(); using (ForumContext db = new ForumContext()) { cat = db.Forum.Include(d => d.Topics).ToList(); } foreach (var c in cat) { var l = new CategoryData(); var topic = new List <TopicData>(); l.CategoryID = c.CategoryID; l.Title = c.Title; foreach (var t in c.Topics) { var lt = new TopicData { TopicID = t.TopicID, Title = t.Title }; topic.Add(lt); } l.Topics = topic; local.Add(l); } return(local); }
#pragma warning disable CS0618 // Type or member is obsolete public void Deserialize_DerivedTopicKey_ReturnsExpectedResults() { var sourceData = new TopicData() { Key = "Test", UniqueKey = "Root:Test", ContentType = "Container", DerivedTopicKey = "Root:Meta:Test" }; var json = $"{{" + $"\"Key\":\"{sourceData.Key}\"," + $"\"UniqueKey\":\"{sourceData.UniqueKey}\"," + $"\"ContentType\":\"{sourceData.ContentType}\"," + $"\"DerivedTopicKey\":\"{sourceData.DerivedTopicKey}\"," + $"\"Attributes\":[]," + $"\"Relationships\":[]," + $"\"Children\":[]" + $"}}"; var topicData = JsonSerializer.Deserialize<TopicData>(json); Assert.AreEqual<string?>(sourceData.Key, topicData?.Key); Assert.AreEqual<string?>(sourceData.UniqueKey, topicData?.UniqueKey); Assert.AreEqual<string?>(sourceData.ContentType, topicData?.ContentType); Assert.AreEqual<string?>(sourceData.DerivedTopicKey, topicData?.DerivedTopicKey); Assert.AreEqual<int?>(0, topicData?.Relationships.Count); Assert.AreEqual<int?>(0, topicData?.Attributes.Count); Assert.AreEqual<int?>(0, topicData?.Children.Count); }
internal TopicData GetTopicDataApi(int id) { var local = new TopicData { Subjects = new List <SubjectData>() }; using (ForumContext db = new ForumContext()) { FTopic topic; topic = (from e in db.Topic where e.TopicID == id select e).Include(d => d.Subjects).FirstOrDefault(); local.TopicID = topic.TopicID; local.Title = topic.Title; foreach (var sub in topic.Subjects) { var s = new SubjectData { SubjectID = sub.SubjectID, Title = sub.Title, Author = sub.Author, Text = sub.Text }; local.Subjects.Add(s); } } return(local); }
private async Task <CancellationToken> FlushRecordsToPublish() { if (recordsToPublish.IsEmpty) { return(new CancellationToken(true)); } RepeatedField <TopicDataRecord> repeatedField = new RepeatedField <TopicDataRecord>(); while (!recordsToPublish.IsEmpty) { if (recordsToPublish.TryTake(out TopicDataRecord record)) { repeatedField.Add(record); } } TopicDataRecordList recordList = new TopicDataRecordList() { Elements = { repeatedField }, }; TopicData topicData = new TopicData() { TopicDataRecordList = recordList }; return(await SendTopicDataImmediately(topicData)); }
public FetchResponse ParseFrom(KafkaBinaryReader reader) { int size = 0, correlationId = 0, dataCount = 0; try { size = reader.ReadInt32(); correlationId = reader.ReadInt32(); dataCount = reader.ReadInt32(); var data = new TopicData[dataCount]; for (var i = 0; i < dataCount; i++) { data[i] = TopicData.ParseFrom(reader); } return(new FetchResponse(correlationId, data, size)); } catch (OutOfMemoryException mex) { Logger.Error(string.Format( "OOM Error. Data values were: size: {0}, correlationId: {1}, dataCound: {2}.\r\nFull Stack of exception: {3}", size, correlationId, dataCount, mex.StackTrace)); throw; } }
public void Import_TopicDataWithReferences_MaintainsExisting() { var rootTopic = TopicFactory.Create("Root", "Container"); var topic = TopicFactory.Create("Test", "Container", rootTopic); var referencedTopic1 = TopicFactory.Create("Referenced1", "Container", rootTopic); var referencedTopic2 = TopicFactory.Create("Referenced2", "Container", rootTopic); var topicData = new TopicData() { Key = topic.Key, UniqueKey = topic.GetUniqueKey(), ContentType = topic.ContentType }; var referenceData = new RecordData() { Key = "Referenced", Value = referencedTopic2.GetUniqueKey() }; topic.References.SetValue("Referenced", referencedTopic1); topicData.References.Add(referenceData); topic.Import(topicData); Assert.AreEqual(referencedTopic1, topic.References.GetValue("Referenced")); }
public async Task <IActionResult> ProcessSendActivationUserMailTopic([FromBody] TopicData <User> topicData) { User?user = topicData.Data; if (!string.IsNullOrWhiteSpace(user?.Id)) { _logger.LogInformation($"Receive send activation user mail topic, user id: {user.Id}"); // TODO Add api key ADMIN from global tenant and add tenant Id to header await _daprClient.InvokeMethodAsync("userapi", $"UserMail/activation", data : user, httpExtension : new HTTPExtension() { Verb = HTTPVerb.Post, Headers = new Dictionary <string, string>() { { "tenantId", topicData.TenantId } } } ); } else { _logger.LogWarning($"Receive user topic without id"); } return(Ok()); }
public void Import_TopicDataWithChild_SkipsOrphanedChild() { var topic = TopicFactory.Create("Test", "Container"); var child1 = TopicFactory.Create("Child1", "Container", topic); _ = TopicFactory.Create("Child2", "Container"); var topicData = new TopicData() { Key = topic.Key, UniqueKey = topic.GetUniqueKey(), ContentType = topic.ContentType }; topicData.Children.Add( new() { Key = "Child2", UniqueKey = topic.GetUniqueKey() + ":Child2", ContentType = topic.ContentType } ); topic.Import(topicData); Assert.AreEqual<int>(2, topic.Children.Count); Assert.AreEqual(child1, topic.Children.FirstOrDefault()); Assert.AreEqual(topicData.Children.FirstOrDefault().UniqueKey, topic.Children.LastOrDefault().GetUniqueKey()); }
public async void Send(TopicData topicdata) { Debug.Log("topicdata: " + topicdata); MemoryStream memory_stream = new MemoryStream(); CodedOutputStream coded_output_stream = new CodedOutputStream(memory_stream); topicdata.WriteTo(coded_output_stream); coded_output_stream.Flush(); Debug.Log("coded_output_stream: " + coded_output_stream); var bytebuffer = memory_stream.ToArray(); Debug.Log("buffer length: " + bytebuffer.Length); var array_segment = new ArraySegment <Byte>(bytebuffer); Debug.Log("array_segment length: " + array_segment.Count); CancellationToken cancellation_token = new CancellationToken(); await client_websocket.SendAsync(array_segment, WebSocketMessageType.Binary, true, cancellation_token); /*try * { * await client_websocket.SendAsync(array_segment, WebSocketMessageType.Binary, true, cancellation_token); * } * catch (Exception ex) * { * Debug.LogError(ex.ToString()); * }*/ }
// Called when data received void OnMessage(object sender, NetMQSocketEventArgs e) { e.Socket.ReceiveFrameBytes(out bool hasmore); TopicData topicData = new TopicData { }; if (hasmore) { byte[] bytes = e.Socket.ReceiveFrameBytes(out hasmore); if (bytes.Length == 4) { string msgString = Encoding.UTF8.GetString(bytes, 0, bytes.Length); if (msgString == "PING") { // PING message socket.SendFrame(Encoding.UTF8.GetBytes("PONG")); return; } } else { topicData.MergeFrom(bytes); } } // Invoke callback if (topicData.TopicDataRecord != null) { string topic = topicData.TopicDataRecord.Topic; if (topicdataCallbacks.ContainsKey(topic)) { foreach (Action <TopicDataRecord> callback in topicdataCallbacks[topic]) { callback.Invoke(topicData.TopicDataRecord); } } else { foreach (KeyValuePair <string, List <Action <TopicDataRecord> > > entry in topicdataRegexCallbacks) { Match m = Regex.Match(topic, entry.Key); if (m.Success) { foreach (Action <TopicDataRecord> callback in entry.Value) { callback.Invoke(topicData.TopicDataRecord); } } } } } // catch possible error else if (topicData.Error != null) { Debug.LogError("topicData Error: " + topicData.Error.ToString()); return; } }
/* public void Start() { ProcessChoiceOutcome("Mood(0,-10)"); // test to ensure it get seperate this string correctly } */ public void Load(string fileName) { File = new StreamReader(fileName, Encoding.Default); if(File != null) { Topic = new TopicData("Unknown", new List<DialogueNode>()); string line; do { line = GetValidLine(); if(line != null) ProcessNode(line); } while(line != null); } }
public void GetBytesValidStructure() { string topicName = "topic"; int correlationId = 1; string clientId = "TestClient"; short requiredAcks = 5; int ackTimeout = 345; var partition = 2; short error = 0; var payload = Encoding.UTF8.GetBytes("testMessage"); BufferedMessageSet messageSet = new BufferedMessageSet(new List<Message>() { new Message(payload) }, 0); var partitionData = new PartitionData(partition, ErrorMapper.ToError(error), messageSet); var topicData = new TopicData(topicName, new List<PartitionData>() { partitionData }); var request = new ProducerRequest(correlationId, clientId, requiredAcks, ackTimeout, new List<TopicData>() { topicData }); int requestSize = 2 + //request type id 2 + //versionId 4 + //correlation id request.GetShortStringWriteLength(clientId) + // actual client id 2 + //required acks 4 + //ack timeout 4 + //data count //=== data part request.GetShortStringWriteLength(topicName) + //topic 4 + //partition data count 4 + //partition id 4 + //messages set size messageSet.SetSize; var ms = new MemoryStream(); request.WriteTo(ms); byte[] bytes = ms.ToArray(); Assert.IsNotNull(bytes); // add 4 bytes for the length of the message at the beginning Assert.AreEqual(requestSize + 4, bytes.Length); // first 4 bytes = the message length Assert.AreEqual(requestSize, BitConverter.ToInt32(BitWorks.ReverseBytes(bytes.Take(4).ToArray<byte>()), 0)); // next 2 bytes = the request type Assert.AreEqual((short)RequestTypes.Produce, BitConverter.ToInt16(BitWorks.ReverseBytes(bytes.Skip(4).Take(2).ToArray<byte>()), 0)); // next 2 bytes = the version id Assert.AreEqual((short)ProducerRequest.CurrentVersion, BitConverter.ToInt16(BitWorks.ReverseBytes(bytes.Skip(6).Take(2).ToArray<byte>()), 0)); // next 2 bytes = the correlation id Assert.AreEqual(correlationId, BitConverter.ToInt32(BitWorks.ReverseBytes(bytes.Skip(8).Take(4).ToArray<byte>()), 0)); // next 2 bytes = the client id length Assert.AreEqual((short)clientId.Length, BitConverter.ToInt16(BitWorks.ReverseBytes(bytes.Skip(12).Take(2).ToArray<byte>()), 0)); // next few bytes = the client id Assert.AreEqual(clientId, Encoding.ASCII.GetString(bytes.Skip(14).Take(clientId.Length).ToArray<byte>())); // next 2 bytes = the required acks Assert.AreEqual((short)requiredAcks, BitConverter.ToInt16(BitWorks.ReverseBytes(bytes.Skip(14 + clientId.Length).Take(2).ToArray<byte>()), 0)); // next 4 bytes = the ack timeout Assert.AreEqual(ackTimeout, BitConverter.ToInt32(BitWorks.ReverseBytes(bytes.Skip(16 + clientId.Length).Take(4).ToArray<byte>()), 0)); // next 4 bytes = the data count Assert.AreEqual(1, BitConverter.ToInt32(BitWorks.ReverseBytes(bytes.Skip(20 + clientId.Length).Take(4).ToArray<byte>()), 0)); // next 2 bytes = the tppic length Assert.AreEqual((short)topicName.Length, BitConverter.ToInt16(BitWorks.ReverseBytes(bytes.Skip(24 + clientId.Length).Take(2).ToArray<byte>()), 0)); // next few bytes = the topic Assert.AreEqual(topicName, Encoding.ASCII.GetString(bytes.Skip(26 + clientId.Length).Take(topicName.Length).ToArray<byte>())); // next 4 bytes = the partition data count Assert.AreEqual(topicData.PartitionData.Count(), BitConverter.ToInt32(BitWorks.ReverseBytes(bytes.Skip(26 + clientId.Length + topicName.Length).Take(4).ToArray<byte>()), 0)); // next 4 bytes = the partition Assert.AreEqual(partition, BitConverter.ToInt32(BitWorks.ReverseBytes(bytes.Skip(30 + clientId.Length + topicName.Length).Take(4).ToArray<byte>()), 0)); // skipping MessageSet check - this could be done separately in another unit test }
public TopicData GetTopicData() { TopicData td = Topic; // only allow you to get topic once Topic = null; return td; }
public void PassTopicData(string data) { TopicData topicData = new TopicData(); MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(data)); System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(topicData.GetType()); topicData = serializer.ReadObject(ms) as TopicData; ms.Close(); gspivotviewer.ItemAdornerStyle = this.Resources["topicAdorner"] as Style; gspivotviewer.PivotProperties.Clear(); gspivotviewer.PivotProperties = new List<PivotViewerProperty>() { new PivotViewerNumericProperty() { Binding = new Binding("me_too_count"), Id = "Me Too Count", Options = PivotViewerPropertyOptions.CanFilter | PivotViewerPropertyOptions.CanSearchText }, new PivotViewerStringProperty() { Binding = new Binding("style"), Id = "Style", Options = PivotViewerPropertyOptions.CanFilter | PivotViewerPropertyOptions.CanSearchText }, new PivotViewerStringProperty() { Binding = new Binding("at_sfn"), Id = "URL", Options = PivotViewerPropertyOptions.CanFilter | PivotViewerPropertyOptions.CanSearchText }, new PivotViewerStringProperty() { Binding = new Binding("content"), Id = "Content", Options = PivotViewerPropertyOptions.CanFilter | PivotViewerPropertyOptions.CanSearchText }, new PivotViewerNumericProperty() { Binding = new Binding("reply_count"), Id = "Reply Count", Options = PivotViewerPropertyOptions.CanFilter | PivotViewerPropertyOptions.CanSearchText }, new PivotViewerStringProperty() { Binding = new Binding("status"), Id = "Status", Options = PivotViewerPropertyOptions.CanFilter | PivotViewerPropertyOptions.CanSearchText }, new PivotViewerStringProperty() { Binding = new Binding("subject"), Id = "Subject", Options = PivotViewerPropertyOptions.CanFilter | PivotViewerPropertyOptions.CanSearchText }, new PivotViewerStringProperty() { Binding = new Binding("emotitag.face"), Id = "Emotion", Options = PivotViewerPropertyOptions.CanFilter | PivotViewerPropertyOptions.CanSearchText }, new PivotViewerStringProperty() { Binding = new Binding("emotitag.feeling"), Id = "Feeling", Options = PivotViewerPropertyOptions.CanFilter | PivotViewerPropertyOptions.CanSearchText } }; gspivotviewer.ItemTemplates = new PivotViewerItemTemplateCollection(); gspivotviewer.ItemTemplates.Add((PivotViewerItemTemplate)Resources["topicsTemplate"]); gspivotviewer.ItemsSource = new ObservableCollection<Topic>(); var coll = gspivotviewer.ItemsSource as ObservableCollection<Topic>; coll.Clear(); foreach (Topic topic in topicData.data) { switch (topic.style) { case "problem": topic.styleImage = StyleImages[0]; break; case "idea": topic.styleImage = StyleImages[1]; break; case "question": topic.styleImage = StyleImages[2]; break; case "praise": topic.styleImage = StyleImages[3]; break; case "update": topic.styleImage = StyleImages[4]; break; } coll.Add(topic); } if (topicData.total > 50) { for (int counter = 1; counter < 4; counter++) { if (topicData.total > counter * 50) { string apiToCall = "/topics.json?sort=recently_active&limit=50&page=" + counter + "&callback=handlerMoreTopics"; HtmlPage.Window.Invoke("getMoreData", apiToCall, "People"); } } } }
public void AddMoreTopics(string data) { TopicData topicData = new TopicData(); MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(data)); System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(topicData.GetType()); topicData = serializer.ReadObject(ms) as TopicData; ms.Close(); var coll = gspivotviewer.ItemsSource as ObservableCollection<Topic>; foreach (Topic topic in topicData.data) { switch (topic.style) { case "problem": topic.styleImage = StyleImages[0]; break; case "idea": topic.styleImage = StyleImages[1]; break; case "question": topic.styleImage = StyleImages[2]; break; case "praise": topic.styleImage = StyleImages[3]; break; case "update": topic.styleImage = StyleImages[4]; break; } coll.Add(topic); } }
private TopicData GetTopicData(DirectoryInfo dir) { TopicData t = new TopicData(dir); return t; }
public LoadTopic() { Topic = null; }
/// <summary> /// Initializes a new instance of the <see cref="TopicWriter"/> class. /// </summary> /// <param name="topic">Current topic.</param> /// <param name="parserResult">Parser result.</param> /// <param name="name2topic">Mapping from topic name to data.</param> /// <param name="writer">XML writer.</param> protected TopicWriter(TopicData topic, TopicParserResult parserResult, IDictionary<string, TopicData> name2topic, XmlWriter writer) : base(writer) { this.topic = topic; this.document = parserResult.Document; this.name2topic = name2topic; this.state = new WriterState(); this.commandWriter = new Lazy<Writers.CommandWriter>(CreateCommandWriter); this.containerElementNames = new Lazy<IEnumerable<string>>(GetContainerElementNames); this.includeSeeAlso = new Lazy<bool>(GetIncludeSeeAlso); }
public void AddTopic(TopicData td) { TopicList.Add (td); }
private static TopicWriter Create(TopicData topic, TopicParserResult parserResult, IDictionary<string, TopicData> name2topic, XmlWriter writer) { switch (topic.Type) { case TopicType.Empty: return new EmptyTopicWriter(topic, parserResult, name2topic, writer); case TopicType.General: return new GeneralTopicWriter(topic, parserResult, name2topic, writer); case TopicType.Glossary: return new GlossaryTopicWriter(topic, parserResult, name2topic, writer); case TopicType.HowTo: return new HowToTopicWriter(topic, parserResult, name2topic, writer); case TopicType.Orientation: return new OrientationTopicWriter(topic, parserResult, name2topic, writer); default: throw new InvalidOperationException("Unexpected topic type: " + topic.Type); } }
/// <summary> /// Writes the topic as MAML. /// </summary> /// <param name="writer">Writer.</param> /// <param name="topic">The topic.</param> /// <param name="name2topic">Mapping from topic name to data.</param> /// <param name="paths">Paths.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>Asynchronous task.</returns> public static async Task WriteAsync(TopicData topic, IDictionary<string, TopicData> name2topic, StreamWriter writer, Paths paths, CancellationToken cancellationToken) { var parserResult = topic.ParserResult; if (parserResult == null) { parserResult = await TopicParser.ParseAsync(topic, paths, cancellationToken); } var xmlSettings = new XmlWriterSettings { Async = true, Indent = true, }; using (var xmlWriter = XmlWriter.Create(writer, xmlSettings)) { var topicWriter = TopicWriter.Create(topic, parserResult, name2topic, xmlWriter); await topicWriter.WriteAsync(); } }
public GlossaryTopicWriter(TopicData topic, TopicParserResult parserResult, IDictionary<string, TopicData> name2topic, XmlWriter writer) : base(topic, parserResult, name2topic, writer) { }
private void StartTopic(int id) { CurrentTopicId = id; TopicCurrent = ConversationPartner.GetTopic(id); NodeList = TopicCurrent.GetNodeList(); State = DialogueState.IN_TOPIC; NodeCurrentId = 0; GotoNode(); }