Ejemplo n.º 1
0
        public string IssueToken(Microsoft.AspNetCore.Authentication.AuthenticationTicket data)
        {
            System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler tokenHandler =
                new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();

            System.DateTime now = System.DateTime.UtcNow;

            Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor desc =
                new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor
            {
                //Subject = new System.Security.Claims.ClaimsIdentity(claimList),
                Subject            = (System.Security.Claims.ClaimsIdentity)data.Principal.Identity,
                Issuer             = this.m_validationParameters.ValidIssuer,   //SecurityConstants.TokenIssuer,
                Audience           = this.m_validationParameters.ValidAudience, // SecurityConstants.TokenAudience,
                IssuedAt           = now,
                Expires            = now.AddMinutes(this.m_tokenLifetimeMinutes),
                NotBefore          = now.AddTicks(-1),
                SigningCredentials = this.m_signingCredentials
            };

            // System.IdentityModel.Tokens.Jwt.JwtSecurityToken tok =
            //        tokenHandler.CreateJwtSecurityToken(desc);
            // // tok.Header.Add("jti", "foo");
            // // tok.Payload.Add("jti", "foobar");

            // System.Console.WriteLine(tok.Id);

            // string tokk = tok.ToString();
            // System.Console.WriteLine(tokk);

            return(tokenHandler.CreateEncodedJwt(desc));
        } // End Function IssueToken
        private IEnumerator RequestNewGoogleDriveAccessToken()
        {
            if (googleDriveAccessToken.Length > 0 && lastTokenReceived != null && (lastTokenReceived.AddMinutes(60) > System.DateTime.Now))
            {
                yield break;
            }

            WWWForm apiRequestForm = new WWWForm();

            apiRequestForm.AddField("refresh_token", "[REFRESH_TOKEN]");
            apiRequestForm.AddField("client_id", "[CLIENT_ID]");
            apiRequestForm.AddField("client_secret", "[CLIENT_SECRET]");
            apiRequestForm.AddField("grant_type", "refresh_token");

            obtainedValidAccessKey = false;
            webRequestObj          = new UnityWebRequest();
            webRequestObj          = UnityWebRequest.Post("https://oauth2.googleapis.com/token", apiRequestForm);
            yield return(webRequestObj.SendWebRequest());

            if (webRequestObj.isHttpError || webRequestObj.responseCode != 200)
            {
                Debug.LogError($"[GoogleDataUploader] Unable to get a new Google Drive access token. Try again or contact Tech/QA.");
                yield break;
            }
            lastTokenReceived      = System.DateTime.Now;
            googleDriveAccessToken = ReplaceEscapeCharacters(webRequestObj.downloadHandler.text, true);

            //If access token is complete, go to new section
            Debug.Log($"[GoogleDataUploader] Received a valid Google API access token to upload files.");

            obtainedValidAccessKey = true;
        }
        public void TimestampParsing()
        {
            var originalTime        = new System.DateTime(2019, 10, 15, 8, 30, 0).ToUniversalTime();
            var originalTimestamp   = originalTime.ToString("O");
            var originalTimestampId = originalTimestamp;
            var originalCommentId   = ArticleReactionTimestampId.TimestampToJQueryFriendlyString(originalTimestamp);
            var originalComment     = new ArticleReaction()
            {
                TimestampId = originalTimestampId
            };

            Assert.AreEqual(originalTime, originalComment.PublishDate);
            Assert.AreEqual(originalTimestamp, originalComment.TimestampAsString);
            Assert.AreEqual(originalCommentId, originalComment.ReactionId);
            Assert.AreEqual(originalTimestampId, originalComment.TimestampId);
            Assert.IsEmpty(originalComment.ReactingToId);

            var replyTime        = originalTime.AddMinutes(30);
            var replyTimestamp   = replyTime.ToString("O");
            var replyCommentId   = originalCommentId + "_" + ArticleReactionTimestampId.TimestampToJQueryFriendlyString(replyTimestamp);
            var replyTimestampId = $"{replyTimestamp}_{originalTimestamp}";
            var replyComment     = new ArticleReaction()
            {
                TimestampId = replyTimestampId
            };

            Assert.AreEqual(replyTime, replyComment.PublishDate);
            Assert.AreEqual(replyTimestamp, replyComment.TimestampAsString);
            Assert.AreEqual(replyCommentId, replyComment.ReactionId);
            Assert.AreEqual(replyTimestampId, replyComment.TimestampId);
            Assert.AreEqual(originalComment.ReactionId, replyComment.ReactingToId);
        }
        public void AddMinutes_ShouldMimicSystem()
        {
            var anyDateTimeTicks = 200;
            var anyMinutes = 5.5d;

            var sut = new Abstractions.DateTime(anyDateTimeTicks);
            var systemDateTime = new System.DateTime(anyDateTimeTicks);

            //  Act.
            var res = sut.AddMinutes(anyMinutes);

            //  Assert.
            var expectedResult = systemDateTime.AddMinutes(anyMinutes);
            AssertEquals(expectedResult, res);
        }
Ejemplo n.º 5
0
        public Form1()
        {
            InitializeComponent();
            _1min = Properties.Settings.Default._1min;
            _5min = Properties.Settings.Default._5min;
            menuStrip.BackColor = System.Drawing.ColorTranslator.FromHtml("#88ffffff");
            horario = System.DateTime.Today;
            horario = horario.AddHours(Properties.Settings.Default.Hora); //Utiliza a configuração padrão de hora
            horario = horario.AddMinutes(Properties.Settings.Default.Minuto); //Utiliza a configuração padrão de minuto
            alterarFontes();
            lblRelogio.Text = System.DateTime.Now.ToString("HH:mm");
            timer1.Interval = 1000;
            timer1.Start();
            //Inicializa a localização dos audios
            _1minPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\resources\\mp3_1min.mp3";
            _5minPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\resources\\mp3_5min.mp3";
            if (!System.IO.File.Exists(_1minPath) || !System.IO.File.Exists(_5minPath))
                System.Windows.MessageBox.Show("Arquivos de áudio foram deletados ou corrompidos\nReinstale o programa para corrigir.", "Falha ao abrir áudios", System.Windows.MessageBoxButton.OK, MessageBoxImage.Error);

            configurarExibicao();
        }
Ejemplo n.º 6
0
        public Form1()
        {
            InitializeComponent();
            _1min = Properties.Settings.Default._1min;
            _5min = Properties.Settings.Default._5min;
            menuStrip.BackColor = System.Drawing.ColorTranslator.FromHtml("#88ffffff");
            horario             = System.DateTime.Today;
            horario             = horario.AddHours(Properties.Settings.Default.Hora);     //Utiliza a configuração padrão de hora
            horario             = horario.AddMinutes(Properties.Settings.Default.Minuto); //Utiliza a configuração padrão de minuto
            alterarFontes();
            lblRelogio.Text = System.DateTime.Now.ToString("HH:mm");
            timer1.Interval = 1000;
            timer1.Start();
            //Inicializa a localização dos audios
            _1minPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\resources\\mp3_1min.mp3";
            _5minPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\resources\\mp3_5min.mp3";
            if (!System.IO.File.Exists(_1minPath) || !System.IO.File.Exists(_5minPath))
            {
                System.Windows.MessageBox.Show("Arquivos de áudio foram deletados ou corrompidos\nReinstale o programa para corrigir.", "Falha ao abrir áudios", System.Windows.MessageBoxButton.OK, MessageBoxImage.Error);
            }

            configurarExibicao();
        }
Ejemplo n.º 7
0
        /// <summary>Generates a random DateTime value.</summary>
        /// <param name="random">The random generation algorithm.</param>
        /// <param name="min">The minimum allowed value of the random generation.</param>
        /// <param name="max">The maximum allowed value of the random generation.</param>
        /// <returns>A randomly generated DateTime value.</returns>
        public static System.DateTime DateTime(this System.Random random, System.DateTime min, System.DateTime max)
        {
            if (random == null)
            {
                throw new System.ArgumentNullException("random");
            }
            if (min > max)
            {
                throw new System.ArgumentException("!(min <= max)");
            }
            System.TimeSpan span      = max - min;
            int             day_range = span.Days;

            span -= System.TimeSpan.FromDays(day_range);
            int hour_range = span.Hours;

            span -= System.TimeSpan.FromHours(hour_range);
            int minute_range = span.Minutes;

            span -= System.TimeSpan.FromMinutes(minute_range);
            int second_range = span.Seconds;

            span -= System.TimeSpan.FromSeconds(second_range);
            int millisecond_range = span.Milliseconds;

            span -= System.TimeSpan.FromMilliseconds(millisecond_range);
            int tick_range = (int)span.Ticks;

            System.DateTime result = min;
            result.AddDays(random.Next(day_range));
            result.AddHours(random.Next(hour_range));
            result.AddMinutes(random.Next(minute_range));
            result.AddSeconds(random.Next(second_range));
            result.AddMilliseconds(random.Next(millisecond_range));
            result.AddTicks(random.Next(tick_range));
            return(result);
        }
Ejemplo n.º 8
0
        // Converts a given datetime in DMTF format to System.DateTime object.
        static System.DateTime ToDateTime(string dmtfDate)
        {
            System.DateTime initializer = System.DateTime.MinValue;
            int             year        = initializer.Year;
            int             month       = initializer.Month;
            int             day         = initializer.Day;
            int             hour        = initializer.Hour;
            int             minute      = initializer.Minute;
            int             second      = initializer.Second;
            long            ticks       = 0;
            string          dmtf        = dmtfDate;

            System.DateTime datetime   = System.DateTime.MinValue;
            string          tempString = string.Empty;

            if ((dmtf == null))
            {
                throw new System.ArgumentOutOfRangeException();
            }
            if ((dmtf.Length == 0))
            {
                throw new System.ArgumentOutOfRangeException();
            }
            if ((dmtf.Length != 25))
            {
                throw new System.ArgumentOutOfRangeException();
            }
            try
            {
                tempString = dmtf.Substring(0, 4);
                if (("****" != tempString))
                {
                    year = int.Parse(tempString);
                }
                tempString = dmtf.Substring(4, 2);
                if (("**" != tempString))
                {
                    month = int.Parse(tempString);
                }
                tempString = dmtf.Substring(6, 2);
                if (("**" != tempString))
                {
                    day = int.Parse(tempString);
                }
                tempString = dmtf.Substring(8, 2);
                if (("**" != tempString))
                {
                    hour = int.Parse(tempString);
                }
                tempString = dmtf.Substring(10, 2);
                if (("**" != tempString))
                {
                    minute = int.Parse(tempString);
                }
                tempString = dmtf.Substring(12, 2);
                if (("**" != tempString))
                {
                    second = int.Parse(tempString);
                }
                tempString = dmtf.Substring(15, 6);
                if (("******" != tempString))
                {
                    ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000))));
                }
                if (((((((((year < 0) ||
                           (month < 0)) ||
                          (day < 0)) ||
                         (hour < 0)) ||
                        (minute < 0)) ||
                       (minute < 0)) ||
                      (second < 0)) ||
                     (ticks < 0)))
                {
                    throw new System.ArgumentOutOfRangeException();
                }
            }
            catch (System.Exception e)
            {
                throw new System.ArgumentOutOfRangeException(null, e.Message);
            }
            datetime = new System.DateTime(year, month, day, hour, minute, second, 0);
            datetime = datetime.AddTicks(ticks);
            System.TimeSpan tickOffset         = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime);
            int             UTCOffset          = 0;
            int             OffsetToBeAdjusted = 0;
            long            OffsetMins         = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute)));

            tempString = dmtf.Substring(22, 3);
            if ((tempString != "******"))
            {
                tempString = dmtf.Substring(21, 4);
                try
                {
                    UTCOffset = int.Parse(tempString);
                }
                catch (System.Exception e)
                {
                    throw new System.ArgumentOutOfRangeException(null, e.Message);
                }
                OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset)));
                datetime           = datetime.AddMinutes(((double)(OffsetToBeAdjusted)));
            }
            return(datetime);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// <para>Converts a given DMTF datetime to <see cref='System.DateTime'/> object. The returned DateTime will be in the
        ///			current TimeZone of the system.</para>
        /// </summary>
        /// <param name='dmtfDate'>A string representing the datetime in DMTF format.</param>
        /// <returns>
        /// <para>A <see cref='System.DateTime'/> object that represents the given DMTF datetime.</para>
        /// </returns>
        /// <remarks>
        ///			<para> Date and time in WMI is represented in DMTF datetime format. This format is explained in WMI SDK documentation.
        ///				DMTF datetime string has an UTC offset which this datetime string represents.
        ///				 During conversion to <see cref='System.DateTime'/>, UTC offset is used to convert the date to the
        ///				current timezone. According to DMTF format a particular field can be represented by the character
        ///				'*'. This will be converted to the MinValue of this field that can be represented in <see cref='System.DateTime'/>.
        ///			</para>
        /// </remarks>
        /// <example>
        ///    <code lang='C#'>
        ///	// Convert a DMTF datetime to System.DateTime
        ///	DateTime date = ManagementDateTimeConverter.ToDateTime("20020408141835.999999-420");
        ///    </code>
        ///    <code lang='VB'>
        ///	' Convert a DMTF datetime to System.DateTime
        ///	Dim date as DateTime = ManagementDateTimeConverter.ToDateTime("20020408141835.999999-420")
        ///    </code>
        /// </example>
        public static DateTime ToDateTime(string dmtfDate)
        {
            int      year     = DateTime.MinValue.Year;
            int      month    = DateTime.MinValue.Month;
            int      day      = DateTime.MinValue.Day;
            int      hour     = DateTime.MinValue.Hour;
            int      minute   = DateTime.MinValue.Minute;
            int      second   = DateTime.MinValue.Second;
            int      millisec = 0;
            string   dmtf     = dmtfDate;
            DateTime datetime = DateTime.MinValue;

            // If the string passed is empty or null then throw
            // an exception
            if (dmtf == null)
            {
                throw new System.ArgumentOutOfRangeException("dmtfDate");
            }
            if (dmtf.Length == 0)
            {
                throw new System.ArgumentOutOfRangeException("dmtfDate");
            }

            // if the length of the string is not equal to the
            // standard length of the DMTF datetime then throw an exception
            if (dmtf.Length != SIZEOFDMTFDATETIME)
            {
                throw new System.ArgumentOutOfRangeException("dmtfDate");
            }

            IFormatProvider frmInt32 = (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(System.Int32));

            System.Int64 ticks = 0;
            try
            {
                string tempString = System.String.Empty;
                tempString = dmtf.Substring(0, 4);
                if (("****" != tempString))
                {
                    year = System.Int32.Parse(tempString, frmInt32);
                }
                tempString = dmtf.Substring(4, 2);
                if (("**" != tempString))
                {
                    month = System.Int32.Parse(tempString, frmInt32);
                }
                tempString = dmtf.Substring(6, 2);
                if (("**" != tempString))
                {
                    day = System.Int32.Parse(tempString, frmInt32);
                }
                tempString = dmtf.Substring(8, 2);
                if (("**" != tempString))
                {
                    hour = System.Int32.Parse(tempString, frmInt32);
                }
                tempString = dmtf.Substring(10, 2);
                if (("**" != tempString))
                {
                    minute = System.Int32.Parse(tempString, frmInt32);
                }
                tempString = dmtf.Substring(12, 2);
                if (("**" != tempString))
                {
                    second = System.Int32.Parse(tempString, frmInt32);
                }
                tempString = dmtf.Substring(15, 6);
                if (("******" != tempString))
                {
                    ticks = (System.Int64.Parse(tempString, (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(System.Int64)))) * (System.TimeSpan.TicksPerMillisecond / 1000);
                }
                if (year < 0 || month < 0 || day < 0 || hour < 0 || minute < 0 || second < 0 || ticks < 0)
                {
                    throw new System.ArgumentOutOfRangeException("dmtfDate");
                }
            }
            catch
            {
                throw new System.ArgumentOutOfRangeException("dmtfDate");
            }


            // Construct a new System.DateTime object
            datetime = new System.DateTime(year, month, day, hour, minute, second, millisec);
            // Then add the ticks calculated from the microseconds
            datetime = datetime.AddTicks(ticks);

            // Adjust the UTC time to reflect the current zone time
            System.TimeZone curZone    = System.TimeZone.CurrentTimeZone;
            System.TimeSpan tickOffset = curZone.GetUtcOffset(datetime);
            long            OffsetMins = tickOffset.Ticks / System.TimeSpan.TicksPerMinute;

            // Adjusting the DateTime for the current UTC
            int    UTCOffset          = 0;
            string tempString1        = dmtf.Substring(22, 3);
            long   OffsetToBeAdjusted = 0;

            if (("***" != tempString1))
            {
                tempString1 = dmtf.Substring(21, 4);
                try
                {
                    UTCOffset = System.Int32.Parse(tempString1, frmInt32);
                }
                catch
                {
                    throw new System.ArgumentOutOfRangeException();
                }

                OffsetToBeAdjusted = UTCOffset - OffsetMins;

                // We have to substract the minutes from the time
                datetime = datetime.AddMinutes(OffsetToBeAdjusted * -1);
            }
            return(datetime);
        }
Ejemplo n.º 10
0
 // Converts a given datetime in DMTF format to System.DateTime object.
 static System.DateTime ToDateTime(string dmtfDate)
 {
     System.DateTime initializer = System.DateTime.MinValue;
     int year = initializer.Year;
     int month = initializer.Month;
     int day = initializer.Day;
     int hour = initializer.Hour;
     int minute = initializer.Minute;
     int second = initializer.Second;
     long ticks = 0;
     string dmtf = dmtfDate;
     System.DateTime datetime = System.DateTime.MinValue;
     string tempString = string.Empty;
     if ((dmtf == null))
     {
         throw new System.ArgumentOutOfRangeException();
     }
     if ((dmtf.Length == 0))
     {
         throw new System.ArgumentOutOfRangeException();
     }
     if ((dmtf.Length != 25))
     {
         throw new System.ArgumentOutOfRangeException();
     }
     try
     {
         tempString = dmtf.Substring(0, 4);
         if (("****" != tempString))
         {
             year = int.Parse(tempString);
         }
         tempString = dmtf.Substring(4, 2);
         if (("**" != tempString))
         {
             month = int.Parse(tempString);
         }
         tempString = dmtf.Substring(6, 2);
         if (("**" != tempString))
         {
             day = int.Parse(tempString);
         }
         tempString = dmtf.Substring(8, 2);
         if (("**" != tempString))
         {
             hour = int.Parse(tempString);
         }
         tempString = dmtf.Substring(10, 2);
         if (("**" != tempString))
         {
             minute = int.Parse(tempString);
         }
         tempString = dmtf.Substring(12, 2);
         if (("**" != tempString))
         {
             second = int.Parse(tempString);
         }
         tempString = dmtf.Substring(15, 6);
         if (("******" != tempString))
         {
             ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000))));
         }
         if (((((((((year < 0)
                     || (month < 0))
                     || (day < 0))
                     || (hour < 0))
                     || (minute < 0))
                     || (minute < 0))
                     || (second < 0))
                     || (ticks < 0)))
         {
             throw new System.ArgumentOutOfRangeException();
         }
     }
     catch (System.Exception e)
     {
         throw new System.ArgumentOutOfRangeException(null, e.Message);
     }
     datetime = new System.DateTime(year, month, day, hour, minute, second, 0);
     datetime = datetime.AddTicks(ticks);
     System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime);
     int UTCOffset = 0;
     int OffsetToBeAdjusted = 0;
     long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute)));
     tempString = dmtf.Substring(22, 3);
     if ((tempString != "******"))
     {
         tempString = dmtf.Substring(21, 4);
         try
         {
             UTCOffset = int.Parse(tempString);
         }
         catch (System.Exception e)
         {
             throw new System.ArgumentOutOfRangeException(null, e.Message);
         }
         OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset)));
         datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted)));
     }
     return datetime;
 }
Ejemplo n.º 11
0
 public IDateTime AddMinutes(double value)
 {
     return(new DateTime(backingDateTime.AddMinutes(value).Ticks));
 }
Ejemplo n.º 12
0
        // actions that can be accessed from more then one room - 10
        public List <Choice> generalActions()
        {
            List <Choice> actions = new List <Choice>();

            // bed + couch
            actions.Add(new Choice("sleep", () => {
                CheckRepeat("sleep");
                time         = time.AddMinutes(60);
                lastActionID = "sleep";
            }));
            actions.Add(new Choice("nap", () => {
                CheckRepeat("nap");
                time         = time.AddMinutes(30);
                lastActionID = "nap";
            }));
            actions.Add(new Choice("jump", () => {
                CheckRepeat("jump");
                time         = time.AddMinutes(30);
                lastActionID = "jump";
            }));

            // tv + pc
            actions.Add(new Choice("play games", () => {
                CheckRepeat("play");
                Dialogue a = new Dialogue("I should play...", new int[] { 6, 7, 8 });
                DialogueMenu(a);
                lastActionID = "play";
            }));
            actions.Add(new Choice("netflix&chill", () => {
                time         = time.AddMinutes(60);
                lastActionID = "watch";
            }));
            // bathroom + kitchen
            actions.Add(new Choice("wash hands", () => {
                CheckRepeat("wash");
                time = time.AddMinutes(5);
                if (lastActionID == "number2")
                {
                    cleanFactor = cleanFactor + 1;
                }
                lastActionID = "wash";
            }));
            //game-followup
            actions.Add(new Choice("MatrixJam", () => {
                time = time.AddMinutes(45);
                vids[0].Play();
                vidPanel.SetActive(true);
            }));
            actions.Add(new Choice("A day in life 2020", () => {
                DeathScreen(9);
            }));
            actions.Add(new Choice("fart in a jar", () => {
                time = time.AddMinutes(30);
                vids[1].Play();
                vidPanel.SetActive(true);
            }));
            actions.Add(new Choice("4", () => {
                time = time.AddMinutes(15);
                vids[2].Play();
                vidPanel.SetActive(true);
            }));
            return(actions);
        }
Ejemplo n.º 13
0
        /**
         * @return un oggetto di tipo bool
         * Il metodo in questione verifica la validità del file contenente i metadatai
         * salvato sul File System.
         *
         */
        private bool checkCachedMetadataValidity()
        {
            const string pos = "Cachemanager.checkCachedMetadataValidity - ";
            log.Info(pos + "INIT");

            bool validity = true;
            lastWriteTime = File.GetLastWriteTime(Constants.getMetadatasetFullName());

            log.Info(pos + "lastWriteTime:" + lastWriteTime);

            System.DateTime dateValidity = lastWriteTime.AddMinutes(Constants.KP_METADATASET_TIMEOUT);
            System.DateTime currDate = System.DateTime.Now;

            log.Info(pos + "Validity time:" + dateValidity);
            log.Info(pos + "Current time:" + currDate);

            if (dateValidity.CompareTo(currDate) < 0)
            {
                validity = false;
            }

            log.Info(pos + "Validity :" + validity);

            return validity;
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Converts a string value to a System.DateTime
        /// </summary>
        /// <param name="value">
        /// The date string.
        /// </param>
        /// <param name="format">
        /// The format where 103 = dd/MM/yyyy
        /// </param>
        /// <returns>
        /// A System.DateTime
        /// </returns>
        /// <exception cref="System.Exception">
        /// Exception is thrown if the given string value does not meet the expected format.
        /// </exception>
        public static System.DateTime ToDateTime(this string value, int format)
        {
            var result = new System.DateTime();

            switch (format)
            {
            case 103:
                // Validate
                if ((!string.IsNullOrEmpty(value)) && System.Text.RegularExpressions.Regex.IsMatch(value.Trim(), "^(((0[1-9]|[12]\\d|3[01])\\/(0[13578]|1[02])\\/((1[6-9]|[2-9]\\d)\\d{2}))|((0[1-9]|[12]\\d|30)\\/(0[13456789]|1[012])\\/((1[6-9]|[2-9]\\d)\\d{2}))|((0[1-9]|1\\d|2[0-8])\\/02\\/((1[6-9]|[2-9]\\d)\\d{2}))|(29\\/02\\/((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$"))
                {
                    // Build
                    var dateParts = value.Trim().Split(System.Convert.ToChar("/"));
                    result = result.AddYears(System.Convert.ToInt32(dateParts[2]) - 1);
                    result = result.AddMonths(System.Convert.ToInt32(dateParts[1]) - 1);
                    result = result.AddDays(System.Convert.ToInt32(dateParts[0]) - 1);
                }
                else
                {
                    throw new System.Exception($"String \"{value}\" is not of expected format \"{format}\".");
                }

                break;

            case -1:
                // Validate
                if ((!string.IsNullOrEmpty(value)) && value.Contains(" "))
                {
                    var strDate = value.Trim().Split(System.Convert.ToChar(" "));
                    if (strDate.Length == 2)
                    {
                        if (System.Text.RegularExpressions.Regex.IsMatch(strDate[0].Trim(), "^(((0[1-9]|[12]\\d|3[01])\\/(0[13578]|1[02])\\/((1[6-9]|[2-9]\\d)\\d{2}))|((0[1-9]|[12]\\d|30)\\/(0[13456789]|1[012])\\/((1[6-9]|[2-9]\\d)\\d{2}))|((0[1-9]|1\\d|2[0-8])\\/02\\/((1[6-9]|[2-9]\\d)\\d{2}))|(29\\/02\\/((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$"))
                        {
                            // Build
                            var dateParts = strDate[0].Trim().Split(System.Convert.ToChar("/"));
                            result = result.AddYears(System.Convert.ToInt32(dateParts[2]) - 1);
                            result = result.AddMonths(System.Convert.ToInt32(dateParts[1]) - 1);
                            result = result.AddDays(System.Convert.ToInt32(dateParts[0]) - 1);
                        }
                        else
                        {
                            throw new System.Exception($"String \"{value}\" is not of expected format \"{System.Convert.ToString(format)}\".");
                        }

                        if (System.Text.RegularExpressions.Regex.IsMatch(strDate[1].Trim(), "^([0-1][0-9]|[2][0-3]):([0-5][0-9])$"))
                        {
                            // Build
                            var timeParts = strDate[1].Trim().Split(System.Convert.ToChar(":"));
                            result = result.AddHours(System.Convert.ToInt32(timeParts[0]));
                            result = result.AddMinutes(System.Convert.ToInt32(timeParts[1]));
                        }
                        else
                        {
                            throw new System.Exception($"String \"{value}\" is not of expected format \"{System.Convert.ToString(format)}\".");
                        }
                    }
                    else
                    {
                        throw new System.Exception($"String \"{value}\" is not of expected format \"{System.Convert.ToString(format)}\".");
                    }
                }
                else
                {
                    throw new System.Exception($"String \"{value}\" is not of expected format \"{System.Convert.ToString(format)}\".");
                }

                break;
            }

            return(result);
        }