public static SYSTEMTIME ByteArrayToSystemTime(Byte[] array, int dataOffset)
        {
            SYSTEMTIME result = new SYSTEMTIME();

            result.wYear = BitConverter.ToInt16(array, dataOffset);
            result.wMonth = BitConverter.ToInt16(array, dataOffset + 2);
            result.wDayOfWeek = BitConverter.ToInt16(array, dataOffset + 4);
            result.wDay = BitConverter.ToInt16(array, dataOffset + 6);
            result.wHour = BitConverter.ToInt16(array, dataOffset + 8);
            result.wMinute = BitConverter.ToInt16(array, dataOffset + 10);
            result.wSecond = BitConverter.ToInt16(array, dataOffset + 12);
            result.wMilliseconds = BitConverter.ToInt16(array, dataOffset + 14);

            return result;
        }
 static SYSTEMTIME()
 {
     MinValue = new SYSTEMTIME(1601, 1, 1);
     MaxValue = new SYSTEMTIME(30827, 12, 31, 23, 59, 59, 999);
 }
Example #3
0
 private static extern bool SetSystemTime(ref SYSTEMTIME time);
Example #4
0
        private void UpdateTime(DateTime gpsTime)
        {
            SYSTEMTIME s = new SYSTEMTIME();
             s.Year = (short) gpsTime.Year;
             s.Month = (short) gpsTime.Month;
             s.DayOfWeek = (short) gpsTime.DayOfWeek;
             s.Day = (short) gpsTime.Day;
             s.Hour = (short) gpsTime.Hour;
             s.Minute = (short) gpsTime.Minute;
             s.Second = (short) gpsTime.Second;
             s.Milliseconds = (short) gpsTime.Millisecond;

             bool t = SetSystemTime(ref s);
             Debug.WriteLine("SetSystemTime: " + t);
        }
Example #5
0
        bool SyncSystemTime()
        {
            if (position != null && position.TimeValid)
            {
                SYSTEMTIME st = new SYSTEMTIME();

                st.Day = (short)position.Time.Day;
                st.DayOfWeek = 0;
                st.Month = (short)position.Time.Month;
                st.Year = (short)position.Time.Year;
                st.Hour = (short)position.Time.Hour;
                st.Minute = (short)position.Time.Minute;
                st.Second = (short)position.Time.Second;
                st.Milliseconds = (short)position.Time.Millisecond;
                return SetSystemTime(ref st);
            }
            else
                return false;
        }
 public static extern bool TzSpecificLocalTimeToSystemTime(
     [In] ref TIME_ZONE_INFORMATION lpTimeZone,
     [In] ref SYSTEMTIME lpLocalTime,
     out SYSTEMTIME lpUniversalTime);
 public static extern bool FileTimeToSystemTime(
     [In] ref FILETIME lpFileTime,
     out SYSTEMTIME lpSystemTime);
        private static DateTime SystemTimeToDateTime(ref SYSTEMTIME st)
        {
            FILETIME ft = new FILETIME();

            NativeMethods.SystemTimeToFileTime(ref st, out ft);

            DateTime dt = new DateTime((((long)ft.dwHighDateTime)
                           << 32) | (uint)ft.dwLowDateTime);

            return dt;
        }
Example #9
0
        private static DateTime SystemTimeToDateTime( ref SYSTEMTIME st )
        {
            System.Runtime.InteropServices.ComTypes.FILETIME ft = new System.Runtime.InteropServices.ComTypes.FILETIME();

            NativeMethods.SystemTimeToFileTime( ref st, out ft );

            DateTime dt = new DateTime( ( ( (long) ft.dwHighDateTime ) << 32 ) | (uint) ft.dwLowDateTime );

            return dt;
        }
Example #10
0
 static SYSTEMTIME()
 {
     MinValue = new SYSTEMTIME(1601, 1, 1);
     MaxValue = new SYSTEMTIME(30827, 12, 31, 23, 59, 59, 999);
 }
Example #11
0
 public static extern bool FileTimeToSystemTime(
     [In] ref System.Runtime.InteropServices.ComTypes.FILETIME lpFileTime,
     out SYSTEMTIME lpSystemTime );
        // Added By JK on 01/09/12
        // Moved the code from Shell.xaml.cs to ModuleSelectionPresenter as the client wants
        // the Dispatcher to start even if the connection to backend is not established.
        private void Logon()
        {
            if (log.IsInfoEnabled) log.Info("Initiating Log on");
            int maxTime = (ConfigurationManager.AppSettings["MaxTurnTime"] == null) ? 20 : int.Parse(ConfigurationManager.AppSettings["MaxTurnTime"]);
            LogOnKioskResponse logonResponse = new LogOnKioskResponse();
            LogonServiceClient logonproxy = null;
            DateTime dtBeforeLogon, dtafterLogon, newDateTime;
            TimeSpan timeDiff;
            try
            {
                ValidateCertificate.RegisterCallback();
                logonproxy = new LogonServiceClient();

                if (log.IsInfoEnabled) log.Info("Requesting for Log on");
                dtBeforeLogon = DateTime.Now;
                logonResponse = logonproxy.LogOnKiosk(new LogOnKioskRequest
                {
                    KioskId = Int32.Parse(KioskAppConfig.KioskId),
                    StatusUpdated = DateTime.UtcNow,
                    ReleaseVersion = KioskAppConfig.CurrentVersion
                });

                dtafterLogon = DateTime.Now;
                timeDiff = dtafterLogon.Subtract(dtBeforeLogon);
                if (log.IsInfoEnabled) log.InfoFormat("Hours: {0}, Mins: {1} Sec: {2} Days:{3}", timeDiff.Hours, timeDiff.Minutes, timeDiff.Seconds, timeDiff.Days);
                if (log.IsInfoEnabled) log.Info("Requesting for Log on completed");

                if (!string.IsNullOrEmpty(logonResponse.XXX12))
                {
                    try
                    {
                        RegistryKey pRegKey = Registry.LocalMachine;
                        pRegKey = pRegKey.OpenSubKey("SOFTWARE\\USPInc");

                        SHA256 hasher = SHA256Managed.Create();
                        byte[] hashedData = hasher.ComputeHash(
                            Encoding.Unicode.GetBytes(logonResponse.XXX12));
                        StringBuilder sb = new StringBuilder();
                        foreach (byte b in hashedData)
                        {
                            sb.AppendFormat("{0:x2}", b);
                        }

                        pRegKey.SetValue("xxx23", sb.ToString(), RegistryValueKind.String);
                    }
                    catch (Exception ex)
                    {
                        if (log.IsErrorEnabled) log.ErrorFormat("Set xxx12 error : {0}", ex.Message);
                    }
                }

                logonResponse.isLoggedOn = true;
                if (logonResponse.isLoggedOn)
                {
                    if (log.IsInfoEnabled) log.Info("Kiosk Logged on");
                    //Populate Service List

                    KioskAppConfig.KioskServices = new List<Infrastructure.ObjectModel.KioskService>();
                    KioskAppConfig.KioskDevices = new List<Infrastructure.ObjectModel.KioskDevice>();
                    KioskAppConfig.KioskLocation = logonResponse.KioskLocation;
                    isMonitored = logonResponse.isMonitored;

                    if (timeDiff.Seconds >= 0 &&
                    timeDiff.Seconds <= maxTime)
                    {
                        if (log.IsInfoEnabled) log.InfoFormat("Kiosk Logged on between the turnaround time with time : {0}",logonResponse.CurrentTimeStamp);
                        timeDiff = TimeSpan.FromTicks(timeDiff.Ticks / 2);
                        newDateTime = Convert.ToDateTime(logonResponse.CurrentTimeStamp);//.ToLocalTime();
                        newDateTime.Add(timeDiff);

                        //admin Change the system time
                        if (log.IsInfoEnabled) log.Info("Synchronizing System Time");
                        SYSTEMTIME SysTime = new SYSTEMTIME();
                        SysTime.wYear = (short)newDateTime.Year;
                        SysTime.wMonth = (short)newDateTime.Month;
                        SysTime.wDay = (short)newDateTime.Day;
                        SysTime.wHour = (short)newDateTime.Hour;
                        SysTime.wMinute = (short)newDateTime.Minute;
                        SysTime.wSecond = (short)newDateTime.Second;
                        bool res = SetSystemTime(ref SysTime);

                        if (!res)
                        {
                            if (log.IsErrorEnabled) log.Error("System Time not changed Successfully");
                        }
                        else
                        {
                            if (log.IsInfoEnabled) log.Info("Changed System Time Successfully");
                        }
                    }

                       //this.Transaction.KioskServices = null;

                    foreach (MBMEKiosk.LogonProxy.KioskService service in logonResponse.BillerServiceList)
                    {
                        MBMEKiosk.Infrastructure.ObjectModel.KioskService item = new MBMEKiosk.Infrastructure.ObjectModel.KioskService()
                        {
                            BillerServiceId = service.BillerServiceId,
                            ServiceKey = service.ServiceKey,
                            ActivationDate = service.ActivationDate,
                            Available = service.Available,
                            BillerServiceName = service.BillerServiceName,
                            KioskId = service.KioskId,
                            KioskRefNum = service.KioskRefNum
                        };
                        KioskAppConfig.KioskServices.Add(item);
                    }

                    //Populate Device List
                    foreach (MBMEKiosk.LogonProxy.KioskDevice device in logonResponse.DeviceList)
                    {
                        MBMEKiosk.Infrastructure.ObjectModel.KioskDevice item = new MBMEKiosk.Infrastructure.ObjectModel.KioskDevice()
                        {
                            DeviceId = device.DeviceId,
                            //KioskDeviceId = device.KioskDeviceId,
                            DeviceKey = device.DeviceKey,
                            DeviceEnabled = device.DeviceEnabled,
                            DeviceName = device.DeviceName,
                            KioskId = device.KioskId,
                            KioskRefNum = device.KioskRefNum
                        };

                        KioskAppConfig.KioskDevices.Add(item);
                        if (log.IsInfoEnabled) log.Info("Machine Location retrieved is:" + KioskAppConfig.KioskLocation + ",MachineId:" + KioskAppConfig.KioskId);
                    }

                    // Modified By JK on 01/09/12
                    // Previously the developer had put AND condition but has been replaced with OR.
                    if ((logonResponse.BillerServiceList.Length == 0) &&
                        (logonResponse.DeviceList.Length == 0))
                    {
                        if (log.IsInfoEnabled) log.Info("Kiosk logged on not successful");
                        loggedOn = false;
                        if (log.IsInfoEnabled) log.Info("No Biller Service or Device configured for this Kiosk.");
                    }
                    else
                    {
                        loggedOn = true;
                        if (log.IsInfoEnabled) log.Info("Kiosk logged on successfull");
                        //initialize Devices
                        objKiosk.Name = ConfigurationManager.AppSettings["KDeviceId"].ToString(); ;

                        objPrinter.Name = ConfigurationManager.AppSettings["PDeviceId"].ToString();

                        objCashAcceptor.Name = ConfigurationManager.AppSettings["CADeviceId"].ToString();

                        var kioskDevice = (from A in KioskAppConfig.KioskDevices
                                           where A.DeviceName.Equals(objKiosk.Name)
                                           select A.DeviceId).SingleOrDefault();

                        objKiosk.DeviceId = kioskDevice.ToString();

                        var printerDevice = (from A in KioskAppConfig.KioskDevices
                                             where A.DeviceName.Equals(objPrinter.Name)
                                             select A.DeviceId).SingleOrDefault();

                        objPrinter.DeviceId = printerDevice.ToString();

                        var cashAcceptorDevice = (from A in KioskAppConfig.KioskDevices
                                                  where A.DeviceName.Equals(objCashAcceptor.Name)
                                                  select A.DeviceId).SingleOrDefault();

                        objCashAcceptor.DeviceId = cashAcceptorDevice.ToString();

                        if (connectivityPolling)
                        {
                            //if (isMonitored)
                            RestartConnectivityTimer();
                            //if (monitorClient == null)
                            //  monitorClient.CheckBackendConnectivityCompleted += new EventHandler<CheckBackendConnectivityCompletedEventArgs>(monitorClient_CheckBackendConnectivityCompleted);
                        }
                        if (shutdownCommandActive)
                            RestartShutdownTimer();
                    }
                }
            }
            catch (Exception ex)
            {
                loggedOn = false;
                if (logonproxy != null)
                    logonproxy.Abort();
                if (log.IsErrorEnabled) log.ErrorFormat("Kiosk logon unsuccessfull: {0} {1}", DateTime.Now.ToString(), ex.Message);
            }
            finally
            {
                if (!loggedOn)
                    RestartLogonTimer();
                if (logonproxy != null)
                    logonproxy.Close();
                ValidateCertificate.DeregisterCallback();
            }
        }
        private bool addNewNote(string id, NOTE_DATA data, SCHEDULE_TYPE schedule, NOTE_REL_POSITION relPos,
            ADDITIONAL_NAPP addApp, SYSTEMTIME creation, SYSTEMTIME deletion, NOTE_APPEARANCE appearance, NOTE_PIN pin,
            SEND_REC_STATUS sendrec, StringBuilder tags, StringBuilder links, Dictionary<int, int> groupIds, bool hide)
        {
            try
            {
                var sqlList = new List<string>();
                var sb = new StringBuilder();
                var afv = new AlarmAfterValues();
                var md = new MonthDay();
                var dw = new List<DayOfWeek>();
                var sc = new SizeConverter();
                var pc = new PointConverter();
                var ac = new AlarmAfterValuesConverter();
                var mdc = new MonthDayConverter();
                var dwc = new DaysOfWeekConverter();
                var lfc = new LogFontConverter();

                if (PNStatic.Notes.Any(n => n.ID == id))
                {
                    string message = PNLang.Instance.GetMessageText("id_exists",
                        "The note with the same ID already exists.");
                    message += '\n';
                    message += PNLang.Instance.GetMessageText("continue_anyway", "Continue anyway?");
                    if (
                        PNMessageBox.Show(message, PNStrings.PROG_NAME, MessageBoxButton.YesNo, MessageBoxImage.Question) ==
                        MessageBoxResult.No)
                    {
                        return false;
                    }
                }
                sqlList.Add("DELETE FROM NOTES WHERE ID = '" + id + "'");
                sb.Append(
                    "INSERT INTO NOTES (ID, NAME, GROUP_ID, PREV_GROUP_ID, OPACITY, VISIBLE, FAVORITE, PROTECTED, COMPLETED, PRIORITY, PASSWORD_STRING, PINNED, TOPMOST, ROLLED, DOCK_STATUS, DOCK_ORDER, SEND_RECEIVE_STATUS, DATE_CREATED, DATE_SAVED, DATE_SENT, DATE_RECEIVED, DATE_DELETED, SIZE, LOCATION, EDIT_SIZE, REL_X, REL_Y, SENT_TO, RECEIVED_FROM, PIN_CLASS, PIN_TEXT, RECEIVED_IP) VALUES(");
                // ID
                sb.Append("'");
                sb.Append(id);
                sb.Append("', ");
                // NAME
                sb.Append("'");
                sb.Append(data.szName.Replace("'", "''"));
                sb.Append("', ");
                // GROUP_ID
                if (groupIds.Keys.Contains(data.idGroup))
                {
                    sb.Append(groupIds[data.idGroup]);
                }
                else
                {
                    if (PNStatic.Groups.Any(g => g.ID == data.idGroup))
                    {
                        if (data.idGroup == GROUP_INCOMING)
                            sb.Append((int)SpecialGroups.Incoming);
                        else
                            sb.Append(data.idGroup);
                    }
                    else
                    {
                        sb.Append("0");
                    }
                }
                sb.Append(", ");
                // PREV_GROUP_ID
                sb.Append("0");
                sb.Append(", ");
                // OPACITY
                sb.Append(addApp.transValue != 0 ? (addApp.transValue / 255.0).ToString(PNStatic.CultureInvariant) : "1.0");
                sb.Append(", ");
                // VISIBLE
                sb.Append(!hide ? Convert.ToInt32(data.visible) : 0);
                sb.Append(", ");
                // FAVORITE
                sb.Append("0, ");
                // PROTECTED
                sb.Append(Convert.ToInt32(PNStatic.IsBitSet(data.res1, NB_PROTECTED)));
                sb.Append(", ");
                // COMPLETED
                sb.Append(Convert.ToInt32(PNStatic.IsBitSet(data.res1, NB_COMPLETED)));
                sb.Append(", ");
                // PRIORITY
                sb.Append(Convert.ToInt32(PNStatic.IsBitSet(data.res1, NB_HIGH_PRIORITY)));
                sb.Append(", ");
                // PASSWORD_STRING
                sb.Append("'',");
                // PINNED
                sb.Append(
                    Convert.ToInt32((pin.className != null && pin.text != null && pin.className != "" && pin.text != "")));
                sb.Append(", ");
                // TOPMOST
                sb.Append(Convert.ToInt32(data.onTop));
                sb.Append(", ");
                // ROLLED
                sb.Append(Convert.ToInt32(data.rolled));
                sb.Append(", ");
                // DOCK_STATUS
                int ddata = loWord(data.dockData);
                if (ddata < (int)DockStatus.None || ddata > (int)DockStatus.Bottom)
                    sb.Append((int)DockStatus.None);
                else
                    sb.Append(ddata);
                sb.Append(", ");
                // DOCK_ORDER
                var dorder = -1;
                switch ((DockStatus)ddata)
                {
                    case DockStatus.Left:
                    case DockStatus.Top:
                    case DockStatus.Right:
                    case DockStatus.Bottom:
                        if (PNStatic.DockedNotes[(DockStatus)ddata].Count > 0)
                        {
                            dorder = PNStatic.DockedNotes[(DockStatus)ddata].Max(n => n.DockOrder) + 1;
                            dorder += m_DockedNotes[(DockStatus)ddata];
                            m_DockedNotes[(DockStatus)ddata]++;
                        }
                        else
                            dorder = 0;
                        break;
                }
                sb.Append(dorder);
                sb.Append(", ");
                // SEND_RECEIVE_STATUS
                if (sendrec.sentTo != null && sendrec.recFrom != null && sendrec.sentTo != "" && sendrec.recFrom != "")
                    sb.Append((int)(SendReceiveStatus.Both));
                else if (!string.IsNullOrEmpty(sendrec.sentTo))
                    sb.Append((int)SendReceiveStatus.Sent);
                else if (!string.IsNullOrEmpty(sendrec.recFrom))
                    sb.Append((int)SendReceiveStatus.Received);
                else
                    sb.Append("0");
                sb.Append(", ");
                // DATE_CREATED
                DateTime date = new DateTime(creation.wYear != 0 ? creation.wYear : 1,
                    creation.wMonth != 0 ? creation.wMonth : 1, creation.wDay != 0 ? creation.wDay : 1, creation.wHour,
                    creation.wMinute, creation.wSecond);
                sb.Append("'");
                sb.Append(date.ToString(PNStrings.DATE_TIME_FORMAT, PNStatic.CultureInvariant).Replace("'", "''"));
                sb.Append("', ");
                // DATE_SAVED
                date = new DateTime(data.stChanged.wYear != 0 ? data.stChanged.wYear : 1,
                    data.stChanged.wMonth != 0 ? data.stChanged.wMonth : 1,
                    data.stChanged.wDay != 0 ? data.stChanged.wDay : 1, data.stChanged.wHour, data.stChanged.wMinute,
                    data.stChanged.wSecond);
                sb.Append("'");
                sb.Append(date.ToString(PNStrings.DATE_TIME_FORMAT, PNStatic.CultureInvariant).Replace("'", "''"));
                sb.Append("', ");
                // DATE_SENT
                date = new DateTime(sendrec.lastSent.wYear != 0 ? sendrec.lastSent.wYear : 1,
                    sendrec.lastSent.wMonth != 0 ? sendrec.lastSent.wMonth : 1,
                    sendrec.lastSent.wDay != 0 ? sendrec.lastSent.wDay : 1, sendrec.lastSent.wHour,
                    sendrec.lastSent.wMinute, sendrec.lastSent.wSecond);
                sb.Append("'");
                sb.Append(date.ToString(PNStrings.DATE_TIME_FORMAT, PNStatic.CultureInvariant).Replace("'", "''"));
                sb.Append("', ");
                // DATE_RECEIVED
                date = new DateTime(sendrec.lastRec.wYear != 0 ? sendrec.lastRec.wYear : 1,
                    sendrec.lastRec.wMonth != 0 ? sendrec.lastRec.wMonth : 1,
                    sendrec.lastRec.wDay != 0 ? sendrec.lastRec.wDay : 1, sendrec.lastRec.wHour, sendrec.lastRec.wMinute,
                    sendrec.lastRec.wSecond);
                sb.Append("'");
                sb.Append(date.ToString(PNStrings.DATE_TIME_FORMAT, PNStatic.CultureInvariant).Replace("'", "''"));
                sb.Append("', ");
                // DATE_DELETED
                date = new DateTime(deletion.wYear != 0 ? deletion.wYear : 1, deletion.wMonth != 0 ? deletion.wMonth : 1,
                    deletion.wDay != 0 ? deletion.wDay : 1, deletion.wHour, deletion.wMinute, deletion.wSecond);
                sb.Append("'");
                sb.Append(date.ToString(PNStrings.DATE_TIME_FORMAT, PNStatic.CultureInvariant).Replace("'", "''"));
                sb.Append("', ");
                // SIZE
                Size size = new Size(data.rcp.right - data.rcp.left, data.rcp.bottom - data.rcp.top);
                sb.Append("'");
                sb.Append(sc.ConvertToString(null, PNStatic.CultureInvariant, size));
                sb.Append("', ");
                // LOCATION
                Point location = new Point(data.rcp.left, data.rcp.top);
                sb.Append("'");
                sb.Append(pc.ConvertToString(null, PNStatic.CultureInvariant, location));
                sb.Append("', ");
                // EDIT_SIZE - just copy note size, there is no way to get the edit size of note
                sb.Append("'");
                sb.Append(sc.ConvertToString(null, PNStatic.CultureInvariant, size));
                sb.Append("', ");
                // REL_X
                sb.Append(Math.Abs(relPos.left - 0) > double.Epsilon
                    ? relPos.left.ToString(PNStatic.CultureInvariant)
                    : "1.0");
                sb.Append(", ");
                // REL_Y
                sb.Append(Math.Abs(relPos.top - 0) > double.Epsilon
                    ? relPos.top.ToString(PNStatic.CultureInvariant)
                    : "1.0");
                sb.Append(", ");
                // SENT_TO
                sb.Append("'");
                sb.Append(!string.IsNullOrEmpty(sendrec.sentTo) ? sendrec.sentTo.Replace("'", "''") : "");
                sb.Append("', ");
                // RECEIVED_FROM
                sb.Append("'");
                sb.Append(!string.IsNullOrEmpty(sendrec.recFrom) ? sendrec.recFrom.Replace("'", "''") : "");
                sb.Append("', ");
                // PIN_CLASS
                sb.Append("'");
                sb.Append(!string.IsNullOrEmpty(pin.className) ? pin.className.Replace("'", "''") : "");
                sb.Append("', ");
                // PIN_TEXT
                sb.Append("'");
                sb.Append(!string.IsNullOrEmpty(pin.text) ? pin.text.Replace("'", "''") : "");
                //RECEIVED_IP
                sb.Append("', ''");
                
                sb.Append(")");
                sqlList.Add(sb.ToString());

                // schedule
                // SCHEDULE_TYPE
                if (schedule.scType > 0)
                {
                    ScheduleType sctype;
                    if (schedule.scType > START_PROG)
                    {
                        sctype = (ScheduleType)(schedule.scType - START_PROG);
                    }
                    else
                    {
                        sctype = (ScheduleType)schedule.scType;
                    }
                    var doInsert = true;
                    if (sctype == ScheduleType.RepeatEvery || sctype == ScheduleType.After)
                    {
                        if (schedule.scDate.wYear == 0 &&
                            schedule.scDate.wMonth == 0 &&
                            schedule.scDate.wDayOfWeek == 0 &&
                            schedule.scDate.wDay == 0 &&
                            schedule.scDate.wHour == 0 &&
                            schedule.scDate.wMinute == 0 &&
                            schedule.scDate.wSecond == 0)
                        {
                            doInsert = false;
                        }
                    }
                    if (doInsert)
                    {
                        sb = new StringBuilder();
                        sb.Append(
                            "INSERT INTO NOTES_SCHEDULE (NOTE_ID, SCHEDULE_TYPE, ALARM_DATE, START_DATE, LAST_RUN, SOUND, STOP_AFTER, TRACK, REPEAT_COUNT, SOUND_IN_LOOP, USE_TTS, START_FROM, MONTH_DAY, ALARM_AFTER, WEEKDAYS, PROG_TO_RUN, CLOSE_ON_NOTIFICATION, MULTI_ALERTS, TIME_ZONE) VALUES(");
                        // NOTE_ID
                        sb.Append("'");
                        sb.Append(id);
                        sb.Append("', ");
                        sb.Append((int)sctype);
                        sb.Append(", ");
                        // ALARM_DATE
                        date = new DateTime(schedule.scDate.wYear != 0 ? schedule.scDate.wYear : 1,
                            schedule.scDate.wMonth != 0 ? schedule.scDate.wMonth : 1,
                            schedule.scDate.wDay != 0 ? schedule.scDate.wDay : 1, schedule.scDate.wHour,
                            schedule.scDate.wMinute, schedule.scDate.wSecond);
                        sb.Append("'");
                        sb.Append(date.ToString(PNStrings.DATE_TIME_FORMAT, PNStatic.CultureInvariant)
                            .Replace("'", "''"));
                        sb.Append("', ");
                        // START_DATE
                        date = new DateTime(schedule.scStart.wYear != 0 ? schedule.scStart.wYear : 1,
                            schedule.scStart.wMonth != 0 ? schedule.scStart.wMonth : 1,
                            schedule.scStart.wDay != 0 ? schedule.scStart.wDay : 1, schedule.scStart.wHour,
                            schedule.scStart.wMinute, schedule.scStart.wSecond);
                        sb.Append("'");
                        sb.Append(date.ToString(PNStrings.DATE_TIME_FORMAT, PNStatic.CultureInvariant)
                            .Replace("'", "''"));
                        sb.Append("', ");
                        // LAST_RUN
                        date = new DateTime(schedule.scLastRun.wYear != 0 ? schedule.scLastRun.wYear : 1,
                            schedule.scLastRun.wMonth != 0 ? schedule.scLastRun.wMonth : 1,
                            schedule.scLastRun.wDay != 0 ? schedule.scLastRun.wDay : 1, schedule.scLastRun.wHour,
                            schedule.scLastRun.wMinute, schedule.scLastRun.wSecond);
                        sb.Append("'");
                        sb.Append(date.ToString(PNStrings.DATE_TIME_FORMAT, PNStatic.CultureInvariant)
                            .Replace("'", "''"));
                        sb.Append("', ");
                        // SOUND
                        sb.Append("'");
                        sb.Append(schedule.szSound != null && schedule.szSound.Trim().Length > 0
                            ? schedule.szSound.Replace("'", "''")
                            : PNSchedule.DEF_SOUND);
                        sb.Append("', ");
                        // STOP_AFTER
                        sb.Append(schedule.stopLoop);
                        sb.Append(", ");
                        // TRACK
                        sb.Append(Convert.ToInt32(!PNStatic.IsBitSet(data.res1, NB_NOT_TRACK)));
                        sb.Append(", ");
                        // REPEAT_COUNT - no way to get repeat count
                        sb.Append(0);
                        sb.Append(", ");
                        // SOUND_IN_LOOP
                        sb.Append(Convert.ToInt32(PNStatic.IsBitSet(schedule.parameters, SP_SOUND_IN_LOOP)));
                        sb.Append(", ");
                        // USE_TTS
                        sb.Append(Convert.ToInt32(PNStatic.IsBitSet(schedule.parameters, SP_USE_TTS)));
                        sb.Append(", ");
                        // START_FROM
                        if (schedule.scType > START_PROG)
                            sb.Append((int)ScheduleStart.ProgramStart);
                        else
                            sb.Append((int)ScheduleStart.ExactTime);
                        sb.Append(", ");
                        // MONTH_DAY
                        if (sctype == ScheduleType.MonthlyDayOfWeek)
                        {
                            md.WeekDay = (DayOfWeek)schedule.scDate.wDayOfWeek;
                            md.OrdinalNumber = (DayOrdinal)schedule.scDate.wMilliseconds;
                        }
                        sb.Append("'");
                        var convertToString = mdc.ConvertToString(md);
                        if (convertToString != null) sb.Append(convertToString.Replace("'", "''"));
                        sb.Append("', ");
                        // ALARM_AFTER
                        if (sctype == ScheduleType.RepeatEvery || sctype == ScheduleType.After)
                        {
                            afv.Years = schedule.scDate.wYear;
                            afv.Months = schedule.scDate.wMonth;
                            afv.Weeks = schedule.scDate.wDayOfWeek;
                            afv.Days = schedule.scDate.wDay;
                            afv.Hours = schedule.scDate.wHour;
                            afv.Minutes = schedule.scDate.wMinute;
                            afv.Seconds = schedule.scDate.wSecond;
                        }
                        sb.Append("'");
                        sb.Append(ac.ConvertToString(afv).Replace("'", "''"));
                        sb.Append("', ");
                        // WEEKDAYS
                        if (sctype == ScheduleType.Weekly)
                        {
                            if (PNStatic.IsBitSet(schedule.scDate.wDayOfWeek, 1))
                                dw.Add(DayOfWeek.Sunday);
                            if (PNStatic.IsBitSet(schedule.scDate.wDayOfWeek, 2))
                                dw.Add(DayOfWeek.Monday);
                            if (PNStatic.IsBitSet(schedule.scDate.wDayOfWeek, 3))
                                dw.Add(DayOfWeek.Tuesday);
                            if (PNStatic.IsBitSet(schedule.scDate.wDayOfWeek, 4))
                                dw.Add(DayOfWeek.Wednesday);
                            if (PNStatic.IsBitSet(schedule.scDate.wDayOfWeek, 5))
                                dw.Add(DayOfWeek.Thursday);
                            if (PNStatic.IsBitSet(schedule.scDate.wDayOfWeek, 6))
                                dw.Add(DayOfWeek.Friday);
                            if (PNStatic.IsBitSet(schedule.scDate.wDayOfWeek, 7))
                                dw.Add(DayOfWeek.Saturday);
                        }
                        sb.Append("'");
                        sb.Append(dwc.ConvertToString(dw));
                        sb.Append("','");
                        //PROG_TO_RUN
                        sb.Append("',");
                        //CLOSE_ON_NOTIFICATION
                        sb.Append(0);
                        //MULTI_ALERTS
                        sb.Append(", NULL");
                        //TIME_ZONE
                        sb.Append(", NULL");
                        sb.Append(")");
                        sqlList.Add(sb.ToString());
                    }
                }
                // custom note settings
                sb = new StringBuilder();
                sb.Append(
                    "INSERT INTO CUSTOM_NOTES_SETTINGS (NOTE_ID, BACK_COLOR, CAPTION_FONT_COLOR, CAPTION_FONT, SKIN_NAME, CUSTOM_OPACITY) VALUES(");
                // NOTE_ID
                sb.Append("'");
                sb.Append(id);
                sb.Append("', ");
                // BACK_COLOR
                if (appearance.crWindow != 0 && (appearance.nPrivate & F_B_COLOR) == F_B_COLOR)
                {
                    sb.Append("'");
                    var colorString = PNStatic.FromIntToColorString(appearance.crWindow);
                    sb.Append(colorString);
                    sb.Append("', ");
                }
                else
                {
                    sb.Append("NULL, ");
                }
                // CAPTION_FONT_COLOR
                if (appearance.crCaption != 0 && (appearance.nPrivate & F_C_COLOR) == F_C_COLOR)
                {
                    sb.Append("'");
                    var colorString = PNStatic.FromIntToColorString(appearance.crCaption);
                    sb.Append(colorString);
                    sb.Append("', ");
                }
                else
                {
                    sb.Append("NULL, ");
                }
                // CAPTION_FONT
                if (appearance.lfCaption.lfFaceName != null && appearance.lfCaption.lfFaceName.Trim().Length > 0 &&
                    (appearance.nPrivate & F_C_FONT) == F_C_FONT)
                {
                    var lf = new LOGFONT
                    {
                        lfCharSet = appearance.lfCaption.lfCharSet,
                        lfClipPrecision = appearance.lfCaption.lfClipPrecision,
                        lfEscapement = appearance.lfCaption.lfEscapement,
                        lfFaceName = appearance.lfCaption.lfFaceName.Trim(),
                        lfHeight = appearance.lfCaption.lfHeight,
                        lfItalic = appearance.lfCaption.lfItalic,
                        lfOrientation = appearance.lfCaption.lfOrientation,
                        lfOutPrecision = appearance.lfCaption.lfOutPrecision,
                        lfPitchAndFamily = appearance.lfCaption.lfPitchAndFamily,
                        lfQuality = appearance.lfCaption.lfQuality,
                        lfStrikeOut = appearance.lfCaption.lfStrikeOut,
                        lfUnderline = appearance.lfCaption.lfUnderline,
                        lfWeight = appearance.lfCaption.lfWeight,
                        lfWidth = appearance.lfCaption.lfWidth
                    };
                    sb.Append("'");
                    sb.Append(lfc.ConvertToString(lf));
                    sb.Append("', ");
                }
                else
                {
                    sb.Append("NULL, ");
                }
                // SKIN_NAME
                if (appearance.szSkin != null && appearance.szSkin.Trim().Length > 0 &&
                    (appearance.nPrivate & F_SKIN) == F_SKIN)
                {
                    sb.Append("'");
                    sb.Append(appearance.szSkin.Trim().Replace("'", "''"));
                    sb.Append("', ");
                }
                else
                {
                    sb.Append("NULL, ");
                }
                // CUSTOM_OPACITY
                sb.Append(addApp.transValue != 0 ? 1 : 0);
                sb.Append(")");
                sqlList.Add(sb.ToString());

                // linked notes
                if (links.Length > 0)
                {
                    var arr = links.ToString().Split('|');
                    foreach (var s in arr)
                    {
                        if (s.Trim().Length > 0)
                        {
                            sb = new StringBuilder();
                            sb.Append("INSERT INTO LINKED_NOTES (NOTE_ID, LINK_ID) VALUES(");
                            // NOTE_ID
                            sb.Append("'");
                            sb.Append(id);
                            sb.Append("', ");
                            // LINK_ID
                            sb.Append("'");
                            sb.Append(s);
                            sb.Append("'");
                            sb.Append(")");
                            sqlList.Add(sb.ToString());
                        }
                    }
                }

                // tags
                if (tags.Length > 0)
                {
                    var arr = tags.ToString().Split(',');
                    foreach (var s in arr)
                    {
                        if (s.Trim().Length > 0)
                        {
                            sb = new StringBuilder();
                            sb.Append("INSERT INTO NOTES_TAGS (NOTE_ID, TAG) VALUES(");
                            // NOTE_ID
                            sb.Append("'");
                            sb.Append(id);
                            sb.Append("', ");
                            // TAG
                            sb.Append("'");
                            sb.Append(s.Replace("'", "''"));
                            sb.Append("'");
                            sb.Append(") ");
                            sqlList.Add(sb.ToString());
                        }
                    }
                }

                if (!removeNote(id))
                    return false;
                if (!PNData.ExecuteTransactionForList(sqlList, PNData.ConnectionString))
                    return false;
                return true;
            }
            catch (Exception ex)
            {
                PNStatic.LogException(ex);
                return false;
            }
        }
        private void importNotes(Dictionary<int, int> groupIds)
        {
            try
            {
                var listID = new List<string>();
                var size = 1024;

                var dbPath =
                    Path.Combine(
                        chkUseDataDir.IsChecked != null && chkUseDataDir.IsChecked.Value
                            ? txtDataDir.Text
                            : txtDBDir.Text, "notes.pnid");
                // get all notes ids
                var buffer = new string(' ', size);
                while (PNInterop.GetPrivateProfileString(null, null, null, buffer, size, dbPath) == size - 2)
                {
                    // loop until sufficient buffer size
                    size *= 2;
                    buffer = new string(' ', size);
                }
                // section names are delimeted by '\0' character with additional '\0' character at the end
                var names = buffer.ToString(PNStatic.CultureInvariant).Split('\0');
                var sections = names.Where(n => n.Trim().Length > 0);
                // interate through all notes ids
                foreach (var id in sections)
                {
                    // get names of all keys under the specified id
                    size = 1024;
                    buffer = new string(' ', size);
                    while (PNInterop.GetPrivateProfileString(id, null, null, buffer, size, dbPath) == size - 2)
                    {
                        // loop until sufficient buffer size
                        size *= 2;
                        buffer = new string(' ', size);
                    }
                    // key names are delimeted by '\0' character with additional '\0' character at the end
                    names = buffer.ToString(CultureInfo.InvariantCulture).Split('\0');
                    var keys = names.Where(n => n.Trim().Length > 0);
                    var enumerable = keys as string[] ?? keys.ToArray();
                    if (enumerable.Contains("data"))
                    {
                        // only if there is 'data' key
                        var data = new NOTE_DATA();
                        var schedule = new SCHEDULE_TYPE();
                        var relPos = new NOTE_REL_POSITION();
                        var addApp = new ADDITIONAL_NAPP();
                        var creation = new SYSTEMTIME();
                        var deletion = new SYSTEMTIME();
                        var appearance = new NOTE_APPEARANCE();
                        var pin = new NOTE_PIN();
                        var sendrec = new SEND_REC_STATUS();
                        var password = new StringBuilder(256);
                        var tags = new StringBuilder(1024);
                        var links = new StringBuilder(1024);
                        // iterate through all keys
                        foreach (var key in enumerable)
                        {
                            switch (key)
                            {
                                case "data":
                                    data = PNInterop.ReadINIStructure(dbPath, id, key, data);
                                    if (string.IsNullOrEmpty(data.szName))
                                    {
                                        // no note's name found - continue to iterate notes ids
                                        goto _sections_loop;
                                    }
                                    if (data.idGroup == -2 && (chkNoRecycle.IsChecked != null && chkNoRecycle.IsChecked.Value))
                                    {
                                        // do not get note from Recycle bin - continue to iterate notes ids
                                        goto _sections_loop;
                                    }
                                    break;
                                case "schedule":
                                    schedule = PNInterop.ReadINIStructure(dbPath, id, key, schedule);
                                    break;
                                case "rel_position":
                                    relPos = PNInterop.ReadINIStructure(dbPath, id, key, relPos);
                                    break;
                                case "add_appearance":
                                    addApp = PNInterop.ReadINIStructure(dbPath, id, key, addApp);
                                    break;
                                case "creation":
                                    creation = PNInterop.ReadINIStructure(dbPath, id, key, creation);
                                    break;
                                case "appearance":
                                    appearance = PNInterop.ReadINIStructure(dbPath, id, key, appearance);
                                    break;
                                case "pin":
                                    pin = PNInterop.ReadINIStructure(dbPath, id, key, pin);
                                    break;
                                case "send_rec":
                                    sendrec = PNInterop.ReadINIStructure(dbPath, id, key, sendrec);
                                    break;
                                case "deletion":
                                    deletion = PNInterop.ReadINIStructure(dbPath, id, key, deletion);
                                    break;
                                case "lock":
                                    PNInterop.GetPrivateProfileStringByBuilder(id, key, "", password, 256, dbPath);
                                    if (password.Length > 0)
                                    {
                                        // no import for password protected notes - continue to iterate notes ids
                                        goto _sections_loop;
                                    }
                                    break;
                                case "tags":
                                    while (PNInterop.GetPrivateProfileStringByBuilder(id, key, "", tags, tags.Capacity, dbPath) == tags.Capacity - 1)
                                    {
                                        tags.Capacity *= 2;
                                    }
                                    break;
                                case "links":
                                    while (PNInterop.GetPrivateProfileStringByBuilder(id, key, "", links, links.Capacity, dbPath) == tags.Capacity - 1)
                                    {
                                        links.Capacity *= 2;
                                    }
                                    break;
                            }
                        }
                        if (addNewNote(id, data, schedule, relPos, addApp, creation, deletion, appearance, pin, sendrec,
                            tags, links, groupIds,
                            chkKeepInvisible.IsChecked ?? false))
                        {
                            listID.Add(id);
                        }
                    }
                _sections_loop:
                    System.Windows.Forms.Application.DoEvents();
                }
                if (listID.Count > 0)
                {
                    var rtb = new System.Windows.Forms.RichTextBox();
                    var ids = listID.ToArray();
                    foreach (string id in ids)
                    {
                        var src = Path.Combine(txtDataDir.Text, id + ".pnote");
                        if (!File.Exists(src))
                        {
                            listID.Remove(id);
                            continue;
                        }
                        try
                        {
                            rtb.LoadFile(src, System.Windows.Forms.RichTextBoxStreamType.RichText);
                        }
                        catch (ArgumentException aex)
                        {
                            if (aex.Message.Contains("File format is not valid"))
                            {
                                listID.Remove(id);
                                continue;
                            }
                        }
                        var dest = Path.Combine(PNPaths.Instance.DataDir, id + PNStrings.NOTE_EXTENSION);
                        File.Copy(src, dest, true);
                    }

                    //show notes if appropriate check box is unchecked
                    PNStatic.FormMain.LoadNotesByList(listID, !(chkKeepInvisible.IsChecked ?? false));
                }
            }
            catch (Exception ex)
            {
                PNStatic.LogException(ex);
            }
        }
Example #15
0
 public static extern bool SetSystemTime(ref SYSTEMTIME st);