Пример #1
0
        public static void Send(Pager model)
        {
            if (model.To == null || string.IsNullOrWhiteSpace(model.Message)) return;

            using (model.Modifier(x => x.Message))
            {

                Message message = new Message
                {
                    CreatedTime   = DateTime.Now,
                    From          = From,
                    To            = model.To,
                    ContentAsText = model.Message
                };

                model.Message = string.Empty;
                model.History.Add(message)  ;

                m_history.Add(message);

                using (var factory = new ChannelFactory<IMessageHost>(new BasicHttpBinding(), message.To.Uri))
                {
                     factory.Open();
             					 factory.CreateChannel().Send(new Request<Message>(message));
                }

            }
        }
Пример #2
0
        // This test sets a secure service that user our custom encoder/decoder.
        // the service actually modifies the property after deserializing it to simulate what
        // a forwarder/gateway/proxy might do.
        void EncodeDecodeWithSecureWcf()
        {
            Binding binding = WcfHelpers.CreateCustomSecureBinding();
 
            string address = "net.tcp://localhost:8080";
            ServiceHost host = new ServiceHost(new Service(), new Uri(address));
             
            host.AddServiceEndpoint(typeof(IService1), binding, address);
            host.Open();
 
            ChannelFactory<IService1> factory = new ChannelFactory<IService1>(binding, address);
            factory.Open();
            IService1 proxy = factory.CreateChannel();
            ((IChannel)proxy).Open();
 
            Message msg = WcfHelpers.CreateMessage();

            string originalPayloadValue = Guid.NewGuid().ToString();
            WcfHelpers.AddOutOfBandPropertyToMessage(originalPayloadValue, msg);
            
            Message outputMsg = proxy.Operation(msg);

            Console.WriteLine("\nEncoding with secure WCF");
            ValidateResult(originalPayloadValue, outputMsg, Service.TransportModifier);
 
            ((IChannel)proxy).Close();
            host.Close();
        }
Пример #3
0
		IFS2Contract DoCreate(string serverAddress)
		{
			if (serverAddress.StartsWith("net.pipe:"))
			{
				if (!FS2LoadHelper.Load())
					BalloonHelper.ShowFromFiresec("Не удается соединиться с агентом 2");
			}

			var binding = BindingHelper.CreateBindingFromAddress(serverAddress);

			var endpointAddress = new EndpointAddress(new Uri(serverAddress));
			ChannelFactory = new ChannelFactory<IFS2Contract>(binding, endpointAddress);

			foreach (OperationDescription operationDescription in ChannelFactory.Endpoint.Contract.Operations)
			{
				DataContractSerializerOperationBehavior dataContractSerializerOperationBehavior = operationDescription.Behaviors.Find<DataContractSerializerOperationBehavior>() as DataContractSerializerOperationBehavior;
				if (dataContractSerializerOperationBehavior != null)
					dataContractSerializerOperationBehavior.MaxItemsInObjectGraph = Int32.MaxValue;
			}

			ChannelFactory.Open();

			IFS2Contract firesecService = ChannelFactory.CreateChannel();
			(firesecService as IContextChannel).OperationTimeout = TimeSpan.FromMinutes(10);
			return firesecService;
		}
Пример #4
0
        static void Main(string[] args)
        {
            // allow server certificate that doesn't match the host in the endpoint address
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(IgnoreSubjectNameMismatch);

            string uri = "https://" + Environment.MachineName + ":8443/TestService/BinaryEncoderOverHTTPS";
            if (args.Length > 0)
            {
                uri = args[0];
            }
            EndpointAddress address = new EndpointAddress(uri);
            NetHttpBinding binding = new NetHttpBinding();
            ChannelFactory<IEchoService> factory = new ChannelFactory<IEchoService>(binding, address);
            factory.Open();
            IEchoService service = factory.CreateChannel();
            Console.WriteLine(service.Echo(new string('a', 1024)));

            Console.WriteLine("called service successfully using binding in code");

            factory = new ChannelFactory<IEchoService>("EchoServer");
            factory.Open();
            service = factory.CreateChannel();

            Console.WriteLine(service.Echo(new string('b', 1024)));
            Console.WriteLine("called service successfully using binding from config. Press enter to exit...");

            Console.ReadLine();
        }
Пример #5
0
        private static void joinTopicsManager(string username)
        {
            ChannelFactory<TopicsManager> dupFactory = null;
            TopicsManager clientProxy = null;
            dupFactory = new ChannelFactory<TopicsManager>(
                new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:9000/TopicManager"));
            dupFactory.Open();
            clientProxy = dupFactory.CreateChannel();
            while (true)
            {
                Console.WriteLine("************TOPICS MANAGER************");
                Console.WriteLine("Liste des rooms diponibles : ");
                List<string> list = clientProxy.listTopics();
                foreach (var t in list)
                {
                    Console.WriteLine(t);
                }
                Console.WriteLine("1. Se connecter a une room \n2.Créer un nouveau chatroom");

                switch (Console.ReadLine())
                {
                    case "1":
                        Console.WriteLine("Entrez le nom de la room");
                        joinChatroom(clientProxy.joinTopic(Console.ReadLine()), username);

                        break;
                    case "2":
                        Console.WriteLine("Entrez le nom de la room");
                        clientProxy.createTopic(Console.ReadLine());
                        break;

                }
            }
        }
Пример #6
0
        void ICommunicationObject.Open(TimeSpan timeout)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            ChannelFactory.Open(timeoutHelper.RemainingTime());
            InnerChannel.Open(timeoutHelper.RemainingTime());
        }
Пример #7
0
        private void button1_Click(object sender, EventArgs e)
        {
            string page = textBox1.Text;

            try
            {
                EndpointAddress address = new EndpointAddress(new Uri("net.tcp://localhost:2137/Server"));
                NetTcpBinding binding = new NetTcpBinding();
                binding.MaxBufferPoolSize = 4 * 128 * 1024 * 1024;
                binding.MaxBufferSize = 128 * 1024 * 1024;
                binding.MaxReceivedMessageSize = 128 * 1024 * 1024;
                ChannelFactory<IPictureService> fac = new ChannelFactory<IPictureService>(binding, address);
                fac.Open();
                var svc = fac.CreateChannel();

                MessageBox.Show(svc.TextMe("World"));
                Picture pic = svc.DownloadPicture(page);
                Bitmap bmp = pic.GetBitmap();
                pictureBox1.Image = new Bitmap(bmp, new Size(bmp.Width < 894 ? bmp.Width : 894, bmp.Height < 542 ? bmp.Height : 542));
            }
            catch (EndpointNotFoundException ex)
            {
                MessageBox.Show("Brak połączenia z serwerem.\n\n" + ex.Message.ToString());
            }
            
            

        }
Пример #8
0
 public static ChannelItem CreateInstance(BasicHttpBinding bind, EndpointAddress address)
 {
     ChannelFactory<IFICService> factory = new ChannelFactory<IFICService>(bind, address);
     factory.Open();
     IFICService service = factory.CreateChannel();
     return ((service == null) ? null : new ChannelItem(service));
 }
Пример #9
0
		public ImitatorServiceFactory()
		{
			var binding = BindingHelper.CreateBindingFromAddress("net.pipe://127.0.0.1/GKImitator/");
			var endpointAddress = new EndpointAddress(new Uri("net.pipe://127.0.0.1/GKImitator/"));
			_channelFactory = new ChannelFactory<IImitatorService>(binding, endpointAddress);
			_channelFactory.Open();
		}
Пример #10
0
 public AuthForm()
 {
     InitializeComponent();
     ChannelFactory<AuthentificationManager> dupFactory = null;
     dupFactory = new ChannelFactory<AuthentificationManager>(
         new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:8999/AuthManager"));
     dupFactory.Open();
     clientProxy = dupFactory.CreateChannel();
 }
Пример #11
0
        private void button1_Click(object sender, EventArgs e)
        {
            ChannelFactory<SampleServer.ICalcService> factory = new ChannelFactory<SampleServer.ICalcService>("CustomBinding_ICalcService");
            factory.Open();
            SampleServer.ICalcService channel = factory.CreateChannel();
            string result = channel.SetValue(int.Parse(textBox1.Text));
            factory.Close();

            MessageBox.Show(result);
        }
Пример #12
0
 static void Main(string[] args)
 {
     EndpointAddress address = new EndpointAddress("http://127.0.0.1:3721/demoservice");
     Binding binding = new WebHttpBinding();
     ContractDescription contract = ContractDescription.GetContract(typeof(IContract));
     ServiceEndpoint endpoint = new ServiceEndpoint(contract, binding, address);
     using (ChannelFactory<IContract> channelFactory = new ChannelFactory<IContract>(endpoint))
     {
         channelFactory.Endpoint.Behaviors.Add(new WebHttpBehavior());
         channelFactory.Open();
     }
 }
Пример #13
0
 public static void Configure()
 {
     try
     {
         PubilcyInfoProxy = new ChannelFactory<IPubilcyInfo>("BindingIPubilcyInfoService");
         PubilcyInfoProxy.Open();
     }
     catch (Exception ex)
     {
         Log4netHelper.Logger.Fatal(ex);
     }
 }
Пример #14
0
        public override void OnBrowserCreated(CefBrowserWrapper browser)
        {
            browsers.Add(browser);

            if (parentBrowserId == null)
            {
                parentBrowserId = browser.BrowserId;
            }

            if (ParentProcessId == null || parentBrowserId == null)
            {
                return;
            }

            var browserId = browser.IsPopup ? parentBrowserId.Value : browser.BrowserId;

            var serviceName = RenderprocessClientFactory.GetServiceName(ParentProcessId.Value, browserId);

            var binding = BrowserProcessServiceHost.CreateBinding();

            var channelFactory = new ChannelFactory<IBrowserProcess>(
                binding,
                new EndpointAddress(serviceName)
            );

            channelFactory.Open();

            var browserProcess = channelFactory.CreateChannel();
            var clientChannel = ((IClientChannel)browserProcess);

            try
            {
                clientChannel.Open();
                if (!browser.IsPopup)
                {
                    browserProcess.Connect();
                }

                var javascriptObject = browserProcess.GetRegisteredJavascriptObjects();

                if (javascriptObject.MemberObjects.Count > 0)
                {
                    browser.JavascriptRootObject = javascriptObject;
                }

                browser.ChannelFactory = channelFactory;
                browser.BrowserProcess = browserProcess;
            }
            catch(Exception)
            {
            }
        }
Пример #15
0
        static void Main(string[] args)
        {
            Console.WriteLine("Connecting to service.");
            using (var channelFactory = new ChannelFactory<INetTcpService>("NetTcpBinding_IService1"))
            {
                channelFactory.Open();
                var client = channelFactory.CreateChannel();

                //The line below will throw an exception if .NET 4.6 is installed, works fine with 4.5.x
                string result = client.SayHello(Environment.UserName);
                Console.WriteLine("Recieved response, '{0}'", result);
            }
            Console.ReadLine();
        }
 public override void Initialize(EndpointAddress address, Binding binding, ClientCredentials credentials, PeerReferralPolicy referralPolicy)
 {
     this.address = address;
     this.binding = binding;
     this.credentials = credentials;
     Validate();
     channelFactory = new ChannelFactory<IPeerResolverClient>(binding, address);
     channelFactory.Endpoint.Behaviors.Remove<ClientCredentials>();
     if (credentials != null)
         channelFactory.Endpoint.Behaviors.Add(credentials);
     channelFactory.Open();
     this.referralPolicy = referralPolicy;
     opened = true;
 }
Пример #17
0
		void ClientForm_Load(object sender, EventArgs e)
		{
			string serviceUrl = "net.tcp://localhost:65500/Communicate";
			NetTcpBinding ntb = new NetTcpBinding();
			ntb.TransactionFlow = false;
			ntb.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign;
			ntb.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows;
			ntb.Security.Message.ClientCredentialType = MessageCredentialType.Windows;
			ntb.Security.Mode = SecurityMode.Transport;
			f = new ChannelFactory<ICommunicate>(ntb, serviceUrl);
			f.Credentials.Windows.ClientCredential.UserName = "******";
			f.Credentials.Windows.ClientCredential.Password = "******";
			f.Open();
		}
Пример #18
0
 public TopicManForm()
 {
     InitializeComponent();
     ChannelFactory<TopicsManager> dupFactory = null;
     dupFactory = new ChannelFactory<TopicsManager>(
         new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:9000/TopicManager"));
     dupFactory.Open();
     clientProxy = dupFactory.CreateChannel();
     List<string> l = new List<string>();
     l = clientProxy.listTopics();
     foreach (var t in l)
     {
         listBox1.Items.Add(t);
     }
 }
Пример #19
0
 private void GetEnrollBtn_Click(object sender, RoutedEventArgs e)
 {
     enrolledTxt.Text = "";
     using (ChannelFactory<IStudentEnrollmentService> schoolServiceProxy =
     new ChannelFactory<IStudentEnrollmentService>("MyStudentEnrollmentServiceEndpoint"))
     {
         schoolServiceProxy.Open();
         IStudentEnrollmentService schoolEnrollmentService = schoolServiceProxy.CreateChannel();
         Student[] enrolledStudents = schoolEnrollmentService.GetEnrollStudents();
         foreach (Student s in enrolledStudents)
         {
             enrolledTxt.AppendText(s.Name + "\n");
         }
         schoolServiceProxy.Close();
     }
 }
Пример #20
0
        private static void CallService(ServiceCall service, Request request, ICollection<string> servicesFound)
        {
            Console.WriteLine(String.Format(" \t Request to call service {0}", service.Name));

            // Find the Service Interface Type
            var serviceType = GetCloudServices().SingleOrDefault(s => s.IsInterface && String.Equals(s.Name, String.Format("I{0}", service.Name)));
            if (serviceType == null)
            {
                Console.WriteLine("\t Type is UNKNOWN for {0}", service.Name);
                return;
            }

            Console.WriteLine(String.Format("\t Type is: {0}", serviceType.FullName));

            // Intiatialize a ChannelFactory
            using (var channelFactory = new ChannelFactory<ICloudService>(new WSHttpBinding(), new EndpointAddress(service.Address)))
            //using (var channelFactory = new ChannelFactory<ICloudService>(new WSHttpBinding()))
            {
                channelFactory.Open();

                Console.WriteLine("Calling Service {0} at Address {1}", service.Name, service.Address);

                try
                {
                    // Create the Channel & Execute the Response
                    var response = channelFactory.CreateChannel().Execute(request);

                    // Replace the Original Request Argument
                    request.Argument = response.ReturnObject;

                    // Add the Service to the ServicesFound collection
                    servicesFound.Add(serviceType.FullName);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("EXCEPTION - {0}", ex.Message);
                }

                channelFactory.Close();
            }

            // Recursively Call any other services
            if(service.Services != null && service.Services.Length > 0)
            {
                service.Services.ToList().ForEach(s => CallService(s, request, servicesFound));
            }
        }
Пример #21
0
 /// <summary>
 /// Submit a comment for inclusion on a post. This method will either update Sitecore or submit the comment through the comment service, depending on settings
 /// </summary>
 /// <param name="entryId">The ID of the entry to add the comment to</param>
 /// <param name="comment">The comment to add to the entry</param>
 /// <param name="language">The language to create the comment in</param>
 /// <returns>The ID of the created comment item, or ID.Null if creation failed</returns>
 public ID SubmitComment(ID entryId, Model.Comment comment, Language language = null)
 {
     if (Configuration.Settings.GetBoolSetting("WeBlog.CommentService.Enable", false))
     {
         // Submit comment through WCF service
         ChannelFactory<ICommentService> commentProxy = new ChannelFactory<ICommentService>("WeBlogCommentService");
         commentProxy.Open();
         ICommentService service = commentProxy.CreateChannel();
         var result = service.SubmitComment(Context.Item.ID, comment, language);
         commentProxy.Close();
         if (result == ID.Null)
             Log.Error("WeBlog.CommentManager: Comment submission through WCF failed. Check server Sitecore log for details", typeof(CommentManager));
         return result;
     }
     else
         return AddCommentToEntry(Context.Item.ID, comment, language);
 }
Пример #22
0
        public static void SendNumbers(Uri queueAddress, int numberOfMessages)
        {
            NetMsmqBinding binding = new NetMsmqBinding(NetMsmqSecurityMode.None);
            ChannelFactory<IProductCalculator> factory = 
                    new ChannelFactory<IProductCalculator>(binding);
            factory.Open();
            IProductCalculator ipc = factory.CreateChannel(new EndpointAddress(queueAddress.ToString()));

            Random rand = new Random();
            for (int i = 0; i < numberOfMessages; i++)
            {
                int num1 = rand.Next(1, 10);
                int num2 = rand.Next(1, 10);
                ipc.CalculateProduct(num1, num2);
            }
            factory.Close();
        }
Пример #23
0
 public IUpperCase StartClient(Binding binding)
 {
     IUpperCase res = null;
     try
     {
         Console.WriteLine("  Starting Client...");
         fac = new ChannelFactory<IUpperCase>(binding, "soap.amqp:///UpperCase");
         fac.Open();
         res = fac.CreateChannel();
         Console.WriteLine("[DONE]");              
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
     }
     return res;
 }
Пример #24
0
 public IBooking StartClient(System.ServiceModel.Channels.Binding binding)
 {
     IBooking res = null;
     try
     {
         Console.WriteLine("  Starting Client...");
         _fac = new ChannelFactory<IBooking>(binding, "soap.amqp:///Booking");
         _fac.Open();
         res = _fac.CreateChannel();
         Console.WriteLine("[DONE]");
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
     }
     return res;
 }
Пример #25
0
		public RubezhServiceFactory(string serverAddress)
		{
			_serverAddress = serverAddress;
			var binding = BindingHelper.CreateBindingFromAddress(serverAddress);

			var endpointAddress = new EndpointAddress(new Uri(serverAddress));
			_channelFactory = new ChannelFactory<IRubezhService>(binding, endpointAddress);

			foreach (OperationDescription operationDescription in _channelFactory.Endpoint.Contract.Operations)
			{
				DataContractSerializerOperationBehavior dataContractSerializerOperationBehavior = operationDescription.Behaviors.Find<DataContractSerializerOperationBehavior>() as DataContractSerializerOperationBehavior;
				if (dataContractSerializerOperationBehavior != null)
					dataContractSerializerOperationBehavior.MaxItemsInObjectGraph = Int32.MaxValue;
			}

			_channelFactory.Open();
		}
		public static IFiresecCallbackService CreateClientCallback(string serverAddress)
		{
			var binding = Common.BindingHelper.CreateBindingFromAddress(serverAddress);

			var endpointAddress = new EndpointAddress(new Uri(serverAddress));
			var channelFactory = new ChannelFactory<IFiresecCallbackService>(binding, endpointAddress);

			foreach (OperationDescription operationDescription in channelFactory.Endpoint.Contract.Operations)
			{
				DataContractSerializerOperationBehavior dataContractSerializerOperationBehavior = operationDescription.Behaviors.Find<DataContractSerializerOperationBehavior>() as DataContractSerializerOperationBehavior;
				if (dataContractSerializerOperationBehavior != null)
					dataContractSerializerOperationBehavior.MaxItemsInObjectGraph = Int32.MaxValue;
			}
			channelFactory.Open();
			IFiresecCallbackService _firesecCallbackService = channelFactory.CreateChannel();
			(_firesecCallbackService as IContextChannel).OperationTimeout = TimeSpan.FromMinutes(100);
			return _firesecCallbackService;
		}
        protected void Button1_Click(object sender, EventArgs e)
        {
            ChannelFactory<AspNetCompatiSvc.ICalcService> factory = new ChannelFactory<AspNetCompatiSvc.ICalcService>("CustomBinding_ICalcService");
            factory.Open();
            AspNetCompatiSvc.ICalcService channel = factory.CreateChannel();

            // ヘッダーを操作できるようにコンテキストスコープを設定
            using (OperationContextScope scope = new OperationContextScope(channel as IContextChannel))
            {
                channel.SetValue(int.Parse(TextBox1.Text));

                // Response ヘッダーの SetCookie の内容をセッションにコピー
                HttpResponseMessageProperty httpResponseProp = OperationContext.Current.IncomingMessageProperties[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty;
                Session["WCF_SessionID"] = httpResponseProp.Headers[HttpResponseHeader.SetCookie];
            }

            factory.Close();
        }
Пример #28
0
        private void EnrollBtn_Click(object sender, RoutedEventArgs e)
        {
            if (studentNameTxt.Text == "")
                return;
            using (ChannelFactory<IStudentEnrollmentService> schoolServiceProxy =
            new ChannelFactory<IStudentEnrollmentService>("MyStudentEnrollmentServiceEndpoint"))
            {
                schoolServiceProxy.Open();
                IStudentEnrollmentService schoolEnrollmentService = schoolServiceProxy.CreateChannel();
                Student s = new Student();
                s.Name = studentNameTxt.Text;
                schoolEnrollmentService.EnrollStudent(s);
                schoolServiceProxy.Close();
            }

            studentNameTxt.Text = "";

        }
Пример #29
0
 private static void KillExistingServiceIfNeeded(string serviceName)
 {
     // It might be that there is an existing process already bound to this port. We must get rid of that one, so that the
     // endpoint address gets available for us to use.
     try
     {
         var channelFactory = new ChannelFactory<ISubProcessProxy>(
             new NetNamedPipeBinding(),
             new EndpointAddress(serviceName)
             );
         channelFactory.Open(TimeSpan.FromSeconds(1));
         var javascriptProxy = channelFactory.CreateChannel();
         javascriptProxy.Terminate();
     }
     catch
     {
         // We assume errors at this point are caused by things like the endpoint not being present (which will happen in
         // the first render subprocess instance).
     }
 }
Пример #30
0
        public override void OnBrowserCreated(CefBrowserWrapper browser)
        {
            browsers.Add(browser);

            if (parentBrowserId == null)
            {
                parentBrowserId = browser.BrowserId;
            }

            if (parentProcessId == null || parentBrowserId == null)
            {
                return;
            }

            var browserId = browser.IsPopup ? parentBrowserId.Value : browser.BrowserId;

            var serviceName = RenderprocessClientFactory.GetServiceName(parentProcessId.Value, browserId);

            var binding = BrowserProcessServiceHost.CreateBinding();

            var channelFactory = new ChannelFactory<IBrowserProcess>(
                binding,
                new EndpointAddress(serviceName)
            );

            channelFactory.Open();

            var browserProcess = channelFactory.CreateChannel();
            var clientChannel = ((IClientChannel)browserProcess);

            try
            {
                clientChannel.Open();

                browser.ChannelFactory = channelFactory;
                browser.BrowserProcess = browserProcess;
            }
            catch(Exception)
            {
            }
        }
        public AuthenticationResponse Authenticate(AuthenticationRequest request)
        {
            ChannelFactory<IAuthenticationService> channelFactory = null;
            AuthenticationResponse response = null;
            try
            {
                channelFactory = new ChannelFactory<IAuthenticationService>("authentication");
                channelFactory.Open();

                var service = channelFactory.CreateChannel();

                response = service.Authenticate(request);

                channelFactory.Close();
            }
            catch (CommunicationException)
            {
                if (channelFactory != null)
                {
                    channelFactory.Abort();
                }
            }
            catch (TimeoutException)
            {
                if (channelFactory != null)
                {
                    channelFactory.Abort();
                }
            }
            catch (Exception)
            {
                if (channelFactory != null)
                {
                    channelFactory.Abort();
                }
                throw;
            }

            return response;
        }