Is there a way I can determine how long an application pool (in IIS7) has been up (time since started, or last restart) in c#?
DateTime.Now - Process.GetCurrentProcess().StartTime
Process.GetCurrentProcessInfo() doesn't exist.
Really stupid trick: in some class that everything uses, use a class constructor to remember your start time and use an aspx page to receive it. Now compare to current time.
From the ASP.NET application, you can try TimeSpan uptime = (DateTime.Now - ProcessInfo.GetCurrentProcessInfo ().StartTime)
Based on the above I created a simple class like so..
public static class UptimeMonitor
{
static DateTime StartTime { get; set; }
static UptimeMonitor()
{
StartTime = DateTime.Now;
}
public static int UpTimeSeconds
{
get { return (int)Math.Round((DateTime.Now - StartTime).TotalSeconds,0); }
}
}
and called it in Application_Start() in Global.asax.cs like
var temp = UptimeMonitor.UpTimeSeconds;
It can then be accessed anywhere using
UptimeMonitor.UpTimeSeconds
if you find that Process.GetCurrentProcessInfo() doesn't exist as another user mentioned,
System.Diagnostics.Process.GetCurrentProcess().StartTime
may work for you.
(I wanted to add this as a comment to Eric Humphrey's post but I'm not allowed)
One of two approaches exist that I personally use. Using a static class (as shown in #Original10's answer) or using Application variables.
I have found that using Application variables is acceptable because I noticed Process.GetCurrentProcess() survives application restarts (eg modification of web.config or bin directory). I needed something that would cater for the website restarting as well.
In your Global.asax, add the following to the Application_Start - and add the method it if it's not there.
public void Application_Start(Object sender, EventArgs e)
{
...
Application["ApplicationStartTime"] = DateTime.Now.ToString("o");
}
In your code where you need it, you could do something like:
var appStartTime = DateTime.MinValue;
var appStartTimeValue = Web.HttpCurrent.Application["ApplicationStartTime"].ToString();
DateTime.TryParseExact(appStartTimeValue, "o", null, Globalization.DateTimeStyles.None, Out appStartTime);
var uptime = (DateTime.Now - appStartTime).TotalSeconds
var lsOutput = $"Application has been running since {appStartTime:o} - {uptime:n0} seconds."
Which will produce something along the lines of
Application has been running since 2018-02-16T10:00:56.4370974+00:00 - 10,166 seconds.
There is no checking of the application variable or locking of the application if required. I'll leave this as an exercise to the user.
If you mashed Restarting (Recycling) an Application Pool and http://forums.iis.net/t/1162615.aspx, you should get it
Related
I have a function which is taking a lot of time to execute in a web application.
I have tested this with a profiler and by my logging.
I have other functions running in the same pageload.
What is a best way to display the rest of the values from those functions and keep this function in a thread and display it in a label when it finishes?
This function is used to get events in application which takes time.
private void getEventErrors()
{
EventLog eventLog = new EventLog("Application", ".");
getEvents(eventLog.Entries);
}
private void getEvents(EventLogEntryCollection eventLogEntryCollection)
{
int errorEvents = 0;
foreach (EventLogEntry logEntry in eventLogEntryCollection)
{
if (logEntry.Source.Equals("XYZ"))
{
DateTime variable = Convert.ToDateTime(logEntry.TimeWritten);
long eventTimeTicks = (variable.Ticks);
long eventTimeUTC = (eventTimeTicks - 621355968000000000) / 10000000;
long presentDayTicks = DateTime.Now.Ticks;
long daysBackSeconds = ((presentDayTicks - 864000000000) - 621355968000000000) / 10000000;
if (eventTimeUTC > daysBackSeconds)
{
if (logEntry.EntryType.ToString() == "Error")
{
errorEvents = errorEvents + 1;
}
}
}
}
btn_Link_Event_Errors_Val.Text = errorEvents.ToString(GUIUtility.TWO_DECIMAL_PT_FORMAT);
if (errorEvents == 0)
{
lbl_EventErrorColor.Attributes.Clear();
lbl_EventErrorColor.Attributes.Add("class", "green");
}
else
{
lbl_EventErrorColor.Attributes.Clear();
lbl_EventErrorColor.Attributes.Add("class", "red");
}
}
I have 3 functions in the pageload event, two to get the values from the DB and the other one is shown above.
Should both these functions be service calls?
What i wanted was, the page should load fast and if there is a function taking a lot of time it should run in the background and display when done and in the process if the user want to navigate to a new page it should kill it and move on.
If you have a function that is running in a separate thread in ASP.NET, you may want to consider moving it to a service. There are many reason for this
See this answer (one of many on SO) for why running long running tasks in ASP.NET is not always a good idea.
One option for the service is to use WCF. You can get started here. Your service could implement a method, say GetEvents() which you could use to pull your events. That way you won't tie up your page waiting for this process to complete (using AJAX of course). Also, this allows you to change your implementation of GetEvents() without touching your code on your website.
I have a data object that will store the data that request from database, these data is cached for store only 5 min, after that 5 min it will request from database again.
So something like below:
public class UserCachedData
{
List<string> _SelectableProviderList { get; set; }
DateTime _SelectableProviderList_RequestDateTime = DateTime.MinValue;
public List<string> SelectableProviderList {
get {
if (_SelectableProviderList == null || _SelectableProviderList_RequestDateTime < DateTime.Now)
{
_SelectableProviderList_RequestDateTime = DateTime.Now.AddMinutes(5);
_SelectableProviderList = QueryService.GetList();
}
return _SelectableProviderList;
}
set {
_SelectableProviderList = value;
}
}
}
Here comes the question, I am going to have a lot of these variable in this class, all of them will have a expire time, I wonder what's the best way to avoid writting a Expire time for each of them? Is there any generic way I can have each variable in this class will expires after centain time and do centain action (like call QueryService to get new item list this time)?
Thanks in advance,
King
Just use the Cache class. That's what it's for.
Though it lives in the System.Web.Caching namespace, it is a normal .NET class and can be used in non web applications.
Update:
If you are using .NET 4.0 you should use MemoryCache for this.
Maybe this is dreaming, but is it possible to create an attribute that caches the output of a function (say, in HttpRuntime.Cache) and returns the value from the cache instead of actually executing the function when the parameters to the function are the same?
When I say function, I'm talking about any function, whether it fetches data from a DB, whether it adds two integers, or whether it spits out the content of a file. Any function.
Your best bet is Postsharp. I have no idea if they have what you need, but that's certainly worth checking. By the way, make sure to publish the answer here if you find one.
EDIT: also, googling "postsharp caching" gives some links, like this one: Caching with C#, AOP and PostSharp
UPDATE: I recently stumbled upon this article: Introducing Attribute Based Caching. It describes a postsharp-based library on http://cache.codeplex.com/ if you are still looking for a solution.
I have just the same problem - I have multiply expensive methods in my app and it is necessary for me to cache those results. Some time ago I just copy-pasted similar code but then I decided to factor this logic out of my domain.
This is how I did it before:
static List<News> _topNews = null;
static DateTime _topNewsLastUpdateTime = DateTime.MinValue;
const int CacheTime = 5; // In minutes
public IList<News> GetTopNews()
{
if (_topNewsLastUpdateTime.AddMinutes(CacheTime) < DateTime.Now)
{
_topNews = GetList(TopNewsCount);
}
return _topNews;
}
And that is how I can write it now:
public IList<News> GetTopNews()
{
return Cacher.GetFromCache(() => GetList(TopNewsCount));
}
Cacher - is a simple helper class, here it is:
public static class Cacher
{
const int CacheTime = 5; // In minutes
static Dictionary<long, CacheItem> _cachedResults = new Dictionary<long, CacheItem>();
public static T GetFromCache<T>(Func<T> action)
{
long code = action.GetHashCode();
if (!_cachedResults.ContainsKey(code))
{
lock (_cachedResults)
{
if (!_cachedResults.ContainsKey(code))
{
_cachedResults.Add(code, new CacheItem { LastUpdateTime = DateTime.MinValue });
}
}
}
CacheItem item = _cachedResults[code];
if (item.LastUpdateTime.AddMinutes(CacheTime) >= DateTime.Now)
{
return (T)item.Result;
}
T result = action();
_cachedResults[code] = new CacheItem
{
LastUpdateTime = DateTime.Now,
Result = result
};
return result;
}
}
class CacheItem
{
public DateTime LastUpdateTime { get; set; }
public object Result { get; set; }
}
A few words about Cacher. You might notice that I don't use Monitor.Enter() ( lock(...) ) while computing results. It's because copying CacheItem pointer ( return (T)_cachedResults[code].Result; line) is thread safe operation - it is performed by only one stroke. Also it is ok if more than one thread will change this pointer at the same time - they all will be valid.
You could add a dictionary to your class using a comma separated string including the function name as the key, and the result as the value. Then when your functions can check the dictionary for the existence of that value. Save the dictionary in the cache so that it exists for all users.
PostSharp is your one stop shop for this if you want to create a [Cache] attribute (or similar) that you can stick on any method anywhere. Previously when I used PostSharp I could never get past how slow it made my builds (this was back in 2007ish, so this might not be relevant anymore).
An alternate solution is to look into using Render.Partial with ASP.NET MVC in combination with OutputCaching. This is a great solution for serving html for widgets / page regions.
Another solution that would be with MVC would be to implement your [Cache] attribute as an ActionFilterAttribute. This would allow you to take a controller method and tag it to be cached. It would only work for controller methods since the AOP magic only can occur with the ActionFilterAttributes during the MVC pipeline.
Implementing AOP through ActionFilterAttribute has evolved to be the goto solution for my shop.
AFAIK, frankly, no.
But this would be quite an undertaking to implement within the framework in order for it to work generically for everybody in all circumstances, anyway - you could, however, tailor something quite sufficient to needs by simply (where simplicity is relative to needs, obviously) using abstraction, inheritance and the existing ASP.NET Cache.
If you don't need attribute configuration but accept code configuration, maybe MbCache is what you're looking for?
How can I get the number of times a program has previously run in C# without keeping a file and tallying. If it is not possible that way, can it be gotten from the Scheduled Task Manager?
To C. Ross: how would this be done in a registry setting? forgive me. . . what is a registry setting?
I do this in a registry setting.
static string AppRegyPath = "Software\\Cheeso\\ApplicationName";
static string rvn_Runs = "Runs";
private Microsoft.Win32.RegistryKey _appCuKey;
public Microsoft.Win32.RegistryKey AppCuKey
{
get
{
if (_appCuKey == null)
{
_appCuKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(AppRegyPath, true);
if (_appCuKey == null)
_appCuKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(AppRegyPath);
}
return _appCuKey;
}
set { _appCuKey = null; }
}
public int UpdateRunCount()
{
int x = (Int32)AppCuKey.GetValue(rvn_Runs, 0);
x++;
AppCuKey.SetValue(rvn_Runs, x);
return x;
}
If it's a WinForms app, you can hook the Form's OnClosing event to run UpdateCount.
To the best of my knowledge Windows does not keep this information for you. You would have to tally the value somewhere (file, database, registry setting). The Windows Task Scheduler is very low functionality.
The number of time an app has run is stored in the registry; there are a couple of caveats, though:
It's stored in the user registry (HKCU for instance) [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist]
The path is stored in ROT13 so for instance runme.exe would become ehazr.rkr
The registry actually stores three values in binary form: the last runtime, the run count (which starts at 6 instead of 1, for some reason), and the name of the application.
Don't know if this helps, but there you have it!
Here is a tutorial for registry handling -- C# Registry Basics
You could simply create an application setting called Properties.Settings.Default.TimesRun;
Use it like so:
private void Form1_Load( object sender, EventArgs e )
{
Properties.Settings.Default.TimesRun = timesrun++;
Properties.Settings.Default.Save();
}
No, task manager does not provide that kind of information. I wouldn't be hard to create a script that would update a tally and then execute the application and then set up the task to call the script.
I recommend using the ESENT database that is included with Windows. Software support is easily available with ESENT Managed Interface.
#Cheeso,
You don't need the private member variable with that code, one way to slim it down a bit:
using Microsoft.Win32;
public RegistryKey AppCuKey
{
get
{
return Registry.CurrentUser.OpenSubKey(AppRegyPath, true)
?? Registry.CurrentUser.CreateSubKey(AppRegyPath);
}
}
Or, if you like to update the private variable, in order to keep from calling the method (which is a pretty cheap method, anyway), you can still save yourself an if == null check.
int x = Your_Project.Properties.Settings.Default.Counter;
x++;
Your_Project.Properties.Settings.Default.Counter = x;
Your_Project.Properties.Settings.Default.Save();
For the life of my, I can't figure out this performance hit in my code. I have a container object where I measure how long it takes to run the constructor (object below), timing code in the public constructor
public class WorkUnit : IWorkUnit
{
private JobInformation m_JobInfo;
private MetaInfo m_MetaInfo;
private IPreProcJobInfo m_PreprocDetails;
readonly private Guid m_ID;
private Guid m_ParentID;
private Guid m_MasterJobID;
private string m_ErrorLog = string.Empty;
private PriorityKeeper m_Priority;
private WorkUnitClassification m_Classification;
private IJobPayload m_CachedPayload;
private IJobLogger m_Logger;
private EventHandler<JobEventArgs> m_IsFinished;
private ReaderWriterLockSlim m_Lock;
public WorkUnit(string InputXML, Guid JobID, IJobLogger Logger)
{
DateTime overstarttime = DateTime.Now;
try
{
....Do Stuff....
}
catch(XMLException e)
{...}
catch(Exception e)
{
...
throw;
}
double time = (DateTime.Now - overstarttime).TotalMilliseconds
Console.WriteLine("{0}", time);
}
/// <summary>
/// Private Constructor used to create children
/// </summary>
private WorkUnit(Guid MasterID, Guid ParentID, WorkUnitClassification Classification, PriorityKeeper Keeper)
{...}
[OnDeserializing()]
private void OnDeserialize(StreamingContext s)
{...}
public PriorityKeeper PriorityKey
{...}
public bool HasError
{...}
public bool Processing
{...}
public bool Splittable
{...}
public IEnumerable<IWorkUnit> Split(int RequestedPieces, int Bonds)
{...}
public void Merge(IResponse finishedjob)
{...}
public ReadOnlyCollection<IWorkUnit> Children
{...}
public bool IsMasterJob
{...}
public Guid MasterJobID
{...}
public Guid ID
{...}
public Guid ParentID
{...}
public EnumPriority Priority
{...}
public void ChangePriority(EnumPriority priority)
{...}
public string ErrorLog
{...}
public IMetaInfo MetaData
{...}
public IJobPayload GetProcessingInfo()
{... }
public IResponseGenerator GetResponseGenerator()
{... }
}
Now, I'm measuring the total time it takes to create the object as
DateTime starttime = DateTime.Now;
var test = new WorkUnit(temp, JobID, m_JobLogger);
double finished = (DateTime.Now - starttime).TotalMilliseconds;
and I'm consistently getting the following performance numbers -
Constructor time - 47 ms
Object creation time - 387 ms
47 ms is acceptable, 387 is really bad. Taking out the logging negligibly changes these numbers. Does anyone have any idea why this is taking so long? My system is VS 2008 SP1, targeting .NET 3.5 SP1 on Windows XP. I would appreciate any explanation. I'll be breaking out the profiler shortly, but I feel that it won't be able to delve into the level I need to explain this behavior. Thanks for any help.
EDIT: I'm running in release
Are you sure what you're seeing is the object creation time and not the effects of the CLR starting up?
Try running the test 50 times in a loop and ignoring the first result.
Steve,
Here are a couple of things to consider:
Switch from using DateTime to using a StopWatch. It is much more accurate for these types of situations.
Stop writing out to the console during the timing process. The IO is going to be significant, and impact your timings.
Make sure you're running in a release/optimized build, and not running under the Visual Studio Test Host. If you run from a default VS, switch to Release, build, and use Ctrl+F5 (instead of just F5) to run.
Given your timings, I'm guessing #2 is your issue. Visual Studio adds a lot of "hooks" that dramatically impact perf. timings when running inside of Visual Studio.
First use the StopWatch class to measure time instead. The resolution of the system time is way too low to give any accurate results.
Try to create more than one instance of the class. The first time the assembly might not be JIT:ed, which of course takes some time.
Time to bring out Red Gate Performance Profiler. Instead of asking us to guess what the issue might be...download a trial and let it tell you EXACTLY where your issue is.
Profilers are great tools. Any developer should be familiar with how to utilize them to pinpoint performance issues.
The question contains its own answer; there's more to instantiating an object than just running its constructor. When you call new you're asking the runtime to allocate space for an object, handle whatever internal bookkeeping the runtime needs, call the constructors for each base type (in this case, just object), and finally call your constructor.
When you measure the total instantiation time you're measuring all of that; when you time the constructor alone you're only measuring a part. If the numbers didn't differ, that would be a cause for concern.
As others have suggested, first and foremost, definitely switch to using System.Diagnostics.Stopwatch:
public WorkUnit(string InputXML, Guid JobID, IJobLogger Logger, out TimeSpan elapsed)
{
Stopwatch constructionStopwatch = Stopwatch.StartNew();
// constructor logic
constructionStopwatch.Stop();
elapsed = constructionStopwatch.Elapsed;
}
And then:
TimeSpan constructionTime = TimeSpan.Zero;
Stopwatch creationStopwatch = Stopwatch.StartNew();
var test = new WorkUnit(temp, JobID, m_JobLogger, out constructionTime);
creationStopwatch.Stop();
TimeSpan creationTime = creationStopwatch.Elapsed;
double constructionMs = constructionTime.TotalMilliseconds;
double creationMs = creationTime.TotalMilliseconds;
The reason I advise switching to using TimeSpan objects instead of doing something like (DateTime.Now - startTime).TotalMilliseconds is that, although it should make very little difference, technically in the latter case you are first calling getting the time and then getting the TotalMilliseconds property, which I am almost certain is a calculated value, in the constructor. Which means there's actually a step between checking the time in your constructor and checking the time immediately afterward. Really, this should be basically negligible, but it's good to cover all your bases.
Do you know that the Console.WriteLine in the constructor is throwing of your timing hugely? Any IO op will throw off these timings.
If you want real numbers, store the durations in a global somewhere then print them out after you have recorded everything.