I am a newbie of Websocket. I have created a ASP.NET Web project in Visual Studio named CAPWebSocketProject. Inside this project there is a .ashx file named CPWebSocket.ashx. Inside this ashx file, there are c# codes. Here are the codes:
public class CPWebSocket : IHttpHandler
{
public long fnGetTerminalInfo()
{
string strCom = "COM4"; // hard coded for testing
string strGetTerminalInfoCommand = "C900";
<XXXX> clsTerminal = new <XXXX>();
long lgPortStat = clsTerminal.SendCommand(strCom, strGetTerminalInfoCommand);
return lgPortStat;
}
}
Now, my question is how to create the websocket CPWebSocket.ashx file's URL so I can access from a browser?
I don't think .ashx is websocket, you need to inherit from WebSocketService then you need to create object of websocket in javascript and give it the url of the websocket and the key want to listen to it, here's an example:
http://www.codeproject.com/Articles/1063910/WebSocket-Server-in-Csharp
Related
I am using ASP.NET 4.7 and MVC5 with C# with IIS Express locally and published to Azure App Services.
I want to add something like:
Response.AppendToLog("XXXXX Original IP = 12.12.12.12 XXXXX");
Which adds an Original IP address to the request string in the "request" column in the web server log.
If I add this to a specific "get" Action this works fine. However I do not want to add this code to every Action. Is it possible to place it more centrally such that it gets executed on every "Get" / Request. This may be a simple question, but the answer alludes me at present
Thanks for any wisdom.
EDIT: Is this via Custom Action Filters?
if (filterContext.HttpContext.Request.HttpMethod=="GET")
{
Response.AppendToLog... //I know this will not work as Response not known.
}
You almost know the answer. Try handling OnActionExecuted that gets you the Response.
public class CustomActionFilter : ActionFilterAttribute, IActionFilter
{
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
if(filterContext.HttpContext.Request.Method == HttpMethods.Get)
{
}
}
void IActionFilter.OnActionExecuted(ActionExecutedContext context)
{
var response = context.HttpContext.Response;
}
}
My solution to write out text:
filterContext.RequestContext.HttpContext.Response.AppendToLog("OrigIP");
I have web application and windows application in same solution. I want to dynamically add connection string in web.config file. The connection string information give from windows application. How do i do this please help me.
My window app having:
WebForm1 wf = new WebForm1();
wf.add();
And my wep app having:
public void add()
{
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConnectionStringsSection sec = (ConnectionStringsSection)config.GetSection("connectionStrings");
sec.ConnectionStrings["DBCS"].ConnectionString = "Data Source=GKS_004-PC;Database=hello1;User ID=123;Password=123";
config.Save();
}
I believe you address your problem in a way that may exist a different approach to solve your issue, however in order to do what you want you have two options. First you can read the file using the IO namespace and then parse it like XML using LINQ nodes and second you can use the Configuration class (System.Configuration and System.Web.Configuration namespaces).
//get the configuration file
Configuration config = WebConfigurationManager.OpenWebConfiguration("..."); //path to config
//get Configuration section
ConfigurationSection section = config.GetSection("...");
config.AppSettings.Settings.Add(Key, Value);
config.AppSettings.Settings.Remove(Key);
or this way, instead of using directly Configuration class
AppSettingsSection appsettings = (AppSettingsSection) config.GetSection("...");
appsettings.Settings.Add(key, Value);
I have an asp.net web api application which is acting as a Relay to a wcf web service. In certain scenarios I want to upload large files. The methods in the wcf service accept files as stream.
I do not want to save the files on my intermediate server I want to access the stream of the uploaded file and provide it to the wcf method so that the data is directly streamed to the wcf service.
Here is similar scenario when client is downloading the file
using (IProductsChannel channel = ChannelFactory.CreateChannel())
{
result.Content = new StreamContent(channel.GetFile());
result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
return result;
}
Here is at least one way of doing it. using the HTTPContext the only problem with this one is that it is not good for unit testing so we have to abstract it out in the final solution.
var file = HttpContext.Current.Request.Files[0];
var result = new HttpResponseMessage(HttpStatusCode.OK);
using (IProductsChannel channel = ChannelFactory.CreateChannel())
{
channel.SaveFile(file.InputStream);
}
return new HttpResponseMessage(HttpStatusCode.Created);
}
long time ASP.Net interface developer being asked to learn WCF, looking for some education on more architecture related fronts - as its not my strong suit but I'm having to deal.
In our current ASMX world we adopted a model of creating ServiceManager static classes for our interaction with web services. We're starting to migrate to WCF, attempting to follow the same model. At first I was dealing with performance problems, but I've tweaked a bit and we're running smoothly now, but I'm questioning my tactics. Here's a simplified version (removed error handling, caching, object manipulation, etc.) of what we're doing:
public static class ContentManager
{
private static StoryManagerClient _clientProxy = null;
const string _contentServiceResourceCode = "StorySvc";
// FOR CACHING
const int _getStoriesTTL = 300;
private static Dictionary<string, GetStoriesCacheItem> _getStoriesCache = new Dictionary<string, GetStoriesCacheItem>();
private static ReaderWriterLockSlim _cacheLockStories = new ReaderWriterLockSlim();
public static Story[] GetStories(string categoryGuid)
{
// OMITTED - if category is cached and not expired, return from cache
// get endpoint address from FinderClient (ResourceManagement SVC)
UrlResource ur = FinderClient.GetUrlResource(_contentServiceResourceCode);
// Get proxy
StoryManagerClient svc = GetStoryServiceClient(ur.Url);
// create request params
GetStoriesRequest request = new GetStoriesRequest{}; // SIMPLIFIED
Manifest manifest = new Manifest{}; // SIMPLIFIED
// execute GetStories at WCF service
try
{
GetStoriesResponse response = svc.GetStories(manifest, request);
}
catch (Exception)
{
if (svc.State == CommunicationState.Faulted)
{
svc.Abort();
}
throw;
}
// OMITTED - do stuff with response, cache if needed
// return....
}
internal static StoryManagerClient GetStoryServiceClient(string endpointAddress)
{
if (_clientProxy == null)
_clientProxy = new StoryManagerClient(GetServiceBinding(_contentServiceResourceCode), new EndpointAddress(endpointAddress));
return _clientProxy;
}
public static Binding GetServiceBinding(string bindingSettingName)
{
// uses Finder service to load a binding object - our alternative to definition in web.config
}
public static void PreloadContentServiceClient()
{
// get finder location
UrlResource ur = FinderClient.GetUrlResource(_contentServiceResourceCode);
// preload proxy
GetStoryServiceClient(ur.Url);
}
}
We're running smoothly now with round-trip calls completing in the 100ms range. Creating the PreloadContentServiceClient() method and adding to our global.asax got that "first call" performance down to that same level. And you might want to know we're using the DataContractSerializer, and the "Add Service Reference" method.
I've done a lot of reading on static classes, singletons, shared data contract assemblies, how to use the ChannelFactory pattern and a whole bunch of other things that I could do to our usage model...admittedly, some of its gone over my head. And, like I said, we seem to be running smoothly. I know I'm not seeing the big picture, though. Can someone tell me what I've ended up here with regards to channel pooling, proxy failures, etc. and why I should head down the ChannelFactory path? My gut says to just do it, but my head can't comprehend why...
Thanks!
ChannelFactory is typically used when you aren't using Add Service Reference - you have the contract via a shared assembly not generated via a WSDL. Add Service Reference uses ClientBase which is essentially creating the WCF channel for you behind the scenes.
When you are dealing with REST-ful services, WebChannelFactory provides a service-client like interface based off the shared assembly contract. You can't use Add Service Reference if your service only supports a REST-ful endpoint binding.
The only difference to you is preference - do you need full access the channel for custom behaviors, bindings, etc. or does Add Service Reference + SOAP supply you with enough of an interface for your needs.
Actually, this looks like the download feature, allowing a user to determine the local path where the file should be stored.
The whole thing is: the background program will generate a data file in the server, after that, I want to pass the data file from server to client.
I used FileStreamResult and FileContentResult, but it doesn't work.
A *.csv file was generated, then the file needs to transfer to the client. in controller , the code is very simple , like return new FilePathResult(filePath,"text/csv"); and I set the break point , the code execute without any exception , but I didn't see any web diaglog letting the user to select the path to save the csv file.
Try using return File()
public FileResult GetFile()
{
byte[] test = { 0 };
return File(test, "text/csv","TempFile.csv");
}
and calling it with an actionlink.
#Html.ActionLink("Download File","GetFile","Home")
Thank you guys, I changed the designe--place the csv file under the web root directory, (e.g. \File\Date\testing.csv) in the Controller method will return a json which point to the csv location (e.g. /File/Date/testing.csv) , the js should get the url and redirect to the /File/Date/testing.csv .
public FastJsonResult Download()
{
//generate the csv file under root path
//return the url point to the file
return JsonView(path);
}