C# ticket system - c#

I am currently designing a ticket system for my place of work.
Currently, I have most of it working except one small part. It is setup to automatically send it to the person that is responsible for fixing it. After it tells the user their Unique ID and the estimated date it should be finished. The only problem is People work different shifts. The things I want it to be able to do is
If a ticket is put in before the persons shift, it adjusts to the time they come in for their shift.
If a ticket is put in after a persons shift, adjusts it to the next day and the start of the persons shift.
If the ticket takes longer than the time remaining in the shift, use the time remaining in the shift and the remaining in the following day.
Be able to add time from previous tickets that are not completed and maintain the work schedule. (Currently working except maintaining work schedule)
For example:
First shift comes in at 7:00 am and someone puts in a ticket at 3:00 am, it should go to 7:00 am and than adjust the amount of time needed.
First shift leaves at 3:30pm and someone puts in a ticket at 3:00 pm that takes roughly an hour to complete, it should finish the 30 minutes in the day and go 30 minutes into the following day.
The code I currently have to try to handle this
if (DateTime.Now.AddMinutes(sum).Hour <= 8)
{
MessageBox.Show("Too early");
var now = DateTime.Now;
var tomorrow8am = now.AddDays(0).Date.AddHours(8);
double totalHours = (tomorrow8am - now).TotalHours;
MessageBox.Show("totalHours=" + totalHours);
var today8am = now.Date.AddHours(8).Hour;
EstimatedCompleteDate = DateTime.Today.Month + "/" + DateTime.Today.AddDays(0).Day + "/" + DateTime.Today.Year + " " + DateTime.Now.AddHours(totalHours).AddMinutes(timetoadd).ToLongTimeString();
MessageBox.Show(now.ToString() + Environment.NewLine + tomorrow8am.ToString() + Environment.NewLine + totalHours.ToString());
MessageBox.Show(now.AddHours(totalHours).AddMinutes(timetoadd).Hour.ToString());
if (DateTime.Now.AddHours(totalHours).AddMinutes(timetoadd).Hour > 15)
{
double hourstoadd = 0;// = timetoadd / 60;
do
{
hourstoadd++;
timetoadd = timetoadd - 60;
}
while (timetoadd > 60);
var remaining = hourstoadd;
int i = 0;
MessageBox.Show(remaining.ToString());
do
{
if (remaining > 0)
{
MessageBox.Show("Remaining1: " + remaining.ToString());
MessageBox.Show("Remaining - totalHours" + (remaining - totalHours).ToString());
i++;
EstimatedCompleteDate = DateTime.Today.Month + "/" + DateTime.Today.AddDays(i).Day + "/" + DateTime.Today.Year + " " + DateTime.Now.AddHours(totalHours + remaining).AddMinutes(timetoadd + now.Minute).ToLongTimeString();
remaining = remaining - 8;
}
}
while (remaining > 0);
please excuse the messagebox's I am using to give some feedback to me.

Related

date_trunc interval in PostgreSQL 15 minutes

const string query = "SELECT worker, date_trunc('hour', created) AS created, AVG(hashrate) AS hashrate, " + "AVG(sharespersecond) AS sharespersecond FROM minerstats " +
"WHERE poolid = #poolId AND miner = #miner AND created >= #start AND created <= #end " +
"GROUP BY date_trunc('hour', created), worker " +
"ORDER BY created, worker;";
This query displays the time periods of hours.
how to make 15 minutes?
Here is one option:
date_trunc('hour', created)
+ extract(minute from created)::int / 15 * interval '15' minute

Calculating Estimated Time Left in Loop (When iteration number is very big and time required for each iteration is very low)

I'm trying to calculate total time remaining of a for loop. Total number of iterations can be more than ~1010000000. Total time required for doing "Real job done here" is much lower than a second and it doesnt change much. When i use my current solution time remaining increases for a long time and than starts to decrease.
I'm looking for a better solution. What can i do?
long totalTiles = ((((rightBottom.X) - (topLeft.X)) + 1) * (((rightBottom.Y) - (topLeft.Y)) + 1));
long currentTileProccessed = 0;
DateTime startTime = DateTime.Now;
for (long x = (topLeft.X); x <= (rightBottom.X); x++)
{
for (long y = (topLeft.Y); y <= (rightBottom.Y); y++)
{
**//Real job done here//**
TimeSpan timeRemaining = TimeSpan.FromTicks(DateTime.Now.Subtract(startTime).Ticks * (totalTiles - (currentTileProccessed + 1)) / (currentTileProccessed + 1));
this.Dispatcher.Invoke((Action)delegate () {
EstimatedTimeLeft_TextBlock.Text = "Days : " + timeRemaining.Days.ToString("D2") + ", Hours : " + timeRemaining.Hours.ToString("D2") + ", Minutes :" + timeRemaining.Minutes.ToString("D2") + ", Seconds :" + timeRemaining.Seconds.ToString("D2");
});
currentTileProccessed++;
}
}
Here I am using Stopwatch from System.Diagnostics to determine the average time for the last 100 tasks, which I multiply against the total expected number of tasks minus the number already run.
NOTE: Remaining time can still increase, if suddenly the last 100 tasks start running slower than the previous 10k, this will readjust your remaining time to match the recent runs.
long totalTiles = ((((rightBottom.X) - (topLeft.X)) + 1) * (((rightBottom.Y) - (topLeft.Y)) + 1));
long currentTileProccessed = 0;
Queue<long> taskTimes = new Queue<long>();
int taskTimeHistoryLimit = 100;
long taskTotal = (rightBottom.X - topLeft.X) * (rightBottom.Y - topLeft.Y);
Stopwatch watch = new Stopwatch();
long index = 0;
for (long x = (topLeft.X); x <= (rightBottom.X); x++)
{
for (long y = (topLeft.Y); y <= (rightBottom.Y); y++)
{
index++;
watch.Start();
//Real job done here//
watch.Stop();
taskTimes.Enqueue(watch.ElapsedTicks);
watch.Reset();
while (taskTimes.Count > taskTimeHistoryLimit)
{
taskTimes.Dequeue();
}
TimeSpan timeRemaining = new TimeSpan((taskTotal - index) * (long)taskTimes.Average());
this.Dispatcher.Invoke((Action)delegate () {
EstimatedTimeLeft_TextBlock.Text = "Days : " + timeRemaining.Days.ToString("D2") + ", Hours : " + timeRemaining.Hours.ToString("D2") + ", Minutes :" + timeRemaining.Minutes.ToString("D2") + ", Seconds :" + timeRemaining.Seconds.ToString("D2");
});
}
}

Textchanged event won't calculate correctly

I have been trying to make a simple second to hour and minute converter just to practice some C#. The weird thing is as I pass 599 seconds mark, the program subtracts 60 seconds. So, 540 seconds equals 9 minutes; 599 seconds equals 9 minutes 59 seconds, but 600 seconds equals to 9 minutes. I tried using a button to trigger the commands instead of textchanged and button did the job fine. So, I reckon, the root of the problem must be textchanged event itself. I'll be adding three examples. Screenshot images are in Turkish but you will easily get the idea.
How can I solve this, and what causes this problem? This is really mind boggling.
Screenshot
int second, minute, hour, minuteLeft, secondLeft;
private void txtTime_TextChanged(object sender, EventArgs e)
{
CalculateTime();
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
void CalculateTime()
{
if (txtTime.Text != "")
{
second = Convert.ToInt32(txtSure.Text);
secondLeft = second % 60;
second = second - minuteLeft;
minute = second / 60;
minuteLeft = minute % 60;
minute = minute - minuteLeft;
hour = minute / 60;
lblMsg.Text = hour.ToString() + " hours, " + minuteLeft.ToString() + " minutes " + secondLeft.ToString() + " seconds.";
}
else
{
lblMsg.Text = "";
}
You are subtracting minuteLeft from the number of seconds:
second = second - minuteLeft;
That should be subtracting the secondLeft value:
second = second - secondLeft;
You could consider attacking the problem in a different way:
var durationInSeconds = Convert.ToInt32(txtTime.Text);
var duration = new TimeSpan(0, 0, durationInSeconds);
var second = duration.Seconds;
var minute = duration.Minutes;
var hour = Convert.ToInt32(Math.Truncate(duration.TotalHours));
TimeSpan is well suited to this class of problem, and will allow you to 'automatically' extract the hour, minute and second component of the duration.
You could also consider replacing:
hour.ToString() + " hours, " + minuteLeft.ToString() + " minutes " + secondLeft.ToString() + " seconds.";
with a call to:
public static string ToPrettyFormat(TimeSpan timeSpan)
{
var dayParts = new[] { GetDays(timeSpan), GetHours(timeSpan), GetMinutes(timeSpan) }
.Where(s => !string.IsNullOrEmpty(s))
.ToArray();
var numberOfParts = dayParts.Length;
string result;
if (numberOfParts < 2)
result = dayParts.FirstOrDefault() ?? string.Empty;
else
result = string.Join(", ", dayParts, 0, numberOfParts - 1) + " and " + dayParts[numberOfParts - 1];
return result.UppercaseFirst();
}
Stolen from https://codereview.stackexchange.com/questions/24995/convert-timespan-to-readable-text .

Twilio total call duration does not match with billing minutes

In the attached image , the total voice minutes for July is 30 minutes. However if I pull the call logs for the same month July 2014 (using the instruction in https://www.twilio.com/docs/api/rest/call)
, I get total duration as 17 minutes. Shouldn't the value of usage and total call duration in Log be equal ?.
Here is my test source code for finding the call log files for month July 2014. Any help is greatly appreciated.
public static void callLogs(string AccountSid, string AuthToken)
{
var twilio = new TwilioRestClient(AccountSid, AuthToken);
var request = new CallListRequest();
request.StartTimeComparison = ComparisonType.GreaterThanOrEqualTo;
request.StartTime = new DateTime(2014, 07, 01);
request.EndTimeComparison = ComparisonType.LessThanOrEqualTo;
request.EndTime = new DateTime(2014, 07, 31);
var calls = twilio.ListCalls(request);
int? voiceMinutes = 0;
decimal? totalCost = 0;
foreach (var call in calls.Calls)
{
if ( call.Price != null)
{
voiceMinutes += call.Duration;
totalCost += call.Price ;
}
Console.WriteLine(call.Price +"-" + call.DateCreated + "-" + call.From + "-" + call.To + "-" + call.Status + "-" + call.Duration );
}
Console.WriteLine("Total Voice:" + int.Parse ((voiceMinutes/60).ToString() ));
Console.WriteLine("Total Cost :" + totalCost);
}
For billing minutes, Twilio will round all calls up to the nearest minute. So you should do the same. Something like this:
voiceMinutes += (call.Duration + 60)/ 60;
And then:
Console.WriteLine("Total Voice:" + int.Parse ((voiceMinutes).ToString() ));
I used to work at West Corporation. One of my duties was to manage the billing data for our clients. At West, the contracts were setup so that instead of exact to the second or minute, the billing was done in blocks.
So, for phone calls, for example, you would get charged for a minimum of 15 seconds and then 10 seconds after that.
Twilio might be using a similar billing model.

Estimate loop time for progress bar

I'm currently using a loop in C# to generate files, but the program takes a few seconds to actually do this and I feel the program user would benefit from a progress bar that updates to tell them how far the loop is through so they can estimate when the loop is going to finish and all of their files are generated.
I was wondering if there was a way to calculate the time it's going to take a loop to complete or update a progress bar with the loop to show how much progress the loop has left.
Here's my loop.
String GeneratedLevelName;
int levelx = 0;
int levely = 0;
for (int i = 0; i < GmapLevelArea; i ++) {
if (levelx >= (GmapWidth - 1)) {
levelx = 0;
levely ++;
GeneratedLevelName = (GmapPrefix + "_" + levelx + "_" + levely + ".nw");
File.Copy(ApplicationDirectory + TemplateFileName, GmapDirectory + GeneratedLevelName);
GmapFile.AppendLine('"' + GeneratedLevelName + '"' + ",");
} else {
levelx ++;
GeneratedLevelName = (GmapPrefix + "_" + levelx + "_" + levely + ".nw");
File.Copy(ApplicationDirectory + TemplateFileName, GmapDirectory + GeneratedLevelName);
GmapFile.Append('"' + GeneratedLevelName + '"' + ",");
}
}
Any help is greatly appreciated.
Since it would be difficult to time the File.Copy, I think you should just base your progress bar on total files worked on.
So if you have a progress bar: pb
pb.Minimum = 0;
pb.Maximum = GMapLevelArea;
then set the value of the progress bar to you i value
pb.Value = i;
Now when I usually use progress bars like this, I usually don't update ever iteration. I usually update after a few iterations.
So to do that I usually check for the iteration count:
if(i % 10 == 0) //only true when i is a multiple of 10
pb.Value = i;
Then at the end of the loop, if it doesn't happen to be a multiple of your update, you can either set the progress bar to its maximum value or reset it to zero to let them no its done.
pb.Value = GMapLevelArea; or pb.Value = 0;
It depends on how consistent your files are generated (do they all take a second, or take some longer than others?) and if you know how many you are going to generate. In the easiest case, you can estimate the time by taking the number of files to generate. For example if you create 50 files, you can increment the progress bar by two percent after a file is generated.

Categories