WebDAV with J2ME - http

Is there a way to use WebDAV with J2ME (some libraries or manual coding)?
I've tried:
- javax.microedition.io.HttpConnection, but "SEARCH" method not supported there
- javax.microedition.io.SocketConnection with Http request - nothing returns in response
Maybe something wrong with my code or HTTP header:
String response = "";
String query = "<?xml version='1.0'?> "
+ "<g:searchrequest xmlns:g='DAV:'> "
+ "<g:sql> "
+ "SELECT 'DAV:displayname' "
+ "FROM 'http://exchangeserver.com/Public/' "
+ "</g:sql> "
+ "</g:searchrequest> ";
String len = String.valueOf(query.length());
SocketConnection hc = (SocketConnection) Connector
.open("socket://exchangeserver.com:8080");
DataOutputStream dout =
new DataOutputStream(hc.openOutputStream());
DataInputStream din = new DataInputStream(hc.openInputStream());
String userPass = "username" + ":" + "password";
byte[] encoded =
Base64OutputStream.encode(userPass.getBytes(), 0,
userPass.length(), false, false);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
String request = "SEARCH /Public/ HTTP/1.1\r\n"
+"Content-Type:text/xml\r\nContent-Length:"
+ len
+ "\r\nAuthorization:Basic "
+ new String(encoded)
+ "\r\n\r\n";
bos.write(request.getBytes());
bos.write(query.getBytes());
dout.write(bos.toByteArray());
dout.flush();
dout.close();
byte[] bs = new byte[900];
din.readFully(bs);
bos = new ByteArrayOutputStream();
bos.write(bs);
din.close();
hc.close();
response = bos.toString();

What do you mean by "nothing returns"? No response body? No status code?
I recommend to trace what's going on on the "wire"...
UPDATE: have you tried adding a host header?

Julian +1 you was right for Host property, QRSO +1, thanks to all!
So,
- I have found free WebDAV service MyDisk.se (SEARCH not allowed, so I used PROPFIND)
- used WFetch to play around with WebDAV request
- used Network Monitor to compare requests from WFetch and my app.
:) Finally it's working!
Result code:
String response = "";
String query = "<?xml version='1.0' encoding='UTF-8'?>\r\n"
+ "<d:propfind xmlns:d='DAV:'>\r\n"
+ "<d:prop><d:getcontenttype/></d:prop>\r\n"
+ "<d:prop><d:getcontentlength/></d:prop>\r\n"
+ "</d:propfind>\r\n";
String len = String.valueOf(query.length());
SocketConnection hc = (SocketConnection) Connector
.open("socket://79.99.7.153:80");
DataOutputStream dout = new DataOutputStream(hc.openOutputStream());
DataInputStream din = new DataInputStream(hc.openInputStream());
String userPass = "login" + ":" + "password";
byte[] encoded = Base64OutputStream.encode(userPass.getBytes(), 0,
userPass.length(), false, false);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
String request = "PROPFIND /mgontar/ HTTP/1.1\r\n"
+ "Depth: 1\r\n"
+ "Host: mydisk.se:80\r\n"
+ "Accept: */*\r\n"
+ "Content-Type: text/xml\r\n"
+ "Content-Length: " + len
+ "\r\nAuthorization: Basic " + new String(encoded)
+ "\r\n\r\n";
bos.write(request.getBytes());
bos.write(query.getBytes());
dout.write(bos.toByteArray());
dout.flush();
dout.close();
byte[] bs = new byte[900];
din.readFully(bs);
bos = new ByteArrayOutputStream();
bos.write(bs);
din.close();
hc.close();
response = bos.toString();

FYI If you are testing on an actual mobile phone, then there is a fair chance your mobile network operator could be blocking non-HTTP traffic.
You might want to first check that you can make GET and POST requests to the server first.

Related

How to add file attachment to Email message sent from Razor page (with ASP.NET Core and MailKit)

The following is a method for sending an Email from a Razor page in ASP.NET Core. I need to use MailKit since System.Net.Mail is not available in ASP.NET Core.
Despite much research, I haven't been able to figure out a way to include the image to the Email. Note that it doesn't have to be an attachment - embedding the image will work.
public ActionResult Contribute([Bind("SubmitterScope, SubmitterLocation, SubmitterItem, SubmitterCategory, SubmitterEmail, SubmitterAcceptsTerms, SubmitterPicture")]
EmailFormModel model)
{
if (ModelState.IsValid)
{
try
{
var emailName= _appSettings.EmailName;
var emailAddress = _appSettings.EmailAddress;
var emailPassword = _appSettings.EmailPassword;
var message = new MimeMessage();
message.From.Add(new MailboxAddress(emailName, emailAddress));
message.To.Add(new MailboxAddress(emailName, emailAddress));
message.Subject = "Record Submission From: " + model.SubmitterEmail.ToString();
message.Body = new TextPart("plain")
{
Text = "Scope: " + model.SubmitterScope.ToString() + "\n" +
"Zip Code: " + model.SubmitterLocation.ToString() + "\n" +
"Item Description: " + model.SubmitterItem.ToString() + "\n" +
"Category: " + model.SubmitterCategory + "\n" +
"Submitted By: " + model.SubmitterEmail + "\n" +
// This is the file that should be attached.
//"Picture: " + model.SubmitterPicture + "\n" +
"Terms Accepted: " + model.SubmitterAcceptsTerms + "\n"
};
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 587);
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
// Note: only needed if the SMTP server requires authentication
client.Authenticate(emailAddress, emailPassword);
client.Send(message);
client.Disconnect(true);
return RedirectToAction("Success");
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message + ": " + ex.StackTrace);
return RedirectToAction("Failure");
}
}
else
{
return View();
}
}
This is from the FAQ on Mailkit github repo, and seems to cover the full process.
https://github.com/jstedfast/MailKit/blob/master/FAQ.md#CreateAttachments
var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("Joey", "joey#friends.com"));
message.To.Add (new MailboxAddress ("Alice", "alice#wonderland.com"));
message.Subject = "How you doin?";
// create our message text, just like before (except don't set it as the message.Body)
var body = new TextPart ("plain") {
Text = #"Hey Alice,
What are you up to this weekend? Monica is throwing one of her parties on
Saturday and I was hoping you could make it.
Will you be my +1?
-- Joey
"
};
// create an image attachment for the file located at path
var attachment = new MimePart ("image", "gif") {
ContentObject = new ContentObject (File.OpenRead (path), ContentEncoding.Default),
ContentDisposition = new ContentDisposition (ContentDisposition.Attachment),
ContentTransferEncoding = ContentEncoding.Base64,
FileName = Path.GetFileName (path)
};
// now create the multipart/mixed container to hold the message text and the
// image attachment
var multipart = new Multipart ("mixed");
multipart.Add (body);
multipart.Add (attachment);
// now set the multipart/mixed as the message body
message.Body = multipart;

Follow Company issue (LinkedIn API)

I am trying to follow a company without success.
I have generated an access token for all scopes which also works for other functions with the API:
scope=w_messages+rw_company_admin+rw_nus+r_emailaddress+r_basicprofile+rw_groups+r_fullprofile+r_network+r_contactinfo
The below code reaches the end and shows the MessageBox with message:
"BadRequest,Can not parse JSON company document.\nRequest body:\n\nError:\nnull"
I will be happy for help. I have follwed the below documentation but it doesn't exactly show how to follow the company, so it leaves me with this question and example below:
https://developer.linkedin.com/documents/company-follow-and-suggestions
String companyID = "9288340";
requestUrl = "https://api.linkedin.com/v1/people/~/following/companies/id=" + companyID + "?oauth2_access_token=MYTOKENGOESHERE";
RestSharp.RestClient rc = new RestSharp.RestClient();
RestSharp.RestRequest request = new RestSharp.RestRequest(requestUrl, RestSharp.Method.POST); //POST = Follow
request.AddHeader("Content-Type", "application/json");
request.AddHeader("x-li-format", "json");
request.RequestFormat = RestSharp.DataFormat.Json;
RestSharp.RestResponse restResponse = (RestSharp.RestResponse)rc.Execute(request);
RestSharp.ResponseStatus responseStatus = restResponse.ResponseStatus;
MessageBox.Show(restResponse.StatusCode.ToString() + "," + restResponse.Content.ToString());
After a lot of testing, I just managed to be able to follow a company.
So the below code is working:
requestUrl = "https://api.linkedin.com/v1/people/~/following/companies?oauth2_access_token=MYTOKENGOESHERE";
var BODY = new
{
id = "9288340" //companyID
};
RestSharp.RestClient rc = new RestSharp.RestClient();
RestSharp.RestRequest request = new RestSharp.RestRequest(requestUrl, RestSharp.Method.POST); //POST = Follow
request.AddHeader("Content-Type", "application/json");
request.AddHeader("x-li-format", "json");
request.RequestFormat = RestSharp.DataFormat.Json;
request.AddBody(BODY);
RestSharp.RestResponse restResponse = (RestSharp.RestResponse)rc.Execute(request);
RestSharp.ResponseStatus responseStatus = restResponse.ResponseStatus;
MessageBox.Show(restResponse.StatusCode.ToString() + "," + restResponse.Content.ToString());

HTTP delete request in J2ME

I'm trying to send an delete request on a Rails Server from J2ME
The output is
STATUS: 422
and the element is not deleted.
Here's the code:
HttpConnection hc = null;
InputStream istrm = null;
String msg = "_method=DELETE";
System.out.println(id);
try {
hc = (HttpConnection) Connector.open(server + "documents/" + id + ".xml");
hc.setRequestMethod(HttpConnection.POST);
hc.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
hc.setRequestProperty("Content-length", "" + msg.getBytes().length);
OutputStream out = hc.openOutputStream();
out.write(msg.getBytes());
out.close();
System.out.println("STATUS: " + hc.getResponseCode()+ hc.getResponseMessage());
Add the following statements before closing outputstream
int res_code=hc.getResponseCode();
if(res_code==HttpConnection.HTTP_OK)
{
//Success
}
else
{
//Failure
}
.........
//After performing all operations then close streams and connection
out.close();
hc.close();
Try it.All the best

Amazon CloudFront invalidation in ASP.Net

I am not sure how to send a request using ASP.Net to Amazon CloudFront to invalidate an object.
The details are here http://docs.amazonwebservices.com/AmazonCloudFront/latest/DeveloperGuide/index.html?Invalidation.html
but I am not sure how to implement this in ASP.Net.
The accepted answer no longer works as of the latest version of the AWS SDK for .NET (1.5.8.0). This should do the trick:
using Amazon;
using Amazon.CloudFront.Model;
...
var client = AWSClientFactory.CreateAmazonCloudFrontClient(accessKey, secretKey);
client.CreateInvalidation(new CreateInvalidationRequest {
DistributionId = distributionID,
InvalidationBatch = new InvalidationBatch {
Paths = new Paths {
Quantity = arrayofpaths.Length,
Items = arrayofpaths.ToList()
},
CallerReference = DateTime.Now.Ticks.ToString()
}
});
Got it working, here it is if anyone else finds it useful.
public static void InvalidateContent(string distributionId, string fileName)
{
string httpDate = Helpers.GetHttpDate();
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = #"<InvalidationBatch>" +
" <Path>/" + fileName + "</Path>" +
" <CallerReference>" + httpDate + "</CallerReference>" +
"</InvalidationBatch>";
byte[] data = encoding.GetBytes(postData);
// Prepare web request...
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://cloudfront.amazonaws.com/2010-08-01/distribution/" + distributionId + "/invalidation");
webRequest.Method = "POST";
webRequest.ContentType = "text/xml";
webRequest.Headers.Add("x-amz-date", httpDate);
Encoding ae = new UTF8Encoding();
HMACSHA1 signature = new HMACSHA1(ae.GetBytes(GlobalSettings.AWSSecretAccessKey.ToCharArray()));
string b64 = Convert.ToBase64String(signature.ComputeHash(ae.GetBytes(webRequest.Headers["x-amz-date"].ToCharArray())));
webRequest.Headers.Add(HttpRequestHeader.Authorization, "AWS" + " " + GlobalSettings.AWSAccessKeyId + ":" + b64);
webRequest.ContentLength = data.Length;
Stream newStream = webRequest.GetRequestStream();
// Send the data.
newStream.Write(data, 0, data.Length);
newStream.Close();
}
/// <summary>
/// Gets a proper HTTP date
/// </summary>
public static string GetHttpDate()
{
// Setting the Culture will ensure we get a proper HTTP Date.
string date = System.DateTime.UtcNow.ToString("ddd, dd MMM yyyy HH:mm:ss ", System.Globalization.CultureInfo.InvariantCulture) + "GMT";
return date;
}
Here's a python version of the above, if anyone finds it useful
from datetime import datetime
import urllib2, base64, hmac, hashlib
def getHTTPDate():
return datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S UTC")
def submitInvalidationRequest(fileName,distributionId):
url = "https://cloudfront.amazonaws.com/2010-08-01/distribution/" + distributionId + "/invalidation"
httpDate = getHTTPDate();
postData = "<InvalidationBatch>" +"<Path>/" + fileName + "</Path>" +"<CallerReference>" + httpDate + "</CallerReference>" +"</InvalidationBatch>";
sig = hmac.new(AWSSecretAccessKey, unicode(httpDate), hashlib.sha1)
headers = {"ContentType": "text/xml",
"x-amz-date": httpDate,
"Authorization":"AWS " + AWSAccessKeyId + ":" + base64.b64encode( sig.digest() )}
req = urllib2.Request(url,postData,headers)
return urllib2.urlopen(req).read()
using the AWSSDK .net api wrapper from amazon makes this task even easier.
using Amazon.CloudFront.Model;
...
var client = Amazon.AWSClientFactory.CreateAmazonCloudFrontClient(ConfigurationManager.AppSettings["Aws.AccessKey"],
ConfigurationManager.AppSettings["Aws.SecretKey"]);
var request = new PostInvalidationRequest();
request.DistributionId = ConfigurationManager.AppSettings["Cdn.DistributionId"];
request.InvalidationBatch = new InvalidationBatch();
request.InvalidationBatch.CallerReference = new Guid().ToString();
request.InvalidationBatch.Paths = PathsInput.Text.Split(new[]{'\n','\r'},StringSplitOptions.RemoveEmptyEntries).ToList();
var response = client.PostInvalidation(request);
Here's perl:
use warnings;
use strict;
use HTTP::Date;
use Digest::SHA qw(hmac_sha1);
use LWP::UserAgent;
use MIME::Base64;
use Encode qw(encode_utf8);
#ARGV == 4 || die "usage: $0 url distribution_id accesskey secretkey\n";
my $invalid_url = $ARGV[0];
my $distribution_id = $ARGV[1];
my $accesskey = $ARGV[2];
my $secretkey = $ARGV[3];
my $url = "https://cloudfront.amazonaws.com/2010-11-01/distribution/$distribution_id/invalidation";
my $date = time2str;
my $post_data = <<HERE;
<?xml version="1.0" encoding="UTF-8"?>
<InvalidationBatch>
<Path>$invalid_url</Path>
<CallerReference>$date</CallerReference>
</InvalidationBatch>
HERE
my $sig = encode_base64(hmac_sha1(encode_utf8($date),encode_utf8($secretkey)));
my $browser = LWP::UserAgent->new;
my $res = $browser->post($url,
"Content" => $post_data,
"ContentType" => "text/xml",
"x-amz-date" => $date,
"Authorization" => "AWS $accesskey:$sig");
print $res->status_line, "\n", $res->content;

Proper web redirection with JS window.open call

On a testing server my URL=
http:
//scantdev04:8086/ActivityReport.aspx
I want to prefill a new URL with query data and pass it to the new url:
string sUrl = sRelativePath + "?Organization=" + sOrganization
+ "&&StartDate=" + sStartDate
+ "&&EndDate=" + endDate;
string displayScript = "" +
"window.open('" + sUrl + "', 'DisplayReport', " +
"'width=1200, height=800, toolbar=yes, menubar=yes, resizable=yes, scrollbars=yes')" +
"";
Pretty straight forward.
On dev box, localhost, it is all good.
But in test, the URL spits out like:
http://www.displayreport.aspx/?Organization=Correctional%20Alternatives,%20Inc&&StartDate=09-01-2009&&EndDate=10/6/2009%2012:00:00%20AM
How do I fix the www. that is now there and repeat the "http://scantdev04:8086/"
I would rather not push this to the web.config but will if necessary.
Where does your sRelativePath string come from?
Found this and it seems to work:
old version:
string sRelativePath = Request.ApplicationPath + "/DisplayReport.aspx";
Now changed to :
string sRelativePath = GetWebAppRoot() + "/DisplayReport.aspx";
GetWebRoot() :
string host = (HttpContext.Current.Request.Url.IsDefaultPort) ?
HttpContext.Current.Request.Url.Host : HttpContext.Current.Request.Url.Authority;
host = String.Format("{0}://{1}", HttpContext.Current.Request.Url.Scheme, host);
if (HttpContext.Current.Request.ApplicationPath == "/")
return host;
else
return host + HttpContext.Current.Request.ApplicationPath;

Resources