Azure http-put UnityWebRequest on android - android

I'm trying to upload a video to a private Azure blob. The UnityWebRequest works perfectly on PC, but once it's built on an Android device it keeps returning a 403 error.
For debugging I tried to use the normal HttpWebRequest on the android device, with the same settings, which works fine. It's not an option to switch over to HttpWebRequest.
I'm wondering whether the HttpWebRequest has some default options that the UnityWebRequest doesn't, or if perhaps anyone knows of other issues?
HttpWebRequest: Works on both devices
I can provide code if necessary.
[Update]
public IEnumerator PutBlob(string filePath, string blockBlobReference)
{
String httpMethod = "PUT";
Byte[] blobContent = File.ReadAllBytes(filePath);
Int32 blobLength = blobContent.Length;
const String blobType = "BlockBlob";
String urlPath = String.Format("{0}/{1}", AzureStorageConstants.container, blockBlobReference);
String msVersion = "2009-09-19";
//String msVersion = "2015-02-21";
String dateInRfc1123Format = DateTime.UtcNow.AddHours(1).ToString("R", CultureInfo.InvariantCulture);
String canonicalizedHeaders = String.Format("x-ms-blob-type:{0}\nx-ms-date:{1}\nx-ms-version:{2}", blobType, dateInRfc1123Format, msVersion);
String canonicalizedResource = String.Format("/{0}/{1}", AzureStorageConstants.Account, urlPath);
String stringToSign = String.Format("{0}\n\n\n{1}\n\n\n\n\n\n\n\n\n{2}\n{3}", httpMethod, blobLength, canonicalizedHeaders, canonicalizedResource);
String authorizationHeader = CreateAuthorizationHeader(stringToSign);
Uri uri = new Uri(AzureStorageConstants.BlobEndPoint + urlPath);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = httpMethod;
request.Headers.Add("x-ms-blob-type", blobType);
request.Headers.Add("x-ms-date", dateInRfc1123Format);
request.Headers.Add("x-ms-version", msVersion);
request.Headers.Add("Authorization", authorizationHeader);
request.ContentLength = blobLength;
ServicePointManager.ServerCertificateValidationCallback = MyRemoteCertificateValidationCallback;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(blobContent, 0, blobLength);
yield return requestStream;
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
String ETag = response.Headers["ETag"];
}
}
UnityWebRequest: Works on computer, but not on android
public IEnumerator PutBlob(string filePath, string blockBlobReference)
{
String httpMethod = "PUT";
Byte[] blobContent = File.ReadAllBytes(filePath);
Int32 blobLength = blobContent.Length;
const String blobType = "BlockBlob";
String urlPath = String.Format("{0}/{1}", AzureStorageConstants.container, blockBlobReference);
String msVersion = "2009-09-19";
//String msVersion = "2015-02-21";
String dateInRfc1123Format = DateTime.UtcNow.AddHours(1).ToString("R", CultureInfo.InvariantCulture);
String canonicalizedHeaders = String.Format("x-ms-blob-type:{0}\nx-ms-date:{1}\nx-ms-version:{2}", blobType, dateInRfc1123Format, msVersion);
String canonicalizedResource = String.Format("/{0}/{1}", AzureStorageConstants.Account, urlPath);
String stringToSign = String.Format("{0}\n\n\n{1}\n\n\n\n\n\n\n\n\n{2}\n{3}", httpMethod, blobLength, canonicalizedHeaders, canonicalizedResource);
String authorizationHeader = CreateAuthorizationHeader(stringToSign);
Uri uri = new Uri(AzureStorageConstants.BlobEndPoint + urlPath);
ServicePointManager.ServerCertificateValidationCallback = MyRemoteCertificateValidationCallback;
using (UnityWebRequest webRequest = new UnityWebRequest())
{
webRequest.SetRequestHeader("x-ms-blob-type", blobType);
webRequest.SetRequestHeader("x-ms-date", dateInRfc1123Format);
webRequest.SetRequestHeader("x-ms-version", msVersion);
webRequest.SetRequestHeader("Authorization", authorizationHeader);
UploadHandler uploadHandler = new UploadHandlerRaw(blobContent);
webRequest.uploadHandler = uploadHandler;
uploadHandler.contentType =
webRequest.url = uri.ToString();
webRequest.method = httpMethod;
webRequest.Send();
while (!webRequest.isDone)
{
ProgressBar = webRequest.uploadProgress;
yield return null;
}
}
}

Related

fcm push notification to mobile with topic messaging using C#

We have an important requirement to push notification to more than 50000 mobile users (Android & IOS). We were implemented this by Topic Messaging. We created batch for every 998 users, and then push to the fcm using topic. But the delivery of push notification is inaccurate. Sometime, some devices get the notification message and some times, no devices. We were use only two topics, one for Android and other for IOS. Sending multiple batches(each batch contains 998 tokens) to the Same topic. Can you please share whats the issue behind this, or please share how to achieve the above scenario.
Batch Push
public string pushBatchbasedonTopic(string Topic, List<string> RegisterIds)
{
_basemobile.WriteToLog("\n Log pushBatchbasedonTopic: ","");
string topic = Topic;
string str = null;
try
{
string senderId = WebConfigurationManager.AppSettings["FCM_SENDER_ID"].ToString();
string applicationkey = WebConfigurationManager.AppSettings["FCM_KEY"].ToString();
WebRequest tRequest = WebRequest.Create("https://iid.googleapis.com/iid/v1:batchAdd");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
tRequest.Timeout = 600000;
var dataser = new
{
to = topic,
registration_tokens = RegisterIds.ToArray()
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(dataser);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationkey));
tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
tRequest.ContentLength = byteArray.Length;
_basemobile.WriteToLog("\n Log tRequest: ", tRequest.ToString());
using (Stream dataStream = tRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
using (WebResponse tResponse = tRequest.GetResponse())
{
using (Stream dataStreamResponse = tResponse.GetResponseStream())
{
using (StreamReader tReader = new StreamReader(dataStreamResponse))
{
String sResponseFromServer = tReader.ReadToEnd();
str = sResponseFromServer;
_basemobile.WriteToLog("\n Log sResponseFromServer: ", sResponseFromServer);
}
}
}
}
_basemobile.WriteToLog("\n Log TopicCreation: " + str, "");
return str;
}
catch (Exception ex)
{
str = ex.Message;
_basemobile.WriteToLog("\n Log topic creation error: " + ex.Message, "");
_basemobile.WriteToLog("\n Stack Trace topic creation: " + ex.StackTrace, "");
_basemobile.WriteToLog("\n InnerException topic creation: " + ex.InnerException, "");
return str;
}
}
FCM Push
public string pushusingFCMforBatchAndroidBasedOnOneTopic(string Id, string Condition, string Message, string Type, string count)
{
_basemobile.WriteToLog("\n Log pushusingFCMforBatchAndroidBasedOnOneTopic: ", "");
string setcondition = Condition;
//string deviceId = DeviceToken;
string str = null;
try
{
string senderId = WebConfigurationManager.AppSettings["FCM_SENDER_ID"].ToString();
string applicationkey = WebConfigurationManager.AppSettings["FCM_KEY"].ToString();
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
tRequest.Timeout = 600000;
var dataser = new
{
//to = deviceId,
condition = setcondition,
data = new
{
Notification_Id = Id,
msg_type = Type,
Count = count,
sound = "Enabled",
body = Message,
badge = count
}
// count = 0,
//type = Type
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(dataser);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationkey));
tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
tRequest.ContentLength = byteArray.Length;
_basemobile.WriteToLog("\n Log tRequest: ", tRequest.ToString());
using (Stream dataStream = tRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
using (WebResponse tResponse = tRequest.GetResponse())
{
using (Stream dataStreamResponse = tResponse.GetResponseStream())
{
using (StreamReader tReader = new StreamReader(dataStreamResponse))
{
String sResponseFromServer = tReader.ReadToEnd();
str = sResponseFromServer;
_basemobile.WriteToLog("\n Log sResponseFromServer: ", sResponseFromServer);
}
}
}
}
_basemobile.WriteToLog("\n Log pushfcmandroid: " + str, "");
return str;
}
catch (Exception ex)
{
str = ex.Message;
_basemobile.WriteToLog("\n Log errorios: " + ex.Message, "");
_basemobile.WriteToLog("\n Stack Traceios: " + ex.StackTrace, "");
_basemobile.WriteToLog("\n Inner Exceptionios: " + ex.InnerException, "");
return str;
}
}

500 internal server error when writing file to the server

I'm developing an android app with Xamarin that uploads file to the server. My server is asp.net based and is hosted by azure. Xamarin throws this error when the code tries to write the file to the server directory. The code I'm using to post the file to the server is as follows:
public async Task<HttpResponseMessage> UploadFile(byte[] file)
{
videoThumbName = Guid.NewGuid().ToString();
var progress = new System.Net.Http.Handlers.ProgressMessageHandler();
progress.HttpSendProgress += progress_HttpSendProgress;
using (var client = HttpClientFactory.Create(progress))
{
client.BaseAddress = new Uri(GlobalVariables.host);
// Set the Accept header for BSON.
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/bson"));
var request = new uploadFileModel { data = file, dateCreated = DateTime.Now, fileName = fileName, username = loggedUser, VideoThumbName = videoThumbName};
// POST using the BSON formatter.
MediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();
var m = client.MaxResponseContentBufferSize;
var result = await client.PostAsync("api/media/upload", request, bsonFormatter);
return result.EnsureSuccessStatusCode();
}
}
I've tried using a try catch block and the weird thing is that the exception is caught even after the file has been written to the path and I get the 500 internal server error. So far every file I tried to upload was save to the path but I can't figure out why is error occurring.
My server side code looks like the following:
[HttpPost]
[Route("upload")]
public async Task<HttpResponseMessage> Upload(uploadFileModel model)
{
var result = new HttpResponseMessage(HttpStatusCode.OK);
if (ModelState.IsValid)
{
string thumbname = "";
string resizedthumbname = Guid.NewGuid() + "_yt.jpg";
string FfmpegPath = Encoding_Settings.FFMPEGPATH;
string tempFilePath = Path.Combine(HttpContext.Current.Server.MapPath("~/tempuploads"), model.fileName);
string pathToFiles = HttpContext.Current.Server.MapPath("~/tempuploads");
string pathToThumbs = HttpContext.Current.Server.MapPath("~/contents/member/" + model.username + "/thumbs");
string finalPath = HttpContext.Current.Server.MapPath("~/contents/member/" + model.username + "/flv");
string resizedthumb = Path.Combine(pathToThumbs, resizedthumbname);
var outputPathVid = new MediaFile { Filename = Path.Combine(finalPath, model.fileName) };
var inputPathVid = new MediaFile { Filename = Path.Combine(pathToFiles, model.fileName) };
int maxWidth = 380;
int maxHeight = 360;
var namewithoutext = Path.GetFileNameWithoutExtension(Path.Combine(pathToFiles, model.fileName));
thumbname = model.VideoThumbName;
string oldthumbpath = Path.Combine(pathToThumbs, thumbname);
var fileName = model.fileName;
try
{
File.WriteAllBytes(tempFilePath, model.data);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
if (model.fileName.Contains("audio"))
{
File.WriteAllBytes(Path.Combine(finalPath, model.fileName), model.data);
string audio_thumb = "mic_thumb.jpg";
string destination = Path.Combine(pathToThumbs, audio_thumb);
string source = Path.Combine(pathToFiles, audio_thumb);
if (!System.IO.File.Exists(destination))
{
System.IO.File.Copy(source, destination, true);
}
Video_Struct vd = new Video_Struct();
vd.CategoryID = 0; // store categoryname or term instead of category id
vd.Categories = "";
vd.UserName = model.username;
vd.Title = "";
vd.Description = "";
vd.Tags = "";
vd.OriginalVideoFileName = model.fileName;
vd.VideoFileName = model.fileName;
vd.ThumbFileName = "mic_thumb.jpg";
vd.isPrivate = 0;
vd.AuthKey = "";
vd.isEnabled = 1;
vd.Response_VideoID = 0; // video responses
vd.isResponse = 0;
vd.isPublished = 1;
vd.isReviewed = 1;
vd.Thumb_Url = "none";
//vd.FLV_Url = flv_url;
vd.Embed_Script = "";
vd.isExternal = 0; // website own video, 1: embed video
vd.Type = 0;
vd.YoutubeID = "";
vd.isTagsreViewed = 1;
vd.Mode = 0; // filter videos based on website sections
long videoid = VideoBLL.Process_Info(vd, false);
}
The exception doesn't reveal much for me to understand the issue. Strangely I don't get any errors when I'm sending request to the local server. Any idea what might be wrong here?
Edit:
The exception no longer occurring when I get the internal server error at this line of my code using (var engine = new Engine()) This is a library I'm trying to use to encode a media file. If everything works on the local server then why doesn't it on the live server :/
using (var engine = new Engine())
{
engine.GetMetadata(inputPathVid);
// Saves the frame located on the 15th second of the video.
var outputPathThumb = new MediaFile { Filename = Path.Combine(pathToThumbs, thumbname+".jpg") };
var options = new ConversionOptions { Seek = TimeSpan.FromSeconds(0), CustomHeight = 360, CustomWidth = 380 };
engine.GetThumbnail(inputPathVid, outputPathThumb, options);
}
Image image = Image.FromFile(Path.Combine(pathToThumbs, thumbname+".jpg"));
//var ratioX = (double)maxWidth / image.Width;
//var ratioY = (double)maxHeight / image.Height;
//var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(maxWidth);
var newHeight = (int)(maxHeight);
var newImage = new Bitmap(newWidth, newHeight);
Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
Bitmap bmp = new Bitmap(newImage);
bmp.Save(Path.Combine(pathToThumbs, thumbname+"_resized.jpg"));
//File.Delete(Path.Combine(pathToThumbs, thumbname));
using (var engine = new Engine())
{
var conversionOptions = new ConversionOptions
{
VideoSize = VideoSize.Hd720,
AudioSampleRate = AudioSampleRate.Hz44100,
VideoAspectRatio = VideoAspectRatio.Default
};
engine.GetMetadata(inputPathVid);
engine.Convert(inputPathVid, outputPathVid, conversionOptions);
}
File.Delete(tempFilePath);
Video_Struct vd = new Video_Struct();
vd.CategoryID = 0; // store categoryname or term instead of category id
vd.Categories = "";
vd.UserName = model.username;
vd.Title = "";
vd.Description = "";
vd.Tags = "";
vd.Duration = inputPathVid.Metadata.Duration.ToString();
vd.Duration_Sec = Convert.ToInt32(inputPathVid.Metadata.Duration.Seconds.ToString());
vd.OriginalVideoFileName = model.fileName;
vd.VideoFileName = model.fileName;
vd.ThumbFileName = thumbname+"_resized.jpg";
vd.isPrivate = 0;
vd.AuthKey = "";
vd.isEnabled = 1;
vd.Response_VideoID = 0; // video responses
vd.isResponse = 0;
vd.isPublished = 1;
vd.isReviewed = 1;
vd.Thumb_Url = "none";
//vd.FLV_Url = flv_url;
vd.Embed_Script = "";
vd.isExternal = 0; // website own video, 1: embed video
vd.Type = 0;
vd.YoutubeID = "";
vd.isTagsreViewed = 1;
vd.Mode = 0; // filter videos based on website sections
//vd.ContentLength = f_contentlength;
vd.GalleryID = 0;
long videoid = VideoBLL.Process_Info(vd, false);
}`enter code here`

Best method to send image and a text from android to wcf service

I need to send an image and text from android to wcf service, tried with http client with multipart but no luck, kindly suggest.
send image using multipartBuilder and send text separately as json via http url connection, the below code for sending image to wcf service is this
Android code
public String postFiless( byte[] imgbyt, String urlString) throws Exception {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
byte[] data = imgbyt;
String fileName = String.format("File_%d.jpg",new Date().getTime());
ByteArrayBody bab = new ByteArrayBody(data, fileName);
builder.addPart("image", bab);
final HttpEntity entity = builder.build();
post.setEntity(entity );
HttpResponse response = client.execute(post);
Log.e("result code", ""+response.getStatusLine().getStatusCode());
return getContent(response);
}
public static String getContent(HttpResponse response) throws IOException {
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String body = "";
String content = "";
while ((body = rd.readLine()) != null)
{
content += body + "\n";
}
return content.trim();
}
WCF CODE TO GET THE IMAGE STREAM SENT FROM ANDROID
Three steps to upload image using Multipart Parser from android to WCF Rest Service
//Step 1
//WCF Rest Interface
// Namespace
using System.IO;
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, UriTemplate = "/UploadImg")]
string UploadImg(Stream fileStream);
Step 2
// WCF Implementation class
// Name spaces
using System.IO;
public string UploadImg(Stream fileStream) {
string strRet = string.Empty;
string strFileName = AppDomain.CurrentDomain.BaseDirectory + "Log\\"; // System.Web.Hosting.HostingEnvironment.MapPath("~/Logs/");
string Path = HttpContext.Current.Server.MapPath("~/Photos");// System.Web.Hosting.HostingEnvironment.MapPath("~/Photos/");// HttpContext.Current.Server.MapPath("~/Photos/")
try {
MultipartParser parser = new MultipartParser(fileStream);
if (parser.Success) {
string fileName = parser.Filename;
string contentType = parser.ContentType;
byte[] fileContent = parser.FileContents;
Encoding encoding = Encoding.UTF8;
FileStream fileToupload = new FileStream(Path + "/" + fileName, FileMode.Create);
fileToupload.Write(fileContent, 0, fileContent.Length);
fileToupload.Close();
fileToupload.Dispose();
fileStream.Close();
strRet= fileName;
} else {
return "Image Not Uploaded";
} }
catch (Exception ex) {
// handle the error
}
return strRet;
}
Step 3
// MultipartParser class
//Namespace
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
public class MultipartParser {
public IDictionary<string, string> Parameters = new Dictionary<string, string>();
public MultipartParser(Stream stream) {
this.Parse(stream, Encoding.UTF8);
}
public MultipartParser(Stream stream, Encoding encoding) {
this.Parse(stream, encoding);
}
public string getcontent(Stream stream, Encoding encoding) {
// Read the stream into a byte array
byte[] data = ToByteArray(stream);
// Copy to a string for header parsing
string content = encoding.GetString(data);
string delimiter = content.Substring(0, content.IndexOf("\r\n"));
string[] sections = content.Split(new string[] { delimiter }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in sections) {
Match nameMatch = new Regex(#"(?<=name\=\"")(.*?)(?=\"")").Match(s);
string name = nameMatch.Value.Trim().ToLower();
if (!string.IsNullOrWhiteSpace(name)) {
int startIndex = nameMatch.Index + nameMatch.Length + "\r\n\r\n".Length;
}
}
string strRet = ""; //Parameters["name"];
return strRet;
}
private void Parse(Stream stream, Encoding encoding) {
this.Success = false;
// Read the stream into a byte array
byte[] data = ToByteArray(stream);
// Copy to a string for header parsing
string content = encoding.GetString(data);
// The first line should contain the delimiter
int delimiterEndIndex = content.IndexOf("\r\n");
if (delimiterEndIndex > -1) {
string delimiter = content.Substring(0, content.IndexOf("\r\n"));
// Look for Content-Type
Regex re = new Regex(#"(?<=Content\-Type:)(.*?)(?=\r\n\r\n)");
Match contentTypeMatch = re.Match(content);
// Look for filename
re = new Regex(#"(?<=filename\=\"")(.*?)(?=\"")");
Match filenameMatch = re.Match(content);
//re = new Regex(#"(?<=name\=\"")(.*?)(?=\"")");
//Match nameMatch = re.Match(content);
// Did we find the required values?
if (contentTypeMatch.Success && filenameMatch.Success) {
// Set properties
this.ContentType = contentTypeMatch.Value.Trim();
this.Filename = filenameMatch.Value.Trim();
// Get the start & end indexes of the file contents
int startIndex = contentTypeMatch.Index + contentTypeMatch.Length + "\r\n\r\n".Length;
byte[] delimiterBytes = encoding.GetBytes("\r\n" + delimiter);
int endIndex = IndexOf(data, delimiterBytes, startIndex);
int contentLength = endIndex - startIndex;
// Extract the file contents from the byte array
byte[] fileData = new byte[contentLength];
Buffer.BlockCopy(data, startIndex, fileData, 0, contentLength);
this.FileContents = fileData;
this.Success = true; }
} }
private int IndexOf(byte[] searchWithin, byte[] serachFor, int startIndex) {
int index = 0;
int startPos = Array.IndexOf(searchWithin, serachFor[0], startIndex);
if (startPos != -1) {
while ((startPos + index) < searchWithin.Length) {
if (searchWithin[startPos + index] == serachFor[index]) {
index++;
if (index == serachFor.Length) {
return startPos;
}
} else {
startPos = Array.IndexOf<byte>(searchWithin, serachFor[0], startPos + index);
if (startPos == -1) {
return -1;
}
index = 0;
}
}
}
return -1;
}
private byte[] ToByteArray(Stream stream) {
byte[] buffer = new byte[32768];
using (MemoryStream ms = new MemoryStream()) {
while (true) {
int read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
}
public bool Success {
get;
private set;
}
public string ContentType {
get;
private set;
}
public string Filename {
get;
private set;
}
public byte[] FileContents {
get;
private set;
}
public string Imgname {
get;
private set;
} }
// End of Wcf rest Service Code

Android to WCF: Streaming multi part image and Json string

Android to WCF: Streaming multi part image and Json string
I want to create a WCF-RESTful web service method,in which i need to upload an image(multipart-form data) along with some other information (in JSON format). This web service will be accessed by android and iPhone application to send Image and json information as
I want WCF Server Side and Android Code, Help me
I'm trying to upload an image and a text to a wcf service. I create a service to save upload images:
Rest Client Code
protected void Button2_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
MemoryStream mStream = new MemoryStream();
Bitmap bmpPostedImage = new Bitmap(FileUpload1.PostedFile.InputStream);
bmpPostedImage.Save(mStream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] imageArray = mStream.ToArray();
mStream.Close();
VehicleCheckListTransaction objAttachmentRequestDto = new VehicleCheckListTransaction();
objAttachmentRequestDto.VehicleCheckListTransactionID = 0;
objAttachmentRequestDto.VehicleCheckListID = 2;
objAttachmentRequestDto.TTID = 10;
objAttachmentRequestDto.UserID = 226;
objAttachmentRequestDto.UserTypeID = 4;
objAttachmentRequestDto.ValidTill = "215-05-10";
objAttachmentRequestDto.CurrentDate = "215-07-22";
objAttachmentRequestDto.CurrentStatus = "Yes";
objAttachmentRequestDto.CreatedBy= 226;
objAttachmentRequestDto.ModifiedBy = 226;
objAttachmentRequestDto.CreatedDate = string.Empty;
objAttachmentRequestDto.ModifiedDate = string.Empty;
objAttachmentRequestDto.Notes = "Some Text";
objAttachmentRequestDto.IsActive = true;
objAttachmentRequestDto.FileName = "";
objAttachmentRequestDto.FilePath = "";
objAttachmentRequestDto.VerifiedBy = 226;
var serializer = new DataContractJsonSerializer(typeof(VehicleCheckListTransaction));
var ms = new MemoryStream();
serializer.WriteObject(ms, objAttachmentRequestDto);
ms.Position = 0;
var reader = new StreamReader(ms);
string requestBody = reader.ReadToEnd();
var client = new RestClient();
client.BaseUrl = new Uri("http://localhost:49188/WDS_SERVICE.svc/");
var request = new RestRequest(Method.POST) { DateFormat = DataFormat.Json.ToString(), Resource = "vehiclechecklisttransaction/Add" };
if (requestBody != null)
request.AddParameter("VehicleCheckListTransaction", requestBody);
request.AddFile("file1", imageArray, "NEVER.jpg");
var response = client.Execute(request);
}
}
WCF Service Code
public string UploadPhoto(Stream request)
{
//Read in our Stream into a string...
StreamReader reader = new StreamReader(request);
string JSONdata = reader.ReadToEnd();
// ..then convert the string into a single "wsCustomer" record.
JavaScriptSerializer jss = new JavaScriptSerializer();
Checklist Checklist = jss.Deserialize<Checklist>(JSONdata);
try
{
FileStream targetStream = null;
Stream sourceStream = Checklist.fileContents;
String guid = Guid.NewGuid().ToString();
//get photofolder path
string photofolderName = "Trip\\Android";
string filename = guid + ".JPEG";
string uriPath = "file:\\C:\\inetpub\\wwwroot\\WDS\\Media\\" + photofolderName + "\\" + filename;
string photopath = new Uri(uriPath).LocalPath;
using (targetStream = new FileStream(photopath, FileMode.Create, FileAccess.Write, FileShare.None))
{
//read from the input stream in 6K chunks
//and save to output stream
const int bufferLen = 65000;
byte[] buffer = new byte[bufferLen];
int count = 0;
while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
{
targetStream.Write(buffer, 0, count);
}
targetStream.Close();
sourceStream.Close();
}
db.Checklists.Add(Checklist);
db.SaveChanges();
return filename + "_" + Checklist.ChecklistID;
}
catch (Exception ex)
{
throw new FaultException(ex.Message);
}
}

JSON object is returning -1

I want to store these values to server.
The data which i have to store is complete in the variables.
I should get
{"response":{"result":1,"Message":"Poll Entered Successfully."}}
from server
but getting -1
#Override
protected String doInBackground(String... params) {
String jsonString = null;
HttpURLConnection linkConnection = null;
try {
String squestion = question.getText().toString();
String shashtag = hashTag.getText().toString();
spolltime = polltime.getText().toString();
StringBuilder scat = new StringBuilder();
scat.append("");
scat.append(categoryid);
StringBuilder sid = new StringBuilder();
sid.append("");
sid.append(LoginPage.logid);
//int ipolltime = Integer.parseInt(spolltime);
String equestion = URLEncoder.encode(squestion,"UTF-8");
String ehashtag = URLEncoder.encode(shashtag,"UTF-8");
String ecategory = URLEncoder.encode(scat.toString(),"UTF-8");
String eA = URLEncoder.encode(OptionA.stext,"UTF-8");
String eB = URLEncoder.encode(OptionB.stext,"UTF-8");
String eC = URLEncoder.encode(OptionC.stext,"UTF-8");
String eD = URLEncoder.encode(OptionD.stext,"UTF-8");
String eid = URLEncoder.encode(sid.toString(),"UTF-8");
String epolltime = URLEncoder.encode(spolltime,"UTF-8");
URL linkurl = new URL("http://iipacademy.in/askpoll/pollfeeds.php?user_id="+eid+"&question="+equestion+
"&hashtag="+ehashtag+"&category_id="+ecategory+"&option1="+eA+"&option2="+eB+"&option3="+eC+"&option4="+eD+"" +
"&pollopen="+epolltime+"&optiontype1=texty&optiontype2=texty&optiontype3=texty&optiontype4=texty");
linkConnection = (HttpURLConnection) linkurl.openConnection();
int responseCode = linkConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream linkinStream = linkConnection.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int j = 0;
while ((j = linkinStream.read()) != -1) {
baos.write(j);
}
byte[] data = baos.toByteArray();
jsonString = new String(data);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (linkConnection != null) {
linkConnection.disconnect();
}
}
//Toast.makeText(getApplicationContext(),jsonString.toString(),
//Toast.LENGTH_LONG).show();
return jsonString;
}
I am not able to find my mistake !
thanks
first of all try to make this call from browser and check for response . there is an extension
on chrome PostMan rest client. please check first. may be you are not getting the response correctly.

Categories

Resources