I'm trying to check is a given URL is Valid and downloadable.
I wrote this code and it does work but i'm wondering if it can be achieved without the ugly try-catch
public static bool IsUrlValid(string url)
{
try
{
WebClient webClient = new WebClient();
var stream = webClient.OpenRead(url);
return true;
}
catch (Exception ex)
{
return false;
}
}
Getting an error exception thrown on this small piece of code but I can't figure out why / where. Fairly new to this so any help would be apprecaited
private void GetServiceData(string url)
{
try
{
if (!string.IsNullOrEmpty(this.Service) && !string.IsNullOrEmpty(url))
{
string data = string.Empty;
string name = string.Format("{0}Data", this.Service);
using (WebClient client = new WebClient())
{
data = client.DownloadString(url);
}
Page.ClientScript.RegisterHiddenField(name, data);
}
}
catch (Exception ex)
{
Shared.Utilities.ExceptionLog.WriteExceptionToLog(ex, "CourseFinderServiceControl.GetServiceData()");
}
}
If this is for Twitch, you need to specify client when requesting the data.
I'm developing a windows phone app that generates a QRcode, when the code is scanned, then response has to come back as true, please look at my code and advice as i'm getting a false response even thought the other app has scanned the code.
private async void queryQRCode(string code)
{
try
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var authorisationHeader = GenerateBasicAuthorizationParameter("merchant-" + ObjUserData.MerchantId, ObjUserData.PassApiPassword); // 12ED5A5F2B38ACCBE437731BB2AC1F30 35A09A5C2AE97F055A0FDAEDA5A7093D
//Console.WriteLine ("http content - " + httpContent.ReadAsStringAsync().Result);
HttpResponseMessage httpResponse = new HttpResponseMessage();
// Do the actual request and await the response
client.DefaultRequestHeaders.Authorization = authorisationHeader;
var f = QueryCodeUrl + "/" + code + "/scanned";
httpResponse = await client.GetAsync(new Uri(f));
//httpResponse.EnsureSuccessStatusCode();
// If the response contains content we want to read it!
if (httpResponse.Content != null)
{
var responseContent = await httpResponse.Content.ReadAsStringAsync();
// From here on you could deserialize the ResponseContent back again to a concrete C# type using Json.Net
Debug.WriteLine(responseContent);
try
{
ScannedCodeResult res = JsonConvert.DeserializeObject<ScannedCodeResult>(responseContent);
Debug.WriteLine("RETURNED RESPONSE IS "+res.scanned.ToString());
if (res.scanned == false)
{
queryQRCode(code);
}
else
{
Debug.WriteLine("YAY!!!! The User has successfully scanned the application");
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message + ex.StackTrace);
}
// var qrResponse = (VcsMasterPassService.MasterPassModels.QRCodeResponse)JsonConvert.DeserializeObject (responseContent, typeof(VcsMasterPassService.MasterPassModels.QRCodeResponse));
// CreateQRCodeImage (qrResponse.code);
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message + ex.StackTrace);
}
finally
{
}
}
Above problem is caused by windows phone caching.
I am trying to delete a Jenkins job using a C# script.
When I run the code, it actually works. The job is deleted. However, Jenkins still returns a 403 error. Am I doing something wrong?
This is my code:
String credentials = ConfigurationManager.AppSettings["jenkinsUser"] + ":" + ConfigurationManager.AppSettings["jenkinsKey"];
String authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
try
{
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.Authorization] = "Basic " + authorization;
string HtmlResult = wc.UploadString(ConfigurationManager.AppSettings["jenkinsDeleteJobUrl"], "POST", "");
Console.WriteLine("Success");
}
}
catch(WebException e)
{
Console.WriteLine("Something went wrong");
throw e;
}
the url I use is [My Jenkins url]/job/{0}/doDelete
I also tried using HttpWebRequest with the same result. Hope someone knows the answer.
[Edit] note that when I use Postman to do the same request, it goes through all right, redirecting to the Jenkins main page with a return code 200.
This is the Postman call:
POST /job/[jobname]/doDelete HTTP/1.1
Host: [my jenkins url]
Authorization: Basic [my auth hash]
Cache-Control: no-cache
I think the problem is that, when you delete a Jenkins job using the doDelete url, you get redirected to your Jenkins homepage. Since you do this programatically, Jenkins does not recognize a user session (even though your original request contained an Authorization header), resulting in a forbidden code.
As a work-around, I did the following:
try {
string credentials = ConfigurationManager.AppSettings["jenkinsUser"] + ":" + ConfigurationManager.AppSettings["jenkinsKey"];
string authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.Authorization] = "Basic " + authorization;
string HtmlResult = wc.UploadString(String.Format(ConfigurationManager.AppSettings["jenkinsDeleteJobUrl"], jobName), "POST", "");
}
}
catch (WebException e)
{
// ignore the 403 error for now
HttpWebResponse errorResponse = e.Response as HttpWebResponse;
if(errorResponse.StatusCode != HttpStatusCode.Forbidden)
{
throw e;
}
}
// if the job no longer exists, it is proof that the request went through
if(!JenkinsHelper.GetJenkinsJobs().Contains(jobName))
{
Console.WriteLine("Job successfully deleted.");
return true;
}
else
{
Console.WriteLine("Could not delete job.");
return false;
}
with this helper function, in which JenkinsJobListUrl = [MyJenkinsUrl]/api/xml?xpath=hudson/job/name&wrapper=jobs
public static List<string> GetJenkinsJobs()
{
try
{
string credentials = ConfigurationManager.AppSettings["jenkinsUser"] + ":" + ConfigurationManager.AppSettings["jenkinsKey"];
string authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.Authorization] = "Basic " + authorization;
string HtmlResult = wc.DownloadString(String.Format(ConfigurationManager.AppSettings["jenkinsJobListUrl"]));
XDocument doc = XDocument.Parse(HtmlResult);
return doc.Root.Elements("name").Select(element => element.Value).ToList();
}
}
catch (WebException e)
{
Console.WriteLine("Could not retreive Jenkins job list");
throw e;
}
}
I know it isn't pretty, but for lack of a better solution this gets the job done.
Hope this helps people who have been struggling with this too. If you find a better solution, please let me know.
I'm making a project on Windows Phone where user can take a photo, save it on phone and next upload on my server. So there are two projects, WP8.1 and ASP.NET WEB API.
Currently I don't know how to upload photo to my server(from phone), I even don't know how to catch it in API. What's the best way to make it?
Here is my method to show on the screen(phone), picture which was taken by user.
private async void LoadCapturedphoto(string filename)
{
//load saved image
StorageFolder pictureLibrary = KnownFolders.SavedPictures;
StorageFile savedPicture = await pictureLibrary.GetFileAsync(filename);
ImageProperties imgProp = await savedPicture.Properties.GetImagePropertiesAsync();
var savedPictureStream = await savedPicture.OpenAsync(FileAccessMode.Read);
//set image properties and show the taken photo
bitmap = new WriteableBitmap((int)imgProp.Width, (int)imgProp.Height);
await bitmap.SetSourceAsync(savedPictureStream);
takenImage.Source = bitmap;
takenImage.Visibility = Visibility.Visible;
}
I think that I should convert WriteableBitmap to Byte[], send these Byte[] by API to server and on server convert Byte[] to JPG/PNG/etc.
private byte[] ConvertBitmapToByteArray(WriteableBitmap bitmap)
{
WriteableBitmap bmp = bitmap;
using (Stream stream = bmp.PixelBuffer.AsStream())
{
MemoryStream memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
Any ideas? Do you think it's good idea to make it like that? WriteableBitmap -> Byte[] and next on server Byte[] -> JPG/PNG etc. Is it even possible?
If it can be done much more easier please write some samples.
it's my method for calling api methods
public string apiCommand(string api, string json)
{
using (var httpClient = new HttpClient())
{
HttpContent content = new StringContent(json, Encoding.UTF8);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage response = httpClient.PostAsync(Variables.apiURL + api, content).Result;
response.EnsureSuccessStatusCode();
Task<string> responseBody = response.Content.ReadAsStringAsync();
//var msg = new MessageDialog(responseBody.Result.ToString());
if (response.StatusCode.ToString() != "OK")
{
return "ERROR: " + response.StatusCode.ToString();
}
else
{
return "SUCCES: " + responseBody.Result.ToString();
}
}
}
You need to use multipart/form-data request to the server. You can send the json to the web api using payload field (another alternative is send every field separately, but you need reflection to do that.)
This maybe can help you:
public string UploadUserPictureApiCommand(string api, string json, byte[] picture)
{
using (var httpClient = new HttpClient())
{
MultipartFormDataContent form = new MultipartFormDataContent();
form.Add(new StringContent(json), "payload");
form.Add(new ByteArrayContent(picture, 0, picture.Count()), "user_picture", "user_picture.jpg");
HttpResponseMessage response = await httpClient.PostAsync(api, form);
response.EnsureSuccessStatusCode();
Task<string> responseBody = response.Content.ReadAsStringAsync();
if (response.StatusCode.ToString() != "OK")
{
return "ERROR: " + response.StatusCode.ToString();
}
else
{
return "SUCCES: " + responseBody.Result.ToString();
}
}
}
I handle image and word files in my project by this way, hope it helps.
1) Server side, I have a generic api method to process Json requests.
[HttpPost]
public HttpResponseMessage ProcessRequest([FromBody] string sJsonRequest)
{
ResponseMsg rspMsg = null;
RequestMsg oRequestMsg = null;
string sDeteializeMsg = "";
try
{
string sUnescapeJsonData = System.Uri.UnescapeDataString(sJsonRequest);
sJsonRequest = sUnescapeJsonData;
oRequestMsg = (RequestMsg)JsonHelper.Deserialize(typeof(RequestMsg), sJsonRequest);
}
catch (Exception ex)
{
...
}
if (oRequestMsg == null)
{
return AppHelper.GetUTF8PlainTextHttpResponse(#"Invalid request message.");
}
rspMsg = new ResponseMsg(oRequestMsg);
string sJsonRet = "";
try
{
if(oRequestMsg.RequestType==SavingFile)
{
byte[] bytes = System.Convert.FromBase64String(oRequestMsg.Base64Data);
System.IO.File.WriteAllBytes(sFileName, bytes);
....
}
//update rspMsg ....
}
catch (Exception ex)
{
...
}
finally
{
sJsonRet = JsonHelper.Serialize(rspMsg);
}
return AppHelper.GetUTF8PlainTextHttpResponse(sJsonRet);
}
Client side,
1) call through .net code, I use system.Net.webclient,
system.Net.webclient cli=new system.Net.webclient();
cli.Credentials = Credentials;
cli.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
//http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx
sJsonRequest = "=" + EscapeDataStringBig(sJsonRequest);
response = cli.UploadString(sRemoteUrl, "POST", sJsonRequest);
ResponseMsg rsp = (ResponseMsg)JsonHelper.Deserialize(typeof(ResponseMsg), response);
return rsp;
2) call it through JavaScript, usually I will create a method in website controller and forward the json request to the method defined as above. if your javascript code and api code share same json objects, it is quite easy.
2.1) web site controller code,
[HttpPost]
public ActionResult AjaxRequest(int nPostType = -1, string sJsonObject = "")
{
try
{
WebModelAjaxRequestTypes nReqType = (WebModelAjaxRequestTypes)nPostType;
bool bIsBase64Data = IsBase64Request(nReqType);
string sJsonRet = "";
if (!bIsBase64Data)
{
....
}
else
{
//base64 content requests
string sBase64Data = sJsonObject;
//put the string into a json request and send it to api call. and get the return => sJsonRet
}
return Content(sJsonRet); }
catch (Exception ex)
{
....
}
}
2.2) JavaScript ajax call sample code:
var type = "POST";
var sContentType = "";
var sData = ""
if (bIsBase64) {
//sJsonParas is base64 string. don't use encodeURI to encode it.!!!
sContentType = 'application/json; charset=utf-8';
sData = '{ "nPostType" :' + nPostType.toString() + ',"sJsonObject" : "' + sJsonParas + '" }';
}
else {
sContentType = "application/x-www-form-urlencoded; charset=UTF-8";
sData = "nPostType=" + nPostType.toString() + "&sJsonObject=" + encodeURIComponent(sJsonParas);
}
jQuery.ajax({
url: sUrl,
type: type,
data: sData,
contentType: sContentType,
success: function (result) {
....
},
error: function (jqXHR, textStatus, errorThrown) {
....
},
complete: function (jqXHR, textStatus) {
....
} //end complete
});