I have a query that contains a string that looks like this: .
When I put this into my query hardcoded it does return results and as a variable it doesn't.
var myresult = RepositoryQuery.Where(a => a.Account== #"domain\\user");
Works.
string account= "domain\\user";
var user = RepositoryQuery.Where(a => a.Account == account);
Does not work.
Account GetAccount(account){
return RepositoryQuery.Where(a => a.Account == account);
}
Does not work.
Account GetAccount(account){
return RepositoryQuery.Where(a => a.Account == #account);
}
Does not work.
My guess is that it would have to do with the backslashes, but I can't any answers.
I found someone with the same problem but I couldn't get a solution out of it.
What am I doing wrong?
[edit]
Updated the typo var name.
account.Replace("\\", "\\\\");
If I replace it like this it works.
Looks ugly though..
[Solution]
So the account string I get from my session has already been escaped. I decided to replace the backslashes at session creation to keep the databases in line and not have one with double backslashes and one with single.
Sometimes you have to be aware of what you are looking at might have been changed by the IDE visually, when debugging, for example you could get confused when looking at filepaths in visual studio. where a string "c:\something\file.bla" could be shown as "c:\\something\\file.bla"
this also happens in connection strings and other things.
In your case #"domain\\user" is really "domain\\user"
whereas if you don't use the verbatim string
"domain\\user" would be "domain\user" when querying the database.
Use:
string accountid = #"domain\user"
Or
string accountid = "domain\\user"
On a second note:
the # in front of a variable is used to allow you to use reserved words as your variable names.
something like:
string #class = "1st. class";
Or
bool #if = true;
if(#if)
{
Console.WriteLine("If is: "+ #if); //would print "If is: true"
}
Your first mistake: you filter with account variable instead of accountid.
Maybe it behaves as an escape character, try with verbatim string:
string accountid = #"domain\\user";
or if you store it with single backslash:
string accountid = #"domain\user";
I think this could work:
string accountid = #"domain\user";
var user = RepositoryQuery.Where(a => a.Account == accountid );
or this (but I don't suggest):
string accountid = "domain\\user";
var user = RepositoryQuery.Where(a => a.Account == accountid );
Related
I use System.Linq.Dynamic to query entities with dynamic 'where' expressions. I'm querying object that has property "newValue" of string type. Exemplary value would be : "{\"ProcessId\":764, \"ProcessLength\":1000}".
I can't use == because I want to find all hits where the property contains "ProcessId:764", regardless on the rest of the string. The thing is, that stored string contains escape sign "\" and double quotes and I can't figure out what it should like exactly..
dbContext.Processes.Where("#newValue.Contains(\"ProcessId\":764\")") brings error, however dbContext.Processes.Where("#newValue.Contains(\":764\")") works correctly. I guess it must be something with backslashes or double quotes in my query but can't figure it out on my own..
There are two things to note here:
If you know at compile time the column that should be queried (i.e., newValue), just use standard Linq: var list = items.Where(i => i.NewValue.Contains("904")).ToList().
If you do want to use dyanmic Linq, What you'd usually want is to apply Where on some column, e.g. Where("SomeColumn.Contains("something")"), or Where("SomeColumn.Contains(#0)", new string[] {"something"}).
So, in your case, this should work: items.Where("newValue.Contains(\"904\")").
Doing Where("#newValue.Contains("something")") doesn't really make sense, since #newValue would be parsed as a string literal. See also this comment on a similiar question.
Here' a quick example:
public static void Main(string[] args)
{
var items = new []
{
new { Id = "1", Title = "ProcessId: 123"},
new { Id = "4", Title = "ProcessId: 456"},
new { Id = "7", Title = "ProcessId: 789"},
}.ToList();
// returns null, because the string "Title" doesn't contain the string "7"
var res1 = items.Where("#0.Contains(\"7\")", new string[] {"Title"}).FirstOrDefault();
// works - returns the 3rd element of the array
var res2a = items.Where("Title.Contains(#0)", new string[] {"ProcessId: 789"}).FirstOrDefault();
var res2b = items.Where("Title.Contains(\"ProcessId: 789\")").FirstOrDefault();
}
#HeyJude Thanks for the effort, but I still can't get it to work. It has somehow gone wronger and now I can't even fetch correct rows giving only ProcessId number..
Let me give you more detailed description of my setup. In the database there's a table with column "NewValue", I use this column to store json string of current (for the time of creating row in the table) representation of some object e.g. object Process. So the column stores for example string of {"ProcessId":904,"ProcessLength":1000}. To fetch this data from db I create collection of table's records: var items = (from l in db.JDE_Logs
join u in db.JDE_Users on l.UserId equals u.UserId
join t in db.JDE_Tenants on l.TenantId equals t.TenantId
where l.TenantId == tenants.FirstOrDefault().TenantId && l.Timestamp >= dFrom && l.Timestamp <= dTo
orderby l.Timestamp descending
select new //ExtLog
{
LogId = l.LogId,
TimeStamp = l.Timestamp,
TenantId = t.TenantId,
TenantName = t.TenantName,
UserId = l.UserId,
UserName = u.Name + " " + u.Surname,
Description = l.Description,
OldValue = l.OldValue,
NewValue = l.NewValue
});. Then I query it to find matching rows for given ProcessId number e.g. query = "#NewValue.Contains(\"904,)\")";
items = items.Where(query);
This should fetch back all records where NewValue column contains the query string, but this doesn't work. It compiles and 'works' but no data are fetched or fetched are only those records where 904 appears later in the string. Sounds stupid but this is what it is.
What should the query string look like to fetch all records containing "ProcessId":904?
Please, I am trying to access my database to get access to a user id. But when i try accessing, what gets returned is 0. Initially, i had issues figuring out how to change this SQL statement (SELECT user_id FROM users WHERE firstname = 'Godymn') to LINQ. But i later found that i could use :
var result = users.Where(x=>x.firstname == "Godymn").Select(x=>x.userid);
So far, when i tried to use the query in my code, it returns a 0. But what i need is to return the user id based on the name specified in the linkLabel. I have not been able to figure out why its not working.
Will appreciate any help.
Here is my code
private int Chk()
{
string link = linkLabelPartner.Text;
var result = (dynamic)null;
using (DbModel db = new DbModel())
{
result = db.users.Where(x => x.firstname == link).Select(x => x.user_id).FirstOrDefault();
}
return result;
}
Here is the button i used to check the content of what got returned.
private void btnTey_Click(object sender, EventArgs e)
{
int test = Chk();
MessageBox.Show(test.ToString());
}
Good Afternoon Godymn.
Here are some possible scenarios:
1 - The user name Godymn does not exist in the database
2 - The user_id is 0.
Try checking this 2 scenarios.
After that, you could change your approach to a more "debug friendly" level.
var result = db.users.First(f => f.firstname == link);
Then, check if result is null. If it is null, the name was not found in the database.
If it is not null, check if the result is 0.
Why this approach: This way, you can tell if the problem is when you are searching for the user or when you are binding the value of Id.
I can't comment, i'm sory, but first of all i'll try this:
var foo = db.users.Select(x => x).ToList();
then you can investigate your result like this
i suppose you try get wrong data (or wrong structure)
when i stuck i do this:
Or maybe you can attach your structure of object?
So yeah, I was able to fix the bug. The problem was with the linkLabelPartner.Text as Chris Dunaway rightly said. As soon as he mentioned if the linklabel contains only firstname, I just knew that was the missing piece. This holds firstname and lastname and I only accounted for just firstname. Hence the value returned remains at 0. So, all I had to do was to concatenate both firstname and lastname which solved the issue. So, yeah the query I used initially was right.
Here is the code
private int Chk()
{
string link = linkLabelPartner.Text;
var result = (dynamic)null;
using (DbModel db = new DbModel ())
{
result = db.users.Where(x => x.lastname + " " + x.firstname == link ).Select(x => x.users).FirstOrDefault();
}
return result;
}
private void btnTey_Click(object sender, EventArgs e)
{
int test = Chk();
MessageBox.Show(test.ToString());
}
Many thanks everyone for your suggestions, appreciate.
I have a table of Somethings. Those Somethings have a Name field. A User of my website can enter a forward or backward combination of that name and I need to return the correct something.
Example:
User enters: "name the".
I have a Something.Name of "the name".
I return that Something.
Now, the SQL would look like this:
SELECT * FROM Somethings
Where Name LIKE '%name the%'
OR Name LIKE '%the name%'
As you can see, I need to get all permutations of the string the user enters and then search for each one. I tried doing this in a loop, using Linq to Entities, like so:
var string[] arr = {"name the", "the name"};
foreach (var str in arr)
{
var matchingSomethings = db.Somethings
.Where(e => e.Name.IndexOf(str , StringComparison.InvariantCultureIgnoreCase) >= 0);
}
This worked really well, when the user entered two words. But, with five words (120 permutations), it became cumbersome and the query timed out for the user.
I then tried:
var matchingSomethings = db.Somethings
.Where(e => arr.Contains(e.Name));
You can clearly see the obvious flaw there, being that the a Something that had a Name of "the name of the Something" would not be matched in this query, because that name is not included in the snippet the user entered of "the name".
So how would I write that Linq to Entities query to get all possible Somethings where any permutation of the snippet the user entered is contained in the Name of the Something?
Look for each word individually and return the item that had all matching words. This should do it:
public void MatchSomethings(string input)
{
var data = new List<something>();
var wordsInName = input.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var match = data.Where(s => wordsInName.All(word => s.Name.Contains(word)));
}
I have a Url as shown below
http://www.mytestsite.com/TesPage.aspx?pageid=32&LangType=1033&emailAddress=myname%40gmail.com
I would like to have the email address from the url
Note
The email address may have the escape character of # sometimes.
ie it may be myname%40gmail.com or myname#gmail.com
Is there any way to get the email address from a url, such that if the that have the matching regx for an email patten and retrieve the value.
Here is the code that i have tried
string theRealURL = "http://www.mytestsite.com/TesPage.aspx?pageid=32&LangType=1033&emailAddress=myname%40gmail.com";
string emailPattern = #"^([\w\.\-]+)(((%40))|(#))([\w\-]+)((\.(\w){2,3})+)$";
Match match = Regex.Match(theRealURL, emailPattern);
if (match.Success)
string campaignEmail = match.Value;
If anyone helps what went wrong here?
Thanks
If possible, don't use a regular expression when there are domain-specific tools available.
Unless there is a reason not to reference System.Web, use
var uri = new Uri(
"http://www.mytestsite.com/TesPage.aspx?pageid=32&LangType=1033&emailAddress=myname%40gmail.com");
var email = HttpUtility.ParseQueryString(uri.Query).Get("emailAddress");
Edit: If (for some reason) you don't know the name of the parameter containing the address, use appropriate tools to get all the query values and then see what looks like an email address.
var emails = query
.AllKeys
.Select(k => query[k])
.Where(v => Regex.IsMatch(v, emailPattern));
If you want to improve your email regex too, there are plenty of answers about that already.
Starting with Rawling's answer in response to the comment
The query string parameter can vary.. How can it possible without using the query string parameter name.
The follwing code will produce a list (emails) of the emails in the supplied input:
var input = "http://www.mytestsite.com/TesPage.aspx?pageid=32&LangType=1033&emailAddress=myname%40gmail.com";
var queryString = new Uri(input).Query;
var parsed = HttpUtility.ParseQueryString(queryString);
var attribute = new EmailAddressAttribute();
var emails = new List<string>();
foreach (var key in parsed.Cast<string>())
{
var value = parsed.Get(key);
if (attribute.IsValid(value))
emails.Add(value);
}
Console.WriteLine(String.Join(", ", emails)); // prints: myname#gmail.com
See also this answer for email parsing technique.
I am trying to pass in a variable with a single quote to be stored in Neo4j while using Neo4jClient and I cannot seems to get the character escaping correctly.
When I use this:
var Command = new UpdateCommand()
{
Name = "3 o'clock";
};
I get an error saying there is a syntax error. When I use this:
var Command = new UpdateCommand()
{
Name = "3 o\\'clock ";
};
It is storing the variable name incorrectly with an extra escape character.
My create node is quite simple and looks like this, the newUser object has one property (Name) that is being set by the command.
_client.Cypher
.Create("(u:User {user})")
.WithParams(new { user = newUser })
.ExecuteWithoutResults();
What am I doing wrong here? What is the proper way to escape your strings with Neo4jClient?
UPDATE: My problem isn't with creating a new node as describe above but rather while doing an on create on match cypher. I was trying to simplify the question for SO and I removed the problem. Please see the below updated code and this code is throwing and error for me. It could be that I am just going about the on create / on match incorrectly as well.
_client.Cypher
.Merge("(u:User { UserId: " + userId + "})")
.OnCreate()
.Set("u = {user}")
.WithParams(new { user = newUser })
.OnMatch()
.Set(string.Format("u.Name = '{0}'",
newUser.Name))
.ExecuteWithoutResults();
You shouldn't need to do any escaping aside from standard C# (of which you don't need to for a single quote). The following code creates a new user with the name of 3 O'clock and returns it absolutely fine.
var newUser = new User{Name = "3 O'clock"};
gc.Cypher
.Create("(u:Test {user})")
.WithParams(new {user = newUser})
.ExecuteWithoutResults();
var val = gc.Cypher
.Match("(n:Test)")
.Return(n => n.As<User>())
.Results
.First();
Console.WriteLine(val.Name);
If this code doesn't work for you - what version of Neo4jClient are you using, against what version of Neo4j, and what does this 'UpdateCommand' do?
EDIT FOR UPDATE
You should still use parameters for setting:
gc.Cypher
.Merge(string.Format("(u:User {{UserId: {0}}})", userId))
.OnCreate().Set("u = {userParam}").WithParam("userParam", newUser)
.OnMatch().Set("u.Name = {nameParam}").WithParam("nameParam", newUser.Name)
.ExecuteWithoutResults();
Let Neo4jClient deal with all the quotes / formatting of the parameters!