how to call magento soap webservice in windows form application? - winforms

I have soap link like this http://example.com/index.php/api/v2_soap/?wsdl (it is a magento website), the username password is abc , 123
I just added a service reference at solution explorer the name is ServiceReference1
I created a button (using vs2015, project name is printOrder) as the code is following:
private void button1_Click(object sender, EventArgs e)
{
}
the app.config is the following:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="Binding" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://example.com/index.php/api/v2_soap/index/"
binding="basicHttpBinding" bindingConfiguration="Binding"
contract="ServiceReference1.PortType" name="Port" />
</client>
</system.serviceModel>
</configuration>
So,
1) how to create a soap client object with username and password?
2) after created soap client object, how do i call the web service?
i've searched a lot of topics in google but seems there is small different from my case......
Anyone know how to to that?
The same thing i want to do is
$cs = getSesstion();
$result = $cs['client']->salesOrderShipmentInfo($cs['session'], '200001811');
$complexFilter = array(
'complex_filter' => array(
array(
'key' => 'orderIncrementId',
'value' => array('key' => 'in', 'value' => '100004496')
)
)
);
var_dump($cs);
//$result = $cs['client']->salesOrderInfo($cs['session'],'100004496');
//var_dump($result);
function getSesstion() {
$client = new SoapClient('http://example.com/index.php/api/v2_soap/?wsdl');
$username = 'vtec';
$apikey= 'Abcd1234';
$session = $client->login($username, $apikey);
$cs = array();
$cs['client'] = $client;
$cs['session'] = $session;
return $cs;
}
----------------------------answer-----------------------------
with Regie Baquero's help, the right code i found is
ServiceReference1.PortTypeClient client = new ServiceReference1.PortTypeClient();
string session = client.login("vtec","Abcd1234");
Console.WriteLine(session);
//client.(session, "product_stock.list", "qqaz");
var result = client.salesOrderInfo(session, "145000037");
//client.endSession(session);
Console.WriteLine(result.increment_id.ToString());

If you have already added your soap service what you need is to declare it in your code something like:
`ServiceReference1.Service service variable = new ServiceReference1.Service();`
in order for you to access method or function inside the soap service.
Sample code if you have written your soap service in visual studio c# your code should look like this:
[WebMethod]
public bool Password_Verification(string password)
{
if(password=="12345")
{
return true;
}
}
you can access it using
`ServiceReference1.Service service variable = new ServiceReference1.Service();`
bool verify = service variable.Password_Verification("12345");
Same goes with wsdl file. you just need to know what function/method is implemented in that soap service.
.........................

Related

No Association Found Error while indexing data to Solr using Spring-Data-Solr

I am trying out a sample service application of spring data mongoDB + spring data solr where MongoDB is used to persist the data and solr for indexing and searching.
The save operation to MongoDB happens successfully in the service class. But on calling the SolrOperation save() method the service crashes with the error log as below:
SEVERE [com.sun.jersey.spi.container.ContainerResponse] (defaulttask-1)The
RuntimeException could not be mapped to a response, re-throwing the HTTP
container:org.springframework.data.solr.UncategorizedSolrException:No
association fond!; nested exception is java.lang.IllegalStateException: No
association found! at org.springframework.data.solr.core.SolrTemplate.execute(SolrTemplate.java:171)
As I analyse the log further deep it says:
Caused by: java.lang.IllegalStateException:No association found!
at org.springframework.data.mapping.PersistentProperty.getRequiredAssociation(PersistentProperty.java:166)
The line getConverter().write(bean, document) inside convertBeanToSolrInputDocument () inside SolrTemplate is throwing the error.
The DAO method
public String addToRepo(MyEntity myEntity){
mongoOperation.save(myEntity); //works fine data saved to MongoDB
solrOperation.save("collectionName",myEntity); //generates above exception
return "success";
}
I am using Spring 5 + solrj-6.1.0 + spring-data-solr-4.0.2.
The solroperation has been correctly loaded as:
ApplicationContext SOLR_CONFIG_APP_CTX = new AnnotationConfigApplicationContext(SpringSolrConfig.class);
SolrOperations solrOperation = (SolrOperations)ctx.getBean("solrTemplate");
public static final SolrOperations SOLR_OPS=
(SolrOperations)SOLR_CONFIG_APP_CTX.getBean("solrTemplate");
SpringSolrConfig.java
#Configuration
public class SpringSolrConfig extends AbstractSolrConfig {
public SolrClientFactory solrClientFactory (){
SolrClient solrClient = new HttpSolrClient.Builder(solrUrl).build();
HttpSolrClientFactory solrClientFactory = new HttpSolrClientFactory (solrClient);
return solrClientFactory;
}
}
The SpringConfig.xml file looks like this:
<mongo:mongo host="195.168.1.140" port="27017"/>
<mongo:dbfactory dbname="myDB"/>
<bean id="mongoTemplate"
class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg-name="mongoDbFactory" ref="mongoDbFactory"/>
</bean>
<repositories base-package="sample.package.repositories"/>
<bean id="myEntityRepo" class="sample.package..repositories.MyEntityRepositoryInterface"/>
<solr:repositories base-package="sample.package.repositories"/>
<solr:sorl-server id="solrServer" url="http://localhost:8983/solr"/>
<bean id="solrTemplate" class="org.springframework.data.solr.core.SolrTemplate">
<constructor-arg index="0" ref="solrServer"/>
</bean>
Thanks in advance for helping me troubleshoot this!
I updated my SpringSolrConfig file as below to fix the problem. Courtesy: https://jira.spring.io/browse/DATASOLR-394
#Configuration
public class SpringSolrConfig extends AbstractSolrConfig {
String solrUrl = "http://localhost:8983/solr/"; // TODO read this ideally from spring-configuration.xml file
public SolrClientFactory solrClientFactory (){
SolrClient solrClient = new HttpSolrClient.Builder(solrUrl).build();
HttpSolrClientFactory solrClientFactory = new HttpSolrClientFactory (solrClient);
return solrClientFactory;
}
#Bean
public SolrTemplate solrTemplate () {
SolrTemplate solrTemplateObj = new SolrTemplate(solrClientFactory));
// This ensures that the default MappingSolrConverter.java is not used for converting the bean to a Solr Document before indexing
solrTemplateObj.setSolrConverter(new SolrJConverter());
return solrTemplateObj;
}
}

Error Validating Signed MTOM Message CXF 3.0.6 and up

I created a simple web service using CXF that has MTOM enabled, it also expects a time stamp and the body to be signed, it configured like this:
#ComponentScan(basePackageClasses={MyService.class})
#Configuration
#ImportResource({ "classpath:META-INF/cxf/cxf.xml" })
public class CXFConfig {
#Autowired
Bus cxfBus;
#Autowired
MyService ws;
#Bean
public Endpoint endpoint() {
EndpointImpl endpoint = new EndpointImpl(cxfBus, ws);
endpoint.publish("/MyService");
SOAPBinding binding = (SOAPBinding)endpoint.getBinding();
binding.setMTOMEnabled(true);
Map<String, Object> inProps = new HashMap<String, Object>();
inProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.SIGNATURE+" "+WSHandlerConstants.TIMESTAMP);
inProps.put(WSHandlerConstants.SIG_PROP_FILE, "wsserver.properties");
WSS4JInInterceptor inc = new WSS4JInInterceptor(inProps);
endpoint.getInInterceptors().add(inc);
return endpoint;
}
}
My Service Interface is:
#WebService
#Component
public interface MyService {
#WebMethod(action="doStuff")
public String doStuff(#WebParam(name="FileData") MTOMMessage message) throws IOException;
}
My Data Type is:
#XmlType
#XmlAccessorType(XmlAccessType.FIELD)
public class MTOMMessage {
#XmlElement(name = "data", required = true)
#XmlMimeType("text/xml")
protected DataHandler data;
#XmlElement(name = "FileName", required = true)
protected String fileName;
//Getters and Setters
}
I then have a client to call it:
public static void main(String[] args) throws IOException {
String xmlLoc = "classpath:com/avum/dasn/ws/test/client-context.xml";
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(xmlLoc);
MyService svc = ctx.getBean(MyService.class);
MTOMMessage msg = new MTOMMessage();
msg.setXmlData(new DataHandler(getURLForTestFile()));
msg.setFileName("TestFileName");
System.out.println(svc.doStuff(msg));
}
The client-context.xml looks like this:
<jaxws:properties>
<entry key="mtom-enabled" value="true"/>
</jaxws:properties>
<jaxws:outInterceptors>
<bean class="org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor">
<constructor-arg>
<map>
<entry key="action" value="Signature Timestamp"/>
<entry key="signaturePropFile" value="wsclient.properties"/>
<entry key="user" value="ws-security" />
<entry key="passwordCallbackClass" value="com.co.test.PasswordCallbackHandler"/>
</map>
</constructor-arg>
</bean>
<bean class="org.apache.cxf.interceptor.LoggingOutInterceptor" />
</jaxws:outInterceptors>
If I’m using CXF version 3.0.5 or lower this works fine. However if I use 3.0.6 or later I get “A security error was encountered when verifying the message.”. On the server I’m getting messages like “Couldn't validate the References”. This is because the server doesn’t get the same DigestValue that comes across in the ds:DigestValue element.
I think it has something to do with the way MTOM message are handled by the server side code because if I disable MTOM (on the client and server) then it works fine. I’m not sure how to get this working in later versions of CXF. Does anyone have any ideas what I’m doing wrong?
Thanks
David

Rest API is not always called

I have a Single Page Application with a webClient and a webAPI. When I go to a view which has a table, my table is not being updated. Actually the API is only being called once upon startup of application even though it is suppose to be called each time, or what I expected to happen.
Service Code -
function getPagedResource(baseResource, pageIndex, pageSize) {
var resource = baseResource;
resource += (arguments.length == 3) ? buildPagingUri(pageIndex, pageSize) : '';
return $http.get(serviceBase + resource).then(function (response) {
var accounts = response.data;
extendAccounts(accounts);
return {
totalRecords: parseInt(response.headers('X-InlineCount')),
results: accounts
};
});
}
factory.getAccountsSummary = function (pageIndex, pageSize) {
return getPagedResource('getAccounts', pageIndex, pageSize);
};
API Controller -
[Route("getAccounts")]
[EnableQuery]
public HttpResponseMessage GetAccounts()
{
int totalRecords;
var accountsSummary = AccountRepository.GetAllAccounts(out totalRecords);
HttpContext.Current.Response.Headers.Add("X-InlineCount", totalRecords.ToString());
return Request.CreateResponse(HttpStatusCode.OK, accountsSummary);
}
I can trace it to the service, but it will not hit a break point in the controller.
I added this to my web.config file for the REST API project and now it works as I need it -
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Cache-Control" value="no-cache, no-store, must-revalidate" />
<!-- HTTP 1.1. -->
<add name="Pragma" value="no-cache" />
<!-- HTTP 1.0. -->
<add name="Expires" value="0" />
<!-- Proxies. -->
</customHeaders>
</httpProtocol>
</system.webServer>
Thanks everybody for pointing me in the right direction!
I suspect the REST service response is getting cached in your browser on first call. So on REST service side add headers in response not to cache it or in your request add some additional changeable parameter(like time stamp) to ensure browser will not pick up the response form cache.

Can anyone point me to a working example Camel route using a cxfrs client/producer?

I am having trouble getting my Camel route to successfully POST a message to an existing RESTful web service. I have tried all the examples in the camel cxf package but none of them produce a web service call (they are consumers). I would love to find a working example for this so I can step through the CxfRsProducer execution to hopefully discover why my route is not posting correctly to the web service.
Here is my RouteBuilder's configuration:
public void configure()
{
//errorHandler(deadLetterChannel(String.format("file:%s/../errors", sourceFolder)).useOriginalMessage().retriesExhaustedLogLevel(LoggingLevel.DEBUG));
errorHandler(loggingErrorHandler());
/*
* JMS to WS route for some of the events broadcast to the jms topic
*/
Endpoint eventTopic = getContext().getEndpoint(String.format("activemq:topic:%s?clientId=%s&durableSubscriptionName=%s", eventTopicName, durableClientId, durableSubscriptionName));
from(eventTopic) // listening on the jms topic
.process(eventProcessor) // translate event into a Notifications object (JAX-RS annotated class)
.choice() // gracefully end the route if there is no translator for the event type
.when(header("hasTranslator").isEqualTo(false)).stop() // no translator stops the route
.otherwise() // send the notification to the web service
.to("cxfrs:bean:rsClient");
}
Here is the rsClientBean:
<cxf:rsClient id="rsClient"
address="http://localhost/ws"
serviceClass="com.foo.notifications.NotificationsResource"
loggingFeatureEnabled="true" />
I'm pretty new to REST and I don't really understand what the serviceClass does for the rsClient because it looks to me like the definition of the exposed web service on the server.
The NotificationsResource class:
#Path("/notifications/")
public class NotificationManagerResource
{
// NOTE: The instance member variables will not be available to the
// Camel Exchange. They must be used as method parameters for them to
// be made available
#Context
private UriInfo uriInfo;
public NotificationManagerResource()
{
}
#POST
public Response postNotification(Notifications notifications)
{
return null;
}
}
The processor creates a Notifications object to put in the exechange message body:
private class EventProcessor implements Processor
{
#Override
public void process(Exchange exchange) throws Exception
{
Message in = exchange.getIn();
IEvent event = (IEvent) in.getBody();
Notifications notifications = null;
in.setHeader("hasTranslator", false);
in.setHeader("Content-Type", "application/xml");
in.setHeader(CxfConstants.CAMEL_CXF_RS_USING_HTTP_API, false);
// I've tried using the HTTP API as 'true', and that results in a 405 error instead of the null ptr.
INotificationTranslator translator = findTranslator(event);
if (translator != null)
{
notifications = translator.build(event);
in.setHeader("hasTranslator", true);
}
// replace the IEvent in the body with the translation
in.setBody(notifications);
exchange.setOut(in);
}
}
The Notifications class is annotated with JAXB for serialization
#XmlRootElement(name = "ArrayOfnotification")
#XmlType
public class Notifications
{
private List<Notification> notifications = new ArrayList<>();
#XmlElement(name="notification")
public List<Notification> getNotifications()
{
return notifications;
}
public void setNotifications(List<Notification> notifications)
{
this.notifications = notifications;
}
public void addNotification(Notification notification)
{
this.notifications.add(notification);
}
}
The error that is returned from the web service:
Exchange
---------------------------------------------------------------------------------------------------------------------------------------
Exchange[
Id ID-PWY-EHANSEN-01-62376-1407805689371-0-50
ExchangePattern InOnly
Headers {breadcrumbId=ID:EHANSEN-01-62388-1407805714469-3:1:1:1:47, CamelCxfRsUsingHttpAPI=false, CamelRedelivered=false, CamelRedeliveryCounter=0, Content-Type=application/xml, hasTranslator=true, JMSCorrelationID=null, JMSDeliveryMode=2, JMSDestination=topic://SysManEvents, JMSExpiration=1407805812574, JMSMessageID=ID:EHANSEN-01-62388-1407805714469-3:1:1:1:47, JMSPriority=4, JMSRedelivered=false, JMSReplyTo=null, JMSTimestamp=1407805782574, JMSType=null, JMSXGroupID=null, JMSXUserID=null}
BodyType com.ehansen.notification.types.v2.Notifications
Body <?xml version="1.0" encoding="UTF-8"?><ArrayOfnotification xmlns="http://schemas.datacontract.org/2004/07/ehansen.Notifications.Dto"> <notification> <causeType>EVENT_NAME</causeType> <causeValue>DeviceEvent</causeValue> <details> <notificationDetail> <name>BUSY</name> <value>false</value> <unit>boolean</unit> </notificationDetail> <notificationDetail> <name>DESCRIPTION</name> <value>Software Computer UPS Unit</value> <unit>name</unit> </notificationDetail> <notificationDetail> <name>DEVICE_NUMBER</name> <value>1</value> <unit>number</unit> </notificationDetail> <notificationDetail> <name>DEVICE_SUB_TYPE</name> <value>1</value> <unit>type</unit> </notificationDetail> <notificationDetail> <name>DEVICE_TYPE</name> <value>UPS</value> <unit>type</unit> </notificationDetail> <notificationDetail> <name>FAULTED</name> <value>false</value> <unit>boolean</unit> </notificationDetail> <notificationDetail> <name>RESPONDING</name> <value>true</value> <unit>boolean</unit> </notificationDetail> <notificationDetail> <name>STORAGE_UNIT_NUMBER</name> <value>1</value> <unit>number</unit> </notificationDetail> </details> <sourceType>DEVICE_ID</sourceType> <sourceValue>1:UPS:1</sourceValue> <time>2014-08-11T18:09:42.571-07:00</time> </notification></ArrayOfnotification>
]
Stacktrace
---------------------------------------------------------------------------------------------------------------------------------------
java.lang.NullPointerException
at java.lang.Class.searchMethods(Class.java:2670)
at java.lang.Class.getMethod0(Class.java:2694)
at java.lang.Class.getMethod(Class.java:1622)
at org.apache.camel.component.cxf.jaxrs.CxfRsProducer.findRightMethod(CxfRsProducer.java:266)
at org.apache.camel.component.cxf.jaxrs.CxfRsProducer.invokeProxyClient(CxfRsProducer.java:222)
at org.apache.camel.component.cxf.jaxrs.CxfRsProducer.process(CxfRsProducer.java:90)
at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:61)
at org.apache.camel.processor.SendProcessor$2.doInAsyncProducer(SendProcessor.java:143)
at org.apache.camel.impl.ProducerCache.doInAsyncProducer(ProducerCache.java:307)
at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:138)
It is the methodName parameter in the following method from CxfRsProducer class that is null... so I assume there is something about my rsClient that is not configured correctly.
private Method findRightMethod(List<Class<?>> resourceClasses, String methodName, Class<?>[] parameterTypes) throws NoSuchMethodException {
Method answer = null;
for (Class<?> clazz : resourceClasses) {
try {
answer = clazz.getMethod(methodName, parameterTypes);
} catch (NoSuchMethodException ex) {
// keep looking
} catch (SecurityException ex) {
// keep looking
}
if (answer != null) {
return answer;
}
}
throw new NoSuchMethodException("Cannot find method with name: " + methodName + " having parameters: " + arrayToString(parameterTypes));
}
Thanks for any help anyone can provide!
The serviceClass is a JAX-RS annotated Java class that defines the operations of a REST web service.
When configuring a CXF REST client, you must specify and address and a serviceClass. By inspecting the annotations found on the serviceClass, the CXF client proxy knows which REST operations are supposed to be available on the REST service published on the specified address.
So in your case, you need to add in.setHeader.setHeader(CxfConstants.OPERATION_NAME, "postNotification"); to the EventProcessor to tell camel which method of the service class you want to call.
Alright then. Here is the camel configuration xml file.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://w3.org/2001/XMLSchema-instance"
xmlns:cxf="http://camel.apache.org/schema/cxf"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
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/jaxrs
http://cxf.apache.org/schemas/jaxrs.xsd
http://camel.apache.org/schema/spring
http://camel.apache.org/schema/spring/camel-spring.xsd
>
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<bean id="helloBean" class="com.examples.camel.cxf.rest.resource.HelloWorldResource" />
<cxf:rsServer id="helloServer" address="/helloapp" loggingFeatureEnabled="true">
<cxf:serviceBeans>
<ref bean="helloBean" />
</cxf:serviceBeans>
<cxf:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
</cxf:providers>
</cxf:rsServer>
<camelContext id="context" xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="cxfrs:bean:helloServer />
<log message="Processing CXF route....http method ${header.CamelHttpMethod}" />
<log message="Processing CXF route....path is ${header.CamelHttpPath}" />
<log message="Processing CXF route....body is ${body}" />
<choice>
<when>
<simple>${header.operationName} == 'sayHello'</simple>
<to uri="direct:invokeSayHello" />
</when>
<when>
<simple>${header.operationName} == 'greet'</simple>
<to uri="direct:invokeGreet" />
</when>
</choice>
</route>
<route id="invokeSayHello">
<from uri="direct:invokeSayHello" />
<bean ref="helloBean" method="sayHello" />
</route>
<route id="invokeGreet">
<from uri="direct:invokeGreet" />
<bean ref="helloBean" method="greet" />
</route>
</camelContext>
</beans>
The actual resource implementation class looks like below.
package com.examples.camel.cxf.rest.resource;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
public class HelloWorldResource implements HelloWorldIntf
{
public Response greet() {
return Response.status(Status.OK).
entity("Hi There!!").
build();
}
public Response sayHello(String input) {
Hello hello = new Hello();
hello.setHello("Hello");
hello.setName("Default User");
if(input != null)
hello.setName(input);
return Response.
status(Status.OK).
entity(hello).
build();
}
}
class Hello {
private String hello;
private String name;
public String getHello() { return hello; }
public void setHello(String hello) { this.hello = hello; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
You don't need , and cxf:rsServer> to be provided.
The tag alone will suffice to handle a web service request and invoke a route.
In case you have both and the then invoking the former will not help you in executing a route. For a route to get invoked, the request must reach to the address published by .
Hope this helps.

Silverlight 4 HtmlPage.Document.Cookies is always empty

I'm very much new to silverlight, so please assume I've done something very daft....
I am trying to make a call from a silverlight app to a WCF service and check a value in the session. The value will have been put there by an aspx page. It's a little convoluted, but that's where we are.
My service looks like this:
[ServiceContract]
public interface IExportStatus
{
[OperationContract]
ExportState RequestExportComplete();
}
public enum ExportState
{
Running,
Complete
}
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class ExportStatus : IExportStatus
{
ExportState IExportStatus.RequestExportComplete()
{
// check value of session variable here.
}
}
The site that hosts the silverlight app also hosts the wcf service. Its web config looks like this:
<configuration>
<system.serviceModel>
<services>
<service name="SUV_MVVM.Web.Services.ExportStatus" behaviorConfiguration="MyBehavior">
<endpoint binding="basicHttpBinding"
bindingConfiguration="MyHttpBinding"
contract="SUV_MVVM.Web.Services.IExportStatus"
address="" />
</service>
</services>
<bindings>
<basicHttpBinding>
<binding name="MyHttpBinding" />
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="MyBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
I added the service reference to my silverlight app using the VS tooling acepting the defaults (apart for the namespace)
Initially I was just trying to call the service like this:
var proxy = new ExportStatusClient();
proxy.RequestExportCompleteCompleted += (s, e) =>
{
//Handle result
};
proxy.RequestExportCompleteAsync();
But the session in the service was always empty (not null, just empty), so I tried manually setting the session Id into the request like this:
var proxy = new ExportStatusClient();
using (new OperationContextScope(proxy.InnerChannel))
{
var request = new HttpRequestMessageProperty();
//this might chnage if we alter the cookie name in the web config.
request.Headers["ASP.NET_SessionId"] = GetCookie("ASP.NET_SessionId");
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = request;
proxy.RequestExportCompleteCompleted += (s, e) =>
{
//Handle result
};
proxy.RequestExportCompleteAsync();
}
private string GetCookie(string key)
{
var cookies = HtmlPage.Document.Cookies.Split(';');
return (from cookie in cookies
select cookie.Split('=')
into keyValue
where keyValue.Length == 2 && keyValue[0] == key
select keyValue[1]).FirstOrDefault();
}
But what I'm finding is that the HtmlPage.Document.Cookies property is always empty.
So Am I just missing something really basic, or are there any other things that I need to change or test?
I just did a test from a Silverlight 4 application.
System.Windows.Browser.HtmlPage.Document.Cookies = "KeyName1=KeyValue1;expires=" + DateTime.UtcNow.AddSeconds(10).ToString("R");
System.Windows.Browser.HtmlPage.Document.Cookies = "KeyName2=KeyValue2;expires=" + DateTime.UtcNow.AddSeconds(60).ToString("R");
Each cookie expired as expected.
The value of System.Windows.Browser.HtmlPage.Document.Cookies...
Immediately after setting the cookies: "KeyName1=KeyValue1; KeyName2=KeyValue2"
30 seconds later: "KeyName2=KeyValue2"
60+ seconds later: ""

Resources