Example #1
0
        /// <summary>
        /// Initializes a new instance of the Client class.
        /// </summary>
        /// <param name="name">The name of the client application.</param>
        /// <param name="pinReady">The event to communicate there is a pin waiting.</param>
        public Client(string name, AutoResetEvent pinReady)
        {
            this.PinReady = pinReady;

            // Create the BusAttachment and other prep for accepting input from the client(s).
            this.ConnectBus = new Task(() =>
            {
                try
                {
                    this.InitializeAllJoyn(name);
                    App app = Windows.UI.Xaml.Application.Current as App;
                    app.Bus = this.Bus;
                }
                catch (Exception ex)
                {
                    const string ErrorFormat = "Bus intialization for client produced error(s). QStatus = 0x{0:X}.";
                    QStatus status           = AllJoynException.GetErrorCode(ex.HResult);
                    string error             = string.Format(ErrorFormat, status);

                    System.Diagnostics.Debug.WriteLine(error);
                    App.OutputLine(error);
                }
            });

            this.ConnectBus.Start();
        }
Example #2
0
            /**
             * Add a method handler to this object. The interface for the method handler must have already
             * been added by calling AddInterface().
             *
             * @param member   Interface member implemented by handler.
             * @param handler  Method handler.
             *
             * @return
             *      - QStatus.OK if the method handler was added.
             *      - An error status otherwise
             */
            public QStatus AddMethodHandler(InterfaceDescription.Member member, MethodHandler handler)
            {
                InternalMethodHandler internalMethodHandler = (IntPtr bus, IntPtr m, IntPtr msg) =>
                {
                    MethodHandler h = handler;
                    h(new InterfaceDescription.Member(m), new Message(msg));
                };

                _methodHandlerDelegateRefHolder.Add(internalMethodHandler);

                GCHandle membGch = GCHandle.Alloc(member._member, GCHandleType.Pinned);

                MethodEntry entry;

                entry.member         = membGch.AddrOfPinnedObject();
                entry.method_handler = Marshal.GetFunctionPointerForDelegate(internalMethodHandler);

                GCHandle gch = GCHandle.Alloc(entry, GCHandleType.Pinned);
                QStatus  ret = alljoyn_busobject_addmethodhandlers(_busObject, gch.AddrOfPinnedObject(), (UIntPtr)1);

                gch.Free();
                membGch.Free();

                return(ret);
            }
 internal static void CheckStatus(QStatus status)
 {
     if (status != QStatus.ER_OK)
     {
         throw new AllJoynException(status);
     }
 }
Example #4
0
        public IHttpActionResult PutQStatus(int id, QStatus qStatus)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != qStatus.QStatusID)
            {
                return(BadRequest());
            }

            db.Entry(qStatus).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!QStatusExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
        /// <summary>
        /// Initializes a new instance of the ChatSessionObject class.
        /// </summary>
        /// <param name="bus">The BusAttachment to be associated with.</param>
        /// <param name="path">The path for the BusObject.</param>
        /// <param name="host">The instance of the MainPage which handles the UI for this
        /// application.</param>
        public ChatSessionObject(BusAttachment bus, string path, MainPage host)
        {
            try
            {
                this.hostPage  = host;
                this.busObject = new BusObject(bus, path, false);

                /* Add the interface to this object */
                InterfaceDescription[] ifaceArr = new InterfaceDescription[1];
                bus.CreateInterface(ChatServiceInterfaceName, ifaceArr, false);
                ifaceArr[0].AddSignal("Chat", "s", "str", 0, string.Empty);
                ifaceArr[0].Activate();

                InterfaceDescription chatIfc = bus.GetInterface(ChatServiceInterfaceName);

                this.busObject.AddInterface(chatIfc);

                this.chatSignalReceiver = new MessageReceiver(bus);
                this.chatSignalReceiver.SignalHandler += new MessageReceiverSignalHandler(this.ChatSignalHandler);
                this.chatSignalMember = chatIfc.GetMember("Chat");
                bus.RegisterSignalHandler(this.chatSignalReceiver, this.chatSignalMember, path);
            }
            catch (System.Exception ex)
            {
                QStatus errCode = AllJoyn.AllJoynException.GetErrorCode(ex.HResult);
                string  errMsg  = AllJoyn.AllJoynException.GetErrorMessage(ex.HResult);
                this.hostPage.DisplayStatus("Create ChatSessionObject Error : " + errMsg);
            }
        }
Example #6
0
            public QStatus GetPeerGuid(string name, out string guid)
            {
                UIntPtr guidSz;
                QStatus ret = alljoyn_busattachment_getpeerguid(_busAttachment, name,
                                                                IntPtr.Zero, ref guidSz);

                if (!ret)
                {
                    guid = "";
                }
                else
                {
                    byte[]   guidBuffer = new byte[(int)guidSz];
                    GCHandle gch        = GCHandle.Alloc(guidBuffer, GCHandleType.Pinned);
                    ret = alljoyn_busattachment_getpeerguid(_busAttachment, name,
                                                            gch.AddrOfPinnedObject(), ref guidSz);
                    gch.Free();
                    if (!ret)
                    {
                        guid = "";
                    }
                    else
                    {
                        guid = System.Text.ASCIIEncoding.ASCII.GetString(guidBuffer);
                    }
                }
                return(ret);
            }
        /// <summary>
        /// Event handler which is called when a remote object tries to set the property 'name'
        /// in this service's interface.
        /// </summary>
        /// <param name="interfaceName">name of the interface containing property 'name'.</param>
        /// <param name="propertyName">name of the property whos value to set.</param>
        /// <param name="msg">contains the new value for which to set the property value.</param>
        /// <returns>ER_OK if the property value change and signal were executed sucessfully,
        /// else returns ER_BUS_BAD_SEND_PARAMETER.</returns>
        public QStatus SetHandler(string interfaceName, string propertyName, MsgArg msg)
        {
            QStatus status = QStatus.ER_OK;

            if (propertyName == "name")
            {
                string newName = msg.Value.ToString();
                try
                {
                    App.OutputLine("///////////////////////////////////////////////////////////////////////");
                    App.OutputLine("Name Property Changed (newName=" + newName + "\toldName=" + this.name + ").");
                    this.name = newName;
                    object[] obj      = { newName };
                    MsgArg   msgReply = new MsgArg("s", obj);
                    this.BusObject.Signal(string.Empty, 0, this.signalMember, new MsgArg[] { msgReply }, 0, (byte)AllJoynFlagType.ALLJOYN_FLAG_GLOBAL_BROADCAST);
                    status = QStatus.ER_OK;
                }
                catch (Exception ex)
                {
                    App.OutputLine("The Name Change signal was not able to send.");
                    System.Diagnostics.Debug.WriteLine("Exception:");
                    System.Diagnostics.Debug.WriteLine(ex.ToString());
                    status = QStatus.ER_BUS_BAD_SEND_PARAMETER;
                }
            }

            return(status);
        }
Example #8
0
        /// <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();
        }
Example #9
0
            public QStatus GetKeyExpiration(string guid, out uint timeout)
            {
                uint    _timeout = 0;
                QStatus ret      = alljoyn_busattachment_getkeyexpiration(_busAttachment, guid, ref _timeout);

                timeout = _timeout;
                return(ret);
            }
Example #10
0
            public QStatus NameHasOwner(string name, out bool hasOwner)
            {
                int     intHasOwner = 0;
                QStatus ret         = alljoyn_busattachment_namehasowner(_busAttachment, name, ref intHasOwner);

                hasOwner = (intHasOwner == 1 ? true : false);
                return(ret);
            }
Example #11
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);
            }
        }
Example #12
0
        /// <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();
            }
        }
Example #13
0
            public QStatus BindSessionPort(ref ushort sessionPort, SessionOpts opts, SessionPortListener listener)
            {
                QStatus ret = QStatus.OK;
                ushort  otherSessionPort = sessionPort;

                ret = alljoyn_busattachment_bindsessionport(_busAttachment, ref otherSessionPort,
                                                            opts.UnmanagedPtr, listener.UnmanagedPtr);
                sessionPort = otherSessionPort;
                return(ret);
            }
Example #14
0
        /// <summary>
        /// <para>This is the handler of AuthListener. It is designed to only handle SRP Key Exchange
        /// Authentication requests.
        /// </para>
        /// <para>When a Password request (CRED_PASSWORD) comes in using App.SecurityType the
        /// code will generate a 6 digit random pin code. The client must enter the same
        /// pin code into his AuthListener for the Authentication to be successful.
        /// </para>
        /// <para>If any other authMechanism is used other than SRP Key Exchange authentication it
        /// will fail.</para>
        /// </summary>
        /// <param name="authMechanism">A string describing the authentication method.</param>
        /// <param name="authPeer">The name of the peer to be authenticated.</param>
        /// <param name="authCount">The number of attempts at authentication.</param>
        /// <param name="userId">The parameter is not used.</param>
        /// <param name="credMask">The type of credentials expected.</param>
        /// <param name="context">The details of the credentials.</param>
        /// <returns>true if successful or false if there was a problem.</returns>
        private QStatus AuthRequestCredentals(
            string authMechanism,
            string authPeer,
            ushort authCount,
            string userId,
            ushort credMask,
            AuthContext context)
        {
            QStatus returnValue = QStatus.ER_AUTH_FAIL;

            if (!string.IsNullOrEmpty(authMechanism) && !string.IsNullOrEmpty(authPeer))
            {
                const string RequestFormat = "RequestCredentials for authenticating {0} using mechanism {1}.";

                App.OutputLine(string.Format(RequestFormat, authPeer, authMechanism));

                if (authMechanism.CompareTo(App.SecurityType) == 0 &&
                    0 != (credMask & (ushort)CredentialType.CRED_PASSWORD))
                {
                    if (authCount <= 3)
                    {
                        Random rand      = new Random();
                        string pin       = ((int)(rand.NextDouble() * 1000000)).ToString("D6");
                        string pinReport = string.Format("One Time Password : {0}.", pin);

                        App.OutputLine(pinReport);
                        App.OutputPIN(pin);

                        Credentials creds = new Credentials();

                        creds.Expiration = 120;
                        creds.Password   = pin;

                        this.AuthenticationListener.RequestCredentialsResponse(context, true, creds);

                        returnValue = QStatus.ER_OK;
                    }
                    else
                    {
                        App.OutputLine(string.Format("Authorization failed after {0} attempts.", authCount));
                    }
                }
                else
                {
                    App.OutputLine("Unexpected authorization mechanism or credentials mask.");
                }
            }
            else
            {
                App.OutputLine("Empty or null string parameters received in AuthRequestCredentials.");
            }

            return(returnValue);
        }
Example #15
0
        public IHttpActionResult GetQStatus(int id)
        {
            QStatus qStatus = db.QStatus.Find(id);

            if (qStatus == null)
            {
                return(NotFound());
            }

            return(Ok(qStatus));
        }
Example #16
0
        public IHttpActionResult PostQStatus(QStatus qStatus)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.QStatus.Add(qStatus);
            db.SaveChanges();

            return(CreatedAtRoute("DefaultApi", new { id = qStatus.QStatusID }, qStatus));
        }
        internal AllJoynException(QStatus code, string message)
        {
            var error = ErrorCodeLookup.GetError((int)code);

            Source = Constants.DLL_IMPORT_TARGET;
            int codeNumber = (int)code;

            _message         = message ?? $"0x{codeNumber:x4} {error.Name}: {error.Comment}";
            AllJoynError     = error.Name;
            AllJoynErrorCode = error.Value;
            AllJoynComment   = error.Comment;
        }
Example #18
0
 /// <summary>
 /// Sends a 'Chat' signal using the specified parameters
 /// </summary>
 /// <param name="filter">filter to use </param>
 public void AddRule(string filter)
 {
     try
     {
         this.busObject.Bus.AddMatch(filter);
     }
     catch (Exception ex)
     {
         QStatus status = AllJoynException.GetErrorCode(ex.HResult);
         string  errMsg = AllJoynException.GetErrorMessage(ex.HResult);
         this.sessionOps.Output("adding a rule failed: " + errMsg);
     }
 }
Example #19
0
        public IHttpActionResult DeleteQStatus(int id)
        {
            QStatus qStatus = db.QStatus.Find(id);

            if (qStatus == null)
            {
                return(NotFound());
            }

            db.QStatus.Remove(qStatus);
            db.SaveChanges();

            return(Ok(qStatus));
        }
 /// <summary>
 /// This method sends a message to the person on the other end.
 /// </summary>
 /// <param name="id">The destination ID.</param>
 /// <param name="msg">The message to send.</param>
 public void SendChatSignal(uint id, string msg)
 {
     try
     {
         MsgArg msgarg = new MsgArg("s", new object[] { msg });
         this.busObject.Signal(string.Empty, id, this.chatSignalMember, new MsgArg[] { msgarg }, 0, 0);
     }
     catch (System.Exception ex)
     {
         QStatus errCode = AllJoyn.AllJoynException.GetErrorCode(ex.HResult);
         string  errMsg  = AllJoyn.AllJoynException.GetErrorMessage(ex.HResult);
         this.hostPage.DisplayStatus("SendChatSignal Error: " + errMsg);
     }
 }
Example #21
0
        /// <summary>
        /// <para>This is the handler of authentication requests. It is designed to only handle SRP
        /// Key Exchange Authentication requests.
        /// </para>
        /// <para>When a Password request (CRED_PASSWORD) comes in using App.SecurityType the
        /// code will generate a 6 digit random pin code. The client must enter the same
        /// pin code into his AuthListener for the Authentication to be successful.
        /// </para>
        /// <para>If any other authMechanism is used other than SRP Key Exchange authentication it
        /// will fail.</para>
        /// </summary>
        /// <param name="authMechanism">A string describing the authentication method.</param>
        /// <param name="authPeer">The name of the peer to be authenticated.</param>
        /// <param name="authCount">The number of attempts at authentication.</param>
        /// <param name="userId">The parameter is not used.</param>
        /// <param name="credMask">The type of credentials expected.</param>
        /// <param name="context">The context of the authentication request.</param>
        /// <returns>true if successful or false if there was a problem.</returns>
        private QStatus AuthRequestCredentals(
            string authMechanism,
            string authPeer,
            ushort authCount,
            string userId,
            ushort credMask,
            AuthContext context)
        {
            QStatus returnValue = QStatus.ER_AUTH_FAIL;

            if (!string.IsNullOrEmpty(authMechanism) && !string.IsNullOrEmpty(authPeer))
            {
                const string RequestFormat = "RequestCredentials for authenticating {0} using mechanism {1}.";

                App.OutputLine(string.Format(RequestFormat, authPeer, authMechanism));

                if (authMechanism.CompareTo(App.SecurityType) == 0 &&
                    0 != (credMask & (ushort)CredentialType.CRED_PASSWORD))
                {
                    if (authCount <= 3)
                    {
                        if (this.PinReady.WaitOne(Client.PinWaitTime) && !string.IsNullOrWhiteSpace(this.Pin))
                        {
                            Credentials creds = new Credentials();

                            creds.Expiration = 120;
                            creds.Password   = this.Pin;
                            this.AuthenticationListener.RequestCredentialsResponse(context, true, creds);

                            returnValue = QStatus.ER_OK;
                        }
                    }
                    else
                    {
                        App.OutputLine(string.Format("Authorization failed after {0} attempts.", authCount));
                    }
                }
                else
                {
                    App.OutputLine("Unexpected authorization mechanism or credentials mask.");
                }
            }
            else
            {
                App.OutputLine("Empty or null string parameters received in AuthRequestCredentials.");
            }

            return(returnValue);
        }
Example #22
0
 /// <summary>
 /// This method sends the current message to the chat service for delivery to the remote device.
 /// </summary>
 /// <param name="id">The session ID associated with this message.</param>
 /// <param name="message">The actual message being sent.</param>
 private void SendMyMessage(uint id, string message)
 {
     try
     {
         this.OnChat(this.SessionId, "Me : ", message);
         this.chatService.SendChatSignal(this.SessionId, message);
         this.MessageBox.Text = string.Empty;
     }
     catch (Exception ex)
     {
         QStatus stat   = AllJoynException.GetErrorCode(ex.HResult);
         string  errMsg = AllJoynException.GetErrorMessage(ex.HResult);
         DisplayStatus("SendMessage Error : " + errMsg);
     }
 }
Example #23
0
            public QStatus UnbindSessionPort(ushort sessionPort)
            {
                QStatus ret        = QStatus.OK;
                Thread  bindThread = new Thread((object o) => {
                    ret = alljoyn_busattachment_unbindsessionport(_busAttachment, sessionPort);
                });

                bindThread.Start();
                while (bindThread.IsAlive)
                {
                    AllJoyn.TriggerCallbacks();
                    Thread.Sleep(0);
                }
                return(ret);
            }
Example #24
0
        /// <summary>
        /// Leave the currently active chat session.
        /// </summary>
        private void LeaveChannel()
        {
            try
            {
                this.bus.LeaveSession(this.SessionId);
                this.DisplayStatus("Leave chat session " + this.SessionId + " successfully");
            }
            catch (Exception ex)
            {
                QStatus stat   = AllJoynException.GetErrorCode(ex.HResult);
                string  errMsg = AllJoynException.GetErrorMessage(ex.HResult);
                this.DisplayStatus("Leave chat session " + this.SessionId + " failed: " + errMsg);
            }

            this.SessionId = 0;
        }
Example #25
0
        /// <summary>
        /// Do the work of joining a session.
        /// </summary>
        /// <param name="folder">The folder to put the received file in.</param>
        /// <returns>true if all the input variables look good.</returns>
        public bool StartJoinSessionTask(StorageFolder folder)
        {
            bool returnValue = false;

            this.Folder = folder;

            if (null != this.Bus && null != this.Folder)
            {
                Task task = new Task(async() =>
                {
                    try
                    {
                        if (0 != this.SessionId)
                        {
                            this.Bus.LeaveSession(this.SessionId);
                        }

                        this.lastIndex = 0;
                        this.CreateInterfaceAndBusObject();
                        this.AddSignalHandler();

                        // We found a remote bus that is advertising the well-known name so connect to it.
                        bool result = await this.JoinSessionAsync();

                        if (result)
                        {
                            App.OutputLine("Successfully joined session.");
                        }
                    }
                    catch (Exception ex)
                    {
                        QStatus status = AllJoynException.GetErrorCode(ex.HResult);
                        string message = string.Format(
                            "Errors were produced while establishing the application '{0}' (0x{0:X}).",
                            status.ToString(),
                            status);
                        App.OutputLine(message);
                    }
                });

                task.Start();

                returnValue = true;
            }

            return(returnValue);
        }
Example #26
0
            public QStatus BindSessionPort(ref ushort sessionPort, SessionOpts opts, SessionPortListener listener)
            {
                QStatus ret = QStatus.OK;
                ushort  otherSessionPort = sessionPort;
                Thread  bindThread       = new Thread((object o) => {
                    ret = alljoyn_busattachment_bindsessionport(_busAttachment, ref otherSessionPort,
                                                                opts.UnmanagedPtr, listener.UnmanagedPtr);
                });

                bindThread.Start();
                while (bindThread.IsAlive)
                {
                    AllJoyn.TriggerCallbacks();
                    Thread.Sleep(0);
                }
                sessionPort = otherSessionPort;
                return(ret);
            }
Example #27
0
        /// <summary>
        /// Shut down the hosted channel.
        /// </summary>
        private void StopChannel()
        {
            try
            {
                var wellKnownName = this.MakeWellKnownName(this.channelHosted);
                this.bus.CancelAdvertiseName(wellKnownName, alljoynTransports);
                this.bus.UnbindSessionPort(ContactPort);
                this.bus.ReleaseName(wellKnownName);
                this.Channels.Remove(this.channelHosted);

                this.channelHosted = null;
            }
            catch (Exception ex)
            {
                QStatus stat   = AllJoynException.GetErrorCode(ex.HResult);
                string  errMsg = AllJoynException.GetErrorMessage(ex.HResult);
                DisplayStatus("StopChannel Error : " + errMsg);
            }
        }
        /// <summary>
        /// Joins a session with specified nameprefix using specs provided
        /// </summary>
        /// <param name="name">Name prefix or well-known name to join session with</param>
        /// <param name="sessionPort">Port for session</param>
        /// <param name="opts">Session Opts for session</param>
        public async void DoJoinAsync(string name, uint sessionPort, SessionOpts opts)
        {
            SessionOpts[]     optsOut    = new SessionOpts[1];
            JoinSessionResult joinResult = await this.busAtt.JoinSessionAsync(name, (ushort)sessionPort, (SessionListener)this.busListener, opts, optsOut, null);

            QStatus status = joinResult.Status;

            if (QStatus.ER_OK == status)
            {
                this.mainPage.Output("BusAttachment.JoinSessionAsync(" + name + ", " + sessionPort + ", ...) succeeded with id=" + joinResult.SessionId);
                lock (this.sessionMap)
                {
                    this.sessionMap.Add(joinResult.SessionId, new SessionInfo(joinResult.SessionId, new SessionPortInfo(sessionPort, name, opts)));
                }
            }
            else
            {
                this.mainPage.Output("BusAttachment.JoinSessionAsync(" + name + ", " + sessionPort + ", ...) failed: " + status.ToString());
            }
        }
Example #29
0
 /// <summary>
 /// Start up the channel we are hosting.
 /// </summary>
 /// <param name="name">The name, minus the name prefix, for the channel we are hosting.</param>
 private void StartChannel(string name)
 {
     try
     {
         this.channelHosted = name;
         string wellKnownName = this.MakeWellKnownName(name);
         this.bus.RequestName(wellKnownName, (int)RequestNameType.DBUS_NAME_DO_NOT_QUEUE);
         this.bus.AdvertiseName(wellKnownName, alljoynTransports);
         ushort[]    portOut = new ushort[1];
         SessionOpts opts    = new SessionOpts(TrafficType.TRAFFIC_MESSAGES, true, ProximityType.PROXIMITY_ANY, alljoynTransports);
         this.bus.BindSessionPort(ContactPort, portOut, opts, this.busListeners);
         DisplayStatus("Start Chat channel " + name + " successfully");
     }
     catch (Exception ex)
     {
         QStatus stat   = AllJoynException.GetErrorCode(ex.HResult);
         string  errMsg = AllJoynException.GetErrorMessage(ex.HResult);
         DisplayStatus("StartChannel Error : " + errMsg);
     }
 }
Example #30
0
            public void SayHiHandler(InterfaceMember member, Message message)
            {
                Assert.AreEqual("hello", message.GetArg(0).Value.ToString());
                MsgArg retArg = new MsgArg("s", new object[] { "aloha" });

                try
                {
                    // BUGBUG: Throws exception saying signature of the msgArg is not what was expected, but its correct.
                    this.busObject.MethodReplyWithQStatus(message, QStatus.ER_OK);
                }
                catch (Exception ex)
                {
#if DEBUG
                    string err = AllJoynException.GetExceptionMessage(ex.HResult);
#else
                    QStatus err = AllJoynException.FromCOMException(ex.HResult);
#endif
                    Assert.IsFalse(true);
                }
            }
Example #31
0
 protected virtual void SecurityViolation(QStatus status, Message msg)
 {
 }
Example #32
0
 /**
  * Reply to a method call with an error message.
  *
  * @param message        The method call message
  * @param status     The status code for the error
  * @return
  *      - QStatus.OK if successful
  *      - An error status otherwise
  */
 protected QStatus MethodReply(Message message, QStatus status)
 {
     return alljoyn_busobject_methodreply_status(_busObject, message.UnmanagedPtr, status.value);
 }