Quantcast
Channel: WCF, ASMX and other Web Services
Viewing all 555 articles
Browse latest View live

Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

$
0
0

Appreciate if anyone could help me to resolve this issue.

I am using DataServiceContext to get data from SQL DB using WCF service and Connection string and StackTrace is as under as under:

<add name="Entities" connectionString="metadata=res://*/MYDB.csdl|res://*/MYDB.ssdl|res://*/MYDB.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=MyDataSource;initial catalog=MyDB;user id=sa;password=Pass@123;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />    
[DataServiceClientException: <?xml version="1.0" encoding="utf-8"?><m:error xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"><m:code /><m:message xml:lang="en-US">An error occurred while processing this request.</m:message><m:innererror><m:message>An error occurred while executing the command definition. See the inner exception for details.</m:message><m:type>System.Data.Entity.Core.EntityCommandExecutionException</m:type><m:stacktrace>   at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)&#xD;
   at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)&#xD;
   at System.Data.Entity.Core.Objects.ObjectQuery`1.&lt;&gt;c__DisplayClassb.&lt;GetResults&gt;b__a()&#xD;
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)&#xD;
   at System.Data.Entity.Core.Objects.ObjectQuery`1.&lt;&gt;c__DisplayClassb.&lt;GetResults&gt;b__9()&#xD;
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)&#xD;
   at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)&#xD;
   at System.Data.Entity.Core.Objects.ObjectQuery`1.&lt;System.Collections.Generic.IEnumerable&lt;T&gt;.GetEnumerator&gt;b__0()&#xD;
   at System.Lazy`1.CreateValue()&#xD;
   at System.Lazy`1.LazyInitValue()&#xD;
   at System.Lazy`1.get_Value()&#xD;
   at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()&#xD;
   at System.Data.Services.QueryResultInfo.MoveNext()&#xD;
   at System.Data.Services.DataService`1.SerializeResponseBody(RequestDescription description, IDataService dataService, IODataResponseMessage responseMessage)&#xD;
   at System.Data.Services.DataService`1.HandleNonBatchRequest(RequestDescription description)&#xD;
   at System.Data.Services.DataService`1.HandleRequest()</m:stacktrace><m:internalexception><m:message>Execution Timeout Expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.</m:message><m:type>System.Data.SqlClient.SqlException</m:type><m:stacktrace>   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)&#xD;
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)&#xD;
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)&#xD;
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean&amp; dataReady)&#xD;
   at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()&#xD;
   at System.Data.SqlClient.SqlDataReader.get_MetaData()&#xD;
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption)&#xD;
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task&amp; task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)&#xD;
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task&amp; task, Boolean&amp; usedCache, Boolean asyncWrite, Boolean inRetry)&#xD;
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)&#xD;
   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)&#xD;
   at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)&#xD;
   at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)&#xD;
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.&lt;&gt;c__DisplayClassb.&lt;Reader&gt;b__8()&#xD;
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TInterceptionContext,TResult](Func`1 operation, TInterceptionContext interceptionContext, Action`1 executing, Action`1 executed)&#xD;
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)&#xD;
   at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)&#xD;
   at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)&#xD;
   at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)</m:stacktrace><m:internalexception><m:message>The wait operation timed out</m:message><m:type>System.ComponentModel.Win32Exception</m:type><m:stacktrace></m:stacktrace></m:internalexception></m:internalexception></m:innererror></m:error>]
   System.Data.Services.Client.QueryResult.ExecuteQuery() +253
   System.Data.Services.Client.DataServiceRequest.Execute(DataServiceContext context, QueryComponents queryComponents) +273

Any Mobile client can consume or call asmx based web service

$
0
0

i am curious to know that if i build a web service with legacy asmx technology and host that web service in a pc which is publicly accessible over internet then any mobile client can consume or call asmx based web service ?

because i know Mobile client can consume or call web site.

if the answer is no mean Mobile client can't consume or call asmx based web service then please highlight all the reasons. thanks

How to gain access to Label1.Text in WebMethod section code ?

$
0
0

On aspx I have this

function ShowCurrentTime() {$.ajax({
        type: "POST",
        url: "JSFireCSharp.aspx/GetCurrentTime",
        data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function(response) {
            alert(response.d);
        }
    });
}

Then I have this in code behind

[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
    return "Hello " + name + Environment.NewLine + "The Current Time is: "+ DateTime.Now.ToString();

(((Here I want to add a line Label1.Text = name but get error))))
}


I want to add a line Label1.Text = name but get error. It seems I am not able to gain access to Label1.
Pls help. What can I do ? Thanks
   

Is there any tool or library we can use to generate API document.

WCF in Azure Load Balanced servers

$
0
0

Hi,

We are currently testing our website in Azure.

There are two web servers with one load balancer.

We configured the website and the WCF in both server.

However, the error as the image below appears once a while.

https://ibb.co/k9YkKw

Is there anything we need to set to make it work in the load balancer environment?

It works all the time in our testing server without load balancer.

Thanks.

Authentication token based WCF Services

$
0
0

How to implement WCF Services with token for Authentication?

How to check .net service status using Powershell scripts

$
0
0

I have different types of webservices like asmx, WCF and WEB APIs. is there a way to check the status of all those services using powershell scripts and send an email 

Old books on WCF...

$
0
0

I've seen old books about WCF that are from 2010/2011.....

I know that WCF doesnt change so fast....

So  those books still relevant? What differences should I care about ?

thx

anderson


How to call WebMethod dynamically without adding VS Webreference.

$
0
0

I have a code that works great when I add web reference, and on my code behind all the properties and signatures are all exposed. I can do inserts easily as you can see below

 Dim soap As New ServiceNowRef.ServiceNow_incident
        Dim cred As New System.Net.NetworkCredential("xxx", "xxxxx")
        'Dim soapclient As New We
        Dim msg As String = String.Empty
        Dim insert As New ServiceNowRef.insert
        Dim insertResponse As New ServiceNowRef.insertResponse

        soap.Credentials = cred
        insert.u_ticketnumber1 = Request.Form("ticketnumber1")
        insert.u_ticketnumber2 = Request.Form("ticketnumber2")
        insert.u_ticketstatus = Request.Form("TicketStatus")
        insert.u_ticketstatusnotes = Request.Form("TicketStatusNotes")

        Try
            updateResponse = soap.insert(insert)
            msg = "Incident inserted"
        Catch ex As Exception
            msg = "Incident Not inserted:" & ex.ToString
        End Try

The code requirement has changed and instead of doing through webreference, I need to perform same function like INSERTing a record to an API, the URL & other references should be defined on the same page.
How do I achieve that? Is it possible without adding too much complexity. Can you show me some samples?

Thank You

How to access intranet web services over internet

$
0
0

I am not sure which forum to choose for this.

I have web application developed in visual studio 2015 in c#. This web application is back-end and which runs only in intranet.

We have mobile app as front-end which access some web services written in the back-end app. This front-end mobile app is available on internet. 

So are these web services can be accessible through front-end app without doing anything?

Or how can we make available web services to access through front-end mobile app over internet.

What should we do?

------------------

So far our both back-end and front-end both were on intranet or both were on internet, so was not a problem. Now it's mix of intranet and internet (back-end with web services - intranet, front-end which access web services - internet) , so not sure what we need to change so web services will be accessible over internet. 

How can i host a wcf service for others to invoke ?

$
0
0

Hi,

I have created a wcf service which is called successfuly in  my local app. I have run unit tests . But it is on  my local host and i need to host it so that it can be tested by a testing centre ...

they mention 

The textbox below needs a URI for an API you create and host. It should be your own implementation of our reference service.

the text box has        http://your-hostname/api

I assume the wcf service would be required here or is an ai required ?

I dont have an external host name , can i use github ?

thanks

What is throttling in WCF

$
0
0

please explain with example that What is throttling in WCF

Publish only web service on server

$
0
0

I have web application with web services, .asmx page.

I have to publish web application on intranet and I have to publish web service on internet.

So I have to create separate application in IIS having web service, .asmx page only and separate web site for web application.

How to know with .asmx page what else i need to keep in that folder. For e.g. do i need to keep web.config, bin folder and what else?

I have keep same web.config, bin folder in my other web app web site folder also.

-----------------

My application and web service share common folder on server. That folder will be under application web site folder. How can I point my web service to access the same folder as my application?

How to access folder or files in another published application

$
0
0

I have published CMS and web service separately. But CMS and web service share common folders and files.

Folders and files are in CMS published folder. How can I enable my web service to point to those files and folders?

Webservice, Generating WSDL with elementFormDefault = “Unqualified”

$
0
0

Hello,

we are right now trying to expose a Web Service method to another company. Their demands are that the method is OneWay and we need to have the attribute **elementFormDefault = "Unqualified" **.

We don't fully understand the way this works, we are using VS 2010 and we added a new Item called "Web Service". Then we defined our Web Method and build the solution. Everything worked well and the WSDL generated looks good. The only problem is that we always have elementFormDefault = "Qualified" no matter how we define our class.

We can make the WSDL generated to indicate that all attributes are unqualified but we always have the element for default defined as qualified...

When our client tries to use our method we receive empty information...

our class to generate the XML is this one, note that the class is a bit messy as we tried multiple solutions:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using WSGerfip.Ws_Tesouraria;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using WSGerfip.Client_IlcrCallback;

namespace WSGerfip
{


    // -----------------------------------------------------------------------------------------------------------------------------------
    // CallBack - WebService que a ESPAP chama.
    //            Este WebService CallBack, por sua vez, chama o Web Service da Tesouraria (Ws_NotasCobranca)
    //            Foi necess�rio implementer esta camada no dotnet, porque em Outsystems n�o dava para definir o atributo OneWay
    // -----------------------------------------------------------------------------------------------------------------------------------

    [WebService(Namespace = "urn:espap.gerfip.ilcr.v1")]
    //[XmlRoot(Namespace = "urn:espap.gerfip.ilcr.v1", IsNullable=true)]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]


    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
    //glide.wsdl.schema.UnqualifiedElementFormDefault




    public class CallBackReceita : System.Web.Services.WebService
    {

        [SoapDocumentMethod(OneWay = true)]
        [WebMethod]

        public void RegisterLogisticInvoiceResult(
            [System.Xml.Serialization.XmlAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)] string CorrelationId)
            [System.Xml.Serialization.XmlAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)] int ResultStatus,
            [System.Xml.Serialization.XmlAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)] RegisterLogisticInvoiceResultResult[] Results,
            [System.Xml.Serialization.XmlAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)] WSGerfip.Client_IlcrCallback.Messages[] GeneralMessages)
        {
            //CorrelationId = this.CorrelationId;
             string linhaA_Escrever;
             string path_escrita;
            path_escrita = "c:\\Temp\\Log_Fatura.txt";

            StreamWriter streamWriter = new StreamWriter(path_escrita, true, System.Text.Encoding.GetEncoding("ISO-8859-1"));

            try
            {

                linhaA_Escrever = "--------------------------------------------------" + Environment.NewLine;
                linhaA_Escrever = linhaA_Escrever + "Data: " + DateTime.Now + Environment.NewLine;
                linhaA_Escrever = linhaA_Escrever + "IdCorrela��o: " + CorrelationId + Environment.NewLine;


                //Results = new Result[1];

                linhaA_Escrever = linhaA_Escrever + "0" + Environment.NewLine;

                //Results[0] = new Result();

                linhaA_Escrever = linhaA_Escrever + "00" + Environment.NewLine;

                //Results[] = Results[];

                //Results[0].PDF = new PDF();
                //Results[0].PDF.InvoicePdf = new byte[10000000];

                linhaA_Escrever = linhaA_Escrever + "1" + Environment.NewLine;


                //Ws_Tesouraria.RegisterLogisticInvoiceResult RegisterLogisticInvoiceResult = new Ws_Tesouraria.RegisterLogisticInvoiceResult();

                //RegisterLogisticInvoiceResult.CorrelationId = CorrelationId;
                //RegisterLogisticInvoiceResult.ResultStatus = ResultStatus;
                //RegisterLogisticInvoiceResult.Results = Results;
                //RegisterLogisticInvoiceResult.GeneralMessages = GeneralMessages;



                //linhaA_Escrever = linhaA_Escrever + "Pdf:2 " + Results[0].PDF.InvoicePdfName + Environment.NewLine;

                ////if (Results[0].PDF != null)
                //linhaA_Escrever = linhaA_Escrever + "Pdf:3 " + Results[0].PDF.InvoicePdfName + Environment.NewLine;



                //linhaA_Escrever = linhaA_Escrever + "Pdf4: " + Results[0].PDF.InvoicePdf.Length + Environment.NewLine;

                //linhaA_Escrever = linhaA_Escrever + "2" + Environment.NewLine;


                ////linhaA_Escrever = linhaA_Escrever + "Nr Fatura: " + Results[0].InvoiceResultNumber + Environment.NewLine;

                ////linhaA_Escrever = linhaA_Escrever + "3" + Environment.NewLine;


                //linhaA_Escrever = linhaA_Escrever + "Resultado: " + ResultStatus;

                streamWriter.WriteLine(linhaA_Escrever);

                //Ws_Tesouraria.RegisterLogisticInvoiceResult RegisterLogisticInvoiceResult = new Ws_Tesouraria.RegisterLogisticInvoiceResult();

                //RegisterLogisticInvoiceResult.CorrelationId = CorrelationId;
                //RegisterLogisticInvoiceResult.ResultStatus = ResultStatus;
                //RegisterLogisticInvoiceResult.Results = Results;
                //RegisterLogisticInvoiceResult.GeneralMessages = GeneralMessages;

                //Ws_Tesouraria.WS_NotasCobranca WS = new Ws_Tesouraria.WS_NotasCobranca();

                //WS.RespostaFatura(RegisterLogisticInvoiceResult);
            }
            catch (Exception ex)
            {
                //linhaA_Escrever = linhaA_Escrever + Environment.NewLine + " Erro: " + ex;
                //streamWriter.WriteLine(linhaA_Escrever);
            }
            finally
            {
                streamWriter.Close();
                streamWriter.Dispose();
            }

        }
    }
}

and one of the generated WSDL's:

<wsdl:definitions xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:tns="urn:espap.gerfip.ilcr.v1" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" targetNamespace="urn:espap.gerfip.ilcr.v1"><wsdl:types><s:schema elementFormDefault="qualified" targetNamespace="urn:espap.gerfip.ilcr.v1"><s:element name="RegisterLogisticInvoiceResult"><s:complexType><s:attribute form="unqualified" name="CorrelationId" type="s:string"/></s:complexType></s:element></s:schema></wsdl:types><wsdl:message name="RegisterLogisticInvoiceResultSoapIn"><wsdl:part name="parameters" element="tns:RegisterLogisticInvoiceResult"/></wsdl:message><wsdl:portType name="CallBackReceitaSoap"><wsdl:operation name="RegisterLogisticInvoiceResult"><wsdl:input message="tns:RegisterLogisticInvoiceResultSoapIn"/></wsdl:operation></wsdl:portType><wsdl:binding name="CallBackReceitaSoap" type="tns:CallBackReceitaSoap"><soap:binding transport="http://schemas.xmlsoap.org/soap/http"/><wsdl:operation name="RegisterLogisticInvoiceResult"><soap:operation soapAction="urn:espap.gerfip.ilcr.v1/RegisterLogisticInvoiceResult" style="document"/><wsdl:input><soap:body use="literal"/></wsdl:input></wsdl:operation></wsdl:binding><wsdl:binding name="CallBackReceitaSoap12" type="tns:CallBackReceitaSoap"><soap12:binding transport="http://schemas.xmlsoap.org/soap/http"/><wsdl:operation name="RegisterLogisticInvoiceResult"><soap12:operation soapAction="urn:espap.gerfip.ilcr.v1/RegisterLogisticInvoiceResult" style="document"/><wsdl:input><soap12:body use="literal"/></wsdl:input></wsdl:operation></wsdl:binding><wsdl:service name="CallBackReceita"><wsdl:port name="CallBackReceitaSoap" binding="tns:CallBackReceitaSoap"><soap:address location="http://srvsicofdv/wsgerfip/callbackReceita.asmx"/></wsdl:port><wsdl:port name="CallBackReceitaSoap12" binding="tns:CallBackReceitaSoap12"><soap12:address location="http://srvsicofdv/wsgerfip/callbackReceita.asmx"/></wsdl:port></wsdl:service></wsdl:definitions>

We kinda tried everyhing and we are not able to find a solution for this... everytime our method is being called we dont have nothing in the input parameters... and when the cliend send us the WSDL that they used to send to our method infact the attributes are there. This is the WSDL the client wants to send to us, so our WSDL must accept this:

<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing"><s:Header><a:Action s:mustUnderstand="1">SaveLogisticInvoiceResult</a:Action><h:ContextHeader xmlns:h="urn:GeRAP.Services.GSE.ContextHeaderExtension" xmlns="urn:GeRAP.Services.GSE.ContextHeaderExtension" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><BusinessAxis><CompanyCode>5983</CompanyCode><OrganizationalUnit>ADSE</OrganizationalUnit><Entity xsi:nil="true" /><ProcessActivity xsi:nil="true" /><ProcessId xsi:nil="true" /></BusinessAxis><ChannelAxis><ComunicationChannel>www</ComunicationChannel><Security>SSL</Security></ChannelAxis><IdentityAxis><Group xsi:nil="true" /><User>pp\service.pp.adse</User></IdentityAxis><SubscriprionAxis><Application>ADSE</Application><ApplicationContext>ILCR</ApplicationContext></SubscriprionAxis></h:ContextHeader><GseInternalHeader xmlns="urn:eSPap.Services.GSE.Internal" /><dnh0:DynamicChannelHeader xmlns:dnh0="urn:eSPap.Services.GSE.DynamicChannelExtension"><dnh0:CorrelationToken>ILCR_SERVICE.PP.ADSE_5983</dnh0:CorrelationToken></dnh0:DynamicChannelHeader><a:MessageID>urn:uuid:8886fa85-367b-48f5-a37f-232f57376875</a:MessageID><a:To s:mustUnderstand="1">https://pp-gseb2b.gerall.pt/TimeKeepingCallbacks</a:To></s:Header><s:Body><RegisterLogisticInvoiceResult xmlns="urn:espap.gerfip.ilcr.v1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><CorrelationId xmlns="">1721027</CorrelationId><ResultStatus xmlns="">1</ResultStatus><Results xmlns=""><Result><DocumentId>1</DocumentId><SaleOrderResultNumber>3151100234</SaleOrderResultNumber><InvoiceResultNumber>3155000183</InvoiceResultNumber><PDF><InvoicePdfName>DFLOG3155000183201801181901.pdf</InvoicePdfName><InvoicePdf>A BIG SEQUENCE OF BYTES IS HERE BUT I REMOVED FOR TURNING THIS READ FRIENDLY</InvoicePdf></PDF><InvoiceMessages><Message><Type>Warning</Type><Code>MW010</Code><Text>Item 1 - O campo Montante da condição não está preenchido.</Text></Message><Message><Type>Information</Type><Code>MW026</Code><Text>Mensagens Fatura/Ordem Venda</Text></Message><Message><Type>Information</Type><Code>V1311</Code><Text>Ordem standard 3151100234 foi gravado(a)</Text></Message><Message><Type>Information</Type><Code>VF311</Code><Text>Documento 3155000183 foi gravado</Text></Message></InvoiceMessages><TotalValue>55.00</TotalValue></Result></Results><GeneralMessages xmlns="" /></RegisterLogisticInvoiceResult></s:Body></s:Envelope>

original post is here: StackOverflow original post

Can you guys please give us some hint?

Thanks in advance,

VC


Problem with WCF Soap Service in mono (Xam.Android)

$
0
0

I'm trying to develop a Xamarin App (Xam 4.7.10.38 with Xam.And.SDK 8.0.2.1 using PCL approach) connected to an Dynamics 365 Finance And Operation Custom Web Service. Just to sum it up, it's a WCF Soap service that uses Azure Active Directory Client Id + Client Secret to connect to the soap service.  

I've posted the most important part of the code below for reference.  

So as instructed, I used the Silverlight SDK to create the service reference proxy class and also added the necessary framework references. Then I included this proxy class in my Android Project as wel as in a standard .Net Windows App, both using VS.Net 2017.   Everything is identical up until I call "var resultAsync = service.BeginValidateUser(validateUserRequest, null, null);"  

In my Windows App, it returns System.ServiceModel.Channels.ServiceChannel.SendAsyncResult. I do the WaitOne to conclude it and my EndValidateUser returns a correct result.

  However in my Android App, it returns System.Runtime.Remoting.Messaging.AsyncResult which is a different object with different members/methods. The Waitone still works, but when I call the EndValidateUser, I got an exception saying  "System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.\nParameter name: value\n  at (wrapper managed-to-native) System.Object:__icall_wrapper_mono_delegate_end_invoke (object,intptr)\n  at (wrapper delegate-end-invoke) <Module>:end_invoke_object__this___object[]&_IAsyncResult (object[]&,System.IAsyncResult)\n  at System.ServiceModel.MonoInternal.ClientRuntimeChannel.EndProcess (System.Reflection.MethodBase method, System.String operationName, System.Object[] parameters, System.IAsyncResult result) [0x0001f] in <475dec2c1fe44b95bbfbd21b550b63f8>:0 \n  at System.ServiceModel.ClientBase`1+ChannelBase`1[TChannel,T].EndInvoke (System.String methodName, System.Object[] args, System.IAsyncResult result) [0x00045] in <475dec2c1fe44b95bbfbd21b550b63f8>:0 \n  

Any idea's or approaches on how to solve this ?  

Regards, Sven Peeters    

Code for Reference :      

<div>            AuthenticationContext authenticationContext = new AuthenticationContext(Static_Functions.activeDirectoryTenant);</div> <div> </div> <div>            string aadClientAppSecret = Static_Functions.activeDirectoryClientAppSecret;</div><div>            ClientCredential creadential = new ClientCredential(Static_Functions.activeDirectoryClientAppId, aadClientAppSecret);</div> <div>            AuthenticationResult authenticationResult = authenticationContext.AcquireTokenAsync(Static_Functions.activeDirectoryResource, creadential).Result;</div> <div>            string oAuthHeader = authenticationResult.CreateAuthorizationHeader();</div> <div> </div> <div>            string serviceName = "PWBMobilityServiceGroup";</div> <div>           string soapServiceUriString = Static_Functions.GetSoapServiceUriString(serviceName, Static_Functions.aosUri);</div> <div> </div> <div>            EndpointAddress endpointAddress = new EndpointAddress(soapServiceUriString);</div><div>            System.ServiceModel.Channels.Binding binding = Static_Functions.GetBinding();</div> <div> </div> <div>            SchindlerTechAssist.Droid.D365Service.MobilityServiceClient client = new SchindlerTechAssist.Droid.D365Service.MobilityServiceClient(binding, endpointAddress);</div> <div>            IClientChannel dimServiceChannel = client.InnerChannel;</div> <div> </div> <div>            using (OperationContextScope dimServiceOperContext = new OperationContextScope(dimServiceChannel))</div><div>            {</div> <div>                HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty();</div> <div>                requestMessage.Headers[Static_Functions.OAuthHeader] = oAuthHeader;</div><div>                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage;</div> <div> </div> <div>                CallContext callContext = new CallContext { Company = "DAT" };</div><div> </div> <div>                string empId = "000509";</div> <div>                string pass = "test";</div> <div> </div> <div>                #region Validate User</div> <div> </div><div>                SchindlerTechAssist.Droid.D365Service.PWBMobServiceValidateUserRequest validateUserRequest = new SchindlerTechAssist.Droid.D365Service.PWBMobServiceValidateUserRequest();</div> <div>                validateUserRequest.EmployeeId = empId;</div> <div>                validateUserRequest.Password = pass;</div> <div> </div> <div>                SchindlerTechAssist.Droid.D365Service.MobilityService service = (SchindlerTechAssist.Droid.D365Service.MobilityService)dimServiceChannel;</div><div> </div> <div>                var resultAsync = service.BeginValidateUser(validateUserRequest, null, null);</div> <div>                resultAsync.AsyncWaitHandle.WaitOne();</div> <div> </div> <div>               var result = service.EndValidateUser(resultAsync);</div> <div> </div> <div> </div> <div>                #endregion</div> <div> </div> <div>            }</div>

500 error

$
0
0

I am gettting the following error...

HTTP Error 500.22 - Internal Server Error

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.

Most likely causes:

  • This application defines configuration in the system.web/httpModules section.

++++++++++++++ IPaymentRESTService.cs  +++++++++++++++++++++++++++

using System.ServiceModel;
using System.ServiceModel.Web;

namespace PayMentRESTService
{

[ServiceContract]
public interface IPayMentService
{
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "/PayBill/{PayId}", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string PayBill(string PayId);

}
}

+++++++++++++++++ PaymentRESTService.svc.cs +++++++++++++++++++++++++++++++++++++++

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace PayMentRESTService
{

public class PayMentService : IPayMentService
{
public string PayBill(string PayId)
{
{
return "Transaction having PayId " + PayId + " was successful";
}
}
}
}

++++++++++++++++++++++++++ web.config ++++++++++++++++++++++++++++++++++

<configuration>

<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.6"/>
<httpRuntime targetFramework="4.6"/>
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
</httpModules>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="web">

<webHttp/>

</behavior>

</endpointBehaviors>

</behaviors>
<services>
<service name="PayMentRESTService.PayMentService" behaviorConfiguration="ServiceBehavior">

<endpoint binding="webHttpBinding" contract="PayMentRESTService.IPayMentService" behaviorConfiguration="web">


</endpoint>
</service>

</services>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<!--<protocolMapping>
<add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping>-->
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>

Security in asmx web service

$
0
0

Hi

I am providing a number of web methods via asmx web service for a mobile app. How does security work in this scenario? Does each web method call need to receive username/password to authenticate each time, or can the authentication for a client app be done only once at the start of client app session?

Thanks

Regards

Sharing data contracts between wcf services without use ServiceReference name

$
0
0

Hi

icreated WCF service. My project name is SERVICE_ABC. In solution i created Service_A.svc, Service_B.svc, Service_C.svc and PersonelDTO.cs. All service using PersonelDTO.cs. Her is the code

public interface IService_A
{
[OperationContract]
void DoWork();

[OperationContract]
PersonelDTO GetMyData();
}

public interface IService_B
{
[OperationContract]
void DoWork();

[OperationContract]
PersonelDTO GetMyData();
}

public interface IService_C
{
[OperationContract]
void DoWork();

[OperationContract]
PersonelDTO GetMyData();
}

I read service WEB_ABC .net solution. In the HomeController.cs i have got Deneme() controller.  how can i use PersonelDTO  without ServiceReference_A service reference name

public string Deneme()
{
Service_AClient clientA = new Service_AClient();
Service_BClient clientB = new Service_BClient();
Service_CClient clientC = new Service_CClient();

/*Below these codes working properly
var DataA = clientA.GetMyData();
ServiceReference_B.PersonelDTO DataB = clientB.GetMyData();
ServiceReference_C.PersonelDTO DataC = clientC.GetMyData();
*/

//I want to use PersonelDTO without using ServiceReference_A service reference name
PersonelDTO DataA = clientA.GetMyData();
PersonelDTO DataB = clientB.GetMyData();
PersonelDTO DataC = clientC.GetMyData();

return "Ok";
}

Thanks. You can download project this link

HTTPS over owin rest webservice

$
0
0

I would like to implement a HTTPS connection for my rest webservice. The HTTP version works as well, but when i try to connect over HTTPS and send a XML file or something else, It already fails when establishing the connection via https. Has someone an idea what i can change to test it over https?

Startup.cs

using System;
using Owin;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using AppFunc = System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>;

[assembly: OwinStartup(typeof(SimuXmlDcs.MsiWebServer.Startup))]

namespace SimuXmlDcs.MsiWebServer
{
  using System.Configuration;
  using System.Net;
  using System.Net.Security;
  using System.Net.Sockets;
  using System.Security.Cryptography.X509Certificates;
  using System.Web.Http;
  using Microsoft.Owin.Security;
  using Newtonsoft.Json;

  using SimuXmlDcs.MsiWebServer.App_Start;
  using SimuXmlDcs.MsiWebServer.Controllers;

  /// <summary>
  /// The startup.
  /// </summary>
  public class Startup
  {
    /// <summary>
    /// The configuration.
    /// </summary>
    /// <param name="app">
    /// The app.
    /// </param>
    public void Configuration(IAppBuilder app)
    {
      ConfigureOAuth(app);

      // Configure Web API for self-host.
      HttpConfiguration config = new HttpConfiguration();

      config.MapHttpAttributeRoutes();

      config.Routes.MapHttpRoute(name: "SystemAction", routeTemplate: "api/{controller}/{system}/{action}", defaults: new { action = RouteParameter.Optional });

      config.Routes.MapHttpRoute(name: "System", routeTemplate: "api/{controller}/{system}");

      config.Routes.MapHttpRoute(name: "Info", routeTemplate: "api/{controller}");
      config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
      config.Formatters.XmlFormatter.UseXmlSerializer = true;
      app.UseWebApi(config);

      //byte[] test = new byte[4];
      //test[0] = 10;
      //test[1] = 78;
      //test[2] = 2;
      //test[3] = 193;
      //IPAddress ipaddress = new IPAddress(test);

      //TcpListener server = new TcpListener(ipaddress, 8443);
      //server.Start();

      //TcpClient client = server.AcceptTcpClient();
      //SslStream stream = new SslStream(client.GetStream(), false, VerifyClientCertificate, null);
    }

    private static bool VerifyClientCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
      return true;
    }

    /// <summary>
    /// Setup authorization server
    /// </summary>
    /// <param name="app">
    /// The app.
    /// </param>
    private void ConfigureOAuth(IAppBuilder app)
    {
      int timeSpan;
      AppSettingsReader asr = new AppSettingsReader();
      int.TryParse(asr.GetValue("TokenExpireInMinutes", typeof(string)).ToString(), out timeSpan);

      app.UseOAuthAuthorizationServer(
        new OAuthAuthorizationServerOptions()
          {
            AllowInsecureHttp = !MsiRestServer.UseHttps,
            TokenEndpointPath = new PathString("/api/getsecuretoken"),
            AccessTokenExpireTimeSpan = timeSpan != 0 ? TimeSpan.FromMinutes(timeSpan) : TimeSpan.FromDays(1),
            Provider = new AuthorizationServerProvider(),
            ApplicationCanDisplayErrors = true
          });
      app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }
  }
}

AuthorizationServerProvider:

amespace SimuXmlDcs.MsiWebServer.App_Start
{
  using System.Security.Claims;
  using System.Threading.Tasks;

  using Microsoft.Owin.Security;
  using Microsoft.Owin.Security.OAuth;

  using SimuXmlDcs.MsiWebServer.Models;

  /// <summary>
  /// The authorization server provider.
  /// </summary>
  public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
  {
    /// <summary>
    /// The validate client authentication.
    /// </summary>
    /// <param name="context">
    /// The context.
    /// </param>
    /// <returns>
    /// The <see cref="Task"/>.
    /// </returns>
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
      context.Validated();
    }

    /// <summary>
    /// The grant resource owner credentials.
    /// </summary>
    /// <param name="context">
    /// The context.
    /// </param>
    /// <returns>
    /// The <see cref="Task"/>.
    /// </returns>
    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
      context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

      if (context.Password != "password")
      {
        context.SetError("invalid_grant", "The user name or password is incorrect.");
        return;
      }

      ClaimsIdentity identity = new ClaimsIdentity(context.Options.AuthenticationType);
      identity.AddClaim(new Claim(ClaimTypes.Role, RoleName.Admin));
      identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));

      context.Validated(new AuthenticationTicket(identity, new AuthenticationProperties { }));
    }
  }
}

MsiRestServer:

namespace SimuXmlDcs.MsiWebServer
{
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Reflection;
  using System.Text;
  using System.Threading;
  using System.Threading.Tasks;
  using System.Windows;

  using log4net;

  using Microsoft.Owin.Hosting;

  /// <summary>
  /// The msi rest server.
  /// </summary>
  public static class MsiRestServer
  {
    private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

    private static Thread msiWebServer;

    private static bool endServer = false;

    /// <summary>
    /// Gets or sets a value indicating whether use https.
    /// </summary>
    public static bool UseHttps { get; set; }

    /// <summary>
    /// Gets or sets the base address.
    /// </summary>
    public static string BaseAddress { get; set; } = "https://test2234:8443";

    /// <summary>
    /// The startup server.
    /// </summary>
    public static void StartupServer()
    {
      Thread.Sleep(200);
      endServer = false;
      msiWebServer = new Thread(ServerThread);
      msiWebServer.Start();
    }

    /// <summary>
    /// The stop server.
    /// </summary>
    public static void StopServer()
    {
      endServer = true;
    }

    /// <summary>
    /// The server thread.
    /// </summary>
    private static void ServerThread()
    {
      try
      {
        Uri tstAddress = new Uri(BaseAddress);
        //WebServiceHost svcHost = new WebServiceHost();
        // Start OWIN host
        using (WebApp.Start<Startup>(url: BaseAddress))
        {
          while (!endServer)
          {
            Thread.Sleep(250);
          }
        }
      }
      catch (Exception ex)
      {
        logger.Error(ex);
        MessageBox.Show(ex.Message);
      }
    }
  }
}

Viewing all 555 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>