So i recently decided to again redo the infrastructure of my Jarvis AI. Now i'm using a mix of the code (Google and Microsoft). The Google part of the code will not trigger for some reason and display any words or text when spoken into microphone.
public const int DEFAULT_BIT_RATE = 8000;
public const string DEFAULT_LANGUAGE = "en-US";
static string client = "Jarvis";
public class SpeechInputResult
{
static public string ID;
public int status;
public class Hypothesis
{
public string utterance;
public double confidence = -1.0d;//-1 = No Value
public override string ToString()
{
return "'" +utterance + "'" + ((confidence == -1) ? "" : "#" + confidence);
}
public List<Hypothesis> hypotheses = new List<Hypothesis>();
public Hypothesis getBestHypothesis()
{
if (hypotheses.Count() <=0)
return null;
Hypothesis H = hypotheses[0];
foreach (Hypothesis h in hypotheses)
{
if (h.confidence>=H.confidence)
{
H = h;
}
return H;
}
return null;
}
public string json_men = "";
public void FromJSON(String JSON)
{
json_men = JSON;
JSON = JSON.Replace("\n","").Trim();
Match M;
//status
M = new Regex("\\\"status\\\"\\:([0-9]*),", RegexOptions.IgnoreCase).Match(JSON);
//ID
M = new Regex ("\\\"id\\\"\\:\\\"([^\\\"]*)\\\",", RegexOptions.IgnoreCase).Match(JSON);
ID = M.Groups[1].Value;
//Hypotheses
int l1 = JSON.IndexOf("hypotheses");
l1 = JSON.IndexOf("[",l1);
int r1 = JSON.LastIndexOf("]");
string JSON2 = JSON.Substring(l1, r1-l1+1);
MatchCollection m2 = new Regex("{([^\\}]*)}", RegexOptions.IgnoreCase).Matches(JSON2);
foreach (Match g in m2)
{
string s = g.Value;
SpeechInputResult.Hypothesis h = new SpeechInputResult.Hypothesis();
M = new Regex("\\\"utterance\\\"\\:\\\"([^\\\"]*)\\\"", RegexOptions.IgnoreCase).Match(s);
h.utterance = M.Groups[1].Value;
M = new Regex("\\\"confidence\\\"\\:([0-9\\.]*)", RegexOptions.IgnoreCase).Match(s);
string confidence = M.Groups[1].Value;
confidence = confidence.Replace(".", ",");
if (confidence != "")
{
h.confidence = float.Parse(confidence);
}
hypotheses.Add(h);
}
}
}
public static SpeechInputResult ProcessFlacFile(string FlacFileName, int BIT_RATE = DEFAULT_BIT_RATE, string language = DEFAULT_LANGUAGE, uint maxresults = 1)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://www.google.com/speech-api/v1/recognize?xjerr=1" + "&client=" + client + "&lang=" + language + "&maxresults=" + maxresults + "&pfilter=0");
FileStream fStream = new FileStream(FlacFileName, FileMode.Open, FileAccess.Read);
request.Proxy = null;
request.Timeout = 60000;
request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "audio/x-flac; rate=8000";
//bitrate must = .flac file
request.UserAgent = client;
FileInfo fInfo = new FileInfo(FlacFileName);
long numbytes = fInfo.Length;
byte[] data = null;
using (FileStream fstream = new FileStream(FlacFileName, FileMode.Open, FileAccess.Read))
data = new byte[fstream.Length];
fStream.Read(data, 0, Convert.ToInt32(fStream.Length));
fStream.Close();
using (Stream wrStream = request.GetRequestStream())
{
wrStream.Write(data, 0, data.Length);
}
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
dynamic resp = response.GetResponseStream();
if (resp != null)
{
StreamReader sr = new StreamReader(resp);
MessageBox.Show(sr.ReadToEnd());
//resp.Close();
//resp.Dispose();
}
}
catch (System.Exception ee)
{
MessageBox.Show("hi"+ee);
}
return null;
}
}
}
The code here is all from this website.
After getting it to no errors it still doesn't return or do anything, please help!
Parsing JSON with regular expressions will usually cause you problems. Consider using a library like JSON.NET to parse the string into an object instead.
Related
Hello I Have a request in web form code behind and i like call web api send Object with a property of type IFormCollection, the object properties sending but file not
WebRequest wrqst = WebRequest.Create(URLService + method);
var postData = new StringBuilder();
foreach (string key in form.Keys)
{
postData.AppendFormat("{0}={1}&",
HttpUtility.UrlEncode(key),
HttpUtility.UrlEncode(form[key]));
}
var data = Encoding.ASCII.GetBytes(postData.ToString());
wrqst.Method = "POST";
wrqst.ContentType = "application/x-www-form-urlencoded";
wrqst.ContentLength = data.Length;
using (var stream = wrqst.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
WebResponse oResponse = wrqst.GetResponse();
I Receive file in Request.File
How i can send File?
To send a file in your web API request, you need to use the multipart/form-data content type instead of application/x-www-form-urlencoded.
[HttpPost]
[Route("api/WEB/Pos_PropertyImageSave")]
[Route("api/POS/Pos_PropertyImageSave")]
public HttpResponseMessage Pos_PropertyImageSave()
{
try
{
var request = HttpContext.Current.Request;
bool IsUpload= false;
/******************Image Upload*********************/
if (request.Files["PropertyImage"] != null )
{
obj.AttachemntName = request.Form["AttachemntName"] != null ? request.Form["AttachemntName"].ToString() : "";
obj.AttachemntNo = request.Form["AttachemntNo"] != null ? request.Form["AttachemntNo"].ToString() : "";
HttpPostedFile uploadImage = request.Files["PropertyImage"];
if (uploadImage.ContentLength > 0)
{
//Convert the File data to Byte Array which will be store in database
byte[] bytes;
using (BinaryReader br = new BinaryReader(uploadImage.InputStream))
{
bytes = br.ReadBytes(uploadImage.ContentLength);
}
filesInfo file = new filesInfo
{
File_Name = Path.GetFileName(uploadImage.FileName),
File_Type = uploadImage.ContentType,
File_Data = bytes
};
string FilePath = HttpContext.Current.Server.MapPath("~/Upload/") + Path.GetFileName(uploadImage.FileName);
File.WriteAllBytes(FilePath, bytes);
obj.AttachemntType = Path.GetExtension(uploadImage.FileName);
obj.AttachemntImagePath = "../Upload/" + Path.GetFileName(uploadImage.FileName); ;
obj.AttachemntImage = file.File_Data;
// obj.AttachemntName = Convert.ToBase64String(file.File_Data, 0, file.File_Data.Length);
}
IsUpload= true;
/*******************End Of Image Upload*************/
}
if (IsUpload)
{
String sMessage = string.Format("Image has been " + obj.Mode + " successufully.");
Response responseclass = new Response(sMessage, sMessage, ((int)HttpStatusCode.OK), true);
HttpResponseMessage response = Request.CreateResponse<Response>(HttpStatusCode.OK, responseclass);
return response;
}
else
{
Response responseclass = new Response("", "Image Upload Failed", ((int)HttpStatusCode.NoContent), true);
HttpResponseMessage response = Request.CreateResponse<Response>(HttpStatusCode.OK, responseclass);
return response;
}
}
catch (Exception ex)
{
FailureResponse responseclass1 = new FailureResponse(ex.Message.ToString(), ((int)HttpStatusCode.BadRequest), false);
HttpResponseMessage response1 = Request.CreateResponse<FailureResponse>(HttpStatusCode.OK, responseclass1);
throw new HttpResponseException(response1);
}
}
public class filesInfo
{
public string File_Name { get; set; }
public string File_Type { get; set; }
public byte[] File_Data { get; set; }
}
I'm building an ASP.NET application.
This have this page Pagina.aspx, this is the code:
namespace AnalisiHRVElaborazioni
{
public partial class Pagina : System.Web.UI.Page
{
OmniaCareRehabDemProductionEntities dbTool = new OmniaCareRehabDemProductionEntities();
static HttpClient client = new HttpClient();
protected void Page_Load(object sender, EventArgs e)
{
int? locateInput = null;
int? replaceMethod = null;
int? replaceInput = null;
int? detrendMethod = null;
int? waveletLevels = null;
int? smoothMethod = null;
int? smoothSpan = null;
double? smoothDegree = null;
int? polyOrder = null;
int? meanCorrection = null;
int? resampleRate = null;
int? lambda = null;
int? sdnni = null;
int? pnnx = null;
int? tFWindow = null;
int? tFOverlap = null;
int? m = null;
double? r = null;
int? n1 = null;
int? n2 = null;
int? breakpoint = null;
double vlfMin;
double vlfMax;
double lfMin;
double lfMax;
double hfMin;
double hfMax;
int? arOptionOrder = null;
int? winWith = null;
int? winOverlap = null;
int? pointPSD = null;
int? interpolationRate = null;
String idSlot = Request.QueryString["idSlot"];
if (!String.IsNullOrEmpty(idSlot))
{
Response.Redirect("Home/TimeDomain");
}
else
{
String charMethod = Request.QueryString["charMethod"];
String _locateInput = Request.QueryString["locateInput"];
String _replaceMethod = Request.QueryString["replaceMethod"];
String _replaceInput = Request.QueryString["replaceInput"];
String _detrendMethod = Request.QueryString["detrendMethod"];
String _waveletLevels = Request.QueryString["waveletLevels"];
if (!String.IsNullOrEmpty(_locateInput))
locateInput = int.Parse(_locateInput);
if (!String.IsNullOrEmpty(_replaceMethod))
replaceMethod = int.Parse(_replaceMethod);
if (!String.IsNullOrEmpty(_replaceInput))
replaceInput = int.Parse(_replaceInput);
if (!String.IsNullOrEmpty(_detrendMethod))
detrendMethod = int.Parse(_detrendMethod);
if (!String.IsNullOrEmpty(_waveletLevels))
waveletLevels = int.Parse(_waveletLevels);
RR rr = new RR();
RR.Filter filter = new RR.Filter();
filter.locateInput = locateInput;
filter.replaceMethod = replaceMethod;
filter.replaceInput = replaceInput;
filter.detrendMethod = detrendMethod;
filter.waveletLevels = waveletLevels;
//recupero l'RR
rr.rr = getRR(10);
rr.filter = filter;
var json = new JavaScriptSerializer().Serialize(rr);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:28302/api/parse");
request.Method = "POST";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(json);
request.ContentLength = byteArray.Length;
request.ContentType = #"application/json";
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
length = response.ContentLength;
Stream stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
var jsonObject = new JavaScriptSerializer().DeserializeObject(sr.ReadToEnd());
//ottenuto l oggetto posso mettere tutto in sessione
Session["jsonElaborato"] = jsonObject;
Session["loadJson"] = true;
Response.Redirect("Home/TimeDomain/?idSlot=null");
}
}
catch (WebException ex)
{
// Log exception and throw as for GET example above
}
}
}
[NonAction]
public decimal?[] getRR(int idSlot)
{
/**
* qui devo recuperare il codice per recuperare le informazioni real time dal database
* */
return (from r in dbTool.AA_V_RRSlotXRR
where r.IdSlotRR == idSlot
select r.y).ToArray();
}
}
}
I call this page with this url:
http://localhost:12636/Pagina.aspx/?charMethod="percent"&locateInput=900.....
If I try to call this page. I can execute all code and call a web service.
Then after execute these line of code
Session["jsonElaborato"] = jsonObject;
Session["loadJson"] = true;
Response.Redirect("Home/TimeDomain/?idSlot=null");
I expect that the system redirect the browser at Home/TimeDomain page. But unfortunately the page is redirect always in Pagina.aspx page. Why ?
Please try this:
try
{
// your coding here
}
catch(){}
Response.Redirect("Home/TimeDomain/?idSlot=null");
Not all clean, but probably you need something like
Response.Redirect("~/TimeDomain/?idSlot=null", false)
I have my two functions, the access attempt and the HMAC signing. It runs and returns an error(401) unauthorized, however in addition I feel my code is longer than it needs to be or redundant somehow, pointing that out would be very helpful to me, thanks in advance!
void AccessAttempt(){
var message = Epoch.ToString () + "GET" + "/v2/payment-methods";
const string WEBSERVICE_URL = "https://api.coinbase.com/v2/payment-methods";
try
{
var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
if (webRequest != null)
{
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
webRequest.Headers.Add("CB-ACCESS-SIGN", genHMAC(message));
webRequest.Headers.Add("CB-ACCESS-TIMESTAMP", Epoch.ToString());
webRequest.Headers.Add("CB-ACCESS-KEY", _apiKey);
webRequest.Headers.Add("CB-VERSION",_apiVersion);
using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
{
var jsonResponse = sr.ReadToEnd();
OutputText.text = jsonResponse.ToString();
}
}
}
}
catch (Exception ex)
{
OutputText.text = ex.ToString();
}
}
Below is the HMAC signing function called within main function above:
private string genHMAC(string message)
{
byte [] APISecret_Bytes = System.Text.Encoding.UTF8.GetBytes(_apiSecret);
HMACSHA256 hmac = new HMACSHA256(APISecret_Bytes);
hmac.Initialize ();
byte [] MESSAGE_Bytes = System.Text.Encoding.UTF8.GetBytes(message);
var rawHmac = hmac.ComputeHash(MESSAGE_Bytes);
string rawHmacString = string.Empty;
for (int i=0; i<rawHmac.Length; i++)
{
rawHmacString += rawHmac[i];
}
string hexString = string.Empty;
for (int i=0; i<rawHmac.Length; i++)
{
hexString += rawHmac[i].ToString("X2");
}
return hexString;
}
This is a pretty old question, but in case you don't have an answer yet, it looks like there are a few things wrong with your request - here is some code that works for me
public class CoinbaseV2
{
private string APIKey;
private string Secret;
private const string URL_BASE = "https://api.coinbase.com";
private const string URL_BASE_VERSION = URL_BASE + "/v2/";
private const String GET = "GET";
private const String POST = "POST";
private const String PUT = "PUT";
private const String DELETE = "DELETE";
public CoinbaseV2(string inAPIKey, string inSecret)
{
APIKey = inAPIKey;
Secret = inSecret;
}
public string GetUser()
{
return JsonRequest(URL_BASE_VERSION + "user", GET);
}
public string GetUserAccounts()
{
return JsonRequest(URL_BASE_VERSION + "accounts", GET);
}
private string JsonRequest(string url, string method)
{
// take care of any spaces in params
url = Uri.EscapeUriString(url);
string returnData = String.Empty;
var webRequest = HttpWebRequest.Create(url) as HttpWebRequest;
if (webRequest != null)
{
webRequest.Method = method;
webRequest.ContentType = "application/json";
string timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(CultureInfo.CurrentCulture);
string body = "";
string sigurl = url.Replace(URL_BASE,"");
string signature = GenerateSignature(timestamp,method,sigurl,body,Secret);
var whc = new WebHeaderCollection();
whc.Add("CB-ACCESS-SIGN", signature);
whc.Add("CB-ACCESS-TIMESTAMP", timestamp);
whc.Add("CB-ACCESS-KEY", APIKey);
whc.Add("CB-VERSION", "2017-08-07");
webRequest.Headers = whc;
using (WebResponse response = webRequest.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
returnData = reader.ReadToEnd();
}
}
}
return returnData;
}
//https://github.com/bchavez/Coinbase
public static string GenerateSignature(string timestamp, string method, string url, string body, string appSecret)
{
return GetHMACInHex(appSecret, timestamp + method + url + body).ToLower();
}
internal static string GetHMACInHex(string key, string data)
{
var hmacKey = Encoding.UTF8.GetBytes(key);
var dataBytes = Encoding.UTF8.GetBytes(data);
using (var hmac = new HMACSHA256(hmacKey))
{
var sig = hmac.ComputeHash(dataBytes);
return ByteToHexString(sig);
}
}
//https://stackoverflow.com/questions/311165/how-do-you-convert-a-byte-array-to-a-hexadecimal-string-and-vice-versa/14333437#14333437
static string ByteToHexString(byte[] bytes)
{
char[] c = new char[bytes.Length * 2];
int b;
for (int i = 0; i < bytes.Length; i++)
{
b = bytes[i] >> 4;
c[i * 2] = (char)(87 + b + (((b - 10) >> 31) & -39));
b = bytes[i] & 0xF;
c[i * 2 + 1] = (char)(87 + b + (((b - 10) >> 31) & -39));
}
return new string(c);
}
}
I am working on creating web application and i am getting problem redirecting to another page,if I use redirect code in another method then it works fine but i want to use redirect code from my running thread and it is throwing me HttpExeption.Please can you take a look at this code and show right way to use redirect code in my runloop() method.Thanks in advance.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;
using System.Threading.Tasks;
public partial class _Default : System.Web.UI.Page
{
static TcpListener listener;
static TcpClient client;
public StreamReader STR;
public StreamWriter STW;
public String receive = "kkkk";
public String text_to_send;
string Jsn;
string URI ;
string myParameters;
string URL1;
Thread backgroundThread2;
Thread backgroundThread;
int i, n = 0, k = 0, len = 0, len2 = 0;
public int readflag = 0, writeflag = 0, pre1 = 0, pre2 = 0, pre3 = 0, nopre = 0;
char[] ch = new char[100];
char[] ch1 = new char[100];
char[] ch2 = new char[100];
String test = null, s1, s2, s3;
String test1 = null;
string frame;
const int LIMIT = 5; //5 concurrent clients
protected void Page_Load(object sender, EventArgs e)
{
frame = Request.QueryString["frame"];
if (Request.QueryString["Frame"] != null)
Response.Write("From Page1 param1 value=" + Request.QueryString["frame"]);
}
public void Button1_Click(object sender, EventArgs e) //start server
{
listener = new TcpListener(IPAddress.Any, 8002);
listener.Start();
client = listener.AcceptTcpClient();
STR = new StreamReader(client.GetStream());
STW = new StreamWriter(client.GetStream());
STW.AutoFlush = true;
backgroundThread = new Thread(new ThreadStart(RunLoop));
backgroundThread.Start();
// Task.Delay(50000);
//redirect1();
// Response.Redirect(URL1);
}
public void Button2_Click(object sender, EventArgs e) //Redirect server
{
Jsn = "25";
string URI = "Otherpage.aspx?";
string myParameters = "jasonop="+ Jsn;
string URL1 = URI + myParameters;
Response.Redirect(URL1);
// Response.Redirect("Otherpage.aspx?jasonop=25");
// System.Diagnostics.Process.Start("http://localhost:85/shaktijason/1.php?jasonop=25");
}
public class Person
{
public string Name { get; set; }
}
public void RunLoop() //receive
{
NetworkStream stream = client.GetStream();
Byte[] bytes = new Byte[256];
String data = null;
int i,k=1;
string str = "";
JavaScriptSerializer js = new JavaScriptSerializer();
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
byte[] bHex = Encoding.ASCII.GetBytes(data);
// TextBox1.Text = data;
string json = "[{Name:'01030008000105C8'}]";
Person[] persons = js.Deserialize<Person[]>(json);
string name = persons[0].Name.ToString();
// STW.WriteLine("01030008000105C8")
STW.WriteLine(name);
string result = decodedata(data);
str = result;
k++;
if (k == 4) { break; }
}
// string returnJson = "[{Freq:'" + str + "'}]";
Jsn = GetDeviceJSON(str);
URI = "Otherpage.aspx?";
myParameters = "jasonop="+Jsn;
URL1 = URI + myParameters;
Response.Redirect(URL1,false);
// Response.Redirect("Otherpage.aspx");
//string URI = "http://localhost:85/Shaktijason/1.php";
//string myParameters = "jasonop=jsn";
//using (WebClient wc = new WebClient())
//{
// wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
// string HtmlResult = wc.UploadString(URI, myParameters);
// Response.Redirect(HtmlResult);
//}
//string JSON = Json;
//backgroundThread2.Start();
// backgroundThread.Abort();
//return js.Serialize(returnJson);
}
public string decodedata(string data)
{
ch1 = data.ToCharArray();
ch2 = data.ToCharArray();
int len1 = data.Count(char.IsLetter);
len2 = data.Count(char.IsNumber);
int add = len1 + len2;
while (ch1[k] != 'k')
{
ch2[k] = ch1[k];
k++;
}
string strng = new string(ch2, 0, k);
len = strng.Length;
string sub = data.Substring(k + 1);
len2 = sub.Length;
k = 0;
if (len == 1)
{
strng = "0" + strng.PadLeft(len, '0');
}
if (len2 == 1)
{
sub = "0" + sub.PadLeft(len2, '0');
}
char[] go = new char[20];
string final = strng + sub;
if (final.Equals("00b8"))
{
final = "0";
}
Decimal intAgain = long.Parse(final, System.Globalization.NumberStyles.HexNumber);
intAgain = intAgain / 100;
string final3 = intAgain.ToString();
// string final2 = new string(go);
return final3;
}
[WebMethod]
public static string GetValues(string values)
{
return values;
}
public string GetDeviceJSON(String str)
{
Device[] emps = new Device[] {
new Device()
{
Freq=str
}
//new employee()
//{
// id=102,
// name="dinesh",
// salary=100000
//}
};
return new JavaScriptSerializer().Serialize(emps);
}
}
You are trying to access the Reponse object from a background thread, where the response is already long gone.
You are not allowed to access the Response object, or any other object under HttpContext after the page has stopped rendering. Use web sockets or AJAX calls to create asynchronous requests and responses.
I'm trying to use the new Toggl API (v8) with .NET C#. I've based my code on the example from litemedia (http://litemedia.info/connect-to-toggl-api-with-net), but it was originally created for version 1 of the API.
private const string TogglTasksUrl = "https://www.toggl.com/api/v8/tasks.json";
private const string TogglAuthUrl = "https://www.toggl.com/api/v8/me"; //sessions.json";
private const string AuthenticationType = "Basic";
private const string ApiToken = "user token goes here";
private const string Password = "api_token";
public static void Main(string[] args)
{
CookieContainer container = new CookieContainer();
var authRequest = (HttpWebRequest)HttpWebRequest.Create(TogglAuthUrl);
authRequest.Credentials = CredentialCache.DefaultCredentials;
authRequest.Method = "POST";
authRequest.ContentType = "application/x-www-form-urlencoded";
authRequest.CookieContainer = container;
string value = ApiToken; //= Convert.ToBase64String(Encoding.Unicode.GetBytes(ApiToken));
value = string.Format("{1}:{0}", Password, value);
//value = Convert.ToBase64String(Encoding.Unicode.GetBytes(value));
authRequest.ContentLength = value.Length;
using (StreamWriter writer = new StreamWriter(authRequest.GetRequestStream(), Encoding.ASCII))
{
writer.Write(value);
}
try
{
var authResponse = (HttpWebResponse)authRequest.GetResponse();
using (var reader = new StreamReader(authResponse.GetResponseStream(), Encoding.UTF8))
{
string content = reader.ReadToEnd();
}
HttpWebRequest tasksRequest = (HttpWebRequest)HttpWebRequest.Create(TogglTasksUrl);
tasksRequest.CookieContainer = container;
//var jsonResult = string.Empty;
var tasksResponse = (HttpWebResponse)tasksRequest.GetResponse();
MemoryStream ms = new MemoryStream();
tasksResponse.GetResponseStream().CopyTo(ms);
//using (var reader = new StreamReader(tasksResponse.GetResponseStream(), Encoding.UTF8))
//{
// jsonResult = reader.ReadToEnd();
//}
ms.Seek(0, SeekOrigin.Begin);
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Task));
var tasks = ser.ReadObject(ms) as List<Task>;
ms.Close();
//var tasks = DataContractJsonConvert.DeserializeObject<Task[]>(jsonResult);
foreach (var task in tasks)
{
Console.WriteLine(
"{0} - {1}: {2} starting {3:yyyy-MM-dd HH:mm}",
task.Project.Name,
task.Description,
TimeSpan.FromSeconds(task.Duration),
task.Start);
}
}
catch (System.Exception ex)
{
throw;
}
}
The following line is returning a 404 error.
var authResponse = (HttpWebResponse)authRequest.GetResponse();
Here is code that works. Since I was looking for this answer recently there might still be others as lost as me.
Notes: I used Encoding.Default.GetBytes() because Encoding.Unicode.GetBytes() did not give me a correct result on my .NET string. I hope it doesn't depend on the default setup of Visual Studio.
The content-type is "application/json".
Sorry, I haven't tried a POST version yet.
string ApiToken = "user token goes here";
string url = "https://www.toggl.com/api/v8/me";
string userpass = ApiToken + ":api_token";
string userpassB64 = Convert.ToBase64String(Encoding.Default.GetBytes(userpass.Trim()));
string authHeader = "Basic " + userpassB64;
HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(url);
authRequest.Headers.Add("Authorization", authHeader);
authRequest.Method = "GET";
authRequest.ContentType = "application/json";
//authRequest.Credentials = CredentialCache.DefaultNetworkCredentials;
try
{
var response = (HttpWebResponse)authRequest.GetResponse();
string result = null;
using (Stream stream = response.GetResponseStream())
{
StreamReader sr = new StreamReader(stream);
result = sr.ReadToEnd();
sr.Close();
}
if (null != result)
{
System.Diagnostics.Debug.WriteLine(result.ToString());
}
// Get the headers
object headers = response.Headers;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message + "\n" + e.ToString());
}