I have stored resumes in my database and i have retrive it from asp.net web page by creating linkbutton...i can view ,download the resumes which i stored in my database.My issuse is when i view one resume example (domnic resume)then no of visitor for domnic resume should be count .if again i view that resume no of visitor should be 2...how can i do that in asp.net?
There are a ton of ways to do this, each have their quirks. Here is a quick and dirty way to do it, the only thing to remember is that the Session_OnEnd can be a bit flaky.
public void Application_OnStart(Object sender, EventArgs e)
{
Hashtable ht = (Hashtable)Application["SESSION_LIST"];
if(ht == null)
{
ht = new Hashtable();
lock(Application)
{
Application["SESSION_LIST"] = ht;
Application["TOTAL_SESSIONS"] = 0;
}
}
}
public void Session_OnStart(Object sender, EventArgs e)
{
Hashtable ht = (Hashtable)Application["SESSION_LIST"];
if(ht.ContainsKey(Session.SessionID) == false)
{
ht.Add(Session.SessionID, Session);
}
lock(Application)
{
int i = (int)Application["TOTAL_SESSIONS"];
i++;
Application["TOTAL_SESSIONS"] = i;
}
}
public void Session_OnEnd(Object sender, EventArgs e)
{
Session.Clear();
Hashtable ht = (Hashtable)Application["SESSION_LIST"];
ht.Remove(Session.SessionID);
lock(Application)
{
int i = (int)Application["TOTAL_SESSIONS"];
i--;
Application["TOTAL_SESSIONS"] = i;
}
}
Here's another way...
Membership.GetNumberOfUsersOnline();
You can keep track of no of views displayed by keeping the count in the database or a persistent storage of your choice. Whenever a particular resume view is requested, update the view count for that resume. You may disclose some elements of the design you have done to get more specific answers.
If you just want to see this count as a developer/admin, and you have interest in collecting stats site-wide, you may also look into using Google Analytics.
Related
I am new to aspx and can not get my web timer to work. What am I missing here? Also DebugSet.logoutTime = 1800000 and DebugSet.logotWarnings = 3. The user is to be warned every minute before they are logged out of the system. These settings will be raised before the release, I just lowered them for testing purposes.
public partial class test : System.Web.UI.Page
{
private LoggedUser _User;
private Timer LogoutTimer;
private int TmCnt = 0;
protected void Page_Load(object sender, EventArgs e)
{
_User = new LoggedUser(true);
SetTimer();
}
private void SetTimer()
{
LogoutTimer = new Timer();
LogoutTimer.Interval = DebugSet.logoutTime/DebugSet.logoutWarnings;
LogoutTimer.Tick += new EventHandler<EventArgs>(LogoutTimer_Tick);
LogoutTimer.Enabled = true;
LogoutTimer.ViewStateMode = ViewStateMode.Enabled;
}
private void LogoutTimer_Tick(object sender, EventArgs e)
{
TmCnt++;
if (TmCnt == DebugSet.logoutWarnings)
{
_User.UserLoggedIn = false;
_User.SetSessions();
LogoutTimer.Enabled = false;
HttpContext.Current.Session["FCSWarning"] = "LoggedOut";
Response.Redirect("../Views/index.aspx");
}
else
{
int i = (DebugSet.logoutTime / (1000 * 60)) - ((DebugSet.logoutTime / (1000 * 60)) * TmCnt);
string msg = "<Script language=javascript>alert('You will be logged out in " + i.ToString() + " min. due to inactivity.');</Script>";
Response.Write(msg);
}
}
}
The ASP.NET Timer is an ASP.NET control. Each ASP.NET control must be added into a page control hierarchy, otherwise, it won't operate correctly or won't operate at all.
Add your Timer to page control hierarchy:
LogoutTimer = new Timer();
LogoutTimer.ID = "MyTimer";
this.Controls.Add(LogoutTimer);
LogoutTimer.Interval = DebugSet.logoutTime/DebugSet.logoutWarnings;
...
You are using a winforms timer (I think). With websites all instances of variables and classes are destroyed when the page is send to the browser (garbage collection). So LogoutTimer only exists for a very short time. You need to use the Timer control.
https://msdn.microsoft.com/en-us/library/bb386404.aspx
You should know this also when working with websites, the Page Life Cycle:
https://msdn.microsoft.com/en-us/library/ms178472.aspx
i need to programmatically detect when Google bot or any other search engine bot crawl our web site page. i have logic in Application_BeginRequest of my global.asax that when any page is requested then i try to read two cookies value and if anyone is missing then i redirect user to a specific page from where user select country and from there few cookies are dropped in user pc.
protected void Application_BeginRequest(Object sender, EventArgs e)
{
string strCountryCookie = BBAreman.CountryCookie.GetCookieValue();
string strShippingCookie = BBAreman.CountryCookie.GetShippingCookieValue();
if (Request.Url.ToString().IndexOf(".asmx") == -1)
{
if (strCountryCookie.Trim() == "" || strShippingCookie.Trim() == "")
{
if (Request.Url.GetLeftPart(UriPartial.Authority).ToString() + "/index.aspx?ShowCountry=true" != HttpContext.Current.Request.Url.ToString())
{
Response.Redirect("~/index.aspx?ShowCountry=true");
}
}
}
}
now when Google bot access any of our page then bot is redirecting to a specific page and not being able to access any of page. as a result our web site is loosing ranking.
i never face this situation.so guys please guide me how to handle this situation. thanks
EDIT
i got a routine like
If(Request.Browser.Crawler) Then
'this is a web bot
Else
'this is a regular user
End If
i guess the above way i can detect that bot is crawling my page or any human? just tell me am i on right track or not ?
Solved
i solved it this way
public class Utility
{
public static bool IsCrawlByBot()
{
List<string> Crawlers = new List<string>()
{
"googlebot","bingbot","yandexbot","ahrefsbot","msnbot","linkedinbot","exabot","compspybot",
"yesupbot","paperlibot","tweetmemebot","semrushbot","gigabot","voilabot","adsbot-google",
"botlink","alkalinebot","araybot","undrip bot","borg-bot","boxseabot","yodaobot","admedia bot",
"ezooms.bot","confuzzledbot","coolbot","internet cruiser robot","yolinkbot","diibot","musobot",
"dragonbot","elfinbot","wikiobot","twitterbot","contextad bot","hambot","iajabot","news bot",
"irobot","socialradarbot","ko_yappo_robot","skimbot","psbot","rixbot","seznambot","careerbot",
"simbot","solbot","mail.ru_bot","spiderbot","blekkobot","bitlybot","techbot","void-bot",
"vwbot_k","diffbot","friendfeedbot","archive.org_bot","woriobot","crystalsemanticsbot","wepbot",
"spbot","tweetedtimes bot","mj12bot","who.is bot","psbot","robot","jbot","bbot","bot"
};
string ua = HttpContext.Current.Request.UserAgent.ToLower();
bool iscrawler = Crawlers.Exists(x => ua.Contains(x));
return iscrawler;
}
}
protected void Application_BeginRequest(Object sender, EventArgs e)
{
//if (!Request.Browser.Crawler)
if (!Utility.IsCrawlByBot())
{
string strCountryCookie = BBAreman.CountryCookie.GetCookieValue();
string strShippingCookie = BBAreman.CountryCookie.GetShippingCookieValue();
if (Request.Url.ToString().IndexOf(".asmx") == -1)
{
if (strCountryCookie.Trim() == "" || strShippingCookie.Trim() == "")
{
if (Request.Url.GetLeftPart(UriPartial.Authority).ToString() + "/index.aspx?ShowCountry=true" != HttpContext.Current.Request.Url.ToString())
{
Response.Redirect("~/index.aspx?ShowCountry=true");
}
}
}
}
}
i have a very large database of images from the web which i am categorizing (downloaded locally).
so i have a website (locally) to do this, but the db queries were taking long, so i got an idea to "preload" the next page, so that only the very first load of the page would be slow. I save the list of items loaded in a seperate thread in session. So far so good.
I wanted to optimize further, and did some testing on what took the longest, and loading the images to check the size to see if i needed to scale them (set image height and width on the img obj) - so i wanted to do this with a parallel.foreach loop - but after doing this, my buttons on the page stopped responding? i can see the page runs through the page_load event when i press a button, but it doesn't reach the buttons "code":
protected virtual void btnSaveFollowPosts_Click(object sender, EventArgs e)
{...}
any take on what i am doing wrong? i have tried to limit the degree of paralellelism to 1 just to see if that would fix it - but it did not.
Update - code:
trying to boil it down:
protected void Page_Load(object sender, EventArgs e)
{
Search(false);
}
protected void Search(bool updateCounters)
{
if (Session[SessionItems] == null)
{
if (Session[SessionItemsCache] == null)
{
//if is being constructed, wait, else construct
//if construction is not running
if (Session[SessionCacheConstructionRunning] == null)
{
StartPreLoadContent();
}
while (Session[SessionCacheConstructionRunning] != null)
{
Thread.Sleep(25); //block main thread untill items ready
}
}
List<ContentView> contentViewList = Session[SessionItemsCache] as List<ContentView>;
Session[SessionItemsCache] = null; //clean preload cache
Session[SessionItems] = contentViewList; //save in current usage storage
Filltable(ref tblContent, contentViewList);
//preload next batch
StartPreLoadContent();
}
else
{
List<ContentView> contentViewList = Session[SessionItems] as List<ContentView>; //get items from session
Session[SessionItems] = contentViewList; //save in current usage storage
Filltable(ref tblContent, contentViewList);
}
}
protected void StartPreLoadContent()
{
Session[SessionCacheConstructionRunning] = true;
//start task
Thread obj = new Thread(new ThreadStart(RunPreLoadContent));
obj.IsBackground = true;
obj.Start();
}
protected void RunPreLoadContent()
{
using (DBEntities entities = new DBEntities())
{
entities.CommandTimeout = 86400;
IQueryable<ContentView> query = entities.ContentView.Where(some criterias);
List<ContentView> contentViewListCache = query.ToList();
ParallelOptions options = new ParallelOptions();
options.MaxDegreeOfParallelism = 7;
Parallel.ForEach(contentViewListCache, options, content =>
{
try
{
Interlocked.Increment(ref imageSizeCount);
string path = Path.Combine(basePath, content.LocalPath);
int imageSize = 150;
using (System.Drawing.Image realImage = System.Drawing.Image.FromFile(path))
{
double scale = 0;
if (realImage.Height > realImage.Width)
{
scale = (double)realImage.Height / imageSize;
}
else
{
scale = (double)realImage.Width / imageSize;
}
if (scale > 1)
{
content.ImageHeight = (int)((double)realImage.Height / scale);
content.ImageWidth = (int)((double)realImage.Width / scale);
content.ImageScaled = true;
}
content.ShowImage = true;
}
}
catch (Exception)
{
}
});
Session[SessionItemsCache] = contentViewListCache;
Session[SessionCacheConstructionRunning] = null; //cache ready
}
protected virtual void btnSave_Click(object sender, EventArgs e)
{
try
{
//save
...some reading and saving going on here...
//update
Session[SessionItems] = null;
Search(true);
}
catch (Exception error)
{
ShowError(error);
}
}
I agree with a previous comment: you should probably do this logic earlier in the page lifecycle. Consider overriding OnInit and putting it there.
Also, you could try this line of code instead of your current thread code (which is more suited to Windows not Web programming):
using System.Threading.Tasks;
Task.Run(() => { RunPreLoadContent(); });
I'm very new to ASP.NET so there is a high risk that I am missing something simple here, but I have a problem with my Session. When I click the "NewTurn" button the first time, it creates the player just as it should, however, when I click it again, somehow all the stats are back as if it got created again (stats such as "health" is back to max value) but I can see in debug mode that it only enters the "if == null" function ONCE.
I don't understand what I am doing wrong, here is the code:
protected void NewTurn_Click(object sender, ImageClickEventArgs e)
{
StartButton.Visible = false;
RulesLink.Visible = false;
NewTurnButton.Visible = true;
if (Session["PrevObject"] == null)
{
Character player = new Character(1);
Session["PrevObject"] = player;
}
Character prevObj = (Character)Session["PrevObject"];
prevObj = CreateCard(prevObj);
Session["PrevObject"] = prevObj;
}
EDIT: I found the error and it had nothing to do with the Session, I just returned the object without setting the correct values before sending it back. Thank you for your suggestions, though and I'm sorry to have wasted your time!
please check comment in your code
protected void NewTurn_Click(object sender, ImageClickEventArgs e)
{
StartButton.Visible = false;
RulesLink.Visible = false;
NewTurnButton.Visible = true;
if (Session["PrevObject"] == null)
{
Character player = new Character(1);
Session["PrevObject"] = player;
}
Character prevObj = (Character)Session["PrevObject"];
// I think here you made mistake
prevObj = CreateCard(prevObj);
// check here again using DEbug point
// and make sure prevObj not null
Session["PrevObject"] = prevObj;
}
You should have to mention the Property of the player will be assign to the Session["PrevObject"].
suppose I have the class such as
public class Character
{
public playtime{get;set;}
Character(int i)
{
playtime=i;
}
}
Now I will code as you mention:
protected void NewTurn_Click(object sender, ImageClickEventArgs e)
{
StartButton.Visible = false;
RulesLink.Visible = false;
NewTurnButton.Visible = true;
if (Session["PrevObject"] == null)
{
Character player = new Character(1);
//Here is a little change you will have to specify what shuold be assign to the Session //variable
Session["PrevObject"] = player.playtime;
}
Hope this will help you.
Vote if you find helpful
Thanks is always appreciated.
Perhaps my previous question on output caching output caching was too complex.
Let's simplify.
How can I get the final, "ready for sending" rendered HTML from a page (or control) event in ASP.Net? I assume that this will be the same content that will be used for the output cache, so could be queried to find out what is about to be placed into the cache.
Code copied from:
http://aspcode.net/Last-second-HTML-changes-in-your-ASPNET-page.aspx
protected override void Render(HtmlTextWriter writer)
{
using(System.IO.MemoryStream msOur = new System.IO.MemoryStream())
{
using(System.IO.StreamWriter swOur = new System.IO.StreamWriter(msOur))
{
HtmlTextWriter ourWriter = new HtmlTextWriter(swOur);
base.Render(ourWriter);
ourWriter.Flush();
msOur.Position = 0;
using(System.IO.StreamReader oReader = new System.IO.StreamReader(msOur))
{
string sTxt = oReader.ReadToEnd();
Response.Write(sTxt);
oReader.Close();
}
}
}
}