I have a code that gets a line of text from raw.githubusercontent.com
WebRequest webRequest = WebRequest.Create(getargs[1]);
using (WebResponse response = webRequest.GetResponse())
using (Stream content = response.GetResponseStream())
using (StreamReader reader = new StreamReader(content))
{
string strCntent = reader.ReadToEnd();
string[] plgnCntn;
plgnCntn = strCntent.Split('(', ')', ':', ',');
if (plgnCntn[0] != "validplgn")
{
newln("Plgn couldn't be installed. Not validated.");
}
else
{
string dmy = plgnCntn[1];
dummy = dmy.Split('-');
install_id = Convert.ToInt32(dummy[1]);
dummy = plgnCntn[2].Split('-');
install_plgn_nme = dummy[1];
dummy = plgnCntn[3].Split('-');
install_cmmd = dummy[1];
plgnbyID.Add(install_id, install_plgn_nme);
plgncmds.Add(install_plgn_nme, install_cmmd);
inverseplgncmds.Add(install_cmmd, install_plgn_nme);
plgnparse.Add(install_plgn_nme, plgnCntn[4]);
}
}
And all seems fine, the program gets the data, i'm testing with
"validplgn(id-0001,plgn_nme-plgn,cmmd-plgninfo):{ln-This plugin has been downloaded from the creator's GitHub;hlp-hlp}"
When it gets the data, it splits it in
"validplgn", "id-0001", "plgn_nme-plgn", "cmmd-plgninfo", "{ln-This plugin has been downloaded from the creator's GitHub;hlp-hlp}"
It is supposed to test if [0] == "validplgn", saves all the data in dictionaries. When all of this data is saved, the program continues running and checking for commands in a loop. Basically detecting what I put on the textbox, checking IF statements and giving answers, when the content in the textbox doesn't match with any command, it writes:
"Command wasn't recognized. Please type hlp".
The problem comes, i think, in this code:
else if (plgncmds.ContainsValue(inp))
{
string plgnnme;
string toparse;
string[] splitparse = {};
int arglength;
inverseplgncmds.TryGetValue(inp, out plgnnme);
plgnparse.TryGetValue(plgnnme, out toparse);
splitparse = toparse.Split(';');
arglength = splitparse.Length;
foreach (string statement in splitparse)
{
string[] dmmy = statement.Split('-');
...
At the final of the checker loop, tests if the unknown command to the client matches with any downloaded command in:
else if (plgncmds.ContainsValue(inp))
So, when i input "plgninfo", that is the text that executes this code:
{ln-This plugin has been downloaded from the creator's GitHub;hlp-hlp}
It was declared before, when "cmmd-plgninfo", was splitted and saved the plgninfo part. Now this code gets the key on the dictionary using the command (plgninfo), but it doesn't display anything. And thats the problem. It should print "This plugin has been downloaded from the creator's GitHub" and show program help for the command "hlp". but nothing, I have ReSharper 9 in VS 2013 and any issue is thrown, just nothing happens.
I hope theres a way to fix.
Thanks.
Related
I got a problem for few days, i'm trying to access to firestore in xamarin forms. To do so I am using the environment variable GOOGLE_APPLICATION_CREDENTIALS as you can see in the code below. The environment variable stting is successfull as you can see I did some test and everything is ok about this part. But when I call the method FirestoreClient.Create() I got this exception:
System.TypeLoadException: Could not resolve type with token 0100003b (from typeref, class/assembly System.Runtime.Loader.AssemblyLoadContext, System.Runtime.Loader, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
I'm using Google.Cloud.Firestore and Google.Cloud.Firestore.V1Beta1 both on version 1.0.0-beta02
Here is the code :
public void InitializeFirestore()
{
var assembly = Assembly.GetExecutingAssembly();
Stream steam = assembly.GetManifestResourceStream("AIGallery.AppMobile.CarouselReservation.FirestoreDir.Book-A-Room-Bot-13b38d0674e5.json");
string text = "";
//I create the json files to get the path, because can't get the path from an embedded ressource
string json = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "creditential.json");
//Here I just copy past the json file from google inside creditential.json
using (var reader = new StreamReader(steam))
{
text = reader.ReadToEnd();
}
using (var w = new StreamWriter(json))
{
w.WriteLine(text);
w.Flush();
}
//Here was just to be sure everything was wirtten inside json, it works
text = "";
using (var reader = new System.IO.StreamReader(json))
{
text = reader.ReadToEnd();
}
//Set the variable
System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", json);
//See the content, worked well
var t = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS");
//Here on Create, it crash
client = FirestoreClient.Create();
I'm trying to find out what is wrong for few days, can't figure it out. Thanks in advance
I have the following code which tries to read data from a text file (so users can modify easily) and auto format a paragraph based on a the words in the text document plus variables in the form. I have the file "body" going into a field. my body text file has the following data in it
"contents: " + contents
I was hoping based on that to get
contents: Item 1, 2, etc.
based on my input. I only get exactly whats in the text doc despite putting "". What am I doing wrong? I was hoping to get variables in addition to my text.
string readSettings(string name)
{
string path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/Yuneec_Repair_Inv";
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader(path + "/" + name + ".txt"))
{
string data = sr.ReadToEnd();
return data;
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The settings file for " + name + " could not be read:");
Console.WriteLine(e.Message);
string content = "error";
return content;
}
}
private void Form1_Load(object sender, EventArgs e)
{
createSettings("Email");
createSettings("Subject");
createSettings("Body");
yuneecEmail = readSettings("Email");
subject = readSettings("Subject");
body = readSettings("Body");
}
private void button2_Click(object sender, EventArgs e)
{
bodyTextBox.Text = body;
}
If you want to provide the ability for your users to customize certain parts of the text you should use some "indicator" that you know before hand, that can be searched and parsed out, something like everything in between # and # is something you will read as a string.
Hello #Mr Douglas#,
Today is #DayOfTheWeek#.....
At that point your user can replace whatever they need in between the # and # symbols and you read that (for example using Regular Expressions) and use that as your "variable" text.
Let me know if this is what you are after and I can provide some C# code as an example.
Ok, this is the example code for that:
StreamReader sr = new StreamReader(#"C:\temp\settings.txt");
var set = sr.ReadToEnd();
var settings = new Regex(#"(?<=\[)(.*?)(?=\])").Matches(set);
foreach (var setting in settings)
{
Console.WriteLine("Parameter read from settings file is " + setting);
}
Console.WriteLine("Press any key to finish program...");
Console.ReadKey();
And this is the source of the text file:
Hello [MrReceiver],
This is [User] from [Company] something else, not very versatile using this as an example :)
[Signature]
Hope this helps!
When you read text from a file as a string, you get a string of text, nothing more.
There's no part of the system which assumes it's C#, parses, compiles and executes it in the current scope, casts the result to text and gives you the result of that.
That would be mostly not what people want, and would be a big security risk - the last thing you want is to execute arbitrary code from outside your program with no checks.
If you need a templating engine, you need to build one - e.g. read in the string, process the string looking for keywords, e.g. %content%, then add the data in where they are - or find a template processing library and integrate it.
I'm encountering some odd errors in Visual Studio and can't find head or tail. I'm coding some backend in C# which contacts a third party API to retrieve data. The code in question, a single class, is part of a larger solution, but must be the problem as the errors encountered does not occur when not using this class.
Computer setup:
Visual Studio 2013, update 4
Windows 10, Preview Build 10041
Errors encountered
Yesterday the application started behaving weird when debugging it.
The first error I don't remember exactly, but it was something along the lines of "bad" or "corrupted memory".
Without altering the program, I could also encounter a FatalExecutionEngineError exception, which would be thrown immediately after trying to run the program (It didn't make it to the first breakpoint, which was on the first line in the Main entry of the program. Weird!
EDIT: Looks like this:
Managed Debugging Assistant 'FatalExecutionEngineError' has detected a problem in 'PathRedacted\whatsfordinner\whatsfordinner\bin\Debug\whatsfordinner.vshost.exe'.
Additional information: The runtime has encountered a fatal error. The address of the error was at 0x613e4379, on thread 0x11ac. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.
In the end I rebooted my computer since it was all very strange. Problem solved until today.
Now I can't seem to run the program at all; Upon running the program, vshost32.exe just crashes. I don't get any error messages or anything to hint at where the issue is.
Troubleshooting steps
Rebooted my computer - No change, vshost32.exe crashes upon execution
Outcommented the two lines where the class in question was used - Program runs fine.
Tried starting the program as "Release" rather than "Debug". - Program seems to run fine, although I can't test it to the end. (The class is not entirely done yet, and I don't want to spam the API in question)
Tried running the program on another computer running Windows 7 and Visual Studio 2012. - Program seemed to run fine.
At this point I'm pretty lost. I have little idea as to where the issue might be. The source code unfortunately consists of nearly 200 lines, but as I have no clue, I am posting it all.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Specialized;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
namespace whatsfordinner {
public class eTilbudRetriever {
//Web method names
readonly String Get = "GET";
readonly String Post = "POST";
readonly String Update = "UPDATE";
readonly String Delete = "DELETE";
//Parameter identifiers
readonly String ParamApiKey = "api_key";
readonly String ParamLatitude = "r_lat";
readonly String ParamLongitude = "r_lng";
readonly String ParamRadius = "r_radius";
readonly String ParamLimit = "limit";
readonly String ParamOffset = "offset";
//Parameter values
String Latitude = "57.051188"; //Aalborg coordinates
String Longitude = "9.922371";
String Radius = "800000"; //Radius in meters (800km)
String Limit = "48"; // Results per query
//Custom header identifiers
readonly String HeaderXToken = "X-Token";
readonly String HeaderXSignature = "X-Signature";
//Custom header values
readonly String ContentType = "application/json";
//Web Addresses
readonly String HostAddress = "https://api.etilbudsavis.dk/v2/";
readonly String Sessions = "sessions";
readonly String Stores = "stores";
readonly String Offers = "offers";
readonly String Dealers = "dealers";
//Keys
readonly String ApiKey = "<Redacted>";
readonly String ApiSecret = "<Redacted>";
String XToken; //Same as a Session Token in documentation
String XSignature; //Same as a Session Signature in documentation
public eTilbudRetriever() {
//Create a body consisting of the API key
List<KeyValuePair<String, String>> body = new List<KeyValuePair<String, String>>();
body.Add(new KeyValuePair<String, String>(ParamApiKey, ApiKey));
//Send request to create a new session
String response = SendWebRequest(Post, Sessions, body);
//Get the Session Token from the response
dynamic json = JObject.Parse(response);
XToken = json.token;
//Save the Session Signature as well (SHA256 version of API Secret combined with Session Token)
XSignature = ConvertToSha256(ApiSecret + XToken);
}
public void GetDealersList() {
GetList(Dealers);
}
public void GetStoresList() {
GetList(Stores);
}
public void GetOffersList() {
GetList(Offers);
}
private void GetList(string target) {
List<String> resultSet = new List<String>();
String result;
int offset = 0;
//Add desired parameters as headers for the eTilbudsavisen API
List<KeyValuePair<String, String>> query = new List<KeyValuePair<String, String>>();
query.Add(new KeyValuePair<String, String>(ParamLatitude, Latitude));
query.Add(new KeyValuePair<String, String>(ParamLongitude, Longitude));
query.Add(new KeyValuePair<String, String>(ParamRadius, Radius));
query.Add(new KeyValuePair<String, String>(ParamLimit, Limit));
query.Add(new KeyValuePair<String, String>(ParamOffset, offset.ToString()));
//Retrieve a result through the request
result = SendWebRequest(Get, target, query);
/*
* If result is valid, add it to the set of valid results.
* Keep sending requests and increase the offset to avoid duplicated results
* Stop when returned results are no longer valid
*/
while (!String.IsNullOrEmpty(result)) {
resultSet.Add(result);
offset += Int32.Parse(Limit);
query[query.Count-1] = new KeyValuePair<String, String>(ParamOffset, offset.ToString());
result = SendWebRequest(Get, target, query);
}
}
private String SendWebRequest(String method, String extension, List<KeyValuePair<String, String>> arguments) {
try {
String finalAddress = HostAddress + extension;
//Add query to Address (if applicable)
if (method.Equals(Get)) {
finalAddress += '?';
finalAddress += arguments[0].Key + '=' + arguments[0].Value;
for (int i = 1; i < arguments.Count; i++) {
finalAddress += '&' + arguments[i].Key + '=' + arguments[i].Value;
}
}
//Create request and set mandatory header properties
var request = (HttpWebRequest)WebRequest.Create(finalAddress);
request.Method = method;
request.ContentType = ContentType;
request.Accept = ContentType;
//If a Session Token and Signature are available (= After session create), add as headers
if (!String.IsNullOrEmpty(XToken)) {
request.Headers.Add(HeaderXToken, XToken);
request.Headers.Add(HeaderXSignature, XSignature);
}
//Create JSON string containing the desired body arguments (if applicable)
if (method.Equals(Post)) {
//Write body to API
using (var writer = new StreamWriter(request.GetRequestStream())) {
writer.Write(MakeJsonBody(arguments));
}
}
//get response as a JSON object in string format
var response = (HttpWebResponse)request.GetResponse();
return new StreamReader(response.GetResponseStream()).ReadToEnd();
} catch (UriFormatException e) {
Console.WriteLine(e.ToString());
return null;
} catch (WebException e) {
Console.WriteLine(e.ToString());
return null;
}
}
private String ConvertToSha256(String text) {
byte[] bytes = Encoding.UTF8.GetBytes(text);
SHA256Managed hashstring = new SHA256Managed();
byte[] hash = hashstring.ComputeHash(bytes);
string hashString = string.Empty;
foreach (byte x in hash) {
hashString += String.Format("{0:x2}", x);
}
return hashString;
}
private String MakeJsonBody(List<KeyValuePair<String, String>> arguments) {
String json = "{";
foreach (KeyValuePair<String, String> kv in arguments) {
json += "\"" + kv.Key + "\": \"" + kv.Value + "\"";
if (arguments.IndexOf(kv) != arguments.Count() - 1) {
json += ", ";
}
}
json += "}";
return json;
}
}
}
In Main, this is what is executed in relation to the class. The program runs fine when removing these lines from the solution.
eTilbudRetriever retriever = new eTilbudRetriever();
retriever.GetDealersList();
Windows 10, Preview Build 10041
That's the only cue to the possible reason why your program is crashing like this. There are no other ones, your code doesn't do anything dangerous and Newtonsoft.Json has been slammed every possible way by millions of programs. You are using beta versions of both the .NET Framework (v4.6) and the operating system. Thanks on behalf of all Microsoft customers to help debug this new software, your problem is not one that we'll have to troubleshoot. Hopefully, FEEE crashes are exceedingly nasty and hard to debug.
What you are supposed to do is submit a minidump of the crashed process to Microsoft so they can fix the underlying bug. Whatever it might be, there are no cues in your question. Maybe it is the complete rewrite of the x64 jitter (project code name RyuJit). The odds that it has no bugs right now are very slim and such a bug can certainly crash your program like this. That's just a wild guess though.
Microsoft makes these previews available at no cost. Their underlying intention is to get the bugs out before the product ships. Should happen somewhere around the summer. Only real way they can have some confidence that their Support phone lines are not going to get overloaded once they ship the product. The beta updates come fast and furious, there have been 6 CTP versions of .NET 4.6. Quite unprecedented, there usually are no more than 3. At least part of it is the beta for VS2015, lots and lots of new stuff in that release. Which you are not using, that doesn't help either.
Your role in this is one as an unpaid beta-tester. This tends to be rather incompatible with your other role, a programmer that makes a living writing and debugging code. Your code, not somebody else's. When you can't afford to be bogged-down like this then the only sensible thing to do is to unsubscribe from that beta program. Restore your machine to a known-good version of the framework and the operating system. Right now that's .NET 4.5.2 and Windows 8.1
I have a program that sends emails utilizing templates via a web service. To test the templates, I made a simple program that reads the templates, fills it up with dummy value and send it. The problem is that the templates have different 'fill in' variable names. So what I want to do is open the template, make a list of the variables and then fill them with dummy text.
Right no I have something like:
StreamReader SR = new StreamReader(myPath);
.... //Email code here
Msg.Body = SR.ReadToEnd();
SR.Close();
Msg.Body = Msg.Body.Replace(%myFillInVariable%, "Test String");
....
So I'm thinking, opening the template, search for values in between "%" and put them in an ArrayList, then do the Msg.Body = SR.ReadToEnd(); part. Loop the ArrayList and do the Replace part using the value of the Array.
What I can't find is how to read the value between the % tags. Any suggestions on what method to use will be greatly appreciated.
Thanks,
MORE DETAILS:
Sorry if I wasn't clear. I'm passing the name of the TEMPLATE to the script from a drop down. I might have a few dozen Templates and they all have different %VariableToBeReplace%. So that's is why I want to read the Template with the StreamReader, find all the %value names%, put them into an array AND THEN fill them up - which I already know how to do. It's getting the the name of what I need to replace in code which I don't know what to do.
I am not sure on your question either but here is a sample of how to do the replacement.
You can run and play with this example in LinqPad.
Copy this content into a file and change the path to what you want. Content:
Hello %FirstName% %LastName%,
We would like to welcome you and your family to our program at the low cost of %currentprice%. We are glad to offer you this %Service%
Thanks,
Some Person
Code:
var content = string.Empty;
using(var streamReader = new StreamReader(#"C:\EmailTemplate.txt"))
{
content = streamReader.ReadToEnd();
}
var matches = Regex.Matches(content, #"%(.*?)%", RegexOptions.ExplicitCapture);
var extractedReplacementVariables = new List<string>(matches.Count);
foreach(Match match in matches)
{
extractedReplacementVariables.Add(match.Value);
}
extractedReplacementVariables.Dump("Extracted KeyReplacements");
//Do your code here to populate these, this part is just to show it still works
//Modify to meet your needs
var replacementsWithValues = new Dictionary<string, string>(extractedReplacementVariables.Count);
for(var i = 0; i < extractedReplacementVariables.Count; i++)
{
replacementsWithValues.Add(extractedReplacementVariables[i], "TestValue" + i);
}
content.Dump("Template before Variable Replacement");
foreach(var key in replacementsWithValues.Keys)
{
content = content.Replace(key, replacementsWithValues[key]);
}
content.Dump("Template After Variable Replacement");
Result from LinqPad:
I am not really sure that I understood your question but, you can try to put on the first line of the template your 'fill in variable'.
Something like:
StreamReader SR = new StreamReader(myPath);
String fill_in_var=SR.ReadLine();
String line;
while((line = SR.ReadLine()) != null)
{
Msg.Body+=line;
}
SR.Close();
Msg.Body = Msg.Body.Replace(fill_in_var, "Test String");
Right now I'm exporting some text to a 2010 Word document. I have everything working except new lines. What is the character for a new line? I've tried "\r\n", " ^p ", and "\n", Nothing is working.
I'm using the "FindAndReplace" method to replace strings with strings.
The purpose for the newlines is some required formatting. My coworkers have a 6 line box that the text belongs in. On line 1 in that box I have "" and I'm replacing it with information from a database. If the information exceeds one line, they don't want the box to become 7 lines. So I've figured out how to calculate how many lines the text requires and I re-sized the box to 1 line. So for example if my string requires 2 lines, I want to put 4 blank lines after that.
If this is not possible, I was thinking of putting in that box:
<line1>
<line2>
<line3> and so on...
Then just replace each line individually. Any other thoughts?
Thanks in advance.
You can find each instance of new line with ^13 or (the equivalent) ^l and replace them with as many newlines as you require by concatenating ^13. The "Suchen und Ersetzen" dialog below is German for "Search and Replace". Tested in Word 2010.
Example:
This should work as is using COM automation with c#. An example link if you need one.
Here's proof of concept code:
namespace StackWord
{
using StackWord = Microsoft.Office.Interop.Word;
internal class Program
{
private static void Main(string[] args)
{
var myWord = new StackWord.Application { Visible = true };
var myDoc = myWord.Documents.Add();
var myParagraph = myDoc.Paragraphs.Add();
myParagraph.Range.Text =
"Example test one\rExample two\rExample three\r";
foreach (StackWord.Range range in myWord.ActiveDocument.StoryRanges)
{
range.Find.Text = "\r";
range.Find.Replacement.Text = "\r\r\r\r";
range.Find.Wrap = StackWord.WdFindWrap.wdFindContinue;
object replaceAll = StackWord.WdReplace.wdReplaceAll;
if (range.Find.Execute(Replace: ref replaceAll))
{
Console.WriteLine("Found and replaced.");
}
}
Console.WriteLine("Press any key to close...");
Console.ReadKey();
myWord.Quit();
}
}
}
You can always try using:
Environment.NewLine
You save your file word to word 97 - 2003(*.doc), your "FindAndReplace" method will working :D