URL Downloader asp mvc - asp.net-mvc

I'm writing a windows app with C#.net to download a file from the internet
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
prbPercent.Value = e.ProgressPercentage;
lblPercent.Text = e.ProgressPercentage.ToString();
}
private void Completed(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show("Completed");
}
private void btnPath_Click(object sender, EventArgs e)
{
FolderBrowserDialog s = new FolderBrowserDialog();
s.ShowDialog();
txtPath.Text = s.SelectedPath;
}
private void btnDownload_Click(object sender, EventArgs e)
{
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
int t1 = txtLink.Text.LastIndexOf('/');
string strFileName = txtLink.Text.Remove(0, t1 + 1);
webClient.DownloadFileAsync(new Uri(txtLink.Text), txtPath.Text + "//" + strFileName);
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
but I'm looking for how to I write something like that with asp.net MVC
I want to do it with website.
Thanks in advance.

Related

What is the currently proper request-response pattern for NetMQ?

I'm trying to upgrade a Windows desktop application from .Net Framework to .Net (Core) 6.0. As part of that, I need to use NetMQ instead of the old clrzmq. But every reference I find for how to do a simple request-response using the new API has been obsoleted by subsequent updates. I found working code at this question, but again, some of the methods used no longer exist. I attempted to convert the source reasonably and arrived at the below.
The server prints nothing; the client claims to be sending messages; Wireshark sees no messages on "port 5556". (I tagged Wireshark in case I'm using it wrong.)
I think if I can find out how this code should work I can properly convert my original application. Any help would be much appreciated.
Program.cs (by itself in its own solution, for the server):
using NetMQ;
using NetMQ.Sockets;
using NLog;
class Program
{
private static Logger _logger = LogManager.GetCurrentClassLogger();
static void Main(string[] args)
{
try
{
using (var responseSocket = new ResponseSocket())
{
responseSocket.Connect("tcp://localhost:5556");
var poller = new NetMQPoller();
responseSocket.ReceiveReady += RouterSocketOnReceiveReady;
poller.Add(responseSocket);
poller.Run();
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadKey();
}
private static void RouterSocketOnReceiveReady(object? sender, NetMQSocketEventArgs netMqSocketEventArgs)
{
NetMQMessage? clientMessage = new();
bool result = netMqSocketEventArgs.Socket.TryReceiveMultipartMessage(new TimeSpan(0, 0, 0, 5),
ref clientMessage, 5);
if (result == false || clientMessage == null)
{
Console.WriteLine("Something went wrong?!");
return;
}
var address = clientMessage[0];
var address2 = clientMessage[1];
var clientMessageString = clientMessage[3].ConvertToString();
//_logger.Debug("Message from client received: '{0}'", clientMessageString);
Console.WriteLine(String.Format("Message from client received: '{0}'", clientMessageString));
netMqSocketEventArgs
.Socket.SendMoreFrame(address.Buffer)
.SendMoreFrame(address2.Buffer)
.SendMoreFrameEmpty()
.SendFrame("I have received your message");
}
}
CollectorDevice.cs (in the client project and solution):
using NetMQ;
using NetMQ.Sockets;
using NLog;
public class CollectorDevice : IDisposable
{
private NetMQPoller _poller;
private RouterSocket _frontendSocket;
private DealerSocket _backendSocket;
private readonly string _backEndAddress;
private readonly string _frontEndAddress;
private readonly int _expectedFrameCount;
private readonly ManualResetEvent _startSemaphore = new(false);
private readonly Thread _localThread;
private static Logger _logger = LogManager.GetCurrentClassLogger();
/// <summary>
/// Constructor
/// </summary>
/// <param name="backEndAddress"></param>
/// <param name="frontEndAddress"></param>
/// <param name="expectedFrameCount"></param>
public CollectorDevice(string backEndAddress, string frontEndAddress, int expectedFrameCount)
{
_expectedFrameCount = expectedFrameCount;
_backEndAddress = backEndAddress;
_frontEndAddress = frontEndAddress;
_frontendSocket = new RouterSocket(_frontEndAddress);
_backendSocket = new DealerSocket(_backEndAddress);
_backendSocket.ReceiveReady += OnBackEndReady;
_frontendSocket.ReceiveReady += OnFrontEndReady;
_poller = new NetMQPoller { _frontendSocket, _backendSocket };
_localThread = new Thread(DoWork) { Name = "IPC Collector Device Thread" };
}
public void Start()
{
_localThread.Start();
_startSemaphore.WaitOne();
}
public void Stop()
{
_poller.Stop();
}
#region Implementation of IDisposable
public void Dispose()
{
Stop();
}
#endregion
#region Private Methods
private void DoWork()
{
try
{
_startSemaphore.Set();
_poller.Run();
}
catch (Exception e)
{
_logger.Error(e);
}
}
private void OnBackEndReady(object? sender, NetMQSocketEventArgs e)
{
NetMQMessage message = _backendSocket.ReceiveMultipartMessage(_expectedFrameCount);
_frontendSocket.SendMultipartMessage(message);
}
private void OnFrontEndReady(object? sender, NetMQSocketEventArgs e)
{
NetMQMessage message = _frontendSocket.ReceiveMultipartMessage(_expectedFrameCount);
_backendSocket.SendMultipartMessage(message);
}
#endregion
}
Program.cs (also in the client project and solution):
using NetMQ;
using NetMQ.Sockets;
using NLog;
using System.Text;
class Program
{
private static Logger _logger = LogManager.GetCurrentClassLogger();
private static void Main(string[] args)
{
Console.WriteLine("Client. Please enter message for server. Enter 'QUIT' to turn off server");
Console.ReadKey();
var encoding = Encoding.ASCII;
using (var collectorDevice = new CollectorDevice("tcp://localhost:5556", "inproc://broker", 3))
{
collectorDevice.Start();
var tasks = new List<Task>();
for (int i = 0; i < 100; i++)
{
Console.WriteLine(i);
int j = i;
Task t = Task.Factory.StartNew(() =>
{
try
{
using (var requestSocket = new RequestSocket("inproc://broker"))
{
requestSocket.SendFrame(encoding.GetBytes(String.Format("Request client: {0} id: {1}", j, Task.CurrentId)));
_logger.Debug(String.Format("Request client: {0} id: {1}", j, Task.CurrentId));
Console.WriteLine(String.Format("Request client: {0} id: {1}", j, Task.CurrentId));
string responseMessage = requestSocket.ReceiveFrameString();
_logger.Debug(String.Format("Response from server: {0} id: {1} message: {2}", j, Task.CurrentId, responseMessage));
Console.WriteLine(String.Format("Response from server: {0} id: {1} message: {2}", j, Task.CurrentId, responseMessage));
}
}
catch (Exception e)
{
Console.WriteLine(e);
_logger.Error(e);
}
});
tasks.Add(t);
}
Task.WaitAll(tasks.ToArray());
}
}
}
I got my answer at the GitHub issue I opened. The updated code successfully exchanges messages and terminates with 0, but the messages are out of order; additional logic would be required to put the messages in order, but the point of this question was just to exchange messages.
The necessary changes are mostly in the server's Program.cs:
using NetMQ;
using NetMQ.Sockets;
using NLog;
Logger _logger = LogManager.GetCurrentClassLogger();
try
{
using (var responseSocket = new ResponseSocket())
{
responseSocket.Bind("tcp://localhost:5556");
var poller = new NetMQPoller();
responseSocket.ReceiveReady += RouterSocketOnReceiveReady;
poller.Add(responseSocket);
poller.Run();
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadKey();
void RouterSocketOnReceiveReady(object? sender, NetMQSocketEventArgs netMqSocketEventArgs)
{
NetMQMessage? clientMessage = new();
bool result = netMqSocketEventArgs.Socket.TryReceiveMultipartMessage(new TimeSpan(0, 0, 0, 5),
ref clientMessage, 5);
if (result == false || clientMessage == null)
{
Console.WriteLine("Something went wrong?!");
return;
}
var clientMessageString = clientMessage.Single().ToByteArray();
//_logger.Debug("Message from client received: '{0}'", clientMessageString);
Console.WriteLine(string.Format("Message from client received: '{0}'", string.Join(", ", clientMessageString)));
netMqSocketEventArgs
.Socket
.SendFrame("I have received your message");
}
Here's the client's Program.cs:
using NetMQ;
using NetMQ.Sockets;
using NLog;
using System.Text;
Logger _logger = LogManager.GetCurrentClassLogger();
Console.WriteLine("Client. Please enter message for server. Enter 'QUIT' to turn off server");
Console.ReadKey();
var encoding = Encoding.ASCII;
using var collectorDevice = new CollectorDevice("tcp://localhost:5556", "inproc://broker", 3);
collectorDevice.Start();
var tasks = new List<Task>();
for (int i = 0; i < 100; i++)
{
Console.WriteLine(i);
int j = i;
Task t = Task.Factory.StartNew(() =>
{
try
{
using (var requestSocket = new RequestSocket("inproc://broker"))
{
requestSocket.SendFrame(encoding.GetBytes(string.Format("Request client: {0} id: {1}", j, Task.CurrentId)));
_logger.Debug(string.Format("Request client: {0} id: {1}", j, Task.CurrentId));
Console.WriteLine(string.Format("Request client: {0} id: {1}", j, Task.CurrentId));
string responseMessage = requestSocket.ReceiveFrameString();
_logger.Debug(string.Format("Response from server: {0} id: {1} message: {2}", j, Task.CurrentId, responseMessage));
Console.WriteLine(string.Format("Response from server: {0} id: {1} message: {2}", j, Task.CurrentId, responseMessage));
}
}
catch (Exception e)
{
Console.WriteLine(e);
_logger.Error(e);
}
});
tasks.Add(t);
}
Task.WaitAll(tasks.ToArray());
And the client's CollectorDevice.cs:
using NetMQ;
using NetMQ.Sockets;
using NLog;
public class CollectorDevice : IDisposable
{
private NetMQPoller _poller;
private RouterSocket _frontendSocket;
private DealerSocket _backendSocket;
private readonly string _backEndAddress;
private readonly string _frontEndAddress;
private readonly int _expectedFrameCount;
private readonly ManualResetEvent _startSemaphore = new(false);
private readonly Thread _localThread;
private static Logger _logger = LogManager.GetCurrentClassLogger();
/// <summary>
/// Constructor
/// </summary>
/// <param name="backEndAddress"></param>
/// <param name="frontEndAddress"></param>
/// <param name="expectedFrameCount"></param>
public CollectorDevice(string backEndAddress, string frontEndAddress, int expectedFrameCount)
{
_expectedFrameCount = expectedFrameCount;
_backEndAddress = backEndAddress;
_frontEndAddress = frontEndAddress;
_frontendSocket = new RouterSocket(_frontEndAddress);
_backendSocket = new DealerSocket(_backEndAddress);
_backendSocket.ReceiveReady += OnBackEndReady;
_frontendSocket.ReceiveReady += OnFrontEndReady;
_poller = new NetMQPoller { _frontendSocket, _backendSocket };
_localThread = new Thread(DoWork) { Name = "IPC Collector Device Thread" };
}
public void Start()
{
_localThread.Start();
_startSemaphore.WaitOne();
}
public void Stop()
{
_poller.Stop();
}
#region Implementation of IDisposable
public void Dispose()
{
Stop();
}
#endregion
#region Private Methods
private void DoWork()
{
try
{
_startSemaphore.Set();
_poller.Run();
}
catch (Exception e)
{
_logger.Error(e);
}
}
private void OnBackEndReady(object? sender, NetMQSocketEventArgs e)
{
NetMQMessage message = _backendSocket.ReceiveMultipartMessage(_expectedFrameCount);
_frontendSocket.SendMultipartMessage(message);
}
private void OnFrontEndReady(object? sender, NetMQSocketEventArgs e)
{
NetMQMessage message = _frontendSocket.ReceiveMultipartMessage(_expectedFrameCount);
_backendSocket.SendMultipartMessage(message);
}
#endregion
}

Updating image control in Windows Phone 8

I have a HTML5 web app I can view through my mobile devices.
I have an img control that would download an image using an ashx asp.net handler.
I updated via a timer.
I am trying to port this over to a Windows Phone 8.1 app instead.
The image seems to take ages to update (if at all). This is my code:
long tick = DateTime.Now.Ticks;
BitmapImage bmp =new BitmapImage(new Uri("http://my url/Mobile/NewFrame.ashx?b=1a=9A5C3-E1945-3D315-BB43C&c=3&m=1&t=" + tick));
imgFrame1.Source = bmp;
Is this the correct way?
this is the full code:
private async void LogIn()
{
using (var client = new HttpClient())
{
var resp = await client.PostAsJsonAsync("http://my url/UserManagement/Login.aspx/Test",
new { username = "", password = "", hubuserid = hubuserid });
var str = await resp.Content.ReadAsStringAsync();
var jsonObj = JsonConvert.DeserializeObject<UserLogIn>(str);
if (jsonObj.d.Success)
{
UpdateConnectionState("Logged In");
}
else
{
UpdateConnectionState("Not Logged In");
}
}
}
public class D
{
public string __type { get; set; }
public bool Success { get; set; }
}
public class UserLogIn
{
public D d { get; set; }
}
private string hubuserid = "";
public string Uptime { get; set; }
private byte ImageIsLoaded = 1;
private async void UpdateTime(int data)
{
await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
try
{
txtInfo.Text = data.ToString();
if (ImageIsLoaded == 1)
{
ImageIsLoaded = 0;
long tick = DateTime.Now.Ticks;
BitmapImage bi = new BitmapImage(new Uri("http://www.informedmotion.co.uk/Mobile/NewFrame.ashx?b=1a=9A5C3-E1945-3D315-BB43C&c=3&m=1&t=" + tick, UriKind.Absolute));
bi.DownloadProgress += bi_DownloadProgress;
bi.ImageOpened += bi_ImageOpened; }
}
catch (Exception ex)
{
txtInfo.Text = ex.ToString();
}
});
}
void bi_DownloadProgress(object sender, DownloadProgressEventArgs e)
{
//throw new NotImplementedException();
}
void bi_ImageOpened(object sender, RoutedEventArgs e)
{
ImageIsLoaded = 1;
imgFrame1.Source = (BitmapImage)sender;
}
private void imgFrame1_ImageOpened(object sender, RoutedEventArgs e)
{
ImageIsLoaded = 1;
}
private void imgFrame1_ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
ImageIsLoaded = 1;
}
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
imgFrame1.ImageFailed += imgFrame1_ImageFailed;
imgFrame1.ImageOpened += imgFrame1_ImageOpened;
ConnectToHub();
}
private void ConnectToHub()
{
proxy.On<int>("broadcastMessage", data =>
{
UpdateTime(data);
});
connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
UpdateConnectionState("Not Connected");
ConnectToHub();
}
else
{
UpdateConnectionState(string.Format("Success! Connected with client connection id {0}", connection.ConnectionId));
hubuserid = connection.ConnectionId;
LogIn();
}
});
connection.Error += ex =>
{
UpdateConnectionState(string.Format("An error occurred {0}", ex.Message));
};
connection.Closed += () =>
{
UpdateConnectionState(string.Format("Connection with client id {0} closed", connection.ConnectionId));
ConnectToHub();
};
connection.Reconnected += () =>
{
//LogIn();
UpdateConnectionState("The connection was re-established");
};
}
Windows.UI.Core.CoreDispatcher dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;
async void UpdateConnectionState(string state)
{
await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
try{
txtInfo.Text = state;
}
catch (Exception ex)
{
txtInfo.Text = ex.ToString();
}
});
}
static HubConnection connection = new HubConnection("http://www.informedmotion.co.uk/");
IHubProxy proxy = connection.CreateHubProxy("ChatHub");
If you're going to download the image, then you probably want to hooked the
Image.DownloadProgress event
Image.ImageOpened event
ImageOpened will fire once the download is complete, so at that moment you can set the .Source to it.
While it is downloading (if it's a huge image) you can either show the previous image or a place holder image (with progress bar maybe?)
BitmapImage bi = new BitmapImage(new Uri("http://www.google.com/myimage.bmp", UriKind.Absolute));
bi.DownloadProgress += bi_DownloadProgress;
bi.ImageOpened += bi_ImageOpened;
hiddenImage.Source = bi; // we need to set it to an element in the visual tree so the
// events will fire, we're going to use the hiddenImage
void bi_DownloadProgress(object sender, DownloadProgressEventArgs e)
{
throw new NotImplementedException();
}
void bi_ImageOpened(object sender, RoutedEventArgs e)
{
throw new NotImplementedException();
}
<!-- myImage is your image that you use to show stuff -->
<!-- hiddenImage is the image we use to fire the event -->
<Image x:Name="myImage"></Image>
<Image x:Name="hiddenImage" Visibility="Collapsed"></Image>

How can i catch parameter on maproute?

How can i retrieve certain a section on routemap pattern.For instance i have a routemap pattern on my config file as routes.MapRoute("", "Post/{slug}", new { controller = "Post", action = "Index" }) and i want to catch slug parameter inside global.asax.I tried as followed but it returns null.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
var context = base.Context;
if (context != null)
{
Response.Write(context.Request.RequestContext.RouteData.Values["slug"]);
}
}
You can try this:
protected void Application_BeginRequest(object sender, EventArgs e)
{
var httpContext = ((MvcApplication)sender).Context;
var currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
if (currentRouteData.Values["slug"] != null)
{
Response.Write(currentRouteData.Values["slug"]);
}
}
I believe RouteData is not yet resolved when BeginRequest event is fired. You can use EndRequest instead.
protected void Application_EndRequest(object sender, EventArgs e)
{
var context = base.Context;
if (context != null)
{
Response.Write(context.Request.RequestContext.RouteData.Values["slug"]);
}
}
To make sure correct route is being used and slug parameter is actually supplied I'd recommend Route debugger

I cant access to HttpContext.Application It always return null

this is my code for counting online users
it works well in global.asax and it count well
but when I call it from controller it returns null
void Session_Start(object sender, EventArgs e)
{
Application.Lock();
Application["OnlineUsers"] = (int)Application["OnlineUsers"] + 1;
Application.UnLock();
}
void Session_End(object sender, EventArgs e)
{
Application.Lock();
Application["OnlineUsers"] = (int)Application["OnlineUsers"] - 1;
Application.UnLock();
}
protected void Application_Start()
{
Application["OnlineUsers"] = 0;
}
in controller:
string strUsersOnline = HttpContext.Application["OnlineUsers"] as string;
ViewData["OnlineUsers"] = strUsersOnline;
The value is null because the of the as keyword, use explicit conversion or .ToString()
Refer MSDN

Global.asax in Umbraco 6

I had the following in my Global.asax (Umbraco 4.7)
Application_Start
Application_EndRequest
Application_Error
Session_Start
Session_End
Now I have upgraded to Umbraco 6.0.3, which global.asax inherits from Umbraco.Web.UmbracoApplication
Where do I put my event handlers (and what are the equivalent method names)?
This is what I found so far.
You can create your own class
public class Global : Umbraco.Web.UmbracoApplication
{
public void Init(HttpApplication application)
{
application.PreRequestHandlerExecute += new EventHandler(application_PreRequestHandlerExecute);
application.EndRequest += (new EventHandler(this.Application_EndRequest));
//application.Error += new EventHandler(Application_Error); // Overriding this below
}
protected override void OnApplicationStarted(object sender, EventArgs e)
{
base.OnApplicationStarted(sender, e);
// Your code here
}
private void application_PreRequestHandlerExecute(object sender, EventArgs e)
{
try
{
if (Session != null && Session.IsNewSession)
{
// Your code here
}
}
catch(Exception ex) { }
}
private void Application_BeginRequest(object sender, EventArgs e)
{
try { UmbracoFunctions.RenderCustomTree(typeof(CustomTree_Manage), "manage"); }
catch { }
}
private void Application_EndRequest(object sender, EventArgs e)
{
// Your code here
}
protected new void Application_Error(object sender, EventArgs e)
{
// Your error handling here
}
}
And have Global.asax inherit from your class
<%# Application Codebehind="Global.asax.cs" Inherits="Global" Language="C#" %>
Alternative method: Inherit ApplicationEventHandler - but it's not working for me

Resources