/// <summary>
        /// Initialize the AllJoyn portions of the application.
        /// </summary>
        private void InitializeAllJoyn()
        {
            Task t1 = new Task(() =>
            {
                try
                {
                    Debug.UseOSLogging(true);
                    //Debug.SetDebugLevel("ALL", 1);
                    //Debug.SetDebugLevel("ALLJOYN", 7);

                    bus = new BusAttachment(ApplicationName, true, 4);
                    bus.Start();

                    const string connectSpec = "null:";
                    bus.ConnectAsync(connectSpec).AsTask().Wait();
                    DisplayStatus("Connected to AllJoyn successfully.");

                    busListeners = new Listeners(bus, this);
                    bus.RegisterBusListener(busListeners);
                    chatService = new ChatSessionObject(bus, ObjectPath, this);
                    bus.RegisterBusObject(chatService);
                    bus.FindAdvertisedName(NamePrefix);
                }
                catch (Exception ex)
                {
                    QStatus stat  = AllJoynException.GetErrorCode(ex.HResult);
                    string errMsg = AllJoynException.GetErrorMessage(ex.HResult);
                    DisplayStatus("InitializeAllJoyn Error : " + errMsg);
                }
            });

            t1.Start();
        }
        public void RegisterBusListenerTest()
        {
            BusAttachment service = new BusAttachment("service", true, 4);

            service.Start();
            service.ConnectAsync(connectSpec).AsTask().Wait();
            service.RequestName("org.alljoyn.service", (byte)RequestNameType.DBUS_NAME_DO_NOT_QUEUE);
            service.BindSessionPort(78, new ushort[1], new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false,
                                                                       ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY), new SessionPortListener(service));
            service.AdvertiseName("org.alljoyn.service", TransportMaskType.TRANSPORT_ANY);

            BusAttachment   bus = new BusAttachment("buslistenertest", true, 4);
            BusListenerTest bl  = new BusListenerTest(bus);

            bus.RegisterBusListener(bl.bl);
            listenerRegistered.WaitOne();
            bus.Start();
            bus.ConnectAsync(connectSpec).AsTask().Wait();
            bus.RequestName("org.alljoyn.buslistener", (byte)RequestNameType.DBUS_NAME_DO_NOT_QUEUE);
            nameOwnerChanged.WaitOne();
            bus.FindAdvertisedName("org.alljoyn.service");
            foundAdvertisedName.WaitOne();
            service.CancelAdvertiseName("org.alljoyn.service", TransportMaskType.TRANSPORT_ANY);
            lostAdvertisedName.WaitOne();
            bus.CancelFindAdvertisedName("org.alljoyn.service");
            bus.UnregisterBusListener(bl.bl);
            listenerUnregistered.WaitOne();
            bus.DisconnectAsync(connectSpec).AsTask().Wait();
            // BUGBUG: Don't receive the BusDisconnected signal (this will wait indefinitely)
            //busDisconnected.WaitOne();
            bus.StopAsync().AsTask().Wait();
            // BUGBUG: Don't receive the BusStopping signal (this will wait indefinitely)
            //busStopping.WaitOne();
        }
Exemple #3
0
        async void InitializeAllJoyn()
        {
            Debug.UseOSLogging(true);
            Debug.SetDebugLevel("ALLJOYN", 7);

            _bus = new BusAttachment(APPLICATION_NAME, true, 4);
            string connectSpec = "null:";

            _bus.Start();

            try
            {
                _mp3Reader = new MP3Reader();

                if (_streamingSong != null)
                {
                    _streamingSongBasicProperties = await _streamingSong.GetBasicPropertiesAsync();

                    if (_streamingSongBasicProperties != null)
                    {
                        _streamingSongMusicProperties = await _streamingSong.Properties.GetMusicPropertiesAsync();

                        if (_streamingSongMusicProperties != null)
                        {
                            await _mp3Reader.SetFileAsync(_streamingSong);

                            _bus.ConnectAsync(connectSpec).AsTask().Wait();
                            _connected = true;

                            _listeners = new Listeners(_bus, this);
                            _bus.RegisterBusListener(_listeners);
                            _mediaSource = new MediaSource(_bus);
                            _audioStream = new AudioStream(_bus, "mp3", _mp3Reader, 100, 1000);
                            _mediaSource.AddStream(_audioStream);

                            /* Register MediaServer bus object */
                            _bus.RegisterBusObject(_mediaSource.MediaSourceBusObject);
                            /* Request a well known name */
                            _bus.RequestName(MediaServerName, (int)(RequestNameType.DBUS_NAME_REPLACE_EXISTING | RequestNameType.DBUS_NAME_DO_NOT_QUEUE));

                            /* Advertise name */
                            _bus.AdvertiseName(MediaServerName, TransportMaskType.TRANSPORT_ANY);

                            /* Bind a session for incoming client connections */
                            SessionOpts opts    = new SessionOpts(TrafficType.TRAFFIC_MESSAGES, true, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY);
                            ushort[]    portOut = new ushort[1];
                            _bus.BindSessionPort(SESSION_PORT, portOut, opts, _listeners);
                        }
                    }
                }
            } catch (Exception ex)
            {
                string  message = ex.Message;
                QStatus status  = AllJoynException.GetErrorCode(ex.HResult);
                string  errMsg  = AllJoynException.GetErrorMessage(ex.HResult);
            }
        }
        public void JoinSessionAsyncTest()
        {
            BusAttachment service          = new BusAttachment("service", true, 4);
            ServiceSessionPortListener spl = new ServiceSessionPortListener(service);

            service.Start();
            service.ConnectAsync(connectSpec).AsTask().Wait();
            service.RequestName("org.alljoyn.testing.service", (byte)RequestNameType.DBUS_NAME_DO_NOT_QUEUE);
            SessionOpts opts = new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY);

            service.BindSessionPort(77, new ushort[1], opts, spl.spl);
            service.AdvertiseName("org.alljoyn.testing.service", TransportMaskType.TRANSPORT_ANY);

            BusAttachment         client = new BusAttachment("client", true, 4);
            BusListener           cbl    = new BusListener(client);
            ClientSessionListener csl    = new ClientSessionListener(client);

            cbl.FoundAdvertisedName += new BusListenerFoundAdvertisedNameHandler(
                (string name, TransportMaskType transport, string namePrefix) =>
            {
                if (namePrefix == "org.alljoyn.testing.service")
                {
                    clientFoundService.Set();
                }
            });
            client.RegisterBusListener(cbl);
            client.Start();
            client.ConnectAsync(connectSpec).AsTask().Wait();
            client.FindAdvertisedName("org.alljoyn.testing.service");
            clientFoundService.WaitOne();
            SessionOpts[]            optsOut  = new SessionOpts[1];
            Task <JoinSessionResult> joinTask = client.JoinSessionAsync("org.alljoyn.testing.service", (ushort)77, csl.sl, opts, optsOut, null).AsTask <JoinSessionResult>();

            joinTask.Wait();
            //The wait of 10ms ensures that the acceptSessionJoiner and sessionJoined callbacks are completed onthe service side.
            Task.Delay(10).Wait();
            if (QStatus.ER_OK == joinTask.Result.Status)
            {
                Assert.IsTrue(spl.AcceptSessionJoinerCalled && spl.SessionJoinedCalled);
                Assert.AreEqual(joinTask.Result.SessionId, spl.SessionId);
                Assert.AreEqual(joinTask.Result.Opts.IsMultipoint, optsOut[0].IsMultipoint);
                Assert.AreEqual(joinTask.Result.Opts.Proximity, optsOut[0].Proximity);
                Assert.AreEqual(joinTask.Result.Opts.Traffic, optsOut[0].Traffic);
                Assert.AreEqual(joinTask.Result.Opts.TransportMask, optsOut[0].TransportMask);
                Assert.AreEqual(joinTask.Result.Opts.IsMultipoint, opts.IsMultipoint);
                Assert.AreEqual(joinTask.Result.Opts.Proximity, opts.Proximity);
                Assert.AreEqual(joinTask.Result.Opts.Traffic, opts.Traffic);
                Assert.AreEqual(joinTask.Result.Opts.TransportMask, opts.TransportMask);
            }
            else
            {
                Assert.IsFalse(true);
            }
            service.LeaveSession(spl.SessionId);
            sessionLost.WaitOne();
        }
        /// <summary>
        /// connects with the bus, creates an interface and advertises a well-known name for
        /// clients to join a session with.
        /// </summary>
        /// <param name="sender">UI control which signaled the click event.</param>
        /// <param name="e">arguments associated with the click event.</param>
        private void Button_RunClick(object sender, RoutedEventArgs e)
        {
            if (busObject == null && busAtt == null)
            {
                Task task = new Task(async() =>
                {
                    try
                    {
                        busAtt = new BusAttachment("SignalServiceApp", true, 4);

                        busObject = new SignalServiceBusObject(busAtt);
                        OutputLine("BusObject Created.");

                        busListener = new SignalServiceBusListener(busAtt);
                        OutputLine("BusAttachment and BusListener Created.");
                        busAtt.RegisterBusListener(busListener);
                        OutputLine("BusListener Registered.");

                        busAtt.Start();
                        await busAtt.ConnectAsync(SignalServiceGlobals.ConnectSpec);
                        OutputLine("Bundled Daemon Registered.");
                        OutputLine("BusAttachment Connected to " + SignalServiceGlobals.ConnectSpec + ".");

                        SessionOpts sessionOpts = new SessionOpts(
                            SignalServiceGlobals.SessionProps.TrType,
                            SignalServiceGlobals.SessionProps.IsMultiPoint,
                            SignalServiceGlobals.SessionProps.PrType,
                            SignalServiceGlobals.SessionProps.TmType);
                        try
                        {
                            ushort[] portOut = new ushort[1];
                            busAtt.BindSessionPort(SignalServiceGlobals.SessionProps.SessionPort, portOut, sessionOpts, busListener);

                            busAtt.RequestName(SignalServiceGlobals.WellKnownServiceName, (int)RequestNameType.DBUS_NAME_DO_NOT_QUEUE);

                            busAtt.AdvertiseName(SignalServiceGlobals.WellKnownServiceName, TransportMaskType.TRANSPORT_ANY);
                            OutputLine("Name is Being Advertised as: " + SignalServiceGlobals.WellKnownServiceName);
                        }
                        catch (COMException ce)
                        {
                            QStatus s = AllJoynException.GetErrorCode(ce.HResult);
                            OutputLine("Errors were produced while establishing the service.");
                            TearDown();
                        }
                    }
                    catch (Exception ex)
                    {
                        OutputLine("Errors occurred while setting up the service.");
                        QStatus status = AllJoynException.GetErrorCode(ex.HResult);
                        busObject      = null;
                        busAtt         = null;
                    }
                });
                task.Start();
            }
        }
        public void FindAdvertisedNameTest()
        {
            gotAllNames.Reset();
            BusAttachment bus = new BusAttachment("advertise", true, 4);

            bus.Start();
            bus.ConnectAsync(connectSpec).AsTask().Wait();

            BusAttachment        clientConsumer = new BusAttachment("clientConsumer", true, 4);
            AdvertiseBusListener bl             = new AdvertiseBusListener(clientConsumer);

            clientConsumer.Start();
            clientConsumer.ConnectAsync(connectSpec).AsTask().Wait();
            clientConsumer.FindAdvertisedName("org.alljoyn.prefix");

            byte   flags = (byte)RequestNameType.DBUS_NAME_DO_NOT_QUEUE;
            string name0 = "org.alljoyn.prefix";
            string name1 = "org.alljoyn.prefix.looooooooooonnnnggggggggggg.sssstttttrrrrringgggg";
            string name2 = "org.alljoyn.prefix.m3455555555552349568868979999";
            string name3 = "org.alljoyn.prefix.asfdff.g123555555.jisjjiofdjkdsf.z45566666";
            string name4 = "org.alljoyn.this.should.not.befound";
            string name5 = "org.alljoyn.pre";
            string name6 = "org.alljoyn";

            bus.RequestName(name4, flags);
            bus.RequestName(name5, flags);
            bus.RequestName(name6, flags);
            bus.RequestName(name0, flags);
            bus.RequestName(name1, flags);
            bus.RequestName(name2, flags);
            bus.RequestName(name3, flags);
            bus.AdvertiseName(name4, TransportMaskType.TRANSPORT_ANY);
            bus.AdvertiseName(name5, TransportMaskType.TRANSPORT_ANY);
            bus.AdvertiseName(name6, TransportMaskType.TRANSPORT_ANY);
            bus.AdvertiseName(name0, TransportMaskType.TRANSPORT_ANY);
            bus.AdvertiseName(name1, TransportMaskType.TRANSPORT_ANY);
            bus.AdvertiseName(name2, TransportMaskType.TRANSPORT_ANY);
            bus.AdvertiseName(name3, TransportMaskType.TRANSPORT_ANY);

            gotAllNames.WaitOne();

            lock (bl.FoundNames)
            {
                Assert.IsTrue(bl.FoundNames.Contains(name0));
                Assert.IsTrue(bl.FoundNames.Contains(name1));
                Assert.IsTrue(bl.FoundNames.Contains(name2));
                Assert.IsTrue(bl.FoundNames.Contains(name3));
                Assert.IsFalse(bl.FoundNames.Contains(name4));
                Assert.IsFalse(bl.FoundNames.Contains(name5));
                Assert.IsFalse(bl.FoundNames.Contains(name6));
            }
        }
        public void ConnectAsyncTest()
        {
            BusAttachment bus = new BusAttachment("connect", true, 4);

            bus.Start();

            for (int i = 0; i < 5; i++)
            {
                bus.ConnectAsync(connectSpec).AsTask().Wait();
                Assert.IsTrue(bus.IsConnected());
                bus.DisconnectAsync(connectSpec).AsTask().Wait();
                Assert.IsFalse(bus.IsConnected());
            }
        }
        public void NameHasOwnerTest()
        {
            BusAttachment bus1 = new BusAttachment("one", true, 4);

            bus1.Start();
            bus1.ConnectAsync(connectSpec).AsTask().Wait();
            bus1.RequestName("org.alljoyn.nametaken", (byte)RequestNameType.DBUS_NAME_DO_NOT_QUEUE);

            BusAttachment bus2 = new BusAttachment("two", true, 4);

            bus2.Start();
            bus2.ConnectAsync(connectSpec).AsTask().Wait();
            bool[] isTaken = new bool[1];
            bus2.NameHasOwner("org.alljoyn.nametaken", isTaken);
            Assert.IsTrue(isTaken[0]);
        }
        public void BindSessionPortTest()
        {
            BusAttachment bus = new BusAttachment("bindports", true, 4);

            bus.Start();
            bus.ConnectAsync(connectSpec).AsTask().Wait();

            SessionOpts         opts = new SessionOpts(TrafficType.TRAFFIC_MESSAGES, true, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY);
            SessionPortListener spl  = new SessionPortListener(bus);

            for (ushort i = 1; i <= 10; i++)
            {
                ushort[] portOut = new ushort[1];
                bus.BindSessionPort((ushort)(i * 10), portOut, opts, spl);
                Assert.AreEqual((ushort)(i * 10), portOut[0]);
            }
        }
        public void SignalTest()
        {
            BusAttachment   service = new BusAttachment("signalservice", true, 4);
            SignalBusObject busObj  = new SignalBusObject(service, "/sigtest");

            service.Start();
            service.ConnectAsync(connectSpec).AsTask().Wait();
            SessionPortListener spl = new SessionPortListener(service);

            spl.AcceptSessionJoiner += new SessionPortListenerAcceptSessionJoinerHandler((ushort sessionPort, string joiner, SessionOpts opts) =>
            {
                Assert.AreEqual(89, sessionPort);
                return(true);
            });
            service.RequestName("org.alljoyn.signaltesting", (byte)RequestNameType.DBUS_NAME_DO_NOT_QUEUE);
            service.BindSessionPort(89, new ushort[1], new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false,
                                                                       ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY), spl);
            service.AdvertiseName("org.alljoyn.signaltesting", TransportMaskType.TRANSPORT_ANY);

            BusAttachment    client = new BusAttachment("methodcaller", true, 4);
            ServiceBusObject sbo    = new ServiceBusObject(client, "/clientbusobj");
            BusListener      bl     = new BusListener(client);

            client.RegisterBusListener(bl);
            bl.FoundAdvertisedName += new BusListenerFoundAdvertisedNameHandler(
                (string name, TransportMaskType transport, string namePrefix) =>
            {
                foundSignalObjectName.Set();
            });
            client.Start();
            client.ConnectAsync(connectSpec).AsTask().Wait();
            client.FindAdvertisedName("org.alljoyn.signaltesting");
            foundSignalObjectName.WaitOne();

            Task <JoinSessionResult> joinTask = client.JoinSessionAsync("org.alljoyn.signaltesting", 89, new SessionListener(client),
                                                                        new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY), new SessionOpts[1], null).AsTask <JoinSessionResult>();

            joinTask.Wait();
            Assert.IsTrue(QStatus.ER_OK == joinTask.Result.Status);

            // TODO: call BusObject.Signal() for each one of the signals in the interface and make sure
            // they're received and the data is consistent with what was sent.
        }
        public async void EnablePeerSecurityTest()
        {
            BusAttachment      clientBus = new BusAttachment("client", true, 4);
            ClientAuthListener cl        = new ClientAuthListener(clientBus);

            clientBus.Start();
            clientBus.EnablePeerSecurity("ALLJOYN_SRP_LOGON", cl.al, "/.alljoyn_keystore/s_central.ks", true);
            await clientBus.ConnectAsync(connectSpec);

            Assert.IsTrue(clientBus.IsPeerSecurityEnabled());

            BusAttachment          srpLogonBus = new BusAttachment("srplogon", true, 4);
            SRP_LOGON_AuthListener srpl        = new SRP_LOGON_AuthListener(srpLogonBus);

            srpLogonBus.Start();
            srpLogonBus.EnablePeerSecurity("ALLJOYN_SRP_LOGON", srpl.al, "/.alljoyn_keystore/s_central.ks", true);
            await srpLogonBus.ConnectAsync(connectSpec);

            Assert.IsTrue(srpLogonBus.IsPeerSecurityEnabled());

            BusAttachment         srpKeyxBus = new BusAttachment("srpkeyx", true, 4);
            SRP_KEYX_AuthListener srpk       = new SRP_KEYX_AuthListener(srpKeyxBus);

            srpKeyxBus.Start();
            srpKeyxBus.EnablePeerSecurity("ALLJOYN_SRP_KEYX", srpk.al, "/.alljoyn_keystore/s_central.ks", true);
            await srpKeyxBus.ConnectAsync(connectSpec);

            Assert.IsTrue(srpKeyxBus.IsPeerSecurityEnabled());

            BusAttachment         rsaKeyxBus = new BusAttachment("rsakeyx", true, 4);
            RSA_KEYX_AuthListener rsak       = new RSA_KEYX_AuthListener(srpKeyxBus);

            rsaKeyxBus.Start();
            rsaKeyxBus.EnablePeerSecurity("ALLJOYN_RSA_KEYX", rsak.al, "/.alljoyn_keystore/s_central.ks", true);
            await rsaKeyxBus.ConnectAsync(connectSpec);

            Assert.IsTrue(rsaKeyxBus.IsPeerSecurityEnabled());

            // TODO: Finish. Find an easier way to activate the auth process than calling interface method
        }
        private void InitializeAllJoyn()
        {
            Task _t1 = new Task(() =>
            {
                Debug.UseOSLogging(true);
                //Debug.SetDebugLevel("ALLJOYN", 7);

                string connectSpec = "null:";

                try
                {
                    _bus = new BusAttachment(APPLICATION_NAME, true, 4);
                }
                catch (Exception ex)
                {
                    QStatus stat = AllJoynException.GetErrorCode(ex.HResult);
                }
                _bus.Start();

                _bus.ConnectAsync(connectSpec).AsTask().Wait();

                _listeners = new Listeners(_bus, this);
                _bus.RegisterBusListener(_listeners);

                _mediaSink            = new MediaSink(_bus);
                _mediaRender          = new MediaRenderer();
                _mediaRender.OnOpen  += OnOpen;
                _mediaRender.OnPlay  += OnPlay;
                _mediaRender.OnPause += OnPause;
                _mediaRender.OnClose += OnClose;

                _bus.FindAdvertisedName(MEDIA_SERVER_NAME);
            });

            _t1.Start();
        }
        async void InitializeAllJoyn(){
            Debug.UseOSLogging(true);
            Debug.SetDebugLevel("ALLJOYN", 7);

            _bus = new BusAttachment(APPLICATION_NAME, true, 4);
            string connectSpec = "null:";
            _bus.Start();

            try
            {
                _mp3Reader = new MP3Reader();

                if (_streamingSong != null)
                {
                    _streamingSongBasicProperties = await _streamingSong.GetBasicPropertiesAsync();
                    if (_streamingSongBasicProperties != null)
                    {
                        _streamingSongMusicProperties = await _streamingSong.Properties.GetMusicPropertiesAsync();
                        if (_streamingSongMusicProperties != null)
                        {
                            await _mp3Reader.SetFileAsync(_streamingSong);

                            _bus.ConnectAsync(connectSpec).AsTask().Wait();
                            _connected = true;

                            _listeners = new Listeners(_bus, this);
                            _bus.RegisterBusListener(_listeners);
                            _mediaSource = new MediaSource(_bus);
                            _audioStream = new AudioStream(_bus, "mp3", _mp3Reader, 100, 1000);
                            _mediaSource.AddStream(_audioStream);

                            /* Register MediaServer bus object */ 
                            _bus.RegisterBusObject(_mediaSource.MediaSourceBusObject); 
                             /* Request a well known name */ 
                            _bus.RequestName(MediaServerName, (int)(RequestNameType.DBUS_NAME_REPLACE_EXISTING | RequestNameType.DBUS_NAME_DO_NOT_QUEUE));

                            /* Advertise name */
                            _bus.AdvertiseName(MediaServerName, TransportMaskType.TRANSPORT_ANY);
   
                            /* Bind a session for incoming client connections */
                            SessionOpts opts = new SessionOpts(TrafficType.TRAFFIC_MESSAGES, true, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY);
                            ushort[] portOut = new ushort[1];
                            _bus.BindSessionPort(SESSION_PORT, portOut, opts, _listeners);
                        }
                    }
                }
            } catch (Exception ex)
            {
                string message = ex.Message;
                QStatus status = AllJoynException.GetErrorCode(ex.HResult);
                string errMsg = AllJoynException.GetErrorMessage(ex.HResult);
            }
        }
        /// <summary>
        /// Connects to the bus, finds the service and calls the 'cat' with the two
        /// arguments "Hello " and "World!"
        /// </summary>
        /// <param name="sender">UI control which signaled the click event</param>
        /// <param name="e">arguments associated with the click event</param>
        private void Button_RunClick(object sender, RoutedEventArgs e)
        {
            if (!runningClient)
            {
                Task task = new Task(async() =>
                {
                    try
                    {
                        runningClient = true;

                        busAtt = new BusAttachment("ClientApp", true, 4);
                        this.OutputLine("BusAttachment Created.");

                        BasicClientBusListener basicClientBusListener = new BasicClientBusListener(busAtt, foundNameEvent);
                        busAtt.RegisterBusListener(basicClientBusListener);
                        this.OutputLine("BusListener Registered.");

                        /* Create and register the bundled daemon. The client process connects to daemon over tcp connection */
                        busAtt.Start();
                        await busAtt.ConnectAsync(BasicClientGlobals.ConnectSpec);
                        this.OutputLine("Bundled Daemon Registered.");
                        this.OutputLine("BusAttachment Connected to " + BasicClientGlobals.ConnectSpec + ".");

                        busAtt.FindAdvertisedName(BasicClientGlobals.WellKnownServiceName);
                        foundNameEvent.WaitOne();

                        /* Configure session properties and request a session with device with wellKnownName */
                        SessionOpts sessionOpts = new SessionOpts(
                            BasicClientGlobals.SessionProps.TrType,
                            BasicClientGlobals.SessionProps.IsMultiPoint,
                            BasicClientGlobals.SessionProps.PrType,
                            BasicClientGlobals.SessionProps.TmType);
                        SessionOpts[] sOptsOut        = new SessionOpts[1];
                        JoinSessionResult joinResults = await busAtt.JoinSessionAsync(
                            BasicClientGlobals.WellKnownServiceName,
                            BasicClientGlobals.SessionProps.SessionPort,
                            basicClientBusListener,
                            sessionOpts,
                            sOptsOut,
                            null);
                        QStatus status = joinResults.Status;
                        if (QStatus.ER_OK != status)
                        {
                            this.OutputLine("Joining a session with the Service was unsuccessful.");
                        }
                        else
                        {
                            this.OutputLine("Join Session was successful (sessionId=" + joinResults.SessionId + ").");
                        }

                        // Create the proxy for the service interface by introspecting the service bus object
                        ProxyBusObject proxyBusObject = new ProxyBusObject(busAtt, BasicClientGlobals.WellKnownServiceName, BasicClientGlobals.ServicePath, 0);
                        if (QStatus.ER_OK == status)
                        {
                            IntrospectRemoteObjectResult introResult = await proxyBusObject.IntrospectRemoteObjectAsync(null);
                            status = introResult.Status;
                            if (QStatus.ER_OK != status)
                            {
                                this.OutputLine("Introspection of the service bus object failed.");
                            }
                            else
                            {
                                this.OutputLine("Introspection of the service bus object was successful.");
                            }
                        }

                        if (QStatus.ER_OK == status)
                        {
                            // Call 'cat' method with the two string to be concatenated ("Hello" and " World!")
                            MsgArg[] catMe = new MsgArg[2];
                            catMe[0]       = new MsgArg("s", new object[] { "Hello" });
                            catMe[1]       = new MsgArg("s", new object[] { " World!" });

                            InterfaceDescription interfaceDescription = proxyBusObject.GetInterface(BasicClientGlobals.InterfaceName);
                            InterfaceMember interfaceMember           = interfaceDescription.GetMember("cat");

                            this.OutputLine("Calling the 'cat' method of the service with args 'Hello' and ' World!'");
                            MethodCallResult callResults = await proxyBusObject.MethodCallAsync(interfaceMember, catMe, null, 100000, 0);
                            Message msg = callResults.Message;
                            if (msg.Type == AllJoynMessageType.MESSAGE_METHOD_RET)
                            {
                                string strRet = msg.GetArg(0).Value as string;
                                this.OutputLine("Sender '" + msg.Sender + "' returned the value '" + strRet + "'");
                            }
                            else
                            {
                                this.OutputLine("The 'cat' method call produced errors of type: " + msg.Type.ToString());
                            }
                        }

                        TearDown();
                    }
                    catch (Exception ex)
                    {
                        QStatus s = AllJoynException.GetErrorCode(ex.HResult);
                    }
                });
                task.Start();
            }
        }
        public void AdvertisingTest()
        {
            BusAttachment bus = new BusAttachment("advertise", true, 4);

            bus.Start();
            bus.ConnectAsync(connectSpec).AsTask().Wait();

            BusAttachment        clientConsumer = new BusAttachment("clientConsumer", true, 4);
            AdvertiseBusListener bl             = new AdvertiseBusListener(clientConsumer);

            clientConsumer.Start();
            clientConsumer.ConnectAsync(connectSpec).AsTask().Wait();
            clientConsumer.FindAdvertisedName("org.alljoyn.one");
            clientConsumer.FindAdvertisedName("org.alljoyn.two");
            clientConsumer.FindAdvertisedName("org.alljoyn.three");
            clientConsumer.FindAdvertisedName("org.alljoyn.four");

            byte   flags = (byte)RequestNameType.DBUS_NAME_DO_NOT_QUEUE;
            string name1 = "org.alljoyn.one";
            string name2 = "org.alljoyn.two";
            string name3 = "org.alljoyn.three";
            string name4 = "org.alljoyn.four";

            bus.RequestName(name1, flags);
            bus.RequestName(name2, flags);
            bus.RequestName(name3, flags);
            bus.RequestName(name4, flags);

            bus.AdvertiseName(name1, TransportMaskType.TRANSPORT_ANY);
            bus.AdvertiseName(name2, TransportMaskType.TRANSPORT_ANY);
            bus.AdvertiseName(name3, TransportMaskType.TRANSPORT_ANY);
            bus.AdvertiseName(name4, TransportMaskType.TRANSPORT_ANY);

            gotAllNames.WaitOne();

            lock (bl.FoundNames)
            {
                Assert.IsTrue(bl.FoundNames.Contains(name1));
                Assert.IsTrue(bl.FoundNames.Contains(name2));
                Assert.IsTrue(bl.FoundNames.Contains(name3));
                Assert.IsTrue(bl.FoundNames.Contains(name4));
            }

            gotAllNames.Reset();

            bus.CancelAdvertiseName(name1, TransportMaskType.TRANSPORT_ANY);
            bus.CancelAdvertiseName(name2, TransportMaskType.TRANSPORT_ANY);
            bus.CancelAdvertiseName(name3, TransportMaskType.TRANSPORT_ANY);
            bus.CancelAdvertiseName(name4, TransportMaskType.TRANSPORT_ANY);

            gotAllNames.WaitOne();

            lock (bl.LostNames)
            {
                Assert.IsTrue(bl.LostNames.Contains(name1));
                Assert.IsTrue(bl.LostNames.Contains(name2));
                Assert.IsTrue(bl.LostNames.Contains(name3));
                Assert.IsTrue(bl.LostNames.Contains(name4));
            }

            // TODO: Make sure we're not still receiving advertisements for the names
        }
Exemple #16
0
        /// <summary>
        /// Connects to the bus and registers a signal handler for when the 'name' property changes.
        /// </summary>
        /// <param name="sender">UI control which signaled the click event.</param>
        /// <param name="e">arguments associated with the click event.</param>
        private void Button_RunClick(object sender, RoutedEventArgs e)
        {
            if (busAtt == null)
            {
                Task task = new Task(async() =>
                {
                    try
                    {
                        busAtt = new BusAttachment("SignalConsumerApp", true, 4);

                        // create and activate the interface
                        InterfaceDescription[] interfaceDescription = new InterfaceDescription[1];
                        busAtt.CreateInterface(SignalConsumerGlobals.InterfaceName, interfaceDescription, false);
                        interfaceDescription[0].AddSignal("nameChanged", "s", "newName", (byte)0, string.Empty);
                        interfaceDescription[0].AddProperty("name", "s", (byte)PropAccessType.PROP_ACCESS_RW);
                        interfaceDescription[0].Activate();

                        busListener = new SignalConsumerBusListener(busAtt, foundNameEvent);
                        OutputLine("BusAttachment and BusListener Created.");
                        busAtt.RegisterBusListener(busListener);
                        OutputLine("BusListener Registered.");

                        busAtt.Start();
                        busAtt.ConnectAsync(SignalConsumerGlobals.ConnectSpec).AsTask().Wait();
                        OutputLine("Bundled Daemon Registered.");
                        OutputLine("BusAttachment Connected to " + SignalConsumerGlobals.ConnectSpec + ".");

                        busAtt.FindAdvertisedName(SignalConsumerGlobals.WellKnownServiceName);
                        foundNameEvent.WaitOne();

                        /* Configure session properties and request a session with device with wellKnownName */
                        SessionOpts sessionOpts = new SessionOpts(
                            SignalConsumerGlobals.SessionProps.TrType,
                            SignalConsumerGlobals.SessionProps.IsMultiPoint,
                            SignalConsumerGlobals.SessionProps.PrType,
                            SignalConsumerGlobals.SessionProps.TmType);
                        SessionOpts[] sessionOptsOut = new SessionOpts[1];
                        OutputLine("Requesting a session with the well known service name.");
                        JoinSessionResult joinResult = await busAtt.JoinSessionAsync(
                            SignalConsumerGlobals.WellKnownServiceName,
                            SignalConsumerGlobals.SessionProps.SessionPort,
                            busListener,
                            sessionOpts,
                            sessionOptsOut,
                            null);

                        if (QStatus.ER_OK == joinResult.Status)
                        {
                            OutputLine("Join Session was successful (sessionId=" + joinResult.SessionId + ").");
                            busAtt.AddMatch("type='signal',interface='org.alljoyn.Bus.signal_sample',member='nameChanged'");
                            OutputLine("Subscribed to the 'nameChanged' signal.");
                        }
                        else
                        {
                            OutputLine("Join Session was unsuccessful.");
                        }
                    }
                    catch (Exception ex)
                    {
                        OutputLine("Errors were produced while establishing the application.");
                        QStatus status = AllJoynException.GetErrorCode(ex.HResult);
                        busAtt         = null;
                    }
                });
                task.Start();
            }
        }
        /// <summary>
        /// connects with the bus, creates an interface and advertises a well-known name for
        /// clients to join a session with.
        /// </summary>
        /// <param name="sender">UI control which signaled the click event.</param>
        /// <param name="e">arguments associated with the click event.</param>
        private void Button_RunClick(object sender, RoutedEventArgs e)
        {
            if (busObject == null && busAtt == null)
            {
                Task task = new Task(async () =>
                {
                    try
                    {
                        busAtt = new BusAttachment("SignalServiceApp", true, 4);

                        busObject = new SignalServiceBusObject(busAtt);
                        OutputLine("BusObject Created.");

                        busListener = new SignalServiceBusListener(busAtt);
                        OutputLine("BusAttachment and BusListener Created.");
                        busAtt.RegisterBusListener(busListener);
                        OutputLine("BusListener Registered.");

                        busAtt.Start();
                        await busAtt.ConnectAsync(SignalServiceGlobals.ConnectSpec);
                        OutputLine("Bundled Daemon Registered.");
                        OutputLine("BusAttachment Connected to " + SignalServiceGlobals.ConnectSpec + ".");

                        SessionOpts sessionOpts = new SessionOpts(
                            SignalServiceGlobals.SessionProps.TrType,
                            SignalServiceGlobals.SessionProps.IsMultiPoint,
                            SignalServiceGlobals.SessionProps.PrType,
                            SignalServiceGlobals.SessionProps.TmType);
                        try
                        {
                            ushort[] portOut = new ushort[1];
                            busAtt.BindSessionPort(SignalServiceGlobals.SessionProps.SessionPort, portOut, sessionOpts, busListener);

                            busAtt.RequestName(SignalServiceGlobals.WellKnownServiceName, (int)RequestNameType.DBUS_NAME_DO_NOT_QUEUE);

                            busAtt.AdvertiseName(SignalServiceGlobals.WellKnownServiceName, TransportMaskType.TRANSPORT_ANY);
                            OutputLine("Name is Being Advertised as: " + SignalServiceGlobals.WellKnownServiceName);
                        }
                        catch (COMException ce)
                        {
                            QStatus s = AllJoynException.GetErrorCode(ce.HResult);
                            OutputLine("Errors were produced while establishing the service.");
                            TearDown();
                        }
                    }
                    catch (Exception ex)
                    {
                        OutputLine("Errors occurred while setting up the service.");
                        QStatus status = AllJoynException.GetErrorCode(ex.HResult);
                        busObject = null;
                        busAtt = null;
                    }
                });
                task.Start();
            }
        }
        public void RegisterBusListenerTest()
        {
            BusAttachment service = new BusAttachment("service", true, 4);
            service.Start();
            service.ConnectAsync(connectSpec).AsTask().Wait();
            service.RequestName("org.alljoyn.service", (byte)RequestNameType.DBUS_NAME_DO_NOT_QUEUE);
            service.BindSessionPort(78, new ushort[1], new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false, 
                ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY), new SessionPortListener(service));
            service.AdvertiseName("org.alljoyn.service", TransportMaskType.TRANSPORT_ANY);

            BusAttachment bus = new BusAttachment("buslistenertest", true, 4);
            BusListenerTest bl = new BusListenerTest(bus);
            bus.RegisterBusListener(bl.bl);
            listenerRegistered.WaitOne();
            bus.Start();
            bus.ConnectAsync(connectSpec).AsTask().Wait();
            bus.RequestName("org.alljoyn.buslistener", (byte)RequestNameType.DBUS_NAME_DO_NOT_QUEUE);
            nameOwnerChanged.WaitOne();
            bus.FindAdvertisedName("org.alljoyn.service");
            foundAdvertisedName.WaitOne();
            service.CancelAdvertiseName("org.alljoyn.service", TransportMaskType.TRANSPORT_ANY);
            lostAdvertisedName.WaitOne();
            bus.CancelFindAdvertisedName("org.alljoyn.service");
            bus.UnregisterBusListener(bl.bl);
            listenerUnregistered.WaitOne();
            bus.DisconnectAsync(connectSpec).AsTask().Wait();
            // BUGBUG: Don't receive the BusDisconnected signal (this will wait indefinitely)
            //busDisconnected.WaitOne();
            bus.StopAsync().AsTask().Wait();
            // BUGBUG: Don't receive the BusStopping signal (this will wait indefinitely)
            //busStopping.WaitOne();
        }
        public void NameHasOwnerTest()
        {
            BusAttachment bus1 = new BusAttachment("one", true, 4);
            bus1.Start();
            bus1.ConnectAsync(connectSpec).AsTask().Wait();
            bus1.RequestName("org.alljoyn.nametaken", (byte)RequestNameType.DBUS_NAME_DO_NOT_QUEUE);

            BusAttachment bus2 = new BusAttachment("two", true, 4);
            bus2.Start();
            bus2.ConnectAsync(connectSpec).AsTask().Wait();
            bool[] isTaken = new bool[1];
            bus2.NameHasOwner("org.alljoyn.nametaken", isTaken);
            Assert.IsTrue(isTaken[0]);
        }
        /// <summary>
        /// Connects to the bus, finds the service and sets the 'name' property to the value 
        /// specified by the user.
        /// </summary>
        /// <param name="sender">UI control which signaled the click event.</param>
        /// <param name="e">Arguments associated with the click event.</param>
        private void Button_RunNameChangeClient(object sender, RoutedEventArgs e)
        {
            if (this.TextBox_Input.Text == string.Empty)
            {
                this.OutputLine("You must provide an argument to run Name Change Client!");
            }

            if (!runningClient && this.TextBox_Input.Text != string.Empty)
            {
                string newName = this.TextBox_Input.Text;
                Task task = new Task(async () =>
                {
                    try
                    {
                        runningClient = true;

                        busAtt = new BusAttachment("NameChangeApp", true, 4);
                        OutputLine("BusAttachment Created.");

                        NameChangeBusListener busListener = new NameChangeBusListener(busAtt, foundNameEvent);
                        busAtt.RegisterBusListener(busListener);
                        OutputLine("BusListener Registered.");

                        /* Create and register the bundled daemon. The client process connects to daemon over tcp connection */
                        busAtt.Start();
                        await busAtt.ConnectAsync(NameChangeGlobals.ConnectSpec);
                        OutputLine("Bundled Daemon Registered.");
                        OutputLine("BusAttachment Connected to " + NameChangeGlobals.ConnectSpec + ".");

                        busAtt.FindAdvertisedName(NameChangeGlobals.WellKnownServiceName);
                        foundNameEvent.WaitOne();

                        /* Configure session properties and request a session with device with wellKnownName */
                        SessionOpts sOpts = new SessionOpts(
                            NameChangeGlobals.SessionProps.TrType,
                            NameChangeGlobals.SessionProps.IsMultiPoint,
                            NameChangeGlobals.SessionProps.PrType,
                            NameChangeGlobals.SessionProps.TmType);
                        SessionOpts[] sOptsOut = new SessionOpts[1];
                        JoinSessionResult joinResults = await busAtt.JoinSessionAsync(
                            NameChangeGlobals.WellKnownServiceName, 
                            NameChangeGlobals.SessionProps.SessionPort, 
                            busListener, 
                            sOpts, 
                            sOptsOut, 
                            null);
                        QStatus status = joinResults.Status;
                        if (QStatus.ER_OK == status) 
                        {
                            this.OutputLine("Join Session was successful (sessionId=" + joinResults.SessionId + ").");
                        }
                        else 
                        {
                            this.OutputLine("Join Session was unsuccessful.");
                        }

                        ProxyBusObject pbo = new ProxyBusObject(busAtt, NameChangeGlobals.WellKnownServiceName, NameChangeGlobals.ServicePath, sessionId);
                        if (QStatus.ER_OK == status)
                        {
                            IntrospectRemoteObjectResult introResult = await pbo.IntrospectRemoteObjectAsync(null);
                            status = introResult.Status;
                            if (QStatus.ER_OK == status)
                            {
                                this.OutputLine("Introspection of the service object was successful.");
                            }
                            else
                            {
                                this.OutputLine("Introspection of the service object was unsuccessful.");
                            }
                        }

                        if (QStatus.ER_OK == status)
                        {
                            object[] obj = new object[] { newName };
                            MsgArg msg = new MsgArg("s", obj);
                            SetPropertyResult setResult = await pbo.SetPropertyAsync(NameChangeGlobals.InterfaceName, "name", msg, null, 2000);
                        }

                        TearDown();
                    }
                    catch (Exception ex)
                    {
                        QStatus s = AllJoynException.GetErrorCode(ex.HResult);
                        OutputLine("Error: " + ex.ToString());
                        runningClient = false;
                    }
                });
                task.Start();
            }
        }
        public void AddMatchTest()
        {
            BusAttachment  bus    = new BusAttachment("addmatch", true, 4);
            AddMatchBusObj busObj = new AddMatchBusObj(bus);
            BusListener    bl     = new BusListener(bus);

            bus.RegisterBusListener(bl);
            busObj.MatchValid = true;
            bus.Start();
            bus.ConnectAsync(connectSpec).AsTask().Wait();

            BusAttachment service = new BusAttachment("service", true, 4);
            BusObject     busObj2 = new BusObject(service, "/serviceTest", false);

            InterfaceDescription[] intf = new InterfaceDescription[1];
            service.CreateInterface("org.alljoyn.addmatchtest", intf, false);
            intf[0].AddSignal("testSig", "s", "str", (byte)0, "");
            intf[0].Activate();
            busObj2.AddInterface(intf[0]);
            service.RegisterBusObject(busObj2);
            service.Start();
            service.ConnectAsync(connectSpec).AsTask().Wait();
            service.RequestName("org.alljoyn.addmatch", (byte)RequestNameType.DBUS_NAME_DO_NOT_QUEUE);
            service.BindSessionPort(43, new ushort[1], new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false,
                                                                       ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY), new SessionPortListener(service));
            service.AdvertiseName("org.alljoyn.addmatch", TransportMaskType.TRANSPORT_ANY);

            bl.FoundAdvertisedName += new BusListenerFoundAdvertisedNameHandler(
                (string name, TransportMaskType transport, string namePrefix) =>
            {
                if (namePrefix == "org.alljoyn.addmatch")
                {
                    foundService.Set();
                }
            });
            bus.FindAdvertisedName("org.alljoyn.addmatch");

            foundService.WaitOne();
            Task <JoinSessionResult> join = bus.JoinSessionAsync("org.alljoyn.addmatch", 43, new SessionListener(bus),
                                                                 new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY),
                                                                 new SessionOpts[1], null).AsTask <JoinSessionResult>();

            join.Wait();
            Assert.IsTrue(QStatus.ER_OK != join.Result.Status);

            bus.AddMatch("type='signal',interface='org.alljoyn.addmatchtest',member='testSig'");
            for (int i = 0; i < 5; i++)
            {
                calledHandle.Reset();
                MsgArg sigArg1 = new MsgArg("s", new object[] { "hello" + i });
                busObj2.Signal("", 0, intf[0].GetSignal("testSig"), new MsgArg[] { sigArg1 }, 0, (byte)AllJoynFlagType.ALLJOYN_FLAG_GLOBAL_BROADCAST);
                calledHandle.WaitOne();
            }

            bus.RemoveMatch("type='signal',interface='org.alljoyn.addmatchtest',member='testSig'");
            busObj.MatchValid = false;
            for (int i = 0; i < 10; i++)
            {
                MsgArg sigArg1 = new MsgArg("s", new object[] { "hello" + i });
                busObj2.Signal("", 0, intf[0].GetSignal("testSig"), new MsgArg[] { sigArg1 }, 0, (byte)AllJoynFlagType.ALLJOYN_FLAG_GLOBAL_BROADCAST);
            }

            bus.AddMatch("type='signal',interface='org.alljoyn.addmatchtest',member='testSig'");
            busObj.MatchValid = true;
            for (int i = 0; i < 5; i++)
            {
                calledHandle.Reset();
                MsgArg sigArg1 = new MsgArg("s", new object[] { "hello" + i });
                busObj2.Signal("", 0, intf[0].GetSignal("testSig"), new MsgArg[] { sigArg1 }, 0, (byte)AllJoynFlagType.ALLJOYN_FLAG_GLOBAL_BROADCAST);
                calledHandle.WaitOne();
            }
        }
        /// <summary>
        /// Initialize the AllJoyn portions of the application.
        /// </summary>
        private void InitializeAllJoyn()
        {
            Task t1 = new Task(() =>
            {
                try
                {
                    Debug.UseOSLogging(true);
                    //Debug.SetDebugLevel("ALL", 1);
                    //Debug.SetDebugLevel("ALLJOYN", 7);

                    bus = new BusAttachment(ApplicationName, true, 4);
                    bus.Start();

                    const string connectSpec = "null:";
                    bus.ConnectAsync(connectSpec).AsTask().Wait();
                    DisplayStatus("Connected to AllJoyn successfully.");

                    busListeners = new Listeners(bus, this);
                    bus.RegisterBusListener(busListeners);
                    chatService = new ChatSessionObject(bus, ObjectPath, this);
                    bus.RegisterBusObject(chatService);
                    bus.FindAdvertisedName(NamePrefix);
                }
                catch (Exception ex)
                {
                    QStatus stat = AllJoynException.GetErrorCode(ex.HResult);
                    string errMsg = AllJoynException.GetErrorMessage(ex.HResult);
                    DisplayStatus("InitializeAllJoyn Error : " + errMsg);
                }
            });
            t1.Start();
        }
        public void AddMethodHandlerTest()
        {
            BusAttachment service = new BusAttachment("methodhandler", true, 4);
            MethodHandlerBusObject busObj = new MethodHandlerBusObject(service, "/handlertest");
            service.Start();
            service.ConnectAsync(connectSpec).AsTask().Wait();
            SessionPortListener spl = new SessionPortListener(service);
            spl.AcceptSessionJoiner += new SessionPortListenerAcceptSessionJoinerHandler((ushort sessionPort, string joiner, SessionOpts opts) =>
            {
                Assert.AreEqual(33, sessionPort);
                return true;
            });
            service.RequestName("org.alljoyn.methodhandlertest", (byte)RequestNameType.DBUS_NAME_DO_NOT_QUEUE);
            service.BindSessionPort(33, new ushort[1], new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false,
                ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY), spl);
            service.AdvertiseName("org.alljoyn.methodhandlertest", TransportMaskType.TRANSPORT_ANY);

            BusAttachment client = new BusAttachment("methodcaller", true, 4);
            BusListener bl = new BusListener(client);
            client.RegisterBusListener(bl);
            bl.FoundAdvertisedName += new BusListenerFoundAdvertisedNameHandler(
                (string name, TransportMaskType transport, string namePrefix) =>
                {
                    foundMethodObjectName.Set();
                });
            client.Start();
            client.ConnectAsync(connectSpec).AsTask().Wait();
            client.FindAdvertisedName("org.alljoyn.methodhandlertest");
            foundMethodObjectName.WaitOne();
            Task<JoinSessionResult> joinTask = client.JoinSessionAsync("org.alljoyn.methodhandlertest", 33, new SessionListener(client),
                new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY), new SessionOpts[1], null).AsTask<JoinSessionResult>();
            joinTask.Wait();
            Assert.IsTrue(QStatus.ER_OK == joinTask.Result.Status);
            ProxyBusObject proxy = new ProxyBusObject(client, "org.alljoyn.methodhandlertest", "/handlertest", joinTask.Result.SessionId);
            Task<IntrospectRemoteObjectResult> introTask = proxy.IntrospectRemoteObjectAsync(null).AsTask<IntrospectRemoteObjectResult>();
            introTask.Wait();
            Assert.IsTrue(QStatus.ER_OK == introTask.Result.Status);

            MsgArg[] args1 = new MsgArg[2];
            args1[0] = new MsgArg("s", new object[] { "one" });
            args1[1] = new MsgArg("s", new object[] { "two" });
            Task<MethodCallResult> catTask = proxy.MethodCallAsync(service.GetInterface("org.alljoyn.methodhandler").GetMethod("cat"),
                args1, null, 60000, (byte)0).AsTask<MethodCallResult>();
            catTask.Wait();
            Assert.IsTrue(AllJoynMessageType.MESSAGE_METHOD_RET == catTask.Result.Message.Type);
            Assert.AreEqual("onetwo", catTask.Result.Message.GetArg(0).Value.ToString());

            // Check BUGBUG above
            //MsgArg[] args2 = new MsgArg[1];
            //args2[0] = new MsgArg("s", new object[] { "hello" });
            //Task<MethodCallResult> sayHiTask = proxy.MethodCallAsync(service.GetInterface("org.alljoyn.methodhandler").GetMethod("sayhi"),
            //    args2, null, 60000, (byte)0).AsTask<MethodCallResult>();
            //sayHiTask.Wait();
            //Assert.IsTrue(AllJoynMessageType.MESSAGE_METHOD_RET == sayHiTask.Result.Message.Type);
            //Assert.AreEqual("aloha", sayHiTask.Result.Message.GetArg(0).Value.ToString());

            // TODO: add another method call that test function with signature MethodReply(AllJoyn.Message msg, string error, string errorMessage)
        }
        /// <summary>
        /// Connects to the bus, finds the service and sets the 'name' property to the value
        /// specified by the user.
        /// </summary>
        /// <param name="sender">UI control which signaled the click event.</param>
        /// <param name="e">Arguments associated with the click event.</param>
        private void Button_RunNameChangeClient(object sender, RoutedEventArgs e)
        {
            if (this.TextBox_Input.Text == string.Empty)
            {
                this.OutputLine("You must provide an argument to run Name Change Client!");
            }

            if (!runningClient && this.TextBox_Input.Text != string.Empty)
            {
                string newName = this.TextBox_Input.Text;
                Task   task    = new Task(async() =>
                {
                    try
                    {
                        runningClient = true;

                        busAtt = new BusAttachment("NameChangeApp", true, 4);
                        OutputLine("BusAttachment Created.");

                        NameChangeBusListener busListener = new NameChangeBusListener(busAtt, foundNameEvent);
                        busAtt.RegisterBusListener(busListener);
                        OutputLine("BusListener Registered.");

                        /* Create and register the bundled daemon. The client process connects to daemon over tcp connection */
                        busAtt.Start();
                        await busAtt.ConnectAsync(NameChangeGlobals.ConnectSpec);
                        OutputLine("Bundled Daemon Registered.");
                        OutputLine("BusAttachment Connected to " + NameChangeGlobals.ConnectSpec + ".");

                        busAtt.FindAdvertisedName(NameChangeGlobals.WellKnownServiceName);
                        foundNameEvent.WaitOne();

                        /* Configure session properties and request a session with device with wellKnownName */
                        SessionOpts sOpts = new SessionOpts(
                            NameChangeGlobals.SessionProps.TrType,
                            NameChangeGlobals.SessionProps.IsMultiPoint,
                            NameChangeGlobals.SessionProps.PrType,
                            NameChangeGlobals.SessionProps.TmType);
                        SessionOpts[] sOptsOut        = new SessionOpts[1];
                        JoinSessionResult joinResults = await busAtt.JoinSessionAsync(
                            NameChangeGlobals.WellKnownServiceName,
                            NameChangeGlobals.SessionProps.SessionPort,
                            busListener,
                            sOpts,
                            sOptsOut,
                            null);
                        QStatus status = joinResults.Status;
                        if (QStatus.ER_OK == status)
                        {
                            this.OutputLine("Join Session was successful (sessionId=" + joinResults.SessionId + ").");
                        }
                        else
                        {
                            this.OutputLine("Join Session was unsuccessful.");
                        }

                        ProxyBusObject pbo = new ProxyBusObject(busAtt, NameChangeGlobals.WellKnownServiceName, NameChangeGlobals.ServicePath, sessionId);
                        if (QStatus.ER_OK == status)
                        {
                            IntrospectRemoteObjectResult introResult = await pbo.IntrospectRemoteObjectAsync(null);
                            status = introResult.Status;
                            if (QStatus.ER_OK == status)
                            {
                                this.OutputLine("Introspection of the service object was successful.");
                            }
                            else
                            {
                                this.OutputLine("Introspection of the service object was unsuccessful.");
                            }
                        }

                        if (QStatus.ER_OK == status)
                        {
                            object[] obj = new object[] { newName };
                            MsgArg msg   = new MsgArg("s", obj);
                            SetPropertyResult setResult = await pbo.SetPropertyAsync(NameChangeGlobals.InterfaceName, "name", msg, null, 2000);
                        }

                        TearDown();
                    }
                    catch (Exception ex)
                    {
                        QStatus s = AllJoynException.GetErrorCode(ex.HResult);
                        OutputLine("Error: " + ex.ToString());
                        runningClient = false;
                    }
                });
                task.Start();
            }
        }
        public void FindAdvertisedNameTest()
        {
            gotAllNames.Reset();
            BusAttachment bus = new BusAttachment("advertise", true, 4);
            bus.Start();
            bus.ConnectAsync(connectSpec).AsTask().Wait();

            BusAttachment clientConsumer = new BusAttachment("clientConsumer", true, 4);
            AdvertiseBusListener bl = new AdvertiseBusListener(clientConsumer);
            clientConsumer.Start();
            clientConsumer.ConnectAsync(connectSpec).AsTask().Wait();
            clientConsumer.FindAdvertisedName("org.alljoyn.prefix");

            byte flags = (byte)RequestNameType.DBUS_NAME_DO_NOT_QUEUE;
            string name0 = "org.alljoyn.prefix";
            string name1 = "org.alljoyn.prefix.looooooooooonnnnggggggggggg.sssstttttrrrrringgggg";
            string name2 = "org.alljoyn.prefix.m3455555555552349568868979999";
            string name3 = "org.alljoyn.prefix.asfdff.g123555555.jisjjiofdjkdsf.z45566666";
            string name4 = "org.alljoyn.this.should.not.befound";
            string name5 = "org.alljoyn.pre";
            string name6 = "org.alljoyn";
            bus.RequestName(name4, flags);
            bus.RequestName(name5, flags);
            bus.RequestName(name6, flags);
            bus.RequestName(name0, flags);
            bus.RequestName(name1, flags);
            bus.RequestName(name2, flags);
            bus.RequestName(name3, flags);
            bus.AdvertiseName(name4, TransportMaskType.TRANSPORT_ANY);
            bus.AdvertiseName(name5, TransportMaskType.TRANSPORT_ANY);
            bus.AdvertiseName(name6, TransportMaskType.TRANSPORT_ANY);
            bus.AdvertiseName(name0, TransportMaskType.TRANSPORT_ANY);
            bus.AdvertiseName(name1, TransportMaskType.TRANSPORT_ANY);
            bus.AdvertiseName(name2, TransportMaskType.TRANSPORT_ANY);
            bus.AdvertiseName(name3, TransportMaskType.TRANSPORT_ANY);

            gotAllNames.WaitOne();
            
            lock (bl.FoundNames)
            {
                Assert.IsTrue(bl.FoundNames.Contains(name0));
                Assert.IsTrue(bl.FoundNames.Contains(name1));
                Assert.IsTrue(bl.FoundNames.Contains(name2));
                Assert.IsTrue(bl.FoundNames.Contains(name3));
                Assert.IsFalse(bl.FoundNames.Contains(name4));
                Assert.IsFalse(bl.FoundNames.Contains(name5));
                Assert.IsFalse(bl.FoundNames.Contains(name6));
            }
        }
        public void AdvertisingTest()
        {
            BusAttachment bus = new BusAttachment("advertise", true, 4);
            bus.Start();
            bus.ConnectAsync(connectSpec).AsTask().Wait();

            BusAttachment clientConsumer = new BusAttachment("clientConsumer", true, 4);
            AdvertiseBusListener bl = new AdvertiseBusListener(clientConsumer);
            clientConsumer.Start();
            clientConsumer.ConnectAsync(connectSpec).AsTask().Wait();
            clientConsumer.FindAdvertisedName("org.alljoyn.one");
            clientConsumer.FindAdvertisedName("org.alljoyn.two");
            clientConsumer.FindAdvertisedName("org.alljoyn.three");
            clientConsumer.FindAdvertisedName("org.alljoyn.four");

            byte flags = (byte)RequestNameType.DBUS_NAME_DO_NOT_QUEUE;
            string name1 = "org.alljoyn.one";
            string name2 = "org.alljoyn.two";
            string name3 = "org.alljoyn.three";
            string name4 = "org.alljoyn.four";

            bus.RequestName(name1, flags);
            bus.RequestName(name2, flags);
            bus.RequestName(name3, flags);
            bus.RequestName(name4, flags);

            bus.AdvertiseName(name1, TransportMaskType.TRANSPORT_ANY);
            bus.AdvertiseName(name2, TransportMaskType.TRANSPORT_ANY);
            bus.AdvertiseName(name3, TransportMaskType.TRANSPORT_ANY);
            bus.AdvertiseName(name4, TransportMaskType.TRANSPORT_ANY);

            gotAllNames.WaitOne();

            lock (bl.FoundNames)
            {
                Assert.IsTrue(bl.FoundNames.Contains(name1));
                Assert.IsTrue(bl.FoundNames.Contains(name2));
                Assert.IsTrue(bl.FoundNames.Contains(name3));
                Assert.IsTrue(bl.FoundNames.Contains(name4));
            }

            gotAllNames.Reset();

            bus.CancelAdvertiseName(name1, TransportMaskType.TRANSPORT_ANY);
            bus.CancelAdvertiseName(name2, TransportMaskType.TRANSPORT_ANY);
            bus.CancelAdvertiseName(name3, TransportMaskType.TRANSPORT_ANY);
            bus.CancelAdvertiseName(name4, TransportMaskType.TRANSPORT_ANY);

            gotAllNames.WaitOne();

            lock (bl.LostNames)
            {
                Assert.IsTrue(bl.LostNames.Contains(name1));
                Assert.IsTrue(bl.LostNames.Contains(name2));
                Assert.IsTrue(bl.LostNames.Contains(name3));
                Assert.IsTrue(bl.LostNames.Contains(name4));
            }

            // TODO: Make sure we're not still receiving advertisements for the names
        }
        /// <summary>
        /// Connects to the bus and registers a signal handler for when the 'name' property changes.
        /// </summary>
        /// <param name="sender">UI control which signaled the click event.</param>
        /// <param name="e">arguments associated with the click event.</param>
        private void Button_RunClick(object sender, RoutedEventArgs e)
        {
            if (busAtt == null)
            {
                Task task = new Task(async () =>
                {
                    try
                    {
                        busAtt = new BusAttachment("SignalConsumerApp", true, 4);

                        // create and activate the interface
                        InterfaceDescription[] interfaceDescription = new InterfaceDescription[1];
                        busAtt.CreateInterface(SignalConsumerGlobals.InterfaceName, interfaceDescription, false);
                        interfaceDescription[0].AddSignal("nameChanged", "s", "newName", (byte)0, string.Empty);
                        interfaceDescription[0].AddProperty("name", "s", (byte)PropAccessType.PROP_ACCESS_RW);
                        interfaceDescription[0].Activate();

                        busListener = new SignalConsumerBusListener(busAtt, foundNameEvent);
                        OutputLine("BusAttachment and BusListener Created.");
                        busAtt.RegisterBusListener(busListener);
                        OutputLine("BusListener Registered.");

                        busAtt.Start();
                        busAtt.ConnectAsync(SignalConsumerGlobals.ConnectSpec).AsTask().Wait();
                        OutputLine("Bundled Daemon Registered.");
                        OutputLine("BusAttachment Connected to " + SignalConsumerGlobals.ConnectSpec + ".");

                        busAtt.FindAdvertisedName(SignalConsumerGlobals.WellKnownServiceName);
                        foundNameEvent.WaitOne();

                        /* Configure session properties and request a session with device with wellKnownName */
                        SessionOpts sessionOpts = new SessionOpts(
                            SignalConsumerGlobals.SessionProps.TrType,
                            SignalConsumerGlobals.SessionProps.IsMultiPoint,
                            SignalConsumerGlobals.SessionProps.PrType,
                            SignalConsumerGlobals.SessionProps.TmType);
                        SessionOpts[] sessionOptsOut = new SessionOpts[1];
                        OutputLine("Requesting a session with the well known service name.");
                        JoinSessionResult joinResult = await busAtt.JoinSessionAsync(
                            SignalConsumerGlobals.WellKnownServiceName, 
                            SignalConsumerGlobals.SessionProps.SessionPort, 
                            busListener, 
                            sessionOpts, 
                            sessionOptsOut, 
                            null);

                        if (QStatus.ER_OK == joinResult.Status)
                        {
                            OutputLine("Join Session was successful (sessionId=" + joinResult.SessionId + ").");
                            busAtt.AddMatch("type='signal',interface='org.alljoyn.Bus.signal_sample',member='nameChanged'");
                            OutputLine("Subscribed to the 'nameChanged' signal.");
                        }
                        else
                        {
                            OutputLine("Join Session was unsuccessful.");
                        }
                    }
                    catch (Exception ex)
                    {
                        OutputLine("Errors were produced while establishing the application.");
                        QStatus status = AllJoynException.GetErrorCode(ex.HResult);
                        busAtt = null;
                    }
                });
                task.Start();
            }
        }
        public void AddMatchTest()
        {
            BusAttachment bus = new BusAttachment("addmatch", true, 4);
            AddMatchBusObj busObj = new AddMatchBusObj(bus);
            BusListener bl = new BusListener(bus);
            bus.RegisterBusListener(bl);
            busObj.MatchValid = true;
            bus.Start();
            bus.ConnectAsync(connectSpec).AsTask().Wait();

            BusAttachment service = new BusAttachment("service", true, 4);
            BusObject busObj2 = new BusObject(service, "/serviceTest", false);
            InterfaceDescription[] intf = new InterfaceDescription[1];
            service.CreateInterface("org.alljoyn.addmatchtest", intf, false);
            intf[0].AddSignal("testSig", "s", "str", (byte)0, "");
            intf[0].Activate();
            busObj2.AddInterface(intf[0]);
            service.RegisterBusObject(busObj2);
            service.Start();
            service.ConnectAsync(connectSpec).AsTask().Wait();
            service.RequestName("org.alljoyn.addmatch", (byte)RequestNameType.DBUS_NAME_DO_NOT_QUEUE);
            service.BindSessionPort(43, new ushort[1], new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false, 
                ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY), new SessionPortListener(service));
            service.AdvertiseName("org.alljoyn.addmatch", TransportMaskType.TRANSPORT_ANY);

            bl.FoundAdvertisedName += new BusListenerFoundAdvertisedNameHandler(
                (string name, TransportMaskType transport, string namePrefix) =>
                {
                    if (namePrefix == "org.alljoyn.addmatch")
                    {
                        foundService.Set();
                    }
                });
            bus.FindAdvertisedName("org.alljoyn.addmatch");

            foundService.WaitOne();
            Task<JoinSessionResult> join = bus.JoinSessionAsync("org.alljoyn.addmatch", 43, new SessionListener(bus),
                            new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY),
                            new SessionOpts[1], null).AsTask<JoinSessionResult>();
            join.Wait();
            Assert.IsTrue(QStatus.ER_OK != join.Result.Status);

            bus.AddMatch("type='signal',interface='org.alljoyn.addmatchtest',member='testSig'");
            for (int i = 0; i < 5; i++)
            {
                calledHandle.Reset();
                MsgArg sigArg1 = new MsgArg("s", new object[] { "hello" + i });
                busObj2.Signal("", 0, intf[0].GetSignal("testSig"), new MsgArg[] { sigArg1 }, 0, (byte)AllJoynFlagType.ALLJOYN_FLAG_GLOBAL_BROADCAST);
                calledHandle.WaitOne();
            }

            bus.RemoveMatch("type='signal',interface='org.alljoyn.addmatchtest',member='testSig'");
            busObj.MatchValid = false;
            for (int i = 0; i < 10; i++)
            {
                MsgArg sigArg1 = new MsgArg("s", new object[] { "hello" + i });
                busObj2.Signal("", 0, intf[0].GetSignal("testSig"), new MsgArg[] { sigArg1 }, 0, (byte)AllJoynFlagType.ALLJOYN_FLAG_GLOBAL_BROADCAST);
            }

            bus.AddMatch("type='signal',interface='org.alljoyn.addmatchtest',member='testSig'");
            busObj.MatchValid = true;
            for (int i = 0; i < 5; i++)
            {
                calledHandle.Reset();
                MsgArg sigArg1 = new MsgArg("s", new object[] { "hello" + i });
                busObj2.Signal("", 0, intf[0].GetSignal("testSig"), new MsgArg[] { sigArg1 }, 0, (byte)AllJoynFlagType.ALLJOYN_FLAG_GLOBAL_BROADCAST);
                calledHandle.WaitOne();
            }
        }
        public void JoinSessionAsyncTest()
        {
            BusAttachment service = new BusAttachment("service", true, 4);
            ServiceSessionPortListener spl = new ServiceSessionPortListener(service);
            service.Start();
            service.ConnectAsync(connectSpec).AsTask().Wait();
            service.RequestName("org.alljoyn.testing.service", (byte)RequestNameType.DBUS_NAME_DO_NOT_QUEUE);
            SessionOpts opts = new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY);
            service.BindSessionPort(77, new ushort[1], opts, spl.spl);
            service.AdvertiseName("org.alljoyn.testing.service", TransportMaskType.TRANSPORT_ANY);

            BusAttachment client = new BusAttachment("client", true, 4);
            BusListener cbl = new BusListener(client);
            ClientSessionListener csl = new ClientSessionListener(client);
            cbl.FoundAdvertisedName += new BusListenerFoundAdvertisedNameHandler(
                (string name, TransportMaskType transport, string namePrefix) =>
                {
                    if (namePrefix == "org.alljoyn.testing.service")
                    {
                        clientFoundService.Set();
                    }
                });
            client.RegisterBusListener(cbl);
            client.Start();
            client.ConnectAsync(connectSpec).AsTask().Wait();
            client.FindAdvertisedName("org.alljoyn.testing.service");
            clientFoundService.WaitOne();
            SessionOpts[] optsOut = new SessionOpts[1];
            Task<JoinSessionResult> joinTask = client.JoinSessionAsync("org.alljoyn.testing.service", (ushort)77, csl.sl, opts, optsOut, null).AsTask<JoinSessionResult>();
            joinTask.Wait();
            //The wait of 10ms ensures that the acceptSessionJoiner and sessionJoined callbacks are completed onthe service side.
            Task.Delay(10).Wait();
            if (QStatus.ER_OK == joinTask.Result.Status)
            {
                Assert.IsTrue(spl.AcceptSessionJoinerCalled && spl.SessionJoinedCalled);
                Assert.AreEqual(joinTask.Result.SessionId, spl.SessionId);
                Assert.AreEqual(joinTask.Result.Opts.IsMultipoint, optsOut[0].IsMultipoint);
                Assert.AreEqual(joinTask.Result.Opts.Proximity, optsOut[0].Proximity);
                Assert.AreEqual(joinTask.Result.Opts.Traffic, optsOut[0].Traffic);
                Assert.AreEqual(joinTask.Result.Opts.TransportMask, optsOut[0].TransportMask);
                Assert.AreEqual(joinTask.Result.Opts.IsMultipoint, opts.IsMultipoint);
                Assert.AreEqual(joinTask.Result.Opts.Proximity, opts.Proximity);
                Assert.AreEqual(joinTask.Result.Opts.Traffic, opts.Traffic);
                Assert.AreEqual(joinTask.Result.Opts.TransportMask, opts.TransportMask);
            } 
            else 
            {
                Assert.IsFalse(true);
            }
            service.LeaveSession(spl.SessionId);
            sessionLost.WaitOne();
        }
        public void BindSessionPortTest()
        {
            BusAttachment bus = new BusAttachment("bindports", true, 4);
            bus.Start();
            bus.ConnectAsync(connectSpec).AsTask().Wait();

            SessionOpts opts = new SessionOpts(TrafficType.TRAFFIC_MESSAGES, true, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY);
            SessionPortListener spl = new SessionPortListener(bus);
            for (ushort i = 1; i <= 10; i++)
            {
                ushort[] portOut = new ushort[1];
                bus.BindSessionPort((ushort)(i * 10), portOut, opts, spl);
                Assert.AreEqual((ushort)(i * 10), portOut[0]);
            }
        }
        public void AddMethodHandlerTest()
        {
            BusAttachment          service = new BusAttachment("methodhandler", true, 4);
            MethodHandlerBusObject busObj  = new MethodHandlerBusObject(service, "/handlertest");

            service.Start();
            service.ConnectAsync(connectSpec).AsTask().Wait();
            SessionPortListener spl = new SessionPortListener(service);

            spl.AcceptSessionJoiner += new SessionPortListenerAcceptSessionJoinerHandler((ushort sessionPort, string joiner, SessionOpts opts) =>
            {
                Assert.AreEqual(33, sessionPort);
                return(true);
            });
            service.RequestName("org.alljoyn.methodhandlertest", (byte)RequestNameType.DBUS_NAME_DO_NOT_QUEUE);
            service.BindSessionPort(33, new ushort[1], new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false,
                                                                       ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY), spl);
            service.AdvertiseName("org.alljoyn.methodhandlertest", TransportMaskType.TRANSPORT_ANY);

            BusAttachment client = new BusAttachment("methodcaller", true, 4);
            BusListener   bl     = new BusListener(client);

            client.RegisterBusListener(bl);
            bl.FoundAdvertisedName += new BusListenerFoundAdvertisedNameHandler(
                (string name, TransportMaskType transport, string namePrefix) =>
            {
                foundMethodObjectName.Set();
            });
            client.Start();
            client.ConnectAsync(connectSpec).AsTask().Wait();
            client.FindAdvertisedName("org.alljoyn.methodhandlertest");
            foundMethodObjectName.WaitOne();
            Task <JoinSessionResult> joinTask = client.JoinSessionAsync("org.alljoyn.methodhandlertest", 33, new SessionListener(client),
                                                                        new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY), new SessionOpts[1], null).AsTask <JoinSessionResult>();

            joinTask.Wait();
            Assert.IsTrue(QStatus.ER_OK == joinTask.Result.Status);
            ProxyBusObject proxy = new ProxyBusObject(client, "org.alljoyn.methodhandlertest", "/handlertest", joinTask.Result.SessionId);
            Task <IntrospectRemoteObjectResult> introTask = proxy.IntrospectRemoteObjectAsync(null).AsTask <IntrospectRemoteObjectResult>();

            introTask.Wait();
            Assert.IsTrue(QStatus.ER_OK == introTask.Result.Status);

            MsgArg[] args1 = new MsgArg[2];
            args1[0] = new MsgArg("s", new object[] { "one" });
            args1[1] = new MsgArg("s", new object[] { "two" });
            Task <MethodCallResult> catTask = proxy.MethodCallAsync(service.GetInterface("org.alljoyn.methodhandler").GetMethod("cat"),
                                                                    args1, null, 60000, (byte)0).AsTask <MethodCallResult>();

            catTask.Wait();
            Assert.IsTrue(AllJoynMessageType.MESSAGE_METHOD_RET == catTask.Result.Message.Type);
            Assert.AreEqual("onetwo", catTask.Result.Message.GetArg(0).Value.ToString());

            // Check BUGBUG above
            //MsgArg[] args2 = new MsgArg[1];
            //args2[0] = new MsgArg("s", new object[] { "hello" });
            //Task<MethodCallResult> sayHiTask = proxy.MethodCallAsync(service.GetInterface("org.alljoyn.methodhandler").GetMethod("sayhi"),
            //    args2, null, 60000, (byte)0).AsTask<MethodCallResult>();
            //sayHiTask.Wait();
            //Assert.IsTrue(AllJoynMessageType.MESSAGE_METHOD_RET == sayHiTask.Result.Message.Type);
            //Assert.AreEqual("aloha", sayHiTask.Result.Message.GetArg(0).Value.ToString());

            // TODO: add another method call that test function with signature MethodReply(AllJoyn.Message msg, string error, string errorMessage)
        }
        public void ConnectAsyncTest()
        {
            BusAttachment bus = new BusAttachment("connect", true, 4);
            bus.Start();

            for (int i = 0; i < 5; i++)
            {
                bus.ConnectAsync(connectSpec).AsTask().Wait();
                Assert.IsTrue(bus.IsConnected());
                bus.DisconnectAsync(connectSpec).AsTask().Wait();
                Assert.IsFalse(bus.IsConnected());
            }
        }
        public async void EnablePeerSecurityTest()
        {
            BusAttachment clientBus = new BusAttachment("client", true, 4);
            ClientAuthListener cl = new ClientAuthListener(clientBus);
            clientBus.Start();
            clientBus.EnablePeerSecurity("ALLJOYN_SRP_LOGON", cl.al, "/.alljoyn_keystore/s_central.ks", true);
            await clientBus.ConnectAsync(connectSpec);
            Assert.IsTrue(clientBus.IsPeerSecurityEnabled());

            BusAttachment srpLogonBus = new BusAttachment("srplogon", true, 4);
            SRP_LOGON_AuthListener srpl = new SRP_LOGON_AuthListener(srpLogonBus);
            srpLogonBus.Start();
            srpLogonBus.EnablePeerSecurity("ALLJOYN_SRP_LOGON", srpl.al, "/.alljoyn_keystore/s_central.ks", true);
            await srpLogonBus.ConnectAsync(connectSpec);
            Assert.IsTrue(srpLogonBus.IsPeerSecurityEnabled());

            BusAttachment srpKeyxBus = new BusAttachment("srpkeyx", true, 4);
            SRP_KEYX_AuthListener srpk = new SRP_KEYX_AuthListener(srpKeyxBus);
            srpKeyxBus.Start();
            srpKeyxBus.EnablePeerSecurity("ALLJOYN_SRP_KEYX", srpk.al, "/.alljoyn_keystore/s_central.ks", true);
            await srpKeyxBus.ConnectAsync(connectSpec);
            Assert.IsTrue(srpKeyxBus.IsPeerSecurityEnabled());

            BusAttachment rsaKeyxBus = new BusAttachment("rsakeyx", true, 4);
            RSA_KEYX_AuthListener rsak = new RSA_KEYX_AuthListener(srpKeyxBus);
            rsaKeyxBus.Start();
            rsaKeyxBus.EnablePeerSecurity("ALLJOYN_RSA_KEYX", rsak.al, "/.alljoyn_keystore/s_central.ks", true);
            await rsaKeyxBus.ConnectAsync(connectSpec);
            Assert.IsTrue(rsaKeyxBus.IsPeerSecurityEnabled());

            // TODO: Finish. Find an easier way to activate the auth process than calling interface method
        }
        public void SignalTest()
        {
            BusAttachment service = new BusAttachment("signalservice", true, 4);
            SignalBusObject busObj = new SignalBusObject(service, "/sigtest");
            service.Start();
            service.ConnectAsync(connectSpec).AsTask().Wait();
            SessionPortListener spl = new SessionPortListener(service);
            spl.AcceptSessionJoiner += new SessionPortListenerAcceptSessionJoinerHandler((ushort sessionPort, string joiner, SessionOpts opts) =>
            {
                Assert.AreEqual(89, sessionPort);
                return true;
            });
            service.RequestName("org.alljoyn.signaltesting", (byte)RequestNameType.DBUS_NAME_DO_NOT_QUEUE);
            service.BindSessionPort(89, new ushort[1], new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false,
                ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY), spl);
            service.AdvertiseName("org.alljoyn.signaltesting", TransportMaskType.TRANSPORT_ANY);

            BusAttachment client = new BusAttachment("methodcaller", true, 4);
            ServiceBusObject sbo = new ServiceBusObject(client, "/clientbusobj");
            BusListener bl = new BusListener(client);
            client.RegisterBusListener(bl);
            bl.FoundAdvertisedName += new BusListenerFoundAdvertisedNameHandler(
                (string name, TransportMaskType transport, string namePrefix) =>
                {
                    foundSignalObjectName.Set();
                });
            client.Start();
            client.ConnectAsync(connectSpec).AsTask().Wait();
            client.FindAdvertisedName("org.alljoyn.signaltesting");
            foundSignalObjectName.WaitOne();

            Task<JoinSessionResult> joinTask = client.JoinSessionAsync("org.alljoyn.signaltesting", 89, new SessionListener(client),
                new SessionOpts(TrafficType.TRAFFIC_MESSAGES, false, ProximityType.PROXIMITY_ANY, TransportMaskType.TRANSPORT_ANY), new SessionOpts[1], null).AsTask<JoinSessionResult>();
            joinTask.Wait();
            Assert.IsTrue(QStatus.ER_OK == joinTask.Result.Status);

            // TODO: call BusObject.Signal() for each one of the signals in the interface and make sure
            // they're received and the data is consistent with what was sent.
        }
        /// <summary>
        /// Connects to the bus, finds the service and calls the 'cat' with the two 
        /// arguments "Hello " and "World!"
        /// </summary>
        /// <param name="sender">UI control which signaled the click event</param>
        /// <param name="e">arguments associated with the click event</param>
        private void Button_RunClick(object sender, RoutedEventArgs e)
        {
            if (!runningClient)
            {
                Task task = new Task(async () =>
                {
                    try
                    {
                        runningClient = true;

                        busAtt = new BusAttachment("ClientApp", true, 4);
                        this.OutputLine("BusAttachment Created.");

                        BasicClientBusListener basicClientBusListener = new BasicClientBusListener(busAtt, foundNameEvent);
                        busAtt.RegisterBusListener(basicClientBusListener);
                        this.OutputLine("BusListener Registered.");

                        /* Create and register the bundled daemon. The client process connects to daemon over tcp connection */
                        busAtt.Start();
                        await busAtt.ConnectAsync(BasicClientGlobals.ConnectSpec);
                        this.OutputLine("Bundled Daemon Registered.");
                        this.OutputLine("BusAttachment Connected to " + BasicClientGlobals.ConnectSpec + ".");

                        busAtt.FindAdvertisedName(BasicClientGlobals.WellKnownServiceName);
                        foundNameEvent.WaitOne();

                        /* Configure session properties and request a session with device with wellKnownName */
                        SessionOpts sessionOpts = new SessionOpts(
                            BasicClientGlobals.SessionProps.TrType, 
                            BasicClientGlobals.SessionProps.IsMultiPoint, 
                            BasicClientGlobals.SessionProps.PrType, 
                            BasicClientGlobals.SessionProps.TmType);
                        SessionOpts[] sOptsOut = new SessionOpts[1];
                        JoinSessionResult joinResults = await busAtt.JoinSessionAsync(
                            BasicClientGlobals.WellKnownServiceName,
                            BasicClientGlobals.SessionProps.SessionPort,
                            basicClientBusListener,
                            sessionOpts,
                            sOptsOut,
                            null);
                        QStatus status = joinResults.Status;
                        if (QStatus.ER_OK != status)
                        {
                            this.OutputLine("Joining a session with the Service was unsuccessful.");
                        }
                        else
                        {
                            this.OutputLine("Join Session was successful (sessionId=" + joinResults.SessionId + ").");
                        }

                        // Create the proxy for the service interface by introspecting the service bus object
                        ProxyBusObject proxyBusObject = new ProxyBusObject(busAtt, BasicClientGlobals.WellKnownServiceName, BasicClientGlobals.ServicePath, 0);
                        if (QStatus.ER_OK == status)
                        {
                            IntrospectRemoteObjectResult introResult = await proxyBusObject.IntrospectRemoteObjectAsync(null);
                            status = introResult.Status;
                            if (QStatus.ER_OK != status)
                            {
                                this.OutputLine("Introspection of the service bus object failed.");
                            }
                            else
                            {
                                this.OutputLine("Introspection of the service bus object was successful.");
                            }
                        }

                        if (QStatus.ER_OK == status)
                        {
                            // Call 'cat' method with the two string to be concatenated ("Hello" and " World!")
                            MsgArg[] catMe = new MsgArg[2];
                            catMe[0] = new MsgArg("s", new object[] { "Hello" });
                            catMe[1] = new MsgArg("s", new object[] { " World!" });

                            InterfaceDescription interfaceDescription = proxyBusObject.GetInterface(BasicClientGlobals.InterfaceName);
                            InterfaceMember interfaceMember = interfaceDescription.GetMember("cat");

                            this.OutputLine("Calling the 'cat' method of the service with args 'Hello' and ' World!'");
                            MethodCallResult callResults = await proxyBusObject.MethodCallAsync(interfaceMember, catMe, null, 100000, 0);
                            Message msg = callResults.Message;
                            if (msg.Type == AllJoynMessageType.MESSAGE_METHOD_RET)
                            {
                                string strRet = msg.GetArg(0).Value as string;
                                this.OutputLine("Sender '" + msg.Sender + "' returned the value '" + strRet + "'");
                            }
                            else
                            {
                                this.OutputLine("The 'cat' method call produced errors of type: " + msg.Type.ToString());
                            }
                        }

                        TearDown();
                    }
                    catch (Exception ex)
                    {
                        QStatus s = AllJoynException.GetErrorCode(ex.HResult);
                    }
                });
                task.Start();
            }
        }