I have some ASP.net code that I am working with and I am running into a silent failing.
using System;
using System.IO;
using System.Web;
using System.Web.Services;
public partial class _Default : System.Web.UI.Page
{
[WebMethod(EnableSession=false)]
public static string ProcessData()
{
string chartFile = HttpContext.Current.Server.MapPath("~/Example/chartData.json");
//StreamWriter chartData = new StreamWriter(chartFile);
StreamWriter chartData = new StreamWriter("C:\\_Sites\\Example\\chartData.json");
chartData.WriteLine("Test This Out");
chartData.Flush();
chartData.Close(); // Close the instance of StreamWriter.
chartData.Dispose(); // Dispose from memory.
return chartFile;
}
}
The code I have commented out fails silently. I know the path is being correctly placed into chartFile. I think StreamWriter is not super happy about the var possibly due to the : and \ not being escaped in the string.
I cannot provide a direct path due to the nature of the deployment server. Any suggestions on how to get StreamWriter to play nice with the string contained in chartFile?
Thanks in advance.
Related
I am learning how to use the .NET framework. I am working with ASP .NET core. I have never had or hit my azure webhosting quota until recently I keep hitting quota by making very few request and this started ever since I installed dotnetbrowser library. its the best library for my project because it makes getting data easier. however, I will appreciate if someone can tell me how to get same data without using a browser control like web browser or dotnetbrowser. the data I needed go through multiple server and client communications before the needed value is provided. So my question is how can achieve the same thing without using browser control?
finally, my code might be buggy given that I am not too familiar with threads and task. I might be using too much memory. so below is my code
using DotNetBrowser;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Web.Http;
namespace AjaxRequest.Controllers
{
public class ValuesController : ApiController
{
private static ManualResetEvent waitEvent;
private static List<string> ajaxUrls = new List<string>();
static string str = "";
public static Browser browser;
public ValuesController()
{
waitEvent = new ManualResetEvent(false);
browser = BrowserFactory.Create();
browser.Context.NetworkService.ResourceHandler = new AjaxResourceHandler();
browser.Context.NetworkService.NetworkDelegate = new AjaxNetworkDelegate();
}
// GET api/values
public string Get(int id, string title)
{
string Title = title.Replace(" ", "-");
browser.LoadURL(string.Format("https://ba.com/foo/{0}-{1}/something.html", Title, id));
waitEvent.WaitOne();
browser.Dispose();
string Json = Regex.Replace(str, #"\\","");
return Json.Replace("\\\"", "\"");
}
public class AjaxResourceHandler : ResourceHandler
{
//HomeController hc;
public bool CanLoadResource(ResourceParams parameters)
{
if (parameters.ResourceType == ResourceType.XHR && parameters.URL.Contains("https://something.com/ajax/blahblah"))
{
ajaxUrls.Add(parameters.URL);
}
return true;
}
}
public class AjaxNetworkDelegate : DefaultNetworkDelegate
{
//HomeController hc;
public override void OnDataReceived(DataReceivedParams parameters)
{
if (ajaxUrls.Contains(parameters.Url))
{
PrintResponseData(parameters.Data);
}
}
public void PrintResponseData(byte[] data)
{
str = Encoding.UTF8.GetString(data);
ajaxUrls.Clear();
browser.Stop();
browser.dispose();
waitEvent.Set();
}
public void error(string info)
{
str = info;
waitEvent.Set();
}
}
}
}
is it possible that I am doing it wrong? if that's the case how can it be improved to conserve memory or data?
UPDATE: am using azure free hosting services
DotNetBrowser is a Chromium wrapper - I am not entirely sure why you would need it in a web app, but that said, it is likely it is the culprit. Once you remove it, you can use HttpClient to perform the right requests with no memory overhead.
Profiling-wise, your best bet is to start with Application Insights - it's enabled by default in ASP.NET Core projects. It will allow resource tracking across app components.
It seems like you have more than one running Browser instance.
I can suggest to check that Browser instance is disposed correctly. If not, you can try to dispose it in the Dispose method of the controller.
I don't think I understand dictionaries at all. I understand how to set them up and access them from the same script/object but when it comes to accessing it from a different object/script that's not parent/child I have no idea what I'm doing. This is my script for the gameobject holding the dictionaries:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class HeroStats : MonoBehaviour {
//Dictionary Structure <Key, value>
Dictionary<string,int> HeroStat = new Dictionary<string,int>();
Dictionary<string,string>HeroName = new Dictionary<string,string>();
Dictionary<string,string>StatDef = new Dictionary<string,string>();
//Initialization:
void Start(){
//===NAME==========================
HeroName.Add("Name","Insert Name");
//===STATS=========================
HeroStat.Add("Constitution", 3);
HeroStat.Add("Dexterity", 3);
HeroStat.Add("Intelligence", 3);
HeroStat.Add("Strength", 3);
HeroStat.Add("Wisdom", 3);
//===STAT DEFINITION==============
StatDef.Add("Constitution", "Your Overall Healthiness");
print (HeroName["Name"]);
print (HeroStat["Strength"]);
}
}
and this is the script I'm trying to use to access the dictionary:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System;
public class heroName : MonoBehaviour {
public HeroStats heroStats;
public Text text;
public string lookUp;
public string what;
// Use this for initialization
void Start(){
heroStats = FindObjectOfType<HeroStats>();
what = heroStats.GetType().GetField("Name").GetValue(this).ToString();
text = gameObject.GetComponent<Text>();
lookUp = this.gameObject.name;
}
void Update(){
}
}
I just have no idea what I'm doing at this point or know what to google. Every video/tutorial I've seen always shows them accessing the dictionary from the same script/object.
A Dictionary is just a way of storing data. Just like an int, or string. You need to have access to your Dictionary in your external script.
You would need to make your Dictionary public in HeroStats, and then in heroName you would simply have
heroStats.HeroStat["Constitution"]
I am new to ASP.NET C#. I try to follow this tutorial page to make a function using globally, but no luck.
https://web.archive.org/web/20210612122420/http://aspnet.4guysfromrolla.com/articles/122403-1.aspx
What I try to do is use a function global any where in my code. I have a function called "FormatDateNoTime". I have create a Class file under App_Code folder. But when I call that function in one of my code behind page (example Page1.aspx.cs), it gives me the error:
Error: The name 'MyClass' does not exist in the current context
MyClass.cs file under the App_Code folder.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for Class1
/// </summary>
public class MyClass
{
//
// TODO: Add constructor logic here
//
public static string FormatDateNoTime(string input) {
string thedate;
DateTime strDate = DateTime.Parse(input);
thedate = strDate.ToString("MM/dd/yyyy");
return thedate;
}
}
The code in my Page1.aspx.cs calling the FormateNoTime function
TextBox BeginDate = (TextBox)FormView1.FindControl("BeginDate");
BeginDate.Text = MyClass.FormatDateNoTime(objDs.Tables[0].Rows[0]["BeginDate"].ToString());
It seems like other pages don't recognize this class.function().
Please help. Thanks in advance.
Right click the source file in App_Code and set its "Build Action" property to "Compile". Click on the .cs file in App_Code and hit F4 key (or right click -> Properties), and you should see an option for "Build Action"
That way, it will build the code in your App_Code folder, and you should be able to access your static method in your class. If the above doesn't help, remove the class from the app_code and drop it in the root folder and try compiling it.
The code you have doesn't compile. I'm pretty sure Visual Studio is throwing an error when you try to run it; pay attention to what it's saying.
Also, change the following:
public static string FormatDateNoTime(object sender, EventArgs e)
{
string thedate;
DateTime strDate = DateTime.Parse(input);
thedate = strDate.ToString("MM/dd/yyyy");
return thedate;
}
To
public static string FormatDateNoTime(String input)
{
string thedate;
DateTime strDate = DateTime.Parse(input);
thedate = strDate.ToString("MM/dd/yyyy");
return thedate;
}
I'd go further and validate that the input is parseable into a DateTime, but that's for you to explore.
I am newbie in .NET. I am using Threads in my project. please check my code below -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication6
{
class Program
{
private void Amadeus(object str)
{
Console.WriteLine(str.ToString());
}
static void Main(string[] args)
{
Program objClass = new Program();
//One way to call Amadeus Method...
Thread objThread = new Thread(objClass.Amadeus);
objThread.Start("Amadeus without ParameterizedThreadStart");
//Other way to call Amadeus Method...
ParameterizedThreadStart objParamThread = new ParameterizedThreadStart(objClass.Amadeus);
Thread ObjThreadParam = new Thread(objParamThread);
ObjThreadParam.Start("Amadeus with ParameterizedThreadStart");
Console.ReadLine();
}
}
}
Can you please tell me what is the difference between above both way as both are doing same work.
Thanks in advance.
Both are same. Read the MSDN documentation.
Visual Basic and C# users can omit the ThreadStart or
ParameterizedThreadStart delegate constructor when creating a thread.
In Visual Basic, use the AddressOf operator when passing your method
to the Thread constructor; for example, Dim t As New Thread(AddressOf
ThreadProc). In C#, simply specify the name of the thread procedure.
The compiler selects the correct delegate constructor.
Yes, both are doing the same thing.
You can create a thread by passing in a function with a ThreadStart (void ThreadStart()) or ParameterisedThreadStart (void ParameterisedThreadStart(Object x)) signature.
The compiler is working out which constructor to call from the type of parameter you are passing into the constructor.
I am new in asp.net. i want to know about the generic handlers in asp.net
and how and where it use?
Could you help me?
Generic handlers are the .NET components that implement the System.Web.IHttpHandler interface. Any class that implements the IHttpHandler interface can act as a target for the incoming HTTP requests. Page is also generic handler. In general generic handlers have an extension of ASHX.
You can find example here
Handlers are used when you want to avoid the overhead of a regular asp.net page. Practical examples include image processing or handling AJAX requests.
See Using HTTP Modules and Handlers to Create Pluggable ASP.NET Components.
Some ASP.NET files are dynamically generated. They are generated with C# code or disk resources. These files do not require web forms. Instead, an ASHX generic handler is ideal. It can dynamically return an image from a query string, write XML, or any other data.
Ashx File is nothing but just like an aspx page.They're equivalent to custom handlers written in C Sharp or Visual Basic.NET in that they contain classes that fully implement IHttpHandler. They're convenient in the same way ASPX files are convenient. You simply surf to them and they're compiled automatically.
When WebForms(aspx)to be used
Simple Html Pages
Asp.net Custom Controls
Simple Dyanamic Pages
When Handlers(ashx) to be used
Binary files
Dynamic Image Views
Performance critical web pages
xml files
Minimal Web Pages
ASHX Generic Handler is a concept to return dynamic content. It is used to return ajax calls, image from a query string, write XML, or any other data.
I have used it to return MP4 file from query string. Please find the following code.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace ESPB.CRM.Web.UI.VideoUploading
{
public class FileCS : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
int id = int.Parse(context.Request.QueryString["id"]);
byte[] bytes;
string contentType;
string strConnString = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
string name;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Name, Data, ContentType from VideoUpload where Id=#Id";
cmd.Parameters.AddWithValue("#Id", id);
cmd.Connection = con;
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
sdr.Read();
bytes = (byte[])sdr["Data"];
contentType = sdr["ContentType"].ToString();
name = sdr["Name"].ToString();
con.Close();
}
}
context.Response.Clear();
context.Response.Buffer = true;
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name);
context.Response.ContentType = contentType;
context.Response.BinaryWrite(bytes);
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
Here I have created FileCS.ashx file.
Where I inherit IHttpHandler interface. and wrote ProcessRequest(HttpContext context) function, which will run default while call the file. And context.Request.QueryString[] will get the parameter. Here I am passing id as parameter. IsReusable() function can be use for good performance.