Adding multiple times in (HH.mm) - c#

data in sqlserver.
calling it in gridview
how do i add all the time in the column, i have 4 columns to calculate for different total time.
for example :
time 1 = 256.20 (HH.mm)
time 2 = 257.41 (HH.mm)
time 3 = 114.50 (HH.mm)
time 4 = 371.20 (HH.mm)
total = 1000.11 (HH.mm)
the total will keep on increasing but the format must be hours and minutes.
i added 2 time for the time 1 from above using string split
doing it in C#.net
thanking you in advance.
thank you very much #CodingYoshi
> //string time1 = TextBox1.Text;
//string time2 = TextBox2.Text;
//string[] part1 = time1.Split('.');
//int h1 = int.Parse(part1[0]);
//int m1 = int.Parse(part1[1]);
//string[] part2 = time2.Split('.');
//int h2 = int.Parse(part2[0]);
//int m2 = int.Parse(part2[1]);
//int totalHours = h1 + h2;
//int totalMinutes = m1 + m2;
//if (totalMinutes >= 60)
//{
// totalHours = totalHours + 1;
// totalMinutes = totalMinutes % 60;
//}
var times = new List<string>
{
TextBox1.Text,TextBox2.Text
};
TimeSpan total = new TimeSpan();
foreach (var thisString in times)
{
var split = thisString.Split('.');
total = total.Add(new TimeSpan(int.Parse(split[0]), int.Parse(split[1]), 0));
}
var totalHours = (int)total.TotalHours;
var totalMinutes = total.Minutes;
TextBox3.Text = totalHours.ToString() + "." + totalMinutes.ToString();
from gridview
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "select * from totalHours";
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
TimeSpan total = new TimeSpan();
var times = new List<string> ();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
times.Add((GridView1.Rows[i].Cells[0].Text));
}
foreach (var thisString in times)
{
var split = thisString.Split('.');
total = total.Add(new TimeSpan(int.Parse(split[0]), int.Parse(split[1]), 0));
}
var totalHours = (int)total.TotalHours;
var totalMins = total.Minutes;
Label2.Text = totalHours.ToString() + "." + totalMins.ToString();
thank you again #CodingYoshi

Here I am adding 2 of them and you can do the rest:
var t1 = new TimeSpan(256, 20, 0);
var t2 = new TimeSpan(257, 41, 0);
var tTotal = t1.Add(t2).ToString(#"dd\.hh\:mm\:ss");
tTotal will display the days, hours, minutes and seconds of adding t1 and t2;
If you want to do them using a loop, you can do it like this:
var times = new List<string>
{
"256.20",
"257.41",
"114.50",
"371.20",
"1000.11"
};
TimeSpan total = new TimeSpan();
foreach (var thisString in times)
{
var split = thisString.Split('.');
total = total.Add(new TimeSpan(int.Parse(split[0]), int.Parse(split[1]), 0));
}
var totalDisplay = total.ToString(#"dd\.hh\:mm\:ss");
If you want the total hours and minutes:
var totalHours = (int)total.TotalHours;
var totalMins = total.Minutes;

Related

C# How can I get timer to tick properly?

Making an application that can take Youtube links and add them to a queue and then play them until the queue is empty. Currently my timer1_Tick doesn't seem to be executing and I'm not sure why :(
//timer1_Tick
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
Video.Movie = "";
q.Dequeue();
qq.Dequeue();
}
Here is the meat and potatoes
if (e.ChatMessage.Message.StartsWith("!songrequest"))
{
var myString = e.ChatMessage.Message.ToString();
var newString = myString.Remove(0, myString.IndexOf(' ') + 1);
var getID = newString.Remove(0, newString.IndexOf('=') + 1);
var vUrl = "https://www.youtube.com/v/" + getID + "&autoplay=1";
var vUrlString = vUrl.ToString();
q.Enqueue(vUrlString);
qq.Enqueue(getID.ToString());
string[] array = new string[q.Count];
string[] array2 = new string[qq.Count];
q.CopyTo(array, 0);
qq.CopyTo(array2, 0);
if (timer1.Enabled == false)
{
for (int i = 0; i < array.Length; i++)
{
YouTubeVideo video = new Helix.YouTubeVideo(array2[i]);
var gDur = getDuration(video.duration);
string[] time = gDur.ToString().Split(' ');
int min = int.Parse(time[0]);
int sec = int.Parse(time[1]);
int msm = min * 60000;
int mss = sec * 1000;
int dur = msm + mss;
timer1.Interval = dur;
Video.Movie = array[i];
timer1.Start();
client.SendMessage("Now playing: " + video.title + ".");
client.SendMessage($"Timer set to { dur } ms.");
}
}
else
{
client.SendMessage("It's still running somehow.");
}
here you are checking disabled timer and only if it is not enabled it will go into condition..
if (timer1.Enabled == false)
{
for (int i = 0; i < array.Length; i++)
{
YouTubeVideo video = new Helix.YouTubeVideo(array2[i]);
var gDur = getDuration(video.duration);
string[] time = gDur.ToString().Split(' ');
int min = int.Parse(time[0]);
int sec = int.Parse(time[1]);
int msm = min * 60000;
int mss = sec * 1000;
int dur = msm + mss;
timer1.Interval = dur;
Video.Movie = array[i];
timer1.Start();
client.SendMessage("Now playing: " + video.title + ".");
client.SendMessage($"Timer set to { dur } ms.");
}
}
so if you are starting timer, on timer1.Start(), you need to enable it first.
try
if (timer1.Enabled == false)
{
timer1.Enabled = true;
for (int i = 0; i < array.Length; i++)
{
YouTubeVideo video = new Helix.YouTubeVideo(array2[i]);
var gDur = getDuration(video.duration);
string[] time = gDur.ToString().Split(' ');
int min = int.Parse(time[0]);
int sec = int.Parse(time[1]);
int msm = min * 60000;
int mss = sec * 1000;
int dur = msm + mss;
timer1.Interval = dur;
Video.Movie = array[i];
timer1.Start();
client.SendMessage("Now playing: " + video.title + ".");
client.SendMessage($"Timer set to { dur } ms.");
}
}
You need to enable the timer, its defaulted to false.

Wpf C# DateTime Database

I have two tables in my database, energyinfo (t1) and enerfyinfometers (t2).
I have a start and stop time in t1 like 500 min difference.
I want to add the time in between t1 (start and stop) for every one minute in t2.
Here's my code. it takes a lot of time to run and t1 entries is happening but fails to do t2.
if (dbContext == null)
{
dbContext = Context.Create("d:\\temp\\new.sdf", "");
var start = DateTime.Now;
DateTime time = DateTime.Now;
DateTime time2 = DateTime.Now;
// time = time + TimeSpan.FromMinutes(30);
time2 = time2 + TimeSpan.FromMinutes(1);
Random rnd = new Random();
double Counter = 50;
var stop = start.AddMinutes(15);
double value2 =36;
for (int i = 1; i < 36; i++)
{
Counter = Counter + 0.5;
double value3 = rnd.Next (2,12) +0.5;
double value4 = value3 / 2;
double value = rnd.Next(50) + 0.5;
value2 += (value / 60);
double roundedValue = Math.Ceiling(value2) + 1;
int LMH = rnd.Next(0, 3);
dbContext.EnergyInfo.Add(new EnergyInfo()
{ EId = i,
Timestamp = time, type = LMH,
startTime = start, stopTime = stop,
demandCharge = value3,
threshHold = 70,
normalCharge = value4,
peakDuration = 900 });
dbContext.SaveChanges();
for (var x = start; x < stop; x.AddMinutes(1))
{
var ob = new EnergyMeterInfo() { Timestamp = x, MeterId = 5,
powerConsumptionKW = Counter,
cumlativePwrConsumption = roundedValue,
EnergyInfoId = i };
using (dbContext.Database.BeginTransaction())
{
dbContext.EnergyMeterInfo.Add(ob);
}
}
start = stop;
stop = start.AddMinutes(500);
dbContext.SaveChanges();
}
}
MessageBox.Show(dbContext.EnergyInfo.Count() + " Records found !" + dbContext.EnergyMeterInfo.Count() + " found");
x.AddMinutes(1) does not change the value of x. Instead it returns a new DateTime instance, which you should then assign to x.
The loop should therefore look like this:
for (var x = start; x < stop; x = x.AddMinutes(1))
{
...
}

How to iterate date in for loop?

I have some values.
DateTime date=04/03/2015(date)
Total Woring days=6 (total)
Rotation Days=2 (rotationday)
Shift Group=S1(this group contain two shift id 1 and 2)
I want to run the shift for 6 days. but after each 2 days Shift id 1 rotate to shift id 2 and again after two days shift id 2 rotate to shift id 1 and so on...
My output should be like
04/03/2015=1
05/03/2015=1
06/03/2015=2
07/03/2015=2
08/03/2015=1
09/03/2015=1
I am getting shift id through a foreach loop. I tried like below mentioned way but not getting a proper resul. Please help me solve this issue
SqlCommand cmd2 = new SqlCommand("select ShiftID from ShiftGroup where
ShiftName='" + ide + "'", conn2);
SqlDataAdapter sda2 = new SqlDataAdapter(cmd2);
DataSet ds4 = new DataSet();
var rows2 = ds4.Tables[0].Rows;
if (ds4.Tables[0].Rows.Count > 0)
{
foreach (DataRow row2 in rows2)
{
string shiftname = Convert.ToString(row2["ShiftID"]);
DateTime date=04/03/2015(date)
Total Woring days=6 (total)
Rotation Days=2 (rotationday)
DateTime rotation= date.AddDays(rotationday);//
DateTime totaldate = date.AddDays(workingdays);
for (DateTime rotation = date; rotation <= totaldate; rotation = rotation.AddDays(1))//total working days
{
//to check rotation date
if (rotation <= totaldate )
{
allocation.shiftallocation( rotation, shiftid);
}
}
}
I am stucked with this from last day, anybody help me . No need of consider my for loop, kindly provide a for loop which generate the above mentioned output
You can try this,
DateTime date=DateTime.ParseExact("04/03/2015","dd/MM/yyyy",CultureInfo.InvariantCulture);
DateTime totaldate = date.AddDays(6);
for (int i=0; date <= totaldate; date = date.AddDays(1),i++)//total working days
{
if((i/2)%2==0)
Console.WriteLine(date+" "+1);
else
Console.WriteLine(date+" "+2);
}
Don't use dates at loop cycle, use abstract indicies. You can really abstract from concrete numbers and use only variables for managing result. So you can easily change rotationDays count and even workshifts labels array without changing cycle.
var date = DateTime.Parse("04/03/2015");
var totalWorkingDays = 15;
var rotationDays = 2;
var workshifts = new[] { "S1", "S2" };
var currentWorkshiftIndex = 0;
for (int dayIndex = 0; dayIndex <= totalWorkingDays; dayIndex++) {
if (dayIndex != 0 && dayIndex % rotationDays == 0) currentWorkshiftIndex = (currentWorkshiftIndex + 1) % workshifts.Length;
Console.WriteLine(date.AddDays(dayIndex) + " " + workshifts[currentWorkshiftIndex]);
}
var date = DateTime.Parse("04/03/2015");
var totalWorkingDays = 6;
var rotationDays = 2;
var rotationId = 1;
var rotationCounter = 1;
for (DateTime rotation = date;
rotation <= date.AddDays(totalWorkingDays);
rotation = rotation.AddDays(1))
{
Console.WriteLine(rotation + " " + rotationId);
if (rotationCounter++ == 2)
{
rotationCounter = 1;
rotationId = 3 - rotationId;
}
}
Or, with a linq query
var date = DateTime.Parse("04/03/2015");
var totalWorkingDays = 6;
var rotationDays = 2;
foreach (var d in Enumerable.Range(0, totalWorkingDays)
.Select((i, index) => date.AddDays(i) +
(((int)(index / rotationDays)) % 2 == 1 ? " 2" : " 1")))
{
Console.WriteLine(d);
}
According to your comment for the 5 working days a week, I wrote this:
var start = new DateTime(2015, 04, 03);
var working_day_count = 6;
var rotation_interval = 2;
var shifts = new List<int> { 1, 2 };
var rotation_count = 1;
var shift_index = 0;
for (var i = 0; i < working_day_count; i++) {
while ((start.DayOfWeek == DayOfWeek.Saturday) ||
(start.DayOfWeek == DayOfWeek.Sunday)) {
start = start.AddDays(1);
}
Console.WriteLine(start.ToString() + " = " + shifts[shift_index].ToString());
start = start.AddDays(1);
rotation_count++;
if (rotation_count > rotation_interval) {
rotation_count = 1;
shift_index++;
if (shift_index >= shifts.Count) {
shift_index = 0;
}
}
}
Just change the values of the first four varibales as you like.
I tried to make it easy to understand instead of performant or compact.
A generic solution with holidays taken into account.
int totalDays = 10;
int rotationDays = 3;
int[] shifts = new[] { 1, 2 };
string startDate = "04/03/2015";
var holidays = new List<DayOfWeek>(new[] { DayOfWeek.Saturday, DayOfWeek.Sunday, DayOfWeek.Tuesday });
var shiftAllocations = new Dictionary<DateTime, int>();
int currentShiftIndex = 0;
DateTime current = DateTime.ParseExact(startDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
for (int i = 0; i < totalDays; i += rotationDays)
{
var currentShiftId = shifts[currentShiftIndex];
// For each day from the current day till the number of shift rotation days, allocate the shift.
for (int j = 0; j < rotationDays;)
{
// If the current day is a holiday, move to the next day by incrementing i.
if (holidays.Contains(current.AddDays(i + j).DayOfWeek))
{
i++;
continue;
}
shiftAllocations.Add(current.AddDays(i + j), currentShiftId);
j++;
}
// Increase the shift index if the value is within the bounds. If not reset the index to the beginning
if ((currentShiftIndex + 1) >= shifts.Length)
currentShiftIndex = 0;
else
currentShiftIndex++;
}
foreach (var kvp in shiftAllocations)
{
Console.WriteLine(kvp.Key.ToString("dd/MM/yyyy") + ":" + kvp.Value);
}

Execute array values in query c#

I'm busy with a task program and then I came on to a problem!
Here is my code:
int id = 1;
List<Button> _bListGroups = new List<Button>();
MySqlCommand mcCommandUserID = new MySqlCommand("SELECT * FROM pakket WHERE gebruikersid=#id", _msConnection);
mcCommandUserID.Parameters.AddWithValue("#id", id);
MySqlDataReader msReader = mcCommandUserID.ExecuteReader();
DataTable dtGetUserid = new DataTable();
dtGetUserid.Load(msReader);
string[] nummer = new string[10];
int i = 0;
foreach (DataRow row in dtGetUserid.Rows)
{
nummer[i] = row["groepsid"].ToString();
i++;
}
MySqlCommand msCommandGetGroup = new MySqlCommand("SELECT * FROM groep WHERE id=#id",_msConnection);
msCommandGetGroup.Parameters.AddWithValue("#id", nummer[i]);
MySqlDataReader msGetGroup = msCommandGetGroup.ExecuteReader();
DataTable dtGetGroup = new DataTable();
dtGetGroup.Load(msGetGroup);
int mtop = 10;
int mleft = 15;
int count = 1;
foreach (DataRow dr in dtGetGroup.Rows)
{
Button temp = new Button();
temp.Name = "bt" + dr["id"];
temp.Text = (string)dr["groepsnaam"];
temp.Width = 125;
temp.Height = 125;
temp.Left = mleft;
temp.Top = mtop;
mleft += 127;
if (count == 2)
{
mtop += 125;
mleft = 15;
count = 0;
}
count++;
_bListGroups.Add(temp);
}
return _bListGroups.ToArray();
When i give my array a specific number(like nummer[1]) i get one button back but if I use the variable i, it doesn't give me any buttons. I already tried to debug it but I couldn't solve it.
Note that you are increasing i in the end of every iteration. So in the end i is greater than the last assigned index by 1. Therefore you need i-1:
msCommandGetGroup.Parameters.AddWithValue("#id", nummer[i-1]);
Also you might want to have some prechecks here for edge cases, say when there is no rows in dtGetUserid.Rows.
You've failed to reset your counter.
the variable i is at this stage:
msCommandGetGroup.Parameters.AddWithValue("#id", nummer[i]);
set to an array index which you havent allocated with any values.

show every result of foreach loop

I made a <List>DateTime class which named GetDataRange so that users can get days between two specific days.
Then I want to show days in the columns of data grid view. I use a foreach loop, This loop will cause a problem. The problem is it won't show all days in the columns because I want to show all days in other calendar. see the codes :
for (int i = 0; i < dtEnd.Subtract(dtStart).Days; i++)
{
TimeSpan counter = new TimeSpan(i, 0, 0, 0);
string s1 = "10/9/2012";
string s2 = "11/10/2012";
d1 = Convert.ToDateTime(s1);
d2 = Convert.ToDateTime(s2);
foreach (DateTime item in GetDateRange(d1, d2))
{
s = item.ToShortDateString();
}
PersianCalendar p = new PersianCalendar();
DateTime date = Convert.ToDateTime(s);
int day = p.GetDayOfMonth(date);
int month = p.GetMonth(date);
int year = p.GetYear(date);
string dt = string.Format("{0}/{1}/{2}", year, month, day);
dataGridView1.Columns.Add(string.Format("col{0}", i), string.Format("{0} {1}", (dtStart + counter).DayOfWeek.ToString(), dt));
}
It will show only one day because of that foreach loop. DayOfWeek is working perfectly but the problem is showing the days in foreach loop it will only show one day.
UPDATE
string dt only show one day it won't show other days.
You can't do that. because every time in the loop you are overriding the value. can you show the dates in a new row.
Try this :
for (int i = 0; i < dtEnd.Subtract(dtStart).Days; i++)
{
TimeSpan counter = new TimeSpan(i, 0, 0, 0);
dataGridView1.Columns.Add(string.Format("col{0}", i), string.Format("{0}", (dtStart + counter).DayOfWeek.ToString()));
}
Then add new row for that :
d1 = dtStart;
d2 = dtEnd;
foreach (DateTime item in GetDateRange(d1, d2))
{
int day = p.GetDayOfMonth(item);
int month = p.GetMonth(item);
int year = p.GetYear(item);
string dt1 = string.Format("{0}/{1}/{2}", year, month, day);
listBox1.Items.Add(dt1);
}
dataGridView1.Rows.Add();
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
try
{
dataGridView1.Rows[0].Cells[i].Value = listBox1.Items[i];
}
catch (Exception)
{
}
}

Categories