Example #1
0
        /// <summary>
        /// Publish Reusable Workflow
        /// </summary>
        /// <param name="mapping"></param>
        public void PublishReusableWorkflow(NWFMappingEntry mapping)
        {
            SPContentType ct = web.ContentTypes[mapping.BindingName];
            string workflowName = mapping.WorkflowName;
            string pathToNWF = Path.Combine(properties.Definition.RootDirectory, mapping.WorkflowFileName);
            byte[] workflowData = File.ReadAllBytes(pathToNWF);
            string workflowFile = Utility.ConvertByteArrayToString(workflowData);

            while ((int)workflowFile[0] != (int)char.ConvertFromUtf32(60)[0])
                workflowFile = workflowFile.Remove(0, 1);

            ExportedWorkflowWithListMetdata workflowWithListMetdata = ExportedWorkflowWithListMetdata.Deserialize(workflowFile);
            string xmlMessage = workflowWithListMetdata.ExportedWorkflowSeralized;
            SPListCollection lists = web.Lists;
            Dictionary<string, Guid> dictionary = new Dictionary<string, Guid>(lists.Count);
            foreach (SPList spList in lists)
            {
                if (!dictionary.ContainsKey(spList.Title.ToUpper()))
                    dictionary.Add(spList.Title.ToUpper(), spList.ID);
            }
            foreach (var listReference in workflowWithListMetdata.ListReferences)
            {
                string key = listReference.ListName.ToUpper();
                if (dictionary.ContainsKey(key) && !dictionary.ContainsValue(listReference.ListId))
                    xmlMessage = xmlMessage.Replace(Utility.FormatGuid(listReference.ListId), Utility.FormatGuid(dictionary[key]));
            }
            var exportedWorkflow = WorkflowPart.Deserialize<ExportedWorkflow>(xmlMessage);
            foreach (var config in exportedWorkflow.Configurations.ActionConfigs)
                WorkflowRenderer.ProcessActionConfig(config);

            Guid listId = Guid.Empty;
            bool validateWorkflow = true;
            Publish publish = new Publish(web);
            publish.PublishAWorkflow(workflowName, exportedWorkflow.Configurations, listId, web, (ImportContext)null, validateWorkflow, ct.Id, string.Empty);
        }
Example #2
0
        public void On(Publish x)
        {
            var notifications = x.Events
                .Select(e => new Notification(e, DateTime.Now, HubGateway.LocalHubId()))
                .ToArray();

            observers.Notify(notifications);                
        }
        public void Publish(WebServiceHandler h)
        {
            var publish = h.Context.Request.Path.SkipUntilOrEmpty("/publish/");
            var p = new Publish();

            if (p.ContainsKey(publish))
            {
                var f = p[publish];

                var bytes = File.ReadAllBytes(f);

                h.Context.Response.OutputStream.Write(bytes, 0, bytes.Length);
                h.CompleteRequest();
            }
        }
Example #4
0
        public void Publish(string node, XmlElement item)
        {
            IQ iq = new IQ(m_Account.Client.Document);
            iq.Type = IQType.set;
            PubSub pubsub = new PubSub(m_Account.Client.Document);
            pubsub.SetAttribute("xmlns", "http://jabber.org/protocol/pubsub");
            Publish publish = new Publish(m_Account.Client.Document);
            publish.SetAttribute("node", node);
            publish.AddChild(item);
            pubsub.AddChild(publish);
            iq.AddChild(pubsub);

            if (m_Account.ConnectionState == AccountConnectionState.Connected) {
                m_Account.Send(iq);
            } else {
                lock (m_Queue) {
                    m_Queue.Enqueue(iq);
                }
            }
        }
        public Analyze AutomaticAnalyze(string host, Publish publish, StartNew startNew, FromCache fromCache, int? maxHours, All all, IgnoreMismatch ignoreMismatch,
			int maxWaitInterval, int sleepInterval)
        {
            var startTime = DateTime.UtcNow;
            var sleepIntervalMilliseconds = sleepInterval * 1000;
            var apiPassCount = 1;
            var analyzeModel = Analyze(host, publish, startNew, fromCache, maxHours, all, ignoreMismatch);

            // Ignoring cache settings after first request to prevent loop
            startNew = StartNew.Ignore;

            // Shouldn't have to check status header as HasErrorOccurred should be enough
            while (analyzeModel.HasErrorOccurred == false && analyzeModel.status != "READY" && (DateTime.UtcNow - startTime).TotalSeconds < maxWaitInterval)
            {
                Thread.Sleep(sleepIntervalMilliseconds);
                apiPassCount++;
                analyzeModel = Analyze(host, publish, startNew, fromCache, null, all, ignoreMismatch);
            }

            analyzeModel.Wrapper.ApiPassCount = apiPassCount;

            return analyzeModel;
        }
 private Akka.Cluster.PubSub.Serializers.Proto.Publish PublishToProto(Publish publish)
 {
     return Akka.Cluster.PubSub.Serializers.Proto.Publish.CreateBuilder()
         .SetTopic(publish.Topic)
         .SetPayload(PayloadToProto(publish.Message))
         .Build();
 }
        public async Task when_sending_publish_with_qos0_then_publish_is_sent_to_subscribers_and_no_ack_is_sent()
        {
            var clientId = Guid.NewGuid().ToString();

            var configuration = new MqttConfiguration {
                MaximumQualityOfService = MqttQualityOfService.ExactlyOnce
            };
            var topicEvaluator     = new Mock <IMqttTopicEvaluator> ();
            var connectionProvider = new Mock <IConnectionProvider> ();
            var publishSenderFlow  = new Mock <IPublishSenderFlow> ();
            var retainedRepository = new Mock <IRepository <RetainedMessage> > ();
            var sessionRepository  = new Mock <IRepository <ClientSession> > ();
            var willRepository     = new Mock <IRepository <ConnectionWill> >();

            sessionRepository.Setup(r => r.Read(It.IsAny <string> ()))
            .Returns(new ClientSession(clientId)
            {
                PendingMessages = new List <PendingMessage> {
                    new PendingMessage()
                }
            });

            var packetIdProvider            = Mock.Of <IPacketIdProvider> ();
            var undeliveredMessagesListener = new Subject <MqttUndeliveredMessage> ();

            var topic = "foo/bar";

            var flow = new ServerPublishReceiverFlow(topicEvaluator.Object, connectionProvider.Object,
                                                     publishSenderFlow.Object, retainedRepository.Object, sessionRepository.Object, willRepository.Object,
                                                     packetIdProvider, undeliveredMessagesListener, configuration);

            var subscribedClientId1 = Guid.NewGuid().ToString();
            var subscribedClientId2 = Guid.NewGuid().ToString();
            var requestedQoS1       = MqttQualityOfService.AtLeastOnce;
            var requestedQoS2       = MqttQualityOfService.ExactlyOnce;
            var sessions            = new List <ClientSession> {
                new ClientSession(subscribedClientId1, clean: false)
                {
                    Subscriptions = new List <ClientSubscription> {
                        new ClientSubscription {
                            ClientId = subscribedClientId1,
                            MaximumQualityOfService = requestedQoS1, TopicFilter = topic
                        }
                    }
                },
                new ClientSession(subscribedClientId2, clean: false)
                {
                    Subscriptions = new List <ClientSubscription> {
                        new ClientSubscription {
                            ClientId = subscribedClientId2,
                            MaximumQualityOfService = requestedQoS2, TopicFilter = topic
                        }
                    }
                }
            };

            var client1Receiver = new Subject <IPacket> ();
            var client1Channel  = new Mock <IMqttChannel <IPacket> > ();

            client1Channel.Setup(c => c.ReceiverStream).Returns(client1Receiver);

            var client2Receiver = new Subject <IPacket> ();
            var client2Channel  = new Mock <IMqttChannel <IPacket> > ();

            client2Channel.Setup(c => c.ReceiverStream).Returns(client2Receiver);

            topicEvaluator.Setup(e => e.Matches(It.IsAny <string> (), It.IsAny <string> ())).Returns(true);
            sessionRepository.Setup(r => r.ReadAll()).Returns(sessions.AsQueryable());

            connectionProvider
            .Setup(p => p.GetConnection(It.Is <string> (s => s == subscribedClientId1)))
            .Returns(client1Channel.Object);
            connectionProvider
            .Setup(p => p.GetConnection(It.Is <string> (s => s == subscribedClientId2)))
            .Returns(client2Channel.Object);

            var publish = new Publish(topic, MqttQualityOfService.AtMostOnce, retain: false, duplicated: false);

            publish.Payload = Encoding.UTF8.GetBytes("Publish Receiver Flow Test");

            var receiver = new Subject <IPacket> ();
            var channel  = new Mock <IMqttChannel <IPacket> > ();

            channel.Setup(c => c.ReceiverStream).Returns(receiver);

            await flow.ExecuteAsync(clientId, publish, channel.Object)
            .ConfigureAwait(continueOnCapturedContext: false);

            retainedRepository.Verify(r => r.Create(It.IsAny <RetainedMessage> ()), Times.Never);
            publishSenderFlow.Verify(s => s.SendPublishAsync(It.Is <string>(x => x == subscribedClientId1),
                                                             It.Is <Publish> (p => p.Topic == publish.Topic &&
                                                                              p.Payload.ToList().SequenceEqual(publish.Payload)),
                                                             It.Is <IMqttChannel <IPacket> >(c => c == client1Channel.Object), It.Is <PendingMessageStatus>(x => x == PendingMessageStatus.PendingToSend)));
            publishSenderFlow.Verify(s => s.SendPublishAsync(It.Is <string>(x => x == subscribedClientId2),
                                                             It.Is <Publish> (p => p.Topic == publish.Topic &&
                                                                              p.Payload.ToList().SequenceEqual(publish.Payload)),
                                                             It.Is <IMqttChannel <IPacket> >(c => c == client2Channel.Object), It.Is <PendingMessageStatus>(x => x == PendingMessageStatus.PendingToSend)));
            channel.Verify(c => c.SendAsync(It.IsAny <IPacket> ()), Times.Never);
        }
        public async Task when_sending_publish_and_subscriber_with_qos2_send_publish_received_then_publish_is_not_re_transmitted()
        {
            var clientId = Guid.NewGuid().ToString();

            var configuration = new MqttConfiguration {
                MaximumQualityOfService = MqttQualityOfService.ExactlyOnce,
                WaitTimeoutSecs         = 2
            };
            var topicEvaluator     = new Mock <IMqttTopicEvaluator> ();
            var connectionProvider = new Mock <IConnectionProvider> ();
            var publishSenderFlow  = new Mock <IPublishSenderFlow> ();
            var retainedRepository = new Mock <IRepository <RetainedMessage> > ();
            var sessionRepository  = new Mock <IRepository <ClientSession> > ();
            var willRepository     = new Mock <IRepository <ConnectionWill> >();

            sessionRepository.Setup(r => r.Read(It.IsAny <string> ()))
            .Returns(new ClientSession(clientId)
            {
                PendingMessages = new List <PendingMessage> {
                    new PendingMessage()
                }
            });

            var packetIdProvider            = Mock.Of <IPacketIdProvider> ();
            var undeliveredMessagesListener = new Subject <MqttUndeliveredMessage> ();

            var topic = "foo/bar";

            var flow = new ServerPublishReceiverFlow(topicEvaluator.Object, connectionProvider.Object, publishSenderFlow.Object,
                                                     retainedRepository.Object, sessionRepository.Object, willRepository.Object, packetIdProvider, undeliveredMessagesListener, configuration);

            var subscribedClientId = Guid.NewGuid().ToString();
            var requestedQoS       = MqttQualityOfService.ExactlyOnce;
            var sessions           = new List <ClientSession> {
                new ClientSession(subscribedClientId, clean: false)
                {
                    Subscriptions = new List <ClientSubscription> {
                        new ClientSubscription {
                            ClientId = subscribedClientId, MaximumQualityOfService = requestedQoS, TopicFilter = topic
                        }
                    }
                }
            };

            var clientReceiver = new Subject <IPacket> ();
            var clientSender   = new Subject <IPacket> ();
            var clientChannel  = new Mock <IMqttChannel <IPacket> > ();

            clientSender.OfType <Publish>().Subscribe(p => {
                clientReceiver.OnNext(new PublishReceived(p.PacketId.Value));
            });

            clientChannel.Setup(c => c.ReceiverStream).Returns(clientReceiver);
            clientChannel.Setup(c => c.SenderStream).Returns(clientSender);
            clientChannel.Setup(c => c.SendAsync(It.IsAny <IPacket> ()))
            .Callback <IPacket> (packet => clientSender.OnNext(packet))
            .Returns(Task.Delay(0));
            topicEvaluator.Setup(e => e.Matches(It.IsAny <string> (), It.IsAny <string> ())).Returns(true);
            sessionRepository.Setup(r => r.ReadAll()).Returns(sessions.AsQueryable());

            connectionProvider
            .Setup(p => p.GetConnection(It.Is <string> (s => s == subscribedClientId)))
            .Returns(clientChannel.Object);

            var packetId = (ushort?)new Random().Next(0, ushort.MaxValue);
            var publish  = new Publish(topic, MqttQualityOfService.ExactlyOnce, retain: false, duplicated: false, packetId: packetId);

            publish.Payload = Encoding.UTF8.GetBytes("Publish Receiver Flow Test");

            var receiver = new Subject <IPacket> ();
            var channel  = new Mock <IMqttChannel <IPacket> > ();

            channel.Setup(c => c.ReceiverStream).Returns(receiver);

            await flow.ExecuteAsync(clientId, publish, channel.Object)
            .ConfigureAwait(continueOnCapturedContext: false);

            publishSenderFlow.Verify(s => s.SendPublishAsync(It.Is <string>(x => x == subscribedClientId),
                                                             It.Is <Publish> (p => p.Topic == publish.Topic &&
                                                                              p.Payload.ToList().SequenceEqual(publish.Payload)),
                                                             It.Is <IMqttChannel <IPacket> >(c => c == clientChannel.Object), It.Is <PendingMessageStatus>(x => x == PendingMessageStatus.PendingToSend)), Times.Once);
            clientChannel.Verify(c => c.SendAsync(It.Is <IPacket> (p => p is Publish)), Times.Never);
        }
Example #9
0
        public async Task WriteAsync(IEnumerable <ISerie <TKey, TEntry> > items, PublicationType publicationType, Publish publish, bool useTemporaryStorageOnFailure)
        {
            // ensure we only iterate the original collection once, if it is not a list or array
            if (!(items is ICollection <ISerie <TKey, TEntry> > || items is Array))
            {
                items = items.ToList();
            }

            var tasks = new List <Task <IEnumerable <ISerie <TKey, TEntry> > > >();

            tasks.AddRange(LookupStorages(items).Select(c => WriteToStorageAsync(c.Storage, c.Lookups, useTemporaryStorageOnFailure)));
            await Task.WhenAll(tasks).ConfigureAwait(false);

            // Only publish things that were written
            var writtenItems = tasks.SelectMany(x => x.Result);

            if (publish.HasFlag(Publish.Remotely))
            {
                if (_remotePublishSubscribe == null)
                {
                    throw new MissingTsdbServiceException("No remote publish subscribe store has been provided for the TsdbClient.");
                }

                await _remotePublishSubscribe.PublishAsync(writtenItems, publicationType).ConfigureAwait(false);
            }
            if (publish.HasFlag(Publish.Locally))
            {
                await _localPublishSubscribe.PublishAsync(writtenItems, publicationType).ConfigureAwait(false);
            }
        }
Example #10
0
 public GreenApp()
 {
     Publish.Message <GreenMessage>().To("tcp://localhost:2555/blue");
     Handlers.DisableConventionalDiscovery();
 }
 public NotAGitHubRepositoryViewModel(ITeamExplorerServices teamExplorerServices)
 {
     this.teamExplorerServices = teamExplorerServices;
     Publish = ReactiveCommand.Create();
     Publish.Subscribe(_ => OnPublish());
 }
Example #12
0
 public void Add(Publish publish)
 {
     SocialNetworkingKata_PublishDbContext.Publish.Add(publish);
     SocialNetworkingKata_PublishDbContext.SaveChanges();
 }
Example #13
0
        public ActionResult MyPoetry2(int id)
        {
            string          taqtiObject = "";
            MySqlConnection myConn;
            MySqlDataReader dataReader;

            myConn = new MySqlConnection(TaqtiController.connectionString);
            myConn.Open();
            MySqlCommand cmd = new MySqlCommand(TaqtiController.connectionString);

            cmd             = myConn.CreateCommand();
            cmd.CommandText = "select * from mypoetry where id = @id";
            cmd.Parameters.AddWithValue("@id", id);
            dataReader = cmd.ExecuteReader();
            Publish p = new Publish();

            while (dataReader.Read())
            {
                p.id    = dataReader.GetInt32(0);
                p.text  = dataReader.GetString(4);
                p.name  = dataReader.GetString(1);
                p.title = dataReader.GetString(3);
                try
                {
                    taqtiObject = dataReader.GetString(5);
                }
                catch
                {
                }
                try
                {
                    p.url = dataReader.GetString(2);
                }
                catch
                {
                }
            }
            myConn.Close();
            List <int> met = new List <int>();

            Scansion scn = new Scansion();

            scn.fuzzy      = false;
            scn.freeVerse  = false;
            scn.isChecked  = false;
            scn.errorParam = 2;
            scn.meter      = met;

            List <scanOutput> lst = new List <scanOutput>();

            if (string.IsNullOrEmpty(taqtiObject))
            {
                foreach (string line in p.text.Split('\n'))
                {
                    if (!string.IsNullOrWhiteSpace(line))
                    {
                        scn.addLine(new Lines(line.Trim()));
                    }
                }
                lst = scn.scanLines();

                if (lst.Count == 0)
                {
                    scanOutput sc = new scanOutput();
                    sc.identifier = id;
                    sc.poet       = p.name;
                    sc.title      = p.title;
                    sc.text       = p.text;
                    sc.url        = p.url;
                    lst.Add(sc);
                }
                else
                {
                    lst[0].identifier = id;
                    lst[0].poet       = p.name;
                    lst[0].title      = p.title;
                    lst[0].text       = p.text;
                    lst[0].url        = p.url;
                }
                XmlSerializer ser        = new XmlSerializer(typeof(List <scanOutput>));
                StringWriter  textWriter = new StringWriter();
                ser.Serialize(textWriter, lst);
                MySqlConnection myConn2 = new MySqlConnection(TaqtiController.connectionString);
                myConn2.Open();
                MySqlCommand cmd2 = new MySqlCommand(TaqtiController.connectionString);
                cmd2             = myConn2.CreateCommand();
                cmd2.CommandText = "update mypoetry set taqtiObject = @object where id = @id;";
                cmd2.Parameters.AddWithValue("@object", (string)textWriter.ToString());
                cmd2.Parameters.AddWithValue("@id", p.id);
                cmd2.ExecuteNonQuery();
                myConn2.Close();
            }
            else
            {
                XmlSerializer ser    = new XmlSerializer(typeof(List <scanOutput>));
                StringReader  reader = new StringReader(taqtiObject);
                lst = (List <scanOutput>)ser.Deserialize(reader);
                lst[0].identifier = id;
                lst[0].poet       = p.name;
                lst[0].title      = p.title;
                lst[0].text       = p.text;
                lst[0].url        = p.url;
            }
            return(PartialView("_Poetry", crunch(lst)));
        }
Example #14
0
        public void use_send_this_to_send_message_while_publishing()
        {
            var b = BusSetup.StartWith <Conservative>(cb => cb.ConfigurePublishing(
                                                          p => p.MessageMatch(m => m.IsType <MessageA>()).PublishPipeline(Publish.This(new MessageB()), new SequentialPublisher())))
                    .Construct();

            int bCount = 0;
            int aCount = 0;

            b.Subscribe <MessageB>(msg => bCount++);
            b.Subscribe <MessageA>(msg => aCount++);

            b.Publish(new MessageA());
            bCount.ShouldBeEqualTo(1);
            aCount.ShouldBeEqualTo(1);
        }
Example #15
0
        /// <summary>
        /// Advances the player to the next quest state.
        /// </summary>
        /// <param name="player">The player advancing to the next quest state</param>
        /// <param name="questSource">The source of quest advancement</param>
        internal void Advance(NWGameObject player, NWGameObject questSource)
        {
            if (!GetIsPlayer(player))
            {
                return;
            }

            // Retrieve the player's current quest state.
            var playerID    = GetGlobalID(player);
            var questStatus = QuestProgressRepo.Get(playerID, QuestID);

            // Can't find a state? Notify the player they haven't accepted the quest.
            if (questStatus.CurrentState <= 0)
            {
                SendMessageToPC(player, "You have not accepted this quest yet.");
                return;
            }

            // If this quest has already been completed, exit early.
            // This is used in case a module builder incorrectly configures a quest.
            // We don't want to risk giving duplicate rewards.
            if (questStatus.TimesCompleted > 0 && !IsRepeatable)
            {
                return;
            }

            var currentState = GetState(questStatus.CurrentState);
            var lastState    = GetStates().Last();

            // If this is the last state, the assumption is that it's time to complete the quest.
            if (currentState == lastState)
            {
                RequestRewardSelectionFromPC(player, questSource);
            }
            else
            {
                // Progress player's quest status to the next state.
                questStatus.CurrentState++;
                var nextState = GetState(questStatus.CurrentState);

                // Update the player's journal
                AddJournalQuestEntry(JournalTag, questStatus.CurrentState, player, false);

                // Notify the player they've progressed.
                SendMessageToPC(player, "Objective for quest '" + Name + "' complete! Check your journal for information on the next objective.");

                // Submit all of these changes to the cache/DB.
                QuestProgressRepo.Set(playerID, questStatus);

                // Create any extended data entries for the next state of the quest.
                foreach (var objective in nextState.GetObjectives())
                {
                    objective.Initialize(player, QuestID);
                }

                // Run any quest-specific code.
                foreach (var action in _onAdvanceActions)
                {
                    action.Invoke(player, questSource, questStatus.CurrentState);
                }

                // Notify to subscribers that the player has advanced to the next state of the quest.
                Publish.CustomEvent(player, QuestEventPrefix.OnQuestAdvanced, new QuestAdvanced(player, QuestID, questStatus.CurrentState));
            }
        }
 public ClientHubConnectionHandler(string name, Publish method) : base(name)
 {
     PublishMethod = method;
 }
Example #17
0
        // GET: MyPoetry
        public ActionResult Index(int?page)
        {
            List <Publish>  pt = new List <Publish>();
            MySqlConnection myConn;
            MySqlDataReader dataReader;

            myConn = new MySqlConnection(TaqtiController.connectionString);
            myConn.Open();
            MySqlCommand cmd = new MySqlCommand(TaqtiController.connectionString);

            cmd = myConn.CreateCommand();
            int maxCount = 1;
            int maxPages = 1;
            int residue  = 0;

            cmd.CommandText = "select count(id) from mypoetry where publish = '1';";
            dataReader      = cmd.ExecuteReader();
            while (dataReader.Read())
            {
                maxCount = dataReader.GetInt32(0);
            }
            myConn.Close();
            maxPages = maxCount / 18;
            residue  = maxCount - maxPages * 18;
            if (residue > 0)
            {
                maxPages = maxPages + 1;
            }
            if (page == null || page == 1)
            {
                MySqlConnection myConn2;
                MySqlDataReader dataReader2;
                myConn2 = new MySqlConnection(TaqtiController.connectionString);
                myConn2.Open();
                MySqlCommand cmd2 = new MySqlCommand(TaqtiController.connectionString);
                cmd2             = myConn2.CreateCommand();
                cmd2.CommandText = "select * from mypoetry  where publish = '1' order by id DESC limit 0,18";
                dataReader2      = cmd2.ExecuteReader();
                while (dataReader2.Read())
                {
                    Publish p = new Publish();
                    p.id    = dataReader2.GetInt32(0);
                    p.text  = dataReader2.GetString(4);
                    p.name  = dataReader2.GetString(1);
                    p.title = dataReader2.GetString(3);
                    try
                    {
                        p.url = dataReader2.GetString(2);
                    }
                    catch
                    {
                    }
                    try
                    {
                        p.date = dataReader2.GetDateTime(6);
                    }
                    catch
                    {
                    }
                    p.mozun       = dataReader2.GetInt32(8);
                    p.maxpages    = maxPages;
                    p.currentPage = 1;
                    pt.Add(p);
                }
                myConn2.Close();
            }
            else
            {
                MySqlConnection myConn2;
                MySqlDataReader dataReader2;
                myConn2 = new MySqlConnection(TaqtiController.connectionString);
                myConn2.Open();
                MySqlCommand cmd2 = new MySqlCommand(TaqtiController.connectionString);
                cmd2             = myConn2.CreateCommand();
                cmd2.CommandText = "select * from mypoetry  where publish = '1' order by id DESC limit @init,@count";
                if (page == maxPages && residue > 0)
                {
                    cmd2.Parameters.AddWithValue("@init", (page - 1) * 18);
                    cmd2.Parameters.AddWithValue("@count", residue);
                }
                else
                {
                    cmd2.Parameters.AddWithValue("@init", (page - 1) * 18);
                    cmd2.Parameters.AddWithValue("@count", 18);
                }

                dataReader2 = cmd2.ExecuteReader();
                while (dataReader2.Read())
                {
                    Publish p = new Publish();
                    p.id    = dataReader2.GetInt32(0);
                    p.text  = dataReader2.GetString(4);
                    p.name  = dataReader2.GetString(1);
                    p.title = dataReader2.GetString(3);
                    try
                    {
                        p.url = dataReader2.GetString(2);
                    }
                    catch
                    {
                    }
                    try
                    {
                        p.date = dataReader2.GetDateTime(6);
                    }
                    catch
                    {
                    }

                    p.mozun       = dataReader2.GetInt32(8);
                    p.maxpages    = maxPages;
                    p.currentPage = (int)page;
                    pt.Add(p);
                }
                myConn2.Close();
            }
            return(View(pt));
        }
        public async Task when_sending_publish_with_qos2_then_publish_is_sent_to_subscribers_and_publish_received_is_sent()
        {
            var clientId = Guid.NewGuid().ToString();

            var configuration = new MqttConfiguration {
                MaximumQualityOfService = MqttQualityOfService.ExactlyOnce
            };
            var topicEvaluator     = new Mock <IMqttTopicEvaluator> ();
            var connectionProvider = new Mock <IConnectionProvider> ();
            var publishSenderFlow  = new Mock <IPublishSenderFlow> ();
            var retainedRepository = new Mock <IRepository <RetainedMessage> > ();
            var sessionRepository  = new Mock <IRepository <ClientSession> > ();
            var willRepository     = new Mock <IRepository <ConnectionWill> >();

            publishSenderFlow.Setup(f => f.SendPublishAsync(It.IsAny <string> (), It.IsAny <Publish> (), It.IsAny <IMqttChannel <IPacket> > (), It.IsAny <PendingMessageStatus> ()))
            .Returns(Task.Delay(0));

            sessionRepository.Setup(r => r.Read(It.IsAny <string> ()))
            .Returns(new ClientSession(clientId)
            {
                PendingMessages = new List <PendingMessage> {
                    new PendingMessage()
                }
            });

            var packetId                    = (ushort?)new Random().Next(0, ushort.MaxValue);
            var packetIdProvider            = Mock.Of <IPacketIdProvider> ();
            var undeliveredMessagesListener = new Subject <MqttUndeliveredMessage> ();

            var topic = "foo/bar";

            var flow = new ServerPublishReceiverFlow(topicEvaluator.Object, connectionProvider.Object, publishSenderFlow.Object,
                                                     retainedRepository.Object, sessionRepository.Object, willRepository.Object, packetIdProvider, undeliveredMessagesListener, configuration);

            var subscribedClientId = Guid.NewGuid().ToString();
            var requestedQoS       = MqttQualityOfService.ExactlyOnce;
            var sessions           = new List <ClientSession> {
                new ClientSession(subscribedClientId, clean: false)
                {
                    Subscriptions = new List <ClientSubscription> {
                        new ClientSubscription {
                            ClientId = subscribedClientId, MaximumQualityOfService = requestedQoS, TopicFilter = topic
                        }
                    }
                }
            };

            var clientReceiver = new Subject <IPacket> ();
            var clientChannel  = new Mock <IMqttChannel <IPacket> > ();

            clientChannel.Setup(c => c.ReceiverStream).Returns(clientReceiver);

            topicEvaluator.Setup(e => e.Matches(It.IsAny <string> (), It.IsAny <string> ())).Returns(true);
            sessionRepository.Setup(r => r.ReadAll()).Returns(sessions.AsQueryable());

            connectionProvider
            .Setup(p => p.GetConnection(It.Is <string> (s => s == subscribedClientId)))
            .Returns(clientChannel.Object);

            var publish = new Publish(topic, MqttQualityOfService.ExactlyOnce, retain: false, duplicated: false, packetId: packetId);

            publish.Payload = Encoding.UTF8.GetBytes("Publish Flow Test");

            var receiver    = new Subject <IPacket> ();
            var sender      = new Subject <IPacket> ();
            var channelMock = new Mock <IMqttChannel <IPacket> > ();

            channelMock.Setup(c => c.IsConnected).Returns(true);
            channelMock.Setup(c => c.ReceiverStream).Returns(receiver);
            channelMock.Setup(c => c.SenderStream).Returns(sender);
            channelMock.Setup(c => c.SendAsync(It.IsAny <IPacket> ()))
            .Callback <IPacket> (packet => sender.OnNext(packet))
            .Returns(Task.Delay(0));

            var channel       = channelMock.Object;
            var ackSentSignal = new ManualResetEventSlim(initialState: false);

            sender.Subscribe(p => {
                if (p is PublishReceived)
                {
                    ackSentSignal.Set();
                }
            });

            var flowTask = flow.ExecuteAsync(clientId, publish, channel);

            var ackSent = ackSentSignal.Wait(1000);

            receiver.OnNext(new PublishRelease(packetId.Value));

            await Task.Delay(TimeSpan.FromMilliseconds(1000));

            Assert.True(ackSent);
            publishSenderFlow.Verify(s => s.SendPublishAsync(It.Is <string>(x => x == subscribedClientId),
                                                             It.Is <Publish> (p => p.Topic == publish.Topic &&
                                                                              p.Payload.ToList().SequenceEqual(publish.Payload)),
                                                             It.Is <IMqttChannel <IPacket> >(c => c == clientChannel.Object), It.Is <PendingMessageStatus>(x => x == PendingMessageStatus.PendingToSend)));
            retainedRepository.Verify(r => r.Create(It.IsAny <RetainedMessage> ()), Times.Never);
            channelMock.Verify(c => c.SendAsync(It.Is <IPacket> (p => p is PublishReceived && (p as PublishReceived).PacketId == packetId.Value)));
        }
Example #19
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Updates all files that require an update.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        private void UpdateFiles()
        {
            bool fAskedUserToExit = false;             // will be set to true as soon as we have asked user

            using (ProgressDialog dlg = new ProgressDialog())
            {
                dlg.ProgressBar.Maximum = m_FilesToUpdate.Length;
                dlg.Show();
                for (int i = 0; i < m_FilesToUpdate.Length && !dlg.ShouldCancel; i++)
                {
                    UpdateFile file = m_FilesToUpdate[i];
                    Trace.WriteLine(DateTime.Now.ToString() + ": Installing " + file.Name);
                    dlg.InstallText = "Installing " + file.Name;

                    if (file.ExitVs && !fAskedUserToExit)
                    {
                        fAskedUserToExit = true;
                        Process[] processes = Process.GetProcessesByName("devenv");
                        if (processes.Length > 0)
                        {
                            if (MessageBox.Show("Visual Studio needs to close before update can proceed",
                                                "Updates available", MessageBoxButtons.OKCancel) == DialogResult.OK)
                            {
                                ExitVs();
                            }
                            else
                            {
                                Trace.WriteLine(DateTime.Now.ToString() + ": Skipped closing Visual Studio by user's request");
                            }
                        }
                    }

                    try
                    {
                        string extension = Path.GetExtension(file.Name).ToLower();
                        if (extension == ".msi" || extension == ".vsi")
                        {
                            // Install this file
                            Process process = new Process();
                            process.StartInfo.FileName       = Path.Combine(m_UpdatePath, file.Name);
                            process.StartInfo.CreateNoWindow = true;
                            process.StartInfo.Arguments      = "/quiet";
                            process.Start();
                            process.WaitForExit();
                            Trace.WriteLine(DateTime.Now.ToString() + ": Exit code: " + process.ExitCode);
                        }
                        else if (extension == ".dll")
                        {
                            // Install in the GAC
                            string  fileName = Path.Combine(m_UpdatePath, file.Name);
                            Publish publish  = new Publish();
                            publish.GacInstall(fileName);
                            Trace.WriteLine(DateTime.Now.ToString() + ": Installed in GAC");
                        }
                    }
                    catch (Exception e)
                    {
                        Trace.WriteLine(DateTime.Now.ToString() + ": Got exception installing " +
                                        file.Name + ": " + e.Message);
                        // remove from list of updated files so that we try again
                        m_FileHash.Remove(file.Name);
                    }
                    dlg.ProgressBar.Increment(1);
                }

                RestartVisualStudio(dlg);
                dlg.Close();
            }
        }
Example #20
0
 public static void Setup()
 {
     publish = new Rescue().GoTo <Publish>();
     //browser = new IE("http://rescue.com:1010/");
 }
Example #21
0
        public void Can_serialize_Publish()
        {
            var message = new Publish("mytopic", "hello");

            AssertEqual(message);
        }
        public IHttpActionResult Publish([FromBody] Publish model)
        {
            var result = new ExamService().Publish(model);

            return(Ok(result));
        }
        static void SendStatusMessage()
        {
            WatchdogStatusMessage msg = new WatchdogStatusMessage(WatchdogComm.GetMachineName(), "", "No Publish Active", WatchdogStatusMessage.StatusLevel.NotRunning, Publish.GetAllPublishNames(pubRoot));

            if (curPublish == null)
            {
                msg.curPublishName = "";
                msg.statusText     = "No Publish Active";
                msg.statusLevel    = WatchdogStatusMessage.StatusLevel.NotRunning;
            }
            else
            {
                msg.curPublishName = curPublish.name;
                if (curPublish.IsCommandRunning())
                {
                    if (curPublish.watchdogAutoRestart)
                    {
                        msg.statusText = "Running. (WD)";
                    }
                    else
                    {
                        msg.statusText = "Running.";
                    }
                }
                else
                {
                    msg.statusText = "Stopped.";
                }
                if (curPublish.IsCommandRunning())
                {
                    msg.statusLevel = WatchdogStatusMessage.StatusLevel.Running;
                }
                else
                {
                    msg.statusLevel = WatchdogStatusMessage.StatusLevel.Error;
                }
            }
            comm.SendMessage(msg);
        }
 void On(Publish x) => observer.Notify(new Notification {
     Text = x.Text
 });
Example #25
0
        private void InstallProc(bool install)
        {
            Publish p = new Publish();

            string appPath = this.RegistryApplicationDirectory;

            try
            {
                if (install)
                {
                    System.Environment.SetEnvironmentVariable("GVIEW4_HOME", appPath, EnvironmentVariableTarget.Machine);
                }
                else
                {
                    System.Environment.SetEnvironmentVariable("GVIEW4_HOME", String.Empty, EnvironmentVariableTarget.Machine);
                }
            }
            catch { }

            DirectoryInfo di = new DirectoryInfo(Path.Combine(appPath, "Framework"));

            FileInfo[] dlls = di.GetFiles("*.dll");


            foreach (FileInfo fi in dlls)
            {
                if (install)
                {
                    p.GacInstall(fi.FullName);
                }
                else
                {
                    p.GacRemove(fi.FullName);
                }
            }

            // Set Envirment Variables
            string PATH      = System.Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine);
            string PATH2     = String.Empty;
            bool   foundPath = false;

            foreach (string path in PATH.Split(';'))
            {
                if (path.ToLower() != appPath.ToLower())
                {
                    if (PATH2 != String.Empty)
                    {
                        PATH2 += ";";
                    }
                    PATH2 += path;
                }
                else
                {
                    foundPath = true;
                }
            }

            if (install)
            {
                if (!foundPath)
                {
                    if (PATH2 != String.Empty)
                    {
                        PATH2 += ";";
                    }
                    PATH2 += appPath;

                    System.Environment.SetEnvironmentVariable("PATH", PATH2);
                }
            }
            else
            {
                if (foundPath)
                {
                    System.Environment.SetEnvironmentVariable("PATH", PATH2, EnvironmentVariableTarget.Machine);
                }
            }
        }
Example #26
0
        private void Form1_Shown(object sender, EventArgs e)
        {
            Publish p = new Publish();


            string appPath = Form1.RegistryApplicationDirectory;

            try
            {
                if (_install)
                {
                    System.Environment.SetEnvironmentVariable("GVIEW4_HOME", appPath + @"\", EnvironmentVariableTarget.Machine);
                }
                else
                {
                    System.Environment.SetEnvironmentVariable("GVIEW4_HOME", String.Empty, EnvironmentVariableTarget.Machine);
                }
            }
            catch { }

            DirectoryInfo di = new DirectoryInfo(Path.Combine(appPath, "Framework"));

            FileInfo[] dlls = di.GetFiles("*.dll");

            progressBar1.Minimum = 0;
            progressBar1.Maximum = dlls.Length;
            progressBar1.Value   = 0;

            foreach (FileInfo fi in dlls)
            {
                lblAssembly.Text = fi.FullName;
                this.Refresh();

                if (_install)
                {
                    p.GacInstall(fi.FullName);
                }
                else
                {
                    p.GacRemove(fi.FullName);
                }

                progressBar1.Value++;
                this.Refresh();

                System.Threading.Thread.Sleep(50);
            }

            // Set Envirment Variables
            string PATH      = System.Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine);
            string PATH2     = String.Empty;
            bool   foundPath = false;

            foreach (string path in PATH.Split(';'))
            {
                if (path.ToLower() != appPath.ToLower())
                {
                    if (PATH2 != String.Empty)
                    {
                        PATH2 += ";";
                    }
                    PATH2 += path;
                }
                else
                {
                    foundPath = true;
                }
            }

            if (_install)
            {
                if (!foundPath)
                {
                    if (PATH2 != String.Empty)
                    {
                        PATH2 += ";";
                    }
                    PATH2 += appPath;

                    System.Environment.SetEnvironmentVariable("PATH", PATH2);
                }
            }
            else
            {
                if (foundPath)
                {
                    System.Environment.SetEnvironmentVariable("PATH", PATH2, EnvironmentVariableTarget.Machine);
                }
            }

            // MapServer.Monitor Service installieren
            //try
            //{
            //    string filename = RegistryApplicationDirectory + @"\gView.MapServer.Monitor.exe";
            //    FileInfo fi = new FileInfo(filename);
            //    if (fi.Exists)
            //    {
            //        if (_install)
            //        {
            //            UInt32 result = (UInt32)mc.InvokeMethod("Install", new object[] { filename });
            //        }
            //        else
            //        {
            //            UInt32 result = (UInt32)mc.InvokeMethod("Uninstall", new object[] { filename });
            //        }
            //    }
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show("Can't " + (_install ? "install" : "uninstall") + " gView.MapServer.Monitor Service...\n" + ex.Message, "Warning");
            //}

            this.Close();
        }
        public void when_sending_publish_with_qos2_and_no_release_is_sent_after_receiving_publish_received_then_publish_received_is_re_transmitted()
        {
            var clientId = Guid.NewGuid().ToString();

            var configuration = new MqttConfiguration {
                MaximumQualityOfService = MqttQualityOfService.ExactlyOnce,
                WaitTimeoutSecs         = 1
            };
            var topicEvaluator     = new Mock <IMqttTopicEvaluator> ();
            var connectionProvider = new Mock <IConnectionProvider> ();
            var publishSenderFlow  = new Mock <IPublishSenderFlow> ();
            var retainedRepository = new Mock <IRepository <RetainedMessage> > ();
            var sessionRepository  = new Mock <IRepository <ClientSession> > ();
            var willRepository     = new Mock <IRepository <ConnectionWill> >();

            sessionRepository.Setup(r => r.Read(It.IsAny <string> ()))
            .Returns(new ClientSession(clientId)
            {
                PendingMessages = new List <PendingMessage> {
                    new PendingMessage()
                }
            });

            var packetIdProvider            = Mock.Of <IPacketIdProvider> ();
            var undeliveredMessagesListener = new Subject <MqttUndeliveredMessage> ();

            var topic = "foo/bar";

            var flow = new ServerPublishReceiverFlow(topicEvaluator.Object, connectionProvider.Object, publishSenderFlow.Object,
                                                     retainedRepository.Object, sessionRepository.Object, willRepository.Object, packetIdProvider, undeliveredMessagesListener, configuration);

            var subscribedClientId = Guid.NewGuid().ToString();
            var requestedQoS       = MqttQualityOfService.ExactlyOnce;
            var sessions           = new List <ClientSession> {
                new ClientSession(subscribedClientId, clean: false)
                {
                    Subscriptions = new List <ClientSubscription> {
                        new ClientSubscription {
                            ClientId = subscribedClientId, MaximumQualityOfService = requestedQoS, TopicFilter = topic
                        }
                    }
                }
            };

            var clientReceiver = new Subject <IPacket> ();
            var clientChannel  = new Mock <IMqttChannel <IPacket> > ();

            clientChannel.Setup(c => c.ReceiverStream).Returns(clientReceiver);

            topicEvaluator.Setup(e => e.Matches(It.IsAny <string> (), It.IsAny <string> ())).Returns(true);
            sessionRepository.Setup(r => r.ReadAll()).Returns(sessions.AsQueryable());

            var packetId = (ushort?)new Random().Next(0, ushort.MaxValue);
            var publish  = new Publish(topic, MqttQualityOfService.ExactlyOnce, retain: false, duplicated: false, packetId: packetId);

            publish.Payload = Encoding.UTF8.GetBytes("Publish Receiver Flow Test");

            var receiver = new Subject <IPacket> ();
            var sender   = new Subject <IPacket> ();
            var channel  = new Mock <IMqttChannel <IPacket> > ();

            channel.Setup(c => c.IsConnected).Returns(true);
            channel.Setup(c => c.ReceiverStream).Returns(receiver);
            channel.Setup(c => c.SenderStream).Returns(sender);
            channel.Setup(c => c.SendAsync(It.IsAny <IPacket> ()))
            .Callback <IPacket> (packet => sender.OnNext(packet))
            .Returns(Task.Delay(0));

            var publishReceivedSignal = new ManualResetEventSlim(initialState: false);
            var retries = 0;

            sender.Subscribe(packet => {
                if (packet is PublishReceived)
                {
                    retries++;
                }

                if (retries > 1)
                {
                    publishReceivedSignal.Set();
                }
            });

            var flowTask = flow.ExecuteAsync(clientId, publish, channel.Object);

            var retried = publishReceivedSignal.Wait(2000);

            Assert.True(retried);
            channel.Verify(c => c.SendAsync(It.Is <IPacket> (p => p is PublishReceived &&
                                                             (p as PublishReceived).PacketId == packetId)), Times.AtLeast(2));
        }
        static void comm_GotCommandMessage(object sender, WatchdogMessageEventArgs <CommandMessage> e)
        {
            if (!((e.msg.machineName.ToLower() == WatchdogComm.GetMachineName().ToLower()) || (e.msg.machineName == CommandMessage.ALLMACHINES)))
            {
                return;
            }

            Trace.WriteLine("Executing Command: " + e.msg.command.ToString());
            switch (e.msg.command)
            {
            case CommandMessage.WatchdogCommand.AddServiceRight:
                LocalSecurityPolicyManager.SetRight("labuser", LocalSecurityPolicyManager.ServiceRight);
                break;

            case CommandMessage.WatchdogCommand.EnableWatchdogAutoReset:
                if (curPublish != null)
                {
                    curPublish.watchdogAutoRestart = true; curPublish.Save(pubRoot);
                }
                break;

            case CommandMessage.WatchdogCommand.DisableWatchdogAutoReset:
                if (curPublish != null)
                {
                    curPublish.watchdogAutoRestart = false; curPublish.Save(pubRoot);
                }
                break;

            case CommandMessage.WatchdogCommand.Quit:
                KillApp();
                break;

            case CommandMessage.WatchdogCommand.StartRemoteDebugger:
                try
                {
                    Process[] p = Process.GetProcessesByName("msvsmon");
                    Trace.WriteLine("MSVSMONS : " + p.Length);
                    if (p.Length > 0)
                    {
                        foreach (Process mon in p)
                        {
                            mon.Kill();
                        }
                    }
                    Trace.WriteLine("Starting : " + pubRoot + "\\deployment\\debugger.bat");
                    ProcessStartInfo pi = new ProcessStartInfo(pubRoot + "\\deployment\\debugger.bat");
                    pi.WorkingDirectory = pubRoot + "\\deployment";
                    Process.Start(pi);
                }
                catch
                { }

                break;

            case CommandMessage.WatchdogCommand.RefreshPublishes:
                SendStatusMessage();
                break;

            case CommandMessage.WatchdogCommand.AutoDetectRunningPublish:
                if (curPublish == null)
                {
                    Publish autoP = AutodetectActivePublish();
                    if (autoP != null)
                    {
                        StartPublish(autoP.name);
                    }
                }
                break;
            }
        }
 private void Add(Publish item)
 {
     _data.Add(item);
     NotifyItemInserted(_data.Count - 1);
 }
        public static void MainLoop()
        {
            comm.GotStartPublishMessage      += new EventHandler <WatchdogMessageEventArgs <StartPublishMessage> >(comm_GotStartPublishMessage);
            comm.GotStopPublishMessage       += new EventHandler <WatchdogMessageEventArgs <StopPublishMessage> >(comm_GotStopPublishMessage);
            comm.GotWatchdogTerminateMessage += new EventHandler <WatchdogMessageEventArgs <WatchdogTerminateMessage> >(comm_GotWatchdogTerminateMessage);
            comm.GotCommandMessage           += new EventHandler <WatchdogMessageEventArgs <CommandMessage> >(comm_GotCommandMessage);

            Thread t = new Thread(new ThreadStart(StatusThread));

            t.Name = "Watchdog Status Thread";
            t.Start();
            Publish autoP = AutodetectActivePublish();

            if (autoP != null)
            {
                StartPublish(autoP.name);
            }
#if !SERVICE
            while (running)
            {
                string s = Console.ReadLine();
                if (s == null)
                {
                    continue;
                }
                if (s.StartsWith("load") && s.Split(" ".ToCharArray(), StringSplitOptions.None).Length > 1)                 //load a publish
                {
                    Trace.WriteLine("Loading " + s.Substring(s.IndexOf(" ") + 1));
                    curPublish = Publish.Load(s.Substring(s.IndexOf(" ") + 1), pubRoot);
                }
                if (s.StartsWith("show all"))
                {
                    foreach (string p in Publish.GetAllPublishNames(pubRoot))
                    {
                        Trace.WriteLine(p);
                    }
                }
                if (s.StartsWith("curpub"))
                {
                    if (curPublish == null)
                    {
                        Trace.WriteLine("No Publish Loaded.");
                    }
                    else
                    {
                        curPublish.PrintDebug();
                        Trace.WriteLine("Running: " + curPublish.IsCommandRunning());
                    }
                }
                if (s.StartsWith("start"))
                {
                    if (curPublish == null)
                    {
                        Trace.WriteLine("No publish loaded.");
                    }
                    else
                    {
                        curPublish.Start(pubRoot);
                    }
                }

                if (s.StartsWith("wdon"))
                {
                    if (curPublish == null)
                    {
                        Trace.WriteLine("No publish loaded.");
                    }
                    else
                    {
                        Trace.WriteLine("Enabling Watchdog...");
                        curPublish.watchdogAutoRestart = true;
                    }
                }

                if (s.StartsWith("wdoff"))
                {
                    if (curPublish == null)
                    {
                        Trace.WriteLine("No publish loaded.");
                    }
                    else
                    {
                        Trace.WriteLine("Disabling Watchdog...");
                        curPublish.watchdogAutoRestart = false;
                    }
                }
                if (s.StartsWith("list"))
                {
                    Process[]      parr             = Process.GetProcesses();
                    List <Process> runningProcesses = new List <Process>(parr);
                    foreach (Process filename in runningProcesses)
                    {
                        Trace.WriteLine(filename.ProcessName);
                    }
                }
            }
            t.Abort();
            traceText.Flush();
#endif
        }
Example #31
0
 public RevertOperation(Publish publish) : base(publish)
 {
 }
Example #32
0
 protected OperationBase(Publish publish) => Publish = publish;
Example #33
0
        /// <exception cref="MalformedMessageException">Exception is thrown in case of invalid packet format</exception>
        public static IByteBuffer encode(MQMessage header)
        {
            int         length = header.GetLength();
            IByteBuffer buf    = GetBuffer(length);
            MessageType type   = header.MessageType;

            switch (type)
            {
            case MessageType.CONNECT:
                Connect connect = (Connect)header;
                if (connect.Will != null && !connect.Will.IsValid())
                {
                    throw new MalformedMessageException("invalid will encoding");
                }

                buf.SetByte(0, (byte)(((Int32)type) << 4));
                buf.WriteShort(Connect.DEFAULT_PROTOCOL_LEVEL);
                buf.WriteBytes(Encoding.UTF8.GetBytes(connect.Name));
                buf.WriteByte(connect.ProtocolLevel);
                byte contentFlags = 0;
                if (connect.CleanSession)
                {
                    contentFlags += 0x02;
                }

                if (connect.Will != null)
                {
                    contentFlags += 0x04;
                    contentFlags += (byte)(((Int32)connect.Will.Topic.Qos) << 3);
                    if (connect.Will.Retain)
                    {
                        contentFlags += 0x20;
                    }
                }

                if (connect.Username != null)
                {
                    contentFlags += 0x40;
                }

                if (connect.Password != null)
                {
                    contentFlags += 0x80;
                }

                buf.WriteByte(contentFlags);
                buf.WriteShort(connect.Keepalive);
                buf.WriteShort(connect.ClientID.Length);
                buf.WriteBytes(Encoding.UTF8.GetBytes(connect.ClientID));

                if (connect.Will != null)
                {
                    String willTopic = connect.Will.Topic.Name;
                    if (willTopic != null)
                    {
                        buf.WriteShort(willTopic.Length);
                        buf.WriteBytes(Encoding.UTF8.GetBytes(willTopic));
                    }

                    byte[] willMessage = connect.Will.Content;
                    if (willMessage != null)
                    {
                        buf.WriteShort(willMessage.Length);
                        buf.WriteBytes(willMessage);
                    }
                }

                String username = connect.Username;
                if (username != null)
                {
                    buf.WriteShort(username.Length);
                    buf.WriteBytes(Encoding.UTF8.GetBytes(username));
                }

                String password = connect.Password;
                if (password != null)
                {
                    buf.WriteShort(password.Length);
                    buf.WriteBytes(Encoding.UTF8.GetBytes(password));
                }
                break;

            case MessageType.CONNACK:
                Connack connack = (Connack)header;
                buf.SetByte(0, (byte)(((Int32)type) << 4));
                buf.WriteBoolean(connack.SessionPresent);
                buf.WriteByte((Int32)connack.ReturnCode);
                break;

            case MessageType.PUBLISH:
                Publish publish   = (Publish)header;
                byte    firstByte = (byte)(((Int32)type) << 4);
                if (publish.Dup)
                {
                    firstByte += 0x08;
                }

                firstByte += (byte)(((Int32)publish.Topic.Qos) << 1);

                if (publish.Retain)
                {
                    firstByte += 0x01;
                }

                buf.SetByte(0, firstByte);
                buf.WriteShort(publish.Topic.Name.Length);
                buf.WriteBytes(Encoding.UTF8.GetBytes(publish.Topic.Name));
                if (publish.PacketID.HasValue)
                {
                    buf.WriteShort(publish.PacketID.Value);
                }
                buf.WriteBytes(publish.Content);
                break;

            case MessageType.PUBACK:
                Puback puback = (Puback)header;
                buf.SetByte(0, (byte)(((Int32)type) << 4));
                buf.WriteShort(puback.PacketID.Value);
                break;

            case MessageType.PUBREC:
                Pubrec pubrec = (Pubrec)header;
                buf.SetByte(0, (byte)(((Int32)type) << 4));
                buf.WriteShort(pubrec.PacketID.Value);
                break;

            case MessageType.PUBREL:
                Pubrel pubrel = (Pubrel)header;
                buf.SetByte(0, (byte)((((Int32)type) << 4) | 0x2));
                buf.WriteShort(pubrel.PacketID.Value);
                break;

            case MessageType.PUBCOMP:
                Pubcomp pubcomp = (Pubcomp)header;
                buf.SetByte(0, (byte)(((Int32)type) << 4));
                buf.WriteShort(pubcomp.PacketID.Value);
                break;

            case MessageType.SUBSCRIBE:
                Subscribe sub = (Subscribe)header;
                buf.SetByte(0, (byte)((((Int32)type) << 4) | 0x2));
                buf.WriteShort(sub.PacketID.Value);
                foreach (Topic subscription in sub.Topics)
                {
                    buf.WriteShort(subscription.Name.Length);
                    buf.WriteBytes(Encoding.UTF8.GetBytes(subscription.Name));
                    buf.WriteByte((Int32)subscription.Qos);
                }
                break;

            case MessageType.SUBACK:
                Suback suback = (Suback)header;
                buf.SetByte(0, (byte)(((Int32)type) << 4));
                buf.WriteShort(suback.PacketID.Value);
                foreach (SubackCode code in suback.ReturnCodes)
                {
                    buf.WriteByte((Int32)code);
                }
                break;

            case MessageType.UNSUBSCRIBE:
                Unsubscribe unsub = (Unsubscribe)header;
                buf.SetByte(0, (byte)((((Int32)type) << 4) | 0x2));
                buf.WriteShort(unsub.PacketID.Value);
                foreach (String topic in unsub.Topics)
                {
                    buf.WriteShort(topic.Length);
                    buf.WriteBytes(Encoding.UTF8.GetBytes(topic));
                }
                break;

            case MessageType.UNSUBACK:
                Unsuback unsuback = (Unsuback)header;
                buf.SetByte(0, (byte)(((Int32)type) << 4));
                buf.WriteShort(unsuback.PacketID.Value);
                break;

            case MessageType.DISCONNECT:
            case MessageType.PINGREQ:
            case MessageType.PINGRESP:
                buf.SetByte(0, (byte)(((Int32)type) << 4));
                break;

            default:
                throw new MalformedMessageException("Invalid header type: " + type);
            }

            return(buf);
        }
        public static void DownloadSDK(WebServiceHandler h)
        {
            const string _download = "/download/";
            const string a = @"assets/PromotionWebApplicationAssets";

            var path = h.Context.Request.Path;

            if (path == "/download")
            {
                //h.Context.Response.Redirect("/download/jsc.configuration.application");

                // F# redist
                h.Context.Response.Redirect("/download/jsc-web-installer.exe");
                h.CompleteRequest();
                return;
            }

            if (path == "/download/jsc-web-installer.exe")
            {
                // http://msdn.microsoft.com/en-us/library/h4k032e1.aspx
                // is chrome happier if we rename it?
                path = "/download/setup.exe";
            }

            if (path == "/download/")
            {
                var href = "http://www.jsc-solutions.net/download/jsc-web-installer.exe";

                var html = @"
                    <meta http-equiv='Refresh' target='_top' content='1;url=" + href + @"' />

                    
                    <center>
                    
                    <br />
                    <br />
                    <br />

<a href='" + href + @"'>Thank you for downloading JSC!</a>
                     
                    <br />
                    <br />
                    <br />
                    <br />
                    <br />

<div><i>Note that recent versions of <b>Google Chrome</b> may need additional time to verify.</i></div>                  
                                       
                                       </center>";

                h.Context.Response.ContentType = "text/html";

                var bytes = Encoding.UTF8.GetBytes(html);
                h.Context.Response.OutputStream.Write(bytes, 0, bytes.Length);
                h.CompleteRequest();
                return;
            }


#if !DEBUG
            // we will compare the win32 relative paths here...
            var publish = path.SkipUntilOrEmpty("/download/").Replace("/", @"\");
            
            var p = new Publish();

            if (p.ContainsKey(publish))
            {
                var f = p[publish];


                var ext = "." + f.SkipUntilLastOrEmpty(".").ToLower();

                // http://en.wikipedia.org/wiki/Mime_type
                // http://msdn.microsoft.com/en-us/library/ms228998.aspx

                var ContentType = "application/octet-stream";

                if (ext == ".application")
                {
                    ContentType = "application/x-ms-application";
                }
                else if (ext == ".manifest")
                {
                    ContentType = "application/x-ms-manifest";
                }
                else if (ext == ".htm")
                {
                    ContentType = "text/html";
                }

                h.Context.Response.ContentType = ContentType;

                //Console.WriteLine("length: " + data.Length + " " + ContentType + " " + f);


                DownloadSDKFile(h, f);


            }
#endif


            return;
        }
Example #35
0
        /// <exception cref="MalformedMessageException">Exception is thrown in case of invalid packet format</exception>
        public static MQMessage Decode(IByteBuffer buf)
        {
            MQMessage header = null;

            byte fixedHeader = buf.ReadByte();

            LengthDetails length = DecodeLength(buf);

            MessageType type = (MessageType)((fixedHeader >> 4) & 0xf);

            switch (type)
            {
            case MessageType.CONNECT:

                Byte[] nameValue = new byte[buf.ReadUnsignedShort()];
                buf.ReadBytes(nameValue, 0, nameValue.Length);
                String name = Encoding.UTF8.GetString(nameValue);
                if (!name.Equals(Connect.PROTOCOL_NAME))
                {
                    throw new MalformedMessageException("CONNECT, protocol-name set to " + name);
                }

                Byte protocolLevel = buf.ReadByte();
                Byte contentFlags  = buf.ReadByte();

                Boolean userNameFlag = (((contentFlags >> 7) & 1) == 1) ? true : false;
                Boolean userPassFlag = (((contentFlags >> 6) & 1) == 1) ? true : false;
                Boolean willRetain   = (((contentFlags >> 5) & 1) == 1) ? true : false;

                Int32 QOSValue = ((contentFlags & 0x1f) >> 3) & 3;
                QOS   willQos  = (QOS)QOSValue;
                if (!Enum.IsDefined(typeof(QOS), QOSValue))
                {
                    throw new MalformedMessageException("CONNECT, will QoS set to " + willQos);
                }
                Boolean willFlag = (((contentFlags >> 2) & 1) == 1) ? true : false;

                if (willQos != QOS.AT_MOST_ONCE && !willFlag)
                {
                    throw new MalformedMessageException("CONNECT, will QoS set to " + willQos + ", willFlag not set");
                }

                if (willRetain && !willFlag)
                {
                    throw new MalformedMessageException("CONNECT, will retain set, willFlag not set");
                }

                Boolean cleanSession = (((contentFlags >> 1) & 1) == 1) ? true : false;

                Boolean reservedFlag = ((contentFlags & 1) == 1) ? true : false;
                if (reservedFlag)
                {
                    throw new MalformedMessageException("CONNECT, reserved flag set to true");
                }

                int keepalive = buf.ReadUnsignedShort();

                Byte[] clientIdValue = new byte[buf.ReadUnsignedShort()];
                buf.ReadBytes(clientIdValue, 0, clientIdValue.Length);
                String clientID = Encoding.UTF8.GetString(clientIdValue);
                if (!StringVerifier.verify(clientID))
                {
                    throw new MalformedMessageException("ClientID contains restricted characters: U+0000, U+D000-U+DFFF");
                }

                String willTopic   = null;
                Byte[] willMessage = null;
                String username    = null;
                String password    = null;

                Will will = null;
                if (willFlag)
                {
                    if (buf.ReadableBytes < 2)
                    {
                        throw new MalformedMessageException("Invalid encoding will/username/password");
                    }

                    byte[] willTopicValue = new byte[buf.ReadUnsignedShort()];
                    if (buf.ReadableBytes < willTopicValue.Length)
                    {
                        throw new MalformedMessageException("Invalid encoding will/username/password");
                    }

                    buf.ReadBytes(willTopicValue, 0, willTopicValue.Length);

                    willTopic = Encoding.UTF8.GetString(willTopicValue);
                    if (!StringVerifier.verify(willTopic))
                    {
                        throw new MalformedMessageException("WillTopic contains one or more restricted characters: U+0000, U+D000-U+DFFF");
                    }

                    if (buf.ReadableBytes < 2)
                    {
                        throw new MalformedMessageException("Invalid encoding will/username/password");
                    }

                    willMessage = new byte[buf.ReadUnsignedShort()];
                    if (buf.ReadableBytes < willMessage.Length)
                    {
                        throw new MalformedMessageException("Invalid encoding will/username/password");
                    }

                    buf.ReadBytes(willMessage, 0, willMessage.Length);
                    if (willTopic.Length == 0)
                    {
                        throw new MalformedMessageException("invalid will encoding");
                    }
                    will = new Will(new Topic(willTopic, willQos), willMessage, willRetain);
                    if (!will.IsValid())
                    {
                        throw new MalformedMessageException("invalid will encoding");
                    }
                }

                if (userNameFlag)
                {
                    if (buf.ReadableBytes < 2)
                    {
                        throw new MalformedMessageException("Invalid encoding will/username/password");
                    }

                    byte[] userNameValue = new byte[buf.ReadUnsignedShort()];
                    if (buf.ReadableBytes < userNameValue.Length)
                    {
                        throw new MalformedMessageException("Invalid encoding will/username/password");
                    }

                    buf.ReadBytes(userNameValue, 0, userNameValue.Length);
                    username = Encoding.UTF8.GetString(userNameValue);
                    if (!StringVerifier.verify(username))
                    {
                        throw new MalformedMessageException("Username contains one or more restricted characters: U+0000, U+D000-U+DFFF");
                    }
                }

                if (userPassFlag)
                {
                    if (buf.ReadableBytes < 2)
                    {
                        throw new MalformedMessageException("Invalid encoding will/username/password");
                    }

                    byte[] userPassValue = new byte[buf.ReadUnsignedShort()];
                    if (buf.ReadableBytes < userPassValue.Length)
                    {
                        throw new MalformedMessageException("Invalid encoding will/username/password");
                    }

                    buf.ReadBytes(userPassValue, 0, userPassValue.Length);
                    password = Encoding.UTF8.GetString(userPassValue);
                    if (!StringVerifier.verify(password))
                    {
                        throw new MalformedMessageException("Password contains one or more restricted characters: U+0000, U+D000-U+DFFF");
                    }
                }

                if (buf.ReadableBytes > 0)
                {
                    throw new MalformedMessageException("Invalid encoding will/username/password");
                }

                Connect connect = new Connect(username, password, clientID, cleanSession, keepalive, will);
                if (protocolLevel != 4)
                {
                    connect.ProtocolLevel = protocolLevel;
                }
                header = connect;
                break;

            case MessageType.CONNACK:
                byte sessionPresentValue = buf.ReadByte();
                if (sessionPresentValue != 0 && sessionPresentValue != 1)
                {
                    throw new MalformedMessageException("CONNACK, session-present set to " + (sessionPresentValue & 0xff));
                }

                Boolean isPresent = sessionPresentValue == 1 ? true : false;

                Int32       connackByte = ((Int32)buf.ReadByte()) & 0xFF;
                ConnackCode connackCode = (ConnackCode)connackByte;
                if (!Enum.IsDefined(typeof(ConnackCode), connackByte))
                {
                    throw new MalformedMessageException("Invalid connack code: " + connackByte);
                }
                header = new Connack(isPresent, connackCode);
                break;

            case MessageType.PUBLISH:
                int dataLength = length.Length;
                fixedHeader &= 0xf;

                Boolean dup = (((fixedHeader >> 3) & 1) == 1) ? true : false;

                QOSValue = (fixedHeader & 0x07) >> 1;
                QOS qos = (QOS)QOSValue;
                if (!Enum.IsDefined(typeof(QOS), (byte)QOSValue))
                {
                    throw new MalformedMessageException("invalid QoS value");
                }
                if (dup && qos == QOS.AT_MOST_ONCE)
                {
                    throw new MalformedMessageException("PUBLISH, QoS-0 dup flag present");
                }

                Boolean retain = ((fixedHeader & 1) == 1) ? true : false;

                byte[] topicNameValue = new byte[buf.ReadUnsignedShort()];
                buf.ReadBytes(topicNameValue, 0, topicNameValue.Length);
                String topicName = Encoding.UTF8.GetString(topicNameValue);
                if (!StringVerifier.verify(topicName))
                {
                    throw new MalformedMessageException("Publish-topic contains one or more restricted characters: U+0000, U+D000-U+DFFF");
                }
                dataLength -= topicName.Length + 2;

                Int32?packetID = null;
                if (qos != QOS.AT_MOST_ONCE)
                {
                    packetID = buf.ReadUnsignedShort();
                    if (packetID < 0 || packetID > 65535)
                    {
                        throw new MalformedMessageException("Invalid PUBLISH packetID encoding");
                    }
                    dataLength -= 2;
                }
                byte[] data = new byte[dataLength];
                if (dataLength > 0)
                {
                    buf.ReadBytes(data, 0, data.Length);
                }
                header = new Publish(packetID, new Topic(topicName, qos), data, retain, dup);
                break;

            case MessageType.PUBACK:
                header = new Puback(buf.ReadUnsignedShort());
                break;

            case MessageType.PUBREC:
                header = new Pubrec(buf.ReadUnsignedShort());
                break;

            case MessageType.PUBREL:
                header = new Pubrel(buf.ReadUnsignedShort());
                break;

            case MessageType.PUBCOMP:
                header = new Pubcomp(buf.ReadUnsignedShort());
                break;

            case MessageType.SUBSCRIBE:
                Int32        subID         = buf.ReadUnsignedShort();
                List <Topic> subscriptions = new List <Topic>();
                while (buf.IsReadable())
                {
                    byte[] value = new byte[buf.ReadUnsignedShort()];
                    buf.ReadBytes(value, 0, value.Length);
                    QOSValue = buf.ReadByte();
                    QOS requestedQos = (QOS)QOSValue;
                    if (!Enum.IsDefined(typeof(QOS), QOSValue))
                    {
                        throw new MalformedMessageException("Subscribe qos must be in range from 0 to 2: " + requestedQos);
                    }
                    String topic = Encoding.UTF8.GetString(value);
                    if (!StringVerifier.verify(topic))
                    {
                        throw new MalformedMessageException("Subscribe topic contains one or more restricted characters: U+0000, U+D000-U+DFFF");
                    }
                    Topic subscription = new Topic(topic, requestedQos);
                    subscriptions.Add(subscription);
                }
                if (subscriptions.Count == 0)
                {
                    throw new MalformedMessageException("Subscribe with 0 topics");
                }

                header = new Subscribe(subID, subscriptions.ToArray());
                break;

            case MessageType.SUBACK:
                Int32             subackID    = buf.ReadUnsignedShort();
                List <SubackCode> subackCodes = new List <SubackCode>();
                while (buf.IsReadable())
                {
                    Int32      subackByte = ((Int32)buf.ReadByte()) & 0xFF;
                    SubackCode subackCode = (SubackCode)subackByte;
                    if (!Enum.IsDefined(typeof(SubackCode), subackByte))
                    {
                        throw new MalformedMessageException("Invalid suback code: " + subackByte);
                    }
                    subackCodes.Add(subackCode);
                }
                if (subackCodes.Count == 0)
                {
                    throw new MalformedMessageException("Suback with 0 return-codes");
                }

                header = new Suback(subackID, subackCodes);
                break;

            case MessageType.UNSUBSCRIBE:
                Int32         unsubID           = buf.ReadUnsignedShort();
                List <String> unsubscribeTopics = new List <String>();
                while (buf.IsReadable())
                {
                    byte[] value = new byte[buf.ReadUnsignedShort()];
                    buf.ReadBytes(value, 0, value.Length);
                    String topic = Encoding.UTF8.GetString(value);
                    if (!StringVerifier.verify(topic))
                    {
                        throw new MalformedMessageException("Unsubscribe topic contains one or more restricted characters: U+0000, U+D000-U+DFFF");
                    }
                    unsubscribeTopics.Add(topic);
                }
                if (unsubscribeTopics.Count == 0)
                {
                    throw new MalformedMessageException("Unsubscribe with 0 topics");
                }
                header = new Unsubscribe(unsubID, unsubscribeTopics.ToArray());
                break;

            case MessageType.UNSUBACK:
                header = new Unsuback(buf.ReadUnsignedShort());
                break;

            case MessageType.PINGREQ:
                header = new Pingreq();
                break;

            case MessageType.PINGRESP:
                header = new Pingresp();
                break;

            case MessageType.DISCONNECT:
                header = new Disconnect();
                break;

            default:
                throw new MalformedMessageException("Invalid header type: " + type);
            }

            if (buf.IsReadable())
            {
                throw new MalformedMessageException("unexpected bytes in content");
            }

            if (length.Length != header.GetLength())
            {
                throw new MalformedMessageException("Invalid length. Encoded: " + length.Length + ", actual: " + header.GetLength());
            }

            return(header);
        }
Example #36
0
 public void Handle(Publish req)
 {
     buffer.Enqueue(req.Event);
 }
        public void when_sending_publish_with_qos2_and_publish_received_is_not_received_then_publish_is_re_transmitted()
        {
            var clientId = Guid.NewGuid().ToString();

            var configuration      = Mock.Of <MqttConfiguration> (c => c.WaitTimeoutSecs == 1 && c.MaximumQualityOfService == MqttQualityOfService.ExactlyOnce);
            var connectionProvider = new Mock <IConnectionProvider> ();
            var sessionRepository  = new Mock <IRepository <ClientSession> > ();

            sessionRepository.Setup(r => r.Get(It.IsAny <Expression <Func <ClientSession, bool> > > ()))
            .Returns(new ClientSession {
                ClientId        = clientId,
                PendingMessages = new List <PendingMessage> {
                    new PendingMessage()
                }
            });

            var flow = new PublishSenderFlow(sessionRepository.Object, configuration);

            var topic    = "foo/bar";
            var packetId = (ushort?)new Random().Next(0, ushort.MaxValue);
            var publish  = new Publish(topic, MqttQualityOfService.ExactlyOnce, retain: false, duplicated: false, packetId: packetId);

            publish.Payload = Encoding.UTF8.GetBytes("Publish Receiver Flow Test");

            var receiver = new Subject <IPacket> ();
            var sender   = new Subject <IPacket> ();
            var channel  = new Mock <IMqttChannel <IPacket> > ();

            channel.Setup(c => c.IsConnected).Returns(true);
            channel.Setup(c => c.ReceiverStream).Returns(receiver);
            channel.Setup(c => c.SenderStream).Returns(sender);
            channel.Setup(c => c.SendAsync(It.IsAny <IPacket> ()))
            .Callback <IPacket> (packet => sender.OnNext(packet))
            .Returns(Task.Delay(0));

            connectionProvider.Setup(m => m.GetConnection(It.IsAny <string> ())).Returns(channel.Object);

            var retrySignal = new ManualResetEventSlim(initialState: false);
            var retries     = 0;

            sender.Subscribe(p => {
                if (p is Publish)
                {
                    retries++;
                }

                if (retries > 1)
                {
                    retrySignal.Set();
                }
            });

            var flowTask = flow.SendPublishAsync(clientId, publish, channel.Object);

            var retried = retrySignal.Wait(2000);

            Assert.True(retried);
            channel.Verify(c => c.SendAsync(It.Is <IPacket> (p => p is Publish &&
                                                             ((Publish)p).Topic == topic &&
                                                             ((Publish)p).QualityOfService == MqttQualityOfService.ExactlyOnce &&
                                                             ((Publish)p).PacketId == packetId)), Times.AtLeast(2));
        }
        public Analyze Analyze(string host, Publish publish, StartNew startNew, FromCache fromCache, int? maxHours, All all, IgnoreMismatch ignoreMismatch)
        {
            var analyzeModel = new Analyze();

            // Checking host is valid before continuing
            if (!_urlValidation.IsValid(host))
            {
                analyzeModel.HasErrorOccurred = true;
                analyzeModel.Errors.Add(new Error { message = "Host does not pass preflight validation. No Api call has been made." });
                return analyzeModel;
            }

            // Building request model
            var requestModel = _requestModelFactory.NewAnalyzeRequestModel(ApiUrl, "analyze", host, publish.ToString().ToLower(), startNew.ToString().ToLower(),
                fromCache.ToString().ToLower(), maxHours, all.ToString().ToLower(), ignoreMismatch.ToString().ToLower());

            try
            {
                var webResponse = _apiProvider.MakeGetRequest(requestModel);
                analyzeModel = _responsePopulation.AnalyzeModel(webResponse, analyzeModel);
            }
            catch (Exception ex)
            {
                analyzeModel.HasErrorOccurred = true;
                analyzeModel.Errors.Add(new Error { message = ex.ToString() });
            }

            // Checking if errors have occoured either from ethier api or wrapper
            if (analyzeModel.Errors.Count != 0 && !analyzeModel.HasErrorOccurred) { analyzeModel.HasErrorOccurred = true; }

            return analyzeModel;
        }
Example #39
0
        public ActionResult UpdatePublish(int id, string PubInvoiceList)
        {
            if (id <= 0)
            {
                throw new HttpRequestValidationException();
            }
            IPublishService      pubSrc = IoC.Resolve <IPublishService>();
            ITaxAuthorityService taxSrv = IoC.Resolve <ITaxAuthorityService>();
            Publish opub = pubSrc.Getbykey(id);

            try
            {
                TryUpdateModel <Publish>(opub);
                opub.TaxAuthorityName = (from tax in taxSrv.Query where tax.Code == opub.TaxAuthorityCode select tax.Name).FirstOrDefault();
                JavaScriptSerializer   jss = new JavaScriptSerializer();
                IList <PublishInvoice> lst = jss.Deserialize <IList <PublishInvoice> >(PubInvoiceList);
                foreach (var it in lst)
                {
                    IPublishInvoiceService pubinvSrv = IoC.Resolve <IPublishInvoiceService>();
                    ICompanyService        _comSrv   = IoC.Resolve <ICompanyService>();
                    Company _currentcompany          = _comSrv.Getbykey(((EInvoiceContext)FXContext.Current).CurrentCompany.id);
                    string  invSer = string.Format("{0}/{1}E", it.InvSerialPrefix, it.InvSerialSuffix);
                    var     old    = pubinvSrv.Query.Where(p => p.RegisterID == it.RegisterID && p.InvSerial == invSer && p.StartDate > it.StartDate && p.FromNo < it.FromNo && p.ComId == _currentcompany.id).FirstOrDefault();
                    if (old != null)
                    {
                        Messages.AddErrorMessage(string.Format("Thông báo có ký hiệu {0}, phải có ngày bắt đầu từ ngày: {1}", old.InvSerial, old.StartDate.ToString("dd/MM/yyyy")));
                        PublishModel model = new PublishModel();
                        model.mPublish = opub;
                        ITaxAuthorityService taxSrc = IoC.Resolve <ITaxAuthorityService>();
                        model.TaxList = new SelectList(from tax in taxSrc.Query select tax, "Code", "Name", opub.TaxAuthorityCode);
                        IRegisterTempService regisSrc = IoC.Resolve <IRegisterTempService>();
                        model.RegTempList    = new SelectList(from re in regisSrc.Query where re.ComId == _currentcompany.id select re, "Id", "Name");
                        model.PubInvoiceList = opub.PublishInvoices.SerializeJSON <PublishInvoice>();
                        return(View("EditRPublish", model));
                    }
                    else
                    {
                        old = pubinvSrv.Query.Where(p => p.RegisterID == it.RegisterID && p.InvSerial == invSer && p.StartDate <it.StartDate && p.FromNo> it.FromNo && p.ComId == _currentcompany.id).FirstOrDefault();
                        if (old != null)
                        {
                            Messages.AddErrorMessage(string.Format("Thông báo có ký hiệu {0}, phải có ngày bắt đầu nhỏ hơn ngày: {1}", old.InvSerial, old.StartDate.ToString("dd/MM/yyyy")));
                            PublishModel model = new PublishModel();
                            model.mPublish = opub;
                            ITaxAuthorityService taxSrc = IoC.Resolve <ITaxAuthorityService>();
                            model.TaxList = new SelectList(from tax in taxSrc.Query select tax, "Code", "Name", opub.TaxAuthorityCode);
                            IRegisterTempService regisSrc = IoC.Resolve <IRegisterTempService>();
                            model.RegTempList    = new SelectList(from re in regisSrc.Query where re.ComId == _currentcompany.id select re, "Id", "Name");
                            model.PubInvoiceList = opub.PublishInvoices.SerializeJSON <PublishInvoice>();
                            return(View("EditRPublish", model));
                        }
                    }
                }
                string mess = "";
                if (pubSrc.Update(opub, lst, out mess) == true)
                {
                    StringBuilder InvInfo = new StringBuilder();
                    for (int i = 0; i < lst.Count; i++)
                    {
                        InvInfo.AppendFormat("{0};{1};{2};{3};{4}_", lst[i].RegisterID, lst[i].InvSerial, lst[i].Quantity, lst[i].FromNo, lst[i].ToNo);
                    }
                    log.Info("Edit Publish by: " + HttpContext.User.Identity.Name + "|InvInfo:" + InvInfo.ToString());
                    Messages.AddFlashMessage("Sửa thành công");
                    return(RedirectToAction("Index"));
                }
                else
                {
                    log.Error("Update Publish:" + mess);
                    ICompanyService _comSrv         = IoC.Resolve <ICompanyService>();
                    Company         _currentcompany = _comSrv.Getbykey(((EInvoiceContext)FXContext.Current).CurrentCompany.id);
                    PublishModel    model           = new PublishModel();
                    model.mPublish = opub;
                    ITaxAuthorityService taxSrc = IoC.Resolve <ITaxAuthorityService>();
                    model.TaxList = new SelectList(from tax in taxSrc.Query select tax, "Code", "Name", opub.TaxAuthorityCode);
                    IRegisterTempService regisSrc = IoC.Resolve <IRegisterTempService>();
                    model.RegTempList    = new SelectList(from re in regisSrc.Query where re.ComId == _currentcompany.id select re, "Id", "Name");
                    model.PubInvoiceList = opub.PublishInvoices.SerializeJSON <PublishInvoice>();
                    Messages.AddErrorMessage(mess);
                    return(View("EditRPublish", model));
                }
            }
            catch (Exception ex)
            {
                log.Error("EditRPublish -" + ex);
                Messages.AddErrorMessage("Có lỗi xảy ra, vui lòng thực hiện lại!");
                PublishModel model = new PublishModel();
                model.mPublish = opub;
                ICompanyService      _comSrv         = IoC.Resolve <ICompanyService>();
                Company              _currentcompany = _comSrv.Getbykey(((EInvoiceContext)FXContext.Current).CurrentCompany.id);
                ITaxAuthorityService taxSrc          = IoC.Resolve <ITaxAuthorityService>();
                model.TaxList = new SelectList(from tax in taxSrc.Query select tax, "Code", "Name", opub.TaxAuthorityCode);
                IRegisterTempService regisSrc = IoC.Resolve <IRegisterTempService>();
                model.RegTempList    = new SelectList(from re in regisSrc.Query where re.ComId == _currentcompany.id select re, "Id", "Name");
                model.PubInvoiceList = opub.PublishInvoices.SerializeJSON <PublishInvoice>();
                return(View("EditRPublish", model));
            }
        }