Wpf C# DateTime Database - c#

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))
{
...
}

Related

Adding multiple times in (HH.mm)

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;

VB6 Math.Random to C# Code

So I have the following code in VB6
string CharString = "KO0LPBGt7HU8NJI9acfDXESvgbYujmikolpw3MZWAQyhn6TFCR1q2Vzse4xdr5";
string DatePassword = string.Empty;
float x = VBMath.Rnd(-1);
DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
x = VBMath.Rnd(-1);
VBMath.Randomize(dt.ToOADate());
for (int i=0; i<6; i++)
{
double y = Math.Truncate(VBMath.Rnd()*62);
DatePassword += CharString.Substring( Convert.ToInt32(y), 1);
}
I am having trouble converting this code over to C#. In particular how call randomize with the seed being a double. Here is my attempt in C#
string CharString = "KO0LPBGt7HU8NJI9acfDXESvgbYujmikolpw3MZWAQyhn6TFCR1q2Vzse4xdr5";
string DatePassword = string.Empty;
Random rnd = new Random(-1);
float x = rnd.Next();
DateTime dt = new DateTime(DateTime.Now.Year + DateTime.Now.Month + 1);
x = rnd.Next();
double z = rnd.NextDouble() * dt.ToOADate();
for (int i = 0; i < 6; i++)
{
x = rnd.Next();
double y = Math.Truncate(x * 62);
DatePassword += CharString.Substring(Convert.ToInt32(y), 1);
}

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.

Odd C# behavior

I'm a hobby programmer.
I tried to ask this question earlier on a very unstructured way (Sorry again), now I try to ask on the proper way.
I wrote the following code that seems to work unreliably.
The code was written like this for several reasons. I know it's messy but it should still work. To explain why I wrote it like this would mean that I need to explain several weeks' of work that is quite extensive. Please accept that this is at least the least worse option I could figure out. In the below sample I removed all sections of the code that are not needed to reproduce the error.
What this program does in a nutshell:
The purpose is to check a large number of parameter combinations for a program that receives streaming data. I simulate the original process to test parameter combinations.
First data is read from files that represents recorded streaming data.
Then the data is aggregated.
Then I build a list of parameters to test for.
Finally I run the code for each parameter combination in parallel.
Inside the parallel part I calculate a financial indicator called the bollinger bands. This is a moving average with adding +/- standard deviation. This means the upper line and the lower line should only be equal when variable bBandDelta = 0. However sometimes it happens that CandleList[slot, w][ctr].bollingerUp is equal to CandleList[slot, w][ctr].bollingerDown even when bBandDelta is not 0.
As a result I don't understand how can line 277 kick in. It seems that sometimes the program fails to write to the CandleList[slot, w][ctr]. However this should not be possible because (1) I lock the list and (2) I use ConcurrentBag. Could I have some help please?
Source files are here.
The code is:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Concurrent;
namespace Justfortest
{
class tick : IComparable<tick> //Data element to represent a tick
{
public string disp_name; //ticker ID
public DateTime? trd_date; //trade date
public TimeSpan? trdtim_1; //trade time
public decimal trdprc_1; //price
public int? trdvol_1; //tick volume
public int CompareTo(tick other)
{
if (this.trdprc_1 == other.trdprc_1)
{
return other.trdprc_1.CompareTo(this.trdprc_1); //Return the later item
}
return this.trdprc_1.CompareTo(other.trdprc_1); //Return the earlier item
}
}
class candle : IComparable<candle> //Data element to represent a candle and all chart data calculated on candle level
{
public int id = 0;
public DateTime? openDate;
public TimeSpan? openTime;
public DateTime? closeDate;
public TimeSpan? closeTime;
public decimal open = 0;
public decimal high = 0;
public decimal low = 0;
public decimal close = 0;
public int? volume = 0;
public decimal totalPrice = 0;
public decimal bollingerUp = 0; //Bollinger upper line
public decimal bollingerDown = 0; //Bollinger below line
public int CompareTo(candle other)
{
if (totalPrice == other.totalPrice)
{
return other.totalPrice.CompareTo(totalPrice); //Return the later item
}
return totalPrice.CompareTo(other.totalPrice); //Return the earlier item
}
}
class param : IComparable<param> //Data element represent a trade event signal
{
public int par1;
public int bollPar;
public int par2;
public int par3;
public int par4;
public int par5;
public int par6;
public decimal par7;
public decimal par8;
public decimal par9;
public decimal par10;
int IComparable<param>.CompareTo(param other)
{
throw new NotImplementedException();
}
}
class programCLass
{
void myProgram()
{
Console.WriteLine("Hello");
Console.WindowWidth = 180;
string[] sources = new string[]
{
#"C:\test\source\sourceW1.csv",
#"C:\test\source\sourceW2.csv",
};
List<candle>[] sourceCandleList = new List<candle>[sources.Count()];
List<param> paramList = new List<param>(10000000);
var csvAnalyzer = new StringBuilder();
{
List<tick>[] updatelist = new List<tick>[sources.Count()];
Console.WriteLine("START LOAD");
for (var i = 0; i < sources.Count(); i++)
{
var file = sources[i];
updatelist[i] = new List<tick>();
// ---------- Read CSV file ----------
var reader = new StreamReader(File.OpenRead(file));
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
tick update = new tick();
update.disp_name = values[0].ToString();
update.trd_date = Convert.ToDateTime(values[1]);
update.trdtim_1 = TimeSpan.Parse(values[2]);
update.trdprc_1 = Convert.ToDecimal(values[3]);
update.trdvol_1 = Convert.ToInt32(values[4]);
updatelist[i].Add(update);
}
Console.WriteLine(i);
}
Console.WriteLine("END LOAD"); // All files are in the memory
// Aggreagate
Console.WriteLine("AGGREGATE START");
int tickAggr = 500;
for (var w = 0; w < sources.Count(); w++)
{
sourceCandleList[w] = new List<candle>();
List<tick> FuturesList = new List<tick>();
foreach (var update in updatelist[w])
{
tick t = new tick();
t.disp_name = update.disp_name.ToString();
t.trd_date = update.trd_date;
t.trdtim_1 = update.trdtim_1;
t.trdprc_1 = Convert.ToDecimal(update.trdprc_1);
t.trdvol_1 = update.trdvol_1;
// Add new tick to the list
FuturesList.Add(t);
if (FuturesList.Count == Math.Truncate(FuturesList.Count / (decimal)tickAggr) * tickAggr)
{
candle c = new candle();
c.openDate = FuturesList[FuturesList.Count - tickAggr].trd_date;
c.openTime = FuturesList[FuturesList.Count - tickAggr].trdtim_1;
c.closeDate = FuturesList.Last().trd_date;
c.closeTime = FuturesList.Last().trdtim_1;
c.open = FuturesList[FuturesList.Count - tickAggr].trdprc_1;
c.high = FuturesList.GetRange(FuturesList.Count - tickAggr, tickAggr).Max().trdprc_1;
c.low = FuturesList.GetRange(FuturesList.Count - tickAggr, tickAggr).Min().trdprc_1;
c.close = FuturesList.Last().trdprc_1;
c.volume = FuturesList.GetRange(FuturesList.Count - tickAggr, tickAggr).Sum(tick => tick.trdvol_1);
c.totalPrice = (c.open + c.high + c.low + c.close) / 4;
sourceCandleList[w].Add(c);
if (sourceCandleList[w].Count == 1)
{
c.id = 0;
}
else
{
c.id = sourceCandleList[w][sourceCandleList[w].Count - 2].id + 1;
}
}
}
FuturesList.Clear();
}
Console.WriteLine("AGGREGATE END");
for (var i = 0; i < sources.Count(); i++)
{
updatelist[i].Clear();
}
}
Console.WriteLine("BUILD PARAMLIST");
for (int par1 = 8; par1 <= 20; par1 += 4) // parameter deployed
{
for (int bollPar = 10; bollPar <= 25; bollPar += 5) // parameter deployed
{
for (int par2 = 6; par2 <= 18; par2 += 4) // parameter deployed
{
for (int par3 = 14; par3 <= 20; par3 += 3) // parameter deployed
{
for (int par4 = 10; par4 <= 20; par4 += 5) // parameter deployed
{
for (int par5 = 4; par5 <= 10; par5 += 2) // parameter deployed
{
for (int par6 = 5; par6 <= 30; par6 += 5)
{
for (decimal par7 = 1.0005M; par7 <= 1.002M; par7 += 0.0005M)
{
for (decimal par8 = 1.002M; par8 <= 1.0048M; par8 += 0.0007M)
{
for (decimal par9 = 0.2M; par9 <= 0.5M; par9 += 0.1M)
{
for (decimal par10 = 0.5M; par10 <= 2; par10 += 0.5M)
{
param p = new param();
p.par1 = par1;
p.bollPar = bollPar;
p.par2 = par2;
p.par3 = par3;
p.par4 = par4;
p.par5 = par5;
p.par6 = par6;
p.par7 = par7;
p.par8 = par8;
p.par9 = par9;
p.par10 = par10;
paramList.Add(p);
}
}
}
}
}
}
}
}
}
}
}
Console.WriteLine("END BUILD PARAMLIST, scenarios to test:{0}", paramList.Count);
var sourceCount = sources.Count();
sources = null;
Console.WriteLine("Start building pools");
int maxThreads = 64;
ConcurrentBag<int> pool = new ConcurrentBag<int>();
List<candle>[,] CandleList = new List<candle>[maxThreads, sourceCount];
for (int i = 0; i <= maxThreads - 1; i++)
{
pool.Add(i);
for (int w = 0; w <= sourceCount - 1; w++)
{
CandleList[i, w] = sourceCandleList[w].ConvertAll(p => p);
}
}
Console.WriteLine("End building pools");
int pItemsProcessed = 0;
Parallel.ForEach(paramList,
new ParallelOptions { MaxDegreeOfParallelism = maxThreads },
p =>
{
int slot = 1000;
while (!pool.TryTake(out slot));
var bollPar = p.bollPar;
decimal bollingerMiddle = 0;
double bBandDeltaX = 0;
for (var w = 0; w < sourceCount; w++)
{
lock (CandleList[slot, w])
{
for (var ctr = 0; ctr < CandleList[slot, w].Count; ctr++)
{
CandleList[slot, w][ctr].bollingerUp = 0; //Bollinger upper line
CandleList[slot, w][ctr].bollingerDown = 0; //Bollinger below line
//Bollinger Bands Calculation
if (ctr + 1 >= bollPar)
{
bollingerMiddle = 0;
bBandDeltaX = 0;
for (int i = 0; i <= bollPar - 1; i++)
{
bollingerMiddle = bollingerMiddle + CandleList[slot, w][ctr - i].totalPrice;
}
bollingerMiddle = bollingerMiddle / bollPar; //average
for (int i = 0; i <= bollPar - 1; i++)
{
bBandDeltaX = bBandDeltaX + (double)Math.Pow(System.Convert.ToDouble(CandleList[slot, w][ctr - i].totalPrice) - System.Convert.ToDouble(bollingerMiddle), 2);
}
bBandDeltaX = bBandDeltaX / bollPar;
decimal bBandDelta = (decimal)Math.Sqrt(System.Convert.ToDouble(bBandDeltaX));
CandleList[slot, w][ctr].bollingerUp = bollingerMiddle + 2 * bBandDelta;
CandleList[slot, w][ctr].bollingerDown = bollingerMiddle - 2 * bBandDelta;
if (CandleList[slot, w][ctr].bollingerUp == CandleList[slot, w][ctr].bollingerDown)
{
Console.WriteLine("?! Items processed=" + pItemsProcessed + " bollPar=" + bollPar + " ctr=" + ctr + " bollingerMiddle=" + bollingerMiddle + " bBandDeltaX=" + bBandDeltaX + " bBandDelta=" + bBandDelta + " bollingerUp=" + CandleList[slot, w][ctr].bollingerUp + " bollingerDown=" + CandleList[slot, w][ctr].bollingerDown);
}
}
// REMOVED Further calculations happen here
}
// REMOVED Some evaluations happen here
}
}
// REMOVED Some more evaluations happen here
Interlocked.Increment(ref pItemsProcessed);
pool.Add(slot);
});
}
static void Main(string[] args)
{
var P = new programCLass();
P.myProgram();
}
}
}

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);
}

Categories