示例#1
0
        // </Snippet3>
        //------------------------------------------------------------------------------------------------------
        //------------------------------------------------------------------------------------------------------
        // <Snippet4>
        // Registering Notepad.exe as a collab application with a fixed GUID.
        // Note: If you're using the application to send invitations,
        // the same application with the same GUID must be registered on the remote peer machine.
        private static PeerApplication RegisterCollabApp()
        {
            PeerApplication application = null;
            string          pathToApp   = "%SystemRoot%\\notepad.exe";
            Guid            appGuid     = new Guid(0xAAAAAAAA, 0xFADE, 0xDEAF, 0xBE, 0xEF, 0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAE);

            application                 = new PeerApplication();
            application.Id              = appGuid;
            application.Path            = pathToApp;
            application.Description     = "Peer Collaboration Sample -- notepad.exe";
            application.PeerScope       = PeerScope.All;
            application.CommandLineArgs = "n";
            application.Data            = ASCIIEncoding.ASCII.GetBytes("Test");

            Console.WriteLine("Attempting to register the application \"notepad.exe\"...");
            try
            {
                PeerApplicationCollection pac = PeerCollaboration.GetLocalRegisteredApplications(PeerApplicationRegistrationType.AllUsers);
                if (pac.Contains(application))
                {
                    Console.WriteLine("The application is already registered on the peer.");
                }
                else
                {
                    PeerCollaboration.RegisterApplication(application, PeerApplicationRegistrationType.AllUsers);
                    Console.WriteLine("Application registration succeeded!");
                }
            }
            catch (ArgumentException argEx)
            {
                Console.WriteLine("The application was previously registered with the Peer Collaboration Infrastructure: {0}.", argEx.Message);
            }
            catch (PeerToPeerException p2pEx)
            {
                Console.WriteLine("The application failed to register with the Peer Collaboration Infrastructure: {0}", p2pEx.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("An unexpected exception occurred when trying to register the application: {0}.", ex.Message);
            }
            return(application);
        }
        public static PeerApplicationCollection GetLocalRegisteredApplications(PeerApplicationRegistrationType type)
        {
            Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Entering GetLocalRegisteredApplications.");
            
            PeerCollaborationPermission.UnrestrictedPeerCollaborationPermission.Demand();

            if ((type < PeerApplicationRegistrationType.CurrentUser) || (type > PeerApplicationRegistrationType.AllUsers)){
                throw new ArgumentOutOfRangeException("type");
            }

            CollaborationHelperFunctions.Initialize();

            PeerApplicationCollection peerAppColl = new PeerApplicationCollection();
            SafeCollabEnum handlePeerEnum = new SafeCollabEnum();
            UInt32 appCount = 0;
            int errorCode = 0;

            //
            // Enumerate and get all the registered applications from native
            //

            try{
                errorCode = UnsafeCollabNativeMethods.PeerCollabEnumApplications(IntPtr.Zero, IntPtr.Zero, out handlePeerEnum);
                if (errorCode != 0){
                    Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerCollabEnumApplications returned with errorcode {0}", errorCode);
                    throw (PeerToPeerException.CreateFromHr(SR.GetString(SR.Collab_GetLocalAppsFailed), errorCode));
                }

                errorCode = UnsafeCollabNativeMethods.PeerGetItemCount(handlePeerEnum, ref appCount);
                if (errorCode != 0){
                    Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerGetItemCount returned with errorcode {0}", errorCode);
                    throw (PeerToPeerException.CreateFromHr(SR.GetString(SR.Collab_GetLocalAppsFailed), errorCode));
                }

                if (appCount == 0){
                    Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "No local registered PeerApplications found.");
                    return peerAppColl;
                }

                unsafe{
                    SafeCollabData appArray = null;
                    try{
                        errorCode = UnsafeCollabNativeMethods.PeerGetNextItem(handlePeerEnum, ref appCount, out appArray);
                        if (errorCode != 0){
                            Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerGetNextItem returned with errorcode {0}", errorCode);
                            throw (PeerToPeerException.CreateFromHr(SR.GetString(SR.Collab_GetLocalAppsFailed), errorCode));
                        }

                        //
                        // Marshal each application from the array
                        //

                        IntPtr pPEER_APLICATION = appArray.DangerousGetHandle();
                        IntPtr* pApps = (IntPtr*)pPEER_APLICATION;
                        for (ulong i = 0; i < appCount; i++){
                            PEER_APPLICATION* pPeerApp = (PEER_APPLICATION*)pApps[i];
                            string description = Marshal.PtrToStringUni(pPeerApp->pwzDescription);
                            byte[] data = null;

                            if (pPeerApp->data.cbData != 0){
                                data = new byte[pPeerApp->data.cbData];
                                Marshal.Copy(pPeerApp->data.pbData, data, 0, (int)pPeerApp->data.cbData);
                            }

                            PeerApplication peerApp = new PeerApplication(  CollaborationHelperFunctions.ConvertGUIDToGuid(pPeerApp->guid), 
                                                                            description, data, null, null, PeerScope.None);
                            peerAppColl.Add(peerApp);
                        }
                    }
                    finally{
                        appArray.Dispose();
                    }
                }
            }
            finally{
                handlePeerEnum.Dispose();
            }

            Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Got all local registered Applications. Start filtering");

            PeerApplicationCollection peerAppCollFiltered = new PeerApplicationCollection();

            //
            // Filter the apps according to the Registration type the user wants
            //

            foreach (PeerApplication peerApplication in peerAppColl)
            {
                GUID guid = CollaborationHelperFunctions.ConvertGuidToGUID(peerApplication.Id);
                SafeCollabData safeAppRegInfo = new SafeCollabData();

                try{
                    errorCode = UnsafeCollabNativeMethods.PeerCollabGetApplicationRegistrationInfo(ref guid,
                                                                                                    type,
                                                                                                    out safeAppRegInfo);
                    if (errorCode != 0)
                        Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerCollabGetApplicationRegistrationInfo returned with errorcode {0}", errorCode);

                    if (!safeAppRegInfo.IsInvalid){
                        PEER_APPLICATION_REGISTRATION_INFO pari = (PEER_APPLICATION_REGISTRATION_INFO)
                                                                Marshal.PtrToStructure(safeAppRegInfo.DangerousGetHandle(),
                                                                                        typeof(PEER_APPLICATION_REGISTRATION_INFO));
                        peerApplication.Path = pari.pwzApplicationToLaunch;
                        peerApplication.CommandLineArgs = pari.pwzApplicationArguments;
                        peerApplication.PeerScope = (PeerScope)pari.dwPublicationScope;
                        
                        peerAppCollFiltered.Add(peerApplication);
                    }
                }
                finally{
                    safeAppRegInfo.Dispose();
                }

            }
            Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Filtering successful. Returning collection with {0} applications", peerAppCollFiltered.Count);

            return peerAppCollFiltered;
        }
        public static void UnregisterApplication(PeerApplication application, PeerApplicationRegistrationType type)
        {
            PeerCollaborationPermission.UnrestrictedPeerCollaborationPermission.Demand();

            if (application == null){
                throw new ArgumentNullException("application");
            }

            if (application.Id.Equals(Guid.Empty)){
                throw new ArgumentException(SR.GetString(SR.Collab_EmptyGuidError));
            }

            if ((type < PeerApplicationRegistrationType.CurrentUser) || (type > PeerApplicationRegistrationType.AllUsers)){
                throw new ArgumentOutOfRangeException("type");
            }

            CollaborationHelperFunctions.Initialize();

            //
            // Convert PeerApplication.Guid into native GUID struct
            //

            GUID guid = CollaborationHelperFunctions.ConvertGuidToGUID(application.Id);

            if (Logging.P2PTraceSource.Switch.ShouldTrace(TraceEventType.Information))
            {
                Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "UnregisterApplication() is called with the following Info");
                application.TracePeerApplication();
            }

            int errorCode = UnsafeCollabNativeMethods.PeerCollabUnregisterApplication(ref guid, type);

            if (errorCode != 0){
                Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerCollabUnregisterApplication returned with errorcode {0}", errorCode);
                throw (PeerToPeerException.CreateFromHr(SR.GetString(SR.Collab_AppUnregFailed), errorCode));
            }

            Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "UnregisterApplication successful");
        }
        public static void RegisterApplication(PeerApplication application, PeerApplicationRegistrationType type)
        {
            PeerCollaborationPermission.UnrestrictedPeerCollaborationPermission.Demand();

            if (application == null){
                throw new ArgumentNullException("application");
            }
            
            if (application.Path == null){
                throw new ArgumentException(SR.GetString(SR.Collab_AppRegNoPathError));
            }

            if ((type < PeerApplicationRegistrationType.CurrentUser) || (type > PeerApplicationRegistrationType.AllUsers)){
                throw new ArgumentOutOfRangeException("type");
            }

            CollaborationHelperFunctions.Initialize();

            int errorCode = 0;

            //
            // Convert PeerApplication.Guid into native GUID struct
            //

            PEER_APPLICATION_REGISTRATION_INFO appRegInfo = new PEER_APPLICATION_REGISTRATION_INFO();
            appRegInfo.application.guid = CollaborationHelperFunctions.ConvertGuidToGUID(application.Id);

            appRegInfo.pwzApplicationArguments = application.CommandLineArgs;
            appRegInfo.pwzApplicationToLaunch = application.Path;
            appRegInfo.dwPublicationScope = (uint)application.PeerScope;

            if (Logging.P2PTraceSource.Switch.ShouldTrace(TraceEventType.Information)){
                Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "RegisterApplication() is called with the following Info");
                application.TracePeerApplication();
            }

            unsafe{

                SafeCollabMemory data = null;
                appRegInfo.application.data.cbData =    (application.Data!=null) ? 
                                                        (UInt32)application.Data.Length : 0;
                GCHandle descHandle = new GCHandle();

                try{
                    //
                    // Marshal any data to send to native call
                    //

                    if ((application.Data!=null) && (application.Data.Length > 0))
                    {
                        data = new SafeCollabMemory(application.Data.Length);
                        appRegInfo.application.data.pbData = data.DangerousGetHandle();
                        Marshal.Copy(application.Data, 0, appRegInfo.application.data.pbData, application.Data.Length);
                    }
                    else
                        appRegInfo.application.data.pbData = IntPtr.Zero;

                    descHandle = GCHandle.Alloc(application.Description, GCHandleType.Pinned);
                    appRegInfo.application.pwzDescription = descHandle.AddrOfPinnedObject();

                    errorCode = UnsafeCollabNativeMethods.PeerCollabRegisterApplication(ref appRegInfo, type);

                }
                finally{
                    if (descHandle.IsAllocated) descHandle.Free();
                    if (data != null) data.Dispose();
                }
            }
            if (errorCode == UnsafeCollabReturnCodes.PEER_E_ALREADY_EXISTS){
                Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerCollabRegisterApplication returned with errorcode {0}. Application already registered.", errorCode);
                throw new ArgumentException(SR.GetString(SR.Collab_AppRegFailed) + " " + SR.GetString(SR.Collab_AppExists));
            }
            else if (errorCode != 0){
                Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerCollabRegisterApplication returned with errorcode {0}", errorCode);
                throw (PeerToPeerException.CreateFromHr(SR.GetString(SR.Collab_AppRegFailed), errorCode));
            }

            Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "RegisterApplication successful");
        }
示例#5
0
        //------------------------------------------------------------------------------------------------------
        //------------------------------------------------------------------------------------------------------
        //List PeerNearMe objects that may be added as contacts.

        private static void AddContact()
        {
            PeerNearMeCollection  pnmc         = null;
            PeerContactCollection peerContacts = null;
            bool peerNameFound = false;

            PeerApplication application = null;

            try
            {
                Console.WriteLine("Listing the existing contacts...");
                peerContacts = PeerCollaboration.ContactManager.GetContacts();
            }
            catch (PeerToPeerException p2pEx)
            {
                Console.WriteLine("The Peer Collaboration Infrastructure is not responding to the contact enumeration request: {0}", p2pEx.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("An unexpected error occurred while attempting to obtain the contact list: {0}", ex.Message);
            }

            DisplayContacts(peerContacts);

            try
            {
                //Adds one of the PeerNearMe objects as a contact.
                pnmc = GetPeersNearMe();
                Console.WriteLine("Please enter the nickname of the peer you wish to add as a contact:");
                string peerNameToAdd = Console.ReadLine();

                application = RegisterCollabApp();

                foreach (PeerNearMe pnm in pnmc)
                {
                    PeerInvitationResponse res = null;
                    if (pnm.Nickname.Contains(peerNameToAdd))
                    {
                        peerNameFound = true;
                        if (!peerContacts.ToString().Contains(pnm.Nickname))
                        {
                            Console.WriteLine("Adding peer {0} to the contact list.", pnm.Nickname);
                            pnm.AddToContactManager();
                        }
                        else
                        {
                            Console.WriteLine("This peer already exists in your contact list.");
                            Console.WriteLine("Sending invitation using the Contact structure instead of the PeerNearMe.");
                            foreach (PeerContact pc in peerContacts)
                            {
                                if (pc.Nickname.Equals(pnm.Nickname))
                                {
                                    res = pnm.Invite(application, "Peer Collaboration Sample", application.Data);
                                    if (res.PeerInvitationResponseType == PeerInvitationResponseType.Accepted)
                                    {
                                        Console.WriteLine("Invitation to contact succeeded.");
                                    }
                                    else
                                    {
                                        Console.WriteLine("Invitation to contact {0}.", res.PeerInvitationResponseType);
                                    }
                                }
                            }
                        }
                    }
                }

                if (!peerNameFound)
                {
                    Console.WriteLine("No such peer exists near you. Cannot add to contacts.");
                    return;
                }

                peerContacts = PeerCollaboration.ContactManager.GetContacts();

                Console.WriteLine("Listing the contacts again...");
                DisplayContacts(peerContacts);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error adding a contact: {0}", ex.Message);
            }
            finally
            {
                application.Dispose();
            }
            return;
        }