Calling Webmethod containing byte array (as in paramaeter)parameter with ksoap2 on android - ksoap

There is WEB service written on C# with next method:
[WebMethod]
public string ByteArrTest(byte[] Buffer)
{
if (Buffer == null) return "buffer is null";
else return Buffer.Length.ToString() + " is buffer length";
}
i 'ld like call this method from android device using Ksoap2 library alike belove (simplified):
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
new MarshalBase64().register(envelope);
envelope.encodingStyle = SoapEnvelope.ENC;
SoapObject request = new SoapObject(this.getNameSpace(), this.getMethodName());
PropertyInfo pi4 = new PropertyInfo();
pi4.setName("Buffer");
byte [] b="this text".getBytes();
pi4.setValue(b);
pi4.setType(byte[].class);
// request.addProperty("buffer", "bytes".getBytes);
request.addProperty(pi4);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport =
new HttpTransportSE(this.getURL());//
androidHttpTransport.call(this.getSoapAction(), envelope);
Object response = envelope.getResponse();
//next implementation
Responce always is "buffer is null"
what is incorrect or wrong?
Thanks for any attention

Posting the whole of your method in Android calling the web service would help more.
I'm using KSoap in an Android project I'm currently working on and I'm retrieving strings. Heres one of my methods modified to match what you need:
private static String NAMESPACE = "http://tempuri.org/";
private static String SOAP_ACTION = "http://tempuri.org/";
private static final String URL = "Your url link to your web services asmx file";
public static String ByteArrTestCall(byte[] t) {
String resTxt = null;
SoapObject request = new SoapObject(NAMESPACE, "ByteArrTest");
// Add the property to request object
request.addProperty("Buffer", t);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug = true;
try
{
androidHttpTransport.call(SOAP_ACTION+"ByteArrTest", envelope);
SoapPrimitive receivedString = (SoapPrimitive) envelope.getResponse();
resTxt = receivedString.toString();
}
catch(Exception e)
{
resTxt = androidHttpTransport.requestDump;
return e.toString() + resTxt;
}
return resTxt;
}

Related

Creating A Service Bus SAS Token and Consuming Relay in WinRT

I have a Service Bus Relay (WCF SOAP) I want to consume in my Windows Store App. I have written the code to create a token as well as the client which is below.
The problem is that I get an AuthorizationFailedFault returned with a faultstring "InvalidSignature: The token has an invalid signature." And I can't figure it out.
My Create Token method:
private static string CreateSasToken()
{
TimeSpan sinceEpoch = DateTime.UtcNow - new DateTime(1970,1, 1);
var expiry = Convert.ToString((int)sinceEpoch.TotalSeconds + 3600);
string stringToSign = webUtility.UrlEncode(ServiceUri.AbsoluteUri) + "\n" + expiry;
string hashKey = Encoding.UTF8.GetBytes(Secret).ToString();
MacAlgorithmProvider macAlgorithmProvider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);
BinaryStringEncoding encoding = BinaryStringEncoding.Utf8;
var messageBuffer = CryptographicBuffer.ConvertStringToBinary(stringToSign,encoding);
IBuffer keyBuffer = CryptographicBuffer.ConvertStringToBinary(hashKey,encoding);
CryptographicKey hmacKey = macAlgorithmProvider.CreateKey(keyBuffer);
IBuffer signedMessage = CryptographicEngine.Sign(hmacKey, messageBuffer);
string signature = CryptographicBuffer.EncodeToBase64String(signedMessage);
var sasToken = String.Format(CultureInfo.InvariantCulture,
"SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}",
WebUtility.UrlEncode(ServiceUri.AbsoluteUri),
WebUtility.UrlEncode(signature), expiry, Issuer);
return sasToken;
}
My Client class:
public partial class ServiceClient
{
public async Task<string> GetDataUsingDataContract(string item, string sasToken)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("ServiceBusAuthorization",sasToken);
client.DefaultRequestHeaders.Add("SOAPAction",".../GetDataUsingDataContract");
client.DefaultRequestHeaders.Add("Host", "xxxxxxxxxxx.servicebus.windows.net");
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post,ServiceUri);
var content =new StringContent(#"<s:Envelope
xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/"">
<s:Header></s:Header><s:Body>"+ item +#"</s:Body>
</s:Envelope>",System.Text.Encoding.UTF8,"application/xml");
request.Content = content;
HttpResponseMessage wcfResponse = client.SendAsync(request).Result;
HttpContent stream = wcfResponse.Content;
var response = stream.ReadAsStringAsync();
var returnPacket = response.Result;
return returnPacket;
}
}
I have been successful consuming the Relay using Http (via Fiddler) by copying an unexpired token created by Micorosft.ServiceBus in a console app.
I figured out a solution which involved both methods being wrong.
CreateSasToken method:
A minor change involved setting the hashKey variable as byte[] and not string. This line:
string hashKey = Encoding.UTF8.GetBytes(Secret).ToString();
Changed to this:
var hashKey = Encoding.UTF8.GetBytes(Secret);
This change meant that I needed to use a different method to set keyBuffer.
This line:
IBuffer keyBuffer = CryptographicBuffer.ConvertStringToBinary(hashKey,encoding);
Change to this:
IBuffer keyBuffer = CryptographicBuffer.CreateFromByteArray(hashKey);
So the new CreateSasToken method is:
private static string GetSasToken()
{
TimeSpan sinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1);
var expiry = Convert.ToString((int)sinceEpoch.TotalSeconds + 3600);
string stringToSign = WebUtility.UrlEncode(ServiceUri.AbsoluteUri) + "\n" + expiry;
var hashKey = Encoding.UTF8.GetBytes(Secret);
MacAlgorithmProvider macAlgorithmProvider =
MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);
const BinaryStringEncoding encoding = BinaryStringEncoding.Utf8;
var messageBuffer = CryptographicBuffer.ConvertStringToBinary(stringToSign,
encoding);
IBuffer keyBuffer = CryptographicBuffer.CreateFromByteArray(hashKey);
CryptographicKey hmacKey = macAlgorithmProvider.CreateKey(keyBuffer);
IBuffer signedMessage = CryptographicEngine.Sign(hmacKey, messageBuffer);
string signature = CryptographicBuffer.EncodeToBase64String(signedMessage);
var sasToken = String.Format(CultureInfo.InvariantCulture,
"SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}",
WebUtility.UrlEncode(ServiceUri.AbsoluteUri),
WebUtility.UrlEncode(signature),
expiry, Issuer);
return sasToken;
}
Service Client Class
A couple of things to note here.
In order for the request to work, the SAS Token had to be added to the header as a parameter of a AuthenticationValueHeader object. So I added the following method to my helper class (ServiceBusHelper) which held the Key, KeyName and SasToken as properties and the CreateSasToken as a method.
public static AuthenticationHeaderValue CreateBasicHeader()
{
return new AuthenticationHeaderValue("Basic", SasToken);
}
The HttpRequestMessage Content property had to be created a special way. Taking the item parameter passed in, which was a serialized WCF DataContract type I needed to do a few things to make the SOAP envelope. Rather than go through them in detail here is the entire class (one method only). I will comment on the code to handle the response immediately following.
public partial class SalesNotifyServiceClient
{
public async Task<string> GetDataUsingDataContract(string item)
{
string returnPacket = "";
string element = "";
try
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("ServiceBusAuthorization",
ServiceBusHelper.CreateBasicHeader().Parameter);
client.DefaultRequestHeaders.Add("SOAPAction",
".../GetDataUsingDataContract");
client.DefaultRequestHeaders.Add("Host",
"xxxxxxxxxx.servicebus.windows.net");
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post,
ServiceBusHelper.ServiceUri);
//Creating the request.Content
var encodedItem = item.Replace("<", "<").Replace(">", ">");
var strRequest =
#"<s:Envelope xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/"">
<s:Header></s:Header><s:Body><GetDataUsingDataContract xmlns=
""http://www.xxxxxxxxxx.com/servicemodel/relay""><item>" +
encodedItem +
#"</item></GetDataUsingDataContract></s:Body></s:Envelope>";
var content = new StringContent(strRequest,
System.Text.Encoding.UTF8, "application/xml");
request.Content = content;
HttpResponseMessage wcfResponse = client.SendAsync(request).Result;
HttpContent stream = wcfResponse.Content;
var response = await stream.ReadAsStringAsync();
//Handling the response
XDocument doc;
using (StringReader s = new StringReader(response))
{
doc = XDocument.Load(s);
}
if (doc.Root != null)
{
element = doc.Root.Value;
}
returnPacket = element;
}
catch (Exception e)
{
var message = e.Message;
}
return returnPacket;
}
}
In order to get at the DataContract object I had to do a few things to the response string. As you can see at the //Handling the response comment above, using StringReader I loaded the returned SOAP envelope as a string into an XDocument and the root value was my serialized DataContract object. I then deserialized the returnPacket variable returned from the method had my response object.

Using OAuthWebSecurity with Salesforce

I'm trying to get an ASP.NET MVC site to accept Salesforce as an authentication provider, but I am not having any luck. I'll start out with the IAuthenticationClient I have so far:
public class SalesForceOAuth2Client : OAuth2Client
{
private readonly String consumerKey;
private readonly String consumerSecret;
#if DEBUG
private const String BaseEndpoint = #"https://test.salesforce.com";
#else
private const String BaseEndpoint = #"https://login.salesforce.com";
#endif
private const String AuthorizeEndpoint = BaseEndpoint + #"/services/oauth2/authorize";
private const String TokenEndpoint = BaseEndpoint + #"/services/oauth2/token";
private const String RevokeEndpoint = BaseEndpoint + #"/services/oauth2/revoke";
public SalesForceOAuth2Client(String consumerKey, String consumerSecret)
: base("SalesForce")
{
if (String.IsNullOrWhiteSpace(consumerKey))
{
throw new ArgumentNullException("consumerKey");
}
if (String.IsNullOrWhiteSpace(consumerSecret))
{
throw new ArgumentNullException("consumerSecret");
}
this.consumerKey = consumerKey;
this.consumerSecret = consumerSecret;
}
protected override Uri GetServiceLoginUrl(Uri returnUrl)
{
String redirect_url = returnUrl.AbsoluteUri;
// Hack to work-around the __provider__ & __sid__ query parameters,
// but it is ultimately useless.
/*String state = String.Empty;
Int32 q = redirect_url.IndexOf('?');
if (q != -1)
{
state = redirect_url.Substring(q + 1);
redirect_url = redirect_url.Substring(0, q);
}*/
var builder = new UriBuilder(AuthorizeEndpoint);
builder.Query = "response_type=code"
+ "&client_id=" + HttpUtility.UrlEncode(this.consumerKey)
+ "&scope=full"
+ "&redirect_uri=" + HttpUtility.UrlEncode(redirect_url)
// Part of the above hack (tried to use `state` parameter)
/*+ (!String.IsNullOrWhiteSpace(state) ? "&state=" + HttpUtility.UrlEncode(state) : String.Empty)*/;
return builder.Uri;
}
protected override IDictionary<String, String> GetUserData(String accessToken)
{
// I am not sure how to get this yet as everything concrete I've
// seen uses the service's getUserInfo call (but this service relies
// heavily on a username, password, token combination. The whole point
// of using oatuh is to avoid asking the user for his/her credentials)
// more information about the original call:
// http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_calls_getuserinfo.htm
// Return static information for now
//TODO: Get information dynamically
return new Dictionary<String, String>
{
{ "username", "BradChristie" },
{ "name", "Brad Christie" }
};
}
protected override String QueryAccessToken(Uri returnUrl, String authorizationCode)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(TokenEndpoint);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
using (StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream()))
{
streamWriter.Write("grant_type=authorization_code");
streamWriter.Write("&client_id=" + HttpUtility.UrlEncode(this.consumerKey));
streamWriter.Write("&client_secret=" + HttpUtility.UrlEncode(this.consumerSecret));
streamWriter.Write("&redirect_uri=" + HttpUtility.UrlEncode(returnUrl.AbsoluteUri));
streamWriter.Write("&code=" + HttpUtility.UrlEncode(authorizationCode));
streamWriter.Flush();
}
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
if (webResponse.StatusCode == HttpStatusCode.OK)
{
using (StreamReader streamReader = new StreamReader(webResponse.GetResponseStream()))
{
String response = streamReader.ReadToEnd();
var queryString = HttpUtility.ParseQueryString(response);
return queryString["access_token"];
}
}
return String.Empty;
}
}
The primary problem is that redirect_uri != Callback Url.
Salesforce enforces the callback URL you supply in the application configuration to match exactly to the value provided in redirect_uri of QueryAccessToken. Unfortunately OAuthWebSecurity relies on DotNetOpenAuth.AspNet, and that library appends two query parameters: __provider__ and __sid__. If I try to remove those (see the hack in GetServiceLoginUrl), obviously the login fails because the hand-back doesn't know how to continue on with the request without knowing which provider to use.
To work around this I did notice that the request call accepts an optional state parameter which is (essentially) there for passing things back and forth across the request/callback. However, with the dependence on __provider__ and __sid__ being their own keys having data=__provider__%3DSalesForce%26__sid__%3D1234567890 is useless.
Is there a work-around without having to fork/recompile the Microsoft.Web.WebPages.OAuth library and modify the OAuthWebSecurity.VerifyAuthenticationCore(HttpContextBase, String) method to look at data first, then continue on to OpenAuthSecurityMananer.GetProviderName?
Also, in case the registration mattered (AuthConfig.cs):
OAuthWebSecurity.RegisterClient(
new SalesForceOAuth2Client(/*consumerKey*/, /*consumerSecret*/),
"SalesForce",
new Dictionary<String, Object>()
);
Update (11.01.2013)
I just got a response back from Salesforce. It looks like they don't know how to implement 3.1.2 of the RFC which means that any query parameters you send in with the return_uri are not only ignored, but prohibited (at least when dynamic in nature). So, it looks like I can't use a library that works on every other platform and follows the standard--i have to create my own.
Sigh.

Twitter API upgrade for Windows Phone

I have tweet poster in my application which uses oAuth 1.0 which will retire soon and will be non functional. I have to upgrade my API to 1.1. Twitter development center says that, If oAuth is used by your application, you can easily transaction to 1.1 by only updating your API endpoint. What exactly is API endpoint?
Here I'm having hard understanding about API endpoint. I think my asyncronous post call URL must be upgraded.
Here is the relevant codes which I think that might include the answer;
private void btnPostTweet_Click(object sender, RoutedEventArgs e)
{
namebocx.Text = userScreenName;
if (txtBoxNewTweet.Text.Trim().Length == 0) { return; }
var credentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = TwitterSettings.consumerKey,
ConsumerSecret = TwitterSettings.consumerKeySecret,
Token = this.accessToken,
TokenSecret = this.accessTokenSecret,
Version = "1.0"
};
var restClient = new RestClient
{
Authority = TwitterSettings.StatusUpdateUrl,
HasElevatedPermissions = true,
Credentials = credentials,
Method = WebMethod.Post
};
restClient.AddHeader("Content-Type", "application/x-www-form-urlencoded");
// Create a Rest Request and fire it
var restRequest = new RestRequest
{
Path = "1/statuses/update.xml?status=" + txtBoxNewTweet.Text //Here must be endpoint of Api??
};
var ByteData = Encoding.UTF8.GetBytes(txtBoxNewTweet.Text);
restRequest.AddPostContent(ByteData);
restClient.BeginRequest(restRequest, new RestCallback(PostTweetRequestCallback));
}
}
and also here is the authentication settings:
public class TwitterSettings
{
public static string RequestTokenUri = "https://api.twitter.com/oauth/request_token";
public static string AuthorizeUri = "https://api.twitter.com/oauth/authorize";
public static string AccessTokenUri = "https://api.twitter.com/oauth/access_token";
public static string CallbackUri = "http://www.google.com";
public static string StatusUpdateUrl { get { return "http://api.twitter.com"; } }
public static string consumerKey = "myconsumerkeyhere";
public static string consumerKeySecret = "myconsumersecrethere";
public static string oAuthVersion = "1.0a";
}
Here what twitter says me to replace with this instead of written in my code;
https://api.twitter.com/1.1/statuses/update.json
and some parameters told here -->> https://dev.twitter.com/docs/api/1.1/post/statuses/update
How should I update my API endpoint, what kind of changes do I have to do?
If you can help me, I really appreciate
You can change this:
Path = "1/statuses/update.xml?status=" + txtBoxNewTweet.Text
//Here must be endpoint of Api??
to this:
Path = "1.1/statuses/update.json?status=" + txtBoxNewTweet.Text
//Here must be endpoint of Api??

WCF- Large Data [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have a WCF Web Service with basicHTTPBinding , the server side the transfer mode is streamedRequest as the client will be sending us large file in the form of memory stream.
But on client side when i use transfer mode as streamedRequest its giving me a this errro
"The remote server returned an error: (400) Bad Request"
And when i look in to trace information , i see this as the error message
Exception: There is a problem with the XML that was received from the network. See inner exception for more details.
InnerException: The body of the message cannot be read because it is empty.
I am able to send up to 5MB of data using trasfermode as buffered , but it will effect the performance of my web service in the long run , if there are many clients who are trying to access the service in buffered transfer mode.
SmartConnect.Service1Client Serv = new SmartConnectClient.SmartConnect.Service1Client();
SmartConnect.OrderCertMailResponse OrderCert = new SmartConnectClient.SmartConnect.OrderCertMailResponse();
OrderCert.UserID = "abcd";
OrderCert.Password = "7a80f6623";
OrderCert.SoftwareKey = "90af1";
string applicationDirectory = #"\\inid\utty\Bran";
byte[] CertMail = File.ReadAllBytes(applicationDirectory + #"\5mb_test.zip");
MemoryStream str = new MemoryStream(CertMail);
//OrderCert.Color = true;
//OrderCert.Duplex = false;
//OrderCert.FirstClass = true;
//OrderCert.File = str;
//OrderCert.ReturnAddress1 = "Test123";
//OrderCert.ReturnAddress2 = "Test123";
//OrderCert.ReturnAddress3 = "Test123";
//OrderCert.ReturnAddress4 = "Test123";
OrderCert.File = str;
//string OrderNumber = "";
//string Password = OrderCert.Password;
//int ReturnCode = 0;
//string ReturnMessage = "";
//string SoftwareKey = OrderCert.SoftwareKey;
//string UserID = OrderCert.UserID;
//OrderCert.File = str;
MemoryStream FileStr = str;
Serv.OrderCertMail(OrderCert);
// Serv.OrderCertMail(ref OrderNumber, ref Password, ref ReturnCode, ref ReturnMessage, ref SoftwareKey, ref UserID, ref FileStr );
lblON.Text = OrderCert.OrderNumber;
Serv.Close();
// My Web Service - Service Contract
[OperationContract]
OrderCertMailResponse OrderCertMail(OrderCertMailResponse OrderCertMail);
[MessageContract]
public class OrderCertMailResponse
{
string userID = "";
string password = "";
string softwareID = "";
MemoryStream file = null;
//MemoryStream str = null;
[MessageHeader]
//[DataMember]
public string UserID
{
get { return userID; }
set { userID = value; }
}
[MessageHeader]
//[DataMember]
public string Password
{
get { return password; }
set { password = value; }
}
[MessageHeader]
//[DataMember]
public string SoftwareKey
{
get { return softwareID; }
set { softwareID = value; }
}
[MessageBodyMember]
// [DataMember]
public MemoryStream File
{
get { return file; }
set { file = value; }
}
[MessageHeader]
//[DataMember]
public string ReturnMessage;
[MessageHeader]
//[DataMember]
public int ReturnCode;
[MessageHeader]
public string OrderNumber;
}
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class Service1 : IService1
{
public OrderCertMailResponse OrderCertMail(OrderCertMailResponse OrderCertMail)
{
OrderService CertOrder = new OrderService();
ClientUserInfo Info = new ClientUserInfo();
ControlFileInfo Control = new ControlFileInfo();
//Info.Password = "f2496623"; // hard coded password for development testing purposes
//Info.SoftwareKey = "6dbb71"; // hard coded software key this is a developement software key
//Info.UserName = "sdfs"; // hard coded UserID - for testing
Info.UserName = OrderCertMail.UserID.ToString();
Info.Password = OrderCertMail.Password.ToString();
Info.SoftwareKey = OrderCertMail.SoftwareKey.ToString();
//Control.ReturnAddress1 = OrderCertMail.ReturnAddress1;
//Control.ReturnAddress2 = OrderCertMail.ReturnAddress2;
//Control.ReturnAddress3 = OrderCertMail.ReturnAddress3;
//Control.ReturnAddress4 = OrderCertMail.ReturnAddress4;
//Control.CertMailFirstClass = OrderCertMail.FirstClass;
//Control.CertMailColor = OrderCertMail.Color;
//Control.CertMailDuplex = OrderCertMail.Duplex;
//byte[] CertFile = new byte[0];
//byte[] CertFile = null;
//string applicationDirectory = #"\\inid\utility\Bryan";
// byte[] CertMailFile = File.ReadAllBytes(applicationDirectory + #"\3mb_test.zip");
//MemoryStream str = new MemoryStream(CertMailFile);
OrderCertMailResponseClass OrderCertResponse = CertOrder.OrderCertmail(Info,Control,OrderCertMail.File);
OrderCertMail.ReturnMessage = OrderCertResponse.ReturnMessage.ToString();
OrderCertMail.ReturnCode = Convert.ToInt32(OrderCertResponse.ReturnCode.ToString());
OrderCertMail.OrderNumber = OrderCertResponse.OrderNumber;
return OrderCertMail;
}
Below are my new operation contract which takes only datastream as a parameter
[OperationContract]
SmartStream SendStream(MemoryStream DataStream);
public SmartStream SendStream(MemoryStream DataStream)
{
OrderService CertOrder = new OrderService();
ClientUserInfo Info = new ClientUserInfo();
ControlFileInfo Control = new ControlFileInfo();
MemoryStream serverStream = null;
Info.Password = "78f24dsfsdf96623";
Info.SoftwareKey = "dfs6dbb71";
Info.UserName = "ssfsdf";
using (serverStream = new MemoryStream(100))
{
int count = 0;
const int buffLen = 4096;
byte[] buf = new byte[buffLen];
while ((count = CertFile.Read(buf, 0, buffLen)) > 0)
{
serverStream.Write(buf, 0, count);
}
CertFile.Close();
serverStream.Close();
return null;
}
My client method to access
protected void Page_Load(object sender, EventArgs e)
{
SmartConnect.Service1Client Serv = new
SmartConnectClient.SmartConnect.Service1Client();
string applicationDirectory = #"\\intrepid\utility\Bryan";
byte[] CertMail = File.ReadAllBytes(applicationDirectory + #"\100mb_test.zip");
MemoryStream str = new MemoryStream(CertMail);
SmartConnectClient.SmartConnect.SendStreamRequest request =
new SmartConnectClient.SmartConnect.SendStreamRequest();
SmartConnectClient.SmartConnect.SmartStream SmartStr =
new SmartConnectClient.SmartConnect.SmartStream();
request.DataStream = str;
SmartConnectClient.SmartConnect.SendStreamResponse response = Serv.SendStream(request);
}
Pinu, I still think you're probably not doing the service contract right for WCF streaming. See the MSDN docs on WCF Streaming - especially this section on restrictions:
Restrictions on Streamed Transfers
Using the streamed transfer mode
causes the run time to enforce
additional restrictions.
Operations that occur across a
streamed transport can have a contract
with at most one input or output
parameter. That parameter corresponds
to the entire body of the message and
must be a Message, a derived type of
Stream, or an IXmlSerializable
implementation. Having a return value
for an operation is equivalent to
having an output parameter.
From your code posted, I'm still under the impression you're trying to mix both buffered and streamed transfers.
If you want to have real streaming, your service contract must look something like:
[ServiceContract(Namespace=".....")]
interface IUploadFileService
{
[OperationContract]
UploadResponse UploadFile(Stream file);
}
That's about all you can have in your service contract for that service method.
Also have a look at some really good blog posts on streaming here and here.
#Marc - Thank you so much for all the your help. It helped me fix many of the problems of my service.
The web service started working when I ran it on local IIS on my machine , it was throwing all those errors when I was running on the Visual Studio development server. I could not figure why it is so , why it did not run on Visual studio development server.

HTTP Authentication with Web References

I have a web reference created from the WSDL, but I'm not allowed to call the function unless I pass in the username / password; the original code for the XML toolkit was:
Set client = CreateObject("MSSOAP.SOAPClient30")
URL = "http://" & host & "/_common/webservices/Trend?wsdl"
client.mssoapinit (URL)
client.ConnectorProperty("WinHTTPAuthScheme") = 1
client.ConnectorProperty("AuthUser") = user
client.ConnectorProperty("AuthPassword") = passwd
On Error GoTo err
Dim result1() As String
result1 = client.getTrendData(expression, startDate, endDate,
limitFromStart, maxRecords
How do I add the AuthUser/AuthPassword to my new code?
New code:
ALCServer.TrendClient tc = new WindowsFormsApplication1.ALCServer.TrendClient();
foreach(string s in tc.getTrendData(textBox2.Text, "5/25/2009", "5/28/2009", false, 500))
textBox1.Text+= s;
Found it: Even if Preauthenticate==True, it doesn't do it. You have to overried the WebRequest:
protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
HttpWebRequest request;
request = (HttpWebRequest)base.GetWebRequest(uri);
if (PreAuthenticate)
{
NetworkCredential networkCredentials =
Credentials.GetCredential(uri, "Basic");
if (networkCredentials != null)
{
byte[] credentialBuffer = new UTF8Encoding().GetBytes(
networkCredentials.UserName + ":" +
networkCredentials.Password);
request.Headers["Authorization"] =
"Basic " + Convert.ToBase64String(credentialBuffer);
}
else
{
throw new ApplicationException("No network credentials");
}
}
return request;
}
Since it gets created as a partial class, you can keep the stub in a separate file and rebuilding the Reference.cs won't clobber you.