I created service that take the data from android and save them into SQL. I am using IIS 7
My code:
namespace WcfService_SuiviColis
{
// REMARQUE : vous pouvez utiliser la commande Renommer du menu Refactoriser pour changer le nom d'interface "IService1" à la fois dans le code et le fichier de configuration.
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat= WebMessageFormat.Json, BodyStyle =WebMessageBodyStyle.Wrapped, UriTemplate = "SaveData")]
void SaveData(Pers_Ordre_NET oData);
}
[DataContract]
public class Pers_Ordre_NET
{
[DataMember]
string _CodeClient;
public string CodeClient
{
get { return _CodeClient; }
set { _CodeClient = value; }
}
[DataMember]
string _CodeDest;
public string CodeDest
{
get { return _CodeDest; }
set { _CodeDest = value; }
}
[DataMember]
string _NoOrdre;
public string NoOrdre
{
get { return _NoOrdre; }
set { _NoOrdre = value; }
}
[DataMember]
string _DateTampon;
public string DateTampon
{
get { return _DateTampon; }
set { _DateTampon = value; }
}
[DataMember]
string _GeoPos;
public string GeoPos
{
get { return _GeoPos; }
set { _GeoPos = value; }
}
[DataMember]
string _StsOrdre;
public string StsOrdre
{
get { return _StsOrdre; }
set { _StsOrdre = value; }
}
[DataMember]
string _Camion;
public string Camion
{
get { return _Camion; }
set { _Camion = value; }
}
}
}
and service.svc.cs:
namespace WcfService_SuiviColis
{
// REMARQUE : vous pouvez utiliser la commande Renommer du menu Refactoriser pour changer le nom de classe "Service1" dans le code, le fichier svc et le fichier de configuration.
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
public void SaveData(Pers_Ordre_NET oOrdre)
{
try
{
using (var connectionWrapper = new Connexion())
{
var connectedConnection = connectionWrapper.GetConnected();
string sql_Adding = "INSERT INTO [SUIVI_ORDRE]"+
" ([CODE_CLIENT] ,[CODE_DEST],[NO_ORDRE],[DATE_TAMPON],[GPS_POS],[STATUS_ORDRE],CAMION)"+
"VALUES (#CODE_CLIENT,#CODE_DEST,#NO_ORDRE,#DATE_TAMPON,#GPS_POS,#STATUS_ORDRE,#CAMION)";
SqlCommand comm_Insrt = new SqlCommand(sql_Adding, connectionWrapper.conn);
comm_Insrt.Parameters.AddWithValue("#CODE_CLIENT", oOrdre.CodeClient);
comm_Insrt.Parameters.AddWithValue("#CODE_DEST", oOrdre.CodeDest);
comm_Insrt.Parameters.AddWithValue("#NO_ORDRE", oOrdre.NoOrdre);
comm_Insrt.Parameters.AddWithValue("#DATE_TAMPON", oOrdre.DateTampon);
comm_Insrt.Parameters.AddWithValue("#GPS_POS", oOrdre.GeoPos);
comm_Insrt.Parameters.AddWithValue("#STATUS_ORDRE", oOrdre.StsOrdre);
comm_Insrt.Parameters.AddWithValue("#CAMION", oOrdre.Camion);
comm_Insrt.ExecuteNonQuery();
}
}
catch (Exception excThrown)
{
throw new Exception(excThrown.Message);
}
}
}
}
and web.config:
<system.serviceModel>
<services>
<service name="WcfService_SuiviColis.Service1" behaviorConfiguration="ServiceBehaviour">
<endpoint
address="SaveData"
behaviorConfiguration="httpBehavior"
binding="webHttpBinding"
contract="WcfService_SuiviColis.IService1" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehaviour">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="httpBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true">
</serviceHostingEnvironment>
</system.serviceModel>
<system.webServer>
<security>
<requestFiltering>
<verbs>
<add verb="POST" allowed="true"/>
</verbs>
<fileExtensions>
<add fileExtension=".svc" allowed="true"/>
</fileExtensions>
</requestFiltering>
</security>
<directoryBrowse enabled="true"/>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
I can not find the right configuration for the endpoint.
When I write like this:
<endpoint
address="SaveData" behaviorConfiguration="httpBehavior"
binding="webHttpBinding"
contract="WcfService_SuiviColis.IService1" />
I got endpoint not found
When I write it like this:
<endpoint
address="" behaviorConfiguration="httpBehavior"
binding="webHttpBinding"
contract="WcfService_SuiviColis.IService1" />
I got method not allowed
When I write like this:
<endpoint
address=""
binding="basicHttpBinding"
contract="WcfService_SuiviColis.IService1" />
I got error 415, type mismatch because I want to receive JSON but in fiddler I got html
I put also Factory="System.ServiceModel.Activation.WebServiceHostFactory"
When I put
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
I got error 400 page not found
I call my method like this:
http://mydomain:4004/Code/WcfService_SuiviColis/WcfService_SuiviColis/Service1.svc/SaveData
EDITED
i think the correct endpoint :
<endpoint
address="" behaviorConfiguration="httpBehavior"
binding="webHttpBinding"
contract="WcfService_SuiviColis.IService1" />
but with this endpoint i got error 405, mmethode not allowed. is posible that IIS 7 not allowed POST (receive the data from ANDROID to SERVER) ?
because i have created another wcf programm with GET (send the data from SERVER to ANDROID) it work fine.
At first glance the address of the endpoint you are defining is not valid. It should contain the full address of the machine where the service is located along with the port number
<endpoint address ="http://mydomain:4004/...../>
Since you're using IIS, the web URL to use is basically defined by IIS: your server name, name of the virtual directory, path and location of the *.svc file.
http://YourWebServer/VirtualDirectory/Path/service.svc
Then, you might have an additional, relative address in your endpoint definition, so if you use
<endpoint
address="SaveData" behaviorConfiguration="httpBehavior"
binding="webHttpBinding"
contract="WcfService_SuiviColis.IService1" />
then the complete URL would be:
http://YourWebServer/VirtualDirectory/Path/service.svc/SaveData
I'm not sure if you might need to add another /SaveData to that URL since you've defined this as your UriTemplate on the service contract:
http://YourWebServer/VirtualDirectory/Path/service.svc/SaveData/SaveData
++++++++ ********
| |
relative address |
from endpoint |
|
UriTemplate from your service contract
Endpoint not found usually means you're using a wrong URL to try and access your service.
Related
after upgrading the Java implementation of Camel from 2.13.0 to 2.17.2 (and cxf-rt-frontend-jaxrs from 2.7.10 to 3.1.5, and spring framework from 3.2.8 to 4.3.2), the webapp that is serving as a proxy stopped working correctly.
The app is supposed to intercept a webservice request, modify fields that are defined in a properties file throught the ContextManager class, and forward the request to the correct endpoint.
After the upgrade, the app is unable to set the missing fields in the original request, thus returning the following message: "REQUEST_MESSAGE_NOT_COMPLIANT_WITH_SCHEMA - Your request message does not comply to the web service schema".
This is of course expected since the missing fields are not being set.
Any help would be greatly appreciated.
UPDATE:
The problem seems to be coming from the xpath method which in the previous version returned the correct node where some information needs to be set and now is returning null.
My Camel route definition is as follows:
CreditLimitRequestServiceRoute.class
public class CreditLimitRequestServiceRoute extends AbstractEHRoute {
#Autowired
private ContextManager contextManager;
#Override
public void configure() throws Exception {
Namespaces ns = new Namespaces("ns1", "http://ehsmartlink/commonError");
onException(SoapFault.class)
.to("consoleflux:message?level=ERROR&text=${exception.message}&content=${exception.detail}")
.setHeader("soapFaultDetail", simple("${exception.detail}"))
.choice()
.when(and(header("soapFaultDetail").isNotNull(), xpath("//ns1:commonError/errorType/text() = 'BusinessError'", ns, "soapFaultDetail")))
.to("consoleflux:finish?ignoreContent=true")
.otherwise()
.to("consoleflux:error?ignoreContent=true");
onException(Exception.class)
.to("consoleflux:error");
from("cxf:bean:creditLimitRequestServiceProxy?dataFormat=PAYLOAD").routeId("creditLimitRequestServiceRoute")
.log(LoggingLevel.INFO, "Invocation du WS").streamCaching()
.to("consoleflux:start?source=SOA&dest=EH&type=CREDIT_LIMIT")
.to("consoleflux:message?ignoreContent=true&text=Affectation du Contexte EH")
.setHeader("context").xpath("//context")
.bean(contextManager, "setContext")
.to("consoleflux:message?ignoreContent=true&text=Invocation du WS EH ${headers.operationName}")
.to("cxf:bean:creditLimitRequestService?dataFormat=PAYLOAD")
.to("consoleflux:finish");
}
}
AbstractEHRoute.class
public abstract class AbstractEHRoute extends RouteBuilder {
protected XPathBuilder xpath(String text, Namespaces namespaces, String headerName) {
XPathBuilder xpath = XPathBuilder.xpath(text).namespaces(namespaces);
xpath.setHeaderName(headerName);
return xpath;
}
}
ContextManager
package com.stef.soa.eh.integration.beans;
import static com.google.common.base.Objects.firstNonNull;
import static com.google.common.base.Strings.isNullOrEmpty;
import java.util.Map;
import java.util.UUID;
import org.apache.camel.Header;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
#Component
public class ContextManager {
private static final String USER_NAME = "userName";
private static final String USER_PASSWORD = "userPassword";
private static final String LANGUAGE_TEXT_IDENTIFIER = "languageTextIdentifier";
private static final String TRANSACTION_IDENTIFIER = "transactionIdentifier";
private static final String POLICIY_IDENTIFIER = "policyIdentifier";
private static final String POLICY_EXTENSION_IDENTIFIER = "policyExtensionIdentifier";
private static final String POLICY_EHBU_IDENTIFIER = "policyEHBUIdentifier";
private static final String IP_ADRESS = "ipAdress";
#Value("${eh.context.userName}")
private String userName;
#Value("${eh.context.userPassword}")
private String userPassword;
#Value("${eh.context.languageTextIdentifier}")
private String languageTextIdentifier;
#Value("${eh.context.policyIdentifier}")
private String policyIdentifier;
#Value("${eh.context.policyExtensionIdentifier}")
private String policyExtensionIdentifier;
#Value("${eh.context.policyEHBUIdentifier}")
private String policyEHBUIdentifier;
#Value("${eh.context.ipAdress}")
private String ipAdress;
public void setContext(#Header("context") Node context) {
Preconditions.checkNotNull(context, "Le contexte doit être renseigné");
// Suppression des noeuds enfants avec sauvegarde les valeurs courantes dans une map
Map<String, String> currentValues = Maps.newHashMap();
NodeList list = context.getChildNodes();
for (int i = list.getLength() - 1; i >= 0; i--) {
Node child = list.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE && !isNullOrEmpty(child.getTextContent())) {
currentValues.put(child.getNodeName(), child.getTextContent());
}
context.removeChild(child);
}
// Ajout des noeuds enfants
appendChild(context, USER_NAME, userName, currentValues);
appendChild(context, USER_PASSWORD, userPassword, currentValues);
appendChild(context, LANGUAGE_TEXT_IDENTIFIER, languageTextIdentifier, currentValues);
appendChild(context, TRANSACTION_IDENTIFIER, UUID.randomUUID().toString(), currentValues);
appendChild(context, POLICIY_IDENTIFIER, policyIdentifier, currentValues);
appendChild(context, POLICY_EXTENSION_IDENTIFIER, policyExtensionIdentifier, currentValues);
appendChild(context, POLICY_EHBU_IDENTIFIER, policyEHBUIdentifier, currentValues);
appendChild(context, IP_ADRESS, ipAdress, currentValues);
}
private void appendChild(Node node, String name, String value, Map<String, String> currentValues) {
Document document = node.getOwnerDocument();
Element child = document.createElement(name);
child.setTextContent(firstNonNull(currentValues.get(name), value));
node.appendChild(child);
}
}
context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:eh.properties, file:///${eh.home}/conf/eh.properties"
ignore-resource-not-found="true" system-properties-mode="OVERRIDE" />
<context:component-scan base-package="com.stef.soa.eh" />
<context:annotation-config />
<import resource="classpath:META-INF/eh/spring/broker.xml" />
<import resource="classpath:META-INF/eh/spring/camel.xml" />
<import resource="classpath:META-INF/eh/spring/cxf.xml" />
<import resource="classpath:META-INF/soa-console-flux-client/spring/context.xml"/>
</beans>
camel.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:http="http://cxf.apache.org/transports/http/configuration"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring
http://camel.apache.org/schema/spring/camel-spring.xsd
http://cxf.apache.org/transports/http/configuration
http://cxf.apache.org/schemas/configuration/http-conf.xsd" >
<!-- Camel Context -->
<camelContext xmlns="http://camel.apache.org/schema/spring" id="ehContext">
<properties>
<property key="org.apache.camel.xmlconverter.output.indent" value="yes"/>
<property key="org.apache.camel.xmlconverter.output.{http://xml.apache.org/xslt}indent-amount" value="4"/>
</properties>
<package>com.stef.soa.eh.integration</package>
</camelContext>
</beans>
cxf.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cxf="http://camel.apache.org/schema/cxf"
xmlns:http="http://cxf.apache.org/transports/http/configuration"
xmlns:sec="http://cxf.apache.org/configuration/security"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/cxf
http://camel.apache.org/schema/cxf/camel-cxf.xsd
http://cxf.apache.org/transports/http/configuration
http://cxf.apache.org/schemas/configuration/http-conf.xsd" >
<!-- Serveur Proxy, Certificat -->
<http:conduit name="*.http-conduit">
<http:client ProxyServer="${proxy.host}" ProxyServerPort="${proxy.port}"
ConnectionTimeout="${http.client.connectionTimeout}" ReceiveTimeout="${http.client.receiveTimeout}" />
<http:proxyAuthorization>
<sec:UserName>${proxy.username}</sec:UserName>
<sec:Password>${proxy.password}</sec:Password>
</http:proxyAuthorization>
<http:tlsClientParameters>
<sec:keyManagers keyPassword="${eh.keyStore.password}">
<sec:keyStore type="pkcs12" password="${eh.keyStore.password}" file="${eh.home}/${eh.keyStore.file}" />
</sec:keyManagers>
</http:tlsClientParameters>
</http:conduit>
<!-- Services Proxy et Cible -->
<cxf:cxfEndpoint
id="creditLimitRequestServiceProxy"
address="/creditLimitRequestService"
wsdlURL="META-INF/eh/wsdl/CreditLimitRequestService/EH_SMARTLINK_CreditLimitRequestServiceV4.wsdl"
serviceName="ns:CreditLimitRequestServiceV4"
endpointName="ns:CreditLimitRequestServiceV4"
xmlns:ns="http://ehsmartlink/CreditLimitRequestService/v4"
/>
<cxf:cxfEndpoint
id="creditLimitRequestService"
address="${eh.creditLimitRequestService.url}"
wsdlURL="META-INF/eh/wsdl/CreditLimitRequestService/EH_SMARTLINK_CreditLimitRequestServiceV4.wsdl"
serviceName="ns:CreditLimitRequestServiceV4"
endpointName="ns:CreditLimitRequestServiceV4"
xmlns:ns="http://ehsmartlink/CreditLimitRequestService/v4"
loggingFeatureEnabled="true"
/>
<cxf:cxfEndpoint
id="customerListRetrieveServiceProxy"
address="/customerListRetrieveService"
wsdlURL="META-INF/eh/wsdl/CustomerListRetrieveService/CustomerListRetrieveV2.wsdl"
serviceName="ns:CustomerListRetrieveServiceV2"
endpointName="ns:CustomerListRetrieveServiceV2"
xmlns:ns="http://ehsmartlink/CustomerListRetrieve/v2"
/>
<cxf:cxfEndpoint
id="customerListRetrieveService"
address="${eh.customerListRetrieveService.url}"
wsdlURL="META-INF/eh/wsdl/CustomerListRetrieveService/CustomerListRetrieveV2.wsdl"
serviceName="ns:CustomerListRetrieveServiceV2"
endpointName="ns:CustomerListRetrieveServiceV2"
xmlns:ns="http://ehsmartlink/CustomerListRetrieve/v2"
loggingFeatureEnabled="true"
/>
<cxf:cxfEndpoint
id="firstEuroListRepertoireReadServiceProxy"
address="/firstEuroListRepertoireReadService"
wsdlURL="META-INF/eh/wsdl/FirstEuroListRepertoireReadService/EH_SMARTLINK_FirstEuroListRepertoireReadService-v1.wsdl"
serviceName="ns:FirstEuroListRepertoireReadService-v1"
endpointName="ns:FirstEuroListRepertoireReadServicePort-v1_soap11"
xmlns:ns="http://eulerhermes.com/SMARTLINK/services/FirstEuroListRepertoireReadService/v1"
/>
<cxf:cxfEndpoint
id="firstEuroListRepertoireReadService"
address="${eh.firstEuroListRepertoireReadService.url}"
wsdlURL="META-INF/eh/wsdl/FirstEuroListRepertoireReadService/EH_SMARTLINK_FirstEuroListRepertoireReadService-v1.wsdl"
serviceName="ns:FirstEuroListRepertoireReadService-v1"
endpointName="ns:FirstEuroListRepertoireReadServicePort-v1_soap11"
xmlns:ns="http://eulerhermes.com/SMARTLINK/services/FirstEuroListRepertoireReadService/v1"
loggingFeatureEnabled="true"
/>
<cxf:cxfEndpoint
id="firstEuroListRepertoireUpdateServiceProxy"
address="/firstEuroListRepertoireUpdateService"
wsdlURL="META-INF/eh/wsdl/FirstEuroListRepertoireUpdateService/EH_SMARTLINK_FirstEuroListRepertoireUpdateService-v1.wsdl"
serviceName="ns:FirstEuroListRepertoireUpdateService-v1"
endpointName="ns:FirstEuroListRepertoireUpdateServicePort-v1"
xmlns:ns="http://eulerhermes.com/SMARTLINK/services/FirstEuroListRepertoireUpdateService/v1"
/>
<cxf:cxfEndpoint
id="firstEuroListRepertoireUpdateService"
address="${eh.firstEuroListRepertoireUpdateService.url}"
wsdlURL="META-INF/eh/wsdl/FirstEuroListRepertoireUpdateService/EH_SMARTLINK_FirstEuroListRepertoireUpdateService-v1.wsdl"
serviceName="ns:FirstEuroListRepertoireUpdateService-v1"
endpointName="ns:FirstEuroListRepertoireUpdateServicePort-v1"
xmlns:ns="http://eulerhermes.com/SMARTLINK/services/FirstEuroListRepertoireUpdateService/v1"
loggingFeatureEnabled="true"
/>
<cxf:cxfEndpoint
id="limitDetailReadServiceProxy"
address="/limitDetailReadService"
wsdlURL="META-INF/eh/wsdl/LimitDetailReadService/EH_SMARTLINK_LimitDetailReadService-v2.wsdl"
serviceName="ns:LimitDetailReadService-v2"
endpointName="ns:LimitDetailReadServicePort-v2"
xmlns:ns="http://eulerhermes.com/SMARTLINK/services/LimitDetailReadService/v2"
/>
<cxf:cxfEndpoint
id="limitDetailReadService"
address="${eh.limitDetailReadService.url}"
wsdlURL="META-INF/eh/wsdl/LimitDetailReadService/EH_SMARTLINK_LimitDetailReadService-v2.wsdl"
serviceName="ns:LimitDetailReadService-v2"
endpointName="ns:LimitDetailReadServicePort-v2"
xmlns:ns="http://eulerhermes.com/SMARTLINK/services/LimitDetailReadService/v2"
loggingFeatureEnabled="true"
/>
</beans>
I want to retrieve list of images from database that are stored in the form of bytes.I am able to return only single images bytes length.How can i send list of bytes .i am using below code please let me know
public List<Byte[]> GetAllProjectStandardIcons()
{
var qry = (from p in dbModel.tbl_STANDARDPROJECTICONS
select new
{
p.ProjectIcons
}).ToList();
//How to return list here from WCF web service
}
I have tried to create a service with an Image Service that returns images from the images stored in the same folder as the service. You can the streaming later if you want.
[ServiceContract]
public interface IImagesService
{
[OperationContract]
List<Byte[]> FetchImages();
}
public class ImagesService : IImagesService
{
List<string> images = new List<string>();
public ImagesService()
{
images.Add("Box.png");
images.Add("Clock.png");
}
public List<byte[]> FetchImages()
{
List<Byte[]> imagesInBytes = new List<byte[]>();
foreach (var image in images)
{
Image newImage = new Bitmap(image);
byte[] b = this.imageToByteArray(newImage);
imagesInBytes.Add(b);
}
return imagesInBytes;
}
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
}
Hosted the service on httpbinding
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="NewBehavior0">
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="WCFImagesExample.ImagesService" behaviorConfiguration="NewBehavior0">
<endpoint address="Images" binding="basicHttpBinding" bindingConfiguration=""
contract="WCFImagesExample.IImagesService" />
<endpoint address="mex" binding="mexHttpBinding" bindingConfiguration=""
contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:{portnumber}" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
Now you can create a client proxy and save the images back
static void Main(string[] args)
{
ImagesReference.IImagesService imagesService = new ImagesServiceClient();
byte[][] bytes = imagesService.FetchImages();
int i=0;
foreach (byte[] byteArray in bytes)
{
Image image = byteArrayToImage(byteArray);
image.Save(#"c:\Development\" + i + ".png");
i++;
}
}
public static Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
Highly like you want to return an image. No matter what you can have a look at the following:Large Data and Streaming
This is the error:
The type initializer for 'System.ServiceModel.Diagnostics.TraceUtility' threw an exception.
This error ocurs when I try to instance my proxy class
namespace TesteWebService
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnPdv_Click(object sender, EventArgs e)
{
SuporteTecnicoClientProxy proxy = new SuporteTecnicoClientProxy();=> **Here error**
try
{
TPDV pdv = proxy.getCnpjParceiro(txtCnpj.Text);
lblRazao.Text = pdv.RazaoSocial;
lblEndereco.Text = pdv.Endereco;
}
catch (Exception ex)
{ }
finally
{ }
}
}
}
My proxy class
namespace TesteWebService
{
class SuporteTecnicoClientProxy : ClientBase<ISuporteTecnicoContract>, ISuporteTecnicoContract
{
public TPDV getCnpjParceiro(string _cnpj)
{
return this.Channel.getCnpjParceiro(_cnpj);
}
}
}
My Interface
[ServiceContract]
public interface ISuporteTecnicoContract
{
[OperationContract]
[WebGet(UriTemplate = "/{_cnpj}")]
TPDV getCnpjParceiro(string _cnpj);
}
My App.Config
<client>
<endpoint adress="http://localhost:4600/SuporteTecnicoService.svc" binding="webHttpBinding" contract="V99SuporteTecnicoContracts.ISuporteTecnicoContract"
behaviorConfiguration="WebBehavior">
</endpoint>
</client>
<behaviors>
<endpointBehaviors>
<behavior name="WebBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
What is really going to generate the exception mentioned above. My Interface is other projet. A Class Library Project. So, I have 2 projects. A WCF project(Web Service) and my contract project(POCO class and Interface). This last project Class Library.
Glass GDK here. Trying to insert a livecard using remote views from service. I'm launching service via voice invocation. The voice command works, however it appears my service is not starting(no entries in log). Service is in android manifest. Below is code:
public class PatientLiveCardService extends Service {
private static final String LIVE_CARD_ID = "timer";
#Override
public void onCreate() {
Log.warn("oncreate");
super.onCreate();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
publishCard(this);
return START_STICKY;
}
#Override
public void onDestroy() {
unpublishCard(this);
super.onDestroy();
}
private void publishCard(Context context) {
Log.info("inserting live card");
if (mLiveCard == null) {
String cardId = "my_card";
TimelineManager tm = TimelineManager.from(context);
mLiveCard = tm.getLiveCard(cardId);
mLiveCard.setViews(new RemoteViews(context.getPackageName(),
R.layout.activity_vitals));
Intent intent = new Intent(context, MyActivity.class);
mLiveCard.setAction(PendingIntent
.getActivity(context, 0, intent, 0));
mLiveCard.publish();
} else {
// Card is already published.
return;
}
}
private void unpublishCard(Context context) {
if (mLiveCard != null) {
mLiveCard.unpublish();
mLiveCard = null;
}
}
}
Here is AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<uses-permission android:name="android.permission.RECORD_AUDIO" >
</uses-permission>
<application
android:name="com.myApp"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.myApp.MyActivity"
android:label="#string/app_name"
android:screenOrientation="landscape" >
</activity>
<service android:name="com.myApp.services.MyService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.android.glass.action.VOICE_TRIGGER" />
</intent-filter>
<meta-data
android:name="com.google.android.glass.VoiceTrigger"
android:resource="#xml/voice_trigger_get_patient" />
</service>
</application>
This is a bug with XE11: the service is not started after the speech recognizer is complete.
As a workaround, you can have your voice trigger start an Activity which:
Processes the recognized speech in onResume.
Once the speech is processed, starts your Service with startService.
Calls finish to jump to the published LiveCard.
I have been trying to troubleshoot this error for a long time.
"An error occurred when verifying security for the message"
I did some research, people said this is because the time difference between the server and the client.
This anyone else have the same problem?
Below is the detail of my error
System.ServiceModel.FaultException was caught
Message=An error occurred when verifying security for the message.
Source=mscorlib
StackTrace:
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at WindowsFormsApplication1.CrmSdk.Discovery.IDiscoveryService.Execute(DiscoveryRequest request)
at WindowsFormsApplication1.CrmSdk.Discovery.DiscoveryServiceClient.Execute(DiscoveryRequest request) in WindowsFormsApplication1\Service References\CrmSdk.Discovery\Reference.cs:line 723
at WindowsFormsApplication1.Form1.DiscoverOrganizationUrl(String organizationName, String discoveryServiceUrl) in Form1.cs:line 110
InnerException:
Here is the code i used to access the hosted CRM online webservice
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Web;
//using System.ServiceModel;
//using System.ServiceModel.Description;
namespace WindowsFormsApplication1
{
using CrmSdk;
using CrmSdk.Discovery;
using System.Net;
using System.Globalization;
using LocalServices;
using System.ServiceModel;
using System.Web.Services.Protocols;
public partial class Form1 : Form
{
///hosted CRM online
private const string DiscoveryServiceUrl = "https://disco.crm.dynamics.com/XRMServices/2011/Discovery.svc";
private IOrganizationService _service;
private string fetchXML =
#"
<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='account'>
<attribute name='name' />
<attribute name='address1_city' />
<attribute name='primarycontactid' />
<attribute name='telephone1' />
<attribute name='accountid' />
<order attribute='name' descending='false' />
<filter type='and'>
<condition attribute='ownerid' operator='eq-userid' />
<condition attribute='statecode' operator='eq' value='0' />
</filter>
<link-entity name='contact' from='contactid' to='primarycontactid' visible='false' link-type='outer' alias='accountprimarycontactidcontactcontactid'>
<attribute name='emailaddress1' />
</link-entity>
</entity>
</fetch>
";
public Form1()
{
InitializeComponent();
//GetDataFromCRM();
GetDataFromCRM2();
}
private void GetDataFromCRM2()
{
private string DiscoverOrganizationUrl(string organizationName, string discoveryServiceUrl)
{
using (CrmSdk.Discovery.DiscoveryServiceClient client = new CrmSdk.Discovery.DiscoveryServiceClient("CustomBinding_IDiscoveryService", discoveryServiceUrl))
{
//ApplyCredentials(client, credentials);
client.ClientCredentials.Windows.ClientCredential.UserName = UserName;
client.ClientCredentials.Windows.ClientCredential.Password = Password
client.ClientCredentials.Windows.ClientCredential.Domain = Domain
CrmSdk.Discovery.RetrieveOrganizationRequest request = new CrmSdk.Discovery.RetrieveOrganizationRequest()
{
UniqueName = organizationName
};
try
{
CrmSdk.Discovery.RetrieveOrganizationResponse response = (CrmSdk.Discovery.RetrieveOrganizationResponse)client.Execute(request);
foreach (KeyValuePair<CrmSdk.Discovery.EndpointType, string> endpoint in response.Detail.Endpoints)
{
if (CrmSdk.Discovery.EndpointType.OrganizationService == endpoint.Key)
{
Console.WriteLine("Organization Service URL: {0}", endpoint.Value);
return endpoint.Value;
}
}
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
"Organization {0} does not have an OrganizationService endpoint defined.", organizationName));
}
catch (FaultException e)
{
MessageBox.Show(e.Message);
throw;
}
catch (SoapHeaderException e)
{
MessageBox.Show(e.Message);
throw;
}
catch (SoapException e)
{
MessageBox.Show(e.Message);
throw;
}
return null;
}
}
//private static void ApplyCredentials<TChannel>(ClientBase<TChannel> client, ICredentials credentials)
// where TChannel : class
//{
// client.ClientCredentials.Windows.ClientCredential = credentials.Windows.ClientCredential;
//}
private void ExecuteFetch(string serviceUrl)
{
using (OrganizationServiceClient client = new OrganizationServiceClient("CustomBinding_IOrganizationService", new EndpointAddress(serviceUrl)))
{
client.ClientCredentials.Windows.ClientCredential.UserName = UserName;
client.ClientCredentials.Windows.ClientCredential.Password = Password;
client.ClientCredentials.Windows.ClientCredential.Domain = Domain;
_service = (IOrganizationService)client;
FetchExpression expression = new FetchExpression();
expression.Query =
#"
<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='account'>
<attribute name='name' />
<attribute name='address1_city' />
<attribute name='primarycontactid' />
<attribute name='telephone1' />
<attribute name='accountid' />
<order attribute='name' descending='false' />
<filter type='and'>
<condition attribute='ownerid' operator='eq-userid' />
<condition attribute='statecode' operator='eq' value='0' />
</filter>
<link-entity name='contact' from='contactid' to='primarycontactid' visible='false' link-type='outer' alias='accountprimarycontactidcontactcontactid'>
<attribute name='emailaddress1' />
</link-entity>
</entity>
</fetch>
";
EntityCollection result = _service.RetrieveMultiple(expression);
DataTable temp = ConvertEntityToTable(result);
}
}
/// Convert Entity To datatable
private DataTable ConvertEntityToTable(EntityCollection result)
{
DataTable dt = new DataTable();
int rowCount = result.Entities.Count();
try
{
for (int i = 0; i < rowCount; i++)
{
DataRow dr = dt.NewRow();
Entity currentEntity = (Entity)result.Entities[i];
var keys = currentEntity.Attributes.Count();
for (int j = 0; j < keys; j++)
{
string columName = currentEntity.Attributes[j].Key;
string value = currentEntity.Attributes[j].Value.ToString();
if (dt.Columns.IndexOf(columName) == -1)
dt.Columns.Add(columName, Type.GetType("Sysem.String"));
dr[columName] = value;
}
dt.Rows.Add(dr);
}
return dt;
}
catch (Exception exp)
{
throw;
}
}
}
}
app.config
<bindings>
<customBinding>
<binding name="CustomBinding_IDiscoveryService">
<textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16"
messageVersion="Default" writeEncoding="utf-8">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
</textMessageEncoding>
<httpsTransport manualAddressing="false" maxBufferPoolSize="524288"
maxReceivedMessageSize="65536" allowCookies="false" authenticationScheme="Anonymous"
bypassProxyOnLocal="false" decompressionEnabled="true" hostNameComparisonMode="StrongWildcard"
keepAliveEnabled="true" maxBufferSize="65536" proxyAuthenticationScheme="Anonymous"
realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="false"
useDefaultWebProxy="true" requireClientCertificate="false"
/>
</binding>
It throw the error at FaultException
Thanks for all the help
The general consensus appears to be that besides the actual time, the timezone and daylight savings time settings appear to be the cause of this error. The client and server need to be in sync with each other.