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

Could not load type 'System.ServiceModel.Activation.HttpModule'

$
0
0

Hi All, 

I am using Windows 10 for my developing WCF Data Service and i am getting below error:

Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

I have already done necessary configurations like HTTP Activation, etc. but no luck. Can anyone suggest me the solution or article to fix this?


Web Service and Database Communication

$
0
0

Will it be a good solution if a web service directly communicate with database, is it recommended? Further is there any development or helping material to fulfill the requirement like sending auto-emails to customer email address and verifying mobile number as well using One Time Password (OTP). 

WCF load test

$
0
0

I have a WCF web service to get data from database, i am testing it using simple test application,

it some times receives data from the first call, and some times gives an error.

any advises how to make a load test to this service?  

Java Web Service call from C# windows application returns "Object reference not set to an instance of an object"

$
0
0

Dear Experts,

I'm using web service exposed from a website to submit my client transaction and get the response back.i'm passing correct parameters to web service in the correct formats the same web service call with the exact same parameter is working when I'm using testing tool SOAPUI but when I'm running through my c# code getting the exception "Object reference not set to an instance of an object".

Below is the signature of web service function :

int WebSvcFunction(string login,string pwd,string xmlClaimInput,out string xmlDRGDetails,out byte[] auditFileContent,out byte[] reportFileContent,out string errorMessage);

Any help in this regards is highly appreciated.Thanks in advance.

Below is my sample code for Testing :

private void btnTestService_Click(object sender, EventArgs e)
  {
         try
         {
               string xmlDRGDetails = (string)null;
               byte[] auditFileContent = (byte[])null;
               byte[] reportFileContent = (byte[])null;
               string errorMessage = (string)null;

               int m = objWebservicesSoapClient.WebSvcFunction(gstrLoginId, gstrpwd, rTxtDrgTab.Text.ToString(), out xmlDRGDetails,
                                                       out auditFileContent , out reportFileContent, out errorMessage);

               MessageBox.Show(string.Format("Success {0}", m));
          }
          catch (Exception ex)
          {
               MessageBox.Show(string.Format("Source: {0}\nDescription:{1}\nTarget Site:{2}\nCall Stack:{3}", (object)ex.Source, (object)ex.Message, (object)ex.TargetSite, (object)ex.StackTrace), "Convert DRG", MessageBoxButtons.OK, MessageBoxIcon.Error);
          }

         }

Path too long exception System.IO.PathTooLongException:

$
0
0
Hi, I am getting this error when I am trying to convert dataset into XML xmldocu.Load(dset.GetXml()); where dset is the Dataset containg the data. ERROR: System.IO.PathTooLongException: The path is too long after being fully qualified. Make sure path is less than 260 characters. My webservice returns a dataset to the calling application. It was working jsut fine with the dataset, but when I tried converting it into the xml first before returning, it gave me this error. I also tried returning dataset to the calling application and converting dataset into xml in the calling application but it gave me the same error.

secure username/password authentication issue in WCF service application

$
0
0

My web.config of the service is as follows

<configuration>

<appSettings>

<add key="SSLUserName" value="lgxitadmin" />
<add key="SSLPassword" value="lgxadmin$123" />
</appSettings>

<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="SafeServiceConf">
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="Basic" proxyCredentialType="Basic"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>

<services>
<service name="Ramco_LGX_interfaces.LGXService" behaviorConfiguration="metadataBehavior">
<endpoint address="" binding="" bindingConfiguration="SafeServiceConf" contract="Ramco_LGX_interfaces.ILGXService" />
<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />
</service>
</services>

<behaviors>
<serviceBehaviors>
<behavior name="metadataBehavior">
<serviceSecurityAudit auditLogLocation="Application" serviceAuthorizationAuditLevel="Failure" messageAuthenticationAuditLevel="Failure" suppressAuditFailure="true" />
<serviceMetadata httpsGetEnabled="true" />
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<!-- 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="true" />
<serviceCredentials>
<!--<clientCertificate>
<authentication certificateValidationMode="None" />
</clientCertificate>-->
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="Ramco_LGX_interfaces.CustomValidator,Ramco-LGX_interfaces" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />

</system.serviceModel>

CustomValidator:

public class CustomValidator : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
if (null == userName || null == password)
{
throw new ArgumentNullException();
}


if (!AuthenticateUser(userName, password))
throw new SecurityTokenValidationException("Invalid Service Credentials");
else
{
// do nothing - they're good
}
}
public bool AuthenticateUser(string userName, string password)
{
if (userName != ConfigurationManager.AppSettings["SSLUserName"].ToString() || password != ConfigurationManager.AppSettings["SSLPassword"].ToString())
{
return false;
}
else
{
return true;
}
}
}

in IIS  Enabled "Basic" Authentication 

When i test this in SOAP UI with lgxitadmin/lgxadmin$123 credentials as configured in Config file am getting below error

Getting below error;

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<s:Fault>
<faultcode xmlns:a="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">a:InvalidSecurity</faultcode>
<faultstring xml:lang="en-AU">An error occurred when verifying security for the message.</faultstring>
</s:Fault>
</s:Body>
</s:Envelope>

Thanks in advance. 

Kindly support on this

Regards

Raghu

Get Datatable from WCF Data Service

$
0
0

Hello

I have created WCF Data Service using WF6. my question is how can i get data in datatable from EF. I know it does not return datatable straight a way. i am looking for which shows how to acheive it.i came across below link but i am not sure how to use it. 

https://stackoverflow.com/questions/10254272/execute-stored-procedure-in-entity-framework-return-listdatatable-or-dataset

IEnumerable<SqlParameter> parameters = new List<SqlParameter>() { 1, 0, 0 };


                using (var ctx = new RContext())
                {
                    ExecuteStoredProcedure(context, Constants.GetApplicationPrimaryUrl, parameters);


                }

  public static DataTable ExecuteStoredProcedure(ObjectContext db, string storedProcedureName, IEnumerable<SqlParameter> parameters)
        {
            var connectionString = ((EntityConnection)db.Connection).StoreConnection.ConnectionString;
            var ds = new DataTable();

            using (var conn = new SqlConnection(connectionString))
            {
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = storedProcedureName;
                    cmd.CommandType = CommandType.StoredProcedure;
                    foreach (var parameter in parameters)
                    {
                        cmd.Parameters.Add(parameter);
                    }

                    using (var adapter = new SqlDataAdapter(cmd))
                    {
                        adapter.Fill(ds);
                    }
                }
            }

            return ds;
        }

How to avoid null value property class property from Json Serialization

$
0
0

I am creating a webservice using asp.net 4.0.

I have created a asmx file and creating a User.cs Class. It has 8 Properties. I have return a service with json format. If the userlogin is true i need to return all the properties of user.cs, if it's fail i need to return only 2 property.

How to achieve it.

User login is true. It will return all

{"message":"valid user","BranchId":1,"BranchName":"My branch Name","Id":1,"Name":"admin","Password":"admin","RoleId":1,"Status":1}

User login is failed i need to return only message and Status. but it will return all like as follows

{"message":"username or password is invalid","BranchId":0,"BranchName":null,"Id":0,"Name":null,"Password":null,"RoleId":0,"Status":0}

My properties like this

/ Properties
    public int BranchId
    {
        get { return _BranchId; }
        set { if (_BranchId != value) { _BranchId = value; } }
    }

    public string BranchName
    {
        get { return _BranchName; }
        set { _BranchName = value; }
    }

    private String _message;

    public String message
    {
        get { return _message; }
        set { _message = value; }
    }

My service.asmx

[WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public void appLogin(String userName, String passWord)
    {
        Admin_AppUserBLL objusr = Admin_AppUserBLL.GetAdmin_AppUserBLL(userName);
        string strResponse = "";
        if (objusr != null)
        {
            if (objusr.Password == passWord)
            {
                objusr.message = "valid username";
                strResponse = new JavaScriptSerializer().Serialize(objusr);
            }
        }
        else
        {
            objusr = new Admin_AppUserBLL();
            objusr.message = "username or password is invalid";
            strResponse = new JavaScriptSerializer().Serialize(objusr);
        }
        Context.Response.Clear();
        Context.Response.ContentType = "application/json";
        Context.Response.AddHeader("content-length", strResponse.Length.ToString());
        Context.Response.Flush();
        Context.Response.Write(strResponse);
    }


IIS Thread Usage for WCF and Db Connections

$
0
0
<div class="container"> <div class="body">

I am running a rest interface(using ApiController class) using the ASP.NET 4.6 and IIS 7.5.   The rest interfaces are making a WCF asynch call out to a web service to log all the incoming and outgoing request and response strings for tracking purposes.  The C# code is accessing an Oracle database using the ODP.net 4.112.3.0.

Under normal load everything works fine on the site in production.  However, when a huge spike in traffic comes (14k requests within 10 minutes) we start to see long response times from the initial request/response logging web service we have and then we see database timeouts.  The database team sees no connection issues on the db server.  I know the async logging WCF calls get pushed to the CLR threads to be run.  My question is are the threads in IIS that are being used to make the outbound wcf asynch web service call the same threads that are used to access the database and thus causing the database timeouts?  If so how can I determine what the max threads are on each machine and how to optimize the usage of the threads?

</div> </div>

WebService Question

$
0
0

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{

This is code from my Consumer app. It doesn't like "local host" - could not be found. Can you help?

    class Program
    {
        static void Main(string[] args)
        {
            localhost.Service1 myMathService = new localhost.Service1();
            Console.Write("2 + 4 = {0}", myMathService.Add(2, 4));
        }
    }
}
*************************************************** Producer ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace MathService
{
    /// <summary>
    /// Summary description for WebService1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [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]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public int Add(int a, int b)
        {
            return (a + b);
        }

        [WebMethod]
        public System.Single Subtract(System.Single A, System.Single B)
        {
            return (A - B);
        }

        [WebMethod]
        public System.Single Multiply(System.Single A, System.Single B)
        {
            return A * B;
        }

        [WebMethod]
        public System.Single Divide(System.Single A, System.Single B)
        {
            if (B == 0)
                return -1;
            return Convert.ToSingle(A / B);
        }
    
    }
}

How do I make the DocumentContent element NotNullable

$
0
0

How do I make the DocumentContent element NotNullable please ?  minOccurs="1" maxOccurs="1" ?

 



.asmx webservice calling a wcf webservice

$
0
0

I just recently modified a WCF service and added two fields to the returning result set.   One of the new fields is an integer the other a string,  The WCF Service  is hosted in IIS  as a  website. when I invoke the service from a browser it works fine. 

In this solution there is  a .asxm service that is calls  the  WCF service . When I run it I get the following error

 System.ArgumentException: Encountered unexpected namespace 'http://schemas.datacontract.org/DataAccessLayer.Entities'The namespace must be empty.Parameter name: ns

I then  changed the WCF service to remove one of the new parameters  the string variable and recompiled it . it worked when called from the .asmx and .wcf service. I then changed the service to return a string rather than an integer  and  yet again failed. The old resultset from the service does have string and numeric results and it also works along with the new field when it is an integer but not a string!

My Question is there something that I need to do to link the WSDL result set to what the .asxm is expecting so it can return a json result set?

Can anyone help me understand how I could do this without needing the .asxm service I want to return a return json from my WCF Service.

This is the code in the .asmx file that is calling the WCF Service . The error occurs when it hits statement   serializer.WriteObject(ms, d);

public string GetCourseRosterDetailByRosterId(int rosterId)
    {
        Services cmService = new Services();
        VEnterpriseCourseRosterDetail[] d = cmService.GetCourseRosterDetailByRosterId(rosterId);
        if (d != null)
        {
            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(d.GetType());
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            serializer.WriteObject(ms, d);
            return System.Text.Encoding.Default.GetString(ms.ToArray());
        }
        else
            return string.Empty;
    }

Consuming Web Service with SSL .p12 cert

$
0
0

Hello to all

I have a c# .net client that consumes a web service that uses a .p12 cert, but yesterday started to send a "Could not establish a trust relationship for the SSL/TLS secure channel" message, it had been working fine 2 years with the code:

                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

public bool AcceptAllCertifications(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        } 

Has something change about accepting all kind of certs?

(Note: I have no problem consuming it with ApacheJmeter or Java client)

I apreciate your help

transfer large amount of data using WCF service

$
0
0

Hi,

I have WCF service to read large amount of data from database, based on searching between 2 dates.

i can execute the query from the sql server without any problems with response time maximum 10-15 seconds (about 10,000) records.

but when call it from the service it gives time out. any suggestions

?

ASMX [WebMethod] - How to accept multiple document

$
0
0

Hi there,

My schema has  “Documents” element it should contain the “Document” element which should consist of SeqNumber, DocumentId, DocumentType, DocumentContent.

 

 

I am at the moment able to send a single file, but what I need is to send multiple documents.

How do I declare the Documents variable so I’m able to accept more than one document. ?

 


Serialization IEnumerable in WCF

$
0
0

Hi

I Knew that when I serialize IEnumerable  in wcf is not posible since IEnumerable can't be serialized since it is a interface., so many years ago I obtained the error:

Cannot serialize member :

https://stackoverflow.com/questions/15925060/how-to-use-datamember-for-ienumerablestring-for-property-in-wcf

Now, the wcf returns an "ienumerable" and it doesn't return error..

My method is: ver()

public CompositeType1 ver()     {         return new CompositeType1 { ver = ver1() };     }     public IEnumerable<int> ver1()     {          var x = new List<int>()         {             1,             2,             3         };         return x;     }

And it returns an ienumerable without errors... I suppose that Microsoft fixed after VS 2013.

Send a logical signed xml file to a Web Service.

$
0
0

Hi there! I am trying to consume a Web Service to send a xml file signed with EMPRESA.PFX 
I am doing this with vb.net and C# (Visual Studio 2010). As you will see, I tried two approachs: both - sadly - fail.
Would you please lend a hand?

Thanks a lot from now.
   Ruben

    Private Sub SendWSToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EnviarWSToolStripMenuItem.Click
        Dim wsSOBRE As New WsTest.WS_eFacturaSoapPortClient
        Dim DatosRecibidos As New WsTest.Data
        Dim Datos_a_Enviar As New WsTest.Data

        Dim vari As String
        Dim SOBRE_cCFE As String = "SignedFile.xlm"

        Dim ClaveDelCertificado As String = "Prueba.01"
        Dim certPath = Path.Combine("C:\Users\", "EMPRESA.pfx") ' indicate where to find the certificate

        Dim newFile As StringBuilder = New StringBuilder()
        Dim campo() As String = File.ReadAllLines(SOBRE_cCFE)

        For Each item As String In campo
            newFile.Append(item + "\n") ' save the line adding LF -> 0x0A
        Next
        vari = newFile.ToString()

        Datos_a_Enviar.xmlData = vari

       Dim certificate As New X509Certificate2(certPath, ClaveDelCertificado, X509KeyStorageFlags.Exportable Or X509KeyStorageFlags.PersistKeySet)
        Dim executeCall As New eDocums.WsTest.WS_eFacturaSoapPortClient("EFACRECEPCIONSOBRE")

        executeCall.ClientCredentials.ClientCertificate.Certificate = certificate
        wsSOBRE.ClientCredentials.ClientCertificate.Certificate = certificate

        Try
            DatosRecibidos = wsSOBRE.EFACRECEPCIONSOBRE(Datos_a_Enviar)
            executeCall.EFACRECEPCIONSOBRE(Datos_a_Enviar)

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

    End Sub

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

Best authentication option for asmx based web service

$
0
0

tell me Best authentication option for asmx based web service for variety of clients and technology who can consume my web service.

we know we can implement form authentication in asmx based web service but i like to know if we implement form authentication in asmx based web service then other client developed with java,pythin etc can use my web service?

looking for some guidance for old legacy asmx based web service.

Create a windows service to read email body from *.msg file using c#

$
0
0

Hi All,

        Could you please give any reference and link or logic to create a windows service which can read email body from the emails which are saved in a windows directory using c#.

Thanks

Viewing all 555 articles
Browse latest View live