linqToTwitter UserID always zero - linq-to-twitter

I need to construct the URL to the original tweet as
http://twitter.com/{twitter-user-id}/status/{tweet-staus-id}
Joe's code on linq2twitter works fine, but when I replace User.ScreenNameResponse from his sample with User.UserID,
the UserID is always zero. The debugger shows tweet.UserID is also zero. Most fields are populated.
My code:
var twitterCtx = new TwitterContext(getAuth());
var searchResponse =
await
(from search in twitterCtx.Search
where search.Type == SearchType.Search &&
search.Query == searchTxt &&
search.Count == searchCount
select search)
.SingleOrDefaultAsync();
if (searchResponse != null && searchResponse.Statuses != null)
searchResponse.Statuses.ForEach(tweet =>
Console.WriteLine(
"User: {0}, Tweet: {1}",
//tweet.User.ScreenNameResponse,
tweet.User.UserID,
tweet.Text));
Version: 3.1.1 from NuGet using app authentication.
How can I get the UserID so I can construct the tweet URL?
This SO thread (use id_str) did not help.

That would be in tweet.User.UserIDResponse.
A bit of background: Anything used as an input parameter is also looked at in the query response, so if a user omits the parameter in a query but the twitter response contains a value, it was being filtered out of the results. To fix this, I adopted a convention where any return parameters also match input parameters would have a 'Response' suffix. e.g. ScreenName (input) and ScreenNameResponse (output). To find which values are input, the docs for each API (including Search) call contain the input/filter parameters.

Related

How to write this LINQ query to get a particular claim from Identity oauth

I have a list of claims in my object and I want to look for a particular claim with its name and find its value which is Boolean. I wrote the following query but I am getting the error saying that I can't use '&&' operator on string and Boolean operands.
bool isSSO = context.Ticket.Identity.HasClaim(c => c.Type == "IsSSO"&& c.Value);
Please advise.
The problem is that Claim.Value property is string, probably you are receiving values like "true" or "false". Try this:
bool isSSO = context.Ticket.Identity.HasClaim(c => c.Type == "IsSSO" && bool.Parse(c.Value));

how to check for a value in the last 10 entries using linq to entities

I have method where I need to retrieve using EF the last ten entries in the database and check to see if there is a match between the value and the current term. Here is what I have thus far
public static int ValidatePassword(string username, string password, int securityUserId)
{
int validResult = 0;
/*Need to pass to client a value based upon success or failure of validation
* 0 - success
* 1 - password has already been used in the last 10 entries
* 2 - password does not meet CJIS requirements
*/
IEnumerable<string> oldpassword = null;
// Create a Regular Expression to determine whether or not special characters are present.
Regex regularExpression = new Regex("[^a-z0-9]");
//if id exists pull last ten passwords
if (securityUserId > 0)
{
long id = Convert.ToInt64(securityUserId);
using (var context = new SecurityEntities(string.Empty))
{
try
{
oldpassword = (from p in context.SecurityAudits
where p.SecurityUserId == id &&
p.OldPassword == password
orderby p.ActionDate descending
select p.OldPassword.Take(10).ToString()).ToList();
}
catch (Exception ex)
{
string err = string.Format("ValidateCJISPassword() was unable to return an object msg:{0}", ex.Message);
throw new Exception(err, ex.InnerException);
}
finally
{
context.Dispose();
}
}
}
else if (oldpassword == null)
{
//no matching record found now check other requirements
if ((password.Length >= DEFAULT_CJIS_PASSWORD_MIN_LENGTH) && regularExpression.IsMatch(password) && (password != username))
{
//success
validResult = 0;
}
else
{
//password does not meet standard CJIS requirements
validResult = 2;
}
}
else
{
//matching record was found
validResult = 1;
}
return validResult;
}
}
Where I am currently hung up is the query throws an exception on the ToString() method
LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.
I'm still learning EF and how linq works so I'm not sure what the best approach here is. Should I try to set the result to something other than IEnumerable like an array or List or is there another approach I should consider?
Thanks in advance,
Cheers,
Change this
oldpassword = (from p in context.SecurityAudits
where p.SecurityUserId == id &&
p.OldPassword == password
orderby p.ActionDate descending
select p.OldPassword.Take(10).ToString()).ToList();
To this
oldpassword = (from p in context.SecurityAudits
where p.SecurityUserId == id &&
p.OldPassword == password
orderby p.ActionDate descending
select p.OldPassword).Take(10).ToList();
The problem was that your Take(10) clause was not part of the whole result but inside the actual linq statement.. it goes on the outside of it to take the top 10 of the entire resultset.. then you do the ToList() which turns the whole thing into an array
The next problem is that you just created an array and assigned it to oldpassword
I don't see anything here that does anything with the array...
You need to do something like:
declare your array of strings
assign the array to the return of the linq query
evaluate the return for > 0 results
if > 0 then the password has been used in the last 10
if = 0 then new password should be ok, correct?
Now that I have an understanding of what I needed in the query I was able to also update the linq statement as follows:
var lastTenPassword = (from p in context.SecurityAudits.Take(10)
orderby p.ActionDate descending
where p.SecurityUserId == id
select p.OldPassword).ToList();
string oldpassword = lastTenPassword.Where(a => a == password).FirstOrDefault();
Testing is further down the line but now by moving the .Take() method inside the query I am explicitly grabbing the top ten where as my first attempt would have retrieved all the records and then grabbed the top ten.
For testing you can also see where I broke out the initial where() to first grab all records by id and then perform a filter on that set by looking for a matching password within that set.
Thanks again for your help

Match on 2 values

I'm trying to figure out how to modify this to match on 2:
var result = _context.FirstOrDefault(c => c.CarId == carId);
I'm not sure how to tack this on. I just want to base it on c.CarId == carId && c.UserId == userId
where carId and userId are incoming params to my method that this LINQ statement resides in. I want to keep this as a lambda expression syntax.
Just do it exactly as you've written it:
var result = _context.FirstOrDefault(c => c.CarId == carId && c.UserId == userId);
There's nothing wrong with that. The lambda expression isn't restricted to compare a single property.
If you want to learn about LINQ in more detail, I'd start with LINQ to Objects, which is simpler to understand and predict. There are various tutorials around for it, and I have a blog series called Edulinq which examines each operator in detail.

TargetInvocationException thrown when attempting FirstOrDefault on IEnumerable

I suspect I'm missing something rather basic, yet I can't figure this one out.
I'm running a simple linq query -
var result = from UserLine u in context.Users
where u.PartitionKey == provider.Value && u.RowKey == id.Value
select u;
UserLine user = null;
try
{
user = result.FirstOrDefault();
}
For some reason this produces a TargetInvocationException with an inner exception of NullReferenceException.
This happens when the linq query produces no results, but I was under the impression that FirstOrDefault would return Default<T> rather than throw an exception?
I don't know if it matters, but the UserLine class inherits from Microsoft.WindowsAzure.StorageClient.TableServiceEntity
there are two possible reasons:
provider.Value
id.Value
Are you sure that theese nullables have value. You might want to check HasValue before
var result = from UserLine u in context.Users
where (provider.HasValue && u.PartitionKey == provider.Value)
&& (id.HasValue && u.RowKey == id.Value)
select u;
UserLine user = null;
try
{
user = result.FirstOrDefault();
}
I thought it produced a different error, but based on the situation in which the problem is occurring you might want to look to check if context.IgnoreResourceNotFoundException is set to false? If it is try setting it to true.
This property is a flag to indicate whether you want the storage library to throw and error when you use both PartitionKey and RowKey in a query and no result is found (it makes sense when you think about what the underlying REST API is doing, but it's a little confusing when you're using LINQ)
I figured it out - the problem occured when either id or provider had '/' in the value, which the id did. when I removed it the code ran fine
Understanding the Table Service Data Model has a section on 'Characters Disallowed in Key Fields' -
The following characters are not allowed in values for the
PartitionKey and RowKey properties:
The forward slash (/) character
The backslash () character
The number sign (#) character
The question mark (?) character
Here's some fun try putting the where query the other way around like this to see if it works (I heard a while ago it does!):
where (id.HasValue && u.RowKey == id.Value) && (provider.HasValue && u.PartitionKey == provider.Value)
Other than this you can now set IgnoreResourceNotFoundException = true in the TableServiceContext to receive null when an entity is not found instead of the error.
It's a crazy Azure storage thing.

Getting a column value

private string FindTaxItemLocation(string taxItemDescription)
{
if (!templateDS.Tables.Contains(cityStateTaxesTable.TableName))
throw new Exception("The schema dos not include city state employee/employer taxes table");
var cityStateTaxes =
templateDS.Tables[cityStateTaxesTable.TableName].AsEnumerable().FirstOrDefault(
x => x.Field<string>(Fields.Description.Name) == taxItemDescription);//[x.Field<string>(Fields.SteStateCodeKey.Name)]);
if (cityStateTaxes != null)
return cityStateTaxes[Fields.SteStateCodeKey.Name].ToString();
return null;
}
cityStateTaxes is a DataRow, why/how I cannot get the column value inside FirstOrDefault()?
Thanks,
FirstOrDefault() selects the first item in the collection (optionally that satisfies a predicate) or returns null in the case there it is empty (or nothing satisfies the predicate). It will not do projections for you. So if you use it, it can be awkward to access a field of the item since you must include default value checks.
My suggestion is to always project to your desired field(s) first before using FirstOrDefault(), that way you get your field straight without needing to perform the check.
var cityStateTaxes = templateDS.Tables[cityStateTaxesTable.TableName]
.AsEnumerable()
.Where(row => row.Field<string>(Fields.Description.Name) == taxItemDescription) // filter the rows
.Select(row => row.Field<string>(Fields.SteStateCodeKey.Name)) // project to your field
.FirstOrDefault(); // you now have your property (or the default value)
return cityStateTaxes;

Resources