Can I avoid this linq query redundancy? - c#

My code :
var myList = xDoc.Descendants("localita").Select(n => new
{
ID = n.Element("id").Value.ToString(),
Localita = n.Element("nome").Value.ToString(),
Lat = n.Element("lat").Value.ToString(),
Lng = n.Element("lon").Value.ToString(),
MeteoOggi = new MeteoGiorno()
{
Min = n.Descendants("previsione").First().Element("temp_perc").Value.ToString(),
Max = n.Descendants("previsione").First().Element("temp").Value.ToString(),
DescrizioneTempo = n.Descendants("previsione").First().Element("desc_tempo").Value.ToString(),
Precipitazioni = n.Descendants("previsione").First().Element("prec").Value.ToString(),
VentoDirezione = n.Descendants("previsione").First().Element("v_dir").Value.ToString(),
VentoIntensita = n.Descendants("previsione").First().Element("v_int").Value.ToString(),
Pressione = n.Descendants("previsione").First().Element("press").Value.ToString(),
ZeroTermico = n.Descendants("previsione").First().Element("zerot").Value.ToString(),
Immagine = n.Descendants("previsione").First().Element("id_tempo").Value.ToString()
}
});
but as you can see, that n.Descendants("previsione").First() is "searched" each time when I set the values for the Class MeteoGiorno. Can I put a sort of reference to that node in my example?

Sure you can, just change the Select:
var myList = xDoc.Descendants("localita").Select(n => {
var previsione = n.Descendants("previsione").First();
return new {
ID = n.Element("id").Value.ToString(),
....
MeteoOggi = new MeteoGiorno()
{
Min = previsione.Element("temp_perc").Value.ToString(),
Max = previsione.Element("temp").Value.ToString(),
....
}
}
});

Related

C# Solr query - how to only get future dates?

I have a search method that queries Solr for event items. I need to modify it to only get events where the date has not already passed (i.e. Where(x => x.EventDate.Date >= DateTime.Now.Date), but I'm not sure how to add this because I'm not very familiar with Solr. Here's my search function:
public SearchQueryResults Search(string keywords, int page,int perPage, List<Guid> contentTypeFilters, List<Guid> otherFilters, ISortBuilder<SearchResultItem> sortBuilder)
{
var searchFilters = new List<IPredicateBuilder<SearchResultItem>>()
{
new IsSearchablePredicateBuilder()
};
if (contentTypeFilters.Any())
{
var contentTypePredicateBuilder = new ContentTypePredicateBuilder();
contentTypePredicateBuilder.ContentTypes = contentTypeFilters;
searchFilters.Add(contentTypePredicateBuilder);
}
if (otherFilters.Any())
{
var tagFilterBuilder = new TagsAndPredicateBuilder(otherFilters,_sitecoreContext);
searchFilters.Add(tagFilterBuilder);
}
if (string.IsNullOrWhiteSpace(keywords))
{
keywords = "";
}
SearchRequest searchRequest = new SearchRequest();
var queryParams = new Dictionary<string, string>() { };
queryParams.Add("q", keywords);
searchRequest.QueryParameters = queryParams;
searchRequest.SortBy = "";
searchRequest.SortOrder = "";
SearchQuery<SearchResultItem> queryArguments = new SearchQuery<SearchResultItem>();
queryArguments.FilterBuilders = searchFilters;
queryArguments.Page = page;
queryArguments.PerPage = perPage;
queryArguments.FacetsBuilder = new SearchFacetBuilder<SearchResultItem>();
queryArguments.SearchRequest = searchRequest;
queryArguments.IndexName = _indexName;
if (string.IsNullOrWhiteSpace(keywords))
{
queryArguments.QueryBuilders =new List<IPredicateBuilder<SearchResultItem>>();
}
else
{
queryArguments.QueryBuilders = new[] { new KeywordPredicateBuilder<SearchResultItem>(new[] { keywords }) };
}
queryArguments.SortBuilder = sortBuilder;
try
{
var results = _searchManager.GetResults<SearchResultItem>(queryArguments);
SearchQueryResults queryResults = new SearchQueryResults();
queryResults.ResultItems = results.Results;
queryResults.CurrentPage = page;
queryResults.TotalResults = Int32.Parse(results.TotalResults.ToString());
queryResults.TotalPages = (queryResults.TotalResults + perPage - 1) / perPage; ;
return queryResults;
}
catch (Exception exc)
{
Sitecore.Diagnostics.Log.Error("Error with FilteredSearch, could be a loss of connection to the SOLR server: " + exc.Message, this);
return null;
}
}
and here is how it's being called:
Results = _searchService.Search(searchTerm, CurrentPage - 1, 10, contentTypes, searchFilters,
new GenericSortBuilder<SearchResultItem>(q => q.OrderByDescending(r => r.SearchDate)));
How do I add in date filtering so that it only returns items where the date is in the future?
I would add filter query to the list of existing ones filtering the date field. On the documentation page, I was able to find information about fluent API, which could help here
Query.Field("date").From(DateTime.Now)
I'm not C# developer, that this code could have some mistakes, but I think the main idea is clear what needs to be done.

C# (Xamarin iOS) How to loop son data on Custom UITableViewCell?

Any Help will be appreaciated :) Thank you in advance
I tried to loop other object inside of the function and its working but on this, it can't loop. Help. this is rush, and I'm not that familiar with creating iOS app.
public override void ViewDidLoad()
{
base.ViewDidLoad();
using (var web = new WebClient())
{
var url = "http://www.creativeinterlace.com/smitten/maintenance/api/feeds/get-miss-location/101";
json = web.DownloadString(url);
}
json = json.Replace("{\"location\":", "").Replace("}]}", "}]");
var ls = JArray.Parse(json);
if (ls.Count != 0)
{
foreach (var x in ls)
{
var name = x.SelectToken("location");
name1 = Convert.ToString(name);
var loc = x.SelectToken("address");
loc1 = Convert.ToString(loc);
var time = x.SelectToken("time_ago");
time1 = Convert.ToString(time);
locations = new List<Locations>
{
new Locations
{
shopname = name1,
address= loc1,
time = time1
},
};
}
nmtable.Source = new LocationSource(locations);
nmtable.RowHeight = 60;
nmtable.ReloadData();
}
}
You initialize the locations every time in the loop,so the list updates with only the newest object. You should initialize the list outside of the loop , and add object every time.
locations = new List<Locations>();
if (ls.Count != 0)
{
foreach (var x in ls)
{
var name = x.SelectToken("location");
name1 = Convert.ToString(name);
var loc = x.SelectToken("address");
loc1 = Convert.ToString(loc);
var time = x.SelectToken("time_ago");
time1 = Convert.ToString(time);
locations.Add(new Locations{ shopname = name1,address= loc1,time = time1});
};
}

How to withdraw ListFollower in listbox?

Using TweetSharp I am counting the list of followers. How can I withdraw it to the ListBox?
Here is the code:
var options = new ListFollowerIdsOfOptions() { ScreenName = "PutinRF" };
do
{
if (cursor != null)
options.Cursor = cursor;
var followersList = ts.ListFollowerIdsOf(options);
//listBox1.Items.AddRange(followersList.ToArray());
cursor = followersList.NextCursor;
} while (cursor != 0);
Try to use DataSource property:
listBox1.DataSource = followersList;
or look at following implementation:
var allIds = new List<long>();
var options = new ListFollowerIdsOfOptions() { ScreenName = "PutinRF" };
var followersIds = ts.ListFollowerIdsOf(options);
while (followersIds.NextCursor != 0)
{
options.Cursor = followersIds.NextCursor;
allIds.AddRange(followersIds);
}
listBox1.DataSource = allIds;
My decision:
var options = new ListFollowerIdsOfOptions { ScreenName = "PutinRF" };
List<long> All_ods = new List<long>();
TwitterCursorList<long> followerIDS = ts.ListFollowerIdsOf(options);
while(followerIDS.NextCursor!=null)
{
options.Cursor = followerIDS.NextCursor;
All_ods.AddRange(followerIDS.ToArray());
//listBox1.Items.Add(All_ods.ToArray());
listBox1.DataSource = All_ods;
label1.Text = "Получено: " + listBox1.Items.Count.ToString();
break;
}

Check for missing elements while using LINQ to XML

I am trying get data from the xml. Below is the code which
gets data from the XDocument and return list<t>.
However, p.Element("Sponsor") can sometimes be null. How can I check for the null values
var atClauseList = doc.Descendants(CLAUSE_GROUP_TAG).Descendants(AT_CLAUSE_TAG).Select(p => new AtClause()
{
ClauseNumber = (string)p.Element("Number"),
Sponsors = p.Element("Sponsor").Elements(SPONSOR_TAG).Select(y => y.Value)
.ToList(),
Page = p.Element("Sponsor").Element("aItem").Element("AmendText").Element("Page").ElementValueNull(),
Line = p.Element("Sponsor").Element("aItem").Element("AmendText").Element("Line").ElementValueNull(),
LineText = p.Element("Sponsor").Element("aItem").Element("AmendText").Nodes().OfType<XText>().FirstOrDefault().XTextValueNull(),
ItalicText = p.Element("Sponsor").Element("aItem").Element("AmendText").Element("Italic").ElementValueNull(),
ParaList = p.Element("Sponsor").Element("aItem").Element("AmendText").Elements("Para").Select(L => new Para
{
ParaText = (string)L,
Number = ((System.Xml.Linq.XElement)(L)).AttributeValueNull("Number"),
Quote = ((System.Xml.Linq.XElement)(L)).AttributeValueNull("Quote"),
}
).ToList()
}).ToList();
move your code out of an object initializer, and add some logic to it:
var atClauseList = new List<AtClause>();
foreach(var item in doc.Descendants(CLAUSE_GROUP_TAG).Descendants(AT_CLAUSE_TAG))
{
var atClause = new AtClause();
atClause.ClauseNumber = (string)item.Element("Number");
var sponsor = item.Element("Sponsor");
if (sponsor != null)
{
atClause.Sponsors = sponsor.Elements(SPONSOR_TAG).Select(y => y.Value).ToList();
atClause.Page = sponsor.Element("aItem").Element("AmendText").Element("Page").ElementValueNull();
atClause.Line = sponsor.Element("aItem").Element("AmendText").Element("Line").ElementValueNull();
atClause.LineText = sponsor.Element("aItem").Element("AmendText").Nodes().OfType<XText>().FirstOrDefault().XTextValueNull();
atClause.ItalicText = sponsor.Element("aItem").Element("AmendText").Element("Italic").ElementValueNull();
atClause.ParaList = sponsor.Element("aItem").Element("AmendText").Elements("Para").Select(L => new Para
{
ParaText = (string)L,
Number = ((System.Xml.Linq.XElement)(L)).AttributeValueNull("Number"),
Quote = ((System.Xml.Linq.XElement)(L)).AttributeValueNull("Quote"),
}).ToList();
atClauseList.Add(atClause);
}
You can use sequences rather than leaving the IEnumerable immediately:
var value = (string)p.Elements("Sponsor")
.Elements("aItem")
.Elements("AmendText")
.Elements("Page")
.SingleOrDefault()

EWS - How to search for items [message] between dates?

I am trying to search for message items between two dates from the inbox folder.
I use the following restrictionType but it throws this error:
firmt.RootFolder = null
What am I doing wrong?
There is some messages between the mentionned dates ;-)
Thanks for your suggestions.
using (ExchangeServiceBinding esb = new ExchangeServiceBinding())
{
esb.Url = ConfigurationManager.AppSettings["ExchangeWebServicesURL"].ToString();
esb.RequestServerVersionValue = new RequestServerVersion();
esb.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2007_SP1;
esb.PreAuthenticate = true;
esb.Credentials = new NetworkCredential(email, password);
FindItemType findItemRequest = new FindItemType();
// paging
IndexedPageViewType ipvt = new IndexedPageViewType();
ipvt.BasePoint = IndexBasePointType.Beginning;
ipvt.MaxEntriesReturned = nombreMessage;
ipvt.MaxEntriesReturnedSpecified = true;
ipvt.Offset = offset;
findItemRequest.Item = ipvt;
// filter by dates
AndType andType = new AndType();
List<SearchExpressionType> searchExps = new List<SearchExpressionType>();
RestrictionType restriction = new RestrictionType();
PathToUnindexedFieldType pteft = new PathToUnindexedFieldType
{
FieldURI = UnindexedFieldURIType.itemDateTimeSent
};
IsGreaterThanOrEqualToType IsGreaterThanOrEqualTo = new IsGreaterThanOrEqualToType
{
Item = pteft,
FieldURIOrConstant = new FieldURIOrConstantType
{
Item = new ConstantValueType
{
Value = DateTime.Today.AddDays(-6d).ToString()
}
}
};
searchExps.Add(IsGreaterThanOrEqualTo);
IsLessThanOrEqualToType IsLessThanOrEqualTo = new IsLessThanOrEqualToType
{
Item = pteft,
FieldURIOrConstant = new FieldURIOrConstantType
{
Item = new ConstantValueType
{
Value = DateTime.Today.AddDays(1d).ToString()
}
}
};
searchExps.Add(IsLessThanOrEqualTo);
andType.Items = searchExps.ToArray();
restriction.Item = andType;
findItemRequest.Restriction = restriction;
//// Define the sort order of items.
FieldOrderType[] fieldsOrder = new FieldOrderType[1];
fieldsOrder[0] = new FieldOrderType();
PathToUnindexedFieldType dateOrder = new PathToUnindexedFieldType
{
FieldURI = UnindexedFieldURIType.itemDateTimeReceived
};
fieldsOrder[0].Item = dateOrder;
fieldsOrder[0].Order = SortDirectionType.Descending;
findItemRequest.SortOrder = fieldsOrder;
findItemRequest.Traversal = ItemQueryTraversalType.Shallow;
// define which item properties are returned in the response
findItemRequest.ItemShape = new ItemResponseShapeType
{
BaseShape = DefaultShapeNamesType.IdOnly
};
// identify which folder to search
DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[1];
folderIDArray[0] = new DistinguishedFolderIdType { Id = DistinguishedFolderIdNameType.inbox };
// add folders to request
findItemRequest.ParentFolderIds = folderIDArray;
// find the messages
FindItemResponseType findItemResponse = esb.FindItem(findItemRequest);
//-------------
ArrayOfResponseMessagesType responseMessages = findItemResponse.ResponseMessages;
ResponseMessageType responseMessage = responseMessages.Items[0];
if (responseMessage is FindItemResponseMessageType)
{
FindItemResponseMessageType firmt = (responseMessage as FindItemResponseMessageType);
*******FindItemParentType fipt = firmt.RootFolder;********
object obj = fipt.Item;
// FindItem contains an array of items.
ArrayOfRealItemsType realitems = (obj as ArrayOfRealItemsType);
ItemType[] items = realitems.Items;
// if no messages were found, then return null -- we're done
if (items == null || items.Count() <= 0)
return null;
// FindItem never gets "all" the properties, so now that we've found them all, we need to get them all.
BaseItemIdType[] itemIds = new BaseItemIdType[items.Count()];
for (int i = 0; i < items.Count(); i++)
itemIds[i] = items[i].ItemId;
GetItemType getItemType = new GetItemType
{
ItemIds = itemIds,
ItemShape = new ItemResponseShapeType
{
BaseShape = DefaultShapeNamesType.AllProperties,
BodyType = BodyTypeResponseType.Text,
BodyTypeSpecified = true,
AdditionalProperties = new BasePathToElementType[] {
new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.itemDateTimeSent },
new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageFrom },
new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageIsRead },
new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageSender },
new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageToRecipients },
new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageCcRecipients },
new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageBccRecipients }
}
}
};
GetItemResponseType getItemResponse = esb.GetItem(getItemType);
messages = ReadItems(getItemResponse, items.Count());
}
I found the answer on my own after a long search about date format.
The restrictions has to be defined as this:
// greater or equal to
string dateStart = DateTime.Today.add(-6d);
string dateEnd = DateTime.Today.Add(1d);
PathToUnindexedFieldType dateSentPath = new PathToUnindexedFieldType();
dateSentPath.FieldURI = UnindexedFieldURIType.itemDateTimeSent;
IsGreaterThanOrEqualToType IsGreaterThanOrEqual = new IsGreaterThanOrEqualToType();
IsGreaterThanOrEqual.Item = dateSentPath;
FieldURIOrConstantType dateConstant = new FieldURIOrConstantType();
ConstantValueType dateConstantValue = new ConstantValueType();
dateConstantValue.Value = string.Format("{0}-{1}-{2}T00:00:00Z", dateStart.Year.ToString(), dateStart.Month.ToString(), dateStart.Day.ToString());
dateConstant.Item = dateConstantValue;
IsGreaterThanOrEqual.FieldURIOrConstant = dateConstant;
// less than or equal to
PathToUnindexedFieldType dateSentPath1 = new PathToUnindexedFieldType();
dateSentPath1.FieldURI = UnindexedFieldURIType.itemDateTimeSent;
IsLessThanOrEqualToType lessThanOrEqualTo = new IsLessThanOrEqualToType();
lessThanOrEqualTo.Item = dateSentPath1;
FieldURIOrConstantType dateConstant1 = new FieldURIOrConstantType();
ConstantValueType dateConstantValue1 = new ConstantValueType();
dateConstantValue1.Value = string.Format("{0}-{1}-{2}T00:00:00Z", dateEnd.Year.ToString(), dateEnd.Month.ToString(), dateEnd.Day.ToString());
dateConstant1.Item = dateConstantValue1;
lessThanOrEqualTo.FieldURIOrConstant = dateConstant1;
RestrictionType restriction = new RestrictionType();
AndType andType = new AndType();
andType.Items = new SearchExpressionType[] { lessThanOrEqualTo, IsGreaterThanOrEqual };
restriction.Item = andType;
findItemRequest.Restriction = restriction;
Hope this help someone some day ;-)
In case anyone stumbles upon this in the future, EWS has gotten even more strict about date formatting. The accepted answer formatting works for 2 digit months, but it does not for single digit months.
The formatting that works in all cases is:
DateTime.Today.AddDays(15).ToString("yyyy-MM-ddThh:mm:ssZ")
The restriction also works using the "Sortable date/time pattern".
Datetime.Now.ToString("s")

Categories

Resources