Commit 9f01e3a2 by Joona Romppanen

RestClient cleanup ja exception handler parannus

1 parent 2947ab57
......@@ -15,3 +15,5 @@ MoyaSignup/installers/
MoyaAdmin/MoyaAdminUI/ImageResizer/ImageResizer/ImageResizer/obj/
MoyaAdmin/MoyaAdminUI/ImageResizer/ImageResizer/ImageResizer/bin.old/
MoyaAdmin/MoyaAdminUI/ImageResizer/ImageResizer/Backup/
MoyaSignup/\.vs/
......@@ -65,6 +65,7 @@
<Compile Include="Maps.cs" />
<Compile Include="MetaData.cs" />
<Compile Include="MetaDataList.cs" />
<Compile Include="MoyaApiException.cs" />
<Compile Include="OrgMeal.cs" />
<Compile Include="OrgMealList.cs" />
<Compile Include="Place.cs" />
......
using System;
using System.Net;
namespace MoyaAdminLib
{
public class MoyaApiException : WebException
{
public MoyaApiException()
{
}
public MoyaApiException(string message) : base(message)
{
}
public MoyaApiException(string message, Exception innerException) : base(message, innerException)
{
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace MoyaAdminLib
{
public enum HttpVerb
{
GET,
......@@ -19,6 +13,7 @@ namespace MoyaAdminLib
PUT,
DELETE
}
public class RestClient
{
public string EndPoint { get; set; }
......@@ -26,19 +21,20 @@ namespace MoyaAdminLib
public string ContentType { get; set; }
public string PostData { get; set; }
public static string ApiApplicationKey;
public static string ApiUser;
public static string ApiPass;
public static string ApiURL;
public static string ApiApplicationKey { get; set; }
public static string ApiUser { get; set; }
public static string ApiPass { get; set; }
public static string ApiURL { get; set; }
public RestClient()
{
EndPoint = ApiURL;
Method = HttpVerb.GET;
ContentType = "application/json";
PostData = "";
}
public RestClient(string endpoint)
{
EndPoint = endpoint;
......@@ -46,6 +42,7 @@ namespace MoyaAdminLib
ContentType = "application/json";
PostData = "";
}
public RestClient(string endpoint, HttpVerb method)
{
EndPoint = endpoint;
......@@ -62,47 +59,42 @@ namespace MoyaAdminLib
PostData = postData;
}
public static string CalculateSHA1(string text)
private static string CalculateSHA1(string text)
{
// Convert the input string to a byte array
byte[] buffer = Encoding.GetEncoding("iso-8859-1").GetBytes(text);
var buffer = Encoding.GetEncoding("iso-8859-1").GetBytes(text);
// In doing your test, you won't want to re-initialize like this every time you test a
// string.
SHA1CryptoServiceProvider cryptoTransformSHA1 =
new SHA1CryptoServiceProvider();
var cryptoTransformSha1 = new SHA1CryptoServiceProvider();
// The replace won't be necessary for your tests so long as you are consistent in what
// you compare.
string hash = BitConverter.ToString(cryptoTransformSHA1.ComputeHash(buffer)).Replace("-", "").ToLower();
var hash = BitConverter.ToString(cryptoTransformSha1.ComputeHash(buffer)).Replace("-", "").ToLower();
return hash;
}
private static int ConvertToTimestamp(DateTime value)
{
//create Timespan by subtracting the value provided from
//the Unix Epoch
TimeSpan span = (value - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());
var span = (value - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());
//return the total seconds (which is a UNIX timestamp)
return (int)span.TotalSeconds;
}
public static string GetRequestURL(string server, string queryPath)
{
return GetRequestURL(server, queryPath,null);
}
public static string GetRequestURL(string server, string queryPath, string getparms)
{
int timestamp = ConvertToTimestamp(DateTime.Now);
string hash = CalculateSHA1("/" + queryPath + "+" + ApiApplicationKey + "+" + ApiUser + "+" + timestamp + "+" + ApiPass);
if (getparms != null && getparms.Length > 0)
var timestamp = ConvertToTimestamp(DateTime.Now);
var hash = CalculateSHA1("/" + queryPath + "+" + ApiApplicationKey + "+" + ApiUser + "+" + timestamp + "+" + ApiPass);
if (!string.IsNullOrEmpty(getparms))
getparms = getparms + "&";
string url = server + "/rest/" + queryPath + "?";
var url = server + "/rest/" + queryPath + "?";
if (getparms != null)
url += getparms;
......@@ -111,7 +103,12 @@ namespace MoyaAdminLib
Console.WriteLine(url);
return url;
}
public static string GetRequestURL(string server, string queryPath)
{
return GetRequestURL(server, queryPath, null);
}
public string MakeRequest(string queryPath)
{
return MakeRequest(queryPath, null);
......@@ -119,20 +116,14 @@ namespace MoyaAdminLib
public string MakeRequest(string queryPath, string getparms)
{
///placeadmin/places/30+abcdefg+testuser-asdf+1393735570144+acdcabbacd
///
var request = (HttpWebRequest)WebRequest.Create(GetRequestURL(EndPoint,queryPath,getparms));
var request = (HttpWebRequest)WebRequest.Create(GetRequestURL(EndPoint, queryPath, getparms));
request.Method = Method.ToString();
request.ContentLength = 0;
request.ContentType = ContentType;
if (!string.IsNullOrEmpty(PostData) && (Method == HttpVerb.POST || Method == HttpVerb.PUT ))
if (!string.IsNullOrEmpty(PostData) && (Method == HttpVerb.POST || Method == HttpVerb.PUT))
{
var encoding = new UTF8Encoding();
var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData);
request.ContentLength = bytes.Length;
......@@ -142,7 +133,6 @@ namespace MoyaAdminLib
}
}
try
{
using (var response = (HttpWebResponse)request.GetResponse())
......@@ -151,22 +141,20 @@ namespace MoyaAdminLib
if ((int)response.StatusCode < 200 && (int)response.StatusCode >= 300)
{
var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
var message = string.Format("Request failed. Received HTTP {0}", response.StatusCode);
throw new ApplicationException(message);
}
// grab the response
//if (response.ContentLength > 0)
//{
using (var responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (var reader = new StreamReader(responseStream))
{
responseValue = reader.ReadToEnd();
}
}
}
//}
return responseValue;
}
......@@ -174,21 +162,24 @@ namespace MoyaAdminLib
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ConnectFailure)
throw e;
Stream responseStream = ((WebException)e).Response.GetResponseStream();
{
throw;
}
var responseStream = e.Response.GetResponseStream();
if (responseStream != null)
{
string responseValue = StreamToString(responseStream);
var responseValue = StreamToString(responseStream);
Console.WriteLine("Response was " + responseValue);
throw new Exception(responseValue);
throw new MoyaApiException(responseValue, e);
}
throw e;
throw;
}
}
/// <summary>
/// Convert streams from web to string
/// </summary>
......@@ -196,14 +187,11 @@ namespace MoyaAdminLib
/// <returns>string</returns>
private string StreamToString(Stream responseStream)
{
StreamReader reader = new StreamReader(responseStream);
string responseString = reader.ReadToEnd();
var reader = new StreamReader(responseStream);
var responseString = reader.ReadToEnd();
responseStream.Close();
reader.Close();
return responseString;
}
} // class
}
}
......@@ -106,17 +106,26 @@ namespace MoyaSignup
{
btnNewProfile.Visible = false;
CurrentUser = new User(euser);
infoLabel.Text = "Hei! " + CurrentUser.ToString() + " Kirjoita salasanasi ja kirjaudu";
infoLabel.Text = "Hei! " + CurrentUser + " Kirjoita salasanasi ja kirjaudu";
showLogin(true);
}
}
catch (Exception ex)
catch (MoyaApiException)
{
CurrentUser = null;
infoLabel.Text = "Uusi kävijä?";
btnNewProfile.Visible = true;
showLogin(false);
}
catch (WebException)
{
MessageBox.Show(
"Yhteys taustajärjestelmään epäonnistui. Ota yhteys infoon.",
"Järjestelmävirhe",
MessageBoxButtons.OK,
MessageBoxIcon.Error
);
}
timer1.Stop();
}
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!