/// <summary>
        /// Aborts any pending dequeue operation by restoring read position to the
        /// top of the queue.
        /// </summary>
        public void AbortDequeue()
        {
            // Restore read position to front of queue
            this.readPosition = 0;

            // Restore head payload if there are any events in the queue
            if (this.eventPayloads.Count > 0)
            {
                this.headPayload = this.eventPayloads[this.eventPayloads.Count - 1];
            }
            else
            {
                this.headPayload = null;
            }
        }
        /// <summary>
        /// Enqueues a set of events
        /// </summary>
        /// <param name="eventSet">The set of events</param>
        public void Enqueue(EventSet payload)
        {
            // Calculate the size of all the bytes in the event set:
            // FIXME: Can't easily calculate the size here
            int payloadSize = 1; // payload.Events.Aggregate(0, (size, bytes) => size + bytes.Length);

            if (payloadSize > maxPayloadSize)
            {
                throw new ArgumentOutOfRangeException("Events exceed the maximum payload size", "eventSet");
            }

            // Cache result
            payload.PayloadSize = payloadSize;

            // Create new payload object to enqueue:
            // See if we can pack this event set together with the current one:
            if (this.headPayload != null &&
                this.headPayload.ChannelName == payload.ChannelName &&
                this.headPayload.PayloadSize + payloadSize <= maxPayloadSize)
            {
                Payload[] existingPayloads = headPayload.Payloads;
                Payload[] newPayloads = payload.Payloads;
                Array.Resize(ref existingPayloads, existingPayloads.Length + newPayloads.Length);
                Array.Copy(newPayloads, 0, existingPayloads, existingPayloads.Length - newPayloads.Length, newPayloads.Length);
                headPayload.Payloads = existingPayloads;
                headPayload.PayloadSize += payloadSize;
            }
            else
            {
                // Set event sequence to next value
                payload.Sequence = this.eventSequence++;

                // Append this event set to the end of the queue
                eventPayloads.Add(payload);

                // update head to this new item:
                headPayload = payload;
            }

            // Maintain running total of all events
            this.totalPayloadSize += payloadSize;
        }
        /// <summary>
        /// Returns an array of events sets
        /// </summary>
        /// <param name="maxSize">The maximum number of events to return</param>
        /// <returns>The event set as an array. If there are no pending events it returns an empty array</returns>
        public EventSet[] BeginDequeue()
        {
            Debug.Assert(this.readPosition == 0, "Attempt to dequeue events while a dequeue is already in progress");

            // used to track how many events we have tried to fit so far into this total payload
            int curPayloadSize = 0;

            // Get the largest set of events that will fit within the limits
            EventSet[] result = this.eventPayloads.TakeWhile(
                payload =>
                {
                    int tempSize = curPayloadSize + payload.PayloadSize;
                    if (tempSize <= maxPayloadSize)
                    {
                        // if it fits, keep going
                        curPayloadSize = tempSize;
                        return true;
                    }
                    return false;
                }).ToArray();
            
            // subtract the number of events we are about to return from the running total
            this.totalPayloadSize -= curPayloadSize;

            // if this was all of them, set the headPayload cache to null:
            if (result.Length == this.eventPayloads.Count)
            {
                this.headPayload = null;
            }

            // remember how many event sets we dequeued for the commit.
            this.readPosition = result.Length;

            // return the dequeued events
            return result;
        }
        /// <summary>
        /// Commits the pending dequeue operation by removing the previously dequeued
        /// items.
        /// </summary>
        public void CommitDequeue()
        {
            Debug.Assert(this.readPosition > 0, "Attempt to commit dequeue with none pending");

            // Remove the number of commited event sets from the front of the list (FIFO order)
            this.eventPayloads.RemoveRange(0, this.readPosition);

            // Restore read position to front of queue
            this.readPosition = 0;

            // If there are no more events in the queue, clear headPayload cache
            if (this.eventPayloads.Count == 0)
            {
                this.headPayload = null;
            }
        }
Beispiel #5
0
            public void Publish(string channelName, Payload[] payloads)
            {
                EventSet eventSet = new EventSet { ChannelName = channelName, Payloads = payloads };
                bool shouldPublish = false;
                
                lock (this)
                {
                    if (State == PublishState.PermError)
                    {
                        throw new Microsoft.Csa.SharedObjects.ClientDisconnectedException("Publish called on EventLinkClient in a permanent error state.");
                    }

                    this.outgoingQueue.Enqueue(eventSet);
                    if (State == PublishState.Idle)
                    {
                        shouldPublish = true;
                    }
                    OnPublish();
                }
                
                if (shouldPublish)
                {
                    PublishEvents();
                }
            }
Beispiel #6
0
 private void VerifyEventSequencing(EventSet[] events)
 {
     // make sure that events always come in ascending sequence order
     long wm = events[0].Sequence;
     Debug.Assert(wm == this.watermark + 1);
     for (int i = 1; i < events.Length; ++i)
     {
         Debug.Assert(events[i].Sequence == events[i - 1].Sequence + 1);
     }
 }
Beispiel #7
0
 public string WriteToJson(EventSet[] eventsets)
 {
     using (var stream = new MemoryStream())
     {
         StreamWriter sw = new StreamWriter(stream);
         using (JsonPayloadWriter writer = new JsonPayloadWriter(sw))
         {
             writer.Write(string.Empty, eventsets);
         }
         stream.Seek(0, SeekOrigin.Begin);
         StreamReader reader = new StreamReader(stream);
         return reader.ReadToEnd();
     }
 }
Beispiel #8
0
        private void EventLinkEventsReceived(EventSet[] eventSets)
        {
            if (eventSets == null)
            {
                return;
            }

            Console.WriteLine("EventReceived");
        }
Beispiel #9
0
        public EventLinkPage()
        {
            var text = new Div() { Text = "Server Address:" };
            var textbox = new Input() { Value="elipc:4040" };
            var div = new Div();
            div.Add(text);
            div.Add(textbox);
            Browser.Document.Body.Add(div);

            // Conventional DOM interaction
            var jsonButton = new Button { InnerHtml = "Test JSON..." };
            jsonButton.Click += e =>
            {
                MemoryStream st = new MemoryStream();
                PrincipalObject obj = new PrincipalObject() { Sid = "sa", Id = "eli" };
                Console.WriteLine(obj);

                JsonPayloadWriter w = new JsonPayloadWriter(st);
                var pl = new ObjectPayload(Guid.NewGuid(), obj, Guid.NewGuid(), "ObjectName");
                Console.WriteLine(pl);
                w.Write(string.Empty, pl);
                StreamReader sr = new StreamReader(st);
                string output = sr.ReadToEnd();
                Console.WriteLine(output);
                return;



                //DUMMY TEST
                //string jsont = "{ \"ChannelName\": \"test\" }";
                //JsonPayloadReader jsr = new JsonPayloadReader(jsont);
                //Console.WriteLine(jsr.ReadString("ChannelName"));

                string ns = "namespace1";
                string subscriptionId = "1234";
                Guid clientId = Guid.NewGuid();
                Guid parentId = Guid.NewGuid();
                Guid objectId = Guid.NewGuid();

                Payload payload = new ClientConnectPayload(subscriptionId, clientId, ns, NamespaceLifetime.ServerInstance);
                ETag eTag = new ETag(clientId, 2);
                string json = WriteToJson(payload);
                Console.WriteLine("WROTE: {0}", json);

                JsonPayloadReader jsonReader = new JsonPayloadReader(json);
                var payloadResult = jsonReader.ReadObject<Payload>(string.Empty, Payload.CreateInstance);
                Console.WriteLine("READ OBJECT: {0}", payloadResult);

                EventSet[] events = new EventSet[]
                {
                    new EventSet { Sequence = 0, ChannelName = "test", Payloads = new Payload[] { new ClientConnectPayload(subscriptionId, clientId , ns, NamespaceLifetime.ConnectedOnly) } }
                };

                json = WriteToJson(events);
                Console.WriteLine(json);

                MemoryStream ms = new MemoryStream();
                StreamWriter sw = new StreamWriter(ms);
                sw.Write(json);
                sw.Flush();

                var eventsResult = EventSet.CreateEventSetsFromStream(ms, PayloadFormat.JSON);
                Console.WriteLine(eventsResult);

                var principal = new PrincipalObject() { Id = "Eli", Sid = "sa" };
                var es = new EventSet { Sequence = 0, ChannelName = "test", Payloads = new Payload[] { new ClientConnectPayload(subscriptionId, clientId, ns, NamespaceLifetime.ConnectedOnly, principal) } };

                json = WriteToJson(es);
                Console.Write(json);

                return;              
            };
            Browser.Document.Body.Add(jsonButton);
            
            var soButton = new Button { InnerHtml = "Subscribe Shared Objects Client" };
            soButton.Click += e =>
            {
                var guid = Guid.NewGuid();
                var txt = textbox.Value;

                string path = string.Format("http://{0}/{1}", txt, guid.ToString());

                SharedObjectsClient soc = new SharedObjectsClient(path, NamespaceLifetime.ConnectedOnly);
                PrincipalObject principal = new PrincipalObject() { Id = "ClientA", Sid = "sa" };
                soc.PrincipalObject = principal;
                
                soc.Connect();
                Console.WriteLine("Connecting to:{0}", path);
                soc.Connected += (s, ec) =>
                {
                    Console.WriteLine("CONNECTED TO SHARED OBJECTS SERVER");
                };
            };
            Browser.Document.Body.Add(soButton);

            // Conventional DOM interaction
            var subButton = new Button { InnerHtml = "Subscribe..." };
            subButton.Click += e =>
            {
                Console.WriteLine("Subscribing...");

                Uri uri = new Uri("http://elipc:4040/");
                this.client = new EventLinkClient(uri, "3bb04637-af98-40e9-ad65-64fb2668a0d2", (s, ex) =>
                {
                    Console.WriteLine(string.Format("Error state:{0} exception:{1}", s, ex));
                });
                this.client.Subscribe("99ca2aff-538e-49f2-a71c-79b7720e3f21ClientControl", EventLinkEventsReceived, this.OnSubscriptionInitialized);
                return;

                //this.Channel = new EventLinkChannel(new Uri("http://elipc:4040/"), "nameSpace", (c1, c2) =>
                //{
                //    Write("Error state changed");
                //});

                //this.Channel.SubscriptionInitialized += OnIncomingChannelsInitialized;
                //this.Channel.EventsReceived += OnIncomingChannelsDataReceived;
                //string name = Channels.GetClientName(Guid.NewGuid());
                //this.Channel.SubscribeAsync(name);

                //Uri uri = new Uri("http://elipc:4040/");
                //this.client = new EventLinkClient(uri, "f148dc15-ad26-484e-9f74-8d0655e8fc0d", (s, ex) =>
                //{
                //    Console.WriteLine(string.Format("Error state:{0} exception:{1}", s, ex));
                //});
                //this.client.Subscribe("81dddf4c-f84c-414f-9f04-99f926fc8c68ClientControl", EventLinkEventsReceived, () => this.OnSubscriptionInitialized());
            };
            Browser.Document.Body.Add(subButton);

            // Conventional DOM interaction
            var secButton = new Button { InnerHtml = "Test Security..." };
            secButton.Click += e =>
            {
                Console.WriteLine("sec");

                //var el = new EventLinkClient(new Uri("http://localhost:4040/"), "partitionA", (c) =>
                //{
                //    Write("EventLinkClient Connected");
                //});

                //var att = new SharedAttributes();
                //Write(att);

                //var client = new SharedObjectsClient("http://www.cnn.com/namespaceName");
                //Write(client);

                //client.Connect();

                Guid g = Guid.NewGuid();
                Console.WriteLine(g);

                Guid g2 = Guid.Empty;
                Console.WriteLine(g2);

                ETag e2 = new ETag(Guid.Empty);
                Console.WriteLine(e2);

                SharedObjectSecurity s = new SharedObjectSecurity("Security", false, new ETag(Guid.Empty));
                s.AddAccessRule(new SharedObjectAccessRule("Idenity", ObjectRights.ChangePermissions, System.Security.AccessControl.InheritanceFlags.ContainerInherit, System.Security.AccessControl.AccessControlType.Allow));
                Console.WriteLine(s);

                PrincipalObject p = new PrincipalObject() { Id = "Hello", Sid = "Sid" };
                Console.WriteLine(p);

                SharedEntryMap<SampleEntry> map = new SharedEntryMap<SampleEntry>();
                Console.WriteLine(map);

                var attr = new SharedAttributes();
                Console.WriteLine(attr);

                var ep = new ObjectExpirationPolicy("timespan", TimeSpan.FromDays(1), TimeSpan.FromMilliseconds(100));
                Console.WriteLine(ep);

                var v = new ProtocolVersion(1, 0);
                Console.WriteLine(v);

                //var tp = new TracePayload("Message", Guid.Empty);
                //Write(tp);


                
                //ObjectDeletedPayload p2 = new ObjectDeletedPayload(Guid.Empty, Guid.NewGuid());
                //Write(p2);

                ////WAIT FOR SAHRED PROEPRPT
                ////ClientConnectPayload c = new ClientConnectPayload("sub", Guid.Empty, "namespace");
                ////Write(c);



                //var principalObject = new PrincipalObject() { Id = "Eli", Sid = "sa" };
                ////                var principal = new ObjectPayload(Guid.NewGuid(), principalObject, Guid.NewGuid(), "NamedObject");

                //var sharedProps = new Dictionary<short, SharedProperty>();
                //Write(sharedProps);

                ////TODO THIS IS BROKEN 
                ////var spd = new SharedPropertyDictionary();
                ////Write(spd);
                
                //var puo = new PropertyUpdateOperation();
                //Write(puo);



                //JavascriptHttpStream str = new JavascriptHttpStream(null);
                //BinaryReader br = new BinaryReader(str);
                //BinaryWriter bw = new BinaryWriter(str);
                //BinaryReader br = new BinaryReader(null);
                //BinaryWriter bw = new BinaryWriter(null);

                
                
            };
            //Browser.Document.Body.Add(secButton);

            // Conventional DOM interaction
            var linqButton = new Button { InnerHtml = "Test Linq..." };
            linqButton.Click += e =>
            {
                int value = "abc".Select(a => a - 'a').Sum();
                Console.WriteLine(value);

                value = "abcdefg".Select(a => a - 'a').Sum();
                Console.WriteLine(value);
            };

            //Browser.Document.Body.Add(linqButton);
        }