public void ProcessRequest(HttpContext context)
        {
            try
            {
                // Local Variables.
                string uRequestID = String.Empty;
                string uStatus = String.Empty;
                String SOAPEndPoint = context.Session["SOAPEndPoint"].ToString();
                String internalOauthToken = context.Session["internalOauthToken"].ToString();
                String id = context.Request.QueryString["id"].ToString().Trim();
                String status = context.Request.QueryString["status"].ToString().Trim();

                // Create the SOAP binding for call.
                BasicHttpBinding binding = new BasicHttpBinding();
                binding.Name = "UserNameSoapBinding";
                binding.Security.Mode = BasicHttpSecurityMode.TransportWithMessageCredential;
                binding.MaxReceivedMessageSize = 2147483647;
                var client = new SoapClient(binding, new EndpointAddress(new Uri(SOAPEndPoint)));
                client.ClientCredentials.UserName.UserName = "******";
                client.ClientCredentials.UserName.Password = "******";

                using (var scope = new OperationContextScope(client.InnerChannel))
                {
                    // Add oAuth token to SOAP header.
                    XNamespace ns = "http://exacttarget.com";
                    var oauthElement = new XElement(ns + "oAuthToken", internalOauthToken);
                    var xmlHeader = MessageHeader.CreateHeader("oAuth", "http://exacttarget.com", oauthElement);
                    OperationContext.Current.OutgoingMessageHeaders.Add(xmlHeader);

                    // Setup Subscriber Object to pass fields for updating.
                    Subscriber sub = new Subscriber();
                    sub.ID = int.Parse(id);
                    sub.IDSpecified = true;
                    if (status.ToLower() == "unsubscribed")
                        sub.Status = SubscriberStatus.Unsubscribed;
                    else
                        sub.Status = SubscriberStatus.Active;
                    sub.StatusSpecified = true;

                    // Call the Update method on the Subscriber object.
                    UpdateResult[] uResults = client.Update(new UpdateOptions(), new APIObject[] { sub }, out uRequestID, out uStatus);

                    if (uResults != null && uStatus.ToLower().Equals("ok"))
                    {
                        String strResults = string.Empty;
                        strResults += uResults;
                        // Return the update results from handler.
                        context.Response.Write(strResults);
                    }
                    else
                    {
                        context.Response.Write("Not OK!");
                    }
                }
            }
            catch (Exception ex)
            {
                context.Response.Write(ex);
            }
        }
        public Task Subscribe(Subscriber subscriber, MessageType messageType, ContextBag context)
        {
            var dict = storage.GetOrAdd(messageType, type => new ConcurrentDictionary<string, Subscriber>(StringComparer.OrdinalIgnoreCase));

            dict.AddOrUpdate(subscriber.TransportAddress, _ => subscriber, (_, __) => subscriber);
            return TaskEx.CompletedTask;
        }
 public ManageSubscription(GenThreadManager genThreadManager, SystemServices systemServices, 
     Subscriber.MyTransientSubscriber subscriber, IUpdateDials updateDials)
     : base(genThreadManager, systemServices)
 {
     Subscriber = subscriber;
     UpdateDials = updateDials;
 }
        public ActionResult Index(Subscriber input)
        {
            if (!IsValidEmailAddress (input.Email)) {
                ModelState.AddModelError ("Email", "No es una dirección de email válida.");
            }

            if (ModelState.IsValid) {
                Subscriber item = Subscriber.TryFind (input.Email);

                if (item == null) {
                    using (var session = new SessionScope()) {
                        input.IsActive = true;
                        input.CreateAndFlush ();
                    }
                } else {
                    using (var session = new SessionScope()) {
                        item.IsActive = true;
                        item.UpdateAndFlush ();
                    }
                }

                return PartialView ("_Success");
            }

            return PartialView ("_Form", input);
        }
 static void Main(string[] args)
 {
     Publisher publish = new Publisher();
     Subscriber sub = new Subscriber(publish);
     CustemerEventArgs arg = new CustemerEventArgs(3000);
     publish.DoSomething(arg);
 }
Example #6
0
 public void ConnectToBrokerAsClient(Config nbConfig)
 {
     subscriber = new Subscriber(nbConfig);
     subscriber.NotificationHandlers = new BrokerConnectionNotifier.NotificationEventHandler[]{
         OnNotification
                     };
 }
Example #7
0
        static void Main(string[] args)
        {
            /*
             * Make sure this path contains the umundoNativeCSharp.dll!
             */
            SetDllDirectory("C:\\Users\\sradomski\\Desktop\\build\\umundo\\lib");
            org.umundo.core.Node node = new org.umundo.core.Node();
            Publisher pub = new Publisher("pingpong");
            PingReceiver recv = new PingReceiver();
            Subscriber sub = new Subscriber("pingpong", recv);
            node.addPublisher(pub);
            node.addSubscriber(sub);

            while (true)
            {
                Message msg = new Message();
                String data = "data";
                System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
                byte[] buffer = enc.GetBytes(data);
                msg.setData(buffer);
                msg.putMeta("foo", "bar");
                Console.Write("o");
                pub.send(msg);
                System.Threading.Thread.Sleep(1000);
            }
        }
Example #8
0
        public static void Main()
        {
            ComputerSpecifications.Dump();

            var running = new AtomicBoolean(true);
            
            using (var aeron = Aeron.Connect())
            using (var publication = aeron.AddPublication(Channel, StreamID))
            using (var subscription = aeron.AddSubscription(Channel, StreamID))
            {
                var subscriber = new Subscriber(running, subscription);
                var subscriberThread = new Thread(subscriber.Run) {Name = "subscriber"};
                var publisherThread = new Thread(new Publisher(running, publication).Run) {Name = "publisher"};
                var rateReporterThread = new Thread(new RateReporter(running, subscriber).Run) {Name = "rate-reporter"};

                rateReporterThread.Start();
                subscriberThread.Start();
                publisherThread.Start();

                Console.WriteLine("Press any key to stop...");
                Console.Read();

                running.Set(false);
                
                subscriberThread.Join();
                publisherThread.Join();
                rateReporterThread.Join();
            }
        }
        public void One_Publisher_One_Subscriber_Batch_Broadcast()
        {
            using (var publisher = new Publisher())
            using (var subscriber = new Subscriber())
            {
                var endpoint = GetEndpoint();
                publisher.Bind(endpoint);
                subscriber.Connect(endpoint);

                Thread.Sleep(100);

                var counterSignal = new CounterSignal(NumberOfMessagesToReceive);
                subscriber.MessageReceived += (s, m) => counterSignal.Increment();

                var messageSent = new TestMessage();

                var batch = new List<TestMessage>();
                for (var i = 0; i < NumberOfMessagesToReceive; i++)
                    batch.Add(messageSent);

                var sw = Stopwatch.StartNew();
                publisher.Broadcast(batch);
                Assert.IsTrue(counterSignal.Wait(TimeOut), "Timeout waiting for message");
                sw.Stop();

                Assert.Inconclusive("{0} elapsed reading {1} messages ({2:N0} per second)", sw.Elapsed, NumberOfMessagesToReceive, NumberOfMessagesToReceive / sw.Elapsed.TotalSeconds);
            }
        }
        public static void UpdateSubscriber(SoapClient soapClient,
            string iEmailAddress,
            int iListID)
        {
            Subscriber sub = new Subscriber();
            sub.EmailAddress = iEmailAddress;

            // Define the SubscriberList and set the status to Active
            SubscriberList subList = new SubscriberList();
            subList.ID = iListID;
            subList.IDSpecified = true;
            subList.Status = SubscriberStatus.Active;
            // If no Action is specified at the SubscriberList level, the default action is to
            // update the subscriber if they already exist and create them if they do not.
            // subList.Action = "create";

            //Relate the SubscriberList defined to the Subscriber
            sub.Lists = new SubscriberList[] { subList };

            string sStatus = "";
            string sRequestId = "";

            UpdateResult[] uResults =
                soapClient.Update(new UpdateOptions(), new APIObject[] { sub }, out sRequestId, out sStatus);

            Console.WriteLine("Status: " + sStatus);
            Console.WriteLine("Request ID: " + sRequestId);
            foreach (UpdateResult ur in uResults)
            {
                Console.WriteLine("StatusCode: " + ur.StatusCode);
                Console.WriteLine("StatusMessage: " + ur.StatusMessage);
                Console.WriteLine("ErrorCode: " + ur.ErrorCode);
            }
        }
        static void Main(string[] args)
        {
            string connectionString = "MyConnectionString";

            const string topicName = "shopify-notifications";

            Publisher publisher = new Publisher(topicName, connectionString);
            
            Subscriber subscriber = new Subscriber(topicName, connectionString);

            subscriber.Subscribe<SampleEvent>("SampleEvents", message => Console.WriteLine(
                String.Format("received message with id \"{0}\" and content \"{1}\"", message.MessageId,
                    message.GetBody().Message)));

            while (true)
            {
                Console.WriteLine("Write something to send a message:");
                string message = Console.ReadLine();

                if (!string.IsNullOrEmpty(message))
                {
                    var publishMessage = PublishMessage.Create(new SampleEvent(message), Guid.NewGuid().ToString());
                    publisher.Send(publishMessage);
                }
            }
        }
 static void Main()
 {
     Console.WriteLine ("Starting");
     IceApp app = null;
     Subscriber sub = null;
     try
     {
         app = new IceApp("MyTestAdapter", "localhost", 12000);
         sub = new Subscriber(app, "MyTestHolon");
         Thread.Sleep(100000);
     }
     catch (Exception ex)
     {
         Console.WriteLine("Catching" + ex);
     }
     finally
     {
         if (sub != null )
         {
             sub.shutdown();
         }
         if ( app != null )
         {
             app.shutdown();
         }
     }
 }
Example #13
0
        private void OnAddSubcriber_Click(object sender, RoutedEventArgs e)
        {
            string currentMSISDN = this.SubscriberMSISDN.Text;
            string currentName = this.SubscriberName.Text;
            string currentEGN = this.SubscriberEGN.Text;
            string currentTariffPlan = defaultTariffPlan;
            double account = 0;
            Subscriber currentSubscriber = new Subscriber(currentMSISDN, currentName, currentEGN);

            //work with Hashset
            Subscriber.AddSubscriber(currentSubscriber);

            if (this.SubscriberTariffPlan.SelectedItem != null)
            {
                currentTariffPlan = this.SubscriberTariffPlan.SelectedItem.ToString();
                currentSubscriber.ChangeTariffPlan(currentTariffPlan);
            }

            if (this.SubscriberAccount.Text != null)
            {
                account = double.Parse(this.SubscriberAccount.Text.ToString());
                currentSubscriber.UpdateAccount(account);
            }

            billingSystemDB.InsertSubscriber(currentSubscriber);

            SubscriberAllTextBoxInit(sender, e);
        }
        public ActionResult Create(Subscriber subscriber)
        {
            //chamada ao webservice
            _webService.AddorUpdateSubscriber(subscriber.Name, subscriber.Email, subscriber.IsActive);

            return RedirectToAction("Index", this);
        }
 public void SetUp()
 {
     _sut = CreateSUT();
     _resolver = new Mock<IBusinessPartnerSpecificServiceResolver>();
     _resolver.Setup(r => r.GetBuildValueFactoryFor(BusinessPartner.Initech)).Returns(new InitechBuildValueFactory());
     _seg = new SegmentFactory(_resolver.Object);
 }
        public void Trigger(ExactTargetTriggeredEmail exactTargetTriggeredEmail, RequestQueueing requestQueueing = RequestQueueing.No, Priority priority = Priority.Normal)
        {
            var clientId = _config.ClientId;
            var client = SoapClientFactory.Manufacture(_config);

            var subscriber = new Subscriber
            {
                EmailAddress = exactTargetTriggeredEmail.EmailAddress,
                SubscriberKey = exactTargetTriggeredEmail.SubscriberKey ?? exactTargetTriggeredEmail.EmailAddress,
                Attributes =
                    exactTargetTriggeredEmail.ReplacementValues.Select(value => new Attribute
                    {
                        Name = value.Key,
                        Value = value.Value
                    }).ToArray()
            };

            // Add sender information if specified. This will send the email with FromAddress in the sender field.
            // Official doco here under the section "Determining the From Information at Send Time":
            // https://help.exacttarget.com/en/technical_library/web_service_guide/triggered_email_scenario_guide_for_developers/#Determining_the_From_Information_at_Send_Time
            if (!string.IsNullOrEmpty(exactTargetTriggeredEmail.FromAddress) && !string.IsNullOrEmpty(exactTargetTriggeredEmail.FromName))
            {
                subscriber.Owner = new Owner()
                {
                    FromAddress = exactTargetTriggeredEmail.FromAddress,
                    FromName = exactTargetTriggeredEmail.FromName
                };
            }

            var subscribers = new List<Subscriber> { subscriber };

            var tsd = new TriggeredSendDefinition
            {
                Client = clientId.HasValue ? new ClientID { ID = clientId.Value, IDSpecified = true } : null,
                CustomerKey = exactTargetTriggeredEmail.ExternalKey
            };

            var ts = new TriggeredSend
            {
                Client = clientId.HasValue ? new ClientID { ID = clientId.Value, IDSpecified = true } : null,
                TriggeredSendDefinition = tsd,
                Subscribers = subscribers.ToArray()
            };

            var co = new CreateOptions
            {
                RequestType = requestQueueing == RequestQueueing.No ? RequestType.Synchronous : RequestType.Asynchronous,
                RequestTypeSpecified = true,
                QueuePriority = priority == Priority.High ? ExactTargetApi.Priority.High : ExactTargetApi.Priority.Medium,
                QueuePrioritySpecified = true
            };

            string requestId, status;
            var result = client.Create(
                co,
                new APIObject[] { ts },
                out requestId, out status);

            ExactTargetResultChecker.CheckResult(result.FirstOrDefault()); //we expect only one result because we've sent only one APIObject
        }
        public ActionResult Edit(Subscriber subscriber)
        {
            //Edicao feita diretamente atraves do webservice
            _webService.AddorUpdateSubscriber(subscriber.Name, subscriber.Email, subscriber.IsActive);

            return RedirectToAction("Index", this);
        }
Example #18
0
 static void Main()
 {
     Timer timer = new Timer();
     Subscriber sub = new Subscriber();
     sub.Subscribe(timer);
     timer.RepeatWithDelegate(Subscriber.PrintHeart, 1,5);
 }
Example #19
0
        public void EventでUnsubscribe()
        {
            var subscriber = new Subscriber();

            int callNum1 = 0;
            int callNum2 = 0;
            int callNum3 = 0;
            subscriber.Subscribe("topic1", () => { callNum1++; });
            var e = subscriber.Subscribe("topic1", () => { callNum2++; });
            subscriber.Subscribe("topic2", () => { callNum3++; });

            subscriber.Call("topic1");
            subscriber.Call("topic2");
            subscriber.Call("topic1");
            subscriber.Call("topic2");

            subscriber.Unsubscribe(e);

            subscriber.Call("topic1");
            subscriber.Call("topic2");
            subscriber.Call("topic1");
            subscriber.Call("topic2");
            Assert.AreEqual(callNum1, 4);
            Assert.AreEqual(callNum2, 2);
            Assert.AreEqual(callNum3, 4);
        }
Example #20
0
 /// <summary>
 /// Called when subscriber is updates.
 /// </summary>
 /// <param name="subscriber">The subscriber.</param>
 public void OnSubscriberUpdated(Subscriber subscriber)
 {
     if (SubscriberUpdated != null)
     {
         SubscriberUpdated(new SingleItemEventArgs<Subscriber>(subscriber));
     }
 }
        public void FireGenericEventArgs(
            Publisher publisher,
            Subscriber subscriber)
        {
            const int Value = 42;

            "establish a publisher firing an event with generic event args"._(() =>
                {
                    publisher = new Publisher();
                });

            "establish a subscriber listening to the event of the publisher"._(() =>
                {
                    subscriber = new Subscriber();

                    subscriber.RegisterEvent(publisher);
                });

            "when the publisher fires the event"._(() =>
                {
                    publisher.FireEvent(Value);
                });

            "it should pass value to event handler"._(() =>
                {
                    subscriber.ReceivedValue
                        .Should().Be(Value);
                });
        }
Example #22
0
        protected override void Initialize()
        {
            quad = new Quad[6];
            quad[0] = new Quad(Vector3.Backward, Vector3.Backward, Vector3.Up, 2, 2);
            quad[1] = new Quad(Vector3.Left, Vector3.Left, Vector3.Up, 2, 2);
            quad[2] = new Quad(Vector3.Right, Vector3.Right, Vector3.Up, 2, 2);
            quad[3] = new Quad(Vector3.Forward, Vector3.Forward, Vector3.Up, 2, 2);
            quad[4] = new Quad(Vector3.Down, Vector3.Down, Vector3.Right, 2, 2);
            quad[5] = new Quad(Vector3.Up, Vector3.Up, Vector3.Left, 2, 2);
            nh = new NodeHandle();
            imgSub = nh.subscribe<Messages.sensor_msgs.Image>("/camera/rgb/image_rect_color", 1, (img) =>
                                                                    {
                                                                        if (padlock.WaitOne(10))
                                                                        {
                                                                            if (next_texture == null)
                                                                            {
                                                                                next_texture = new Texture2D(GraphicsDevice, (int) img.width, (int) img.height);
                                                                            }
                                                                            util.UpdateImage(GraphicsDevice, img.data, new Size((int)img.width, (int)img.height), ref next_texture, img.encoding.data);
                                                                            padlock.ReleaseMutex();
                                                                        }
                                                                    });

            base.Initialize();
        }
Example #23
0
 public void IsDisconnected_should_return_true_when_not_connected()
 {
     using (var subscriber = new Subscriber())
     {
         Assert.IsTrue(subscriber.IsDisconnected);
     }
 }
Example #24
0
        public void SendMessageToSubscriber()
        {
            var sender = new Sender();
            var s = new Subscriber();
            sender.Send(180);

            Assert.That(s.Value, Is.EqualTo(180));
        }
Example #25
0
 public void SubscribeNewsLetterCheckBox_CheckedChanged(object sender, EventArgs e)
 {
     MembershipUser user = Membership.GetUser();
     Subscriber subscriberInfo = new Subscriber();
     subscriberInfo.Email = user.Email;
     subscriberInfo.SubscribedStatus = SubscribeNewsLetterCheckBox.Checked;
     Subscriber.ResetSubscription(subscriberInfo);
 }
Example #26
0
 public void startListening(NodeHandle nh)
 {
     updater = new DispatcherTimer() { Interval = new TimeSpan(0, 0, 0, 0, 100) };
     updater.Tick += Link;
     updater.Start();
     sub = nh.subscribe<m.Int32>("/camera1/tilt_info", 1, callback);
     pub = nh.advertise<m.Int32>("/camera1/tilt", 1);
 }
 public async Task Unsubscribe(Subscriber subscriber, MessageType messageType, ContextBag context)
 {
     using (var connection = connectionBuilder())
     {
         await connection.OpenAsync();
         await Unsubscribe(subscriber, connection, messageType);
     }
 }
Example #28
0
    static void Main()
    {
        Publisher pub = new Publisher();
        Subscriber sub = new Subscriber(Message, pub);

        // Call the method that raises the event.
        pub.Execute(1000);
    }
Example #29
0
        public MainWindow()
        {
            InitializeComponent();

            ROS.Init(new string[0], "wpf_listener");
            nh = new NodeHandle();

            sub = nh.subscribe<Messages.std_msgs.String>("/chatter", 10, subCallback);
        }
 static void Main()
 {
     Publisher myPublisher = new Publisher();
     Subscriber mySubscriber = new Subscriber(myPublisher);
     for (int i = 0; i < 10; i++)
     {
         myPublisher.RaiseEvent();
         Thread.Sleep(1500);
     }
 }
 private void SubscribeToStream(Stream stream)
 {
     _subscriber = new Subscriber(_activity, stream);
     _subscriber.SetVideoListener(this);
     _session.Subscribe(_subscriber);
 }
Example #32
0
    void OnRosInit()
    {
        nh = ROS.GlobalNodeHandle;
//		NodeHandle privateNH = new NodeHandle("~");

        nh.param <int>("x_axis", ref sAxes.x.axis, 5);
        nh.param <int>("y_axis", ref sAxes.y.axis, 4);
        nh.param <int>("z_axis", ref sAxes.z.axis, 2);
        nh.param <int>("thrust_axis", ref sAxes.thrust.axis, -3);
        nh.param <int>("yaw_axis", ref sAxes.yaw.axis, 1);

        nh.param <double>("yaw_velocity_max", ref sAxes.yaw.factor, 90.0);

        nh.param <int>("slow_button", ref sButtons.slow.button, 4);
        nh.param <int>("go_button", ref sButtons.go.button, 1);
        nh.param <int>("stop_button", ref sButtons.stop.button, 2);
        nh.param <int>("interrupt_button", ref sButtons.interrupt.button, 3);
        nh.param <double>("slow_factor", ref slowFactor, 0.2);

        // TODO dynamic reconfig
        string control_mode = "";

        nh.param <string>("control_mode", ref control_mode, "twist");

        NodeHandle robot_nh = ROS.GlobalNodeHandle;

//		NodeHandle robot_nh = new NodeHandle ();

        // TODO factor out
        robot_nh.param <string>("base_link_frame", ref baseLinkFrame, "base_link");
        robot_nh.param <string>("world_frame", ref worldFrame, "world");
        robot_nh.param <string>("base_stabilized_frame", ref baseStabilizedFrame, "base_stabilized");

        if (control_mode == "attitude")
        {
            nh.param <double>("pitch_max", ref sAxes.x.factor, 30.0);
            nh.param <double>("roll_max", ref sAxes.y.factor, 30.0);
            nh.param <double>("thrust_max", ref sAxes.thrust.factor, 10.0);
            nh.param <double>("thrust_offset", ref sAxes.thrust.offset, 10.0);
            joySubscriber     = nh.subscribe <Joy> ("joy", 1, joyAttitudeCallback);
            attitudePublisher = robot_nh.advertise <AttitudeCommand> ("command/attitude", 10);
            yawRatePublisher  = robot_nh.advertise <YawRateCommand> ("command/yawrate", 10);
            thrustPublisher   = robot_nh.advertise <ThrustCommand> ("command/thrust", 10);
        }
        else if (control_mode == "velocity")
        {
            nh.param <double>("x_velocity_max", ref sAxes.x.factor, 2.0);
            nh.param <double>("y_velocity_max", ref sAxes.y.factor, 2.0);
            nh.param <double>("z_velocity_max", ref sAxes.z.factor, 2.0);

            joySubscriber     = nh.subscribe <Joy> ("joy", 1, joyTwistCallback);
            velocityPublisher = robot_nh.advertise <TwistStamped> ("command/twist", 10);
        }
        else if (control_mode == "position")
        {
            nh.param <double>("x_velocity_max", ref sAxes.x.factor, 2.0);
            nh.param <double>("y_velocity_max", ref sAxes.y.factor, 2.0);
            nh.param <double>("z_velocity_max", ref sAxes.z.factor, 2.0);

            joySubscriber = nh.subscribe <Joy> ("joy", 1, joyPoseCallback);

            pose.pose.position.x    = 0;
            pose.pose.position.y    = 0;
            pose.pose.position.z    = 0;
            pose.pose.orientation.x = 0;
            pose.pose.orientation.y = 0;
            pose.pose.orientation.z = 0;
            pose.pose.orientation.w = 1;
        }
        else
        {
            ROS.Error("Unsupported control mode: " + control_mode);
        }

        motorEnableService = robot_nh.serviceClient <EnableMotors> ("enable_motors");
        takeoffClient      = new TakeoffClient(robot_nh, "action/takeoff");
        landingClient      = new LandingClient(robot_nh, "action/landing");
        poseClient         = new PoseClient(robot_nh, "action/pose");
    }
Example #33
0
        public override IDeepCopyable CopyTo(IDeepCopyable other)
        {
            var dest = other as Coverage;

            if (dest != null)
            {
                base.CopyTo(dest);
                if (Issuer != null)
                {
                    dest.Issuer = (Hl7.Fhir.Model.ResourceReference)Issuer.DeepCopy();
                }
                if (Bin != null)
                {
                    dest.Bin = (Hl7.Fhir.Model.Identifier)Bin.DeepCopy();
                }
                if (Period != null)
                {
                    dest.Period = (Hl7.Fhir.Model.Period)Period.DeepCopy();
                }
                if (Type != null)
                {
                    dest.Type = (Hl7.Fhir.Model.Coding)Type.DeepCopy();
                }
                if (SubscriberId != null)
                {
                    dest.SubscriberId = (Hl7.Fhir.Model.Identifier)SubscriberId.DeepCopy();
                }
                if (Identifier != null)
                {
                    dest.Identifier = new List <Hl7.Fhir.Model.Identifier>(Identifier.DeepCopy());
                }
                if (GroupElement != null)
                {
                    dest.GroupElement = (Hl7.Fhir.Model.FhirString)GroupElement.DeepCopy();
                }
                if (PlanElement != null)
                {
                    dest.PlanElement = (Hl7.Fhir.Model.FhirString)PlanElement.DeepCopy();
                }
                if (SubPlanElement != null)
                {
                    dest.SubPlanElement = (Hl7.Fhir.Model.FhirString)SubPlanElement.DeepCopy();
                }
                if (DependentElement != null)
                {
                    dest.DependentElement = (Hl7.Fhir.Model.PositiveInt)DependentElement.DeepCopy();
                }
                if (SequenceElement != null)
                {
                    dest.SequenceElement = (Hl7.Fhir.Model.PositiveInt)SequenceElement.DeepCopy();
                }
                if (Subscriber != null)
                {
                    dest.Subscriber = (Hl7.Fhir.Model.ResourceReference)Subscriber.DeepCopy();
                }
                if (Network != null)
                {
                    dest.Network = (Hl7.Fhir.Model.Identifier)Network.DeepCopy();
                }
                if (Contract != null)
                {
                    dest.Contract = new List <Hl7.Fhir.Model.ResourceReference>(Contract.DeepCopy());
                }
                return(dest);
            }
            else
            {
                throw new ArgumentException("Can only copy to an object of the same type", "other");
            }
        }
Example #34
0
 public RateReporter(AtomicBoolean running, Subscriber subscriber)
 {
     Running    = running;
     Subscriber = subscriber;
     _stopwatch = Stopwatch.StartNew();
 }
Example #35
0
 public static ConfiguredTaskAwaitable PublishConfiguredAsync(Subscriber <TMessage> subscriber, TMessage message)
 => subscriber._handler.Invoke(message)
 .ConfigureAwait(false);
    /// <summary>
    /// Save subscriber.
    /// </summary>
    /// <returns>Subscriver info object</returns>
    private Subscriber SaveSubscriber()
    {
        // Check if a subscriber exists first
        Subscriber sb = null;

        if (AllowUserSubscribers && (CMSContext.CurrentUser != null) && CMSContext.CurrentUser.IsAuthenticated())
        {
            sb = SubscriberProvider.GetSubscriber(SiteObjectType.USER, CMSContext.CurrentUser.UserID, CMSContext.CurrentSiteID);
        }
        else
        {
            sb = SubscriberProvider.GetSubscriber(txtEmail.Text, CMSContext.CurrentSiteID);
        }

        if ((sb == null) || ((chooseMode) && (sb != null)))
        {
            // Create subscriber
            if (sb == null)
            {
                sb = new Subscriber();
            }

            // Handle authenticated user
            if (AllowUserSubscribers && (CMSContext.CurrentUser != null) && CMSContext.CurrentUser.IsAuthenticated())
            {
                // Get user info and copy first name, last name or full name to new subscriber
                UserInfo ui = UserInfoProvider.GetUserInfo(CMSContext.CurrentUser.UserID);
                if (ui != null)
                {
                    if (!DataHelper.IsEmpty(ui.FirstName) && !DataHelper.IsEmpty(ui.LastName))
                    {
                        sb.SubscriberFirstName = ui.FirstName;
                        sb.SubscriberLastName  = ui.LastName;
                    }
                    else
                    {
                        sb.SubscriberFirstName = ui.FullName;
                    }
                    // Full name consists of "user " and user full name
                    sb.SubscriberFullName = "User '" + ui.FullName + "'";
                }
                else
                {
                    return(null);
                }

                sb.SubscriberType      = "cms.user";
                sb.SubscriberRelatedID = CMSContext.CurrentUser.UserID;
            }
            // Work with non-authenticated user
            else
            {
                sb.SubscriberEmail = txtEmail.Text.Trim();

                // First name
                if (DisplayFirstName)
                {
                    sb.SubscriberFirstName = txtFirstName.Text;
                }
                else
                {
                    sb.SubscriberFirstName = string.Empty;
                }

                // Last name
                if (DisplayLastName)
                {
                    sb.SubscriberLastName = txtLastName.Text;
                }
                else
                {
                    sb.SubscriberLastName = string.Empty;
                }

                // Full name
                sb.SubscriberFullName = (sb.SubscriberFirstName + " " + sb.SubscriberLastName).Trim();

                // Create guid
                sb.SubscriberGUID = Guid.NewGuid();
            }

            // Set site ID
            sb.SubscriberSiteID = CMSContext.CurrentSiteID;

            // Check subscriber limits
            if (!SubscriberProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.Subscribers, VersionActionEnum.Insert))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("LicenseVersionCheck.Subscribers");
                return(null);
            }

            // Save subscriber info
            SubscriberProvider.SetSubscriber(sb);
        }
        // Hide all
        visibleLastName  = false;
        visibleFirstName = false;
        visibleEmail     = false;

        pnlButtonSubmit.Visible = false;
        pnlImageSubmit.Visible  = false;

        plcNwsList.Visible = false;

        // Clear the form
        txtEmail.Text     = string.Empty;
        txtFirstName.Text = string.Empty;
        txtLastName.Text  = string.Empty;

        // Return subscriber info object
        return(sb);
    }
Example #37
0
        static void Main(string[] args)
        {
            #region Subscribers:
            Subscriber subscriber_1 = new Subscriber("Peter", "Parker");
            Subscriber subscriber_2 = new Subscriber("Bill", "Murray");
            Subscriber subscriber_3 = new Subscriber("Andrew", "Boget");
            #endregion

            IBilling billing   = new Billing();
            IStation station   = new Station();
            Operator operator_ = new Operator(station, billing);

            #region Contracts:
            operator_.SignContract(subscriber_1.FirstName, subscriber_1.LastName, 111111, TariffOption.FreeAtNight);
            operator_.SignContract(subscriber_2.FirstName, subscriber_2.LastName, 222222, TariffOption.FreeMinutesStandart);
            operator_.SignContract(subscriber_3.FirstName, subscriber_3.LastName, 333333, TariffOption.FreeMinutesEasy);
            #endregion

            #region Terminals:
            ITerminal terminal_1 = station.ReturnTerminal(111111);
            ITerminal terminal_2 = station.ReturnTerminal(222222);
            ITerminal terminal_3 = station.ReturnTerminal(333333);
            #endregion

            #region Tests:
            terminal_1.Connect();
            terminal_2.Connect();
            terminal_3.Connect();

            terminal_1.Call(222222);
            terminal_2.Answer();
            terminal_1.Reject();

            terminal_1.Call(333333);
            terminal_3.Answer();
            terminal_3.Reject();

            terminal_1.Call(222222);
            terminal_2.Answer();
            terminal_1.Reject();

            terminal_2.Call(333333);
            terminal_3.Answer();
            terminal_1.Call(333333);
            terminal_2.Reject();

            terminal_3.Call(111111);
            terminal_1.Answer();
            terminal_3.Reject();

            operator_.ChangeTariff(222222, TariffOption.FreeAtNight);

            terminal_2.Call(111111);
            terminal_1.Answer();
            terminal_3.Call(222222);
            terminal_2.Reject();

            terminal_2.Call(333333);
            terminal_3.Answer();
            terminal_2.Reject();

            terminal_2.Disconect();

            billing.GetFullStatistic(111111);
            billing.GetFullStatistic(222222);
            billing.GetFullStatistic(333333);

            billing.GetStatisticByCost(111111, 10, 60);
            billing.GetStatisticByTargetAbonent(111111, 222222);
            #endregion
            #region Close application
            Console.WriteLine("\nPress any key to close.");
            Console.ReadKey();
            #endregion
        }
 public SubscriberHosted(ILogger <SubscriberHosted> logger, Subscriber subscriber, IHubContext <ImagesQueueHub> imagesHub)
 {
     _logger     = logger;
     _subscriber = subscriber;
     _imagesHub  = imagesHub;
 }
        public ActionResult Create([Bind(Include = "ContentID,ProjectTitle,Technique,Supplies,FilePath1,FilePath2,FileName,ContactInfo,ApplicationUserID")] HttpPostedFileBase file1, HttpPostedFileBase file2, PremiumContent premiumContent, Subscriber subscriber)
        {
            var currentUserId = User.Identity.GetUserId();

            string FilePath1 = Path.Combine(Server.MapPath("~/UploadedFiles/"), Path.GetFileName(file1.FileName));
            string FilePath2 = Path.Combine(Server.MapPath("~/UploadedFiles/"), Path.GetFileName(file2.FileName));
            string PDFName   = Path.GetFileName(file2.FileName);

            if (ModelState.IsValid)
            {
                file1.SaveAs(FilePath1);
                premiumContent.FilePath1 = "/../UploadedFiles/" + file1.FileName;

                file2.SaveAs(FilePath2);
                premiumContent.FilePath2 = "/../UploadedFiles/" + file2.FileName;
                ViewBag.Message          = "File Uploaded Successfully!";

                premiumContent.FileName      = PDFName;
                subscriber.ApplicationUserID = currentUserId;

                db.PremiumContents.Add(premiumContent);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            else
            {
                ViewBag.Message = "File Upload Failed!";
            }
            return(RedirectToAction("Index"));
        }
 public void InitializeFramework(Framework framework)
 {
     m_mapper       = framework.Mapper;
     m_concentrator = framework.Concentrator;
     m_subscriber   = framework.Subscriber;
 }
Example #41
0
 public void Dispose()
 {
     Subscriber?.Dispose();
 }
Example #42
0
        public async Task Invoke(IIncomingPhysicalMessageContext context, Func <IIncomingPhysicalMessageContext, Task> next)
        {
            var incomingMessage   = context.Message;
            var messageTypeString = GetSubscriptionMessageTypeFrom(incomingMessage);

            var intent = incomingMessage.GetMessageIntent();

            if (string.IsNullOrEmpty(messageTypeString) && intent != MessageIntentEnum.Subscribe && intent != MessageIntentEnum.Unsubscribe)
            {
                await next(context).ConfigureAwait(false);

                return;
            }

            if (string.IsNullOrEmpty(messageTypeString))
            {
                throw new InvalidOperationException("Message intent is Subscribe, but the subscription message type header is missing.");
            }

            if (intent != MessageIntentEnum.Subscribe && intent != MessageIntentEnum.Unsubscribe)
            {
                throw new InvalidOperationException("Subscription messages need to have intent set to Subscribe/Unsubscribe.");
            }

            string subscriberEndpoint = null;

            if (incomingMessage.Headers.TryGetValue(Headers.SubscriberTransportAddress, out var subscriberAddress))
            {
                subscriberEndpoint = incomingMessage.Headers[Headers.SubscriberEndpoint];
            }
            else
            {
                subscriberAddress = incomingMessage.GetReplyToAddress();
            }

            if (subscriberAddress == null)
            {
                throw new InvalidOperationException("Subscription message arrived without a valid ReplyToAddress.");
            }

            if (subscriptionStorage == null)
            {
                var warning = $"Subscription message from {subscriberAddress} arrived at this endpoint, yet this endpoint is not configured to be a publisher. To avoid this warning make this endpoint a publisher by configuring a subscription storage.";
                Logger.WarnFormat(warning);

                if (Debugger.IsAttached)                          // only under debug, so that we don't expose ourselves to a denial of service
                {
                    throw new InvalidOperationException(warning); // and cause message to go to error queue by throwing an exception
                }

                return;
            }

            if (!authorizer(context))
            {
                Logger.Debug($"{intent} from {subscriberAddress} on message type {messageTypeString} was refused.");
                return;
            }
            Logger.Info($"{intent} from {subscriberAddress} on message type {messageTypeString}");
            var subscriber = new Subscriber(subscriberAddress, subscriberEndpoint);

            if (incomingMessage.GetMessageIntent() == MessageIntentEnum.Subscribe)
            {
                var messageType = new MessageType(messageTypeString);
                await subscriptionStorage.Subscribe(subscriber, messageType, context.Extensions, context.CancellationToken).ConfigureAwait(false);

                return;
            }

            await subscriptionStorage.Unsubscribe(subscriber, new MessageType(messageTypeString), context.Extensions, context.CancellationToken).ConfigureAwait(false);
        }
Example #43
0
 public virtual Task Subscribe(Subscriber subscriber, MessageType messageType, ContextBag context)
 {
     return(Retry(() => SubscribeInternal(subscriber, messageType)));
 }
Example #44
0
 public virtual Task Unsubscribe(Subscriber address, MessageType messageType, ContextBag context)
 {
     return(Retry(() => UnsubscribeInternal(address, messageType)));
 }
 static string Serialize(Subscriber subscriber)
 {
     return($"{subscriber.TransportAddress}|{subscriber.Endpoint}");
 }
Example #46
0
 public async Task RemoveSubsriberFromTagAsync(string tag, Subscriber subscriber)
 {
     await dynamoService.DeleteItemAsync <SelfModel>(hashKey : tag, rangeKey : subscriber.PrimaryKeyValue);
 }
    /// <summary>
    /// Saves the data.
    /// </summary>
    private bool Save(string newsletterName, Subscriber sb)
    {
        bool toReturn = false;
        int  siteId   = CMSContext.CurrentSiteID;

        // Check if sunscriber info object exists
        if ((sb == null) || string.IsNullOrEmpty(newsletterName))
        {
            return(false);
        }

        // Get nesletter info
        Newsletter news = NewsletterProvider.GetNewsletter(newsletterName, siteId);

        if (news != null)
        {
            try
            {
                // Check if subscriber is not allready subscribed
                if (!SubscriberProvider.IsSubscribed(sb.SubscriberGUID, news.NewsletterGUID, siteId))
                {
                    toReturn = true;

                    // Subscribe to the site
                    SubscriberProvider.Subscribe(sb.SubscriberID, news.NewsletterID, DateTime.Now, this.SendConfirmationEmail);

                    // Info message
                    if (!chooseMode)
                    {
                        lblInfo.Visible = true;
                        lblInfo.Text    = GetString("NewsletterSubscription.Subscribed");
                    }

                    // Track successful subscription conversion
                    if (this.TrackConversionName != string.Empty)
                    {
                        string siteName = CMSContext.CurrentSiteName;

                        if (AnalyticsHelper.AnalyticsEnabled(siteName) && AnalyticsHelper.TrackConversionsEnabled(siteName) && !AnalyticsHelper.IsIPExcluded(siteName, HTTPHelper.UserHostAddress))
                        {
                            // Log conversion
                            HitLogProvider.LogConversions(siteName, CMSContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue);
                        }
                    }

                    // Log newsletter subscription activity if double opt-in is not required
                    if (!news.NewsletterEnableOptIn)
                    {
                        if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && news.NewsletterLogActivity && ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteId) &&
                            ActivitySettingsHelper.ActivitiesEnabledForThisUser(CMSContext.CurrentUser) &&
                            ActivitySettingsHelper.NewsletterSubscribeEnabled(siteId))
                        {
                            int contactId = ModuleCommands.OnlineMarketingGetCurrentContactID();
                            ModuleCommands.OnlineMarketingUpdateContactFromExternalData(sb, contactId);
                            ModuleCommands.OnlineMarketingCreateRelation(sb.SubscriberID, MembershipType.NEWSLETTER_SUBSCRIBER, contactId);

                            if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(CMSContext.CurrentUser))
                            {
                                var data = new ActivityData()
                                {
                                    ContactID = contactId,
                                    SiteID    = sb.SubscriberSiteID,
                                    Type      = PredefinedActivityType.NEWSLETTER_SUBSCRIBING,
                                    TitleData = news.NewsletterName,
                                    ItemID    = news.NewsletterID,
                                    URL       = URLHelper.CurrentRelativePath,
                                    Campaign  = CMSContext.Campaign
                                };
                                ActivityLogProvider.LogActivity(data);
                            }
                        }
                    }
                }
                else
                {
                    // Info message - subscriber is allready in site
                    if (!chooseMode)
                    {
                        lblInfo.Visible = true;
                        lblInfo.Text    = GetString("NewsletterSubscription.SubscriberIsAlreadySubscribed");
                    }
                    else
                    {
                        lblInfo.Visible = true;
                        lblInfo.Text   += GetString("NewsletterSubscription.SubscriberIsAlreadySubscribedXY") + " " + HTMLHelper.HTMLEncode(news.NewsletterDisplayName) + ".<br />";
                    }
                }
            }
            catch (Exception ex)
            {
                lblError.Visible = true;
                lblError.Text    = ex.Message;
            }
        }
        else
        {
            lblError.Visible = true;
            lblError.Text    = GetString("NewsletterSubscription.NewsletterDoesNotExist");
        }

        return(toReturn);
    }
Example #48
0
        public void Get_Current_Rental_Subs()
        {
            var asset = new Guitar()
            {
                Id   = 10,
                Type = "Bass",
                Name = "Bass Guitar"
            };

            var subOne = new Subscriber
            {
                Id        = 1,
                FirstName = "Jim",
                LastName  = "Brown"
            };

            var subTwo = new Subscriber
            {
                Id        = 2,
                FirstName = "Michael",
                LastName  = "James"
            };

            var subThree = new Subscriber
            {
                Id        = 3,
                FirstName = "Sarah",
                LastName  = "Shannons"
            };


            var rentals = new List <Rental>()
            {
                new Rental
                {
                    Id          = 111,
                    Since       = DateTime.Now,
                    Until       = DateTime.Now,
                    Subscriber  = subOne,
                    RentalAsset = asset
                },
                new Rental
                {
                    Id          = 222,
                    Since       = DateTime.Now,
                    Until       = DateTime.Now,
                    Subscriber  = subTwo,
                    RentalAsset = asset
                },
                new Rental
                {
                    Id          = 333,
                    Since       = DateTime.Now,
                    Until       = DateTime.Now,
                    Subscriber  = subThree,
                    RentalAsset = new Guitar()
                }
            }.AsQueryable();

            var mockDbSet = new Mock <DbSet <Rental> >();

            mockDbSet.As <IQueryable <Rental> >().Setup(p => p.Provider).Returns(rentals.Provider);
            mockDbSet.As <IQueryable <Rental> >().Setup(p => p.Expression).Returns(rentals.Expression);
            mockDbSet.As <IQueryable <Rental> >().Setup(p => p.ElementType).Returns(rentals.ElementType);
            mockDbSet.As <IQueryable <Rental> >().Setup(p => p.GetEnumerator()).Returns(rentals.GetEnumerator);

            var mockContext = new Mock <RentalContext>();

            mockContext.Setup(r => r.Rentals).Returns(mockDbSet.Object);

            var service = new RentalService(mockContext.Object);
            var rental  = service.GetCurrentRentalSubs(asset.Id);

            rental.Should().HaveCount(2);
            rental.Should().Contain("Michael James");
            rental.Should().Contain("Jim Brown");
        }
Example #49
0
        public override V3Message execute(Request message, RequestContext context)
        {
            object returnValue = null;

            switch (operation)
            {
            case SUBSCRIBE_OPERATION:
            {
                IDestination destObj =
                    ORBConfig.GetInstance().GetDataServices().GetDestinationManager().GetDestination(destination);
                Hashtable headers = new Hashtable();

                RTMPConnection connection = (RTMPConnection)ConnectionHub.getConnectionLocal();

                if (destObj != null)
                {
                    String selectorName = (String)this.headers["DSSelector"];
                    String subtopic     = (String)this.headers["DSSubtopic"];
                    String dsId         = connection == null ? (String)this.headers["DSId"] : connection.GetHashCode().ToString();
                    String channel      = (String)this.headers["DSEndpoint"];

                    Subscriber subscriber = SubscriptionsManager.GetInstance().getSubscriber(
                        Subscriber.buildId(dsId, destObj.GetName(), subtopic, selectorName));

                    if (clientId == null || clientId.Equals(""))
                    {
                        clientId = Guid.NewGuid().ToString().ToUpper();
                    }

                    if (subscriber != null)
                    {
                        if (subscriber.addClient(clientId.ToString()))
                        {
                            destObj.GetServiceHandler().HandleSubscribe(subscriber, clientId.ToString(), this);
                        }

                        return(new AckMessage(messageId, clientId, null, headers));
                    }

                    object wsContext = ThreadContext.getProperties()[ORBConstants.WEB_SOCKET_MODE];

                    if (wsContext != null)
                    {
                        subscriber = new WebSocketSubscriber(selectorName, destObj, (UserContext)wsContext);
                    }
                    else if (connection != null)
                    {
                        subscriber = new DedicatedSubscriber(selectorName, destObj);
                        subscriber.setChannelId(RTMPHandler.getChannelId());
                        subscriber.setConnection(connection);
                    }
                    else
                    {
                        subscriber = SubscriberFactory.CreateSubscriber(channel, selectorName, destObj);
                    }

                    subscriber.setDSId(dsId);
                    subscriber.setSubtopic(subtopic);
                    subscriber.addClient((String)clientId);

                    try
                    {
                        SubscriptionsManager.GetInstance().AddSubscriber(dsId, destObj.GetName(), subscriber);
                    }
                    catch (Exception e)
                    {
                        if (Log.isLogging(LoggingConstants.EXCEPTION))
                        {
                            Log.log(LoggingConstants.EXCEPTION, e);
                        }
                    }

                    destObj.GetServiceHandler().HandleSubscribe(subscriber, clientId.ToString(), this);
                }
                else
                {
                    String error = "Unknown destination " + destination + ". Cannot handle subscription request";

                    if (Log.isLogging(LoggingConstants.ERROR))
                    {
                        Log.log(LoggingConstants.ERROR, error);
                    }

                    return(new ErrMessage(messageId, new Exception(error)));
                }

                return(new AckMessage(messageId, clientId, null, headers));
            }
            break;

            case UNSUBSCRIBE_OPERATION:
            {
                String subtopic     = (String)this.headers["DSSubtopic"];
                String dsId         = (String)this.headers["DSId"];
                String selectorName = (String)this.headers["DSSelector"];

                RTMPConnection connection = (RTMPConnection)ConnectionHub.getConnectionLocal();

                if (connection != null)
                {
                    dsId = connection.GetHashCode().ToString();
                }

                Subscriber subscriber = SubscriptionsManager.GetInstance().getSubscriber(
                    Subscriber.buildId(dsId, destination, subtopic, selectorName));

                if (subscriber != null)
                {
                    SubscriptionsManager.GetInstance().unsubscribe(subscriber, clientId.ToString(), this);
                }
            }
            break;

            case DISCONNECT_OPERATION:
            {
                String         dsId       = (String)this.headers["DSId"];
                RTMPConnection connection = (RTMPConnection)ConnectionHub.getConnectionLocal();

                if (connection != null)
                {
                    dsId = connection.GetHashCode().ToString();
                }

                SubscriptionsManager subscriptionsManager = SubscriptionsManager.GetInstance();
                List <Subscriber>    subscribers          = subscriptionsManager.getSubscribersByDsId(dsId);

                if (subscribers != null)
                {
                    foreach (Subscriber subscriber in subscribers)
                    {
                        if (subscriber != null)
                        {
                            subscriptionsManager.unsubscribe(subscriber, this);
                        }
                    }
                }

                subscriptionsManager.removeSubscriber(dsId);
            }
            break;

            case POLL_OPERATION:
            {
                String dsId = (String)this.headers["DSId"];

                RTMPConnection connection = (RTMPConnection)ConnectionHub.getConnectionLocal();

                if (connection != null)
                {
                    dsId = connection.GetHashCode().ToString() + "";
                }

                try
                {
                    WebORBArray <V3Message> messages =
                        new WebORBArray <V3Message>(SubscriptionsManager.GetInstance().getMessages(dsId));

                    if (messages.Count == 0)
                    {
                        return(new AckMessage(null, null, null, new Hashtable()));
                    }

                    return(new CommandMessage(CLIENT_SYNC_OPERATION, messages));
                }
                catch (Exception e)
                {
                    String error = "Invalid client id " + dsId;

                    if (Log.isLogging(LoggingConstants.ERROR))
                    {
                        Log.log(LoggingConstants.ERROR, error, e);
                    }

                    return(new ErrMessage(messageId, new Exception(error)));
                }
            }
            break;

            case CLIENT_PING_OPERATION:
            {
                Hashtable headers = new Hashtable();

                RTMPConnection connection = (RTMPConnection)ConnectionHub.getConnectionLocal();
                if (connection != null)
                {
                    headers.Add("DSId", connection.GetHashCode().ToString());
                }
                else
                {
                    headers.Add("DSId", Guid.NewGuid().ToString().ToUpper());
                }

                return(new AckMessage(messageId, clientId, null, headers));
            }
            break;

            case LOGOUT_OPERATION:
            {
                ThreadContext.setCallerCredentials(null, null);
                Thread.CurrentPrincipal = null;
            }
            break;

            case LOGIN_OPERATION:
            {
                String credentials = (String)((IAdaptingType)((object[])body.body)[0]).defaultAdapt();
                byte[] bytes       = Convert.FromBase64String(credentials);
                credentials = new String(Encoding.UTF8.GetChars(bytes));
                IAuthenticationHandler authHandler = ORBConfig.GetInstance().getSecurity().GetAuthenticationHandler();

                if (authHandler == null)
                {
                    ErrMessage errorMessage = new ErrMessage(messageId, new ServiceException("Missing authentication handler"));
                    errorMessage.faultCode = "Client.Authentication";
                    return(errorMessage);
                }

                int    index    = credentials.IndexOf(":");
                string userid   = null;
                string password = null;

                if (index != -1 && index != 0 && index != credentials.Length - 1)
                {
                    userid   = credentials.Substring(0, index);
                    password = credentials.Substring(index + 1);

                    try
                    {
                        IPrincipal principal = authHandler.CheckCredentials(userid, password, message);

                        try
                        {
                            Thread.CurrentPrincipal = principal;
                            ThreadContext.currentHttpContext().User = principal;
                        }
                        catch (Exception exception)
                        {
                            if (Log.isLogging(LoggingConstants.ERROR))
                            {
                                Log.log(LoggingConstants.ERROR,
                                        "Unable to set current principal. Make sure your current permission set allows Principal Control",
                                        exception);
                            }

                            throw exception;
                        }

                        Credentials creds = new Credentials();
                        creds.userid   = userid;
                        creds.password = password;
                        ThreadContext.setCallerCredentials(creds, principal);
                    }
                    catch (Exception exception)
                    {
                        ErrMessage errorMessage = new ErrMessage(messageId, exception);
                        errorMessage.faultCode = "Client.Authentication";
                        return(errorMessage);
                    }
                }
                else
                {
                    ErrMessage errorMessage = new ErrMessage(messageId, new ServiceException("Invalid credentials"));
                    errorMessage.faultCode = "Client.Authentication";
                    return(errorMessage);
                }
            }
            break;
            }

            return(new AckMessage(messageId, clientId, returnValue, new Hashtable()));
        }
Example #50
0
        /// <summary>
        /// Delivers all Pending Messages for a Single Subscriber
        /// </summary>
        /// <param name="SubscriberId"></param>
        /// <returns></returns>
        private async Task DeliverMessagesToSubscriber(string SubscriberId)
        {
            using (var scope = serviceProvider.CreateScope())
            {
                var subscriberStore = scope.ServiceProvider.GetRequiredService <ISubscriberStore>();
                var queueService    = scope.ServiceProvider.GetRequiredService <ISubscriberQueueStore>();
                var deliveryService = scope.ServiceProvider.GetRequiredService <IDeliveryService>();

                Subscriber subscriber = await subscriberStore.GetSubscriber(SubscriberId);

                // If the Subscriber is Inactive, just log and stop
                if (subscriber.State == SubscriberStates.Inactive)
                {
                    logger.LogWarning($"The Subscriber '{SubscriberId}' is currently marked inactive");
                    return;
                }

                // Deliver each message in sequence until all messages are deliverd
                var nextMessage = await queueService.PeekMessageAsync(SubscriberId);

                while (nextMessage != null)
                {
                    var result = await deliveryService.DeliverMessage(nextMessage.DestinationUri, nextMessage.JsonBody);

                    if (!result.SentSuccessfully)
                    {
                        // Update the Subscriber with Failure Details and Exit
                        logger.LogWarning($"The Subscriber '{SubscriberId}' is down");
                        subscriber = await subscriberStore.GetSubscriber(SubscriberId);

                        subscriber.State       = SubscriberStates.Down;
                        subscriber.LastFailure = DateTime.UtcNow;
                        subscriber.FailureCount++;
                        await subscriberStore.UpdateSubscriberAsync(subscriber);

                        return;
                    }
                    await queueService.ClearMessageAsync(nextMessage.MessageId);

                    // Stop if Requested
                    if (stoppingToken.IsCancellationRequested)
                    {
                        return;
                    }

                    // Attempt to get the next message
                    nextMessage = await queueService.PeekMessageAsync(SubscriberId);
                }

                // Check the Subscriber Status
                // Update the Subscriber with Failure Details and Exit
                subscriber = await subscriberStore.GetSubscriber(SubscriberId);

                if (subscriber.State == Models.SubscriberStates.Down)
                {
                    logger.LogInformation($"The Subscriber '{SubscriberId}' is active again");
                    subscriber.State        = SubscriberStates.Active;
                    subscriber.LastFailure  = null;
                    subscriber.FailureCount = 0;
                    await subscriberStore.UpdateSubscriberAsync(subscriber);
                }
            }
        }
Example #51
0
        public void DeleteSubscriber(CampaignUser user)
        {
            Subscriber subscriber = new Subscriber(_auth, _listId);

            subscriber.Delete(user.Email);
        }
Example #52
0
        //Метод для заполнения таблицы 'Подписчики на периодические издания' тестовыми значениями
        private void AutoInsertSubscribers()
        {
            string[] lastNames = new string[]
            {
                "Пупкин", "Печкин", "Куров", "Синицын", "Скороход"
                , "Домов", "Колотушкин", "Карченко", "Пушкин", "Тарин"
            };

            string[] firstNames = new string[]
            {
                "Владислав", "Илья", "Александр", "Дмитрий", "Виктор"
                , "Станислав", "Константин", "Ян", "Максим", "Пётр"
            };

            string[] midleNames = new string[]
            {
                "Александрович", "Максимов", "Петрович", "Янов", "Владиславович"
                , "Ильич", "Дмитрович", "Константинович", "Станиславович", "Викторович"
            };

            string[] subAddresses = new string[]
            {
                "Украина г.Украинский, ул.Украины, д.32, кв.5"
                , "Россия г.Российсткий, ул.России, д.24, кв.12"
                , "Белоруссия г.Белороссийский, ул.Белорусии, д.43, кв.34"
                , "Польша г.Польский, ул.Польши, д.17, кв.45"
                , "США г.Штацкий, ул.Штатов, д.42, кв.15"
                , "ЮАР г.ЮАРский, ул.ЮАРцев, д.36, кв.8"
                , "Турция г.Турецкий, ул.Турции, д.7, кв.44"
                , "Франция г.Французкий, ул.Франции, д.34, кв.25"
                , "Германия г.Германский, ул.Германии, д.54, кв.6"
                , "Мексика г.Мексиканский, ул.Мексики, д.31, кв.17"
            };

            using (MailContext context = new MailContext())
            {
                try
                {
                    Subscriber        subscriber  = new Subscriber();
                    List <Subscriber> subscribers = new List <Subscriber>();

                    for (int i = 0; i < lastNames.Length; i++)
                    {
                        subscriber.last_Name   = lastNames[i];
                        subscriber.first_Name  = firstNames[i];
                        subscriber.middle_Name = midleNames[i];
                        subscriber.sub_Address = subAddresses[i];
                        subscribers.Add(subscriber);
                        subscriber = new Subscriber();
                    }

                    context.Subscribers.AddRange(subscribers);

                    context.SaveChanges();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Ошибка при заполнении таблицы 'Подписчики на периодические издания' Текст ошибки:" + e.ToString());
                }
            }
        }
Example #53
0
 public static void Publish(Subscriber <TMessage> subscriber, TMessage message)
 => subscriber._handler.Invoke(message)
 .ContinueWith(_ => _)
 .ConfigureAwait(false);
 public DotSubscription(LogFile logFile) : base(logFile)
 {
     Subscriber = new Subscriber <Combat <DotDamageInfo> >(logFile,
                                                           new RegexStrategy <Combat <DotDamageInfo> >(CompiledRegex.DamageRegex, HandleMatches));
     Subscribe();
 }
Example #55
0
 public static Task PublishAsync(Subscriber <TMessage> subscriber, TMessage message)
 => subscriber._handler.Invoke(message);
Example #56
0
 public IHttpActionResult Post(Subscriber value)
 {
     throw new NotImplementedException();
 }
        private void Session_StreamReceived(object sender, Session.StreamEventArgs e)
        {
            Subscriber subscriber = new Subscriber(Context.Instance, e.Stream, SubscriberVideo);

            Session.Subscribe(subscriber);
        }
        // GET: Subscribers/Create
        public ActionResult Create()
        {
            var model = new Subscriber();

            return(View(model));
        }
Example #59
0
 public MainWindow()
 {
     InitializeComponent();
     subscriber = new Subscriber <DateTime>(dummy);
 }
Example #60
0
 public frmSubscriber()
 {
     InitializeComponent();
     Subscriber = new Subscriber();
     Subscriber.OnContentNotified += Subscriber_OnContentNotified;
 }