....
case "DOWNLOAD":
if (File.Exists(commandContent)) {
MessageBox.Show(commandContent);
result = System.Convert.ToBase64String(File.ReadAllBytes(commandContent)); //ERROR
result = HttpUtility.UrlEncode(result);
}
break;
And Unhandled Error exception says "illegal characters" in path. The MessageBox shows a correct path
C:\Users\Me\Myfile.exe
I tried to do the following :
commandContent = commandContent.replace(#"\",#"\\");
result = System.Convert.ToBase64String(File.ReadAllBytes(commandContent)); //ERROR
I also tried the following :
commandContent = #""+commandContent+"";
result = System.Convert.ToBase64String(File.ReadAllBytes(commandContent)); //ERROR
but this doesn't work. And the more strange is that it was working correctly as it is, but once I made some modification in the way I'm inserting commandContent into db (using ajax instead of regular form submit), this problem appears ?
EDIT:
I tried to hard code the path using
commandContent = #"C:\Users\Me\file.exe";
That worked correctly. How can I force the variable not to contain any illegal characters?
i'm pretty sure that you have \n or \r or \t or ... at the end or beginning of the string commandContent
can you do a
System.Text.Encoding.UTF8.GetBytes (commandContent)
and check each byte?
maybe the ajax call doesn't make a proper string/path
you can use this to find which one
class Program
{
static void Main(string[] args)
{
var commandContent = "C:\\Users\\Me\\file.exe\n";
var commandContentBytes = System.Text.Encoding.UTF8.GetBytes(commandContent);
var invalidPathChars = System.IO.Path.GetInvalidPathChars().Select(x=>Convert.ToByte(x));
var found = commandContentBytes.Intersect(invalidPathChars);
}
}
Related
I am trying to basically create config files. A text file will hold something like:
Name::Adam
Location::Washington
I am trying to grab the first part as the field name (i.e. Name.Text would update the TextBox) then put the second part to that Text. Just not sure where to go or what the best way to build this is. The code below is incomplete because I can't figure out how to update the textboxes.
Thanks for the help!
private void clickImportConfig_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
{
Stream myStream = null;
string fieldUpdate = string.Empty;
string fieldUpdateTo = string.Empty;
try
{
using (myStream)
{
string[] lines = File.ReadAllLines(#"c:\\config.txt");
foreach (string s in lines)
{
var splitted = Regex.Split(s, "::");
fieldUpdate = splitted[0].ToString();
fieldUpdateTo = splitted[1].ToString();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
I think this is what you're looking for:
private void clickImportConfig_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
{
Stream myStream = null;
string fieldUpdate = string.Empty;
string fieldUpdateTo = string.Empty;
try
{
using (myStream)
{
string[] lines = File.ReadAllLines(#"c:\\config.txt");
foreach (string s in lines)
{
string[] splitted = s.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries);
fieldUpdate = splitted[0].ToString();
fieldUpdateTo = splitted[1].ToString();
// TextBox textBox = (TextBox)this.FindName(fieldUpdate);
// Or
TextBox textBox = this.FindName(fieldUpdate) as TextBox;
// See below for an explanation
if (textBox != null) // FindName returns null if nothing is found with that name
{
textBox.Text = fieldUpdateTo;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
As insane_developer pointed out, you will be better off using the String.Split method (s being the string in this case so written as s.Split()) instead of Regex.Split. It will give you the benefit of removing any empty results from the array. It may also have better performance as Regex is capable of a lot more complicated things, but I haven't tested that so I could be wrong.
You can use the FindName(string name) method to find an element with the specified name. This method returns null if nothing is found and an object if the element is found. This object will need to be cast to the type you are expecting (I.e. TextBox). You can do this in one of the following ways:
TextBox textBox = (TextBox)this.FindName(fieldUpdate);
or
TextBox textBox = this.FindName(fieldUpdate) as TextBox;
The first option will throw an InvalidCastException if FindName returns an object which is not a TextBox. The second option will instead just set the value of textBox to null which will be checked by the if statement and the exception will be avoided. As you are only catching all generic exceptions in this code, an InvalidCastException would show your "Could not read file from disk" message which is not true. So you may want to add an additional catch block to handle any invalid casting.
If you're wondering why you don't just stick to the second option as it solves this problem, then consider this scenario as an example. Lets say in the future you decide for some reason that you want to change all of your TextBox to TextBlock or something else, but forget to come back to change this code, or accidently end up with the name of another type of control in your text file. The second option will set the value of textBox to null and your field(s) won't be updated. But there will be absolutely no errors, leaving you scratching your head and having to debug the problem. The first option would throw an InvalidCastException showing you exactly where the problem is. You could then choose how to handle this problem by either showing another message box or silently writing the error to a log file etc.
You don't need a regular expression, just:
var splitted = s.Split("::", StringSplitOptions.RemoveEmptyEntries);
fieldUpdate = splitted[0];
fieldUpdateTo = splitted[1];
For the rest you have to be more explicit
I have a javascript file and it contains below js script
(function() {
try {
var click = new MouseEvent('click', {bubbles: true, cancelable: true, view: window});
var field = document.querySelector('input[type="email"]');
setTimeout(function() {
field.dispatchEvent(click);
field.focus();
field.value="{0}";
}, 500);
return true;
} catch(err) {
return false;
}
})();
And I read that as string using below code:
var path = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory) + "\\Resources\\script\\myjavascript.js";
var raw = File.ReadAllText(path);
var args = new object[] { "my_username" };
Console.WriteLine(raw, args);
I got error: Exception thrown: 'System.FormatException' in mscorlib.dll
As I try to replace {0} with "my_username".
Can anybody help me?
Thanks.
Answer based on PepitoSh approach is below:
var path = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory) + "\\Resources\\script\\myjavascript.js";
var raw = File.ReadAllText(path);
var script = raw.Replace("{0}", "my_username");
Console.WriteLine(script);
You have to escape all other { and } and leave only "{0}" for the string.format to work.
Also I would add a js object with properties for all variables and use that as an argument or a global object in js scripts, so I only have to replace the values once for multiple scripts.
Since indeed you have to escape the curly braces that are not part of the formatting, I'd recommend another approach in this specific case:
var path = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory) + "\\Resources\\script\\myjavascript.js";
var raw = File.ReadAllText(path);
raw = raw.Replace("{0}", "my_username");
Console.WriteLine(raw);
I'm rendering HTML emails using RazorEngine and want to include helper functions. One of them uses Regex:
// template.cshtml
#using System.Text.RegularExpressions
#functions {
public string FixImageUrlParam(string url, int width, int height)
{
Regex widthParam = new Regex("w=[0-9]*");
Regex heightParam = new Regex("h=[0-9]*");
url = widthParam.Replace(url, $"w={width}");
url = heightParam.Replace(url, $"h={height}");
return url;
}
}
Here's my config/rendering logic.
// renderer.cs
public static string RenderTemplate(string template, string dataModel)
{
TemplateServiceConfiguration config = new TemplateServiceConfiguration();
config.Namespaces.Add("System.Text.RegularExpressions");
Engine.Razor = RazorEngineService.Create(config); ;
Engine.Razor.AddTemplate("template", File.ReadAllText("template.cshtml"));
Engine.Razor.Compile("template", null);
return = Engine.Razor.Run("template", null, JsonConvert.DeserializeObject<ExpandoObject>(File.ReadAllText("data.json")));
}
The problem is that my helper function causes an error when RazorEngine attempts to render. I've isolated the error to the lines that use the Regex namespace.
Errors while compiling a Template.
Please try the following to solve the situation:
* If the problem is about missing references either try to load the missing references manually (in the compiling appdomain!) or
Specify your references manually by providing your own IReferenceResolver implementation.
Currently all references have to be available as files!
* If you get 'class' does not contain a definition for 'member':
try another modelType (for example 'null' or 'typeof(DynamicObject)' to make the model dynamic).
NOTE: You CANNOT use typeof(dynamic)!
Or try to use static instead of anonymous/dynamic types.
More details about the error:
- error: (862, 35) Unexpected character '$'
\t - error: (863, 36) Unexpected character '$'
Temporary files of the compilation can be found in (please delete the folder): C:\\Users\\anstackh\\AppData\\Local\\Temp\\RazorEngine_3gknk4fd.poe
Have you tried to remove string interpolation? Most probably, this is what the error is about.
Try changing the first snippet into this:
// template.cshtml
#using System.Text.RegularExpressions
#functions {
public string FixImageUrlParam(string url, int width, int height)
{
Regex widthParam = new Regex("w=[0-9]*");
Regex heightParam = new Regex("h=[0-9]*");
url = widthParam.Replace(url, "w=" + width.ToString());
url = heightParam.Replace(url, "h=" + height.ToString());
return url;
}
}
I am working with C# for the first time and I am facing a strange issue.
I am building my own class for a plugin, but copied parts of the code from an existing class. Basically it's
var sanInput = Console.ReadLine();
alternativeNames = sanInput.Split(',');
sanList = new List<string>(alternativeNames);
but somehow this doesn't work. The debug console says System.Console.ReadLine returned jogi,philipp string, but sanInput keeps null as its value.
Even stranger is the fact, that the next step works "a bit". string.Split returned {string[2]} string[], so it returns an array of [jogi, philipp], but still sanInput, alternativeNamesand sanList stay as null.
How is it possible, that the second line works if sanInput has no value and how can I fix this problem? When I work with the existing class with the same code everything works as expected.
//EDIT:
Looks like a quite complicated issue. Here is the complete method:
public override void HandleMenuResponse(string response, List<Target> targets)
{
if (response == "r")
{
Console.WriteLine("Which hosts do you want to configure? Enter numbers separated by a comma.");
var hostsInput = Console.ReadLine();
int[] hosts = null;
string[] alternativeNames = null;
List<string> sanList = null;
hosts = hostsInput.Split(',').Select(int.Parse).ToArray();
Console.Write("Generating certificates for ");
foreach (int entry in hosts)
{
Console.Write(targets[entry - 1].Host + ", ");
}
Console.Write("\n \n");
foreach (int entry in hosts)
{
int entry2 = entry - 1;
if (Program.Options.San)
{
Console.WriteLine("Enter all Alternative Names for " + targets[entry2].Host + " seperated by a comma:");
// Copied from http://stackoverflow.com/a/16638000
int BufferSize = 16384;
Stream inputStream = Console.OpenStandardInput(BufferSize);
Console.SetIn(new StreamReader(inputStream, Console.InputEncoding, false, BufferSize));
var sanInput = Console.ReadLine();
alternativeNames = sanInput.Split(',');
sanList = new List<string>(alternativeNames);
targets[entry2].AlternativeNames.AddRange(sanList);
}
Auto(targets[entry - 1]);
}
}
if (response == "e")
{
string[] alternativeNames = null;
List<string> sanList = new List<string>();
if (Program.Options.San)
{
Console.WriteLine("Enter all Alternative Names seperated by a comma:");
// Copied from http://stackoverflow.com/a/16638000
int BufferSize = 16384;
Stream inputStream = Console.OpenStandardInput(BufferSize);
Console.SetIn(new StreamReader(inputStream, Console.InputEncoding, false, BufferSize));
var sanInput = Console.ReadLine();
alternativeNames = sanInput.Split(',');
}
if (alternativeNames != null)
{
sanList = new List<string>(alternativeNames);
}
foreach (var entry in targets)
{
Auto(entry);
}
}
}
I know the code isn't pretty and efficient. All in all it let's the user decide if he wants to use all detected hosts (response e) or only single ones (response r). But the mentioned problem occurs only in the second if-method. If I switch them it's again the latter one. So maybe the reason lies in the main program or in this BufferSize-Stuff? I don't know.
//EDIT 2: I think I found the problem: Somehow the integer BufferSize (shortly before the Console.Read()) is set to 0, so of course without any buffer it can't read the input. So the question remains: Why?
//EDIT 3: Okay, I'm done. It looks like I can't use the same name for the variables although they are in two different if-methods. I just named them sanInput2, alternativeNames2 etc. and now everything works.
try this, all of the variables are having values(you can use var also for all the variables):
var sanInput = Console.ReadLine();
string[] alternativeNames = sanInput.Split(',');
List<string> sanList = new List<string>(alternativeNames);
The problem you mention is, that debugging code in VS do assignements in two steps. First is to execute Console.ReadLine() (therefore you see Console.Readline returned message) and AFTER that is is assigned into sanInput. Same situation is after Split. Function is called, but not assigned yet.
My recommendation: use rather the step over instead of step inside. After time, you get used to this functionality and appreciate it.
I'm trying to make C# program that gets a line on a website and use it.
Unfortunately, I don't know the full line on the site. I only know "steam://joinlobby/730/". Although, what comes after "/730/" is always different.
So i need help getting the full line that comes after it.
What I've got:
public void Main()
{
WebClient web = new WebClient();
// here is the site that i want to download and read text from it.
string result = web.DownloadString("http://steamcommunity.com/id/peppahtank");
if (result.Contains("steam://joinlobby/730/"))
{
//get the part after /730/
}
}
I can tell you that it always ends with "xxxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxxxxx"
so: steam://joinlobby/730/xxxxxxxxx/xxxxxxxx.
What's to prevent you from just splitting the string on '/730/'?
result.Split(#"/730/")[1]
https://msdn.microsoft.com/en-us/library/system.string.split(v=vs.110).aspx
The easiest method for this particular case would be to take the first part, and then just skip that many characters
const string Prefix = #"steam://joinlobby/730/";
//...
if(result.StartsWith(Prefix))
{
var otherPart = result.SubString(Prefix.Length);
// TODO: Process other part
}
Make sure your result is not null and begins with steam://joinlobby/730/
if(string.IsNullOrWhiteSpaces(result) && result.StartsWith("steam://joinlobby/730/"))
{
string rest = result.SubString(("steam://joinlobby/730/").Length);
}