Пример #1
0
public static void Main(string [] args)
{
try
{

SystemTime time = new SystemTime();
GetSystemTime(ref time);
Console.WriteLine("Year : " +time.year);
Console.WriteLine("month : " +time.month);
Console.WriteLine("Days of Week : " +time.daysofweek);
Console.WriteLine("Day : " + time.day);
Console.WriteLine("Hours : " + time.hour);
Console.WriteLine("minutes : " + time.minute);
Console.WriteLine("Seconds : " + time.seconds);
Console.WriteLine("milliseconds : " + time.milliseconds);
time.year += 1;
SetSystemTime(ref  time);

Console.WriteLine("new year " + time.year);
}
catch(Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message);
}
}
Пример #2
0
 static void Main(string[] args)
 {
     SystemTime t = new SystemTime();
     GetSystemTime(t);
     Console.WriteLine("{0}:{1}:{2}.{3}", t.Hour, t.Minute, t.Second, t.Milliseconds);
     Console.ReadLine();
 }
Пример #3
0
        public static DateTime GetDateTime(int sysTime)
        {
            IntPtr pSysTime = new IntPtr(sysTime);

            SystemTime sTime = new SystemTime();
            sTime = (SystemTime) Marshal.PtrToStructure(pSysTime, typeof (SystemTime));

            return sTime.ToDateTime();
        }
Пример #4
0
    public static bool SetLocalTimeByDateTime(System.DateTime dt)
    {
        bool flag = false;
        SystemTime timeData = new SystemTime();
        timeData.wYear = (ushort)dt.Year;
        timeData.wMonth = (ushort)dt.Month;
        timeData.wDay = (ushort)dt.Day;
        timeData.wHour = (ushort)dt.Hour;
        timeData.wMinute = (ushort)dt.Minute;
        timeData.wSecond = (ushort)dt.Second;

        flag = SetLocalTime(ref timeData);
        return flag;
    }
Пример #5
0
 public static void SetSystemTime(DateTime dateTime)
 {
     // Set system date and time
     SystemTime updatedTime = new SystemTime();
     updatedTime.Year = (ushort)dateTime.Year;
     updatedTime.Month = (ushort)dateTime.Month;
     updatedTime.Day = (ushort)dateTime.Day;
     // UTC time; it will be modified according to the regional settings of the target computer so the actual hour might differ
     updatedTime.Hour = (ushort)dateTime.Hour;
     updatedTime.Minute = (ushort)dateTime.Minute;
     updatedTime.Second = (ushort)dateTime.Second;
     // Call the unmanaged function that sets the new date and time instantly
     Win32SetSystemTime(ref updatedTime);
 }
Пример #6
0
        public static int SetLocalTime(DateTime datetime)
        {
            SystemTime systNew = new SystemTime();

            // 设置属性
            systNew.wDay = (short)datetime.Day;
            systNew.wMonth = (short)datetime.Month;
            systNew.wYear = (short)datetime.Year;
            systNew.wHour = (short)datetime.Hour;
            systNew.wMinute = (short)datetime.Minute;
            systNew.wSecond = (short)datetime.Second;
            systNew.wMilliseconds = (short)datetime.Millisecond;

            // 调用API,更新系统时间
            return SetLocalTime(ref systNew);
        }
Пример #7
0
        static void Main()
        {
            Console.WriteLine("It shows system time columns:");

            var t1 = new SystemTime {Name = "tom"};
            t1.Save();

            var t2 = SystemTime.FindById(t1.Id);
            Console.WriteLine("1) => {0}", t2);

            Thread.Sleep(2000);
            t1.Save();

            var t3 = SystemTime.FindById(t1.Id);
            Console.WriteLine("2) => {0}", t3);
        }
Пример #8
0
        public int Check_Before_Login()
        {
            try
            {
                OleDbConnection conn = new OleDbConnection(strConAll);
                string selectcmd = "select sysdate from dual";

                OleDbCommand comm = new OleDbCommand(selectcmd, conn);

                OleDbDataAdapter da = new OleDbDataAdapter(comm);
                DataSet ds = new DataSet();
                da.Fill(ds);

                //System.DateTime SQLServer_time = (System.DateTime)comm.ExecuteScalar();
                System.DateTime SQLServer_time = (System.DateTime)ds.Tables[0].Rows[0][0];
                conn.Close();

                //SqlConnection conn = new SqlConnection(strConAll);
                //conn.Open();
                //SqlCommand scmd = new SqlCommand(selectcmd, conn);
                //System.DateTime SQLServer_time = (System.DateTime)scmd.ExecuteScalar();
                //conn.Close();

                //根据得到的时间日期,来定义时间、日期
                SystemTime st = new SystemTime();
                st.wYear = (short)SQLServer_time.Year;
                st.wDay = (short)SQLServer_time.Day;
                st.wMonth = (short)SQLServer_time.Month;
                st.wHour = (short)SQLServer_time.Hour;
                st.wMinute = (short)SQLServer_time.Minute;
                st.wSecond = (short)SQLServer_time.Second;
                //修改本地端的时间和日期
                Win32API.SetLocalTime(ref st);
                return 1;

            }
            catch
            {
                MessageBox.Show("服务器可能没启动,请检查以后重新进入! ", "错误 ", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return 0;
                //Application.Exit();
            }
        }
Пример #9
0
 public DateTime[] GetRunTimes(DateTime start, DateTime end, uint count = 0)
 {
     var pstStart = new SystemTime(start);
     var pstEnd = new SystemTime(end);
     var zero = IntPtr.Zero;
     if (_v2Task != null)
         _v2Task.GetRunTimes(ref pstStart, ref pstEnd, ref count, ref zero);
     else
     {
         var num = (count > 0 && count <= 0x5a0 ? (ushort)count : (ushort)0x5a0);
         _v1Task.GetRunTimes(ref pstStart, ref pstEnd, ref num, ref zero);
         count = num;
     }
     var timeArray = new DateTime[count];
     for (var i = 0; i < count; i++)
     {
         var ptr = new IntPtr(zero.ToInt64() + (i * Marshal.SizeOf(typeof(SystemTime))));
         timeArray[i] = (DateTime)((SystemTime)Marshal.PtrToStructure(ptr, typeof(SystemTime)));
     }
     Marshal.FreeCoTaskMem(zero);
     return timeArray;
 }
Пример #10
0
        /// <summary>
        /// 数据中心校时
        /// </summary>
        /// <param name="_now"></param>
        public static bool CheckLocalTime(DateTime _now)
        {
            try
            {
                SystemTime systNew = new SystemTime();

                // 设置属性
                systNew.wYear = short.Parse(_now.Year.ToString());
                systNew.wMonth = short.Parse(_now.Month.ToString());
                systNew.wDay = short.Parse(_now.Day.ToString());
                systNew.wHour = short.Parse(_now.Hour.ToString());
                systNew.wMinute = short.Parse(_now.Minute.ToString());
                systNew.wSecond = short.Parse(_now.Second.ToString());

                // 调用API,更新系统时间
                return SetLocalTime(ref systNew).Equals(1);
            }
            catch
            {
                return false;
            }
        }
Пример #11
0
        public static unsafe void serverThread()
        {
            UdpClient udpClient = new UdpClient(SERVER_PORT);

            string dataTemplate = "sync ";

            while (true)
            {
                IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
                Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
                string returnData = Encoding.ASCII.GetString(receiveBytes);

                if (returnData.IndexOf(dataTemplate) != -1)
                {
                    SystemTime systime = new SystemTime();
                    LibWrap.GetSystemTime(systime);

                    int startIndex = dataTemplate.Length;
                    int allData = returnData.Length;
                    string dataString = returnData.Substring(startIndex, allData - startIndex);

                    DateTime data = Convert.ToDateTime(dataString);

                    systime.Hour = (ushort)data.Hour;
                    systime.Minute = (ushort)data.Minute;
                    systime.Second = (ushort)data.Second;

                    LibWrap.Win32SetSystemTime(systime);

                    Console.WriteLine("Время синхронизировано!");

                    break;
                }
            }

            // Console.ReadLine();
        }
 static extern void GetSystemTime(SystemTime st);
 public static SuperDate Today()
 {
     SystemTime systime = new SystemTime();
     GetSystemTime(systime);
     return new SuperDate(systime.wYear, systime.wMonth, systime.wDay);
 }
        public void FindTop_Should_Return_Top_Users()
        {
            UserScores.AddRange(
                new[]
            {
                new UserScore
                {
                    Id         = 1,
                    Score      = 10,
                    Timestamp  = SystemTime.Now().AddDays(-1),
                    ActionType = UserAction.AccountActivated,
                    User       = new User {
                        Id = Guid.NewGuid(), Role = Roles.User
                    }
                },
                new UserScore
                {
                    Id         = 1,
                    Score      = 10,
                    Timestamp  = SystemTime.Now().AddHours(-12),
                    ActionType = UserAction.AccountActivated,
                    User       = new User {
                        Id = Guid.NewGuid(), Role = Roles.User
                    }
                },
            }
                );

            Users.AddRange(UserScores.Select(us => us.User));

            var pagedResult = _userRepository.FindTop(SystemTime.Now().AddMonths(-1), SystemTime.Now(), 0, 10);

            Assert.Equal(2, pagedResult.Result.Count);
            Assert.Equal(2, pagedResult.Total);
        }
Пример #15
0
 public static extern bool SetSystemTime(ref SystemTime sysTime);
Пример #16
0
 public static extern int SetLocalTime(ref   SystemTime lpSystemTime);
Пример #17
0
 public extern static int SetLocalTime(ref SystemTime st);
        public void FindScoreById_Should_Return_Correct_Score()
        {
            var id = Guid.NewGuid();

            UserScores.AddRange(new []
            {
                new UserScore
                {
                    Id         = 1,
                    Score      = 10,
                    Timestamp  = SystemTime.Now().AddDays(-3),
                    ActionType = UserAction.AccountActivated,
                    UserId     = id
                },
                new UserScore
                {
                    Id         = 2,
                    Score      = 20,
                    Timestamp  = SystemTime.Now().AddDays(-2),
                    ActionType = UserAction.StorySubmitted,
                    UserId     = id
                }
            }
                                );


            var score = _userRepository.FindScoreById(id, SystemTime.Now().AddMonths(-1), SystemTime.Now());

            Assert.Equal(30, score);
        }
Пример #19
0
        public void KbdData(string param, string data)
        {
            try
            {
                if (param.StartsWith("scale"))
                {
                    param = param.Remove(0, "scale".Length);
                    if (ActionMgr.ConvertToRange(param) != ActionMgr.RNG_INVALID)
                    {
                        RunWnd.syscfg.SetScaleAdjust(ActionMgr.ConvertToRange(param), Convert.ToDouble(data));
                    }
                    return;
                }
                if (param == "5" || param == "10")
                {
                    RunWnd.syscfg.SetCurrent(5, (param.IndexOfAny("5".ToCharArray()) < 0), Convert.ToDouble(data));
                }
                if (param == "1" || param == "2")
                {
                    RunWnd.syscfg.SetCurrent(4, (param.IndexOfAny("1".ToCharArray()) < 0), Convert.ToDouble(data));
                }
                if (param == "0.3" || param == "0.6")
                {
                    RunWnd.syscfg.SetCurrent(3, (param.IndexOfAny("3".ToCharArray()) < 0), Convert.ToDouble(data));
                }
                if (param == "0.1" || param == "0.2")
                {
                    RunWnd.syscfg.SetCurrent(2, (param.IndexOfAny("1".ToCharArray()) < 0), Convert.ToDouble(data));
                }
                if (param == "0.01" || param == "0.02")
                {
                    RunWnd.syscfg.SetCurrent(1, (param.IndexOfAny("1".ToCharArray()) < 0), Convert.ToDouble(data));
                }
                if (param == "0.001" || param == "0.002")
                {
                    RunWnd.syscfg.SetCurrent(0, (param.IndexOfAny("1".ToCharArray()) < 0), Convert.ToDouble(data));
                }
                if (param == "0.0001" || param == "0.0002")
                {
                    RunWnd.syscfg.SetCurrent(-1, (param.IndexOfAny("1".ToCharArray()) < 0), Convert.ToDouble(data));
                }
                if (param == "exportdate")
                {
                    #region remove date log
                    if (Regex.IsMatch(data, "^820\\d\\d\\d\\d\\d\\d$"))
                    {
                        data = data.Remove(0, 1);
                        try
                        {
                            foreach (string dname in Directory.GetDirectories(StringResource.basedir, "20*"))
                            {
                                string[] todel = Directory.GetFiles(dname, "20*.txt");
                                foreach (string fname in todel)
                                {
                                    FileInfo fi = new FileInfo(fname);
                                    Match    m  = Regex.Match(fi.Name, @"(\d\d\d\d)_(\d\d)_(\d\d).*");
                                    if (m.Success)
                                    {
                                        if ((Convert.ToUInt16(data.Substring(0, 4)) <= Convert.ToUInt16(m.Groups[1].Value)) &&
                                            (Convert.ToUInt16(data.Substring(4, 2)) <= Convert.ToUInt16(m.Groups[2].Value)) &&
                                            (Convert.ToUInt16(data.Substring(6, 2)) <= Convert.ToUInt16(m.Groups[3].Value)))
                                        {
                                            //do nothing
                                        }
                                        else
                                        {
                                            File.Delete(fname);
                                        }
                                    }
                                }
                            }
                        }
                        catch
                        {
                        }
                        return;
                    }
                    #endregion

                    if (Regex.IsMatch(data, "^20\\d\\d\\d\\d\\d\\d$"))
                    {
                        export_start = data;
                        Program.kbd.Init(StringResource.str("enter_endexport"), "endexport", false, KbdData);
                    }
                    return;
                }
                if (param == "endexport")
                {
                    if (!Regex.IsMatch(data, "^20\\d\\d\\d\\d\\d\\d$"))
                    {
                        return;
                    }

                    try
                    {
                        foreach (string dname in Directory.GetDirectories(StringResource.basedir, "20*"))
                        {
                            foreach (string fname in Directory.GetFiles(dname, "20*.txt"))
                            {
                                FileInfo fi = new FileInfo(fname);
                                Match    m  = Regex.Match(fi.Name, @"(\d\d\d\d)_(\d\d)_(\d\d).*");
                                if (m.Success)
                                {
                                    if ((Convert.ToUInt16(data.Substring(0, 4)) >= Convert.ToUInt16(m.Groups[1].Value)) &&
                                        (Convert.ToUInt16(data.Substring(4, 2)) >= Convert.ToUInt16(m.Groups[2].Value)) &&
                                        (Convert.ToUInt16(data.Substring(6, 2)) >= Convert.ToUInt16(m.Groups[3].Value)) &&
                                        (Convert.ToUInt16(export_start.Substring(0, 4)) <= Convert.ToUInt16(m.Groups[1].Value)) &&
                                        (Convert.ToUInt16(export_start.Substring(4, 2)) <= Convert.ToUInt16(m.Groups[2].Value)) &&
                                        (Convert.ToUInt16(export_start.Substring(6, 2)) <= Convert.ToUInt16(m.Groups[3].Value)))
                                    {
                                        File.Copy(fname, StringResource.udiskdir + "\\" + fi.Name, true);
                                    }
                                }
                            }
                        }
                        Program.msg.Init(StringResource.str("export_done"));
                    }
                    catch
                    {
                        Program.msg.Init(StringResource.str("export_fail"));
                        return;
                    }
                }
                if (param == "newtime")
                {
                    if (!Regex.IsMatch(newdate, "^\\d\\d\\d\\d\\d\\d\\d\\d$"))
                    {
                        return;
                    }

                    if (!Regex.IsMatch(data, "^\\d\\d\\d\\d\\d\\d$"))
                    {
                        return;
                    }
                    SystemTime time = new SystemTime();
                    time.wYear        = Convert.ToUInt16(newdate.Substring(0, 4));
                    time.wMonth       = Convert.ToUInt16(newdate.Substring(4, 2));
                    time.wDay         = Convert.ToUInt16(newdate.Substring(6, 2));
                    time.wHour        = Convert.ToUInt16(data.Substring(0, 2));
                    time.wMinute      = Convert.ToUInt16(data.Substring(2, 2));
                    time.wSecond      = Convert.ToUInt16(data.Substring(4, 2));
                    time.wMiliseconds = 0;
                    SetLocalTime(ref time);
                }
                if (param == "newdate")
                {
                    if (data.StartsWith("8")) //input of scale offset
                    {
                        string sparam = data.Remove(0, 1);
                        if (ActionMgr.ConvertToRange(sparam) != ActionMgr.RNG_INVALID)
                        {
                            this.Invoke(new Action <string>(enterscale), new string[] { sparam });
                        }
                        return;
                    }
                    if (data == "00000") //current calibration
                    {
                        Program.Upgrade();
                        return;
                    }
                    if (data == "99999") //current calibration
                    {
                        string sparam = data.Remove(0, 1);
                        RxInfo myrx   = Program.lst_rxinfo[Program.mainwnd.selectedRx];
                        myrx.var.rRs = Program.lst_rsinfo[0].dTValue;
                        if (myrx.iRRange == ActionMgr.RNG_P001)
                        {
                            myrx.var.iK = 1; //1000:1
                        }
                        else if (myrx.iRRange == ActionMgr.RNG_P01)
                        {
                            myrx.var.iK = 10; //100:1
                        }
                        else if (myrx.iRRange == ActionMgr.RNG_P1)
                        {
                            myrx.var.iK = 100; //10:1
                        }
                        else
                        {
                            myrx.var.iK = (int)Math.Floor(1000.0 / (myrx.var.rRs * RunWnd.syscfg.GetStdCurrent(myrx.iIx, myrx.bSqrt)));
                        }

                        if (myrx.var.iK > 1020)
                        {
                            Program.msg.Init("标准电阻阻值过小,无法校准。标准电阻上电压应不小于1V");
                            return;
                        }
                        Program.msg.Init(String.Format(@"电流校准完成,电流值为{0}", Util.FormatData(Program.mainwnd.task.act_mgr.CalibrateCurr(myrx), 8)));
                        return;
                    }
                    if (data == "1" || data == "2" ||
                        data == "5" || data == "10" ||
                        data == "0.3" || data == "0.6" ||
                        data == "0.1" || data == "0.2" ||
                        data == "0.01" || data == "0.02" ||
                        data == "0.001" || data == "0.002" ||
                        data == "0.0001" || data == "0.0002")
                    {
                        this.Invoke(new Action <string>(entercurrent), new string[] { data });
                        return;
                    }
                    if (data == "65890192")
                    {
                        Process.GetCurrentProcess().Kill(); //back door to exit the current program
                        return;
                    }
                    if (data == "658901920")
                    {
                        Program.OpenLog(0);
                        return;
                    }

                    if (data == "12345678")
                    {
                        Process app = new Process();
                        app.StartInfo.WorkingDirectory = @"\Windows";
                        app.StartInfo.FileName         = @"\Windows\TouchKit.exe";
                        app.StartInfo.Arguments        = "";
                        app.Start();
                        btn_quit_ValidClick(null, null);
                        return;
                    }
                    newdate = data;
                    this.Invoke(new Action(EnterNewTime));
                    return;
                }

                if (param == "ktt")
                {
                    RunWnd.syscfg.iKTT = Convert.ToInt32(data);
                }
                if (param == "measdelay")
                {
                    RunWnd.syscfg.iMeasDelay = Convert.ToInt32(data);
                }
                if (param == "sampletimes")
                {
                    RunWnd.syscfg.iSampleTimes = Convert.ToInt32(data);
                }
                if (param == "meastimes")
                {
                    RunWnd.syscfg.iMeasTimes = Convert.ToInt32(data);
                }
                if (param == "fltlength")
                {
                    RunWnd.syscfg.iFilter = Convert.ToInt32(data);
                }
                InitDisplay();
            }
            catch
            {
            }
        }
Пример #20
0
 public static extern bool SetLocalTime(ref SystemTime sysTime); //设置本地时
        public void SuccessMatch()
        {
            // Arrange
            var validatorFactory = new Mock <IValidatorEngine>();
            var mappingEngine    = new Mock <IMappingEngine>();
            var repository       = new Mock <IRepository>();
            var searchCache      = new Mock <ISearchCache>();

            var service = new PartyRoleService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object);

            // Domain details
            var system = new MDM.SourceSystem {
                Name = "Endur"
            };
            var mapping = new PartyRoleMapping
            {
                System       = system,
                MappingValue = "A",
            };
            var targetSystem = new MDM.SourceSystem {
                Name = "Trayport"
            };
            var targetMapping = new PartyRoleMapping
            {
                System       = targetSystem,
                MappingValue = "B",
                IsDefault    = true
            };
            var details = new MDM.PartyRoleDetails
            {
                Name = "PartyRole 1"
            };
            var party = new MDM.PartyRole
            {
                Id = 1
            };

            party.AddDetails(details);
            party.ProcessMapping(mapping);
            party.ProcessMapping(targetMapping);

            // Contract details
            var targetIdentifier = new MdmId
            {
                SystemName = "Trayport",
                Identifier = "B"
            };

            mappingEngine.Setup(x => x.Map <PartyRoleMapping, MdmId>(targetMapping)).Returns(targetIdentifier);

            var list = new List <PartyRoleMapping> {
                mapping
            };

            repository.Setup(x => x.Queryable <PartyRoleMapping>()).Returns(list.AsQueryable());

            var request = new CrossMappingRequest
            {
                SystemName       = "Endur",
                Identifier       = "A",
                TargetSystemName = "trayport",
                ValidAt          = SystemTime.UtcNow(),
                Version          = 1
            };

            // Act
            var response  = service.CrossMap(request);
            var candidate = response.Contract;

            // Assert
            Assert.IsNotNull(response, "Contract null");
            Assert.IsNotNull(candidate, "Mapping null");
            Assert.AreEqual(1, candidate.Mappings.Count, "Identifier count incorrect");
            Assert.AreSame(targetIdentifier, candidate.Mappings[0], "Different identifier assigned");
        }
Пример #22
0
 public static extern bool SetLocalTime(ref SystemTime sysTime); //设置本地时
Пример #23
0
 public TimeZoneInformation(Win32Native.DynamicTimeZoneInformation dtzi) {
     Bias = dtzi.Bias;
     StandardName = dtzi.StandardName;
     StandardDate = dtzi.StandardDate;
     StandardBias = dtzi.StandardBias;
     DaylightName = dtzi.DaylightName;
     DaylightDate = dtzi.DaylightDate;
     DaylightBias = dtzi.DaylightBias;
 }
Пример #24
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="strTime"></param>
        /// <returns></returns>
        private bool EditTime(string strTime)
        {
            try
            {
                SystemTime systNew = new SystemTime();

                string[] sArray = strTime.Split(' ');
                string[] sArrYear = sArray[0].ToString().Split('-');
                string[] sArrTime = sArray[1].ToString().Split(':');

                systNew.wYear = Convert.ToInt16(sArrYear[0].ToString());
                systNew.wMonth = Convert.ToInt16(sArrYear[1].ToString());
                systNew.wDay = Convert.ToInt16(sArrYear[2].ToString());
                systNew.wHour = Convert.ToInt16(sArrTime[0].ToString());
                systNew.wMinute = Convert.ToInt16(sArrTime[1].ToString());
                systNew.wSecond = Convert.ToInt16(sArrTime[2].ToString());
                int result = SetLocalTime(ref systNew);


                if (result == 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }

            }
            catch (Exception ex)
            {
                if (ex.Message == "尝试读取或写入受保护的内存。这通常指示其他内存已损坏。")
                {
                    return false;
                }
            }
            return true;
        }
Пример #25
0
 static extern int GetDateFormat(int locale, uint dwFlags, ref SystemTime sysTime, string format, StringBuilder sb, int sbSize);
Пример #26
0
 static void UpdateTime()
 {
     GetSystemTimeZone();
     DateTime dt = GetBeijingTime();
     string timeZone = INIFILE.GetValue("MAIN", "TimeZone");
     DateTime dtUTC = TimeZoneInfo.ConvertTimeToUtc(dt, TimeZoneInfo.FindSystemTimeZoneById(ListTimeMap[defaultTimeSpane]));
     dt = TimeZoneInfo.ConvertTimeFromUtc(dtUTC, TimeZoneInfo.FindSystemTimeZoneById(ListTimeMap.Values.ElementAt(GetIndex(timeZone))));
     SystemTime st = new SystemTime();
     st.FromDateTime(dt);
     SetLocalTime(ref st);
 }
Пример #27
0
 static extern int GetTimeFormatW(uint locale, uint dwFlags, ref SystemTime time, string format, StringBuilder sb, int sbSize);
Пример #28
0
        public void KbdData(string param, string data)
        {
            try
            {
                if (param.StartsWith("scale"))
                {
                    param = param.Remove(0, "scale".Length);
                    if(ActionMgr.ConvertToRange(param)!= ActionMgr.RNG_INVALID)
                        RunWnd.syscfg.SetScaleAdjust(ActionMgr.ConvertToRange(param), Convert.ToDouble(data));
                    return;
                }
                if (param == "5" || param == "10")
                    RunWnd.syscfg.SetCurrent(5, (param.IndexOfAny("5".ToCharArray()) < 0), Convert.ToDouble(data));
                if (param == "1" || param == "2" )
                    RunWnd.syscfg.SetCurrent(4, (param.IndexOfAny("1".ToCharArray()) < 0), Convert.ToDouble(data));
                if (param == "0.3" || param == "0.6")
                    RunWnd.syscfg.SetCurrent(3, (param.IndexOfAny("3".ToCharArray()) < 0), Convert.ToDouble(data));
                  if(  param == "0.1" || param == "0.2" )
                      RunWnd.syscfg.SetCurrent(2, (param.IndexOfAny("1".ToCharArray()) < 0), Convert.ToDouble(data));
                  if(  param == "0.01" || param == "0.02" )
                      RunWnd.syscfg.SetCurrent(1, (param.IndexOfAny("1".ToCharArray()) < 0), Convert.ToDouble(data));
                  if(  param == "0.001" || param == "0.002" )
                      RunWnd.syscfg.SetCurrent(0, (param.IndexOfAny("1".ToCharArray()) < 0), Convert.ToDouble(data));
                  if(  param == "0.0001" || param == "0.0002")
                      RunWnd.syscfg.SetCurrent(-1, (param.IndexOfAny("1".ToCharArray()) < 0), Convert.ToDouble(data));
                if (param == "exportdate")
                {
                    #region remove date log
                    if (Regex.IsMatch(data, "^820\\d\\d\\d\\d\\d\\d$"))
                    {
                        data = data.Remove(0, 1);
                        try
                        {
                            foreach (string dname in Directory.GetDirectories(StringResource.basedir, "20*"))
                            {
                                string[] todel = Directory.GetFiles(dname, "20*.txt");
                                foreach (string fname in todel)
                                {
                                    FileInfo fi = new FileInfo(fname);
                                    Match m = Regex.Match(fi.Name, @"(\d\d\d\d)_(\d\d)_(\d\d).*");
                                    if (m.Success)
                                    {
                                        if ((Convert.ToUInt16(data.Substring(0, 4)) <= Convert.ToUInt16(m.Groups[1].Value)) &&
                                            (Convert.ToUInt16(data.Substring(4, 2)) <= Convert.ToUInt16(m.Groups[2].Value)) &&
                                            (Convert.ToUInt16(data.Substring(6, 2)) <= Convert.ToUInt16(m.Groups[3].Value)))
                                        {
                                            //do nothing
                                        }
                                        else
                                        {
                                            File.Delete(fname);
                                        }
                                    }
                                }
                            }
                        }
                        catch
                        {
                        }
                        return;
                    }
                    #endregion

                    if (Regex.IsMatch(data, "^20\\d\\d\\d\\d\\d\\d$"))
                    {
                        export_start = data;
                        Program.kbd.Init(StringResource.str("enter_endexport"), "endexport", false, KbdData);
                    }
                    return;
                }
                if(param == "endexport")
                {
                    if (!Regex.IsMatch(data, "^20\\d\\d\\d\\d\\d\\d$"))
                        return;
                    
                    try
                    {
                        foreach (string dname in Directory.GetDirectories(StringResource.basedir, "20*"))
                        {
                            foreach (string fname in Directory.GetFiles(dname, "20*.txt"))
                            {
                                FileInfo fi = new FileInfo(fname);
                                Match m = Regex.Match(fi.Name, @"(\d\d\d\d)_(\d\d)_(\d\d).*");
                                if (m.Success)
                                {
                                    if ((Convert.ToUInt16(data.Substring(0, 4)) >= Convert.ToUInt16(m.Groups[1].Value)) &&
                                        (Convert.ToUInt16(data.Substring(4, 2)) >= Convert.ToUInt16(m.Groups[2].Value)) &&
                                        (Convert.ToUInt16(data.Substring(6, 2)) >= Convert.ToUInt16(m.Groups[3].Value)) &&
                                        (Convert.ToUInt16(export_start.Substring(0, 4)) <= Convert.ToUInt16(m.Groups[1].Value)) &&
                                        (Convert.ToUInt16(export_start.Substring(4, 2)) <= Convert.ToUInt16(m.Groups[2].Value)) &&
                                        (Convert.ToUInt16(export_start.Substring(6, 2)) <= Convert.ToUInt16(m.Groups[3].Value)))
                                    {
                                        File.Copy(fname, StringResource.udiskdir + "\\" + fi.Name, true);
                                    }
                                }
                            }
                        }
                        Program.msg.Init(StringResource.str("export_done"));
                    }
                    catch
                    {
                        Program.msg.Init(StringResource.str("export_fail"));
                        return;
                    }
                }
                if (param == "newtime")
                {
                    if (!Regex.IsMatch(newdate, "^\\d\\d\\d\\d\\d\\d\\d\\d$"))
                        return;

                    if (!Regex.IsMatch(data, "^\\d\\d\\d\\d\\d\\d$"))
                        return;
                    SystemTime time = new SystemTime();
                    time.wYear = Convert.ToUInt16(newdate.Substring(0, 4));
                    time.wMonth = Convert.ToUInt16(newdate.Substring(4, 2));
                    time.wDay = Convert.ToUInt16(newdate.Substring(6, 2));
                    time.wHour = Convert.ToUInt16(data.Substring(0, 2));
                    time.wMinute = Convert.ToUInt16(data.Substring(2, 2));
                    time.wSecond = Convert.ToUInt16(data.Substring(4, 2));
                    time.wMiliseconds = 0;
                    SetLocalTime(ref time);
                }
                if (param == "newdate")
                {
                    if(data.StartsWith("8")) //input of scale offset
                    {
                        string sparam = data.Remove(0, 1);
                        if (ActionMgr.ConvertToRange(sparam) != ActionMgr.RNG_INVALID)
                        {
                            this.Invoke(new Action<string>(enterscale), new string[] { sparam });
                        }
                        return;
                    }
                    if (data=="00000") //do upgrade
                    {
                        Program.Upgrade();
                        return;
                    }
                    if(data == "99999") //current calibration
                    {
                        string sparam = data.Remove(0, 1);
                        RxInfo myrx = Program.lst_rxinfo[Program.mainwnd.selectedRx];
                        myrx.var.rRs = Program.lst_rsinfo[0].dTValue;
                        if (myrx.iRRange == ActionMgr.RNG_P001)
                            myrx.var.iK = 1; //1000:1
                        else if (myrx.iRRange == ActionMgr.RNG_P01)
                            myrx.var.iK = 10; //100:1
                        else if (myrx.iRRange == ActionMgr.RNG_P1)
                            myrx.var.iK = 100; //10:1
                        else
                            myrx.var.iK = (int)Math.Floor(1000.0 / (myrx.var.rRs*RunWnd.syscfg.GetStdCurrent(myrx.iIx,myrx.bSqrt)));
                        
                        if(myrx.var.iK > 1020)
                        {
                            Program.msg.Init("标准电阻阻值过小,无法校准。标准电阻上电压应不小于1V");
                            return;
                        }
                        Program.msg.Init(String.Format(@"电流校准完成,电流值为{0}", Util.FormatData(Program.mainwnd.task.act_mgr.CalibrateCurr(myrx), 8)));
                        return;
                    }
                    if (data == "1" || data == "2" ||
                        data == "5" || data == "10" ||
                        data == "0.3" || data == "0.6" ||
                        data == "0.1" || data == "0.2" ||
                        data == "0.01" || data == "0.02" ||
                        data == "0.001" || data == "0.002" ||
                        data == "0.0001" || data == "0.0002")
                    {
                        this.Invoke(new Action<string>(entercurrent), new string[] { data });
                        return;
                    }
                    if (data == "65890192")
                    {
                        Process.GetCurrentProcess().Kill(); //back door to exit the current program
                        return;
                    }
                    if (data == "658901920")
                    {
                        Program.OpenLog(0);
                        return;
                    }

                    if (data == "12345678")
                    {
                        Process app = new Process();
                        app.StartInfo.WorkingDirectory = @"\Windows";
                        app.StartInfo.FileName = @"\Windows\TouchKit.exe";
                        app.StartInfo.Arguments = "";
                        app.Start();
                        btn_quit_ValidClick(null, null);
                        return;
                    }
                    newdate = data;
                    this.Invoke(new Action(EnterNewTime));
                    return;
                }

                if (param == "ktt")
                {
                    RunWnd.syscfg.iKTT = Convert.ToInt32(data);
                }
                if (param == "measdelay")
                {
                    RunWnd.syscfg.iMeasDelay = Convert.ToInt32(data);
                }
                if (param == "sampletimes")
                {
                    RunWnd.syscfg.iSampleTimes = Convert.ToInt32(data);
                }
                if (param == "meastimes")
                {
                    RunWnd.syscfg.iMeasTimes = Convert.ToInt32(data);
                }
                if (param == "fltlength")
                {
                    RunWnd.syscfg.iFilter = Convert.ToInt32(data);
                }
                InitDisplay();
            }
            catch
            {
            }
        }
Пример #29
0
        public DatabaseSmuggler(DocumentDatabase database, ISmugglerSource source, ISmugglerDestination destination, SystemTime time,
                                DatabaseSmugglerOptionsServerSide options = null, SmugglerResult result = null, Action <IOperationProgress> onProgress = null,
                                CancellationToken token = default)
        {
            _database    = database;
            _source      = source;
            _destination = destination;
            _options     = options ?? new DatabaseSmugglerOptionsServerSide();
            _result      = result;
            _token       = token;

            if (string.IsNullOrWhiteSpace(_options.TransformScript) == false)
            {
                _patcher = new SmugglerPatcher(_options, database);
            }

            Debug.Assert((source is DatabaseSource && destination is DatabaseDestination) == false,
                         "When both source and destination are database, we might get into a delayed write for the dest while the " +
                         "source already pulsed its' read transaction, resulting in bad memory read.");

            _time       = time;
            _onProgress = onProgress ?? (progress => { });
        }
Пример #30
0
 public static extern bool FileTimeToSystemTime(
     [In] ref long fileTime,
     out SystemTime systemTime);
Пример #31
0
 public static extern bool SetLocalTime(ref SystemTime st);
Пример #32
0
 public RegistryTimeZoneInformation(Win32Native.TimeZoneInformation tzi) {
     Bias = tzi.Bias;
     StandardDate = tzi.StandardDate;
     StandardBias = tzi.StandardBias;
     DaylightDate = tzi.DaylightDate;
     DaylightBias = tzi.DaylightBias;
 }
Пример #33
0
 public static extern bool SetLocalTime(ref SystemTime theDateTime);
Пример #34
0
        // string ms:format-date(string datetime[, string format[, string language]])
        // string ms:format-time(string datetime[, string format[, string language]])
        //
        // Format xsd:dateTime as a date/time string for a given language using a given format string.
        // * Datetime contains a lexical representation of xsd:dateTime. If datetime is not valid, the
        //   empty string is returned.
        // * Format specifies a format string in the same way as for GetDateFormat/GetTimeFormat system
        //   functions. If format is the empty string or not passed, the default date/time format for the
        //   given culture is used.
        // * Language specifies a culture used for formatting. If language is the empty string or not
        //   passed, the current culture is used. If language is not recognized, a runtime error happens.
        public static string MSFormatDateTime(string dateTime, string format, string lang, bool isDate) {
            try {
                int locale = GetCultureInfo(lang).LCID;

                XsdDateTime xdt;
                if (! XsdDateTime.TryParse(dateTime, XsdDateTimeFlags.AllXsd | XsdDateTimeFlags.XdrDateTime | XsdDateTimeFlags.XdrTimeNoTz, out xdt)) {
                    return string.Empty;
                }
                SystemTime st = new SystemTime(xdt.ToZulu());

                StringBuilder sb = new StringBuilder(format.Length + 16);

                // If format is the empty string or not specified, use the default format for the given locale
                if (format.Length == 0) {
                    format = null;
                }
                if (isDate) {
                    int res = GetDateFormat(locale, 0, ref st, format, sb, sb.Capacity);
                    if (res == 0) {
                        res = GetDateFormat(locale, 0, ref st, format, sb, 0);
                        if (res != 0) {
                            sb = new StringBuilder(res);
                            res = GetDateFormat(locale, 0, ref st, format, sb, sb.Capacity);
                        }
                    }
                } else {
                    int res = GetTimeFormat(locale, 0, ref st, format, sb, sb.Capacity);
                    if (res == 0) {
                        res = GetTimeFormat(locale, 0, ref st, format, sb, 0);
                        if (res != 0) {
                            sb = new StringBuilder(res);
                            res = GetTimeFormat(locale, 0, ref st, format, sb, sb.Capacity);
                        }
                    }
                }
                return sb.ToString();
            } catch (ArgumentException) { // Operations with DateTime can throw this exception eventualy
                return string.Empty;
            }
        }
Пример #35
0
 private void SetsyncDateTime()
 {
     SystemTime updatedTime = new SystemTime();
     DateTime dateTime = new LoginService().GetSysDateTime();
     updatedTime.DayOfWeek = (short)dateTime.DayOfWeek;
     updatedTime.Year = (short)dateTime.Year;
     updatedTime.Month = (short)dateTime.Month;
     updatedTime.Day = (short)dateTime.Day;
     updatedTime.Hour = (short)dateTime.Hour;
     updatedTime.Minute = (short)dateTime.Minute;
     updatedTime.Second = (short)dateTime.Second;
     SetLocalTime(ref updatedTime);
 }
Пример #36
0
        public static string OSDateToString(DateTime date, string format, DateTimeFormatInfo dtfi, CultureInfo cultInfo)
        {
            string ret = string.Empty;

#if TEMP
            PropertyInfo cultureName = null;

            foreach (var pi in typeof(DateTimeFormatInfo).GetTypeInfo().DeclaredProperties)
            {
                if (pi.Name == "CultureName") cultureName = pi;
            }

            if (cultureName == null) throw new ArgumentException("Can't find CultureName property on DateTimeFormatInfo");

            // PropertyInfo cultureName = typeof(DateTimeFormatInfo).GetProperty("CultureName", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
            string culture = (string)cultureName.GetValue(dtfi, null);
#endif
            String culture = cultInfo.Name;
            StringBuilder dateSB = new StringBuilder();
            StringBuilder timeSB = new StringBuilder();
            string connector = " ";
            bool useDate = false;
            bool useTime = false;
            int locale = LCIDFromCultureInfo(new CultureInfo(culture));
            string formatDate = null;
            string formatTime = null;
            TimeFormatFlags timeFlag = 0;
            DateFormatFlags dateFlag = 0;

            #region Format switch
            switch (format)
            {
                case "d":
                    useDate = true;
                    dateFlag |= DateFormatFlags.DATE_SHORTDATE;
                    break;
                case "D":
                    useDate = true;
                    dateFlag |= DateFormatFlags.DATE_LONGDATE;
                    break;
                case "f":
                    useDate = true; useTime = true;
                    dateFlag |= DateFormatFlags.DATE_LONGDATE;
                    timeFlag |= TimeFormatFlags.TIME_SHORTTIME;
                    break;
                case "F":
                    useDate = true; useTime = true;
                    dateFlag |= DateFormatFlags.DATE_LONGDATE;
                    timeFlag |= TimeFormatFlags.TIME_LONGTIME;
                    break;
                case "g":
                    useDate = true; useTime = true;
                    dateFlag |= DateFormatFlags.DATE_SHORTDATE;
                    timeFlag |= TimeFormatFlags.TIME_SHORTTIME;
                    break;
                case "G":
                    useDate = true; useTime = true;
                    dateFlag |= DateFormatFlags.DATE_SHORTDATE;
                    timeFlag |= TimeFormatFlags.TIME_LONGTIME;
                    break;
                case "m":
                case "M":
                    formatDate = "MMMM dd";
                    break;
                case "y":
                case "Y":
                    useDate = true;
                    dateFlag |= DateFormatFlags.DATE_YEARMONTH;
                    break;
                case "s":
                    formatDate = "yyyy'-'MM'-'dd'";
                    formatTime = "HH':'mm':'ss";
                    connector = "T";
                    break;
                case "R":
                case "r":
                    formatDate = "ddd, dd MMM yyyy";
                    formatTime = "HH':'mm':'ss 'GMT'";
                    break;
                case "u":
                    formatDate = "yyyy'-'MM'-'dd";
                    formatTime = "HH':'mm':'ss'Z'";
                    break;
                case "U":
                    date = date.ToUniversalTime();
                    useDate = true; useTime = true;
                    dateFlag |= DateFormatFlags.DATE_LONGDATE;
                    timeFlag |= TimeFormatFlags.TIME_LONGTIME;
                    break;
                case "o":
                case "O":
                    formatDate = "yyyy-MM-dd";
                    formatTime = "HH:mm:ss.fffffffK";
                    connector = "T";
                    break;
                case "t":
                    useTime = true;
                    //timeFlag |= TimeFormatFlags.TIME_LONGTIME;  // By design :( DDT #1472
                    timeFlag |= TimeFormatFlags.TIME_SHORTTIME;  // Fixed on SL FC 75
                    break;
                case "T":
                    useTime = true;
                    timeFlag |= TimeFormatFlags.TIME_LONGTIME;
                    break;
                default:
                    connector = "";
                    format = format.Replace("%", string.Empty);
                    int pos = 0;
                    while (pos < format.Length && format[pos] != 'h' && format[pos] != 'H' && format[pos] != 'm' && format[pos] != 's'
                        && format[pos] != 'f' && format[pos] != 'K' && format[pos] != 'F' && format[pos] != 't' && format[pos] != 'z')
                        pos++;
                    if (pos == 0)
                    {
                        formatTime = format;
                    }
                    else if (pos < format.Length)
                    {
                        formatDate = format.Substring(0, pos);
                        formatTime = format.Substring(pos);
                    }
                    else
                    {
                        formatDate = format;
                    }
                    break;
            }
            #endregion

            SystemTime st = new SystemTime(date);
            if (!string.IsNullOrEmpty(formatDate) || !string.IsNullOrEmpty(formatTime))
            {
                ret = string.Empty;
                if (!string.IsNullOrEmpty(formatDate))
                {
                    int cap = GetDateFormatW((uint)locale, 0, ref st, formatDate, dateSB, 0);
                    dateSB = new StringBuilder(cap);
                    GetDateFormatW((uint)locale, 0, ref st, formatDate, dateSB, cap);
                    ret = dateSB.ToString();
                }
                if (!string.IsNullOrEmpty(formatDate) && !string.IsNullOrEmpty(formatTime))
                {
                    ret = ret + connector;
                }
                if (!string.IsNullOrEmpty(formatTime))
                {
                    while (formatTime.Contains("f"))
                    {
                        int beginFS = formatTime.IndexOf("f");
                        int fCount = 0;
                        while (beginFS < formatTime.Length && formatTime[beginFS] == 'f') { fCount++; beginFS++; }
                        long fraction = date.Ticks % 10000000;
                        string fractionalString = fraction.ToString().Substring(0, Math.Min(fCount, fraction.ToString().Length));
                        if (fCount > fractionalString.Length) fractionalString = fractionalString + new string('0', fCount - fractionalString.Length);
                        formatTime = formatTime.Replace(new string('f', fCount), fractionalString);
                    }
                    if (formatTime.Contains("K"))
                    {
                        string tz = null;
                        switch (date.Kind)
                        {
                            case DateTimeKind.Local:
                                TimeSpan offset = TimeZoneInfo.Local.GetUtcOffset(date);
                                if (offset.Ticks >= 0)
                                {
                                    tz = String.Format(CultureInfo.InvariantCulture, "+{0:00}:{1:00}", offset.Hours, offset.Minutes);
                                }
                                else
                                {
                                    tz = String.Format(CultureInfo.InvariantCulture, "-{0:00}:{1:00}", -offset.Hours, -offset.Minutes);
                                }
                                break;
                            case DateTimeKind.Utc:
                                tz = "Z";
                                break;
                            default:
                                tz = string.Empty;
                                break;
                        }
                        formatTime = formatTime.Replace("K", tz);
                    }
                    int cap = GetTimeFormatW((uint)locale, 0, ref st, formatTime, timeSB, 0);
                    timeSB = new StringBuilder(cap);
                    GetTimeFormatW((uint)locale, 0, ref st, formatTime, timeSB, cap);
                    ret = ret + timeSB.ToString();
                }
            }
            else
            {
                ret = string.Empty;
                if (useDate)
                {
                    int cap = GetDateFormatW((uint)locale, (uint)dateFlag, ref st, null, dateSB, 0);
                    dateSB = new StringBuilder(cap);
                    GetDateFormatW((uint)locale, (uint)dateFlag, ref st, null, dateSB, cap);
                    ret = dateSB.ToString();
                }
                if (useDate && useTime) ret = ret + connector;
                if (useTime)
                {
                    int cap = GetTimeFormatW((uint)locale, (uint)timeFlag, ref st, null, timeSB, 0);
                    timeSB = new StringBuilder(cap);
                    GetTimeFormatW((uint)locale, (uint)timeFlag, ref st, null, timeSB, cap);
                    ret = ret + timeSB.ToString();
                }
            }


            if (string.IsNullOrEmpty(ret)) throw new InvalidOperationException("Formatted DateTime unexpectedly empty\nDate: " + date.ToString() + "\nFormat: " + format);
            return ret;
        }
Пример #37
0
        public async Task <CreateInvitationResponse> Handle(CreateInvitationRequest request,
                                                            CancellationToken cancellationToken)
        {
            _logger.LogInformation($"CreateInvitationHandler : Create Invitation call received: {JsonConvert.SerializeObject(request)}");

            ValidateRequest(request);

            var client = await _loginContext.Clients.SingleOrDefaultAsync(c => c.Id == request.ClientId, cancellationToken : cancellationToken);

            if (client == null)
            {
                return(new CreateInvitationResponse()
                {
                    Message = "Client does not exist", ClientId = request.ClientId, Invited = false
                });
            }

            if (client.AllowInvitationSignUp == false)
            {
                return(new CreateInvitationResponse()
                {
                    Message = "Client is not authorised for Invitiation Signup", Invited = false, ClientId = request.ClientId, ServiceName = client.ServiceDetails?.ServiceName
                });
            }

            _logger.LogInformation($"CreateInvitationHandler : Client: {JsonConvert.SerializeObject(client)}");

            var existingUser = await _userAccountService.FindByEmail(request.Email);

            if (existingUser != null)
            {
                await _emailService.SendUserExistsEmail(new UserExistsEmailViewModel
                {
                    Subject      = "Sign up",
                    Contact      = request.GivenName,
                    LoginLink    = client.ServiceDetails.PostPasswordResetReturnUrl,
                    ServiceName  = client.ServiceDetails.ServiceName,
                    ServiceTeam  = client.ServiceDetails.ServiceTeam,
                    EmailAddress = request.Email,
                    TemplateId   = client.ServiceDetails.EmailTemplates.Single(t => t.Name == "LoginSignupError").TemplateId
                });

                return(new CreateInvitationResponse {
                    Message = "User already exists", ExistingUserId = existingUser.Id, Invited = false, ClientId = request.ClientId, ServiceName = client.ServiceDetails?.ServiceName, LoginLink = client.ServiceDetails?.PostPasswordResetReturnUrl
                });
            }

            var inviteExists = _loginContext.Invitations.SingleOrDefault(i => i.Email == request.Email);

            if (inviteExists != null)
            {
                _loginContext.Invitations.Remove(inviteExists);
            }

            var newInvitation = new Invitation
            {
                Email           = request.Email,
                GivenName       = request.GivenName,
                FamilyName      = request.FamilyName,
                SourceId        = request.SourceId,
                ValidUntil      = SystemTime.UtcNow().AddDays(_loginConfig.DaysInvitationIsValidFor).AddHours(1),
                CallbackUri     = request.Callback,
                UserRedirectUri = request.UserRedirect,
                ClientId        = request.ClientId
            };

            _loginContext.Invitations.Add(newInvitation);

            var linkUri = new Uri(_loginConfig.BaseUrl);
            var linkUrl = new Uri(linkUri, "Invitations/CreatePassword/" + newInvitation.Id).ToString();

            if (request.IsInvitationToOrganisation)
            {
                await _emailService.SendInvitationEmail(new InvitationEmailViewModel()
                {
                    Subject      = "Sign up",
                    LoginLink    = linkUrl,
                    ServiceName  = client.ServiceDetails.ServiceName,
                    ServiceTeam  = client.ServiceDetails.ServiceTeam,
                    EmailAddress = newInvitation.Email,
                    TemplateId   = client.ServiceDetails.EmailTemplates.Single(t => t.Name == "LoginSignupInvite").TemplateId,
                    Inviter      = $"{request.Inviter} of {request.OrganisationName}"
                });
            }
            else
            {
                await _emailService.SendInvitationEmail(new InvitationEmailViewModel()
                {
                    Subject            = "Sign up",
                    GivenName          = newInvitation.GivenName,
                    FamilyName         = newInvitation.FamilyName,
                    OrganisationName   = request.OrganisationName,
                    ApprenticeshipName = request.ApprenticeshipName,
                    LoginLink          = linkUrl,
                    CreateAccountLink  = linkUrl,
                    ServiceName        = client.ServiceDetails.ServiceName,
                    ServiceTeam        = client.ServiceDetails.ServiceTeam,
                    EmailAddress       = newInvitation.Email,
                    TemplateId         = client.ServiceDetails.EmailTemplates.Single(t => t.Name == "SignUpInvitation").TemplateId,
                    Inviter            = ""
                });
            }

            _loginContext.UserLogs.Add(new UserLog()
            {
                Id       = GuidGenerator.NewGuid(),
                Action   = "Invite",
                Email    = newInvitation.Email,
                Result   = "Invited",
                DateTime = SystemTime.UtcNow()
            });

            await _loginContext.SaveChangesAsync(cancellationToken);

            return(new CreateInvitationResponse()
            {
                Invited = true, InvitationId = newInvitation.Id, ClientId = request.ClientId, ServiceName = client.ServiceDetails?.ServiceName, LoginLink = client.ServiceDetails?.PostPasswordResetReturnUrl
            });
        }