Commit 9f01e3a2 by Joona Romppanen

RestClient cleanup ja exception handler parannus

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