コード例 #1
1
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                // Local Variables.
                string uRequestID = String.Empty;
                string uStatus = String.Empty;
                String SOAPEndPoint = context.Session["SOAPEndPoint"].ToString();
                String internalOauthToken = context.Session["internalOauthToken"].ToString();
                String id = context.Request.QueryString["id"].ToString().Trim();
                String status = context.Request.QueryString["status"].ToString().Trim();

                // Create the SOAP binding for call.
                BasicHttpBinding binding = new BasicHttpBinding();
                binding.Name = "UserNameSoapBinding";
                binding.Security.Mode = BasicHttpSecurityMode.TransportWithMessageCredential;
                binding.MaxReceivedMessageSize = 2147483647;
                var client = new SoapClient(binding, new EndpointAddress(new Uri(SOAPEndPoint)));
                client.ClientCredentials.UserName.UserName = "******";
                client.ClientCredentials.UserName.Password = "******";

                using (var scope = new OperationContextScope(client.InnerChannel))
                {
                    // Add oAuth token to SOAP header.
                    XNamespace ns = "http://exacttarget.com";
                    var oauthElement = new XElement(ns + "oAuthToken", internalOauthToken);
                    var xmlHeader = MessageHeader.CreateHeader("oAuth", "http://exacttarget.com", oauthElement);
                    OperationContext.Current.OutgoingMessageHeaders.Add(xmlHeader);

                    // Setup Subscriber Object to pass fields for updating.
                    Subscriber sub = new Subscriber();
                    sub.ID = int.Parse(id);
                    sub.IDSpecified = true;
                    if (status.ToLower() == "unsubscribed")
                        sub.Status = SubscriberStatus.Unsubscribed;
                    else
                        sub.Status = SubscriberStatus.Active;
                    sub.StatusSpecified = true;

                    // Call the Update method on the Subscriber object.
                    UpdateResult[] uResults = client.Update(new UpdateOptions(), new APIObject[] { sub }, out uRequestID, out uStatus);

                    if (uResults != null && uStatus.ToLower().Equals("ok"))
                    {
                        String strResults = string.Empty;
                        strResults += uResults;
                        // Return the update results from handler.
                        context.Response.Write(strResults);
                    }
                    else
                    {
                        context.Response.Write("Not OK!");
                    }
                }
            }
            catch (Exception ex)
            {
                context.Response.Write(ex);
            }
        }
コード例 #2
1
ファイル: Program.cs プロジェクト: tengwei/TwApplication
        static void InvokeWithSameProxy()
        {
            ChannelFactory<IAdd> factory=new ChannelFactory<IAdd>("AddService");
            IAdd proxy = factory.CreateChannel();
            if (null != proxy as ICommunicationObject)
            {
                (proxy as ICommunicationObject).Open();
            }
            var datatime = DateTime.Now;
            Console.WriteLine(datatime);
            int num = 100;
            for (int i = 0; i < num; i++)
            {

                ThreadPool.QueueUserWorkItem(delegate
                                             	{
                                                    int clientId = Interlocked.Increment(ref index);
                                             		using (
                                             			OperationContextScope contextScope =
                                             				new OperationContextScope(proxy as IContextChannel))
                                             		{
                                                         Console.WriteLine(i);
                                                         MessageHeader<int> header = new MessageHeader<int>(clientId);
                                             			System.ServiceModel.Channels.MessageHeader messageHeader =
                                             				header.GetUntypedHeader(MessageWrapper.headerClientId,
                                             				                        MessageWrapper.headerNamespace);
                                             			OperationContext.Current.OutgoingMessageHeaders.Add(messageHeader);
                                             			proxy.Add(1, 2);
                                             		    if (i == num-1) {
                                                             Console.WriteLine((DateTime.Now - datatime).Seconds);
                                                         }
                                             		}
                                             	});
            }
        }
コード例 #3
0
		public OperatingSystemList GetOSVersionsProcess(out Operation operation)
		{
			Func<string, OperatingSystemList> func = null;
			OperatingSystemList operatingSystemList = null;
			operation = null;
			using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)base.Channel))
			{
				try
				{
					GetAzureOSVersionCommand getAzureOSVersionCommand = this;
					if (func == null)
					{
						func = (string s) => base.Channel.ListOperatingSystems(s);
					}
					operatingSystemList = ((CmdletBase<IServiceManagement>)getAzureOSVersionCommand).RetryCall<OperatingSystemList>(func);
					operation = base.WaitForOperation(base.CommandRuntime.ToString());
				}
				catch (CommunicationException communicationException1)
				{
					CommunicationException communicationException = communicationException1;
					this.WriteErrorDetails(communicationException);
				}
			}
			return operatingSystemList;
		}
コード例 #4
0
ファイル: Program.cs プロジェクト: AlanLiu-AI/AqDemos
        static void Main(string[] args)
        {
            try
            {
                var aqAquisitionServiceClient = new AQAcquisitionServiceClient("BasicHttpBinding_IAQAcquisitionService", "http://sooke/AQUARIUS/AqAcquisitionService.svc/Basic");
                //var aqAquisitionServiceClient = new AQAcquisitionServiceClient("WSHttpBinding_IAQAcquisitionService", "http://sooke/AQUARIUS/AqAcquisitionService.svc");
                var authToken = aqAquisitionServiceClient.GetAuthToken("admin", "admin");
                Console.WriteLine("Token: " + authToken);

                using (var contextScope = new OperationContextScope(aqAquisitionServiceClient.InnerChannel))
                {
                    var runtimeHeader = MessageHeader.CreateHeader("AQAuthToken", "", authToken, false);
                    OperationContext.Current.OutgoingMessageHeaders.Add(runtimeHeader);
                    var allLocations = aqAquisitionServiceClient.GetAllLocations();
                    Console.WriteLine("There are " + allLocations.Length + " Locations:");
                    foreach (var location in allLocations)
                    {
                        Console.WriteLine("\t" + location.Identifier);
                    }
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine("Error occurred: " + ex.ToString());
            }
            Console.WriteLine("Enter to quit...");
            Console.ReadLine();
        }
 public OperationContextScope(OperationContext context)
 {
     this.originalContext = OperationContext.Current;
     this.originalScope = currentScope;
     this.thread = Thread.CurrentThread;
     this.PushContext(context);
 }
 public OperationContextScope(IContextChannel channel)
 {
     this.originalContext = OperationContext.Current;
     this.originalScope = currentScope;
     this.thread = Thread.CurrentThread;
     this.PushContext(new OperationContext(channel));
 }
コード例 #7
0
        /// <summary>
        /// one-way call to resample an image volume
        /// </summary>
        /// <param name="seriesInstanceUID"></param>
        public void ResampleImageVolume(ImageVolumeResampleRequest request)
        {
            _responseContext =
                OperationContext.Current.IncomingMessageHeaders.GetHeader<ResponseContext>(
                    "ResponseContext", "ServiceModelEx");
            _responseAddress =
                new EndpointAddress(_responseContext.ResponseAddress);

            ResampleEngineClient re = new ResampleEngineClient();

            ImageVolumeResampleResponse response = re.ResampleImageVolume(request);
            System.Diagnostics.Trace.Assert(response.ResampledImageVolumeGuid.CompareTo(Guid.Empty) != 0);

            MessageHeader<ResponseContext> responseHeader = new MessageHeader<ResponseContext>(_responseContext);
            NetMsmqBinding binding = new NetMsmqBinding("NoMsmqSecurity");
            ResampleResponseProxy proxy = new ResampleResponseProxy(binding, _responseAddress);

            using (OperationContextScope scope = new OperationContextScope(proxy.InnerChannel))
            {
                OperationContext.Current.OutgoingMessageHeaders.Add(
                    responseHeader.GetUntypedHeader("ResponseContext", "ServiceModelEx"));

                proxy.OnResampleDone(response);
            }

            proxy.Close();
        }
コード例 #8
0
		internal void AddCertificateProcess()
		{
			Action<string> action = null;
			this.ValidateParameters();
			byte[] certificateData = this.GetCertificateData();
			CertificateFile certificateFile = new CertificateFile();
			certificateFile.Data = Convert.ToBase64String(certificateData);
			certificateFile.Password = this.Password;
			certificateFile.CertificateFormat = "pfx";
			CertificateFile certificateFile1 = certificateFile;
			using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)base.Channel))
			{
				try
				{
					AddAzureCertificateCommand addAzureCertificateCommand = this;
					if (action == null)
					{
						action = (string s) => base.Channel.AddCertificates(s, this.ServiceName, certificateFile1);
					}
					((CmdletBase<IServiceManagement>)addAzureCertificateCommand).RetryCall(action);
					Operation operation = base.WaitForOperation(base.CommandRuntime.ToString());
					ManagementOperationContext managementOperationContext = new ManagementOperationContext();
					managementOperationContext.set_OperationDescription(base.CommandRuntime.ToString());
					managementOperationContext.set_OperationId(operation.OperationTrackingId);
					managementOperationContext.set_OperationStatus(operation.Status);
					ManagementOperationContext managementOperationContext1 = managementOperationContext;
					base.WriteObject(managementOperationContext1, true);
				}
				catch (CommunicationException communicationException1)
				{
					CommunicationException communicationException = communicationException1;
					this.WriteErrorDetails(communicationException);
				}
			}
		}
コード例 #9
0
ファイル: Program.cs プロジェクト: ssickles/archive
        static void Main(string[] args)
        {
            var factory = new ChannelFactory<IFantasyService>("*");
            factory.Credentials.UserName.UserName = "******";
            factory.Credentials.UserName.Password = "******";
            factory.Endpoint.Behaviors.Add(new CustomHeaderEndpointBehavior());
            var proxy = factory.CreateChannel();
            MessageHeader header = MessageHeader.CreateHeader("userId", "http://www.identitystream.com", "Custom Header");

            using (OperationContextScope scope = new OperationContextScope((IContextChannel)proxy))
            {
                OperationContext.Current.OutgoingMessageHeaders.Add(header);

                //HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
                //httpRequestProperty.Headers.Add("myCustomHeader", "Custom Happy Value.");
                //httpRequestProperty.Headers.Add(HttpRequestHeader.UserAgent, "my user agent");
                //OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;

            }
            IList<string> leagueNames = proxy.GetLeagueNames();
            Console.WriteLine(string.Format("{0} league names returned.", leagueNames.Count));
            int teamWins = proxy.GetTeamWins(1);
            Console.WriteLine(string.Format("{0} team wins for team 1.", teamWins));
            Console.ReadLine();
        }
コード例 #10
0
		public void SetAffinityGroupProcess()
		{
			this.ValidateParameters();
			using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)base.Channel))
			{
				try
				{
					UpdateAffinityGroupInput updateAffinityGroupInput = new UpdateAffinityGroupInput();
					updateAffinityGroupInput.Label = ServiceManagementHelper.EncodeToBase64String(this.Label);
					UpdateAffinityGroupInput description = updateAffinityGroupInput;
					if (this.Description != null)
					{
						description.Description = this.Description;
					}
					CmdletExtensions.WriteVerboseOutputForObject(this, description);
					base.RetryCall((string s) => base.Channel.UpdateAffinityGroup(s, this.Name, description));
					Operation operation = base.WaitForOperation(base.CommandRuntime.ToString());
					ManagementOperationContext managementOperationContext = new ManagementOperationContext();
					managementOperationContext.set_OperationDescription(base.CommandRuntime.ToString());
					managementOperationContext.set_OperationId(operation.OperationTrackingId);
					managementOperationContext.set_OperationStatus(operation.Status);
					ManagementOperationContext managementOperationContext1 = managementOperationContext;
					base.WriteObject(managementOperationContext1, true);
				}
				catch (CommunicationException communicationException1)
				{
					CommunicationException communicationException = communicationException1;
					this.WriteErrorDetails(communicationException);
				}
			}
		}
コード例 #11
0
        /// <summary>
        /// 重新连接wcf服务
        /// </summary>
        /// <param name="mainfrm"></param>
        public static void ReConnection()
        {
            try
            {
                NetTcpBinding binding = new NetTcpBinding("NetTcpBinding_WCFHandlerService");
                //binding.OpenTimeout = TimeSpan.FromSeconds(10);
                //binding.TransferMode = TransferMode.Buffered;
                DuplexChannelFactory<IWCFHandlerService> mChannelFactory = new DuplexChannelFactory<IWCFHandlerService>(AppGlobal.cache.GetData("ClientService") as IClientService, binding, System.Configuration.ConfigurationSettings.AppSettings["WCF_endpoint"]);
                IWCFHandlerService wcfHandlerService = mChannelFactory.CreateChannel();

                using (var scope = new OperationContextScope(wcfHandlerService as IContextChannel))
                {
                    var router = System.ServiceModel.Channels.MessageHeader.CreateHeader("routerID", myNamespace, AppGlobal.cache.GetData("routerID").ToString());
                    OperationContext.Current.OutgoingMessageHeaders.Add(router);
                    wcfHandlerService.Heartbeat(AppGlobal.cache.GetData("WCFClientID").ToString());
                }

                if (AppGlobal.cache.Contains("WCFService")) AppGlobal.cache.Remove("WCFService");
                AppGlobal.cache.Add("WCFService", wcfHandlerService);
            }
            catch (Exception err)
            {
                throw new Exception(err.Message);
            }
        }
コード例 #12
0
		public void SetWalkUpgradeDomainProcess()
		{
			Action<string> action = null;
			WalkUpgradeDomainInput walkUpgradeDomainInput = new WalkUpgradeDomainInput();
			walkUpgradeDomainInput.UpgradeDomain = this.DomainNumber;
			WalkUpgradeDomainInput walkUpgradeDomainInput1 = walkUpgradeDomainInput;
			using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)base.Channel))
			{
				try
				{
					SetAzureWalkUpgradeDomainCommand setAzureWalkUpgradeDomainCommand = this;
					if (action == null)
					{
						action = (string s) => base.Channel.WalkUpgradeDomainBySlot(s, this.ServiceName, this.Slot, walkUpgradeDomainInput1);
					}
					((CmdletBase<IServiceManagement>)setAzureWalkUpgradeDomainCommand).RetryCall(action);
					Operation operation = base.WaitForOperation(base.CommandRuntime.ToString());
					ManagementOperationContext managementOperationContext = new ManagementOperationContext();
					managementOperationContext.set_OperationDescription(base.CommandRuntime.ToString());
					managementOperationContext.set_OperationId(operation.OperationTrackingId);
					managementOperationContext.set_OperationStatus(operation.Status);
					ManagementOperationContext managementOperationContext1 = managementOperationContext;
					base.WriteObject(managementOperationContext1, true);
				}
				catch (CommunicationException communicationException1)
				{
					CommunicationException communicationException = communicationException1;
					this.WriteErrorDetails(communicationException);
				}
			}
		}
コード例 #13
0
		protected override void ProcessRecord()
		{
			Func<string, Deployment> func = null;
			base.ProcessRecord();
			if (!string.IsNullOrEmpty(this.ServiceName))
			{
				using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)base.Channel))
				{
					new List<PersistentVMRoleContext>();
					try
					{
						IaaSDeploymentManagementCmdletBase iaaSDeploymentManagementCmdletBase = this;
						IaaSDeploymentManagementCmdletBase iaaSDeploymentManagementCmdletBase1 = this;
						if (func == null)
						{
							func = (string s) => base.Channel.GetDeploymentBySlot(s, this.ServiceName, "Production");
						}
						iaaSDeploymentManagementCmdletBase.CurrentDeployment = ((CmdletBase<IServiceManagement>)iaaSDeploymentManagementCmdletBase1).RetryCall<Deployment>(func);
						this.GetDeploymentOperation = base.WaitForOperation("Get Deployment");
					}
					catch (CommunicationException communicationException1)
					{
						CommunicationException communicationException = communicationException1;
						if (communicationException as EndpointNotFoundException == null)
						{
							throw;
						}
						else
						{
							return;
						}
					}
				}
			}
		}
        private void GetResponse(ICollection<IPointToLaceProvider> response)
        {
            var webService = new ConfigureIvidTitleHolder();

            using (var scope = new OperationContextScope(webService.Client.InnerChannel))
            {
                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] =
                    webService.RequestMessageProperty;

                var request =
                    HandleRequest.GetTitleholderQueryRequest(response,_dataProvider.GetRequest<IAmIvidTitleholderRequest>());

                _logCommand.LogConfiguration(new {request}, null);
                _logCommand.LogRequest(new ConnectionTypeIdentifier(webService.Client.Endpoint.Address.ToString()).ForWebApiType(), new { request }, _dataProvider.BillablleState.NoRecordState);

                _response = webService
                    .Client
                    .TitleholderQuery(request);

                webService.Close();

                _logCommand.LogResponse(_response == null ? DataProviderResponseState.NoRecords : DataProviderResponseState.Successful,
                    new ConnectionTypeIdentifier(webService.Client.Endpoint.Address.ToString())
                        .ForWebApiType(), _response ?? new TitleholderQueryResponse(), _dataProvider.BillablleState.NoRecordState);

                if (_response == null)
                    _logCommand.LogFault(new {_dataProvider}, new {NoRequestReceived = "No response received from Ivid Title Holder Data Provider"});
            }
        }
コード例 #15
0
        public void Submit(Order order)
        {
            Console.WriteLine("Begin to process the order of the order No.: {0}", order.OrderNo);
            FaultException exception = null;
            if (order.OrderDate < DateTime.Now) {
                exception = new FaultException(new FaultReason("The order has expried"), new FaultCode("sender"));
                Console.WriteLine("It's fail to process the order.\n\tOrder No.: {0}\n\tReason:{1}", order.OrderNo, "The order has expried");
            } else {
                Console.WriteLine("It's successful to process the order.\n\tOrder No.: {0}", order.OrderNo);
            }
            NetMsmqBinding binding = new NetMsmqBinding();
            binding.ExactlyOnce = false;
            binding.Security.Transport.MsmqAuthenticationMode = MsmqAuthenticationMode.None;
            binding.Security.Transport.MsmqProtectionLevel = ProtectionLevel.None;

            ChannelFactory<IOrderRessponse> channelFactory = new ChannelFactory<IOrderRessponse>(binding);
            OrderResponseContext responseContext = OrderResponseContext.Current;

            IOrderRessponse channel = channelFactory.CreateChannel(new EndpointAddress(responseContext.ResponseAddress));

            using (OperationContextScope contextScope = new OperationContextScope(channel as IContextChannel)) {
                channel.SubmitOrderResponse(order.OrderNo, exception);
            }
            Console.Read();
        }
        public void DeliverMessage(ExternalDataEventArgs eventArgs, IComparable queueName, object message, object workItem, IPendingWork workHandler)
        {
            if (eventArgs == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("eventArgs");
            }
            if (queueName == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("queueName");
            }

            using (ExternalDataExchangeClient desClient = new ExternalDataExchangeClient(WorkflowRuntimeEndpoint.netNamedPipeContextBinding,
                new EndpointAddress(this.baseUri)))
            {
                using (OperationContextScope scope = new OperationContextScope((IContextChannel)desClient.InnerChannel))
                {
                    IContextManager contextManager = desClient.InnerChannel.GetProperty<IContextManager>();
                    Fx.Assert(contextManager != null, "IContextManager must not be null.");
                    if (contextManager != null)
                    {
                        IDictionary<string, string> context = new Dictionary<string, string>();
                        context["instanceId"] = eventArgs.InstanceId.ToString();
                        contextManager.SetContext(context);
                    }

                    desClient.RaiseEvent(eventArgs, queueName, message);
                }
            }
  
        }
コード例 #17
0
ファイル: MonitorForm.cs プロジェクト: huoxudong125/WCF-Demo
        //其他成员
        private void MonitorForm_Load(object sender, EventArgs e)
        {
            string header = string.Format("{0, -13}{1, -22}{2}", "Client", "Time", "Event");
            this.listBoxExecutionProgress.Items.Add(header);
            _syncContext = SynchronizationContext.Current;
            _callbackInstance = new InstanceContext(new CalculatorCallbackService());
            _channelFactory = new DuplexChannelFactory<ICalculator>(_callbackInstance, "calculatorservice");

            EventMonitor.MonitoringNotificationSended += ReceiveMonitoringNotification;
            this.Disposed += delegate
            {
            EventMonitor.MonitoringNotificationSended -= ReceiveMonitoringNotification;
            _channelFactory.Close();
            };

            for (int i = 0; i < 2; i++)
            {
            ThreadPool.QueueUserWorkItem(state =>
            {
                int clientId = Interlocked.Increment(ref _clientId);
                EventMonitor.Send(clientId, EventType.StartCall);
                ICalculator proxy = _channelFactory.CreateChannel();
                using (OperationContextScope contextScope = new OperationContextScope(proxy as IContextChannel))
                {
                    MessageHeader<int> messageHeader = new MessageHeader<int>(clientId);
                    OperationContext.Current.OutgoingMessageHeaders.Add(messageHeader.GetUntypedHeader(EventMonitor.CientIdHeaderLocalName, EventMonitor.CientIdHeaderNamespace));
                    proxy.Add(1, 2);
                }
                EventMonitor.Send(clientId, EventType.EndCall);
            }, null);
            }
        }
コード例 #18
0
        static void Main(string[] args)
        {
            var aosUriString = ClientConfiguration.Default.UriString;

            var oauthHeader = OAuthHelper.GetAuthenticationHeader();
            var serviceUriString = SoapUtility.SoapHelper.GetSoapServiceUriString(UserSessionServiceName, aosUriString);

            var endpointAddress = new System.ServiceModel.EndpointAddress(serviceUriString);
            var binding = SoapUtility.SoapHelper.GetBinding();

            var client = new UserSessionServiceClient(binding, endpointAddress);
            var channel = client.InnerChannel;

            UserSessionInfo sessionInfo = null;

            using (OperationContextScope operationContextScope = new OperationContextScope(channel))
            {
                HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty();
                 requestMessage.Headers[OAuthHelper.OAuthHeader] = oauthHeader;
                 OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage;
                 sessionInfo = ((UserSessionService)channel).GetUserSessionInfo(new GetUserSessionInfo()).result;
            }

            Console.WriteLine();
            Console.WriteLine("User ID: {0}", sessionInfo.UserId);
            Console.WriteLine("Is Admin: {0}", sessionInfo.IsSysAdmin);
            Console.ReadLine();
        }
コード例 #19
0
ファイル: Program.cs プロジェクト: 0811112150/HappyDayHistory
        static void Main(string[] args)
        {
            Order order1 = new Order(Guid.NewGuid(), DateTime.Today.AddDays(5), Guid.NewGuid(), "Supplier A");
            Order order2 = new Order(Guid.NewGuid(), DateTime.Today.AddDays(-5), Guid.NewGuid(), "Supplier A");

            string path = ConfigurationManager.AppSettings["msmqPath"];
            var address = new Uri(path);
            OrderResponseContext context = new OrderResponseContext();
            context.ResponseAddress = address;

            var channelFactory = new ChannelFactory<IOrderProcesser>("defaultEndpoint");
            var orderProcessor = channelFactory.CreateChannel();
            using (var contextScope = new OperationContextScope(orderProcessor as IContextChannel)) {
                Console.WriteLine("Submit the order of order No.: {0}", order1.OrderNo);
                OrderResponseContext.Current = context;
                orderProcessor.Submit(order1);
            }

            using (OperationContextScope contextScope = new OperationContextScope(orderProcessor as IContextChannel)) {
                Console.WriteLine("Submit the order of order No.: {0}", order2.OrderNo);
                OrderResponseContext.Current = context;
                orderProcessor.Submit(order2);
            }

            Console.Read();
        }
コード例 #20
0
		public GatewayManagementOperationContext NewVirtualNetworkGatewayCommandProcess()
		{
			Func<string, GatewayOperationAsyncResponse> func = null;
			using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)base.Channel))
			{
				try
				{
					NewAzureVNetGatewayCommand newAzureVNetGatewayCommand = this;
					if (func == null)
					{
						func = (string s) => base.Channel.NewVirtualNetworkGateway(s, this.VNetName);
					}
					((CmdletBase<IGatewayServiceManagement>)newAzureVNetGatewayCommand).RetryCall<GatewayOperationAsyncResponse>(func);
					Operation operation = base.WaitForGatewayOperation(base.CommandRuntime.ToString());
					ManagementOperationContext managementOperationContext = new ManagementOperationContext();
					managementOperationContext.set_OperationDescription(base.CommandRuntime.ToString());
					managementOperationContext.set_OperationId(operation.OperationTrackingId);
					managementOperationContext.set_OperationStatus(operation.Status);
					ManagementOperationContext managementOperationContext1 = managementOperationContext;
					base.WriteObject(managementOperationContext1, true);
				}
				catch (CommunicationException communicationException1)
				{
					CommunicationException communicationException = communicationException1;
					this.WriteErrorDetails(communicationException);
				}
			}
			return null;
		}
コード例 #21
0
        protected async void Button1_Click(object sender, EventArgs e)
        {
            var authServer = new AuthorizationServerDescription()
            {
                
                TokenEndpoint = new Uri("http://localhost:53022/OAuth/token "),
                ProtocolVersion = ProtocolVersion.V20
            };
            WebServerClient Client= new WebServerClient(authServer, "idefav", "1");

            var code =await Client.GetClientAccessTokenAsync(new string[] { "http://localhost:55045/IService1/DoWork" });
            string token = code.AccessToken;
            Service1Reference.Service1Client service1Client=new Service1Client();
            var httpRequest = (HttpWebRequest)WebRequest.Create(service1Client.Endpoint.Address.Uri);
            ClientBase.AuthorizeRequest(httpRequest,token);
            var httpDetails = new HttpRequestMessageProperty();
            httpDetails.Headers[HttpRequestHeader.Authorization] = httpRequest.Headers[HttpRequestHeader.Authorization];
            
            using (var scope = new OperationContextScope(service1Client.InnerChannel))
            {
                
                if (OperationContext.Current.OutgoingMessageProperties.ContainsKey(HttpRequestMessageProperty.Name))
                {
                    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpDetails;
                }
                else
                {
                    OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpDetails);
                }
                
                Button1.Text= service1Client.DoWork();
            }


        }
コード例 #22
0
		public GatewayManagementOperationContext SetVirtualNetworkGatewayCommandProcess()
		{
			using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)base.Channel))
			{
				try
				{
					UpdateConnection updateConnection = new UpdateConnection();
					SwitchParameter connect = this.Connect;
					if (!connect.IsPresent)
					{
						updateConnection.Operation = UpdateConnectionOperation.Disconnect;
					}
					else
					{
						updateConnection.Operation = UpdateConnectionOperation.Connect;
					}
					base.RetryCall<GatewayOperationAsyncResponse>((string s) => base.Channel.UpdateVirtualNetworkGatewayConnection(s, this.VNetName, this.LocalNetworkSiteName, updateConnection));
					Operation operation = base.WaitForGatewayOperation(base.CommandRuntime.ToString());
					ManagementOperationContext managementOperationContext = new ManagementOperationContext();
					managementOperationContext.set_OperationDescription(base.CommandRuntime.ToString());
					managementOperationContext.set_OperationId(operation.OperationTrackingId);
					managementOperationContext.set_OperationStatus(operation.Status);
					ManagementOperationContext managementOperationContext1 = managementOperationContext;
					base.WriteObject(managementOperationContext1, true);
				}
				catch (CommunicationException communicationException1)
				{
					CommunicationException communicationException = communicationException1;
					this.WriteErrorDetails(communicationException);
				}
			}
			return null;
		}
コード例 #23
0
ファイル: Program.cs プロジェクト: Kelvin-Lei/WCFService_Demo
        static void Main(string[] args)
        {
            using (ChannelFactory<IMessage> channelFactory = new ChannelFactory<IMessage>("messageservice"))
            {
                IMessage proxy = channelFactory.CreateChannel();
                using (OperationContextScope contextScope = new OperationContextScope(proxy as IContextChannel))
                {
                    MessageHeader<CultureInfo> header = new MessageHeader<CultureInfo>(Thread.CurrentThread.CurrentUICulture);
                    OperationContext.Current.OutgoingMessageHeaders.Add(header.GetUntypedHeader(CultureInfoHeadLocalName, CultureInfoHeaderNamespace));
                    Console.WriteLine("The UI culture of current thread is {0}", Thread.CurrentThread.CurrentUICulture);
                    Console.WriteLine(proxy.GetMessage());
                }

                Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
                using (OperationContextScope contextScope = new OperationContextScope(proxy as IContextChannel))
                {
                    MessageHeader<CultureInfo> header = new MessageHeader<CultureInfo>(Thread.CurrentThread.CurrentUICulture);
                    OperationContext.Current.OutgoingMessageHeaders.Add(header.GetUntypedHeader(CultureInfoHeadLocalName, CultureInfoHeaderNamespace));
                    Console.WriteLine("The UI culture of current thread is {0}", Thread.CurrentThread.CurrentUICulture);
                    Console.WriteLine(proxy.GetMessage());
                }
            }

            Console.Read();
        }
コード例 #24
0
		public void RemoveDeploymentProcess()
		{
			Action<string> action = null;
			using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)base.Channel))
			{
				try
				{
					RemoveAzureDeploymentCommand removeAzureDeploymentCommand = this;
					if (action == null)
					{
						action = (string s) => base.Channel.DeleteDeploymentBySlot(s, this.ServiceName, this.Slot);
					}
					((CmdletBase<IServiceManagement>)removeAzureDeploymentCommand).RetryCall(action);
					Operation operation = base.WaitForOperation(base.CommandRuntime.ToString());
					ManagementOperationContext managementOperationContext = new ManagementOperationContext();
					managementOperationContext.set_OperationDescription(base.CommandRuntime.ToString());
					managementOperationContext.set_OperationId(operation.OperationTrackingId);
					managementOperationContext.set_OperationStatus(operation.Status);
					ManagementOperationContext managementOperationContext1 = managementOperationContext;
					base.WriteObject(managementOperationContext1, true);
				}
				catch (CommunicationException communicationException1)
				{
					CommunicationException communicationException = communicationException1;
					this.WriteErrorDetails(communicationException);
				}
			}
		}
コード例 #25
0
		public OSImage UpdateVMImageProcess(out string operationId)
		{
			operationId = string.Empty;
			OSImage oSImage = null;
			using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)base.Channel))
			{
				try
				{
					OSImage imageName = new OSImage();
					imageName.Name = this.ImageName;
					imageName.Label = this.Label;
					OSImage oSImage1 = imageName;
					CmdletExtensions.WriteVerboseOutputForObject(this, oSImage1);
					oSImage = base.RetryCall<OSImage>((string s) => base.Channel.UpdateOSImage(s, this.ImageName, oSImage1));
					Operation operation = base.WaitForOperation(base.CommandRuntime.ToString());
					ManagementOperationContext managementOperationContext = new ManagementOperationContext();
					managementOperationContext.set_OperationDescription(base.CommandRuntime.ToString());
					managementOperationContext.set_OperationId(operation.OperationTrackingId);
					managementOperationContext.set_OperationStatus(operation.Status);
					ManagementOperationContext managementOperationContext1 = managementOperationContext;
					base.WriteObject(managementOperationContext1, true);
				}
				catch (CommunicationException communicationException1)
				{
					CommunicationException communicationException = communicationException1;
					this.WriteErrorDetails(communicationException);
				}
			}
			return oSImage;
		}
コード例 #26
0
        void MainPageLoaded(object sender, RoutedEventArgs e)
        {
            // Simple Version
            var basicHttpBinding = new BasicHttpBinding();
            var endpointAddress = new EndpointAddress("http://localhost:50738/UserGroupEvent.svc");
            var userGroupEventService = new ChannelFactory<IAsyncUserGroupEventService>(basicHttpBinding, endpointAddress).CreateChannel();

            AsyncCallback asyncCallBack = delegate(IAsyncResult result)
            {
                var response = ((IAsyncUserGroupEventService)result.AsyncState).EndGetUserGroupEvent(result);
                Dispatcher.BeginInvoke(() => SetUserGroupEventData(response));
            };
            userGroupEventService.BeginGetUserGroupEvent("123", asyncCallBack, userGroupEventService);

            // Deluxe Variante mit eigenem Proxy
            var channel = new UserGroupEventServiceProxy("BasicHttpBinding_IAsyncUserGroupEventService").Channel;
            channel.BeginGetUserGroupEvent("123", ProcessResult, channel);

            // Variante mit Faulthandler
            using (var scope = new OperationContextScope((IContextChannel)channel))
            {
                var messageHeadersElement = OperationContext.Current.OutgoingMessageHeaders;
                messageHeadersElement.Add(MessageHeader.CreateHeader("DoesNotHandleFault", "", true));
                channel.BeginGetUserGroupEventWithFault("123", ProcessResultWithFault, channel);
            }
        }
コード例 #27
0
        private static void CallSimpleCustomHeaderService()
        {
            using (var client = new SimpleCustomHeaderServiceClient())
            {
                using (var scope = new OperationContextScope(client.InnerChannel))
                {
                    //Log the user who's web session resulted in this service call
                    var webUser = new MessageHeader<string>("joe.bloggs");
                    var webUserHeader = webUser.GetUntypedHeader("web-user", "ns");

                    //Log which webnode we were on behind the load balancer
                    var webNodeId = new MessageHeader<int>(1234);
                    var webNodeIdHeader = webNodeId.GetUntypedHeader("web-node-id", "ns");

                    //Log a unique session id
                    var webSessionId = new MessageHeader<Guid>(Guid.NewGuid());
                    var webSessionIdHeader = webSessionId.GetUntypedHeader("web-session-id", "ns");

                    OperationContext.Current.OutgoingMessageHeaders.Add(webUserHeader);
                    OperationContext.Current.OutgoingMessageHeaders.Add(webNodeIdHeader);
                    OperationContext.Current.OutgoingMessageHeaders.Add(webSessionIdHeader);

                    System.Console.WriteLine(client.DoWork());
                }
            }
        }
コード例 #28
0
ファイル: CommonCRUDSvAgent.cs プロジェクト: Allen-Zhou/AF
        public void Add(DTOBase entityDTO)
        {
            try
            {
                //var header = new MessageHeader<ProfileContext>();
                //OperationContext.Current.OutgoingMessageHeaders.Add(header.GetUntypedHeader("Int32", "System"));
                Guid result = Guid.Empty;

                var contextChannel = _channel as IContextChannel;
                if (contextChannel != null)
                {
                    using (var scope = new OperationContextScope(contextChannel))
                    {
                        var contextManager = new ServiceContextManager();
                        ServiceContextManager.Current = contextManager;
                        _channel.Add(new List<object>() { entityDTO });
                    }
                }
                else
                {
                    //WCF调用方式 理论上应该不会走到这里,在本地调用方式进行处理

                }

            }
            catch (FaultException<ExceptionBase> seb)
            {
                //系统异常
                //TO DO Log...
                if (seb.Detail != null)
                    throw seb.Detail;
                else
                    throw new ExceptionBase();
            }
            catch (FaultException<UnhandledException> unex)
            {
                //服务端未处理异常
                //TO DO Log...
                throw unex.Detail;
            }
            catch (FaultException fe)
            {
                throw fe.InnerException;
            }
            catch (Exception e)
            {
                //传输过程中出现的异常
                //TO DO Log...
                Console.WriteLine(e.Message);
                throw;
            }
            finally
            {
                var realChannel = _channel as IDisposable;
                if (realChannel != null)
                {
                    realChannel.Dispose();
                }
            }
        }
コード例 #29
0
    public static void DigestAuthentication_Echo_RoundTrips_String_No_Domain()
    {
        ChannelFactory<IWcfService> factory = null;
        IWcfService serviceProxy = null;
        string testString = "Hello";
        BasicHttpBinding binding;

        try
        {
            // *** SETUP *** \\
            binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Digest;
            factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Http_DigestAuth_NoDomain_Address));

            string DigestUsernameHeaderName = "DigestUsername";
            string DigestPasswordHeaderName = "DigestPassword";
            string DigestRealmHeaderName = "DigestRealm";
            string username = Guid.NewGuid().ToString("n").Substring(0, 8);
            string password = Guid.NewGuid().ToString("n").Substring(0, 16);
            string realm = Guid.NewGuid().ToString("n").Substring(0, 5);
            factory.Credentials.HttpDigest.ClientCredential = new NetworkCredential(username, password, realm);

            serviceProxy = factory.CreateChannel();

            // *** EXECUTE *** \\
            string result = null;
            using (var scope = new OperationContextScope((IContextChannel)serviceProxy))
            {
                HttpRequestMessageProperty requestMessageProperty;
                if (!OperationContext.Current.OutgoingMessageProperties.ContainsKey(HttpRequestMessageProperty.Name))
                {
                    requestMessageProperty = new HttpRequestMessageProperty();
                    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessageProperty;
                }
                else
                {
                    requestMessageProperty = (HttpRequestMessageProperty)OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name];
                }

                requestMessageProperty.Headers[DigestUsernameHeaderName] = username;
                requestMessageProperty.Headers[DigestPasswordHeaderName] = password;
                requestMessageProperty.Headers[DigestRealmHeaderName] = realm;

                result = serviceProxy.Echo(testString);
            }

            // *** VALIDATE *** \\
            Assert.True(result == testString, string.Format("Error: expected response from service: '{0}' Actual was: '{1}'", testString, result));

            // *** CLEANUP *** \\
            factory.Close();
            ((ICommunicationObject)serviceProxy).Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }
コード例 #30
0
		public IEnumerable<Certificate> GetCertificateProcess(out Operation operation)
		{
			IEnumerable<Certificate> certificates;
			Func<string, Certificate> func = null;
			Func<string, CertificateList> func1 = null;
			IEnumerable<Certificate> certificates1 = null;
			operation = null;
			using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)base.Channel))
			{
				try
				{
					if (this.Thumbprint == null)
					{
						GetAzureCertificateCommand getAzureCertificateCommand = this;
						if (func1 == null)
						{
							func1 = (string s) => base.Channel.ListCertificates(s, this.ServiceName);
						}
						certificates1 = ((CmdletBase<IServiceManagement>)getAzureCertificateCommand).RetryCall<CertificateList>(func1);
					}
					else
					{
						if (this.ThumbprintAlgorithm != null)
						{
							Certificate[] certificateArray = new Certificate[1];
							Certificate[] certificateArray1 = certificateArray;
							int num = 0;
							GetAzureCertificateCommand getAzureCertificateCommand1 = this;
							if (func == null)
							{
								func = (string s) => base.Channel.GetCertificate(s, this.ServiceName, this.ThumbprintAlgorithm, this.Thumbprint);
							}
							certificateArray1[num] = ((CmdletBase<IServiceManagement>)getAzureCertificateCommand1).RetryCall<Certificate>(func);
							certificates1 = certificateArray;
						}
						else
						{
							throw new ArgumentNullException("ThumbprintAlgorithm", "You must specify the thumbprint algorithm.");
						}
					}
					operation = base.WaitForOperation(base.CommandRuntime.ToString());
				}
				catch (CommunicationException communicationException1)
				{
					CommunicationException communicationException = communicationException1;
					if (communicationException as EndpointNotFoundException == null || base.IsVerbose())
					{
						this.WriteErrorDetails(communicationException);
					}
					else
					{
						certificates = null;
						return certificates;
					}
				}
				return certificates1;
			}
			return certificates;
		}
コード例 #31
0
ファイル: Docusign.cs プロジェクト: uvason/Decisions.Docusign
        //Docusign API dev guide says this method is subject to call limit and should not be used more than once every 15 min per unique envelope ID
        public static string GetDocumentStatus(string envelopeId, [IgnoreMappingDefault] DocusignCredentials overrideCredentials = null)
        {
            IDocusignCreds creds = overrideCredentials as IDocusignCreds ?? DSServiceClientFactory.DsSettings;

            var dsClient = DSServiceClientFactory.GetDsClient(creds);

            using (var scope = new System.ServiceModel.OperationContextScope(dsClient.InnerChannel))
            {
                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = DSServiceClientFactory.GetAuthHeaderRequestProperty(creds);

                return(dsClient.RequestStatus(envelopeId).Status.ToString());
            }
        }
コード例 #32
0
        public DSAPIService.EnvelopeStatus CreateAndSendEnvelope(DocuSignCredential credential, DSAPIService.Envelope envelope)
        {
            DSAPIService.DSAPIServiceSoapClient svc = new DSAPIService.DSAPIServiceSoapClient();

            using (OperationContextScope scope = new System.ServiceModel.OperationContextScope(svc.InnerChannel))
            {
                HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
                httpRequestProperty.Headers.Add("X-DocuSign-Authentication", GetAuthXML(credential));
                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;

                DSAPIService.EnvelopeStatus status = svc.CreateAndSendEnvelope(envelope);
                return(status);
            }
        }
コード例 #33
0
    protected void getTemplates(object sender, EventArgs e)
    {
        String userName      = ConfigurationManager.AppSettings["API.Email"];
        String password      = ConfigurationManager.AppSettings["API.Password"];
        String integratorKey = ConfigurationManager.AppSettings["API.IntegratorKey"];
        String accountID     = ConfigurationManager.AppSettings["API.TemplatesAccountID"];

        try
        {
            ServiceReference1.DSAPIServiceSoapClient srv = new ServiceReference1.DSAPIServiceSoapClient();
            String auth = "<DocuSignCredentials><Username>" + userName
                          + "</Username><Password>" + password
                          + "</Password><IntegratorKey>" + integratorKey
                          + "</IntegratorKey></DocuSignCredentials>";


            using (OperationContextScope scope = new System.ServiceModel.OperationContextScope(srv.InnerChannel))
            {
                HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
                httpRequestProperty.Headers.Add("X-DocuSign-Authentication", auth);
                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;

                EnvelopeTemplateDefinition[] templates = srv.RequestTemplates(accountID, true);
                {
                    foreach (EnvelopeTemplateDefinition etd in templates)
                    {
                        templatesList.Items.Add(new ListItem(etd.Name, etd.TemplateID));
                    }
                }
            }
        }
        catch (Exception ex)
        {
            // Log4Net Piece
            log4net.ILog logger = log4net.LogManager.GetLogger(typeof(_Default));
            logger.Info("\n----------------------------------------\n");
            logger.Error(ex.Message);
            logger.Error(ex.StackTrace);
            Response.Write(ex.Message);
        }
        finally
        {
        }
    }
コード例 #34
0
        /// <summary>
        /// 提交该单据对象相应的业务操作
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="operateState"></param>
        /// <param name="remark"></param>
        /// <returns></returns>
        public virtual int BusinessFlowSubmit(object entity, MB.Util.Model.DocOperateType operateState, string remark)
        {
            object[] pars = new object[] { entity, operateState, remark };
            object   val  = null;

            using (TChannel serverRuleProxy = CreateServerRuleProxy()) {
                System.ServiceModel.IClientChannel channel = MB.Util.MyReflection.Instance.InvokePropertyForGet(serverRuleProxy, "InnerChannel") as System.ServiceModel.IClientChannel;
                using (System.ServiceModel.OperationContextScope scope = new System.ServiceModel.OperationContextScope(channel)) {
                    //增加消息表头信息
                    MB.WinBase.WcfClient.MessageHeaderHelper.AppendUserLoginInfo();
                    val = MB.WcfServiceLocator.WcfClientHelper.Instance.InvokeServerMethod(serverRuleProxy, "BusinessFlowSubmit", pars);
                }
                if (val == null || (int)val < 0)
                {
                    return(-1);
                }
            }
            return(1);
        }
コード例 #35
0
        private void PopContext()
        {
            if (OperationContextScope.s_currentScope != this)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxInterleavedContextScopes0));
            }

            if (OperationContext.Current != _currentContext)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxContextModifiedInsideScope0));
            }

            OperationContextScope.s_currentScope = _originalScope;
            OperationContext.Current             = _originalContext;

            if (_currentContext != null)
            {
                _currentContext.SetClientReply(null, false);
            }
        }
コード例 #36
0
ファイル: Docusign.cs プロジェクト: uvason/Decisions.Docusign
        public static FileData GetSignedDocument(string envelopeId, [IgnoreMappingDefault] DocusignCredentials overrideCredentials = null)
        {
            IDocusignCreds creds = overrideCredentials as IDocusignCreds ?? DSServiceClientFactory.DsSettings;

            var dsClient = DSServiceClientFactory.GetDsClient(creds);

            using (var scope = new System.ServiceModel.OperationContextScope(dsClient.InnerChannel))
            {
                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = DSServiceClientFactory.GetAuthHeaderRequestProperty(creds);

                var documentsPDFs = dsClient.RequestDocumentPDFs(envelopeId);

                if (documentsPDFs == null || documentsPDFs.DocumentPDF == null || documentsPDFs.DocumentPDF.Length == 0)
                {
                    return(null);
                }

                return(new FileData(string.Format("{0}.pdf", documentsPDFs.DocumentPDF[0].Name), documentsPDFs.DocumentPDF[0].PDFBytes));
            }
        }
コード例 #37
0
 private void PopContext()
 {
     if (this.thread != Thread.CurrentThread)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxInvalidContextScopeThread0")));
     }
     if (currentScope != this)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxInterleavedContextScopes0")));
     }
     if (OperationContext.Current != this.currentContext)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxContextModifiedInsideScope0")));
     }
     currentScope             = this.originalScope;
     OperationContext.Current = this.originalContext;
     if (this.currentContext != null)
     {
         this.currentContext.SetClientReply(null, false);
     }
 }
コード例 #38
0
 private void PushContext(OperationContext context)
 {
     _currentContext = context;
     OperationContextScope.s_currentScope = this;
     OperationContext.Current             = _currentContext;
 }
コード例 #39
0
 private void PushContext(OperationContext context)
 {
     this.currentContext      = context;
     currentScope             = this;
     OperationContext.Current = this.currentContext;
 }
コード例 #40
0
    public void fillFieldData()
    {
        String userName      = ConfigurationManager.AppSettings["API.Email"];
        String password      = ConfigurationManager.AppSettings["API.Password"];
        String integratorKey = ConfigurationManager.AppSettings["API.IntegratorKey"];

        String auth = "<DocuSignCredentials><Username>" + userName
                      + "</Username><Password>" + password
                      + "</Password><IntegratorKey>" + integratorKey
                      + "</IntegratorKey></DocuSignCredentials>";

        try
        {
            ServiceReference1.DSAPIServiceSoapClient svc = new ServiceReference1.DSAPIServiceSoapClient();
            using (OperationContextScope scope = new System.ServiceModel.OperationContextScope(svc.InnerChannel))
            {
                HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
                httpRequestProperty.Headers.Add("X-DocuSign-Authentication", auth);
                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;

                if (Request.QueryString.Count > 0)
                {
                    if (!Request.QueryString["envelopeID"].Equals(""))
                    {
                        String      envelope       = Request.QueryString["envelopeID"];
                        String      connectMessage = GetEnvelopeData(envelope);
                        XmlDocument doc            = new XmlDocument();
                        doc.LoadXml(connectMessage);

                        // Create an XmlNamespaceManager to resolve the default namespace.
                        XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
                        nsmgr.AddNamespace("ds", "http://www.docusign.net/API/3.0");

                        // Get the status of the envelope
                        XmlElement root = doc.DocumentElement;

                        // Get all the form data
                        XmlNodeList documentFields = root.SelectNodes("descendant::ds:EnvelopeStatus/ds:DocumentStatuses/ds:DocumentStatus/ds:DocumentFields", nsmgr);
                        XmlNode     documentFieldName;
                        XmlNode     documentFieldValue;

                        foreach (XmlNode documentField in documentFields)
                        {
                            documentFieldName  = documentField.SelectSingleNode("descendant::ds:Name", nsmgr);
                            documentFieldValue = documentField.SelectSingleNode("descendant::ds:Value", nsmgr);
                            Response.Write("<tr>");
                            Response.Write("<td>");
                            if (documentFieldName != null)
                            {
                                Response.Write(documentFieldName.InnerText);
                            }
                            Response.Write("</td>");
                            Response.Write("<td>");
                            if (documentFieldValue != null)
                            {
                                Response.Write(documentFieldValue.InnerText);
                            }
                            Response.Write("</td>");
                            Response.Write("</tr>");
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            // Log4Net Piece
            log4net.ILog logger = log4net.LogManager.GetLogger(typeof(finance_ViewFormData));
            logger.Info("\n----------------------------------------\n");
            logger.Error(ex.Message);
            logger.Error(ex.StackTrace);
            Response.Write(ex.Message);
        }
        finally
        {
        }
    }
コード例 #41
0
        public static void AuthCopyFlow(string envelopeId)
        {
            //Configure these variables for your environment
            string userName      = "";
            string password      = "";
            string integratorKey = "";
            string accountId     = ""; //Use a GUID example db7f5b2a-xxxx-xxxx-xxxx-a815685a63eb


            //OAuth is not yet supported by DocuSign SOAP API
            //Authentication can be either WS-Security UsernameToken or Legacy custom header authentication,
            //although some development stacks may not provide adequate support for WS-Security standards.

            String auth = "<DocuSignCredentials><Username>" + userName
                          + "</Username><Password>" + password
                          + "</Password><IntegratorKey>" + integratorKey
                          + "</IntegratorKey></DocuSignCredentials>";

            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

            DSAPIServiceSoapClient client = new DSAPIServiceSoapClient();


            using (OperationContextScope scope = new System.ServiceModel.OperationContextScope(client.InnerChannel))
            {
                HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
                httpRequestProperty.Headers.Add("X-DocuSign-Authentication", auth);
                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;


                if (envelopeId.Trim().Length != 36)
                {
                    Console.WriteLine("Error: EnvelopeId should be 36 characters. Current is " + envelopeId.Trim().Length.ToString());
                    Console.ReadLine();
                    return;
                }

                try
                {
                    AuthoritativeCopyExportDocuments docs = client.ExportAuthoritativeCopy(envelopeId);

                    //Concatenate the byte arrays of the returned encrypted documents
                    var           s = new MemoryStream();
                    List <string> encryptedFiles = new List <string>();

                    for (int i = 0; i < docs.Count; i++)
                    {
                        byte[] docPDF = docs.DocumentPDF[i].PDFBytes;
                        s.Write(docPDF, 0, docPDF.Length);

                        //write encrypted file to use later
                        encryptedFiles.Add(@"c:\temp\authcopy\Testdoc.dat" + i.ToString());
                        File.WriteAllBytes(@"c:\temp\authcopy\Testdoc.dat" + i.ToString(), docPDF);
                    }

                    //Write the concatenated memory stream to the concatenatedByteArray
                    var concatenatedByteArray = s.ToArray();
                    int size = concatenatedByteArray.Length;

                    //Create a new fixed byte array required to hash
                    byte[] data = new byte[size];
                    data = concatenatedByteArray;

                    System.Security.Cryptography.SHA1 sha = new SHA1CryptoServiceProvider();

                    byte[] computedHash;
                    computedHash = sha.ComputeHash(data);

                    AuthoritativeCopyExportStatus status = client.AcknowledgeAuthoritativeCopyExport(envelopeId.Trim(), docs.TransactionId, computedHash);
                    string key = status.ExportKey;

                    Console.WriteLine("Status = " + status.AuthoritativeCopyExportSuccess + "Key = " + key);

                    // loop writing decrypted docs to files
                    for (int i = 0; i < docs.Count; i++)
                    {
                        //Create an empty target file
                        string decryptedFilename = @"c:\temp\authcopy\" + docs.DocumentPDF[i].Name;

                        if (decryptedFilename == @"c:\temp\authcopy\Summary")
                        {
                            decryptedFilename = @"c:\temp\authcopy\Summary.pdf";
                        }

                        File.Create(decryptedFilename).Dispose();

                        //Decrypte the file using the key that was returned from AcknowledgeAuthoritativeCopyExport()
                        try
                        {
                            Decrypt(status.ExportKey, encryptedFiles[i], decryptedFilename);
                            Console.WriteLine("Success: new file " + decryptedFilename);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Decrypt and file write failed.");
                            Console.WriteLine(ex.Message);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            Console.ReadLine();
        }
コード例 #42
0
    protected void createEnvelope()
    {
        FileStream fs = null;

        try
        {
            String userName      = ConfigurationManager.AppSettings["API.Email"];
            String password      = ConfigurationManager.AppSettings["API.Password"];
            String integratorKey = ConfigurationManager.AppSettings["API.IntegratorKey"];


            String auth = "<DocuSignCredentials><Username>" + userName
                          + "</Username><Password>" + password
                          + "</Password><IntegratorKey>" + integratorKey
                          + "</IntegratorKey></DocuSignCredentials>";
            ServiceReference1.DSAPIServiceSoapClient client = new ServiceReference1.DSAPIServiceSoapClient();

            using (OperationContextScope scope = new System.ServiceModel.OperationContextScope(client.InnerChannel))
            {
                HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
                httpRequestProperty.Headers.Add("X-DocuSign-Authentication", auth);
                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;

                CompositeTemplate template = new CompositeTemplate();

                // Set up recipients
                Recipient[] recipients;
                if (jointEmail.Value.Trim().Equals(""))
                {
                    recipients = new Recipient[1];
                }
                else
                {
                    recipients = new Recipient[2];
                }

                recipients[0]             = new Recipient();
                recipients[0].ID          = "1";
                recipients[0].Email       = email.Value;
                recipients[0].Type        = RecipientTypeCode.Signer;
                recipients[0].UserName    = firstname.Value + " " + lastname.Value;
                recipients[0].CaptiveInfo = new RecipientCaptiveInfo();

                recipients[0].CaptiveInfo.ClientUserId = RandomizeClientUserID();
                recipients[0].RoutingOrder             = 1;
                recipients[0].RoleName = "Signer1";

                // If there is a 2nd recipient, configure
                if (!jointEmail.Value.Equals(""))
                {
                    recipients[1]              = new Recipient();
                    recipients[1].ID           = "2";
                    recipients[1].Email        = jointEmail.Value;
                    recipients[1].Type         = RecipientTypeCode.Signer;
                    recipients[1].UserName     = jointFirstname.Value + " " + jointLastname.Value;
                    recipients[1].RoleName     = "Signer2";
                    recipients[1].RoutingOrder = 1;
                }

                //Configure the inline templates
                InlineTemplate inlineTemplate = new InlineTemplate();
                inlineTemplate.Sequence            = "2";
                inlineTemplate.Envelope            = new Envelope();
                inlineTemplate.Envelope.Recipients = recipients;
                inlineTemplate.Envelope.AccountId  = ConfigurationManager.AppSettings["API.TemplatesAccountId"];

                template.InlineTemplates = new InlineTemplate[] { inlineTemplate };
                // Configure the document
                template.Document      = new Document();
                template.Document.ID   = "1";
                template.Document.Name = "Sample Document";

                BinaryReader binReader = null;
                String       filename  = uploadFile.Value;
                if (File.Exists(Server.MapPath("~/App_Data/" + filename)))
                {
                    fs        = new FileStream(Server.MapPath("~/App_Data/" + filename), FileMode.Open);
                    binReader = new BinaryReader(fs);
                }
                byte[] PDF = binReader.ReadBytes(System.Convert.ToInt32(fs.Length));
                template.Document.PDFBytes = PDF;

                template.Document.TransformPdfFields = true;
                template.Document.FileExtension      = "pdf";

                ServerTemplate serverTemplate = new ServerTemplate();

                serverTemplate.Sequence   = "1";
                serverTemplate.TemplateID = templatesList.SelectedValue;
                template.ServerTemplates  = new ServerTemplate[] { serverTemplate };

                // Set up the envelope
                EnvelopeInformation envInfo = new EnvelopeInformation();
                envInfo.AutoNavigation = true;
                envInfo.AccountId      = ConfigurationManager.AppSettings["API.AccountId"];
                envInfo.Subject        = "Templates Example";

                //Create envelope with all the composite template information
                EnvelopeStatus status = client.CreateEnvelopeFromTemplatesAndForms(envInfo, new CompositeTemplate[] { template }, true);
                RequestRecipientTokenAuthenticationAssertion assert = new RequestRecipientTokenAuthenticationAssertion();
                assert.AssertionID           = "12345";
                assert.AuthenticationInstant = DateTime.Now;
                assert.AuthenticationMethod  = RequestRecipientTokenAuthenticationAssertionAuthenticationMethod.Password;
                assert.SecurityDomain        = "www.magicparadigm.com";

                RequestRecipientTokenClientURLs clientURLs = new RequestRecipientTokenClientURLs();

                clientURLs.OnAccessCodeFailed = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnAccessCodeFailed";
                clientURLs.OnCancel           = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnCancel";
                clientURLs.OnDecline          = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnDecline";
                clientURLs.OnException        = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnException";
                clientURLs.OnFaxPending       = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnFaxPending";
                clientURLs.OnIdCheckFailed    = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnIdCheckFailed";
                clientURLs.OnSessionTimeout   = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnSessionTimeout";
                clientURLs.OnTTLExpired       = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnTTLExpired";
                clientURLs.OnViewingComplete  = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnViewingComplete";


                String url = Request.Url.AbsoluteUri;

                String recipientToken;

                clientURLs.OnSigningComplete = url.Substring(0, url.LastIndexOf("/")) + "/EmbeddedSigningComplete0.aspx?envelopeID=" + status.EnvelopeID;
                recipientToken        = client.RequestRecipientToken(status.EnvelopeID, recipients[0].CaptiveInfo.ClientUserId, recipients[0].UserName, recipients[0].Email, assert, clientURLs);
                Session["envelopeID"] = status.EnvelopeID;
                if (!Request.Browser.Browser.Equals("InternetExplorer") && (!Request.Browser.Browser.Equals("Safari")))
                {
                    docusignFrame.Visible = true;
                    docusignFrame.Src     = recipientToken;
                }
                else // Handle IE differently since it does not allow dynamic setting of the iFrame width and height
                {
                    docusignFrameIE.Visible = true;
                    docusignFrameIE.Src     = recipientToken;
                }
            }
        }
        catch (Exception ex)
        {
            // Log4Net Piece
            log4net.ILog logger = log4net.LogManager.GetLogger(typeof(_Default));
            logger.Info("\n----------------------------------------\n");
            logger.Error(ex.Message);
            logger.Error(ex.StackTrace);
            Response.Write(ex.Message);
        }
        finally
        {
            if (fs != null)
            {
                fs.Close();
            }
        }
    }
コード例 #43
0
        public ResultData Run(StepStartData data)
        {
            IDocusignCreds creds;

            if (data.Data.ContainsKey(INPUT_CREDS) && data.Data[INPUT_CREDS] != null)
            {
                creds = data.Data[INPUT_CREDS] as IDocusignCreds;
            }
            else
            {
                creds = DSServiceClientFactory.DsSettings;
            }

            var dsClient = DSServiceClientFactory.GetDsClient(creds);

            var document   = (FileData[])data.Data[INPUT_DOCUMENT];
            var recipients = (RecipientTabMapping[])data.Data[INPUT_RECIPIENTS];
            var subject    = (string)data.Data[INPUT_SUBJECT];
            var emailBlurb = (string)data.Data[INPUT_EMAILBLURB];

            Dictionary <string, object> resultData = new Dictionary <string, object>();

            try
            {
                using (var scope = new System.ServiceModel.OperationContextScope(dsClient.InnerChannel))
                {
                    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = DSServiceClientFactory.GetAuthHeaderRequestProperty(creds);

                    var dsRecipients   = new List <Recipient>();
                    var tabs           = new List <Tab>();
                    var recipientsList = recipients.ToList();

                    List <Document> documents = new List <Document>();
                    foreach (FileData doc in document)
                    {
                        documents.Add(new Document
                        {
                            PDFBytes = doc.Contents,
                            ID       = new Guid().ToString(),
                            Name     = doc.FileName
                        });
                    }

                    //each recipient has a list of tabs; this is represented by the RecipientTabMapping type
                    var recipientIndex = 1; //RecipientID must be a non-negative integer; using the index of each Recipient in the list for simplicity
                    foreach (var rtm in recipientsList)
                    {
                        dsRecipients.Add(new Recipient
                        {
                            Email                 = rtm.EmailAddress,
                            UserName              = rtm.EmailAddress,
                            Type                  = RecipientTypeCode.Signer,
                            RoutingOrder          = (ushort)rtm.RoutingOrder,
                            RoutingOrderSpecified = rtm.RoutingOrder > 0,
                            ID         = recipientIndex.ToString(),
                            SignerName = rtm.SignerNameField
                        });

                        //add a Tab to the list for each of the RTM's simplified tab objects, setting the RecipientID and DocumentID to match current recipient and document
                        //first do absolutely positioned tabs (normal Tab)
                        if (rtm.AbsolutePositionTabs != null)
                        {
                            foreach (var apt in rtm.AbsolutePositionTabs)
                            {
                                tabs.Add(new Tab
                                {
                                    PageNumber  = apt.PageNumber.ToString(),
                                    XPosition   = apt.XPosition.ToString(),
                                    YPosition   = apt.YPosition.ToString(),
                                    Type        = apt.TabType,
                                    RecipientID = recipientIndex.ToString(),
                                    Name        = apt.TabType == TabTypeCode.SignHere ? rtm.SignerNameField : rtm.UserNameField,
                                    DocumentID  = "1"
                                });
                            }
                        }
                        ;
                        //then do AnchorTabs
                        if (rtm.AnchorStringTabs != null)
                        {
                            foreach (var ast in rtm.AnchorStringTabs)
                            {
                                tabs.Add(new Tab
                                {
                                    PageNumber    = ast.PageNumber.ToString(),
                                    AnchorTabItem = new AnchorTab {
                                        AnchorTabString = ast.AnchorTabString, XOffset = ast.XOffset, YOffset = ast.YOffset
                                    },
                                    Type        = ast.TabType,
                                    RecipientID = recipientIndex.ToString(),
                                    DocumentID  = "1"
                                });
                            }
                        }
                        ;
                        recipientIndex++;
                    }
                    ;

                    //construct the envelope and send; return EnvelopeID
                    var envelopeID = dsClient.CreateAndSendEnvelope(new Envelope
                    {
                        Subject    = subject,
                        EmailBlurb = emailBlurb,
                        Recipients = dsRecipients.ToArray <Recipient>(),
                        AccountId  = creds.AccountId,
                        Documents  = documents.ToArray(),
                        Tabs       = tabs.ToArray()
                    }).EnvelopeID;


                    resultData.Add(OUTPUT_ENVELOPEID, envelopeID);
                    return(new ResultData(OUTCOME_SENT, resultData));
                }
            }
            catch (Exception ex)
            {
                resultData.Add(OUTPUT_ERRORMESSAGE, ex.Message);
                return(new ResultData(OUTCOME_ERROR, resultData));
            }
        }