Пример #1
0
        public DocumentDesc GetDocumentDesc(string guidRequest)
        {
            LOG_TRACE($"GetDocumentDesc({guidRequest})");
            if (_client != null && !string.IsNullOrEmpty(guidRequest))
            {
                DocumentDesc docDesc;
                try
                {
                    using (OperationContextScope scope = new OperationContextScope(_client.InnerChannel))
                    {
                        HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
                        httpRequestProperty.Headers[System.Net.HttpRequestHeader.Authorization] = "Basic " +
                                                                                                  Convert.ToBase64String(Encoding.ASCII.GetBytes(_client.ClientCredentials.UserName.UserName + ":" + _client.ClientCredentials.UserName.Password));
                        OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
                        docDesc = _client.GetDocumentDesc(guidRequest);
                    }

                    return(docDesc);
                }
                catch (CommunicationException)
                {
                    LOG_TRACE($"Первый вызов не вернул результата, ожидаем 10сек и повторяем.");
                    Thread.Sleep(10 * 1000);
                    try
                    {
                        using (OperationContextScope scope = new OperationContextScope(_client.InnerChannel))
                        {
                            HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
                            httpRequestProperty.Headers[System.Net.HttpRequestHeader.Authorization] = "Basic " +
                                                                                                      Convert.ToBase64String(Encoding.ASCII.GetBytes(_client.ClientCredentials.UserName.UserName + ":" + _client.ClientCredentials.UserName.Password));
                            OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
                            docDesc = _client.GetDocumentDesc(guidRequest);
                        }

                        return(docDesc);
                    }
                    catch (CommunicationException)
                    {
                        LOG_ERROR($"Запрос документа {guidRequest} не вернул результата в течении 20 секунд.");
                        return(null);
                    }
                }
            }
            return(null);
        }
Пример #2
0
        public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
        {
            byte[] body;
            Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
            using (MemoryStream ms = new MemoryStream())
            {
                using (StreamWriter sw = new StreamWriter(ms, Encoding.UTF8))
                {
                    using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw))
                    {
                        writer.Formatting = Newtonsoft.Json.Formatting.Indented;
                        if (parameters.Length == 1)
                        {
                            // Single parameter, assuming bare
                            serializer.Serialize(sw, parameters[0]);
                        }
                        else
                        {
                            writer.WriteStartObject();
                            for (int i = 0; i < this.operation.Messages[0].Body.Parts.Count; i++)
                            {
                                writer.WritePropertyName(this.operation.Messages[0].Body.Parts[i].Name);
                                serializer.Serialize(writer, parameters[i]);
                            }

                            writer.WriteEndObject();
                        }

                        writer.Flush();
                        sw.Flush();
                        body = ms.ToArray();
                    }
                }
            }

            Message requestMessage = Message.CreateMessage(messageVersion, operation.Messages[0].Action, new RawBodyWriter(body));

            requestMessage.Headers.To = operationUri;
            requestMessage.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Raw));
            HttpRequestMessageProperty reqProp = new HttpRequestMessageProperty();

            reqProp.Headers[HttpRequestHeader.ContentType] = "application/json";
            requestMessage.Properties.Add(HttpRequestMessageProperty.Name, reqProp);
            return(requestMessage);
        }
        /// <summary>
        /// before the send request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="channel">The channel.</param>
        /// <returns>the mini profiler start</returns>
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            // If we currently are running inside a MiniProfiler context, then add a request onto this request
            var miniProfiler = GetCurrentProfiler();

            if (miniProfiler != null)
            {
                var header = new MiniProfilerRequestHeader
                {
                    User             = miniProfiler.User,
                    ParentProfilerId = miniProfiler.Id
                };

                // ReSharper disable PossibleUnintendedReferenceComparison
                if (request.Headers.MessageVersion != MessageVersion.None)
                // ReSharper restore PossibleUnintendedReferenceComparison
                {
                    var untypedHeader = new MessageHeader <MiniProfilerRequestHeader>(header)
                                        .GetUntypedHeader(MiniProfilerRequestHeader.HeaderName, MiniProfilerRequestHeader.HeaderNamespace);
                    request.Headers.Add(untypedHeader);
                }
                else if (_http || WebOperationContext.Current != null || channel.Via.Scheme == "http" | channel.Via.Scheme == "https")
                {
                    _http = true;

                    if (!request.Properties.ContainsKey(HttpRequestMessageProperty.Name))
                    {
                        request.Properties.Add(HttpRequestMessageProperty.Name, new HttpRequestMessageProperty());
                    }
                    HttpRequestMessageProperty property = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];

                    property.Headers.Add(MiniProfilerRequestHeader.HeaderName, header.ToHeaderText());
                }
                else
                {
                    throw new InvalidOperationException("MVC Mini Profiler does not support EnvelopeNone unless HTTP is the transport mechanism");
                }

                return(new MiniProfilerStart {
                    StartTime = miniProfiler.DurationMilliseconds
                });
            }

            return(null);
        }
Пример #4
0
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            Dictionary <string, string> dic = null;
            var handler = ServiceFactory.ContextSetting;

            if (handler != null)
            {
                dic = handler();
            }
            if (dic == null)
            {
                return(null);
            }
            Dictionary <string, string> .Enumerator iterator = dic.GetEnumerator();
            HttpRequestMessageProperty hrmp = null;

            if (m_IsWebHttpBinding)
            {
                hrmp = request.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
                if (hrmp == null)
                {
                    hrmp = new HttpRequestMessageProperty();
                    request.Properties.Add(HttpRequestMessageProperty.Name, hrmp);
                }
            }
            while (iterator.MoveNext())
            {
                string val = iterator.Current.Value;
                if (val == null)
                {
                    continue;
                }
                val = HeaderContextHelper.EncryptAndSign(val);
                if (m_IsWebHttpBinding)
                {
                    hrmp.Headers.Add(HeaderContextHelper.BuildKey(iterator.Current.Key), val);
                }
                else
                {
                    MessageHeader clientHeader = MessageHeader.CreateHeader(HeaderContextHelper.BuildKey(iterator.Current.Key), string.Empty, val);
                    request.Headers.Add(clientHeader);
                }
            }
            return(null);
        }
Пример #5
0
        protected virtual HttpRequestMessageProperty GetHttpHeaders(Ambiente ambiente)
        {
            var property = new HttpRequestMessageProperty();

            property.Headers.Add("customerid", ambiente.customerid);
            property.Headers.Add("smuser", ambiente.smuser);
            property.Headers.Add("costcenter", ambiente.costcenter);
            property.Headers.Add("billingcenter", ambiente.billingcenter);
            property.Headers.Add("idsender", ambiente.idsender);
            property.Headers.Add("contracttype", ambiente.contracttype);
            property.Headers.Add("sendersystem", ambiente.sendersystem);
            property.Headers.Add("contractid", ambiente.contractid);
            property.Headers.Add("customer", ambiente.customer);
            property.Headers.Add("usertype", ambiente.usertype);


            return(property);
        }
Пример #6
0
        private async Task <getCrossRatesResponse> CallSweaForCrossRate(string fromCurrency, string toCurrency, DateTime conversionDate)
        {
            var sweaWsClient = new SweaWebServicePortTypeClient();
            var parameters   = CrossRateConversionRequestHelper.GetParameters(fromCurrency, toCurrency, conversionDate);

            using (var scope = new FlowingOperationContextScope(sweaWsClient.InnerChannel))
            {
                var request = new HttpRequestMessageProperty();
                request.Headers.Add("Accept-Encoding", "gzip,deflate");

                // this is crucial, without action="urn:[methodName]" the call to Swea WS will result in 404 error.
                request.Headers.Add("Content-Type", @"application/soap+xml;charset=UTF-8;action=""urn:getCrossRates""");

                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = request;

                return(await sweaWsClient.getCrossRatesAsync(parameters).ContinueOnScope(scope));
            }
        }
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            HttpRequestMessageProperty messageProperty;

            if (request.Properties.ContainsKey("httpRequest"))
            {
                messageProperty = (HttpRequestMessageProperty)request.Properties["httpRequest"];
            }
            else
            {
                messageProperty = new HttpRequestMessageProperty();
                request.Properties.Add(HttpRequestMessageProperty.Name, messageProperty);
            }
            var encoded = Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(_userName + ":" + _password));

            messageProperty.Headers.Add("Authorization", "Basic " + encoded);
            return(request);
        }
Пример #8
0
        public object BeforeSendRequest(ref Message request, System.ServiceModel.IClientChannel channel)
        {
            object obj;

            if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out obj))
            {
                var httpRequestMsg = obj as HttpRequestMessageProperty;
                SetRequestCookies(channel, httpRequestMsg);
            }
            else
            {
                var httpRequestMsg = new HttpRequestMessageProperty();
                SetRequestCookies(channel, httpRequestMsg);
                request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMsg);
            }

            return(channel.RemoteAddress.Uri);
        }
Пример #9
0
                public object BeforeSendRequest(ref Message request, IClientChannel channel)
                {
                    HttpRequestMessageProperty httpRequestMessage;
                    object httpRequestMessageObject;

                    if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject))
                    {
                        httpRequestMessage = (HttpRequestMessageProperty)httpRequestMessageObject;
                        httpRequestMessage.Headers[AuthorizationHttpHeader] = _authorizationHeaderValue;
                    }
                    else
                    {
                        httpRequestMessage = new HttpRequestMessageProperty();
                        httpRequestMessage.Headers.Add(AuthorizationHttpHeader, _authorizationHeaderValue);
                        request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
                    }
                    return(null);
                }
Пример #10
0
        public static UslugaBIRzewnPublClient ConBIR() //Metoda Logująca się do GUSu i ustawiająca sid jako header komunikatów
        {
            GusKey                  apiKey    = new GusKey();
            WSHttpBinding           myBinding = Binding();
            EndpointAddress         ea        = new EndpointAddress("https://wyszukiwarkaregontest.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc");
            UslugaBIRzewnPublClient cc        = new UslugaBIRzewnPublClient(myBinding, ea);

            cc.Open();
            string sid = cc.Zaloguj(apiKey.Key);

            Console.WriteLine("Zaloguj " + sid);
            OperationContextScope      scope    = new OperationContextScope(cc.InnerChannel);
            HttpRequestMessageProperty reqProps = new HttpRequestMessageProperty();

            reqProps.Headers.Add("sid", sid);
            OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = reqProps;
            return(cc);
        }
Пример #11
0
        private void PostRequest(string sessionId, string xml, StringBuilder result)
        {
            SMEServiceReferenceFDI.FDISoapClient client = new SMEServiceReferenceFDI.FDISoapClient();
            using (new OperationContextScope(client.InnerChannel))
            {
                // Embeds the extracted cookie in the next web service request
                // Note that we manually have to create the request object since
                // since it doesn't exist yet at this stage
                HttpRequestMessageProperty request = new HttpRequestMessageProperty();
                request.Headers["Cookie"] = "ASP.NET_SessionId=" + sessionId.Trim();
                OperationContext.Current.OutgoingMessageProperties[
                    HttpRequestMessageProperty.Name] = request;

                SMEServiceReferenceFDI.FdiResult rsp = client.FdiIrT(xml.Trim());
                //result = rsp.Result;
                result.Append(rsp.Result);
            }
        }
Пример #12
0
        public string AddAttachments(int oid, string guid, FileInfo file)
        {
            if (_client != null && file != null && file.Exists)
            {
                var    bytes     = File.ReadAllBytes(file.FullName);
                string base64str = Convert.ToBase64String(bytes);

                using (OperationContextScope scope = new OperationContextScope(_client.InnerChannel))
                {
                    HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
                    httpRequestProperty.Headers[System.Net.HttpRequestHeader.Authorization] = "Basic " +
                                                                                              Convert.ToBase64String(Encoding.ASCII.GetBytes(_client.ClientCredentials.UserName.UserName + ":" + _client.ClientCredentials.UserName.Password));
                    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
                    return(_client.AddAttachment(oid, guid, file.Name, base64str, 0, 0, 0, 0, 0));
                }
            }
            return(null);
        }
Пример #13
0
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            HttpRequestMessageProperty httpRequestMessage;
            object httpRequestMessageObject;

            if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject))
            {
                httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;
                httpRequestMessage.Headers[HttpRequestHeader.Authorization] = FileServerProviderSettings.Instance.AccountName + "/" + FileServerProviderSettings.Instance.AccountKey;
            }
            else
            {
                httpRequestMessage = new HttpRequestMessageProperty();
                request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
            }
            httpRequestMessage.Headers[HttpRequestHeader.Authorization] = FileServerProviderSettings.Instance.AccountName + "/" + FileServerProviderSettings.Instance.AccountKey;
            return(null);
        }
        private string GetRequestMessageTextWithHeaders(System.ServiceModel.Channels.Message request)
        {
            string message = string.Empty;

            HttpRequestMessageProperty httpRequest = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];

            message = httpRequest.Method + " " + request.Headers.To.PathAndQuery + " HTTP/1.1" + Environment.NewLine;

            foreach (var header in httpRequest.Headers)
            {
                message += header.ToString() + ": " + httpRequest.Headers.Get(header.ToString()) + Environment.NewLine;
            }

            message += Environment.NewLine;
            message += request.ToString();

            return(message);
        }
Пример #15
0
 public DocListItem[] GetSearchList(string id, object order, int part, string searchName, string kdocfield)
 {
     LOG_TRACE($"GetSearchList(id:{id}, order:{order}, part:{part}, searchName:{searchName}, kdocfield:{kdocfield})");
     if (_searchClient != null)
     {
         ArrayOfDocListItem docListItems;
         using (OperationContextScope scope = new OperationContextScope(_searchClient.InnerChannel))
         {
             HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
             httpRequestProperty.Headers[System.Net.HttpRequestHeader.Authorization] = "Basic " +
                                                                                       Convert.ToBase64String(Encoding.ASCII.GetBytes(_searchClient.ClientCredentials.UserName.UserName + ":" + _searchClient.ClientCredentials.UserName.Password));
             OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
             docListItems = _searchClient.GetSearchList(id, order, part, searchName, kdocfield);
         }
         return(docListItems.ToArray());
     }
     return(null);
 }
Пример #16
0
        protected HttpRequestMessageProperty GetHttpHeaders(Ambiente ambiente, string prodotto = "MOL")
        {
            var    property   = new HttpRequestMessageProperty();
            string customerId = prodotto.Equals("MOL") ? ambiente.customeridMOL : ambiente.customeridCOL;
            string smUser     = prodotto.Equals("MOL") ? ambiente.smuserMOL : ambiente.smuserCOL;

            property.Headers.Add("customerid", customerId);
            property.Headers.Add("smuser", smUser);
            property.Headers.Add("costcenter", ambiente.costcenter);
            property.Headers.Add("billingcenter", ambiente.billingcenter);
            property.Headers.Add("idsender", ambiente.idsender);
            property.Headers.Add("contracttype", ambiente.contracttype);
            property.Headers.Add("sendersystem", ambiente.sendersystem);
            property.Headers.Add("contractid", ambiente.contractid);
            property.Headers.Add("customer", ambiente.customer);
            property.Headers.Add("usertype", ambiente.usertype);
            return(property);
        }
    public static void BasicAuthenticationInvalidPwd_throw_MessageSecurityException()
    {
        StringBuilder errorBuilder = new StringBuilder();
        // Will need to use localized string once it is available
        // On Native retail, the message is stripped to 'HttpAuthorizationForbidden, Basic'
        // On Debug or .Net Core, the entire message is "The HTTP request was forbidden with client authentication scheme 'Basic'."
        // Thus we will only check message contains "forbidden"
        string message = "forbidden";

        MessageSecurityException exception = Assert.Throws <MessageSecurityException>(() =>
        {
            BasicHttpBinding basicHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
            basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;

            ChannelFactory <IWcfCustomUserNameService> factory = new ChannelFactory <IWcfCustomUserNameService>(basicHttpBinding, new EndpointAddress(Endpoints.Https_BasicAuth_Address));
            string username = Guid.NewGuid().ToString("n").Substring(0, 8);
            string password = Guid.NewGuid().ToString("n").Substring(0, 16);
            factory.Credentials.UserName.UserName = username;
            factory.Credentials.UserName.Password = password + "Invalid";

            IWcfCustomUserNameService serviceProxy = factory.CreateChannel();

            string testString = "I am a test";
            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[BasicUsernameHeaderName] = username;
                requestMessageProperty.Headers[BasicPasswordHeaderName] = password;
                string result = serviceProxy.Echo(testString);
            }
        });

        Assert.True(exception.Message.ToLower().Contains(message), string.Format("Expected exception message to contain: '{0}', actual message is: '{1}'", message, exception.Message));
    }
Пример #18
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
        {
        }
    }
Пример #19
0
        public static string SignIn(string user, string password)
        {
            string loginResponse = "failed";

            byte[] bytes  = System.Text.ASCIIEncoding.ASCII.GetBytes("senpa:senpa");
            string base64 = Convert.ToBase64String(bytes, Base64FormattingOptions.None);

            authorizationKey = "Basic " + base64;

            senpaSecurity.SEnPASecurityClient security = new senpaSecurity.SEnPASecurityClient();
            var httpRequestPropertySecurity            = new HttpRequestMessageProperty();

            httpRequestPropertySecurity.Headers[HttpRequestHeader.Authorization] = authorizationKey;

            var contextSecurity = new OperationContext(security.InnerChannel);

            using (new OperationContextScope(contextSecurity))
            {
                try
                {
                    contextSecurity.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestPropertySecurity;
                    senpaSecurity.AuthenticationResponse response = security.Authenticate(user, password);
                    if (response.authenticationStatus)
                    {
                        accessToken        = response.accessToken;
                        Globals.userLogged = response.username;


                        loginResponse = "successful";
                    }
                    else
                    {
                        //XtraMessageBox.Show(response.responseMessage, "Login failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        loginResponse = "failed";
                    }
                }
                catch (Exception ex)
                {
                    loginResponse = "error";
                }
            }

            return(loginResponse);
        }
        object IDispatchMessageInspector.AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            //return null;
            this.ResetFields();

            Uri requestUri = request.Headers.To;

            if (this.logRequest)
            {
                this.requestTime = DateTime.UtcNow;

                try
                {
                    using (StringWriter sw = new StringWriter())
                    {
                        HttpRequestMessageProperty httpReq = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];

                        //sw.WriteLine("{0} {1}", httpReq.Method, requestUri);
                        //foreach (var header in httpReq.Headers.AllKeys)
                        //{
                        //    sw.WriteLine("{0}: {1}", header, httpReq.Headers[header]);
                        //}
                        //sw.WriteLine("{0}", requestUri.PathAndQuery);
                        this.webMethodName = requestUri.PathAndQuery;
                        if (!request.IsEmpty)
                        {
                            //sw.WriteLine();
                            sw.WriteLine(this.MessageToString(ref request, true));
                        }

                        var s = sw.ToString();
                        this.strRequest = s;

                        System.Diagnostics.Debug.WriteLine("-------AfterReceiveRequest - Message Body: " + s);
                    }
                }
                catch (Exception ex)
                {
                    this.LogError(ex);
                }
                //InspectMessageBody(ref request, true);
            }
            return(requestUri);
        }
Пример #21
0
        public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
        {
            T             data            = null;
            string        body            = string.Empty;
            XmlSerializer serializer      = new XmlSerializer(typeof(T));
            Message       originalMessage = originalFormatter.SerializeRequest(messageVersion, parameters);

            foreach (object parameter in parameters)
            {
                if (parameter is T)
                {
                    data = parameter as T;
                    break;
                }
            }

            if (data == null)
            {
                return(originalMessage);
            }

            using (StringWriter bodyWriter = new StringWriter())
            {
                serializer.Serialize(bodyWriter, data);
                body = bodyWriter.ToString();
            }

            body = new XDocument(
                new XElement(XName.Get("entry", ServiceBusConstants.AtomNamespaceName),
                             new XElement(XName.Get("content", ServiceBusConstants.AtomNamespaceName),
                                          new XAttribute("type", "application/xml"),
                                          XDocument.Parse(body).Root))).ToString();
            Message finalMessage = Message.CreateMessage(messageVersion, null, new CustomBodyWriter(body));

            finalMessage.Headers.CopyHeadersFrom(originalMessage);
            finalMessage.Properties.CopyProperties(originalMessage.Properties);
            HttpRequestMessageProperty property = finalMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;

            property.Headers.Add("content-type", "application/xml");
            property.Headers.Add("type", "entry");
            property.Headers.Add("charset", "utf-8");

            return(finalMessage);
        }
Пример #22
0
        public DataSet LerVisao(string userName, string password, string dataServer, string filter, string context)
        {
            var ret = new DataSet();

            wsDataServer.IwsDataServerClient servico = new wsDataServer.IwsDataServerClient();

            servico.ClientCredentials.UserName.UserName = userName.ToString();
            servico.ClientCredentials.UserName.Password = password.ToString();

            string retorno = string.Empty;

            try
            {
                using (new OperationContextScope(servico.InnerChannel))
                {
                    string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(servico.ClientCredentials.UserName.UserName + ":" + servico.ClientCredentials.UserName.Password));
                    HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty();
                    requestMessage.Headers["Authorization"] = auth;
                    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage;
                    retorno = servico.ReadView(dataServer, filter, context);
                }

                XmlTextReader xtr = new XmlTextReader(new System.IO.StringReader(retorno));

                //ret = retorno.Substring(0, retorno.LastIndexOf("</GUSUARIO>"));

                ret.ReadXml(xtr);
            }
            catch (Exception ex)
            {
                DataTable dt = new DataTable("MyTable");
                dt.Columns.Add(new DataColumn("id", typeof(int)));
                dt.Columns.Add(new DataColumn("message", typeof(string)));

                DataRow errorLine = dt.NewRow();

                errorLine["id"]      = 1;
                errorLine["message"] = "Erro na chamada de serviço. Mensagem: " + ex.Message;
                dt.Rows.Add(errorLine);
                ret.Tables.Add(dt);
            }

            return(ret);
        }
Пример #23
0
        /// <summary>
        /// Gets a response from the IdP based on a message.
        /// </summary>
        /// <param name="endpoint">The IdP endpoint.</param>
        /// <param name="message">The message.</param>
        /// <param name="basicAuth">Basic auth settings.</param>
        /// <returns></returns>
        public Stream GetResponse(string endpoint, string message, HttpBasicAuthElement basicAuth)
        {
            Binding binding = CreateSslBinding();
            Message request = Message.CreateMessage(binding.MessageVersion, HttpArtifactBindingConstants.SOAPAction, new SimpleBodyWriter(message));

            request.Headers.To = new Uri(endpoint);

            HttpRequestMessageProperty property = new HttpRequestMessageProperty();

            property.Method = "POST";
            property.Headers.Add(HttpRequestHeader.ContentType, "text/xml; charset=utf-8");

            //We are using Basic http auth over ssl
            if (basicAuth != null && basicAuth.Enabled)
            {
                string basicAuthzHeader = "Basic " +
                                          Convert.ToBase64String(Encoding.UTF8.GetBytes(basicAuth.Username + ":" + basicAuth.Password));
                property.Headers.Add(HttpRequestHeader.Authorization, basicAuthzHeader);
            }

            request.Properties.Add(HttpRequestMessageProperty.Name, property);
            if (_context.Request.Params["relayState"] != null)
            {
                request.Properties.Add("relayState", _context.Request.Params["relayState"]);
            }

            EndpointAddress epa = new EndpointAddress(endpoint);

            ChannelFactory <IRequestChannel> factory = new ChannelFactory <IRequestChannel>(binding, epa);
            IRequestChannel reqChannel = factory.CreateChannel();

            reqChannel.Open();
            Message response = reqChannel.Request(request);

            Console.WriteLine(response);
            reqChannel.Close();
            XmlDocument xDoc = new XmlDocument();

            xDoc.Load(response.GetReaderAtBodyContents());
            string       outerXml  = xDoc.DocumentElement.OuterXml;
            MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(outerXml));

            return(memStream);
        }
Пример #24
0
        public static string SignIn(string user, string password)
        {
            string successful = "failed";

            byte[] bytes  = System.Text.ASCIIEncoding.ASCII.GetBytes("sbfa:sbfa");
            string base64 = Convert.ToBase64String(bytes, Base64FormattingOptions.None);

            authorizationKey = "Basic " + base64;

            sbfaSecurity.SBFASecurityClient security = new sbfaSecurity.SBFASecurityClient();
            var httpRequestPropertySecurity          = new HttpRequestMessageProperty();

            httpRequestPropertySecurity.Headers[HttpRequestHeader.Authorization] = authorizationKey;

            var contextSecurity = new OperationContext(security.InnerChannel);

            using (new OperationContextScope(contextSecurity))
            {
                try
                {
                    contextSecurity.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestPropertySecurity;
                    sbfaSecurity.AuthenticationResponse response = security.Authenticate(user, password);
                    if (response.authenticationStatus)
                    {
                        accessToken        = response.accessToken;
                        Globals.userLogged = response.username;

                        //SBFAMain openMain = new SBFAMain();
                        //openMain.Show();
                        successful = "successful";
                    }
                    else
                    {
                        //MessageBox.Show(response.responseCode.ToString() + " : " + response.responseMessage);
                        successful = "failed";
                    }
                }catch (Exception ex)
                {
                    successful = "error";
                }
            }

            return(successful);
        }
        /// <summary>
        /// Enables inspection or modification of a message before a request message is sent to a service.
        /// </summary>
        /// <param name="request">The message to be sent to the service.</param>
        /// <param name="channel">The WCF client object channel.</param>
        /// <returns>The object that is returned as the <paramref name="correlationState " />argument of the <see cref="M:System.ServiceModel.Dispatcher.IClientMessageInspector.AfterReceiveReply(System.ServiceModel.Channels.Message@,System.Object)" /> method. This is null if no correlation state is used.The best practice is to make this a <see cref="T:System.Guid" /> to ensure that no two <paramref name="correlationState" /> objects are the same.</returns>
        public object BeforeSendRequest(ref Message request, System.ServiceModel.IClientChannel channel)
        {
            HttpRequestMessageProperty httpRequest;

            if (request.Properties.ContainsKey(HttpRequestMessageProperty.Name))
            {
                httpRequest = request.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
            }
            else
            {
                httpRequest = new HttpRequestMessageProperty();
                request.Properties.Add(HttpRequestMessageProperty.Name, httpRequest);
            }

            string WulkaaBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", UserName, Password)));

            httpRequest.Headers["Authorization"] = string.Format("Wulkaa {0}", WulkaaBase64);
            return(null);
        }
Пример #26
0
        /// <summary>
        /// Changes a HTTP GET into a POST.
        /// </summary>
        /// <param name="properties">Properties for which the HTTP method is to be changed.</param>
        public static void MakeHttpPOSTMethod(MessageProperties properties)
        {
            object property;
            HttpRequestMessageProperty httpMessageProperty = null;

            if (properties.TryGetValue(MessageUtility.HttpRequestName, out property))
            {
                httpMessageProperty = property as HttpRequestMessageProperty;
            }

            if (httpMessageProperty == null)
            {
                httpMessageProperty = new HttpRequestMessageProperty();
                properties.Add(MessageUtility.HttpRequestName, httpMessageProperty);
            }

            httpMessageProperty.Method             = MessageUtility.HttpPostMethodName;
            httpMessageProperty.SuppressEntityBody = false;
        }
        public ActionResult executeMessageGet(string project, string message)
        {
            var client       = this.GetClient();
            var channel      = client.InnerChannel;
            var clientConfig = ClientConfiguration.getClientConfiguration();

            var context = new BisMessageHttpActionServiceReference.CallContext()
            {
                Language = clientConfig.LanguageId,
                Company  = clientConfig.CompanyId
            };

            var oauthHeader = OAuthHelper.GetAuthenticationHeader(clientConfig);

            var result = "<xml>Empty</xml>";

            try
            {
                using (OperationContextScope operationContextScope = new OperationContextScope(channel))
                {
                    HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty();
                    requestMessage.Headers[OAuthHelper.OAuthHeader] = oauthHeader;
                    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage;

                    result = ((BisMessageHttpActionServiceReference.BisMessageStartFromHttp)channel).executeMessageGet(new BisMessageHttpActionServiceReference.executeMessageGet(context, message, project)).result;
                }

                return(Content(result));
            }
            catch (Exception ex)
            {
                result = String.Format("<xml>Error: {0}</xml>", ex.Message);

                return(Content(result));
            }
            finally
            {
                if (client != null)
                {
                    client.Close();
                }
            }
        }
Пример #28
0
        public void ContextUserAgentIsSetIfPresent()
        {
            var context = new MockOperationContext();

            context.EndpointUri   = new Uri("http://localhost/Service1.svc");
            context.OperationName = "GetData";

            HttpRequestMessageProperty http = new HttpRequestMessageProperty();

            http.Headers["User-Agent"] = "MyUserAgent";
            context.IncomingProperties.Add(HttpRequestMessageProperty.Name, http);

            var initializer = new UserAgentTelemetryInitializer();
            var telemetry   = new RequestTelemetry();

            initializer.Initialize(telemetry, context);

            Assert.AreEqual("MyUserAgent", telemetry.Context.User.UserAgent);
        }
        public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
        {
            object prop;
            string myHeader;

            if (!OperationContext.Current.IncomingMessageProperties.TryGetValue(HttpRequestMessageProperty.Name, out prop))
            {
                myHeader = Guid.NewGuid().ToString();
            }
            else
            {
                HttpRequestMessageProperty reqProp = (HttpRequestMessageProperty)prop;
                myHeader = reqProp.Headers[X_ACTIVITY_ID_HTTP_HEADER];
            }

            Trace.CorrelationManager.ActivityId = Guid.Parse(myHeader);

            return(null);
        }
        protected virtual string Execute(string soapAction, string message, string[] responseTag, params string[] soapNamespaces)
        {
            var request = WriteSoapEnvelope(message, soapNamespaces);

            RemoteCertificateValidationCallback validation = null;
            var naoValidarCertificado = !ValidarCertificadoServidor();

            if (naoValidarCertificado)
            {
                validation = ServicePointManager.ServerCertificateValidationCallback;
                ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
            }

            var ret = string.Empty;

            try
            {
                //Define a action no content type por ser SOAP 1.2
                var requestMessage = new HttpRequestMessageProperty();
                requestMessage.Headers["Content-Type"] = $"application/soap+xml;charset=UTF-8;action=\"{soapAction}\"";

                request.Properties[HttpRequestMessageProperty.Name] = requestMessage;

                lock (serviceLock)
                {
                    var response = Channel.Request(request);
                    Guard.Against <ACBrDFeException>(response == null, "Nenhum retorno do webservice.");
                    var reader = response.GetReaderAtBodyContents();
                    ret = reader.ReadOuterXml();
                }
            }
            finally
            {
                if (naoValidarCertificado)
                {
                    ServicePointManager.ServerCertificateValidationCallback = validation;
                }
            }

            var xmlDocument = XDocument.Parse(ret);

            return(TratarRetorno(xmlDocument, responseTag));
        }
Пример #31
0
		protected HttpRequestMessageProperty CreateRequestProperty (HttpContextInfo ctxi)
		{
			var query = ctxi.Request.Url.Query;
			var prop = new HttpRequestMessageProperty ();
			prop.Method = ctxi.Request.HttpMethod;
			prop.QueryString = query.StartsWith ("?") ? query.Substring (1) : query;
			// FIXME: prop.SuppressEntityBody
			prop.Headers.Add (ctxi.Request.Headers);
			return prop;
		}