I'm having this issue with the html5 canvas. I'm using EaselJS to load in images.
http://www.createjs.com/Docs/EaselJS/Bitmap.html
But when I add any kind of mouse events (onClick, onMouseOver, onMouseOut) on a parentcontainer of the image, from the moment i move my mouse, EaselJS spams this error:
uncaught exception: An error has occurred. This is most likely due to security restrictions on reading canvas pixel data with local or cross-domain images.
It's running on an IIS server and the image I get is from an other domain.
I can get it working in Chrome by using --disable-web-security. But I'd rather avoid that.
I have read something about a proxy script might help fix this, but I don't know exactly how I could implement that here.
Any suggestions for a fix?
EDIT:
Resolved!
I resolved this by using a simple asp.net proxy script
http://www.sharepointjohn.com/aspnet-proxy-page-cross-domain-requests-from-ajax-and-javascript/
I started from this and with some help of colleagues it came to this .ashx file:
<%# WebHandler Language="C#" Class="getSharepointImage" %>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Drawing;
public class getSharepointImage : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
string proxyURL = string.Empty;
try
{
proxyURL = HttpUtility.UrlDecode(context.Request.QueryString["u"].ToString());
}
catch { }
if (proxyURL != string.Empty)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(proxyURL);
//request.Credentials = new NetworkCredential("username", "password"); //needed if you wish to access something like sharepoint
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode.ToString().ToLower() == "ok")
{
string contentType = "img/png";
Stream content = response.GetResponseStream();
StreamReader contentReader = new StreamReader(content);
context.Response.ContentType = contentType;
var outStream = context.Response.OutputStream;
Bitmap myImage = new Bitmap(System.Drawing.Image.FromStream(response.GetResponseStream()));
MemoryStream writeStream = new MemoryStream();
myImage.Save(outStream, System.Drawing.Imaging.ImageFormat.Png);
writeStream.WriteTo(outStream);
myImage.Dispose();
}
}
}
public bool IsReusable {
get {
return false;
}
}
}
Try the following:
var hitArea = new createjs.Shape;
hitArea.graphics.beginFill("#000").drawRect(0,0,100,100);
yourobj.hitArea = hitArea;
Related
I have been trying to use download a file from my angular 6 application by calling an API method GetFile() written using NancyFx.
The GetFile() API method again calls a web API method GetRemoteFile() using RestSharp.
The GetFile() method follows the async/await pattern. But I see that the file gets downloaded before the success callback of GetRemoteFile() is even being called.
And because of this the downloaded file is 0 bytes.
using RestSharp.Extensions.MonoHttp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using System.Linq;
using Nancy.Json;
using RestSharp.Extensions;
using System.Net;
using Nancy;
using Nancy.Responses;
using RestSharp;
private async Task<Nancy.Response> GetFile(int orderId)
{
var request = new RestRequest($"api/GetRemoteFile", Method.POST);
string json = SomeBodyData();
request.AddJsonBody(new RemoteParameter
{
OId = documentId,
Json = json
});
var taskCompletionSource = new TaskCompletionSource<IResponse>();
client.BaseUrl = new Uri("http://someremoteapi.com/orders/");
var res = client.PostAsync(request, (response,handle) =>
{
taskCompletionSource.SetResult(response);
});
var data = await taskCompletionSource.Task;
var stream = new MemoryStream(data.RawBytes);
stream.Position = 0;
var file= new StreamResponse(() => stream, "text/csv");
return file;
}
Follow the async flow and await ExecuteTaskAsync. With that, you should be able get the desired behavior.
private async Task<Nancy.Response> GetFile(int orderId) {
var request = new RestRequest($"api/GetRemoteFile", Method.POST);
string json = SomeBodyData();
request.AddJsonBody(new RemoteParameter {
OId = documentId,
Json = json
});
client.BaseUrl = new Uri("http://someremoteapi.com/orders/");
var response = await client.ExecuteTaskAsync(request);
var stream = new MemoryStream(response.RawBytes);
stream.Position = 0;
var file= new StreamResponse(() => stream, "text/csv");
return file;
}
In my integration test the object schoolyearCreateRequest sent to /api/schoolyears url contains only null values when passing to the Post([FromBody] SchoolyearCreateRequest request) action parameter.
But when I use fiddler:
http://localhost:6320/api/schoolyears
Content-Type: application/json
Request Body:
{ SchoolyearDto:
{ Id: 10 }
}
Then it works and the SchoolyearDto is not null.
What is the problem in my integration test?
var schoolyearCreateRequest = new SchoolyearCreateRequest
{
SchoolyearDto = new SchoolyearDto(),
SchoolclassCodeDtos = new List<SchoolclassCodeDTO>(),
TimeTablesWeekAddedWeekA = new List<TimeTableDTO>(),
TimeTablesWeekAddedWeekAB = new List<TimeTableDTO>()
};
// Arrange
const string url = "api/schoolyears/";
var request = new HttpRequestMessage(HttpMethod.Post, _server.BaseAddress + url);
request.Content = new ObjectContent<SchoolyearCreateRequest>(schoolyearCreateRequest,new JsonMediaTypeFormatter());
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
// Act
var response = _client.PostAsync(_server.BaseAddress + url, request, new JsonMediaTypeFormatter(), new CancellationToken()).Result;
// Assert
Assert.That(response.StatusCode == HttpStatusCode.Created);
UPDATE:
I made it working now in my integration test too:
replace these lines:
request.Content = new ObjectContent<SchoolyearCreateRequest>(schoolyearCreateRequest,new JsonMediaTypeFormatter());
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
with this line:
var postData = new StringContent(JsonConvert.SerializeObject(schoolyearCreateRequest), Encoding.UTF8, "application/json");
Why do I have to serialize the data by myself? And why is nearly nobody doing this approach with web api integration testing? All blogs I read showed the usage of the ObjectContent ??
You can take a look at my answer in the following post:
How do I exercise Formatters in tests using HttpServer?
Also, you can take a look at my blog post which was written long time back, but is still relevant:
http://blogs.msdn.com/b/kiranchalla/archive/2012/05/06/in-memory-client-amp-host-and-integration-testing-of-your-web-api-service.aspx
UPDATE:
Since there seems to be confusion around this, following is a complete example of an in-memory test. Its a bit crude but still should give you an idea.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using WebApplication251.Models;
namespace WebApplication251.Tests.Controllers
{
[TestClass]
public class PeopleControllerTest
{
string baseAddress = "http://dummyhost/";
[TestMethod]
public void PostTest()
{
HttpConfiguration config = new HttpConfiguration();
// use the configuration that the web application has defined
WebApiConfig.Register(config);
HttpServer server = new HttpServer(config);
//create a client with a handler which makes sure to exercise the formatters
HttpClient client = new HttpClient(new InMemoryHttpContentSerializationHandler(server));
Person p = new Person() { Name = "John" };
using (HttpResponseMessage response = client.PostAsJsonAsync<Person>(baseAddress + "api/people", p).Result)
{
Assert.IsNotNull(response.Content);
Assert.IsNotNull(response.Content.Headers.ContentType);
Assert.AreEqual<string>("application/json; charset=utf-8", response.Content.Headers.ContentType.ToString());
Person recPerson = response.Content.ReadAsAsync<Person>().Result;
Assert.AreEqual(p.Name, recPerson.Name);
}
}
}
public class InMemoryHttpContentSerializationHandler : DelegatingHandler
{
public InMemoryHttpContentSerializationHandler(HttpMessageHandler innerHandler)
: base(innerHandler)
{
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
request.Content = await ConvertToStreamContentAsync(request.Content);
HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
response.Content = await ConvertToStreamContentAsync(response.Content);
return response;
}
private async Task<StreamContent> ConvertToStreamContentAsync(HttpContent originalContent)
{
if (originalContent == null)
{
return null;
}
StreamContent streamContent = originalContent as StreamContent;
if (streamContent != null)
{
return streamContent;
}
MemoryStream ms = new MemoryStream();
await originalContent.CopyToAsync(ms);
// Reset the stream position back to 0 as in the previous CopyToAsync() call,
// a formatter for example, could have made the position to be at the end
ms.Position = 0;
streamContent = new StreamContent(ms);
// copy headers from the original content
foreach (KeyValuePair<string, IEnumerable<string>> header in originalContent.Headers)
{
streamContent.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
return streamContent;
}
}
}
I am new to this forum as well as Windows Phone Development. I am currently developing an app in which I am working with a Web-Service and I need to make a POST request to a web service.
I am trying to accomplish a user login functionality here for which,
-> http://abc.com/login (URI)
-> (PARAMETERS)
apikey: 32 byte long alpha-numeric
username: 3-15 characters
password: 3-15 characters
So for this I am trying to use WebClient class' UploadStringSync method in order to POST the data. My code is as follows.
WebClient wc1 = new WebClient();
wc1.UploadStringAsync(new Uri("http://abc.com/login"),"POST","?apikey=" + Apikey + "&username=username&password=password");
wc1.UploadStringCompleted += new UploadStringCompletedEventHandler(wc1_UploadStringCompleted);
void wc1_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
MessageBox.Show(e.Result);
}
Execution stops here at MessageBox line and throws message saying 'The remote server returned an error: NotFound.'
Is there any problem with the way I am passing the parameters? I tried to search for the working implementation everywhere but was unable to find it.
Can anybody help me with this? This is a starting point of my project and really need help on this one. Any help would be much appreciated.
try this:
public void Post(string address, string parameters, Action<string> onResponseGot)
{
Uri uri = new Uri(address);
HttpWebRequest r = (HttpWebRequest)WebRequest.Create(uri);
r.Method = "POST";
r.BeginGetRequestStream(delegate(IAsyncResult req)
{
var outStream = r.EndGetRequestStream(req);
using (StreamWriter w = new StreamWriter(outStream))
w.Write(parameters);
r.BeginGetResponse(delegate(IAsyncResult result)
{
try
{
HttpWebResponse response = (HttpWebResponse)r.EndGetResponse(result);
using (var stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
onResponseGot(reader.ReadToEnd());
}
}
}
catch
{
onResponseGot(null);
}
}, null);
}, null);
}
I did this and it worked
WebClient web = new WebClient();
web.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
web.UploadStringAsync((new Uri("http://www.something.com/?page=something")), "POST", string.Format("v1=onevalue&v2=anothervalue"));
web.UploadStringCompleted += web_UploadStringCompleted;
and after upload is complete to get the html i used htmlagilitypack, you can just get the whole html using e.Result
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(e.Result);
HtmlNode node = doc.DocumentNode.SelectSingleNode("//body//table");
MessageBox.Show(node.InnerText);
I have a win app on my server that is supposed to display a set of specific pictures and videos for each client . I have no idea how to detect clients and displaying appropriate slides for each one .
Is there any solution ?
you are talking about client server application here try to socket programming which provide you the functionalities of Ip Addresses then you can get the ip address of a client then do what ever you want to do
You have to make two different project to run this Application First make a project which should be called Client and Copy paste this Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace Task4Client
{
class Program
{
static void Main(string[] args)
{
string data;
string input;
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
server.Connect(ipEndPoint);
}
catch (SocketException e)
{
Console.WriteLine("Unable To Connect To Server");
Console.WriteLine(e.ToString());
throw;
}
NetworkStream networkStream = new NetworkStream(server);
StreamReader streamReader = new StreamReader(networkStream);
StreamWriter streamWriter = new StreamWriter(networkStream);
/// data = streamReader.ReadLine();
// Console.WriteLine(data);
while (true)
{
input = Console.ReadLine();
if (input == "exit")
{
break;
}
streamWriter.WriteLine(input);
streamWriter.Flush();
data = streamReader.ReadLine();
Console.WriteLine(data);
}
Console.WriteLine("Disconnecting From Server");
streamWriter.Close();
streamReader.Close();
networkStream.Close();
server.Shutdown(SocketShutdown.Both);
server.Close();
}
}
}
Then make a project which should be called Server and copy paste this code
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace Task4Server
{
class Program
{
static void Main(string[] args)
{
string data;
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 9050);
Socket newSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
newSocket.Bind(ipEndPoint);
newSocket.Listen(10);
Console.WriteLine("waiting for a clinet ...");
Socket client = newSocket.Accept();
IPEndPoint newClient = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("Connected with {0} at port {1}", newClient.Address, newClient.Port);
NetworkStream networkStream = new NetworkStream(client);
StreamReader streamReader = new StreamReader(networkStream);
StreamWriter streamWriter = new StreamWriter(networkStream);
// string welcome = "Welcome to my Haseeb Server";
// streamWriter.WriteLine(welcome);
while (true)
{
try
{
data = streamReader.ReadLine();
}
catch (IOException)
{
break;
}
Console.WriteLine(data);
streamWriter.WriteLine(data);
streamWriter.Flush();
}
Console.WriteLine("Disconnected from {0}", newClient.Address);
streamWriter.Close();
streamReader.Close();
networkStream.Close();
}
}
}
then first run the Server Application Then Client and Sent message from Client to server it will behave like Client Server Application enjoy
I am following http://www.mikesdotnetting.com/Article/125/ASP.NET-MVC-Uploading-and-Downloading-Files. Using VS2010, ASP.NET 4.0, MVC3 in C# with ADO.NET in SQL Server 2008R2. I am getting the following error message...
'System.Web.HttpPostedFileBase' does not contain a definition for 'HasFile' and no extension method 'HasFile' accepting a first argument of type 'System.Web.HttpPostedFileBase' could be found (are you missing a using directive or an assembly reference?)
I searched through Stackflow, there was something about including System.Web.Abstractions. I included this and I still getting the error.
Thanks in advance if anyone can tell me the solution.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Data.SqlClient;
using System.Web.Helpers;
namespace MvcApplication1.Controllers
{
public class MyController : Controller
{
//
// GET: /My/
public ActionResult Index()
{
foreach (string upload in Request.Files)
{
if (!Request.Files[upload].HasFile()) continue;
string mimeType = Request.Files[upload].ContentType;
Stream fileStream = Request.Files[upload].InputStream;
string fileName = Path.GetFileName(Request.Files[upload].FileName);
int fileLength = Request.Files[upload].ContentLength;
byte[] fileData = new byte[fileLength];
fileStream.Read(fileData, 0, fileLength);
const string connect = #"Server=.\SQLExpress;Database=FileTest;Trusted_Connection=True;";
using (var conn = new SqlConnection(connect))
{
var qry = "INSERT INTO FileStore (FileContent, MimeType, FileName) VALUES (#FileContent, #MimeType, #FileName)";
var cmd = new SqlCommand(qry, conn);
cmd.Parameters.AddWithValue("#FileContent", fileData);
cmd.Parameters.AddWithValue("#MimeType", mimeType);
cmd.Parameters.AddWithValue("#FileName", fileName);
conn.Open();
cmd.ExecuteNonQuery();
}
}
return View();
}
public FileContentResult GetFile(int id)
{
SqlDataReader rdr; byte[] fileContent = null;
string mimeType = ""; string fileName = "";
const string connect = #"Server=.\SQLExpress;Database=FileTest;Trusted_Connection=True;";
using (var conn = new SqlConnection(connect))
{
var qry = "SELECT FileContent, MimeType, FileName FROM FileStore WHERE ID = #ID";
var cmd = new SqlCommand(qry, conn);
cmd.Parameters.AddWithValue("#ID", id);
conn.Open();
rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
rdr.Read();
fileContent = (byte[])rdr["FileContent"];
mimeType = rdr["MimeType"].ToString();
fileName = rdr["FileName"].ToString();
}
}
return File(fileContent, mimeType, fileName);
}
}
}
in the Helpers folder I have the Helper class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcApplication1.Models
{
public static class Helper
{
public static bool HasFile(this HttpPostedFileBase file)
{
return (file != null && file.ContentLength > 0) ? true : false;
}
}
You need to add a using statement to your MyController code file, as that is what is required when you want to use an extension method (it needs to be in scope):
using MvcApplication1.Models;