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

What are the unmanaged resources used in WCF?

$
0
0

In WCF we use close() and Abort().

Are these used to dispose the objects?

If so, there should be using of some unmanaged resources. What are they?

In asmx we don't use like this closing. So what is the difference in implementations? I mean WCF is a developed version of asmx to support multiple protocols right?

Then why asmx is not needed to be closed and WCF should be.


Call oracle web service from WCF Service

$
0
0

I need to call an oracle web service from WCF service.

what is the necessary configurations?

deploy wcf service on a different server and consume it from ajax, jquery controls

$
0
0

i have created a wcf ret service using VS 2013/ using ,net 4.5  fw.  which connects to a sql db and fetch records.

now i need to deploy this wcf service onto a  different server with a different port number [other than 80 ] and consume it from ajax  jquery html controls.

 wcf1

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

namespace NPDWCFService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "NPDRESTService" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select NPDRESTService.svc or NPDRESTService.svc.cs at the Solution Explorer and start debugging.
    public class NPDRESTService : INPDRESTService
    {
        private static string strConn;
        public void DoWork()
        {
        }

        //public string GetProducts(string ProductId)
        //{
        //    return "get all products with product id  " + ProductId + " was successful";
        //}


       static string strConn1 = @"Data Source=srv1;Initial Catalog=Products;Integrated Security=True";

        public List<Product> GetAllProducts()
        {
            var productList = new List<Product>();

            SqlDataReader reader = null;
            SqlConnection myConnection = new SqlConnection();

            Product objallproducts = new Product();
            //Server = myServerAddress; Database = myDataBase; User Id = myUsername;      Password = myPassword;



            myConnection.ConnectionString = strConn1;

            SqlCommand sqlCmd = new SqlCommand();
            sqlCmd.CommandType = CommandType.Text;
            sqlCmd.CommandText = "Select * from tblProducts"; // where ProductId=" + id + "";
            sqlCmd.Connection = myConnection;
            myConnection.Open();
            reader = sqlCmd.ExecuteReader();
            Product prodd = null;
            while (reader.Read())
            {
                prodd = new Product();
                prodd.ProductID = Convert.ToInt32(reader.GetValue(0));
                prodd.ProductName = reader.GetValue(1).ToString();
                prodd.ProductCategory = reader.GetValue(2).ToString();
                prodd.Price = Convert.ToInt32(reader.GetValue(3));

                productList.Add(prodd);
            }
            // return prodd;


            myConnection.Close();

            return productList;
            //Code logic to get all students.
        }

i have created a website from iis and given this url in the publish --> web deploy --> destination url as :  http://localhost:8089/

Webservice connection via a load balancer

$
0
0

My (Excel) VSTO (vb.Net) application contains a webservice connection that has to connect to a webservice located behind a load balancer (Big IP)

My understanding of a webservice in a VSTO is that it connects over the passed in url e.g.  https://servername/application.asmx

and the webservice returns a wsdl file in which there is a node <soap:address location = "http://servername/application.asmx"/>

i.e. the returned url uses http, instead of https.  It is this returned address that the client side vsto uses to continue communication and because it does not have the https prefix the subsequent communication fails.

One solution is to add a re-write rule to the load balancer that replaces all occurrences of http://servername with https://servername in the wsdl.  This was quite easy with the BoostEdge load balancer, but not so easy in the Big IP load balancer.  Any suggestions on how to write the rule in a Big IP load balancer gratefully received.

However I would like to know if there are any alternatives to putting a re-write rule in the load balancer. For example is there a way of specifying a relative address instead of an absolute one in a VSTO webservice?

Does anyone have any experience of getting around the issue of a load balancer returning http instead of https?

Connect ESB with Asp.net Resfull Service

$
0
0

hi 

I  need to know about how to intergrate with ESB to asp.net restfull service there any sample could you tell me how to do ?

Thanks

kandee

exposing limited methods via diffrent endpoints ?

$
0
0

I have a WCF service, Which has 5 methods
I want to expose 3 methods using an endpoint and remaining 2 method using different endpoint. 
is it possible without moving them to a different class?

Problem with Security header in wsdl

$
0
0
Hi
I have to make a client for a WSDL. But I keep getting a "No Security header in message but required by policy."

Here is my code

USImportoerService service = new USImportoerService();
X509Certificate2 cert = new X509Certificate2(certPath, PASSWORD, X509KeyStorageFlags.MachineKeySet);

service.ClientCertificates.Add(cert);

var result = ser.getUSKoeretoej();

And heres the App.config

<configuration>
<system.serviceModel>
<bindings>
<customBinding>
<binding name="USImportoerService_Port">
<security authenticationMode="CertificateOverTransport" securityHeaderLayout="LaxTimestampLast" includeTimestamp="true"
enableUnsecuredResponse="true">
</security>
<textMessageEncoding messageVersion="Soap11" />
<httpsTransport />
</binding>
</customBinding>
</bindings>
<client>
<endpoint address="HTTPS TO WSDL"
binding="customBinding" bindingConfiguration="USImportoerService_Port"

Getting Error while seraching a text in my website using Bing Search

$
0
0

Hi Guys,

I have implemented a Bing serach API in my mvc application to search a text in my own website .
But after passing the text it is giving error . 

system.Data.Services.client.DataServiceueryEception occurred in System.Data.Services.client.dll 
but was not handelled in user code.

I m sure this error is coming because I have missed some thing to pass .

Please help .

Thanks


How to consume an XML file in WCF

$
0
0

a client want to send me and XML file and I want to create a service and parse the XML to a database. I am looking from a tutorial. Any ideas?

XSD to WSDL Conversion

$
0
0

Dear All - I need to convert XSD to WSDL, is there any utility available ? Further and what is the best way to consume XSD type web services in WCF 2015. 

I am in a situation our two clients have web services and one in SOAP (WSDL) and other in XSD, we need to prepare a web service that will act as a bridge between our desktop application and customer service. In our webservice we need to consume both web services WSDL and XSD, would you please what is the best way to do it please.

Br.TAM

Consume SOAP and sending response back as Rest in C#

$
0
0

I am working with .net 4.5 C# project. I am consuming SOAP service and then response back them to with REST with SharePoint 2013.

But the issue is part of SOAP response is not parsing as XML but as string. I don't know what I am doing wrong.

Screen marked part parsing as string not XML

Code for Consuming SOAP

public HttpWebRequest CreateWebRequest(string URL)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@"" + URL);
webRequest.Headers.Add(@"SOAP:Action");
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}

public string ConsumeSOAP(string XML, string URL)
{
HttpWebRequest request = CreateWebRequest(URL);
XmlDocument soapEnvelopeXml = new XmlDocument();
soapEnvelopeXml.LoadXml(@"" + XML);

using (Stream stream = request.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
using (WebResponse response = request.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
string soapResult = rd.ReadToEnd();
return soapResult;
}
}
}



Code for SOAP response to REST

public string doLogin(string memberId, string password)
{
string XML = null;
try
{
SOAPService soap = new SOAPService();
XNamespace ns = @"http://schemas.xmlsoap.org/soap/envelope/";

string URL = URL;
string User = User;
string Password = Password;

string authenticateXML = string.Format(@"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:web=""http://webservices.xxx.xxx.com/""><soapenv:Header><web:header><passWord>{0}</passWord><userName>{1}</userName></web:header></soapenv:Header><soapenv:Body><web:authenticate><authenticateRequest><password>{2}</password><username>{3}</username></authenticateRequest></web:authenticate></soapenv:Body></soapenv:Envelope>", Password, User, password, memberId);

string authenticateResponse = soap.ConsumeSOAP(authenticateXML, URL);
var authenticateResponseValue = XDocument.Parse(authenticateResponse);
XML = authenticateResponseValue.Descendants((XNamespace)"http://schemas.xmlsoap.org/soap/envelope/" + "Body").First().FirstNode.ToString();
}
catch
{

}
return XML;
}



Interface for the REST

[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "/doLogin?memberId={memberId}&password={password}")]
string doLogin(string memberId, string password);




[1]: https://i.stack.imgur.com/na54O.png

Web Service open browser??

$
0
0

I pass a parcel ID number to my web service and it returns a list of property photos for that property. Is it possible to have the web service open a web browser to display the pictures? VB.NET. When I run the web service locally on my PC, I can get a browser to open a browser and it displays the pictures. When I publish web service to our web server, I get the list of pictures, but I can't get a browser to open to display the pictures.

WCF SOAP Service with .net 4.5

$
0
0

I have created very simple soap service and it is working good but I want to add some attributes to the soap envelop My Code

Interface

namespace SOAPService
{
[ServiceContract]
public interface IService
{
[OperationContract]
double AddNumbers(double number1, double number2);
}
}

svc code

namespace SOAPService
{

public class Service : IService
{
public double AddNumbers(double number1, double number2)
{
double result = number1 + number2;
return result;
}
}
}

When open request in SOAPUI It looks like

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/"><soapenv:Header/><soapenv:Body><tem:AddNumbers><!--Optional:--><tem:number1>1</tem:number1><!--Optional:--><tem:number2>1</tem:number2></tem:AddNumbers></soapenv:Body></soapenv:Envelope>



But I was looking output like this

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xmlns:xsd="http://www.w3.org/1999/XMLScheme><soapenv:Header/><soapenv:Body><tem:AddNumbers><!--Optional:--><tem:number1>1</tem:number1><!--Optional:--><tem:number2>1</tem:number2></tem:AddNumbers></soapenv:Body></soapenv:Envelope>



How can I add those xmlns:xsi and xmlns:xsd attributes

Class Sending and Retrieving Data From Web Service; Integrating With QuickBooks

$
0
0

Hello all,

 I am new to learning about web services and have read most of the walkthroughs provided by msdn, but I am still unclear about some issues and would like to get some advice on others.

 First off: I am integrating an ecommerce application I wrote in C# with Asp.net 2.0.  This application stores products in a SQL database, simple enough.  Now here comes the issues I have.  I would like to update the product inventory via a Quickbooks POS system and if their is price changes, adjust the price change.  Quickbooks using a program called Quickbooks Web Connector as the go between.  You create a webservice add it to the Web Connector application that resides on the POS machine, and the web connector sends a request to the web service every so often (the interval is user defined), and then if the web service has any request xml, it sends it out at the time.

 The walkthroughs kind of explain services in reverse, and I have been searching the internet looking for a sample application that would truly show how to do this.  My first question is how to send a request via SOAP when the Web Connector sends for requests for the product inventory.   I am looking for maybe sample coding that can be analyzed.. here is the web service coding sample provided by QuickBooks...

 

//
// QuickBooks Web Connector Sample: WCWebService
// Copyright (c) 2006-2007 Intuit, Inc
//
// This sample is a C# ASP.NET web service application that
// communicates with QuickBooks Point of Sale via QBWebConnector. The
// sample focuses primarily on demonstrating how to setup all web service
// web methods to run against QBWebConnector and does not focus on any
// particular use case. For simplicity, it sends three request XMLs:
// CustomerQuery, ItenInventoryQuery and PurchaseOrderQuery.
//
// This sample assumes that you have configured IIS with ASP.NET and
// have a functional system to deploy this web service sample. If you have
// not yet configured ASP.NET with IIS, you may need to run the
// following command from c:\windows\Microsoft.NET\Framework\
// your_asp_dot_net_version path: -
// aspnet_regiis /i
// This will help avoid the occasional message from microsoft development
// environment such as "VS.NET has detected that the specified web server
// is not running ASP.NET version 1.1. You will be unable to run ASP.NET
// web applications or services)".


/*
 * Useful note about using OwnerID and FileID in a real-world application
 *
 * As part of your QB Web Connector configuration (.QWC) file, you include
 * OwnerID and FileID. Following note on these two parameters may be useful.
 *
 * OwnerID -- this is a GUID that represents your application or suite of
 * applications, if your application needs to store private data in the
 * company file for one reason or another (one of the most common cases
 * being to check if you have communicated with this company file before,
 * and possibly some data about that communication) that private data will
 * be visible to any application that knows the OwnerID.
 *
 * FileID -- this is a GUID we stamp in the file on your behalf
 * (using your OwnerID) as a private data extension to the "Company" object.
 * It allows an application to verify that the company file it is exchanging
 * data with is consistent over time (by doing a CompanyQuery with the field
 * set appropriately and reading the DataExtRet values returned.
 *
 * */


using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
using System.IO;
using System.Security.Cryptography;
using Microsoft.Win32;
using System.Xml;
using System.Text.RegularExpressions;


namespace QWCPOSWebService
{
    /// <summary>
    ///  Web Service Namespace="http://developer.intuit.com/",
    ///  Web Service Name="QWCPOSWebService",
    ///  Web Service Description="Sample WebService in ASP.NET to
    ///  demonstrate QBWebConnector with QuickBooks POS
    /// </summary>
    [WebService(
         Namespace = "http://developer.intuit.com/",
         Name = "QWCPOSWebService",
         Description = "Sample WebService in ASP.NET to demonstrate " +"QBWebConnector with QuickBooks POS")]


    // Important Note:
    // You should keep the namespace as http://developer.intuit.com/ for all web
    // services that communicates with QuickBooks Web Connector.




    public class QWCPOSWebService : System.Web.Services.WebService
    {
        #region GlobalVariables
        System.Diagnostics.EventLog evLog = new System.Diagnostics.EventLog();
        public int count = 0;
        public ArrayList req = new ArrayList();
        #endregion


        #region Constructor
        public QWCPOSWebService()
        {
            //CODEGEN: This call is required by the ASP.NET
            //Web Services Designer
            InitializeComponent();
            // Initializing EventLog for logging
            initEvLog();
        }
        #endregion


        #region AutoGeneratedMethods
        //Required by the Web Services Designer
        private IContainer components = null;


        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
        }


        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing && components != null)
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }


        #endregion


        #region WebMethods
        [WebMethod]
        /// <summary>
        /// WebMethod# 1 - clientVersion()
        /// To enable web service with QBWC version control
        /// Signature: public string clientVersion(string strVersion)
        ///
        /// IN:
        /// string strVersion
        ///
        /// OUT:
        /// string errorOrWarning
        /// Possible values:
        /// string retVal
        /// - NULL or <emptyString> = QBWC will let the web service update
        /// - "E:<any text>" = popup ERROR dialog with <any text>
        /// - abort update and force download of new QBWC.
        /// - "W:<any text>" = popup WARNING dialog with <any text>
        /// - choice to user, continue update or not.
        /// </summary>
        public string clientVersion(string strVersion)
        {
            string evLogTxt = "WebMethod: clientVersion() has been called " +"by QBWebconnector" + "\r\n\r\n";
            evLogTxt = evLogTxt + "Parameters received:\r\n";
            evLogTxt = evLogTxt + "string strVersion = " + strVersion + "\r\n";
            evLogTxt = evLogTxt + "\r\n";


            string retVal = null;
            double recommendedVersion = 1.5;
            double supportedMinVersion = 1.0;
            double suppliedVersion = Convert.ToDouble(this.parseForVersion(strVersion));
            evLogTxt = evLogTxt + "QBWebConnector version = " + strVersion + "\r\n";
            evLogTxt = evLogTxt + "Recommended Version = " + recommendedVersion.ToString() + "\r\n";
            evLogTxt = evLogTxt + "Supported Minimum Version = " + supportedMinVersion.ToString() + "\r\n";
            evLogTxt = evLogTxt + "SuppliedVersion = " + suppliedVersion.ToString() + "\r\n";
            if (suppliedVersion < recommendedVersion)
            {
                retVal = "W:We recommend that you upgrade your QBWebConnector";
            }
            else if (suppliedVersion < supportedMinVersion)
            {
                retVal = "E:You need to upgrade your QBWebConnector";
            }
            evLogTxt = evLogTxt + "\r\n";
            evLogTxt = evLogTxt + "Return values: " + "\r\n";
            evLogTxt = evLogTxt + "string retVal = " + retVal;
            logEvent(evLogTxt);
            return retVal;
        }




        [WebMethod]
        /// <summary>
        /// WebMethod# 2 - authenticate()
        /// To verify username and password for the web connector that is trying to connect
        /// Signature: public string[] authenticate(string strUserName, string strPassword)
        ///
        /// IN:
        /// string strUserName
        /// string strPassword
        ///
        /// OUT:
        /// string[] authReturn
        /// Possible values:
        /// string[0] = ticket
        /// string[1]
        /// - empty string = use current company file
        /// - "none" = no further request/no further action required
        /// - "nvu" = not valid user
        /// - any other string value = use this company file
        /// </summary>
        public string[] authenticate(string strUserName, string strPassword)
        {
            string evLogTxt = "WebMethod: authenticate() has been called by QBWebconnector" + "\r\n\r\n";
            evLogTxt = evLogTxt + "Parameters received:\r\n";
            evLogTxt = evLogTxt + "string strUserName = " + strUserName + "\r\n";
            evLogTxt = evLogTxt + "string strPassword = " + strPassword + "\r\n";
            evLogTxt = evLogTxt + "\r\n";




            string[] authReturn = new string[2];
            // Code below uses a random GUID to use as session ticket
            // An example of a GUID is {85B41BEE-5CD9-427a-A61B-83964F1EB426}
            authReturn[0] = System.Guid.NewGuid().ToString();


            // For simplicity of sample, a hardcoded username/password is used.
            // In real world, you should handle authentication in using a standard way.
            // For example, you could validate the username/password against an LDAP
            // or a directory server
            string pwd = "password";
            evLogTxt = evLogTxt + "Password locally stored = " + pwd + "\r\n";
            if (strUserName.ToUpper().Trim().Equals("USERNAME") && strPassword.ToUpper().Trim().Equals(pwd.ToUpper()))
            {
                // An empty string for authReturn[1] means asking QBWebConnector
                // to connect to the company file that is currently openned in QB
                authReturn[1] = "Company Data=IqbalStore";
            }
            else
            {
                authReturn[1] = "nvu";
            }
            // You could also return "none" to indicate there is no work to do
            // or a company filename in the format C:\full\path\to\company.qbw
            // based on your program logic and requirements.


            evLogTxt = evLogTxt + "\r\n";
            evLogTxt = evLogTxt + "Return values: " + "\r\n";
            evLogTxt = evLogTxt + "string[] authReturn[0] = " + authReturn[0].ToString() + "\r\n";
            evLogTxt = evLogTxt + "string[] authReturn[1] = " + authReturn[1].ToString();
            logEvent(evLogTxt);
            return authReturn;
        }




        [WebMethod(Description = "This web method facilitates web service to handle connection errors between QuickBooks and QBWebConnector", EnableSession = true)]
        /// <summary>
        /// WebMethod# 3 - connectionError()
        /// To facilitate capturing of QuickBooks error and notifying it to web services
        /// Signature: public string connectionError (string ticket, string hresult, string message)
        ///
        /// IN:
        /// string ticket = A GUID based ticket string to maintain identity of QBWebConnector
        /// string hresult = An HRESULT value thrown by QuickBooks when trying to make connection
        /// string message = An error message corresponding to the HRESULT
        ///
        /// OUT:
        /// string retVal
        /// Possible values:
        /// - “done” = no further action required from QBWebConnector
        /// - any other string value = use this name for company file
        /// </summary>
        public string connectionError(string ticket, string hresult, string message)
        {
            if (Session["ce_counter"] == null)
            {
                Session["ce_counter"] = 0;
            }


            string evLogTxt = "WebMethod: connectionError() has been called by QBWebconnector" + "\r\n\r\n";
            evLogTxt = evLogTxt + "Parameters received:\r\n";
            evLogTxt = evLogTxt + "string ticket = " + ticket + "\r\n";
            evLogTxt = evLogTxt + "string hresult = " + hresult + "\r\n";
            evLogTxt = evLogTxt + "string message = " + message + "\r\n";
            evLogTxt = evLogTxt + "\r\n";


            string retVal = null;
            //-2147418113 = Can't connect to the database
            const string CANT_CONNECT_TO_DB = "0x8000FFFF";
            // Add more as you need...


            if (hresult.Trim().Equals(CANT_CONNECT_TO_DB))
            {
                evLogTxt = evLogTxt + "HRESULT = " + hresult + "\r\n";
                evLogTxt = evLogTxt + "Message = " + message + "\r\n";
                retVal = "DONE";
            }
            else
            {
                // Depending on various hresults return different value
                if ((int)Session["ce_counter"] == 0)
                {
                    // Try again with this company file
                    evLogTxt = evLogTxt + "HRESULT = " + hresult + "\r\n";
                    evLogTxt = evLogTxt + "Message = " + message + "\r\n";
                    evLogTxt = evLogTxt + "Sending connection string as \"Company Data=\" to QBWebConnector.";
                    retVal = "Company Data=";
                }
                else
                {
                    evLogTxt = evLogTxt + "HRESULT = " + hresult + "\r\n";
                    evLogTxt = evLogTxt + "Message = " + message + "\r\n";
                    evLogTxt = evLogTxt + "Sending DONE to stop.";
                    retVal = "DONE";
                }
            }
            evLogTxt = evLogTxt + "\r\n";
            evLogTxt = evLogTxt + "Return values: " + "\r\n";
            evLogTxt = evLogTxt + "string retVal = " + retVal + "\r\n";
            logEvent(evLogTxt);
            Session["ce_counter"] = ((int)Session["ce_counter"]) + 1;
            return retVal;
        }




        [WebMethod(Description = "This web method facilitates web service to send request XML to QuickBooks via QBWebConnector", EnableSession = true)]
        /// <summary>
        /// WebMethod# 4 - sendRequestXML()
        /// Signature: public string sendRequestXML(string ticket, string strHCPResponse, string strCompanyFileName,
        /// string Country, int qbXMLMajorVers, int qbXMLMinorVers)
        ///
        /// IN:
        /// int qbXMLMajorVers
        /// int qbXMLMinorVers
        /// string ticket
        /// string strHCPResponse
        /// string strCompanyFileName
        /// string Country
        /// int qbXMLMajorVers
        /// int qbXMLMinorVers
        ///
        /// OUT:
        /// string request
        /// Possible values:
        /// - “any_string” = Request XML for QBWebConnector to process
        /// - "" = No more request XML
        /// </summary>
        public string sendRequestXML(string ticket, string strHCPResponse, string strCompanyFileName,
            string qbXMLCountry, int qbXMLMajorVers, int qbXMLMinorVers)
        {
            if (Session["counter"] == null)
            {
                Session["counter"] = 0;
            }
            string evLogTxt = "WebMethod: sendRequestXML() has been called by QBWebconnector" + "\r\n\r\n";
            evLogTxt = evLogTxt + "Parameters received:\r\n";
            evLogTxt = evLogTxt + "string ticket = " + ticket + "\r\n";
            evLogTxt = evLogTxt + "string strHCPResponse = " + strHCPResponse + "\r\n";
            evLogTxt = evLogTxt + "string strCompanyFileName = " + strCompanyFileName + "\r\n";
            evLogTxt = evLogTxt + "string qbXMLCountry = " + qbXMLCountry + "\r\n";
            evLogTxt = evLogTxt + "int qbXMLMajorVers = " + qbXMLMajorVers.ToString() + "\r\n";
            evLogTxt = evLogTxt + "int qbXMLMinorVers = " + qbXMLMinorVers.ToString() + "\r\n";
            evLogTxt = evLogTxt + "\r\n";


            ArrayList req = buildRequest();
            string request = "";
            int total = req.Count;
            count = Convert.ToInt32(Session["counter"]);


            if (count < total)
            {
                request = req[count].ToString();
                evLogTxt = evLogTxt + "sending request no = " + (count + 1) + "\r\n";
                Session["counter"] = ((int)Session["counter"]) + 1;
            }
            else
            {
                count = 0;
                Session["counter"] = 0;
                request = "";
            }
            evLogTxt = evLogTxt + "\r\n";
            evLogTxt = evLogTxt + "Return values: " + "\r\n";
            evLogTxt = evLogTxt + "string request = " + request + "\r\n";
            logEvent(evLogTxt);
            return request;
        }




        [WebMethod(Description = "This web method facilitates web service to receive response XML from QuickBooks via QBWebConnector", EnableSession = true)]
        /// <summary>
        /// WebMethod# 5 - receiveResponseXML()
        /// Signature: public int receiveResponseXML(string ticket, string response, string hresult, string message)
        ///
        /// IN:
        /// string ticket
        /// string response
        /// string hresult
        /// string message
        ///
        /// OUT:
        /// int retVal
        /// Greater than zero  = There are more request to send
        /// 100 = Done. no more request to send
        /// Less than zero  = Custom Error codes
        /// </summary>
        public int receiveResponseXML(string ticket, string response, string hresult, string message)
        {
            string evLogTxt = "WebMethod: receiveResponseXML() has been called by QBWebconnector" + "\r\n\r\n";
            evLogTxt = evLogTxt + "Parameters received:\r\n";
            evLogTxt = evLogTxt + "string ticket = " + ticket + "\r\n";
            evLogTxt = evLogTxt + "string response = " + response + "\r\n";
            evLogTxt = evLogTxt + "string hresult = " + hresult + "\r\n";
            evLogTxt = evLogTxt + "string message = " + message + "\r\n";
            evLogTxt = evLogTxt + "\r\n";


            int retVal = 0;
            if (!hresult.ToString().Equals(""))
            {
                // if there is an error with response received, web service could also return a -ve int

                evLogTxt = evLogTxt + "HRESULT = " + hresult + "\r\n";
                evLogTxt = evLogTxt + "Message = " + message + "\r\n";
                retVal = -101;
            }
            else
            {
                evLogTxt = evLogTxt + "Length of response received = " + response.Length + "\r\n";


                ArrayList req = buildRequest();
                int total = req.Count;
                int count = Convert.ToInt32(Session["counter"]);


                int percentage = (count * 100) / total;
                if (percentage >= 100)
                {
                    count = 0;
                    Session["counter"] = 0;
                }
                retVal = percentage;
            }
            evLogTxt = evLogTxt + "\r\n";
            evLogTxt = evLogTxt + "Return values: " + "\r\n";
            evLogTxt = evLogTxt + "int retVal= " + retVal.ToString() + "\r\n";
            logEvent(evLogTxt);
            return retVal;
        }


        [WebMethod]
        /// <summary>
        /// WebMethod# 6 - getLastError()
        /// Signature: public string getLastError(string ticket)
        ///
        /// IN:
        /// string ticket
        ///
        /// OUT:
        /// string retVal
        /// Possible Values:
        /// Error message describing last web service error
        /// </summary>
        public string getLastError(string ticket)
        {
            string evLogTxt = "WebMethod: getLastError() has been called by QBWebconnector" + "\r\n\r\n";
            evLogTxt = evLogTxt + "Parameters received:\r\n";
            evLogTxt = evLogTxt + "string ticket = " + ticket + "\r\n";
            evLogTxt = evLogTxt + "\r\n";


            int errorCode = 0;
            string retVal = null;
            if (errorCode == -101)
            {
                retVal = "QuickBooks was not running!"; // This is just an example of custom user errors
            }
            else
            {
                retVal = "Error!";
            }
            evLogTxt = evLogTxt + "\r\n";
            evLogTxt = evLogTxt + "Return values: " + "\r\n";
            evLogTxt = evLogTxt + "string retVal= " + retVal + "\r\n";
            logEvent(evLogTxt);
            return retVal;
        }








        [WebMethod]
        /// <summary>
        /// WebMethod# 7 - closeConnection()
        /// At the end of a successful update session, QBWebConnector will call this web method.
        /// Signature: public string closeConnection(string ticket)
        ///
        /// IN:
        /// string ticket
        ///
        /// OUT:
        /// string closeConnection result
        /// </summary>
        public string closeConnection(string ticket)
        {
            string evLogTxt = "WebMethod: closeConnection() has been called by QBWebconnector" + "\r\n\r\n";
            evLogTxt = evLogTxt + "Parameters received:\r\n";
            evLogTxt = evLogTxt + "string ticket = " + ticket + "\r\n";
            evLogTxt = evLogTxt + "\r\n";
            string retVal = null;


            retVal = "OK";


            evLogTxt = evLogTxt + "\r\n";
            evLogTxt = evLogTxt + "Return values: " + "\r\n";
            evLogTxt = evLogTxt + "string retVal= " + retVal + "\r\n";
            logEvent(evLogTxt);
            return retVal;
        }


        #endregion


        #region UtilityMethods
        private void initEvLog()
        {
            try
            {
                string source = "WCWebService";
                if (!System.Diagnostics.EventLog.SourceExists(source))
                    System.Diagnostics.EventLog.CreateEventSource(source, "Application");
                evLog.Source = source;
            }
            catch { };
            return;
        }


        private void logEvent(string logText)
        {
            try
            {
                evLog.WriteEntry(logText);
            }
            catch { };
            return;
        }


        public ArrayList buildRequest()
        {
            string strRequestXML = "";
            XmlDocument inputXMLDoc = null;


            // CustomerQuery
            inputXMLDoc = new XmlDocument();
            inputXMLDoc.AppendChild(inputXMLDoc.CreateXmlDeclaration("1.0", null, null));
            inputXMLDoc.AppendChild(inputXMLDoc.CreateProcessingInstruction("qbposxml", "version=\"1.0\""));


            XmlElement qbposXML = inputXMLDoc.CreateElement("QBPOSXML");
            inputXMLDoc.AppendChild(qbposXML);
            XmlElement qbposXMLMsgsRq = inputXMLDoc.CreateElement("QBPOSXMLMsgsRq");
            qbposXML.AppendChild(qbposXMLMsgsRq);
            qbposXMLMsgsRq.SetAttribute("onError", "stopOnError");
            XmlElement customerQueryRq = inputXMLDoc.CreateElement("CustomerQueryRq");
            qbposXMLMsgsRq.AppendChild(customerQueryRq);
            customerQueryRq.SetAttribute("requestID", "1");
            XmlElement maxReturned = inputXMLDoc.CreateElement("MaxReturned");
            customerQueryRq.AppendChild(maxReturned).InnerText = "1";


            strRequestXML = inputXMLDoc.OuterXml;
            req.Add(strRequestXML);


            // Clean up
            strRequestXML = "";
            inputXMLDoc = null;
            qbposXML = null;
            qbposXMLMsgsRq = null;
            maxReturned = null;


            // ItemInventoryQuery
            inputXMLDoc = new XmlDocument();
            inputXMLDoc.AppendChild(inputXMLDoc.CreateXmlDeclaration("1.0", null, null));
            inputXMLDoc.AppendChild(inputXMLDoc.CreateProcessingInstruction("qbposxml", "version=\"1.0\""));


            qbposXML = inputXMLDoc.CreateElement("QBPOSXML");
            inputXMLDoc.AppendChild(qbposXML);
            qbposXMLMsgsRq = inputXMLDoc.CreateElement("QBPOSXMLMsgsRq");
            qbposXML.AppendChild(qbposXMLMsgsRq);
            qbposXMLMsgsRq.SetAttribute("onError", "stopOnError");
            XmlElement itemInventoryQueryRq = inputXMLDoc.CreateElement("ItemInventoryQueryRq");
            qbposXMLMsgsRq.AppendChild(itemInventoryQueryRq);
            itemInventoryQueryRq.SetAttribute("requestID", "2");
            maxReturned = inputXMLDoc.CreateElement("MaxReturned");
            itemInventoryQueryRq.AppendChild(maxReturned).InnerText = "1";


            strRequestXML = inputXMLDoc.OuterXml;
            req.Add(strRequestXML);


            // Clean up
            strRequestXML = "";
            inputXMLDoc = null;
            qbposXML = null;
            qbposXMLMsgsRq = null;
            maxReturned = null;


            // PurchaseOrderQuery
            inputXMLDoc = new XmlDocument();
            inputXMLDoc.AppendChild(inputXMLDoc.CreateXmlDeclaration("1.0", null, null));
            inputXMLDoc.AppendChild(inputXMLDoc.CreateProcessingInstruction("qbposxml", "version=\"1.0\""));


            qbposXML = inputXMLDoc.CreateElement("QBPOSXML");
            inputXMLDoc.AppendChild(qbposXML);
            qbposXMLMsgsRq = inputXMLDoc.CreateElement("QBPOSXMLMsgsRq");
            qbposXML.AppendChild(qbposXMLMsgsRq);
            qbposXMLMsgsRq.SetAttribute("onError", "stopOnError");
            XmlElement purchaseOrderQueryRq = inputXMLDoc.CreateElement("PurchaseOrderQueryRq");
            qbposXMLMsgsRq.AppendChild(purchaseOrderQueryRq);
            purchaseOrderQueryRq.SetAttribute("requestID", "3");
            maxReturned = inputXMLDoc.CreateElement("MaxReturned");
            purchaseOrderQueryRq.AppendChild(maxReturned).InnerText = "1";


            strRequestXML = inputXMLDoc.OuterXml;
            req.Add(strRequestXML);


            return req;
        }


        private string parseForVersion(string input)
        {
            // This method is created just to parse the first two version components
            // out of the standard four component version number:
            // <Major>.<Minor>.<Release>.<Build>
            //
            // As long as you get the version in right format, you could use
            // any algorithm here.
            string retVal = "";
            string major = "";
            string minor = "";
            Regex version = new Regex(@"^(?\d+)\.(?\d+)(\.\w+){0,2}$", RegexOptions.Compiled);
            Match versionMatch = version.Match(input);
            if (versionMatch.Success)
            {
                major = versionMatch.Result("${major}");
                minor = versionMatch.Result("${minor}");
                retVal = major + "." + minor;
            }
            else
            {
                retVal = input;
            }
            return retVal;
        }
        #endregion
    }
}
 

How to convert Json Date to normal datetime posted from a webservice

$
0
0

Hi there guys, been trying to convert a json date that's been posted on one of the service(handler.ashx file)

i tried using one of the following methods below...

the date comes in one of this format "/Date(1495640387558)/"

i would like to save the date to sql database...

   private DateTime ConvertJsonStringToDateTime(string jsonTime)
    {
        if (!string.IsNullOrEmpty(jsonTime) && jsonTime.IndexOf("Date") > -1)
        {
            string milliSec = jsonTime.Substring(jsonTime.IndexOf("(") + 1);
            string sign = milliSec.IndexOf("+") > -1 ? "+" : "/";
            string hours = milliSec.Substring(milliSec.IndexOf(sign));
            milliSec = milliSec.Substring(0, milliSec.IndexOf(sign));
            hours = milliSec.Substring(0, milliSec.IndexOf(")"));
            return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(Convert.ToInt64(milliSec)).AddHours(Convert.ToInt64(milliSec) / 100);
        }
        return DateTime.Now;
    }

and

 public static DateTime ConvertJsonToDateTime(string microSec)
    {
        long milliSec = (long)(Convert.ToInt64(microSec));
        DateTime startTime = new DateTime(1970, 1, 1);
        TimeSpan time = TimeSpan.FromMilliseconds(milliSec);
        DateTime result = new DateTime(time.Ticks+ startTime.Ticks);
        return result;
    }

kind regards

Tony


Write a generic handler or webservice to handle nested JSON

$
0
0

I have the following JSON and I want to write a generic handler or pagemethod to process this data to sql server. I m stuck here and can't figure it out. please if you could help

how can I map through it. I know that I need a loop but again can't figure it out

I m using ASP/vb.net

{"action": "edit","data": {"2383": {"RecID": 2383,"PtFilenum": "15090248","PrtFilenum": 13090701,"FullName": "saied salem","DOB": "04 Oct 1985","PrtStatus": ""
		},"3387": {"RecID": 3387,"PtFilenum": "15090248","PrtFilenum": 15120996,"FullName": "marwam mohmmad  saleem","DOB": "24 May 2017","PrtStatus": ""
		}
	}
}

post wcf json input AND JSON OUTPUT REMOTE SERVER ERROR

$
0
0

public Status CalculateSelf_Checksum(string empsapid, string wef, string deletionremarks)
{

Status res = new Status();
string result_checksum = string.Empty;
try
{
Status.selfcal obj1 = new Status.selfcal()
{
_s_esapid = empsapid,
_s_wef = wef,
_s_deletionmsg = deletionremarks
};
Functions fobj = new WcfService2.Functions();
result_checksum = fobj.CalculateCheckSumSelfDelete(empsapid, wef, deletionremarks);
DataContractJsonSerializer ser =
new DataContractJsonSerializer(typeof(Status.selfcal));
MemoryStream mem = new MemoryStream();
ser.WriteObject(mem, obj1);

string data =
Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);


System.Net.WebClient webClient = new System.Net.WebClient();
webClient.Headers["Content-type"] = "application/json";
webClient.Encoding = Encoding.UTF8;

string outputJson =
webClient.UploadString("http://localhost:50932/Service2.svc/CalculateSelf_Checksum", "POST", "hh");//SHOWING ERRRO
//Status objStatus = Newtonsoft.Json.JsonConvert.DeserializeObject<Status>(outputJson);


}
catch (Exception ex)
{
string s = ex.Message;
}
return new Status()
{
_esapid = empsapid,
_wef = wef,
_deletionmsg = deletionremarks,
_ReturnChecksum = result_checksum
};
}

windows service and load balancing

$
0
0

Hi, I've started working on windows services lately and I'd like to know some answers to my doubts.

I have a windows service which runs everyday and performs a task. We have load balancer application for our production servers. So basically if one goes down, the other takes over full control until the other one comes back up. We make sure both these servers are in sync all the time. Now I have to set up this windows service, should I configure it on both servers? Will this windows service run on only one server or both servers at scheduled time?

Also, as part of this windows service, a csv file gets processed. This csv file will be uploaded by users from front end application. I have my setup on both servers so files gets uploaded sometimes on server1 and sometimes on server2. Due to this reason, should I configure my windows service on both servers so a correct file gets processed everytime?

All this is little confusing to me as there is very little information or samples of what I am trying to achieve. Currently, I have the service setup on only one server which is always active(has been so far). Sometimes the service gets stopped automatically for no reason.. and I have to go back and restart the service. How to overcome this issue?

Thanks for any hep.

After deploying the WCF service on IIS under SSL, In svcutil.exe https is not comming

$
0
0

Hi All,

I have deployed the WCF service on IIS under SSL. When, I access through browser its open properly, as below URL:

https://mysite/Staging/adms/AdmsService.svc.

BUt, on this page there is svcutill.exe url which shows without https: 

svcutil.exe:  http://mysite/Staging/adms/AdmsService.svc?wsdl

I have tried like: HttpsGetEnable=true

Also, When I do HttpGetEnable=false it shows the https with machine host name:

svcutil.exe https://hostname/Staging/adms/AdmsService.svc?wsdl

Also, https is not coming in targetNamespacespace:

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

<wsdl:types>
<xsd:schema targetNamespace="http://tempuri.org/Imports">
<xsd:import schemaLocation="http://mysite/Staging/adms/AdmsService.svc?xsd=xsd0" namespace="http://tempuri.org/"/>
<xsd:import schemaLocation="http://mysite/Staging/adms/AdmsService.svc?xsd=xsd1" namespace="http://schemas.microsoft.com/2003/10/Serialization/"/>
<xsd:import schemaLocation="http://mysite/Staging/adms/AdmsService.svc?xsd=xsd2" namespace="http://schemas.datacontract.org/2004/07/ns_adms"/>
</xsd:schema>
</wsdl:types>

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

When try to add service reference its giving the following message.

There was an error downloading 'https://mysite/Staging/adms/AdmsService.svc/$metadata'.
The request failed with HTTP status 400: Bad Request.
Metadata contains a reference that cannot be resolved: 'https://mysite/Staging/adms/AdmsService.svc'.
Content Type application/soap+xml; charset=utf-8 was not supported by service https://mysite/Staging/adms/AdmsService.svc. The client and service bindings may be mismatched.
The remote server returned an error: (415) Cannot process the message because the content type 'application/soap+xml; charset=utf-8' was not the expected type 'text/xml; charset=utf-8'..
If the service is defined in the current solution, try building the solution and adding the service reference again.

Kindly suggest.

It will be great help for me.

XML Web Service Versions

$
0
0

I have inherited 3 XML Web services (asmx) contained in a single ASP.NET Web site project (VB.NET, .NET 2).  I would like to create an ASP.NET Web Application project (VB.NET, .NET 4.5), and copy all of the services into that.  Then, replace the old Web site.

The reason I would like to do that is partly so I can add the application to GitHub, and partly so I can break some of the code into separate projects, for example, a DAL project.

I wonder if I can just pretty much copy and paste the web services into the new application, or will I have a problem related to versioning?

There are a lot of different companies that call the old .asmx Web services and they cannot be asked to update their Web references etc.

Thanks very much for any help.

Viewing all 555 articles
Browse latest View live


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