linq-to-twitter Twitter flood get - asp.net-mvc

I tried the code below but again it wasn't exactly as I wanted.
Only 1 pearl flood is coming. There are 90 floods.
RT ones should not come and should only come flood by call.
as an example I shared the picture. What do I have to do in this situation.
const int MaxSearchEntriesToReturn = 100;
const int SearchRateLimit = 180;
string searchTerm = "HANEDANLAR MASASININ YER ALTI EGEMENLİĞİ:RİO TİNTO";
// oldest id you already have for this search term
ulong sinceID = 1;
// used after the first query to track current session
ulong maxID;
var combinedSearchResults = new List<Status>();
List<Status> searchResponse =
await
(from search in ctx.Search
where search.Type == SearchType.Search &&
search.Query == searchTerm &&
search.Count == MaxSearchEntriesToReturn &&
search.SinceID == sinceID &&
search.TweetMode == TweetMode.Extended
select search.Statuses)
.SingleOrDefaultAsync();
if (searchResponse != null)
{
combinedSearchResults.AddRange(searchResponse);
ulong previousMaxID = ulong.MaxValue;
do
{
// one less than the newest id you've just queried
maxID = searchResponse.Min(status => status.StatusID) - 1;
Debug.Assert(maxID < previousMaxID);
previousMaxID = maxID;
searchResponse =
await
(from search in ctx.Search
where search.Type == SearchType.Search &&
search.Query == searchTerm &&
search.Count == MaxSearchEntriesToReturn &&
search.MaxID == maxID &&
search.SinceID == sinceID &&
search.TweetMode == TweetMode.Extended
select search.Statuses)
.SingleOrDefaultAsync();
combinedSearchResults.AddRange(searchResponse);
} while (searchResponse.Any() && combinedSearchResults.Count < SearchRateLimit);
combinedSearchResults.ForEach(tweet =>
Console.WriteLine(
"\n User: {0} ({1})\n Tweet: {2}",
tweet.User.ScreenNameResponse,
tweet.User.UserIDResponse,
tweet.Text ?? tweet.FullText)
);
}
else
{
Console.WriteLine("No entries found.");
}
ViewBag.Twet = combinedSearchResults.ToList();

I own LINQ to Twitter. A paged search can return more values. Here's an example:
const int MaxSearchEntriesToReturn = 100;
const int SearchRateLimit = 180;
string searchTerm = "Flood Name";
// oldest id you already have for this search term
ulong sinceID = 1;
// used after the first query to track current session
ulong maxID;
var combinedSearchResults = new List<Status>();
List<Status> searchResponse =
await
(from search in twitterCtx.Search
where search.Type == SearchType.Search &&
search.Query == searchTerm &&
search.Count == MaxSearchEntriesToReturn &&
search.SinceID == sinceID &&
search.TweetMode == TweetMode.Extended
select search.Statuses)
.SingleOrDefaultAsync();
if (searchResponse != null)
{
combinedSearchResults.AddRange(searchResponse);
ulong previousMaxID = ulong.MaxValue;
do
{
// one less than the newest id you've just queried
maxID = searchResponse.Min(status => status.StatusID) - 1;
Debug.Assert(maxID < previousMaxID);
previousMaxID = maxID;
searchResponse =
await
(from search in twitterCtx.Search
where search.Type == SearchType.Search &&
search.Query == searchTerm &&
search.Count == MaxSearchEntriesToReturn &&
search.MaxID == maxID &&
search.SinceID == sinceID &&
search.TweetMode == TweetMode.Extended
select search.Statuses)
.SingleOrDefaultAsync();
combinedSearchResults.AddRange(searchResponse);
} while (searchResponse.Any() && combinedSearchResults.Count < SearchRateLimit);
combinedSearchResults.ForEach(tweet =>
Console.WriteLine(
"\n User: {0} ({1})\n Tweet: {2}",
tweet.User.ScreenNameResponse,
tweet.User.UserIDResponse,
tweet.Text ?? tweet.FullText));
}
else
{
Console.WriteLine("No entries found.");
}
There are a few things to pay attention to:
Set Count to MaxSearchEntriesToReturn because it defaults to 15 and you want to minimize the number of queries.
The while loop checks SearchRateLimit because there are rate limits that will cause you to get an HTTP 429. The rate limit for App-Only is higher than the 180 I've added here.
Notice how I'm using SinceID and MaxID to page through results. See Working with Timelines in the Twitter API docs to understand what those are.
Also, please read the Search API docs and notice that the standard search API is focused on relevance and not completeness.

Related

How to add check condition if student already paid the fee of current moth in ASP.NET MVC 5

I want to add check condition if student paid the fee of current month so I want to show message the student fee is already paid
public ActionResult EditFees(StudentMV studentMV)
{
string currentMonth = DateTime.Now.Month.ToString();
var check = DB.tblStudents.Where(s => s.AdmissionNO == studentMV.AdmissionNO && s.FeeID != studentMV.FeeID && s.tblFee.Date == DateTime.Now).FirstOrDefault();
if (check == null )
{
var checkstudent = DB.tblStudents.Find(studentMV.StudentID);
checkstudent.StudentID = studentMV.StudentID;
checkstudent.AdmissionNO = studentMV.AdmissionNO;
checkstudent.Name = studentMV.Name;
checkstudent.FatherName = studentMV.FatherName;
checkstudent.tblFee.FeeID = studentMV.FeeID;
checkstudent.tblFee.AdmissionFee = studentMV.AdmissionFee;
checkstudent.tblFee.TutionFee = studentMV.TutionFee;
checkstudent.tblFee.Stationary = studentMV.Stationary;
checkstudent.tblFee.SportFee = studentMV.SportFee;
checkstudent.tblFee.Received = studentMV.Received;
checkstudent.tblFee.Balance = studentMV.Balance;
checkstudent.tblFee.Date = studentMV.Date;
DB.Entry(checkstudent).State = System.Data.Entity.EntityState.Modified;
DB.SaveChanges();
return RedirectToAction("Fees");
}
else
{
ModelState.AddModelError("TutionFee", "Already Paid!");
}
return View(studentMV);
You need to remove the date condition from the LINQ query
s.tblFee.Date == DateTime.Now;
Add below condition in Query
s.tblFee.Month == DateTime.Now.Month && s.tblFee.Year == DateTime.Now.Year;
We need to check the current month as well as year also, otherwise, it gives an error while next year you are paid a fees in your portal

How do I make Last Edit timestamp specific to each tab, with multiple tabs to be added in future?

UPDATE: Got this to work with the following script:
function onEdit(e) {
var range = e.range;
var sheet = range.getSheet();
var name = sheet.getName();
var currentDate = new Date();
//variable
var startRow = 1;
//get modified row and column
var row = e.range.getRow();
var col = e.range.getColumn();
var currentDate = new Date();
if(col === 7 && row === 3 && sheet.getRange(1,14).getValue() == "" &&
sheet.getName() != "4-Transfer Walkthru" &&
sheet.getName() != "1-Cover Sheet" &&
sheet.getName() != "2-Inventory" &&
sheet.getName() != "3-Template"){
sheet.getRange(1,14).setValue(currentDate);
}
else if(row >= startRow){
sheet.getRange(2,14).setValue(currentDate);
}
}
Original Post:
I'm attempting to add a "last edited" timestamp to a cell within each tab of a doc that has many tabs, and will continue to have more tabs added/removed. Everything I've found so far either creates a timestamp whenever anything within the entire doc is edited, or it requires listing out each tab name in the script (which is not ideal as the tabs in this doc are ever-changing).
Is there a way to make edit timestamps specific to each tab, without having to list out each tab's name?
Here's what I have so far, which included a timestamp for when the tab is first created (run by any edits made to cell J3), as well as the timestamp that updates across all tabs any time anything is edited in entire doc:
function onEdit(e) {
addTimestamp(e);
}
function addTimestamp(e){
//variable
var startRow = 1;
//get modified row and column
var row = e.range.getRow();
var col = e.range.getColumn();
var currentDate = new Date();
if(col === 7 && row === 3 && e.source.getActiveSheet().getRange(1,14).getValue() == ""){
e.source.getActiveSheet().getRange(1,14).setValue(currentDate);
}
if(row >= startRow &&
e.source.getActiveSheet().getName() != "Transfer Walkthru" &&
e.source.getActiveSheet().getName() != "Cover Sheet" &&
e.source.getActiveSheet().getName() != "Inventory" &&
e.source.getActiveSheet().getName() != "Template"){
e.source.getActiveSheet().getRange(2,14).setValue(currentDate);
}
}
ETA: Example sheet
Thank you!
onEdit allows you to access the event object range from which you cn deduct the sheet where the edit took place
Then you can implement conditional statements into your code to specify what shall happen depending on which sheet has been edited.
The problem with your code is probably due to e.source.getActiveSheet() because the active sheet might not always be the edited sheet.
I recommend you to retrieve the sheet with e.range.getSheet() instead.
Sample:
function onEdit(e) {
var range = e.range;
var sheet = range.getSheet();
var name = sheet.getName();
var currentDate = new Date();
//variable
var startRow = 1;
//get modified row and column
var row = e.range.getRow();
var col = e.range.getColumn();
var currentDate = new Date();
if(col === 7 && row === 3 && sheet.getRange(1,14).getValue() == ""){
sheet.getRange(1,14).setValue(currentDate);
}
else if(row >= startRow &&
sheet.getName() != "Transfer Walkthru" &&
sheet.getName() != "Cover Sheet" &&
sheet.getName() != "Inventory" &&
sheet.getName() != "Template"){
sheet.getRange(2,14).setValue(currentDate);
}
}

SpreadSheet cell auto fill with value of another cell

I need a script that autofills a cell with the values of a cell in the same row, but in a different (but fixed) column.
I have tried this script, but I can't get it to write the Value of anything but the cell itself.
function onEdit(event) {
var sheet = event.source.getActiveSheet();
var range = event.source.getActiveRange();
if (sheet.getSheetName() == "Tweet" && range.getColumn() == 2 && range.getValue().toString().trim() !== "" && range.getValue().indexOf("http:") != 0) {
range.setValue("http://test.com/" + range.getValue());
}
Try this:
function onEdit(event) {
var sheet = event.source.getActiveSheet();
var range = event.source.getActiveRange();
var fixed_column = 6; //Substitute this to your fixed column number.
if (sheet.getSheetName() == "Tweet" && range.getColumn() == 2 && range.getValue().toString().trim() !== "" && range.getValue().indexOf("http:") != 0) {
range.setValue("http://test.com/" + sheet.getRange(range.getRow(),fixed_column).getValue());
}
}
Just substitute the number of your fixed column.

Filtering IQueryable result set using parameters

I'm getting confused with this and I know there will be a more slick way of starting it off. The 'result' variable has many records and I want to check if IN_SiteId is > 0 and filter on it, same after that for LandownerId and PaymentCategoryId etc. If I can get the right approach for the first 2 I will be ok from there. This should be easier but having a brick wall day. Any comments appreciated
public IQueryable rptRentPaidMonthly(int IN_SiteId, int IN_LandownerId, int IN_PaymentCategoryId, int IN_PaymentTypeId, string IN_ShowRelevantProportion)
{
var result = this._lmsDb.rptRentPaidMonthly(IN_daysFrom, IN_daysTo, IN_SiteId, IN_LandownerId, IN_PaymentCategoryId, IN_PaymentTypeId, IN_ShowRelevantProportion);
if (IN_SiteId > 0)
{
var searchResults = (from s in result
where (s.SiteId == #IN_SiteId)
select s);
return searchResults.AsQueryable();
}
return result.AsQueryable();
}
I'm not a LINQ expert but I think you can do something like this:
public IQueryable rptRentPaidMonthly(int IN_SiteId, int IN_LandownerId, int IN_PaymentCategoryId, int IN_PaymentTypeId, string IN_ShowRelevantProportion)
{
var result = this._lmsDb.rptRentPaidMonthly(IN_daysFrom, IN_daysTo, IN_SiteId, IN_LandownerId, IN_PaymentCategoryId, IN_PaymentTypeId, IN_ShowRelevantProportion);
var searchResults = (from s in result
where (IN_SiteId <= 0 || s.SiteId == IN_SiteId)
&& (IN_LandownerId <= 0 || s.LandownerId == IN_LandownerId)
&& (IN_PaymentCategoryId <= 0 || s.PaymentCategoryId == IN_PaymentCategoryId)
&& (IN_PaymentTypeId <= 0 || s.PaymentTypeId == In_PaymentTypeId)
select s);
return searchResults.AsQueryable();
}
The where clause checks if each filter value is less than or equal to 0, if so then it will return true and will not evaluate the next bit which attempts to filter the actual field on the value provided.

ASP.Net MVC Database Driven Menu Strange HTML output

I have a database driven menu Helper that gets called from within my master page:
<div class="topBar">
<%= Html.MenuTree(39, false, "first", "last") %>
<div class="clear"></div>
</div>
Below is the code that outputs my HTML unordered list. The problem is that sometimes the output of the menu is completely wrong and all over the place ie. sub menu items appear as equal as top menu items.
I cannot find any pattern to why it does it so thought I'd post the code to see if anyone can spot the problem. My only other thought is that somehow its half cached half called and mixes the output.
This is what it should look like Correct http://img718.imageshack.us/img718/9317/screenshot20100328at120.png
Sometimes it comes out like this:alt text http://img413.imageshack.us/img413/9317/screenshot20100328at120.png
Here's the code (the boolean IsAdmin is false in this scenario):
public static string MenuTree(this HtmlHelper helper, int MenuCategoryID, bool Admin, string firstCssClass, string lastCssClass)
{
//TODO: Check for Subsonic fix for UNION bug
IOrderedQueryable<Menu> menuItems;
if (Admin)
{
menuItems = (from menu2 in Menu.All()
join pages in WebPage.All() on menu2.PageID equals pages.ID
join pagesRoles in PageRole.All() on pages.ID equals pagesRoles.PageID
join roles in aspnet_Role.All() on pagesRoles.RoleId equals roles.RoleId
where Roles.GetRolesForUser().Contains(roles.RoleName) && menu2.CategoryID == MenuCategoryID && menu2.Visible
select menu2).Distinct().OrderBy(f => f.OrderID);
}
else
{
menuItems = (from menu2 in Menu.All()
join pages in WebPage.All() on menu2.PageID equals pages.ID
where menu2.CategoryID == MenuCategoryID && menu2.Visible
select menu2).Distinct().OrderBy(f => f.OrderID);
}
var nonlinkedmenuItems = (from menu in Menu.All().Where(x => x.PageID == null && x.CategoryID == MenuCategoryID && x.Visible).OrderBy(f => f.OrderID) select menu);
var allCategories = menuItems.ToList().Concat<Menu>(nonlinkedmenuItems.ToList()).OrderBy(p => p.OrderID).ToList();
allCategories.ForEach(x => x.Children = allCategories.Where(y => y.ParentID == x.ID).OrderBy(f => f.OrderID));
Menu home = null;
if (Admin)
{
home = (from menu in Menu.All()
join pages in WebPage.All() on menu.PageID equals pages.ID
where pages.MenuName == "Home" && pages.IsAdmin
select menu).SingleOrDefault();
}
IEnumerable<Menu> topLevelItems;
if (Admin)
topLevelItems = allCategories.Where(f => f.ParentID == 0 && (f.Children.Count() > 0 || f.ID == home.ID));
else
topLevelItems = allCategories.Where(f => f.ParentID == 0);
var topLevelItemList = topLevelItems.ToList();
sbMenu.Length = 0;
sbMenu.AppendLine("<ul>");
LoopChildren(helper, Admin, topLevelItemList, 0, firstCssClass, lastCssClass);
sbMenu.AppendLine("</ul>");
string menuString = sbMenu.ToString();
//if ((menuString.IndexOf("<li>")) > 0)
// menuString = menuString.Insert((menuString.IndexOf("<li>") + 3), " class='first'");
//if (menuString.LastIndexOf("<li>\r\n") > 0)
// menuString = menuString.Insert((menuString.LastIndexOf("<li>\r\n") + 3), " class='last'");
return sbMenu.ToString();
}
private static void LoopChildren(this HtmlHelper helper, bool Admin, List<Menu> CurrentNode, int TabIndents, string firstCssClass, string lastCssClass)
{
for (int i = 0; i < CurrentNode.Count; i++)
{
sbMenu.Append(Tabs(TabIndents + 1));
string linkUrl = "";
string urlTitle = "";
if (CurrentNode[i].PageID != null)
{
WebPage item = WebPage.SingleOrDefault(x => x.ID == CurrentNode[i].PageID);
linkUrl = item.URL;
urlTitle = item.MenuName;
}
else
{
linkUrl = CurrentNode[i].URL;
urlTitle = CurrentNode[i].Title;
}
//Specify a RouteLink so that when in Error 404 page for example the links don't become /error/homepage
//If in admin we can manually write the <a> tag as it has the controller and action in it
bool selected = false;
if (helper.ViewContext.RouteData.Values["pageName"] != null && helper.ViewContext.RouteData.Values["pageName"].ToString() == linkUrl)
selected = true;
string anchorTag = Admin ? "<a href='" + linkUrl + "'>" + urlTitle + "</a>" : helper.RouteLink(urlTitle, new { controller = "WebPage", action = "Details", pageName = linkUrl });
if (TabIndents == 0 && i == 0 && firstCssClass != null)
sbMenu.AppendLine("<li class='" + firstCssClass + "'>" + anchorTag);
else if (TabIndents == 0 && i == (CurrentNode.Count - 1) && lastCssClass != null)
sbMenu.AppendLine("<li class='" + lastCssClass + "'>" + anchorTag);
else if (selected)
sbMenu.AppendLine("<li class='selected'>" + anchorTag);
else
sbMenu.AppendLine("<li>" + anchorTag);
if (CurrentNode[i].Children != null && CurrentNode[i].Children.Count() > 0)
{
sbMenu.Append(Tabs(TabIndents + 2));
sbMenu.AppendLine("<ul>");
LoopChildren(helper, Admin, CurrentNode[i].Children.ToList(), TabIndents + 2, "", "");
sbMenu.Append(Tabs(TabIndents + 2));
sbMenu.AppendLine("</ul>");
}
sbMenu.Append(Tabs(TabIndents + 1));
sbMenu.AppendLine("</li>");
}
}
private static string Tabs(int n)
{
return new String('\t', n);
}
I agree with the comments that string concatenation for this is painful. TagBuilder is a lot less painful for you.
I didn't check your code for problems, but I imagine that what I would do is basically to take the text output from your helper in a good case and a bad case and run them through a diff tool. Leave some markers before and after the point where you call Html.MenuTree() for debugging purposes - this way you will know exactly where the output starts and stops.
The diff tool will tell you what the differences in the two outputs are. Then you can go looking for the cause of these differences.
Another way I would seriously consider approaching this is through unit testing. Start with a simple unit test giving the MenuTree() method a very simple structure to work with. Verify that the output is sane. Then test more complex scenarios. If you during testing, debugging or in production discover a certain combination of input that causes the problem, write a unit test that tests for the correct output. Then fix it. When the test passes, you'll know that you are finished. Also, if you run your tests whenever you change something, you will know that this particular bug will never creep back in.
New bug? New unit test. And so on. Unit tests never solve the problem for you, but they give you the confidence to know that what used to work still works, even when you refactor and come up with cool new stuff.

Resources