Where in event cycle does gridview get datasource - c#

I'm trying to achieve the same thing as this poster and I'm following what one of the answers says I need to do.
Here is my method
public void DisplayItemRangeForCurrentPage()
{
var totalRecords = ((DataView)gvMagicalSearchResults.DataSource).Count;
var endRecord = gvMagicalSearchResults.PageSize * (gvMagicalSearchResults.PageIndex + 1);
var startsRecods = endRecord - gvMagicalSearchResults.PageSize;
if (endRecord > totalRecords)
endRecord = totalRecords;
if (startsRecods == 0) startsRecods = 1;
if (endRecord == 0) endRecord = totalRecords;
var str = new StringBuilder();
str.Append((string)HttpContext.GetGlobalResourceObject("magicalResx", "GrivSearchCountMessage_Shows"));
str.Append(" " + startsRecods + " - " + endRecord + " ");
str.Append((string)HttpContext.GetGlobalResourceObject("magicalResx", "GrivSearchCountMessage_OfTotal"));
str.Append(" " + totalRecords + " ");
ltrResultsCount.Text = str.ToString();
}
No matter where I call this method it throws an "Object not set to an instance of an object" error on the var totalRecords = ((DataView)gvMagicalSearchResults.DataSource).Count; line.
I tried calling it in several GridView/ObjectDataSource events. I tried calling it in PreRender, OnLoad, Render - Alas, none of them worked...
So can anyone tell me where in the event cycle a gridview gets its datasource?

It happens on the GridView.OnDataBound:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.basedataboundcontrol.databound%28v=vs.90%29.aspx

Related

Pass parameter to a method and read the return value?

Having this code:
var code = "public class TestClass {" +
" public int HelloWorld(int num) {" +
" return 5 + num;" +
" }" +
"}";
var script = CSharpScript.Create(code);
var x = (await script.RunAsync()).ReturnValue;
How does one pass a value for the parameter, call the method and read the return value?
Continue with another code is the simplest.
var call = await script.ContinueWith<int>("new TestClass().HelloWorld(3)").RunAsync();
var x = call.ReturnValue;
By the way, CSharpScript is a scripting engine which does not require you having class and method like ordinary C# program. You can just use 5 + num as script content.
var code = "5 + num";
var numValue = 3;
var setParam = await CSharpScript.RunAsync("var num = " + numValue + ";");
var runCode = await setParam.ContinueWithAsync(code);
var x = runCode.ReturnValue;
For full example, take a look of RoslynScript/Script.cs

How to get the next page of results from Bing Search Container in C#?

I am using the BingSearchContainer.cs with a Winform in C#. I am returning the results using the following code. After a good couple of hours looking I can't figure out how to return the other pages of results. It is only possible to return a maximum of 50 results at a time. I would like to return more pages and then add these to "imageSet" to have a full list of resulting images. Any hints or pointers would be really useful, thanks in advance for any help.
void bingSearch(string searchTerm)
{
try
{
imageSet = new List<Bing.ImageResult>();
const string bingKey = "[key]";
var bing = new BingSearchContainer(
new Uri("https://api.datamarket.azure.com/Bing/Search/")) { Credentials = new NetworkCredential(bingKey, bingKey) };
var query = bing.Image("\"" + searchTerm + "\"" + "(" + site1 + " OR " + site2 + ")", null, null, null, null, null, ImageFilters);
Debug.Print("Full Search: " + query.ToString());
query = query.AddQueryOption("$top", 50);
query = query.AddQueryOption("$skip", 20);
var results = query.Execute();
int index = 0;
foreach (var result in results)
{
imageSet.Add(result);
Debug.Print("URL: " + imageSet[index].MediaUrl);
index++;
}
Debug.Print("Results: " + imageSet.Count);
}
catch
{
Debug.Print("Error");
}
}
Solved this.
Actually it is very simple. The "$skip", 20 query option sets the off-set for the pages such that if I have an off-set of 0 I get the first 50 images, an off-set of 50 I get the next 50 images and so on.

Pageddatasource fails paging With "does not implement ICollection."

I've a Repeater and I need paging, so I'm using PagedDatasource.
Given:
string tag = Request.QueryString["category"];
and tag variable is NOT empty then PagedDataSource fails paging with the following error:
Exception Details: System.Web.HttpException: Cannot compute Count for
a data source that does not implement ICollection.
at this line:
lblCurrentPage.Text = "Page: " + (CurrentPage + 1).ToString() + " of " + pagedDS.PageCount.ToString();
NOTE: When tag variable IS empty then paging works fine.
Full code below:
string tag = Request.QueryString["category"];
var ba = new DataBase.BlogAdapter();
PagedDataSource pagedDS = new PagedDataSource();
pagedDS.AllowPaging = true;
pagedDS.PageSize = 3;
if (String.IsNullOrEmpty(tag))
{
pagedDS.DataSource = ba.GetArticles(null, null);
}
else
{
var t = new DataBase.Tag() { TagName = tag };
var tec = new DataBase.TagEqualityComparer();
pagedDS.DataSource = ba.GetArticles(null, null).Where(a => a.Tags.Contains(t, tec));
CurrentPage = 0;
}
pagedDS.CurrentPageIndex = CurrentPage;
// NEXT LINE FAILS IF "tag" IS NOT EMPTY
lblCurrentPage.Text = "Page: " + (CurrentPage + 1).ToString() + " of " + pagedDS.PageCount.ToString();
You probably need to materialise the filter as a collection, e.g.
ba.GetArticles(null, null).Where(a => a.Tags.Contains(t, tec)).ToList();
IQueryable<> only implements IEnumerable, whereas IList<> implements ICollection.

error: The query results cannot be enumerated more than once

Edit:
DataClassesDataContext dc = new DataClassesDataContext();
string _idCompany = Request["idCompany"];
var newes = dc.GetNewsCompany(Int64.Parse(_idCompany));
string date = "";
string newsHtml = "<center>";
if(newes.GetEnumerator().MoveNext()){
foreach (var item in newes)//say Error .......................
{
// date = calendar.GetDayOfMonth(item.DateSend) + "/" + calendar.GetMonth(item.DateSend) + "/" + calendar.GetYear(item.DateSend).ToString();
// newsHtml += "<li class='news-item'><a style='text-decoration:none' class=\"link\" onclick=\"$(\'#BodyNews\').text(\'" + HttpUtility.HtmlEncode(item.Body).Trim() + "\');$(\'#BodyNews\').dialog({resizable:false});\" href=\"#\" > " + item.Title.ToString() + "</a> " + date + " </li>";
}
newsHtml += "</center>";
}
else
{
// var propertyCompany = dc.GetPropertyCompanyById(Int64.Parse(_idCompany));
// newsHtml += "<li class='news-item'><a style='text-decoration:none' class=\"link\" );$(\'#BodyNews\').dialog({resizable:false});\" href=\"#\" > " + "!به صفحه شخصی شرکت " + propertyCompany.FirstOrDefault().NameCompany + " خوش آمدید " + "</a> " + date + " </li>";
}
return newsHtml;
say error:The query results cannot be enumerated more than once
how check var is empty or null with out enumerated;
Why bother with the if at all?
var newes = dc.GetNewsCompany(Int64.Parse(_idCompany));
//if (newes.GetEnumerator().MoveNext())//check is null or empty
var newesList = newes.ToList();
if (neweList.Count > 0)
{
...
}
You can always check the newesList.Count property afterward.
Not sure what's available as a member in newes, but if it's an object and depending on what dc.GetNewsCompany returns you could check for null
if (news == null) return;
or if it returns an empty collection/array, just check the count/length:
if (news.Count == 0) return;
if (news.Length == 0) return;
the error comes, because you are using .GetEnumerator() on newes and then using the newes again in a foreach Loop .. this causes the "double enumeration".
Generally avoid walking "such var"'s with a foreach, since the DataReader is locked the whole loop !. Means that you cannot use the same entitie in this loop.
Better .ToList() , you can the list.AsQuearable agian if you want to Linq on it
f.e. something like
var newes = dc.CompanyTable.Where(ln => ln.id.Equals(_idCompany));;
List<CompanyTable> newesList = newes.ToList();

client.get("me/statuses") returns empty "data" array using C# Facebook SDK 5.0.3

Using the C# Facebook SDK 5.0.3 everything works fine whit the client.Get("/me").
But when retrieving the status, I should get aan arraylist "data" with all the status messages according to the facebook Graph API, but instead my data array is empty and I get a 'Index out of bounds' exception.
Does anyone have an idea what my problem could be?
if (Request.Params["code"] != null)
{
var client = new FacebookClient(GetAccessToken());
dynamic me = client.Get("/me");
imgUser.ImageUrl = "https://graph.facebook.com/" + me.id + "/picture";
lblUsername.Text = me.name;
lblHometown.Text = me.hometown.name;
lblBirthday.Text = me.birthday;
lblCurrenttown.Text = me.location.name;
lblEmail.Text = me.email;
lblOpleidingen.Text = "";
lblOpleidingen.Text += me.education[1].type + ": " + me.education[1].school.name + ", " + me.education[1].year.name + "<br />"
+ me.education[0].type + ": " + me.education[0].school.name + ", " + me.education[0].year.name;
lblSex.Text = me.gender;
dynamic status = client.get("/me/statuses");
txtStatus.Text = status.data[0].message;
}
It requires the read_stream permission. Ensure you have it.
Your permission array should look like follows:
string[] extendedPermissions = new[] { "user_about_me", "read_stream" };
if (extendedPermissions != null && extendedPermissions.Length > 0)
{
var scope = new StringBuilder();
scope.Append(string.Join(",", extendedPermissions));
parameters["scope"] = scope.ToString();
}
furthermore your second get() should be capitalized: Get()
dynamic status = client.get("/me/statuses");
dynamic status = client.Get("/me/statuses");

Categories