Asp.Net MVC timespan - asp.net

I have a application in which users need to fill out a timesheet for the amount of work that they have completed against a client. I currently use Timespan which works well up to a certain point.
The issue that I am currently having is that if a user has to put 4 hours or more a day against a customer it fails. The current message i am getting is SqlDbType.Time overflow. Value '1.04:00:00' is out of range. Must be between 00:00:00.0000000 and 23:59:59.9999999.
This will only be for my total which adds up all the days.
What I have is this
Model:
public TimeSpan Total
{
get
{
TimeSpan result = new TimeSpan(Monday.Ticks
+ Tuesday.Ticks
+ Wednesday.Ticks
+ Thursday.Ticks
+ Friday.Ticks
+ Saturday.Ticks
+ Sunday.Ticks);
return (result);
}
set
{
TimeSpan result = new TimeSpan(Monday.Ticks
+ Tuesday.Ticks
+ Wednesday.Ticks
+ Thursday.Ticks
+ Friday.Ticks
+ Saturday.Ticks
+ Sunday.Ticks);
}
}
I have tried removing .ticks to .Hours which partially works but gives me an excessive amount of 0s http://prntscr.com/anaigx
Please can someone advise.

The problem you have having is due to your definition of SqlDbType.Time.
This type can only be used for a "normal" time, like 15:36, or whatever, it cannot store number of hours.
If you want to store amount of hours you should either use float type to store hours or int (or bigint) to store ticks.

Related

How to delete first n rows in realm

Suppose there is a table called RecentViewItem which stores recently viewed items by user. I want to keep only first 10 recently viewed items by deleting all other items. My query is like this:
RealmResults<RecentViewItem> results =
realm.where(RecentViewItem.class)
.findAllSorted("updatedAt", Sort.DESCENDING);
// What to do next ?
RealmResults<RecentViewItem> results = realm.where(RecentViewItem.class).findAllSorted("updatedAt", Sort.DESCENDING);
for(int i = 0, size = results.size(); i < 10 && i < size; i++) {
RecentViewItem recentViewItem = results.get(i);
recentViewItem.deleteFromRealm();
}
Since Realm for Java lazy loads its data, there isn't a LIMIT query which adds a bit of work. I query all the data sorted by a timestamp (in your case updatedAt).
Realm realm = Realm.getDefaultInstance();
final RealmResults<RecentViewItem> results = realm.where(RecentViewItem.class).findAllSorted("timestamp", Sort.DESCENDING);
I check whether it's over my limit and, if it is, get the result on the threshold so I can get its timestamp. Then I query against that threshold timestamp and delete all the results from before it.
if (results.size() > UPPER_LIMIT) {
RecentViewItem firstOverLimit = results.get(TRUNCATE_LIMIT);
// Assuming a system time. Maybe your updatedAt is a date. Could use an id too.
long threshold = firstOverLimit.timestamp;
final RealmResults<RecentViewItem> resultsToDelete = realm.where(RecentViewItem.class).lessThanOrEqualTo("timestamp", threshold).findAll();
Log.d(TAG, "cleanUp: total "+ results.size() +
"; over threshold of " + UPPER_LIMIT +
"; truncating to " + TRUNCATE_LIMIT +
"; deleting " + resultsToDelete.size() +
"; all on or before "+ threshold);
realm.executeTransaction(realm1 -> resultsToDelete.deleteAllFromRealm());
}
My TRUNCATE_LIMIT is half my UPPER_LIMIT so that this clean up does not run constantly as new records are added, but you can tune that however you like.
I'm also deleting the first record over the limit, but you can play with the boundary and retain it.
Also, my timestamp is quite exact but if your date is just "today" then you will get fuzzier results.

add timestamp to click event in google tag manager

Currently, in the User Report view of Google Analytics, I get timestamps on each event, but it is only down to the minute, not the second. I can't find a setting in GA that changes that column.
My goal is to pass this timestamp through GTM, perhaps as "tag label", so that I can see it in GA.
How do I create a timestamp variable in GTM?
Create a custom javascript variable (i.e. a variable that contains a function, not a "javascript" variable that just reads a global variable), and give it a name, e.g. "timestamp".
Custom javascript variables are anonymous functions with a return value.
The current way to get a timestamp is Date.now(). This might not be supported by older browser (especially IE 8 and lower), so you might use new Date().getTime(); as an alternative.
The variable body would be as simple as:
function() {
return Date.now();
}
and you would use that in a tag by surrounding the variable name with double curly parenthesis, e.g. {{timestamp}}. Date.now() returns milliseconds ( elapsed since 1 January 1970 00:00:00 UTC), so you might want to divide by thousand.
Alternatively you could create a datetime variable that includes seconds and even milliseconds. I think this was originally by Simo Ahava:
function() {
// Get local time as ISO string with offset at the end
var now = new Date();
var tzo = -now.getTimezoneOffset();
var dif = tzo >= 0 ? '+' : '-';
var pad = function(num) {
var norm = Math.abs(Math.floor(num));
return (norm < 10 ? '0' : '') + norm;
};
return now.getFullYear()
+ '-' + pad(now.getMonth()+1)
+ '-' + pad(now.getDate())
+ 'T' + pad(now.getHours())
+ ':' + pad(now.getMinutes())
+ ':' + pad(now.getSeconds())
+ '.' + pad(now.getMilliseconds())
+ dif + pad(tzo / 60)
+ ':' + pad(tzo % 60);
}
which returns a formatted string like 2016-08-02T09:22:44.496+02:00.
The second it's not accesible via Google Analytics. The closest way to do this is via Google Big Query,but this last is only available for premium members.
Maybe you can add the timeStamp as CustomDimentions
function getdateGA(){
return Date();
}
ga('send', 'event', 'category', 'action', {
'dimention1': getdateGA()
});
The date format is not the best one, try to find the best for you modifing the getdateGA function
More resources about the date in
How to format a JavaScript date

Meteor : Countdown timer

This might be a big ask, but I'm completely stuck so any help is appreciated.
I'm trying to create a countdown timer that runs from Sunday to Sunday and just restarts at the end of the week. I've tried using countdown packages in atmosphere but the documentation is limited and never seems to work. I've also tried to download and run 3rd party jquery packages however they always seem to crash meteor.
Could someone point me in the right direction or show me how to do this in meteor?
Specific details:
Countdown timer used to run an auction.
Auction runs for 7 days, Starts Sunday at 12:00am finishes 7 days
later.
Auction resets and starts again after 7 days.
Countdown timer will be visible by users on multiple pages.
Countdown timer units to be displayed - Days, Hours, Minutes, Seconds (eg.
6 days, 3 hours, 55 minutes, 22 seconds until the next auction
begins.)
The question is too large. But i can suggest the small step to work with this. Your auction scheme will need to have a endDateTime to store the value (even it will start/end in Sunday). On the template you need to display the timer, set one ReactiveVar as number (to count down), one ReactiveVar as string (to display to result)
Template['countDownTemplate'].created = function() {
var due, dueDate, duration, now, num, self;
self = this;
dueDate = Template.instance().data['auction']['endDateTime'];
now = moment.utc();
due = moment.utc(dueDate, 'YYYY-MM-DD hh:mm:ss');
duration = moment.duration(due.diff(now));
num = Math.floor(duration.asSeconds());
if (num >= 0) {
self['remaining'] = new ReactiveVar<number>(num);
self['timeRemaining'] = new ReactiveVar<string>(convertPeriod(num));
self['interval'] = Meteor.setInterval((function() {
var remaining;
remaining = self['remaining'].get();
self['remaining'].set(remaining - 1);
self['timeRemaining'].set(convertPeriod(self['remaining'].get()));
if (remaining === 0) {
Meteor.clearInterval(self['interval']);
} else {
remaining = Math.floor(moment.duration(due.diff(now)).asSeconds());
}
}), 1000);
}
};
(the convertPeriod will be based on the remaining number to convert into your correct format)
The rest is just about showing timeRemaining in the correct format with the convertPeriod

IIS performance improve

Currently:
I have a ASP NET project, which utilises several ASHX.
it runs barely acceptable with daily 50000 login api calls(and each login comes diff amount of other API calls)
but now it takes >1min with daily 150,000 login api calls.
to t/shoot the problem, these thing I done on 1 of the API with sproc call which only retrieve data:
1) I run it in another brand new instance, in local-machine, it runs less than 100milisec; current web-instance runs > 1min
2) I run the sproc alone in SSMS, it take < 1sec; current web-instance runs > 1min
3) I did local parameter assignment on that particular sproc, to prevent parameter sniffing and re-built and re-exec, same result.
4) the part the serialize the Json(newtonsoft) uses static, also very fast, less than 1 sec.
I ran "http://tools.pingdom.com/fpt/" and indeed very slow; but I am not sure why it's slow.
I tried to use "DebugView" ("https://technet.microsoft.com/en-us/library/bb896647.aspx"), since it can write plenty log without file-locking, but not sure how to put it works for web application.
Anyway/ tool to capture the independent begin_request & end_request time externally and accurately? (I tried to put the time span in Global.asax, but get some null parameters sometimes) Best if anyone has the idea to pinpoint the part that caused it.
sample timespan test:
private string single_detail(HttpContext context)
{
PlayDetailApiResult o = new PlayDetailApiResult
{
...
};
string json = generateJsonFromObj(o); // init default
try
{
{
{
long current = 0;
DateTime dtStart = DateTime.Now;
// call sp
int ret = plmainsql.getPracticeQualificationTimeLeft(...);
DateTime dtEnd = DateTime.Now;
TimeSpan ts = dtEnd - dtStart;
LoggingHelper.GetInstance().Debug("single_detail getPracticeQualificationTimeLeft's duration(ms): " + ts.TotalMilliseconds);
if (ret != 0)
{
o.Code = ...;
}
}
DateTime dtStart_1 = DateTime.Now;
json = generateJsonFromObj(o);
DateTime dtEnd_1 = DateTime.Now;
TimeSpan ts_1 = dtEnd_1 - dtStart_1;
LoggingHelper.GetInstance().Debug("single_detail generateJsonFromObj's duration(ms): " + ts_1.TotalMilliseconds);
}
}
catch (Exception ex)
{
LoggingHelper.GetInstance().Debug("single_detail : " + ex.Message + "|" + ex.StackTrace);
}
finally
{
}
return json;
}
most of the result:
2015-03-04 18:45:29,263 [163] DEBUG LoggingHelper single_detail getPracticeQualificationTimeLeft's duration(ms): 5.8594
2015-03-04 18:45:29,264 [163] DEBUG LoggingHelper single_detail generateJsonFromObj's duration(ms): 0
these thing I noted.
1) computer's processor usage and memory usage: memory is at 70%, which i think still is not peak
2) check if Gzip compression is enabled : my json runs on mobile (iOS/Android/WM); some code changes needed, and not tested to prevent any compress-decompress issue; as compression also increase CPU usage at the same time
You can also try miniprofiler. It is very easy to use and displays the execution time for every step or function you want to monitor.
Check out http://miniprofiler.com/

How to get all the defects in Quality Center 11 by Restful API

I use https://qcxxx.xxx.com:443/qcbin/rest/domains/{domain}/projects/{project}/defects but I can only get 100 defects. Actually there are many more than 100 defects. Why is this?
You can pass some paramethers to "fix" it.
/defects?page-size=X&start-index=Y
X is the number of how many defects you can see at same page.
Y is the number of how many defects you will "skip".
There are some limits that are setted in QC configuration.
You can also use:
/defects?page-size=max
This also has a limited amount of returns, but is a simple way of getting all of the results, as long as it doesn't exceed the set max page size. I don't remember the default max page size right now, but it is a few thousands. I also know it can be changed according to your needs, in settings. I've set mine to 5000.
UPDATE:
from the API:
If the specified page-size is greater than the maximum page size, an
exception is thrown. The maximum page size can be specified by the
site parameter REST_API_MAX_PAGE_SIZE. If the site parameter is not
defined, the maximum page size is 2000. The requested page size can be
set equal to the maximum by specifying page-size=max.
Below is a c# function we used that returns the ids of all our hp alm/qc defects having attachments and using pagination in the rest api url.
public List<string> GetDefectIds()
{
XmlNodeList nodeIds = null;
int iteration = 0;
List<string> returnIds = new List<string>();
do
{
string queryString = "?fields=id&query={attachment['Y']}&page-size=" + Constant.ALM_DEFECTS_PAGE_SIZE.ToString() + "&start-index=" + (iteration++ * Constant.ALM_DEFECTS_PAGE_SIZE + 1).ToString();
string url = _urlBase + "/rest/domains/" + _domain + "/projects/" + _project + "/defects" + queryString;
WebRequest wrq = WebRequest.Create(url);
wrq.Headers.Set(HttpRequestHeader.Cookie, _sessionCookie);
WebResponse wrp = wrq.GetResponse();
StreamReader reader = new StreamReader(wrp.GetResponseStream());
string xmlString = reader.ReadToEnd();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlString);
nodeIds = xmlDoc.SelectNodes("/Entities/Entity/Fields/Field/Value");
foreach (XmlNode node in nodeIds)
{
returnIds.Add(node.InnerXml);
}
wrp.Close();
}
while (nodeIds?.Count > 0);
return returnIds;
}
Variables starting with underscore are private class members and the alm page size constant is equal to 250.

Resources