Representation of date and time.
Exemple #1
1
 public object WithRefsWithReturn(
     ref string param1,
     ref int param2,
     ref short param3,
     ref long param4,
     ref uint param5,
     ref ushort param6,
     ref ulong param7,
     ref bool param8,
     ref double param9,
     ref decimal param10,
     ref int? param11,
     ref object param12,
     ref char param13,
     ref DateTime param14,
     ref Single param15,
     ref IntPtr param16,
     ref UInt16 param17,
     ref UInt32 param18,
     ref UInt64 param19,
     ref UIntPtr param20
     )
 {
     throw new Exception("Foo");
 }
 /// <summary>
 /// ดึงรายชื่อพนักงานตามเงื่อนไขที่กำหนด เพื่อนำไปแสดงบนหน้า ConvertByPayor
 /// </summary>
 /// <param name="doeFrom"></param>
 /// <param name="doeTo"></param>
 /// <param name="payor"></param>
 /// <returns></returns>
 public DataTable getPatient(DateTime doeFrom,DateTime doeTo,string payor,string mobileStatus)
 {
     System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
     #region Variable
     var dt = new DataTable();
     var strSQL = new StringBuilder();
     var clsSQL = new clsSQLNative();
     #endregion
     #region Procedure
     #region SQLQuery
     strSQL.Append("SELECT ");
     strSQL.Append("No,HN,PreName,Name,LastName,DOE,Payor,SyncWhen,'0' IsConvertPreOrder ");
     strSQL.Append("FROM ");
     strSQL.Append("Patient P ");
     strSQL.Append("WHERE ");
     strSQL.Append("(DOE BETWEEN '" + doeFrom.ToString("yyyy-MM-dd HH:mm") + "' AND '" + doeTo.ToString("yyyy-MM-dd HH:mm") + "') ");
     if(payor!="" && payor.ToLower() != "null")
     {
         strSQL.Append("AND Payor='"+payor+"' ");
     }
     if (mobileStatus == "NotRegister")
     {
         strSQL.Append("AND SyncStatus!='1' ");
     }
     else if (mobileStatus == "Register")
     {
         strSQL.Append("AND SyncStatus='1' ");
     }
     strSQL.Append("ORDER BY ");
     strSQL.Append("No;");
     #endregion
     dt = clsSQL.Bind(strSQL.ToString(), clsSQLNative.DBType.SQLServer, "MobieConnect");
     #endregion
     return dt;
 }
	void Blink ()
	{
		/*while (running) {
			//BEFORE - Easy on Processor / Not Accurate
			/*int resto = DateTime.Now.Millisecond % delay;
			state = !state;
			Thread.Sleep(delay-resto);*/

			//AFTER - Accurate / Hard on Processor
			/*DateTime now = DateTime.Now;
			 if(now.Subtract(before).Milliseconds >= delay){
				state = !state;
				before = DateTime.Now;
			 }


			//COMBINED - Accurate / Easy on Processor
			DateTime now = DateTime.Now;
			Thread.Sleep(delay - now.Subtract(before).Milliseconds);
			state = !state;
			before = DateTime.Now;
		}*/

        DateTime now = DateTime.Now;
        if (now.Subtract(before).Milliseconds >= delay)
        {
            state = !state;
            before = DateTime.Now;
        }
	}
    private void CompareDates(string name, int month, int day, DateTime SelectedDate)
    {
        //create a DateTime object that is my birthday in the year selected
        DateTime myBirthDay = new DateTime(SelectedDate.Year, 3, 28);

        if (SelectedDate < myBirthDay) {
            lbl.Text += "<br />This date is before " + name + "Travis's Birthday";

        }
        else if (SelectedDate > myBirthDay) {
            lbl.Text += "<br />This date is after Travis's Birthday";

        }
        else {
            lbl.Text += "<br />Party Time";
        }

        if (SelectedDate < myBirthDay) {
            lbl.Text += "<br />This date is before " + name + "Travis's Birthday";

        }
        else if (SelectedDate > myBirthDay) {
            lbl.Text += "<br />This date is after Travis's Birthday";

        }
        else {
            lbl.Text += "<br />Party Time";
        }
    }
        /// <summary>
        /// Tries to parse a string to a DateTime.
        /// </summary>
        /// <param name="text">The text that should be parsed.</param>
        /// <param name="culture">The culture being used.</param>
        /// <param name="result">The parsed DateTime.</param>
        /// <returns>
        /// True if the parse was successful, false if it was not.
        /// </returns>
        /// <remarks>The parsing is culture insensitive. A user can type 8p to
        /// indicate 20:00:00, or 20.</remarks>
        public override bool TryParse(string text, CultureInfo culture, out DateTime? result)
        {
            Match match = exp.Match(text);

            if (match.Success)
            {
                bool pm = text.Contains("p", StringComparison.OrdinalIgnoreCase);

                result = null;

                int hours = int.Parse(match.Groups["hours"].Value, culture);
                if (hours > 23)
                {
                    return false;
                }
                int minutes = match.Groups["minutes"].Success && match.Groups["minutes"].Value.Length > 0 ? int.Parse(match.Groups["minutes"].Value, culture) : 0;
                if (minutes > 59)
                {
                    return false;
                }
                int seconds = match.Groups["seconds"].Success && match.Groups["seconds"].Value.Length > 0 ? int.Parse(match.Groups["seconds"].Value, culture) : 0;
                if (seconds > 59)
                {
                    return false;
                }

                result = DateTime.Now.Date.AddHours(hours).AddMinutes(minutes).AddSeconds(seconds);
                result = result.Value.AddHours(pm && hours < 12 ? 12 : 0);
                return true;
            }
            result = null;
            return false;
        }
Exemple #6
0
 private void SetInitInputTime(DateTime time)
 {
     Configuration cfg = WebConfigurationManager.OpenWebConfiguration("~");
     cfg.AppSettings.Settings[theKeyName].Value = time.ToString();
     cfg.Save();
     Label1.Text = "初始录入结束时间已设置为" + time.ToString();
 }
Exemple #7
0
        public static void X509Cert2Test()
        {
            string certName = TestData.NormalizeX500String(
                @"[email protected], CN=ABA.ECOM Root CA, O=""ABA.ECOM, INC."", L=Washington, S=DC, C=US");

            DateTime notBefore = new DateTime(1999, 7, 12, 17, 33, 53, DateTimeKind.Utc).ToLocalTime();
            DateTime notAfter = new DateTime(2009, 7, 9, 17, 33, 53, DateTimeKind.Utc).ToLocalTime();

            using (X509Certificate2 cert2 = new X509Certificate2(Path.Combine("TestData", "test.cer")))
            {
                Assert.Equal(certName, cert2.IssuerName.Name);
                Assert.Equal(certName, cert2.SubjectName.Name);

                Assert.Equal("ABA.ECOM Root CA", cert2.GetNameInfo(X509NameType.DnsName, true));

                PublicKey pubKey = cert2.PublicKey;
                Assert.Equal("RSA", pubKey.Oid.FriendlyName);

                Assert.Equal(notAfter, cert2.NotAfter);
                Assert.Equal(notBefore, cert2.NotBefore);

                Assert.Equal("00D01E4090000046520000000100000004", cert2.SerialNumber);
                Assert.Equal("1.2.840.113549.1.1.5", cert2.SignatureAlgorithm.Value);
                Assert.Equal("7A74410FB0CD5C972A364B71BF031D88A6510E9E", cert2.Thumbprint);
                Assert.Equal(3, cert2.Version);
            }
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!IsPostBack)
     {
         if (Request.QueryString["m"] != null)
         {
             try
             {
                 ShowDate = ShowDate.AddMonths(Int32.Parse(Request.QueryString["m"]));
             }
             catch
             {
                 // ignore invalid 'm' parameter -- show current month
             }
         }
         ddMonth.Items.Add(new ListItem(System.DateTime.Now.ToString("MMMM yyyy"), "0"));
         ddMonth.Items.Add(new ListItem(System.DateTime.Now.AddMonths(-1).ToString("MMMM yyyy"), "-1"));
         if (Request.QueryString["m"] != null)
             ddMonth.SelectedValue = Request.QueryString["m"];
     }
     else
     {
         ErrorMessageLabel.Visible = false;
         GridView1.Visible = true;
     }
 }
Exemple #9
0
	public Niñera(int rut, int cv, int celular, int numero, int idRegion, int idProv, int idCom, int idEstado,
       string nombre, string ap, string am, DateTime fnac, string descrip, string calle, string villaP, string carrera,
        string casaEstudio, string correo, string clave, string fotoPerfil)
	{
        this.rut = rut;
        this.cv = cv;
        this.celular = celular;
        this.numero = numero;
        this.idRegion = idRegion;
        this.idProv = idProv;
        this.idCom = idCom;
        this.idEstado = idEstado;
        this.nombre = nombre;
        this.apellidoP = ap;
        this.apellidoM = am;
        this.fechaNac = fnac;
        this.Descrip = descrip;
        this.calle = calle;
        this.villaP = villaP;
        this.carrera = carrera;
        this.casaEstudio = casaEstudio;
        this.correo = correo;
        this.clave = clave;
        this.fotoPerfil = fotoPerfil;
	}
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        string sDate = Request.Form[txtStartDate.ID].Trim();
        string eDate = Request.Form[txtEndDate.ID].Trim();

        if (string.IsNullOrEmpty(sDate) && string.IsNullOrEmpty(eDate))
        {
            return;
        }
        else
        {
            DateTime startDate = new DateTime(1999, 1, 1);
            DateTime endDate = new DateTime(1999, 1, 1);
            if (!DateTime.TryParse(sDate, out startDate))
            {
                startDate = new DateTime(1999, 1, 1);
            }
            if (DateTime.TryParse(eDate, out endDate))
            {
                endDate = new DateTime(endDate.Year, endDate.Month, endDate.Day, 23, 59, 59);
            }
            else
            {
                endDate = new DateTime(1999, 1, 1);
            }
            PaginationQueryResult<WrongOrder> result = WrongOrderOperation.GetWrongOrderByCompanyIdAndDate(PaginationHelper.GetCurrentPaginationQueryCondition(Request), user.CompanyId, startDate, endDate);
            rpWrongOrder.DataSource = result.Results;
            rpWrongOrder.DataBind();

            pagi.TotalCount = result.TotalCount;
        }
    }
 // Constructors
 public Call(DateTime date, DateTime time, string dialedPhone, int duration)
 {
     this.Date = date;
     this.Time = time;
     this.DialedPhone = dialedPhone;
     this.Duration = duration;
 }
	void OnTick(object sender, EventArgs e)
	{
		Ped player = Game.Player.Character;

		if (Game.IsControlPressed(2, Control.VehicleExit) && DateTime.Now > this.mLastExit && player.IsInVehicle())
		{
			Wait(250);

			Vehicle vehicle = player.CurrentVehicle;
			bool isDriver = vehicle.GetPedOnSeat(VehicleSeat.Driver) == player;

			if (Game.IsControlPressed(2, Control.VehicleExit))
			{
				player.Task.LeaveVehicle(vehicle, true);
			}
			else
			{
				player.Task.LeaveVehicle(vehicle, false);

				Wait(0);

				if (isDriver)
				{
					vehicle.EngineRunning = true;
				}
			}

			this.mLastExit = DateTime.Now + TimeSpan.FromMilliseconds(2000);
		}
	}
    static bool IsHoliday(DateTime date)
    {
        DateTime[] holidays = new[]
        {
            new DateTime(date.Year, 1, 1),
            new DateTime(date.Year, 3, 3),
            new DateTime(date.Year, 5, 1),
            new DateTime(date.Year, 5, 2),
            new DateTime(date.Year, 5, 6),
            new DateTime(date.Year, 5, 24),
            new DateTime(date.Year, 9, 22),
            new DateTime(date.Year, 12, 24),
            new DateTime(date.Year, 12, 25),
            new DateTime(date.Year, 12, 26),
            new DateTime(date.Year, 12, 31),
        };

        if (date.DayOfWeek.ToString() == "Sunday" || date.DayOfWeek.ToString() == "Saturday")
        {
            return true;
        }

        foreach (DateTime holiday in holidays)
        {
            if (date == holiday)
            {
                return true;
            }
        }

        return false;
    }
    public static List<ReporteNotificacionGeocerca> ObtenerNotificacionesGeocerca(List<string> unidades, List<string> geocercas, DateTime fechaInicial, DateTime fechaFinal, int accion, string cliente)
    {
        List<ReporteNotificacionGeocerca> reporteFinal = new List<ReporteNotificacionGeocerca>();
        List<Vehiculo> vehiculos = AutentificacionBD.VehiculosCliente(cliente);
        string query = "SELECT     Unidad, accion, fechahora, geocerca, nombre, id_reportegeocerca " +
                       "FROM         vReporteGeocercaUTC " +
                       "WHERE     (Unidad IN (";
        foreach (string unidad in unidades)
            query += "'" + unidad + "', ";
        //quitar la última coma y espacio
        query = query.Remove(query.Length - 2);
        //agregar los dos paréntesis finales.
        query += ")) AND (fechahora between @fechainicial AND @fechafinal) ";
        if (accion == ReporteNotificacionGeocerca.AccionFuera)
        {
            query += "AND accion = 'Fuera' ";
        }
        else if(accion == ReporteNotificacionGeocerca.AccionDentro)
        {
            query += "AND accion = 'Dentro' ";
        }
        else if (accion == ReporteNotificacionGeocerca.AccionDentroFuera)
        {
            query += " AND (accion = 'Fuera' OR accion = 'Dentro') ";
        }
        query +="ORDER BY fechahora DESC";

        using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionStringBD"].ConnectionString))
        {
            sqlConnection.Open();
            using (SqlCommand sqlCommand = new SqlCommand(query,sqlConnection))
            {
                sqlCommand.Parameters.AddWithValue("@fechainicial", fechaInicial);
                sqlCommand.Parameters.AddWithValue("@fechafinal", fechaFinal);
                Hashtable nombresGeocercas = GeocercasBD.ConsultarGeocercasNombreBD(cliente);
                using (SqlDataReader reader = sqlCommand.ExecuteReader())
                {
                    while (reader.Read()){
                        string geocercaID= (string)reader["geocerca"];
                        if (geocercas.Where(x=>x.Equals(geocercaID)).ToList().Count == 1)
                        {
                            ReporteNotificacionGeocerca reporte = new ReporteNotificacionGeocerca();
                            string sVehiculo = (string)reader["Unidad"];
                            string sAccionBD = (string)reader["accion"];
                            reporte.VehiculoID = sVehiculo;
                            reporte.GeocercaID = geocercaID;
                            reporte.Fecha = (DateTime)reader["fechahora"];
                            reporte.Vehiculo = vehiculos.Find(x=> x.Unidad.Equals(sVehiculo)).Descripcion;
                            //reporte.Accion = sAccionBD == "Dentro"?Resources.Reportes.aspx.Dentro:Resources.Reportes.aspx.Fuera;
                            reporte.iAccion = sAccionBD == "Dentro" ? ReporteNotificacionGeocerca.AccionDentro : ReporteNotificacionGeocerca.AccionFuera;
                            reporte.Geocerca = nombresGeocercas[geocercaID].ToString();
                            reporteFinal.Add(reporte);
                        }
                    }
                }
            }
        }

        return reporteFinal.OrderBy(x => x.Fecha).ToList();
    }
    void Start()
    {
        _button = GetComponent<Button>();
        _button.interactable = false;

        _rewardCooldownTime = GetRewardCooldownTime();
    }
Exemple #16
0
 public static DateTime DiscardDayTime(DateTime d)
 {
     int year = d.Year;
     int month = d.Month;
     DateTime newD = new DateTime(year, month, 1, 0, 0, 0);
     return newD;
 }
    //改变时间
    public void radWeek_CheckedChanged(object sender, EventArgs e)
    {
        RadioButton rad = sender as RadioButton;
        if (rad.ID == "radDay")
        {
            this.txtBeginDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
        }
        if (rad.ID == "radWeek")
        {
            this.txtBeginDate.Text = DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek).ToString("yyyy-MM-dd"); ;

        }
        if (rad.ID == "radMonth")
        {
            DateTime now = DateTime.Now;
            DateTime nowMonth = new DateTime(now.Year, now.Month, 1);
            this.txtBeginDate.Text = nowMonth.ToString("yyyy-MM-dd");
        }
        if (rad.ID == "radThreeMonth")
        {
            DateTime now = DateTime.Now.AddMonths(-2);
            DateTime nowMonth = new DateTime(now.Year, now.Month, 1);
            this.txtBeginDate.Text = nowMonth.ToString("yyyy-MM-dd");
        }
    }
    private static int InsertNewBook(
        string filePath,
        string title,
        string author,
        DateTime publicationDate,
        string isbn)
    {
        SQLiteConnection connection = GetConnection(filePath);

        connection.Open();
        using (connection)
        {
            SQLiteCommand insertBookCommand = new SQLiteCommand(
                @"INSERT INTO Books (BookTitle, BookAuthor, PublicationDate, ISBN)
                  VALUES (@bookTitle, @bookAuthor, @publicationDate, @isbn)", connection);

            insertBookCommand.Parameters.AddWithValue("@bookTitle", title);
            insertBookCommand.Parameters.AddWithValue("@bookAuthor", author);
            insertBookCommand.Parameters.AddWithValue("@publicationDate", publicationDate);
            insertBookCommand.Parameters.AddWithValue("@isbn", isbn);

            int rowsAffected = insertBookCommand.ExecuteNonQuery();
            return rowsAffected;
        }
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        // recover querystring parameters:
        string temp;
        DateTime tempDate;
        temp = Request.QueryString["provider"];
        if (!string.IsNullOrEmpty(temp))
            _providerName = Page.Server.UrlDecode(temp);

        temp = Request.QueryString["report"];
        if (!string.IsNullOrEmpty(temp))
            _report = Page.Server.UrlDecode(temp);

        temp = Request.QueryString["view"];
        if (!string.IsNullOrEmpty(temp))
            _view = Page.Server.UrlDecode(temp);

        temp = Request.QueryString["startdate"];
        if (!string.IsNullOrEmpty(temp)) {
            if (DateTime.TryParse(Page.Server.UrlDecode(temp), out tempDate))
                _startDate = tempDate;
        }

        temp = Request.QueryString["enddate"];
        if (!string.IsNullOrEmpty(temp)) {
            if (DateTime.TryParse(Page.Server.UrlDecode(temp), out tempDate))
                _endDate = tempDate;
        }

        //Ektron.Cms.API.Css.RegisterCss(this, CommonAPIRef.AppPath + "Analytics/reporting/css/Reports.css", "AnalyticsReportCss");
    }
	/// <summary>
	/// Creates a new achievement object.
	/// </summary>
	/// <param name="id">A unique identifier.</param>
	/// <param name="percentCompleted">Percent completed.</param>
	/// <param name="completed">Completed.</param>
	/// <param name="hidden">Hidden.</param>
	/// <param name="lastReportedDate">Last reported date.</param>
	public LumosAchievement (string id, double percentCompleted, bool hidden, DateTime lastReportedDate)
	{
		this.id = id;
		this.percentCompleted = percentCompleted;
		this.hidden = hidden;
		this.lastReportedDate = lastReportedDate;
	}
Exemple #21
0
 public STD_CBEExam(
     int cBEExamID,
     string candidateName,
     DateTime dOB, 
     string gender, 
     string regiNo, 
     string instituteName, 
     string tel, 
     string mobile, 
     string email, 
     string feesDescription, 
     string addedBy, 
     DateTime addedDate, 
     string updatedBy, 
     DateTime updatedDate, 
     int rowStatusID
     )
 {
     this.CBEExamID = cBEExamID;
     this.CandidateName = candidateName;
     this.DOB = dOB;
     this.Gender = gender;
     this.RegiNo = regiNo;
     this.InstituteName = instituteName;
     this.Tel = tel;
     this.Mobile = mobile;
     this.Email = email;
     this.FeesDescription = feesDescription;
     this.AddedBy = addedBy;
     this.AddedDate = addedDate;
     this.UpdatedBy = updatedBy;
     this.UpdatedDate = updatedDate;
     this.RowStatusID = rowStatusID;
 }
Exemple #22
0
 public static DateTimeOffset ToClientTimeZone(long ticks, int zona)
 {
     var dt = new DateTime(ticks, DateTimeKind.Utc);
     var tz = TimeZoneInfo.GetSystemTimeZones().FirstOrDefault(b => b.BaseUtcOffset.Hours == zona);
     var utcOffset = new DateTimeOffset(dt, TimeSpan.Zero);
     return utcOffset.ToOffset(tz.GetUtcOffset(utcOffset));
 }
Exemple #23
0
    public bool PosTest1()
    {
        bool retVal = true;
        TestLibrary.TestFramework.BeginScenario("Verify DateTime.Hour property when DateTime instance's hour is assigned...");

        try
        {
            TestLibrary.Utilities.CurrentCulture = new CultureInfo("");
            DateTime myDateTime = new DateTime(0978, 08, 29, 03, 00, 00);
            int hour = myDateTime.Hour;

            if (hour != 3)
            {
                TestLibrary.TestFramework.LogError("001","The hour is not correct!");
                retVal = false;
            }

        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002","Unexpected exception occurs: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
 /// <summary>
 /// Récupère la liste des évenements
 /// </summary>
 /// <param name="date"></param>
 /// <param name="controler"></param>
 public async void InitEvent(DateTime date, EventControler controler)
 {
     Controler = controler;
     List<GoogleCalendar.Data.Event> events = await Controler.GetAllEvents();
     UpdateEvent(date, events);
     
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        var q = Request["q"];
        var size = Request["size"];
        if (string.IsNullOrEmpty(size)) size = "10";
        var trangThai = Request["TrangThai"];

        Ngay = Request["Ngay"];
        var url = string.Format("?q={0}&size={1}&TrangThai={2}&Ngay={3}&", q, size, trangThai, Ngay) + "{1}={0}";
        var tuNgay = "";
        var denNgay = "";
        if (!string.IsNullOrEmpty(Ngay))
        {
            Ngay = Server.UrlDecode(Ngay);
            var d = Convert.ToDateTime(Ngay, new CultureInfo("Vi-vn"));
            tuNgay = new DateTime(d.Year, d.Month, d.Day).AddDays(-1).ToString("yyyy-MM-dd");
            denNgay = new DateTime(d.Year, d.Month, d.Day).AddDays(1).ToString("yyyy-MM-dd");
        }

        using (var con = DAL.con())
        {

            var pg =
                PhieuDichVuDal.pagerTdToc(con, url, false, "PDV_Ma desc", q, Convert.ToInt32(size), trangThai
                , Security.UserId.ToString(), tuNgay, denNgay);
            List.List = pg.List;
            paging = pg.Paging;

        }
    }
    static void Main()
    {
        int start = 1;
        int end = 100;
        DateTime startDate = new DateTime(1980, 1, 1);
        DateTime endDate = new DateTime(2013, 12, 31);

        try
        {
            int number = ReadInteger(start, end);
            Console.WriteLine("Your number: " + number);
        }
        catch (InvalidRangeException<int> ex)
        {
            Console.WriteLine("{0}\nRange: [{1}...{2}]", ex.Message, ex.Start, ex.End);
        }

        try
        {
            DateTime date = ReadDate(startDate, endDate);
            Console.WriteLine("Your date: " + date.ToString(DATE_FORMAT));
        }
        catch (InvalidRangeException<DateTime> ex)
        {
            Console.WriteLine("{0}\nRange: [{1} - {2}]", ex.Message, ex.Start.ToString(DATE_FORMAT), ex.End.ToString(DATE_FORMAT));
        }
    }
 public WeekCalendar(DateTime date)
 {
     Date = date;
     this.InitializeComponent();
     Canvas = new Canvas[24, 7];
     initBorder();
 }
    // Vibrates the controller with a given force, specific vibration motor and for a selected amount of time
    public static void controllerVibration(string motor, float force, double vibrateTime)
    {
        /*
        while (timer <= timerend)
        {
            if (motor == "Rough") GamePad.SetVibration(playerIndex, force, 0);
            if (motor == "Smooth") GamePad.SetVibration(playerIndex, 0, force);
            if (motor == "Both") GamePad.SetVibration(playerIndex, force, force);
            timert += Time.deltaTime;
        }
        if (timer > timerend)
        {
            GamePad.SetVibration(playerIndex, 0, 0);
            timer = 0;
        }*/

        timer = DateTime.Now;
        timerend = timer.AddSeconds(vibrateTime);

         while (timer.Second < timerend.Second)
        {

            if (motor == "Rough") GamePad.SetVibration(playerIndex, force, 0);
            if (motor == "Smooth") GamePad.SetVibration(playerIndex, 0, force);
            if (motor == "Both") GamePad.SetVibration(playerIndex, force, force);
            timer = DateTime.Now;
        }
            GamePad.SetVibration(playerIndex, 0, 0);
            //timer = timerend = 0;
    }
 protected void ddlYear_SelectedIndexChanged(object sender, EventArgs e)
 {
     DateTime newday = new DateTime(int.Parse(ddlYear.SelectedValue),int.Parse(ddlMonth.SelectedValue),1);
     string querystring = this.Page.Request.QueryString.ToString();
     querystring = querystring.Replace("Day=" + strDay, "Day=" + newday.ToShortDateString().Replace('/', '-'));
     this.Page.Response.Redirect(this.Page.Request.Path + "?" + querystring);
 }
Exemple #30
0
    public bool PosTest2()
    {
        bool retVal = true;
        TestLibrary.TestFramework.BeginScenario("Verify DateTime.Hour property When DateTime instance is only assigned year month and day...");

        try
        {
            TestLibrary.Utilities.CurrentCulture = new CultureInfo("");
            DateTime myDateTime = new DateTime(1978,08,29);
            int hour = myDateTime.Hour;

            if (hour != 0)
            {
                TestLibrary.TestFramework.LogError("003","The hour is not zero when no value is assigned at init time!");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("", "");
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
 /// <summary>
 ///     Returns the very end of the given day (the last millisecond of the last hour for the given date)
 /// </summary>
 /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param>
 /// <returns>Returns the very end of the given day (the last millisecond of the last hour for the given date)</returns>
 public static DateTime EndOfDay(this DateTime obj)
 {
     return(obj.SetTime(23, 59, 59, 999));
 }
 /// <summary>
 ///     Returns true if the day is Saturday or Sunday
 /// </summary>
 /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param>
 /// <returns>boolean value indicating if the date is a weekend</returns>
 public static bool IsWeekend(this DateTime obj)
 {
     return(obj.DayOfWeek == DayOfWeek.Saturday || obj.DayOfWeek == DayOfWeek.Sunday);
 }
 public void Setup()
 {
     _start = new DateTime(1983, 11, 3);
 }
        public static string FormatValue(double value, TextValueFormat format)
        {
            var output = string.Empty;

            switch (format)
            {
            case TextValueFormat.None: {
                output = value.ToString();

                break;
            }

            case TextValueFormat.WithSpace: {
                if (value < 0f)
                {
                    output = string.Format("-{0}", (-value).ToString("# ### ### ##0").Trim());
                }
                else
                {
                    output = value.ToString("# ### ### ##0").Trim();
                }

                break;
            }

            case TextValueFormat.WithComma: {
                if (value < 0f)
                {
                    output = string.Format("-{0}", (-value).ToString("#,### ### ##0").Trim(','));
                }
                else
                {
                    output = value.ToString("#,### ### ##0").Trim(',').Trim(' ');
                }

                break;
            }

            case TextValueFormat.DateDMHMS: {
                DateTime date = new DateTime((long)value);
                output = date.ToString("dd MM hh:mm:ss");

                break;
            }

            case TextValueFormat.TimeHMSFromSeconds: {
                var t = TimeSpan.FromSeconds(value);
                output = string.Format("{0:D2}:{1:D2}:{2:D2}", t.Hours, t.Minutes, t.Seconds);

                break;
            }

            case TextValueFormat.TimeMSFromSeconds: {
                var t = TimeSpan.FromSeconds(value);
                output = string.Format("{0:D2}:{1:D2}", t.Minutes, t.Seconds);

                break;
            }

            case TextValueFormat.DateDMHMSFromMilliseconds: {
                DateTime date = new DateTime((long)(value / 1000d));
                output = date.ToString("dd MM hh:mm:ss");

                break;
            }

            case TextValueFormat.TimeHMSmsFromMilliseconds: {
                var t = TimeSpan.FromMilliseconds(value);
                output = string.Format("{0:D2}:{1:D2}:{2:D2}`{3:D2}", t.Hours, t.Minutes, t.Seconds, t.Milliseconds);

                break;
            }

            case TextValueFormat.TimeMSmsFromMilliseconds: {
                var t = TimeSpan.FromMilliseconds(value);
                output = string.Format("{0:D2}:{1:D2}`{2:D2}", t.Minutes, t.Seconds, t.Milliseconds);

                break;
            }

            case TextValueFormat.TimeMSFromMilliseconds: {
                var t = TimeSpan.FromMilliseconds(value);
                output = string.Format("{0:D2}:{1:D2}", t.Minutes, t.Seconds);

                break;
            }

            case TextValueFormat.TimeHMSFromMilliseconds: {
                var t = TimeSpan.FromMilliseconds(value);
                output = string.Format("{0:D2}:{1:D2}:{2:D2}", t.Hours, t.Minutes, t.Seconds);

                break;
            }
            }

            return(output);
        }
Exemple #35
0
        /// <summary>
        /// Get activities for a conversation (Aka the transcript).
        /// </summary>
        /// <param name="channelId">Channel Id.</param>
        /// <param name="conversationId">Conversation Id.</param>
        /// <param name="continuationToken">Continuatuation token to page through results.</param>
        /// <param name="startDate">Earliest time to include.</param>
        /// <returns>PagedResult of activities.</returns>
        public async Task <PagedResult <IActivity> > GetTranscriptActivitiesAsync(string channelId, string conversationId, string continuationToken = null, DateTimeOffset startDate = default(DateTimeOffset))
        {
            if (string.IsNullOrEmpty(channelId))
            {
                throw new ArgumentNullException($"missing {nameof(channelId)}");
            }

            if (string.IsNullOrEmpty(conversationId))
            {
                throw new ArgumentNullException($"missing {nameof(conversationId)}");
            }

            var pagedResult = new PagedResult <IActivity>();

            var dirName  = GetDirName(channelId, conversationId);
            var dir      = this.Container.Value.GetDirectoryReference(dirName);
            int pageSize = 20;
            BlobContinuationToken token = null;
            List <CloudBlockBlob> blobs = new List <CloudBlockBlob>();

            do
            {
                var segment = await dir.ListBlobsSegmentedAsync(false, BlobListingDetails.Metadata, null, token, null, null).ConfigureAwait(false);

                foreach (var blob in segment.Results.Cast <CloudBlockBlob>())
                {
                    if (DateTime.Parse(blob.Metadata["Timestamp"]).ToUniversalTime() >= startDate)
                    {
                        if (continuationToken != null)
                        {
                            if (blob.Name == continuationToken)
                            {
                                // we found continuation token
                                continuationToken = null;
                            }
                        }
                        else
                        {
                            blobs.Add(blob);
                            if (blobs.Count == pageSize)
                            {
                                break;
                            }
                        }
                    }
                }

                if (segment.ContinuationToken != null)
                {
                    token = segment.ContinuationToken;
                }
            }while (token != null && blobs.Count < pageSize);

            pagedResult.Items = blobs
                                .Select(async bl =>
            {
                var json = await bl.DownloadTextAsync().ConfigureAwait(false);
                return(JsonConvert.DeserializeObject <Activity>(json));
            })
                                .Select(t => t.Result)
                                .ToArray();

            if (pagedResult.Items.Length == pageSize)
            {
                pagedResult.ContinuationToken = blobs.Last().Name;
            }

            return(pagedResult);
        }
        /// <summary>
        /// Creates a class offering of a given course.
        /// </summary>
        /// <param name="subject">The department subject abbreviation</param>
        /// <param name="number">The course number</param>
        /// <param name="season">The season part of the semester</param>
        /// <param name="year">The year part of the semester</param>
        /// <param name="start">The start time</param>
        /// <param name="end">The end time</param>
        /// <param name="location">The location</param>
        /// <param name="instructor">The uid of the professor</param>
        /// <returns>A JSON object containing {success = true/false}. 
        /// false if another class occupies the same location during any time 
        /// within the start-end range in the same semester, or if there is already
        /// a Class offering of the same Course in the same Semester,
        /// true otherwise.</returns>
        public IActionResult CreateClass(string subject, int number, string season, int year, DateTime start, DateTime end, string location, string instructor)
        {
            //work
            var query =
                from c in db.Classes
                where c.Loc == location && ((TimeSpan.Compare(start-DateTime.Now, c.Start.Value) >= 0 && TimeSpan.Compare(start-DateTime.Now,c.End.Value) <= 0) || (TimeSpan.Compare(end-DateTime.Now, c.Start.Value) >= 0 && TimeSpan.Compare(end-DateTime.Now, c.End.Value) <= 0))
                select c;

            if(query.ToList().Count > 0)
            {
                return Json(new { success = false });
            }
            
            var query2 =
                (from c in db.Classes
                where c.Semester.Substring(0,c.Semester.IndexOf(" "))==season && c.Semester.Substring(c.Semester.IndexOf(" ")+1,c.Semester.Length)==year.ToString()
                join cou in db.Courses on c.CatalogId equals cou.CatalogId
                where cou.Num == number.ToString() && cou.Department == subject
                select c).ToList();

            if (query2.Count > 0)
            {
                return Json(new { success = false });
            }

            var query3 =
                from cou in db.Courses
                where cou.Department == subject && cou.Num == number.ToString()
                select cou.CatalogId;

            /*
            foreach (var v in query)
            {
                System.Diagnostics.Debug.WriteLine("create class: ");
                System.Diagnostics.Debug.WriteLine(v);
            }
            System.Diagnostics.Debug.WriteLine(query3.ToList().Count);
            */

            Classes cl = new Classes();
            cl.CatalogId = query3.ToList()[0]; 
            cl.Semester = season + " " + year.ToString();
            cl.Teacher = instructor;
            cl.Loc = location;
            cl.Start = start.TimeOfDay;
            cl.End = end.TimeOfDay;

            db.Classes.Add(cl);
            db.SaveChanges();

            return Json(new { success = true });
        }
        [InlineData(null, false, "2018-07-30T20:00:00", "")]        // spot break request is empty string
        public void AddSpotToBreakValidatorService_ValidateAddSpot_ReturnsNoFailures(
            string spotBreakType,
            bool respectSpotTime,
            DateTime spotEndDateTime,
            string spotBreakRequest
            )
        {
            // Arrange
            SetupTestData(
                out IReadOnlyCollection<Break> breaksBeingSmoothed,
                out SmoothBreak theSmoothBreak,
                out IReadOnlyCollection<Programme> scheduleProgrammes,
                out List<Spot> spotsForBreak,
                out SalesArea salesArea,
                out IReadOnlyDictionary<string, Clash> clashesByExternalRef,
                out IReadOnlyDictionary<Guid, SpotInfo> spotInfos,
                out ProductClashRules productClashRule,
                out SmoothResources smoothResources,
                out IClashExposureCountService clashExposureCountService,
                out SponsorshipRestrictionService sponsorshipRestrictionsService);

            spotsForBreak[0].BreakType = spotBreakType;
            spotsForBreak[0].EndDateTime = spotEndDateTime;

            var placedSpot = (Spot)_spot.Clone();
            placedSpot.ExternalCampaignNumber = nameof(_spot.ExternalCampaignNumber);
            _ = theSmoothBreak.AddSpot(
                placedSpot,
                1,
                1,
                1,
                true,
                false,
                String.Empty,
                String.Empty);

            spotsForBreak[0].BreakRequest = spotBreakRequest;

            // Act
            var res = AddSpotsToBreakValidatorService.ValidateAddSpots(
                theSmoothBreak,
                programme: scheduleProgrammes.First(),
                salesArea: salesArea,
                spotsForBreak: spotsForBreak,
                spotInfos: spotInfos,
                progSmoothBreaks: new List<SmoothBreak> { theSmoothBreak },
                productClashRule: productClashRule,
                respectCampaignClash: true,
                respectSpotTime: respectSpotTime,
                respectRestrictions: false,
                respectClashExceptions: false,
                breakPositionRules: SpotPositionRules.Exact,
                requestedPositionInBreakRules: SpotPositionRules.Exact,
                clashesByExternalRef: clashesByExternalRef,
                canSplitMultipartSpotsOverBreaks: false,
                smoothResources: smoothResources,
                breaksBeingSmoothed: breaksBeingSmoothed,
                scheduleProgrammes: scheduleProgrammes,
                clashExposureCountService: clashExposureCountService,
                sponsorshipRestrictionsService: sponsorshipRestrictionsService);

            // Assert
            _ = res.Should().ContainSingle();
            _ = res.First().Value.Failures.Should().BeEmpty();
        }
        /// <summary>
        /// Returns true if the date is between or equal to one of the two values.
        /// </summary>
        /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param>
        /// <param name="startvalue">Start date to check for</param>
        /// <param name="endvalue">End date to check for</param>
        /// <returns>boolean value indicating if the date is between or equal to one of the two values</returns>
        //public static bool Between(this DateTime obj, DateTime startDate, DateTime endDate)
        //{
        //    return obj.Ticks.Between(startDate.Ticks, endDate.Ticks);
        //}

        /// <summary>
        ///     Get the quarter that the datetime is in.
        /// </summary>
        /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param>
        /// <returns>Returns 1 to 4 that represenst the quarter that the datetime is in.</returns>
        public static int Quarter(this DateTime obj)
        {
            return((obj.Month - 1) / 3 + 1);
        }
 /// <summary>
 ///     Returns DateTime with changed Year, Month and Day part
 /// </summary>
 /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param>
 /// <param name="year">A number of whole and fractional years. The value parameter can be negative or positive.</param>
 /// <param name="month">A number of whole and fractional month. The value parameter can be negative or positive.</param>
 /// <param name="day">A number of whole and fractional day. The value parameter can be negative or positive.</param>
 /// <returns>
 ///     A DateTime whose value is the sum of the date and time represented by this instance and the numbers
 ///     represented by the parameters.
 /// </returns>
 public static DateTime SetDate(this DateTime obj, int year, int month, int day)
 {
     return(SetDateWithChecks(obj, year, month, day, null, null, null, null));
 }
 /// <summary>
 ///     Converts any datetime to the amount of seconds from 1972.01.01 00:00:00
 ///     Microsoft sometimes uses the amount of seconds from 1972.01.01 00:00:00 to indicate an datetime.
 /// </summary>
 /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param>
 /// <returns>Total seconds past since 1972.01.01 00:00:00</returns>
 public static double ToMicrosoftNumber(this DateTime obj)
 {
     return((obj - new DateTime(1972, 1, 1, 0, 0, 0, 0)).TotalSeconds);
 }
 /// <summary>
 ///     Returns the original DateTime with Hour, Minute, Second and Millisecond parts changed to supplied hour, minute,
 ///     second and millisecond parameters
 /// </summary>
 /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param>
 /// <param name="hour">A number of whole and fractional hours. The value parameter can be negative or positive.</param>
 /// <param name="minute">A number of whole and fractional minutes. The value parameter can be negative or positive.</param>
 /// <param name="second">A number of whole and fractional seconds. The value parameter can be negative or positive.</param>
 /// <param name="millisecond">
 ///     A number of whole and fractional milliseconds. The value parameter can be negative or
 ///     positive.
 /// </param>
 /// <returns>
 ///     A DateTime whose value is the sum of the date and time represented by this instance and the numbers
 ///     represented by the parameters.
 /// </returns>
 public static DateTime SetTime(this DateTime obj, int hour, int minute, int second, int millisecond)
 {
     return(SetDateWithChecks(obj, 0, 0, 0, hour, minute, second, millisecond));
 }
 /// <summary>
 ///     Returns DateTime with changed Year part
 /// </summary>
 /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param>
 /// <param name="year">A number of whole and fractional years. The value parameter can be negative or positive.</param>
 /// <returns>
 ///     A DateTime whose value is the sum of the date and time represented by this instance and the numbers
 ///     represented by the parameters.
 /// </returns>
 public static DateTime SetDate(this DateTime obj, int year)
 {
     return(SetDateWithChecks(obj, year, 0, 0, null, null, null, null));
 }
        private static DateTime SetDateWithChecks(DateTime obj, int year, int month, int day, int?hour, int?minute,
                                                  int?second, int?millisecond)
        {
            DateTime StartDate;

            if (year == 0)
            {
                StartDate = new DateTime(obj.Year, 1, 1, 0, 0, 0, 0);
            }
            else
            {
                if (DateTime.MaxValue.Year < year)
                {
                    StartDate = new DateTime(DateTime.MinValue.Year, 1, 1, 0, 0, 0, 0);
                }
                else if (DateTime.MinValue.Year > year)
                {
                    StartDate = new DateTime(DateTime.MaxValue.Year, 1, 1, 0, 0, 0, 0);
                }
                else
                {
                    StartDate = new DateTime(year, 1, 1, 0, 0, 0, 0);
                }
            }

            if (month == 0)
            {
                StartDate = StartDate.AddMonths(obj.Month - 1);
            }
            else
            {
                StartDate = StartDate.AddMonths(month - 1);
            }
            if (day == 0)
            {
                StartDate = StartDate.AddDays(obj.Day - 1);
            }
            else
            {
                StartDate = StartDate.AddDays(day - 1);
            }
            if (!hour.HasValue)
            {
                StartDate = StartDate.AddHours(obj.Hour);
            }
            else
            {
                StartDate = StartDate.AddHours(hour.Value);
            }
            if (!minute.HasValue)
            {
                StartDate = StartDate.AddMinutes(obj.Minute);
            }
            else
            {
                StartDate = StartDate.AddMinutes(minute.Value);
            }
            if (!second.HasValue)
            {
                StartDate = StartDate.AddSeconds(obj.Second);
            }
            else
            {
                StartDate = StartDate.AddSeconds(second.Value);
            }
            if (!millisecond.HasValue)
            {
                StartDate = StartDate.AddMilliseconds(obj.Millisecond);
            }
            else
            {
                StartDate = StartDate.AddMilliseconds(millisecond.Value);
            }

            return(StartDate);
        }
 /// <summary>
 ///     Returns the original DateTime with Hour and Minute parts changed to supplied hour and minute parameters
 /// </summary>
 /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param>
 /// <param name="hour">A number of whole and fractional hours. The value parameter can be negative or positive.</param>
 /// <param name="minute">A number of whole and fractional minutes. The value parameter can be negative or positive.</param>
 /// <returns>
 ///     A DateTime whose value is the sum of the date and time represented by this instance and the numbers
 ///     represented by the parameters.
 /// </returns>
 public static DateTime SetTime(this DateTime obj, int hour, int minute)
 {
     return(SetDateWithChecks(obj, 0, 0, 0, hour, minute, null, null));
 }
 /// <summary>
 ///     Returns first next occurence of specified DayOfTheWeek
 /// </summary>
 /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param>
 /// <param name="day">A DayOfWeek to find the next occurence of</param>
 /// <returns>
 ///     A DateTime whose value is the sum of the date and time represented by this instance and the enum value
 ///     represented by the day.
 /// </returns>
 public static DateTime Next(this DateTime obj, DayOfWeek day)
 {
     return(obj.AddDays(Sub(obj.DayOfWeek, day) * -1));
 }
 /// <summary>
 ///     Returns next "first" occurence of specified DayOfTheWeek
 /// </summary>
 /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param>
 /// <param name="day">A DayOfWeek to find the previous occurence of</param>
 /// <returns>
 ///     A DateTime whose value is the sum of the date and time represented by this instance and the enum value
 ///     represented by the day.
 /// </returns>
 public static DateTime Previous(this DateTime obj, DayOfWeek day)
 {
     return(obj.AddDays(Sub(day, obj.DayOfWeek)));
 }
        protected virtual void Fill(int typiconVersionId, ModifiedYear modifiedYear)
        {
            var handler = new ModificationsRuleHandler(_dbContext, typiconVersionId, modifiedYear);

            //MenologyRules

            var menologyRules = _dbContext.GetAllMenologyRules(modifiedYear.TypiconVersionId);

            EachDayPerYear.Perform(modifiedYear.Year, date =>
            {
                //находим правило для конкретного дня Минеи
                var menologyRule = menologyRules.GetMenologyRule(date);

                InterpretRule(menologyRule, date, handler);
            });

            //теперь обрабатываем переходящие минейные праздники
            //у них не должны быть определены даты. так их и найдем
            var rules = menologyRules.GetAllMovableRules();

            var firstJanuary = new DateTime(modifiedYear.Year, 1, 1);

            foreach (var a in rules)
            {
                InterpretRule(a, firstJanuary, handler);

                //не нашел другого способа, как только два раза вычислять изменяемые дни
                InterpretRule(a, firstJanuary.AddYears(1), handler);
            }

            //Triodion

            //найти текущую Пасху
            //Для каждого правила выполнять interpret(), где date = текущая Пасха. AddDays(Day.DaysFromEaster)
            DateTime easter = _dbContext.GetCurrentEaster(modifiedYear.Year);

            var triodionRules = _dbContext.GetAllTriodionRules(modifiedYear.TypiconVersionId);

            foreach (var triodionRule in triodionRules)
            {
                InterpretRule(triodionRule, easter.AddDays(triodionRule.DaysFromEaster), handler);
            }

            void InterpretRule(DayRule rule, DateTime dateToInterpret, ModificationsRuleHandler h)
            {
                if (rule != null)
                {
                    h.ProcessingDayRule = rule;

                    var r = _settingsFactory.CreateRecursive(new CreateRuleSettingsRequest()
                    {
                        TypiconVersionId = modifiedYear.TypiconVersionId,
                        Rule = rule,
                        Date = dateToInterpret,
                        RuleMode = RuleMode.ModRule
                    });

                    if (r.Success)
                    {
                        h.Settings = r.Value;

                        //выполняем его
                        h.Settings?.RuleContainer.Interpret(h);
                    }
                }
            }
        }
 /// <summary>
 ///     Returns the Start of the given day (the fist millisecond of the given date)
 /// </summary>
 /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param>
 /// <returns>Returns the Start of the given day (the fist millisecond of the given date)</returns>
 public static DateTime BeginningOfDay(this DateTime obj)
 {
     return(obj.SetTime(0, 0, 0, 0));
 }
Exemple #49
0
        private static void WriteDataTableToExcelWorksheet(DataTable dt, ref WorksheetPart worksheetPart, bool includeAutoFilter)
        {
            string cellValue = "";

            //  Create a Header Row in our Excel file, containing one header for each Column of data in our DataTable.
            //
            //  We'll also create an array, showing which type each column of data is (Text or Numeric), so when we come to write the actual
            //  cells of data, we'll know if to write Text values or Numeric cell values.
            int numberOfColumns = dt.Columns.Count;

            bool[] IsNumericColumn = new bool[numberOfColumns];
            bool[] IsDateColumn    = new bool[numberOfColumns];

            string[] excelColumnNames = new string[numberOfColumns];
            for (int n = 0; n < numberOfColumns; n++)
            {
                excelColumnNames[n] = GetExcelColumnName(n);
            }

            //
            //  Create the Header row in our Excel Worksheet
            //
            uint rowIndex = 1;

            for (int colInx = 0; colInx < numberOfColumns; colInx++)
            {
                DataColumn col = dt.Columns[colInx];

                // Save the cell data in spreadsheet
                var cell = CreateSpreadsheetCellIfNotExist(worksheetPart.Worksheet, excelColumnNames[colInx] + rowIndex.ToString());
                cell.CellValue  = new CellValue(col.ColumnName);
                cell.DataType   = CellValues.String;
                cell.StyleIndex = (UInt32Value)1U;

                IsNumericColumn[colInx] = (col.DataType.FullName == "System.Decimal") || (col.DataType.FullName == "System.Int32") || (col.DataType.FullName == "System.Int64") || (col.DataType.FullName == "System.Double") || (col.DataType.FullName == "System.Single");
                IsDateColumn[colInx]    = (col.DataType.FullName == "System.DateTime");
            }

            // Set the AutoFilter property to a range that is the size of the data
            // within the worksheet
            if (includeAutoFilter)
            {
                AutoFilter autoFilter1 = new AutoFilter()
                {
                    Reference = "A1:" + excelColumnNames[numberOfColumns - 1] + "1"
                };
                worksheetPart.Worksheet.Append(autoFilter1);
            }

            //
            //  Now, step through each row of data in our DataTable...
            //
            double cellNumericValue = 0;

            foreach (DataRow dr in dt.Rows)
            {
                // ...create a new row, and append a set of this row's data to it.
                ++rowIndex;

                // Add Data
                Cell cell;

                for (int colInx = 0; colInx < numberOfColumns; colInx++)
                {
                    cellValue = dr.ItemArray[colInx].ToString();
                    cellValue = ReplaceHexadecimalSymbols(cellValue);

                    // Create cell with data
                    if (IsNumericColumn[colInx])
                    {
                        //  For numeric cells, make sure our input data IS a number, then write it out to the Excel file.
                        //  If this numeric value is NULL, then don't write anything to the Excel file.
                        cellNumericValue = 0;
                        if (double.TryParse(cellValue, out cellNumericValue))
                        {
                            cellValue = cellNumericValue.ToString();
                        }
                        else
                        {
                            cellValue = null;
                        }

                        cell            = CreateSpreadsheetCellIfNotExist(worksheetPart.Worksheet, excelColumnNames[colInx] + rowIndex.ToString());
                        cell.CellValue  = new CellValue(cellValue);
                        cell.DataType   = CellValues.Number;
                        cell.StyleIndex = (rowIndex % 2 == 0) ? (UInt32Value)0U : (UInt32Value)3U;
                    }
                    else if (IsDateColumn[colInx])
                    {
                        //  This is a date value.
                        DateTime dtValue;
                        string   strValue = "";
                        if (DateTime.TryParse(cellValue, out dtValue))
                        {
                            strValue = dtValue.ToOADate().ToString(CultureInfo.InvariantCulture);
                        }

                        cell            = CreateSpreadsheetCellIfNotExist(worksheetPart.Worksheet, excelColumnNames[colInx] + rowIndex.ToString());
                        cell.CellValue  = new CellValue(strValue);
                        cell.DataType   = new EnumValue <CellValues>(CellValues.Number);   //Date is only available in Office 2010
                        cell.StyleIndex = (rowIndex % 2 == 0) ? (UInt32Value)2U : (UInt32Value)4U;
                    }
                    else
                    {
                        //  For text cells, just write the input data straight out to the Excel file.
                        cell            = CreateSpreadsheetCellIfNotExist(worksheetPart.Worksheet, excelColumnNames[colInx] + rowIndex.ToString());
                        cell.CellValue  = new CellValue(cellValue);
                        cell.DataType   = CellValues.String;
                        cell.StyleIndex = (rowIndex % 2 == 0) ? (UInt32Value)0U : (UInt32Value)3U;
                    }
                }
            }

            worksheetPart.Worksheet.Save();
        }
 /// <summary>
 ///     Returns the very end of the given month (the last millisecond of the last hour for the given date)
 /// </summary>
 /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param>
 /// <returns>Returns the very end of the given month (the last millisecond of the last hour for the given date)</returns>
 public static DateTime EndOfMonth(this DateTime obj)
 {
     return(new DateTime(obj.Year, obj.Month, DateTime.DaysInMonth(obj.Year, obj.Month), 23, 59, 59, 999));
 }
Exemple #51
0
 public Account(string name, double balance, DebitCard debitCard, DateTime dateOpened) : this(name, balance, debitCard)
 {
     this.DateOpened = dateOpened;
 }
 /// <summary>
 ///     Returns the Start of the given month (the fist millisecond of the given date)
 /// </summary>
 /// <param name="obj">DateTime Base, from where the calculation will be preformed.</param>
 /// <returns>Returns the Start of the given month (the fist millisecond of the given date)</returns>
 public static DateTime BeginningOfMonth(this DateTime obj)
 {
     return(new DateTime(obj.Year, obj.Month, 1, 0, 0, 0, 0));
 }
 public Claims(int claimID, ClaimType typeOfClaim, string description, decimal claimAmount, DateTime dateOfIncident, DateTime dateOfClaim, bool isValid)
 {
     ClaimID = claimID;
     TypeOfClaim = typeOfClaim;
     Description = description;
     ClaimAmount = claimAmount;
     DateOfIncident = dateOfIncident;
     DateOfClaim = dateOfClaim;
     IsValid = isValid;
 }
Exemple #54
0
 public Account(string name, double balance, DebitCard debitCard, bool isPaperless, DateTime dateOpened) : this(name, balance, debitCard)
 {
     this.IsPaperless = isPaperless;
     this.DateOpened = dateOpened;
 }
 public ICodigoOcorrencia ObtemCodigoOcorrencia(EnumCodigoOcorrenciaRemessa ocorrencia, double valorOcorrencia,
     DateTime dataOcorrencia)
 {
     switch (ocorrencia)
     {
         case EnumCodigoOcorrenciaRemessa.Registro:
         {
             return new CodigoOcorrencia((int) ocorrencia)
             {
                 Codigo = 01,
                 Descricao = "Remessa"
             };
         }
         case EnumCodigoOcorrenciaRemessa.Baixa:
         {
             return new CodigoOcorrencia((int) ocorrencia)
             {
                 Codigo = 02,
                 Descricao = "Pedido de baixa"
             };
         }
         case EnumCodigoOcorrenciaRemessa.ConcessaoDeAbatimento:
         {
             return new CodigoOcorrencia((int) ocorrencia)
             {
                 Codigo = 04,
                 Descricao = "Concessão de abatimento"
             };
         }
         case EnumCodigoOcorrenciaRemessa.CancelamentoDeAbatimento:
         {
             return new CodigoOcorrencia((int) ocorrencia)
             {
                 Codigo = 05,
                 Descricao = "Cancelamento de abatimento concedido"
             };
         }
         case EnumCodigoOcorrenciaRemessa.AlteracaoDeVencimento:
         {
             return new CodigoOcorrencia((int) ocorrencia)
             {
                 Codigo = 06,
                 Descricao = "Alteração de vencimento"
             };
         }
         case EnumCodigoOcorrenciaRemessa.AlteracaoSeuNumero:
         {
             return new CodigoOcorrencia((int) ocorrencia)
             {
                 Codigo = 08,
                 Descricao = "Alteração de seu número"
             };
         }
         case EnumCodigoOcorrenciaRemessa.Protesto:
         {
             return new CodigoOcorrencia((int) ocorrencia)
             {
                 Codigo = 09,
                 Descricao = "Pedido de Protesto"
             };
         }
         case EnumCodigoOcorrenciaRemessa.NaoProtestar:
         {
             return new CodigoOcorrencia((int) ocorrencia)
             {
                 Codigo = 10,
                 Descricao = "Não Protestar"
             };
         }
         case EnumCodigoOcorrenciaRemessa.NaoCobrarJurosDeMora:
         {
             return new CodigoOcorrencia((int) ocorrencia)
             {
                 Codigo = 11,
                 Descricao = "Não Cobrar Juros de Mora"
             };
         }
         case EnumCodigoOcorrenciaRemessa.CobrarJurosdeMora:
         {
             return new CodigoOcorrencia((int) ocorrencia)
             {
                 Codigo = 16,
                 Descricao = "Cobrar Juros de Mora"
             };
         }
         case EnumCodigoOcorrenciaRemessa.AlteracaoValorTitulo:
         {
             return new CodigoOcorrencia((int) ocorrencia)
             {
                 Codigo = 31,
                 Descricao = "(*) Alteração do Valor do Título"
             };
         }
         case EnumCodigoOcorrenciaRemessa.Negativar:
         {
             return new CodigoOcorrencia((int) ocorrencia)
             {
                 Codigo = 90,
                 Descricao = "NEGATIVAR"
             };
         }
         case EnumCodigoOcorrenciaRemessa.BaixaNegativacao:
         {
             return new CodigoOcorrencia((int) ocorrencia)
             {
                 Codigo = 91,
                 Descricao = "BAIXA DE NEGATIVAÇÃO"
             };
         }
         case EnumCodigoOcorrenciaRemessa.NaoNegativarAutomaticamente:
         {
             return new CodigoOcorrencia((int) ocorrencia)
             {
                 Codigo = 92,
                 Descricao = "NÃO NEGATIVAR AUTOMATICAMENTE"
             };
         }
     }
     throw new Exception(
         String.Format(
             "Não foi possível obter Código de Comando/Movimento/Ocorrência. Banco: {0} Código: {1}",
             CodigoBanco, ocorrencia.ToString()));
 }
 public double totalSales(DateTime initial, DateTime final) {
     return Sellers.Sum(seller => seller.TotalSales(initial, final));                        
 }
Exemple #57
0
 /// <summary>
 /// 得到一年中的某周的起始日和截止日    周一到周五  工作日
 /// </summary>
 /// <param name="nYear">年份</param>
 /// <param name="nNumWeek">第几周</param>
 /// <param name="dtWeekStart">开始日期</param>
 /// <param name="dtWeekeEnd">结束日期</param>
 public static void GetWeekWorkTime(int nYear, int nNumWeek, out DateTime dtWeekStart, out DateTime dtWeekeEnd)
 {
     DateTime dt = new DateTime(nYear, 1, 1);
     dt = dt + new TimeSpan((nNumWeek - 1) * 7, 0, 0, 0);
     dtWeekStart = dt.AddDays(-(int)dt.DayOfWeek + (int)DayOfWeek.Monday);
     dtWeekeEnd = dt.AddDays((int)DayOfWeek.Saturday - (int)dt.DayOfWeek + 1).AddDays(-2);
 }
 public IInstrucao ObtemInstrucaoPadronizada(EnumTipoInstrucao tipoInstrucao, double valorInstrucao,
     DateTime dataInstrucao,
     int diasInstrucao)
 {
     switch (tipoInstrucao)
     {
         case EnumTipoInstrucao.NaoReceberPrincipalSemJurosdeMora:
         {
             return new InstrucaoPadronizada
             {
                 Codigo = 01,
                 QtdDias = diasInstrucao,
                 Valor = valorInstrucao,
                 TextoInstrucao = "NÃO RECEBER PRINCIPAL, SEM JUROS DE MORA"
             };
         }
         case EnumTipoInstrucao.DevolverSenaoPagoAte15DiasAposVencimento:
         {
             return new InstrucaoPadronizada
             {
                 Codigo = 02,
                 QtdDias = diasInstrucao,
                 Valor = valorInstrucao,
                 TextoInstrucao = "DEVOLVER, SE NÃO PAGO, ATÉ 15 DIAS APÓS O VENCIMENTO"
             };
         }
         case EnumTipoInstrucao.DevolverSenaoPagoAte30DiasAposVencimento:
         {
             return new InstrucaoPadronizada
             {
                 Codigo = 03,
                 QtdDias = diasInstrucao,
                 Valor = valorInstrucao,
                 TextoInstrucao = "DEVOLVER, SE NÃO PAGO, ATÉ 30 DIAS APÓS O VENCIMENTO"
             };
         }
         case EnumTipoInstrucao.NaoProtestar:
         {
             return new InstrucaoPadronizada
             {
                 Codigo = 07,
                 QtdDias = diasInstrucao,
                 Valor = valorInstrucao,
                 TextoInstrucao = "NÃO PROTESTAR"
             };
         }
         case EnumTipoInstrucao.NaoCobrarJurosDeMora:
         {
             return new InstrucaoPadronizada
             {
                 Codigo = 08,
                 QtdDias = diasInstrucao,
                 Valor = valorInstrucao,
                 TextoInstrucao = "NÃO COBRAR JUROS DE MORA"
             };
         }
         case EnumTipoInstrucao.MultaVencimento:
         {
             return new InstrucaoPadronizada
             {
                 Codigo = 16,
                 QtdDias = diasInstrucao,
                 Valor = valorInstrucao,
                 TextoInstrucao = "MULTA"
             };
         }
     }
     throw new Exception(
         String.Format(
             "Não foi possível obter instrução padronizada. Banco: {0} Código Instrução: {1} Qtd Dias/Valor: {2}",
             CodigoBanco, tipoInstrucao.ToString(), valorInstrucao));
 }
Exemple #59
0
 /// <summary>
 /// 返回年度第几个星期
 /// </summary>
 /// <param name="date">时间</param>
 /// <param name="week">一周的开始日期</param>
 /// <returns></returns>
 public static int WeekOfYear(DateTime date, DayOfWeek week)
 {
     System.Globalization.GregorianCalendar gc = new System.Globalization.GregorianCalendar();
     return gc.GetWeekOfYear(date, System.Globalization.CalendarWeekRule.FirstDay, week);
 }
Exemple #60
0
        private static void WriteExcelFile(DataSet ds, SpreadsheetDocument spreadsheet, bool includeAutoFilter)
        {
            // Reset rows cache
            _rowListCache = new List <Row>();

            // Add a WorkbookPart to the document.
            WorkbookPart workbookpart = spreadsheet.AddWorkbookPart();

            workbookpart.Workbook = new Workbook();

            // Add a WorksheetPart to the WorkbookPart.
            WorksheetPart worksheetPart = workbookpart.AddNewPart <WorksheetPart>();

            worksheetPart.Worksheet = new Worksheet();

            // add styles to sheet
            WorkbookStylesPart wbsp = workbookpart.AddNewPart <WorkbookStylesPart>();

            wbsp.Stylesheet = CreateStylesheet();
            wbsp.Stylesheet.Save();

            DataTable dt            = ds.Tables[0];
            string    worksheetName = dt.TableName;

            // Create columns calculating size of biggest text for the database column
            int     numberOfColumns = dt.Columns.Count;
            Columns columns         = new Columns();

            for (int colInx = 0; colInx < numberOfColumns; colInx++)
            {
                DataColumn col = dt.Columns[colInx];

                string maxText = col.ColumnName;
                foreach (DataRow dr in dt.Rows)
                {
                    string value = string.Empty;
                    if (col.DataType.FullName == "System.DateTime")
                    {
                        DateTime dtValue;
                        if (DateTime.TryParse(dr[col].ToString(), out dtValue))
                        {
                            value = dtValue.ToShortDateString();
                        }
                    }
                    else
                    {
                        value = dr[col].ToString();
                    }

                    if (value.Length > maxText.Length)
                    {
                        maxText = value;
                    }
                }
                //double width = GetWidth("Calibri", 11, maxText);
                //columns.Append(CreateColumnData((uint)colInx + 1, (uint)colInx + 1, width + 2));
                columns.Append(CreateColumnData((uint)colInx + 1, (uint)colInx + 1, 15));
            }
            worksheetPart.Worksheet.Append(columns);

            // Create SheetData and assign to worksheetpart
            SheetData sd = new SheetData();

            worksheetPart.Worksheet.Append(sd);

            // Add Sheets to the Workbook.
            Sheets sheets = spreadsheet.WorkbookPart.Workbook.AppendChild <Sheets>(new Sheets());

            // Append a new worksheet and associate it with the workbook.
            Sheet sheet = new Sheet()
            {
                Id      = spreadsheet.WorkbookPart.GetIdOfPart(worksheetPart),
                SheetId = 1,
                Name    = worksheetName
            };

            sheets.Append(sheet);

            // Append this worksheet's data to our Workbook, using OpenXmlWriter, to prevent memory problems
            WriteDataTableToExcelWorksheet(dt, ref worksheetPart, includeAutoFilter);

            // Save it and close it
            spreadsheet.WorkbookPart.Workbook.Save();
            spreadsheet.Close();
        }