Linq: Except(null) - c#

I know the title of this question is obscure, but I don't know how to describe exactly just in a few words. What I want is to do a simple statistic on web page visitors. When people visi the page, it's IP will be stored in database, I count the IP to see how many visit times for a page, but I don't want to conclude my IP for sure. So my code is:
WebStatDataContext dc = new WebStatDataContext(_connString);
var query = from v in dc.VisitorInfos
where v.IP == "208.xxx.xxx.69"&&v.Site==site
select v.IP;
var all = from v1 in dc.VisitorInfos
where v1.Site==site
select v1.IP;
int result = all.Except(query).Count();
return result;
However, I found that it returns "1", if "query" is null. If "query" is not null, the result is correct. What happens here?

Related

Receive all information from classes

I have some code which I'm having problems which and hopefully somebody can assist me, basically I have a 'Player' class such as:
Player JanMccoy = new Player { playerFirstname = "Jan", playerSurname = "Mccoy", playerAge = 23,
playerCode = "MCC0001"};
I have about 10 players, all of which have a unique code to them self, basically this code is stored into a list box with the Name and Surname. How the data gets their isn't important, basically though there are 10 values in the listbox which look like "Jan Mccoy (MCC0001)"
Basically I want to now be able to get the age of the person in the class, I have an event for a button which when he gets the selected item from the listbox box I store into a string just the playerCode, which this code I need to be able to get the player age
I know this is SQL but I need something basically like:
SELECT * FROM MyClass WHERE playerCode = strPlayerCode
I however am not using SQL, I need something which can do that in C#
If I need to add anymore detail just ask, tried to explain as good as I can.
If you could point me into right direction also that be great also!
In c# there is Linq which works similar to SQL
For example:
SELECT * FROM MyClass WHERE playerCode = strPlayerCode
would be
var players = myListOfPlayers.Where(p => p.playerCode == strPlayerCode);
This will return a collection of all the players with that playercode
However, since you said the key is unique and you are only returning a single record FirstOrDefault will work fine without the need tor the where clause. like SELECT TOP 1 FROM ....
var player = myListOfPlayers.FirstOrDefault(p => p.playerCode == strPlayerCode);
Then I would try LINQ:
var player = players.Where(p => p.playerCode == "MCC001").FirstOrDefault();

Sharepoint 2010 FullTextSQLQuery not returning all results

I'm currently having a very strange issue.
This is the query i'm using:
string queryText = string.Format("SELECT Path, TelefoneContacto, EmpresaContacto, DireccaoContacto, MailContacto, TelemovelContacto, NomeContacto FROM scope() WHERE FREETEXT(NomeContacto, '{0}') AND (CONTAINS(Path,'/Contactos/Pages/')) ORDER BY \"NomeContacto\" ASC", keyword);
FullTextSqlQuery query = new FullTextSqlQuery(site);
query.ResultTypes = ResultType.RelevantResults;
query.EnableStemming = true;
query.TrimDuplicates = true;//alterado 4 Junho 2012
query.Hint = QueryHint.OptimizeWithPropertyStore;
query.KeywordInclusion = KeywordInclusion.AllKeywords;
query.Culture = SPContext.Current.Web.Locale;
query.RowLimit = 200;
query.QueryText = queryText;
Now, an example.
The column in which i'm searching is "NomeContacto".
Imagine i'm searching for a person whose NomeContacto = "Rodrigo José Amaral Costa Nunes". If i search "Costa", it returns 38 results, but none are the above.
However, if the keyword is "Rodrigo Costa", then the only result (correctly) is the person above.
Is there even an explanation for this?
Thanks, but i solved it.
Turns out that it was the
query.TrimDuplicates = true;
line that was causing the issue. I changed it from true to false and it now returns 10 more results in the "costa" search.
However, this does not make any sense. TrimDuplicates is for duplicate values, why was it limiting the results for completely different pages?
Thanks anyway
You can try to specify locale for you content in FREETEXT predicate
CONTAINS | FREETEXT
([<column_identifier>,]'<content_search_condition>' [,LCID])
More info about localizaed searches here

C# Reading and Summarizing Text File with LINQ

I've read MANY different solutions for the separate functions of LINQ that, when put together would solve my issue. My problem is that I'm still trying to wrap my head about how to put LINQ statements together correctly. I can't seem to get the syntax right, or it comes up mish-mash of info and not quite what I want.
I apologize ahead of time if half of this seems like a duplicate. My question is more specific than just reading the file. I'd like it all to be in the same query.
To the point though..
I am reading in a text file with semi-colon separated columns of data.
An example would be:
US;Fort Worth;TX;Tarrant;76101
US;Fort Worth;TX;Tarrant;76103
US;Fort Worth;TX;Tarrant;76105
US;Burleson;TX;Tarrant;76097
US;Newark;TX;Tarrant;76071
US;Fort Worth;TX;Tarrant;76103
US;Fort Worth;TX;Tarrant;76105
Here is what I have so far:
var items = (from c in (from line in File.ReadAllLines(myFile)
let columns = line.Split(';')
where columns[0] == "US"
select new
{
City = columns[1].Trim(),
State = columns[2].Trim(),
County = columns[3].Trim(),
ZipCode = columns[4].Trim()
})
select c);
That works fine for reading the file. But my issue after that is I don't want the raw data. I want a summary.
Specifically I need the count of the number of occurrences of the City,State combination, and the count of how many times the ZIP code appears.
I'm eventually going to make a tree view out of it.
My goal is to have it laid out somewhat like this:
- Fort Worth,TX (5)
- 76101 (1)
- 76103 (2)
- 76105 (2)
- Burleson,TX (1)
- 76097 (1)
- Newark,TX (1)
- 76071 (1)
I can do the tree thing late because there is other processing to do.
So my question is: How do I combine the counting of the specific values in the query itself? I know of the GroupBy functions and I've seen Aggregates, but I can't get them to work correctly. How do I go about wrapping all of these functions into one query?
EDIT: I think I asked my question the wrong way. I don't mean that I HAVE to do it all in one query... I'm asking IS THERE a clear, concise, and efficient way to do this with LINQ in one query? If not I'll just go back to looping through.
If I can be pointed in the right direction it would be a huge help.
If someone has an easier idea in mind to do all this, please let me know.
I just wanted to avoid iterating through a huge array of values and using Regex.Split on every line.
Let me know if I need to clarify.
Thanks!
*EDIT 6/15***
I figured it out. Thanks to those who answered it helped out, but was not quite what I needed. As a side note I ended up changing it all up anyways. LINQ was actually slower than doing it other ways that I won't go into as it's not relevent. As to those who made multiple comments on "It's silly to have it in one query", that's the decision of the designer. All "Best Practices" don't work in all places. They are guidelines. Believe me, I do want to keep my code clear and understandable but I also had a very specific reasoning for doing it the way I did.
I do appreciate the help and direction.
Below is the prototype that I used but later abandoned.
/* Inner LINQ query Reads the Text File and gets all the Locations.
* The outer query summarizes this by getting the sum of the Zips
* and orders by City/State then ZIP */
var items = from Location in(
//Inner Query Start
(from line in File.ReadAllLines(FilePath)
let columns = line.Split(';')
where columns[0] == "US" & !string.IsNullOrEmpty(columns[4])
select new
{
City = (FM.DecodeSLIC(columns[1].Trim()) + " " + columns[2].Trim()),
County = columns[3].Trim(),
ZipCode = columns[4].Trim()
}
))
//Inner Query End
orderby Location.City, Location.ZipCode
group Location by new { Location.City, Location.ZipCode , Location.County} into grp
select new
{
City = grp.Key.City,
County = grp.Key.County,
ZipCode = grp.Key.ZipCode,
ZipCount = grp.Count()
};
The downside of using File.ReadAllLines is that you have to pull the entire file into memory before operating over it. Also, using Columns[] is a bit clunky. You might want to consider my article describing using DynamicObject and streaming the file as an alternative implemetnation. The grouping/counting operation is secondary to that discussion.
var items = (from c in
(from line in File.ReadAllLines(myFile)
let columns = line.Split(';')
where columns[0] == "US"
select new
{
City = columns[1].Trim(),
State = columns[2].Trim(),
County = columns[3].Trim(),
ZipCode = columns[4].Trim()
})
select c);
foreach (var i in items.GroupBy(an => an.City + "," + an.State))
{
Console.WriteLine("{0} ({1})",i.Key, i.Count());
foreach (var j in i.GroupBy(an => an.ZipCode))
{
Console.WriteLine(" - {0} ({1})", j.Key, j.Count());
}
}
There is no point getting everything into one query. It's better to split the queries so that it would be meaningful. Try this to your results
var grouped = items.GroupBy(a => new { a.City, a.State, a.ZipCode }).Select(a => new { City = a.Key.City, State = a.Key.State, ZipCode = a.Key.ZipCode, ZipCount = a.Count()}).ToList();
Result screen shot
EDIT
Here is the one big long query which gives the same output
var itemsGrouped = File.ReadAllLines(myFile).Select(a => a.Split(';')).Where(a => a[0] == "US").Select(a => new { City = a[1].Trim(), State = a[2].Trim(), County = a[3].Trim(), ZipCode = a[4].Trim() }).GroupBy(a => new { a.City, a.State, a.ZipCode }).Select(a => new { City = a.Key.City, State = a.Key.State, ZipCode = a.Key.ZipCode, ZipCount = a.Count() }).ToList();

Solrnet: problem when search field value is query operator (eq. or, and)

To be more precise I will be working with example...
Clean query is: (type:77 AND (zipCode:12345 OR name:OR))
When querying on Solr Admin page this throws exception:
org.apache.lucene.queryParser.ParseException: Cannot parse...
So on Solr Admin page I changed query to:
(type:"77" AND (zipCode:"12345" OR name:"OR"))
which worked as a charm
Now I have a problem to do the same stuff with solrnet. I am using SolrQueryByField class for querying. When I am working with
new SolrQueryByField("name", "OR")
I get Solrnet.Exceptions.InvalidFieldException which is in accordance with Solr Admin page, but when I am working with
new SolrQueryByField("name", "\"OR\"")
I get wrong results. By inspecting network traffic I found out that http get request is different (for brevity only name field name and value are given):
name%3A%22OR%22 => from Solr Admin page
name%3a%5c%22OR%5c%22 => from solrnet
My question is: what sholud I do to prevent solrnet from adding %5C (backslash) to query string?
Thanks in advance
SolrQueryByField produces quoted/escaped values. If you have some special case where this is not desirable (such as this case) you can use SolrQuery, e.g. :
Query.Field("type").Is(77) && (Query.Field("zipCode").Is("12345") || Query.Simple("name:\"OR\""))
Please try to pass the string array that contains multiple field names and search text in the below method. It will return the solrnet query for search with multiple filed name with OR condition.
public ISolrQuery BuildQuery(string[] SearchFields, string SearchText)
{
try
{
AbstractSolrQuery firstQuery = new SolrQueryByField(SearchFields[0], SearchText) { Quoted = false };
for (var i = 1; i < parameters.SearchFields.Length; i++)
{
firstQuery = firstQuery || new SolrQueryByField(SearchFields[i], SearchText) { Quoted = false };
}
return firstQuery;
}

How does one get all child terms of a SharePoint term in C#?

I am writing a webpart for SharePoint 2010 that recuperates the latest page of a certain (custom) type, according to publishing date. It only takes into account pages tagged with a specified term. I would like it to be able to also do so with pages that are tagged with terms which are children of the selected terms.
If I have a term tree like so:
England
Kent
Dover
Canterbury
Surrey
Croydon
Crawley
then by selecting Kent, I want my webpart to show the latest page tagged with Kent, Dover, or Canterbury.
Is this possible in C# ?
Thanks for your time.
The function you are looking for is Term.GetTerms
You will need to get a TaxonomyValue from your field
Then you have to get the current TaxonomySession, then use the TaxonomySession to get the Term used in the field. From that term you can use the Parent field to get the parent Term.
Here is some rough code to show you the objects used.
TaxonomyFieldValue v = null; // Notsurehowtodothisbit();
TaxonomySession session = new TaxonomySession(site);
if (session.TermStores != null && session.TermStores.Count > 0)
{
TermStore termStore = session.TermStores[0];
Term t = termStore.GetTerm(v.TermGuid);
Term parentTerm = t.Parent;
TermCollection childTerms = t.GetTerms();
}
Once you have the tree, you may be able to use a caml query to generate a SPList.GetList query that brings back anything tagged that way.
I have not done an experiment in this regard...
But Bart-Jan Hoeijmakers has
private SPListItemCollection GetItemsByTerm(Term term, SPList list)
{
// init some vars SPListItemCollection items = null;
SPSite site = SPContext.Current.Site; // set up the TaxonomySession
TaxonomySession session = new TaxonomySession(site);
// get the default termstore TermStore termStore = session.TermStores[0];
// If no wssid is found, the term is not used yet in the sitecollection, so no items exist using the term
int[] wssIds = TaxonomyField.GetWssIdsOfTerm(SPContext.Current.Site, termStore.Id, term.TermSet.Id, term.Id, false, 1);
if (wssIds.Length > 0)
{
// a TaxonomyField is a lookupfield. Constructing the SPQuery
SPQuery query = new SPQuery();
query.Query = String.Format("<Where><Eq><FieldRef Name='MyTaxonomyField' LookupId='TRUE' /><Value Type='Lookup'>{0}</Value></Eq></Where>", wssIds[0]);
items = list.GetItems(query);
}
return items;
}
Nat's partial answer using the GetTerms method for the parent is great. The code for querying one list looks good too.
To get the id for the parent term, you can use TermStore.GetTerms against the title.
To search across all lists and libraries in the the site collection, you can use the Search API's FullTextSQLQuery method specifying the guids in the where clause with the owstaxIdMyTaxonomyField as the column.
There is a great example of getting id's by title and searching for a term store by id at Using taxonomy fields in SharePoint 2010: Part III

Categories

Resources