MailKit: ParseException when parsing an email string with email-address in displayname - c#

I am currently working on a microservice that runs on DotNet6 and is using MailKit 3.1.0.
I have the following code snippet:
var from = "John Doe via noreply#company.com <noreply#company.com>";
var mailBoxAddress = MailboxAddress.Parse(from);
The second line of code leads to following Exception:
MimeKit.ParseException: Invalid addr-spec token at offset 0
I did some testing and found out that the following variations of the string work:
var fromAlternative1 = "John Doe via noreplycompany.com <noreply#company.com>"; // missing #
var fromAlternative2 = "JohnDoevianoreply#company.com<noreply#company.com>"; // no empty space
This leads me to the question wether it could exist a configuration that enables parsing the from string, there could be a bug or this behaviour is by design?
As a workaround im parsing the displayname and email-address by myself.

You need to properly quote the name if it contains # symbols or ..
Those are special characters that are required to be quoted by the email specifications.
In other words, the correct string would be:
"John Doe via noreply#company.com" <noreply#company.com>
Or, in C#:
var from = "\"John Doe via noreply#company.com\" <noreply#company.com>";

Related

How to write code in C #, to add new data to the database

Adding triplets to GraphDB
SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri("http://localhost:7200/sparql"), "http://localhost:7200/");
SparqlResultSet results = endpoint.QueryWithResultSet("PREFIX : <http://www.example.org/> INSERT DATA {:test :test :hhrh }");
why does not it work?
StardogConnector stardog = new StardogConnector("http://localhost:7200", "test", "admin", "posw");
stardog.Begin();
string query = "PREFIX : <http://www.example.org/>SELECT * WHERE {:" + line[0] + " ?k :" + line[1] + "}";
stardog.Query(query);
stardog.Commit();
another way, same problem. Created a DB on a lokalka
Yes, I also came to this conclusion, I use GraphDB for the first time. Well, how can I implement it with a file? I wrote such code.
IGraph g = new Graph();
string sql = "PREFIX : <http://www.example.org/> INSERT DATA {:test :test :hhrh }";
g.LoadFromFile("t.n3");
Object results = g.ExecuteQuery(sql);
here comes such an error
VDS.RDF.Parsing.RdfParseException
HResult = 0x80131500
Message = [InsertKeywordToken at Line 1 Column 36 to Line 1 Column 42] Unexpected Token encountered - expected a BASE / PREFIX directive or a Query Keyword to start a Query
Source = dotNetRDF
Stack trace:
in VDS.RDF.Parsing.SparqlQueryParser.ParseInternal (SparqlQueryParserContext context)
in VDS.RDF.Parsing.SparqlQueryParser.ParseInternal (TextReader input)
in VDS.RDF.Parsing.SparqlQueryParser.ParseFromString (String queryString)
in VDS.RDF.GraphExtensions.ExecuteQuery (IGraph g, String sparqlQuery)
in algorAutoText.Program.Main (String [] args) in C: \ Users \ Denis \ source \ repos \ algorAutoText \ algorAutoText \ Program.cs: line 43
judging by mistake, I supposedly did not add BASE / PREFIX. But he is in the request
Update and delete queries come through the /statements endpoint,
i.e. /repositories/{repository_id}/statements.
You can see the RDF4J server REST API here:
http://docs.rdf4j.org/rest-api/#_the_rdf4j_server_rest_api
When you use the DELETE or INSERT keywords you are doing a SPARQL Update, not a Query. SPARQL separates Query and Update into two separate specifications and most triple stores implement them as two separate endpoints (e.g. for security reasons).
To do an update from dotNetRDF into a triple store you have two options.
You can work directly with the SPARQL update endpoint in which case you will need to check the documentation for your triple store to find out how to create the URL for that - see https://github.com/dotnetrdf/dotnetrdf/wiki/UserGuide-Updating-With-SPARQL#remote-updates for details.
Alternatively if your triple store is one of the ones supported by dotNetRDF (Stardog and Sesame/GraphDB both are), then there are convenience wrappers that make this a bit easier - for more information about this please refer to https://github.com/dotnetrdf/dotnetrdf/wiki/UserGuide-Triple-Store-Integration#update

How to use Server.UrlEncode with the Mustache Template Engine?

I am trying to Encode a product SKU on our Product Filter Module.
The problem I am experiencing is that the Detailed Product View uses the following code to retrieve the appropriate product information. The problem arises when an SKU has a forward slash. For Example, BD1115/35 the code below only detects the first part.
var prodCode = Request.QueryString["sku"];
var decodeprodCode = HttpUtility.UrlDecode(prodCode);
It was suggested that I encode the URL. Now I am trying to do this with Mustache which is a templating engine. Look at {{StockCode}} after SKU. This does not work.
<img class='responsive productimage' src='{{ProductImage}}' alt='{{StockDescription}}' />
I had a look at this question: Using Request.QueryString, slash (/) is added to the last querystring when it exists in the first querystring
Update
I have created a new Object in the Backend which is called QueryStringSKU and I am encoding it before it is replaced with Mustache. So the SKU BDF5555/45 will render in the href as BDF5555%2F45.
The problem now comes in when I try to Decode the URL. The querystring is now showing BDF5555&45.
Somehow DotNetNuke is changing this or rewriting this and now it is still ignoring the 45 value which is part of the Stock Keeping Unit (SKU)
I ended up using this code:
string RawurlFromRequest = Request.RawUrl;
var cleanSKU = RawurlFromRequest.Split(new[] { "sku/" }, StringSplitOptions.None)[1];
var decodeprodCode = cleanSKU.Split(new[] { "&" }, StringSplitOptions.None)[0];

Match string that contain unknown text

I have a web service that I'm calling that returns a list of error messages. I'm then doing a foreach over this list, and matching based on the text of the error messages in a config file. However, some of the error messages returned from the web service contains some unknown data, such as a date, or a number.
How can I match this text, using C#? Would I have to split the string and try to match each individual word? How do I deal with an unknown variable such as a date or number when doing a ".Contains(...)"?
Here's an example:
Web service list might contain the following
"This is an example static error message"
"Another example static error message"
"This is an error message for employee 2"
"This is an error message dated 11/2/2017"
"Employee 3 does not work here anymore"
In my config file, I have the following:
<add errorText="This is an example static error message" field="N/A" />
<add errorText="Another example static error message" field="N/A" />
<add errorText="This is another example for employee **X**" field="N/A" />
<add errorText="This is an error message dated **X**" field="N/A" />
<add errorText="Employee **X** does not work here anymore" field="N/A" />
From your config files, you could build regular expressions as follows:
String configString = GetConfigString(3); // "This is another example for employee **X**"
String regexPattern = String.Concat("^", configString.Replace("**X**", ".+"), "$");
Boolean match = Regex.IsMatch("This is another example for employee John", regexPattern);
and then use such regex to match your text strings.
You could also build all of your regular expression patterns as soon as your application starts and cache them somewhere for future use:
String configStrings = GetConfigStrings();
String[] regexPatterns = new String[configStrings.Length];
for (Int32 i = 0; i < configStrings.Length; ++i)
regexPatterns[i] = String.Concat("^", configStrings[i].Replace("**X**", ".+"), "$");
Since you have a mixed type of possible string replacement within your framework, sticking to the .+ token is the better choice.
If course, it's up to you to eventually build a configuration file parsers and implement GetConfigString and GetConfigStrings methods (or only one, depending on the approach you want to use).
You can use Regex to match them:
Regex.IsMatch(message, "This is another example for employee .+")
Regex.IsMatch(message, "This is an error message dated .+")
If you don't like to take regex approach, like me, you can add the known error messages into a HashSet and keep them in memory and then lookup which error message matches the most with the error message on hand, like a match score.

Encoding issue webservice api

I'am having an issue with encoding as I retrieve informations such as customers names or orders info through webservice API. I'am using C# to manipulate the API, here is an example of the encoding problem :
1) Here is the value as seen in the MYSQL database (input source) : TestAcctééa --> We can see that the accent characters "éé" are well interpreted.
2) Here is the value as seen when I retrieve the information through the api : TestAcct????a --> We can see there is a problem, it does this with all the special characters (é, ç, ê,...). I cannot display the string correctly in the console and as I insert it in the target database (MSSQL), it keeps the questions marks in place of the special characters.
Here is my example code to get this particular information with the api :
filters filters = new filters();
WebserviceApi service = new WebserviceApi();
string login = service.login("******", "********");
string test = null;
List<customerCustomerEntity> customers = service.customerCustomerList(login, filters).ToList();
foreach (var customer in customers)
{
if(customer.email == "test#gmail.com")
{
test = customer.firstname;
}
}
MessageBox.Show(test);
I already tried different solutions from forums such as changing the encoding in C# or convert it but none has worked...
Btw, the encoding of the source database is UTF-8 Unicode (utf8).
Thank for your help.

Retrieve information from SVN Repository contains special characters

I am using SharpSVN to connect and retrieve information from Visual SVN Server by C#.
But on SVN Server, a Repository have folder with the name is C# and when read to this folder, exception occurred:
Additional information: URL
'https://< svnserver >/svn/IT/02_SHOPFLOOR/C' non-existent in
revision 13
I debug and found that URI still be:
{https://< svnserver >/svn/IT/02_SHOPFLOOR/C#} System.Uri
How could I do to access SVN repositories which contain special characters?
I had used like following but nothing changed:
if (lists[i].Path.Contains("#"))
{
path = lists[i].Path.Replace("#", "\\#");
}
else
{
path = lists[i].Path;
}
reposss[i] = new Uri("https://< svnserver >/svn/IT/02_SHOPFLOOR/" + path);
svnClient.GetList(reposss[i], out listsInfo); //Exception occur at here
The # is the schema operator in a Url. You need to escape this character using the uri escape rules. There are helper functions for this on the System.Uri class and for some specific scenarios on SvnTools. The escaped character will be something like %23 where 23 is the hexadecimal value of the character.

Categories

Resources