Example #1
0
 /// <summary>
 /// 保存一个查房日志到本地
 /// </summary>
 /// <param name="CheckLog"></param>
 public void SaveCheckLogToLocal(Data.DoctorCheckLog CheckLog)
 {//To do:修改病人的同步标志,标识需同步查房日志
     using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(iDB.DbFile))
     {
         string SqlCheckLog                 = @"Select * From [DoctorCheckLog] Where [DCLID]=?";
         SQLite.SQLiteCommand cmd           = conn.CreateCommand(SqlCheckLog, CheckLog.DCLID);
         Data.DoctorCheckLog  existCheckLog = cmd.ExecuteQuery <DoctorCheckLog>().SingleOrDefault();
         Data.SyncLog         slCheckLog    = new SyncLog()
         {
             TableName  = "[DoctorCheckLog]",
             KeyField   = "DCLID",
             KeyValue   = CheckLog.DCLID,
             ChangeType = "INSERT"
         };
         if (existCheckLog == null)
         {
             conn.Insert(CheckLog);
         }
         else
         {
             conn.Update(CheckLog);
             slCheckLog.ChangeType = "UPDATE";
         }
         SaveSyncLog(conn, slCheckLog);
     }
 }
Example #2
0
        private void SendToSync(int status)
        {
            this.ChangesBusy = true;
            List <DestinationsServer> servers;
            var changes = LogHelper.ReadNotAddedChanges();

            Parallel.ForEach(changes, (change) => {
                if (status == 0)
                {
                    servers = Setting.CurrentSetting.Servers.Where(s => s.IsActive).ToList();
                }
                if (status == 1)
                {
                    servers = GetServer();
                }
                foreach (var server in GetServer())
                {
                    var log             = new SyncLog();
                    log.AddTime         = DateTime.Now;
                    log.SourcePath      = change.FilePath;
                    log.DestinationName = server.Name;
                    log.DestinationPath = Path.GetPathRoot(server.Path) + change.FilePath.Substring(2, change.FilePath.Length - 2);
                    log.DestinationRoot = server.Path;
                    var result          = LogHelper.AddSync(log);
                    if (result)
                    {
                        LogHelper.UpdateChangesStatus(change.Id, 1);
                    }
                }
            });
            this.ChangesBusy = false;
        }
Example #3
0
        private SyncLog deserealizeNameFileLog(string path)
        {
            //1_1_1234124412_14-11-29-013045
            string[] comp = path.Split(new Char[] { '_' });
            SyncLog  log  = null;

            try
            {
                log           = new SyncLog();
                log.client_id = int.Parse(comp[(int)SyncOrdenEsM.index.client_id]);
                if (comp.Length <= 6)
                {
                    log.date_time = FormatDateTime(comp[(int)SyncOrdenEsM.index.date_time].Replace(".csv", ""));
                    log.folio     = comp[(int)SyncOrdenEsM.index.folio];
                }
                else
                {
                    log.date_time = FormatDateTime(comp[(int)SyncOrdenEsM.index.date_time + 2].Replace(".csv", ""));
                    log.folio     = comp[(int)SyncOrdenEsM.index.folio] + "_" +
                                    comp[(int)SyncOrdenEsM.index.folio + 1] + "_" + comp[(int)SyncOrdenEsM.index.folio + 2];
                }
                //log.type = Type(comp[0].Replace("\\rfiddata\\", "")[0]);
                log.type        = Type(comp[0].Replace("\\" + pathFolderName, "")[0]);
                log.user_id     = 1;
                log.description = ContentFile(path);
            }
            catch (Exception exc) { }
            return(log);
        }
 public static void UpdateSyncLog(this SyncLog syncLog, SyncLogViewModel syncLogViewModel)
 {
     syncLog.ID          = syncLogViewModel.ID;
     syncLog.Quantity    = syncLogViewModel.Quantity;
     syncLog.LastTime    = syncLogViewModel.LastTime;
     syncLog.CreatedDate = syncLogViewModel.CreatedDate;
 }
Example #5
0
 public bool SaveAdvice(ObservableCollection <Data.PadAdvice> ListNewAdvice, ref string exMsg)
 {
     using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(iDB.DbFile))
     {
         try
         {
             conn.BeginTransaction();
             foreach (Data.PadAdvice advice in ListNewAdvice)
             {
                 conn.Insert(advice);
                 Data.SyncLog slLog = new SyncLog()
                 {
                     LogID      = Guid.NewGuid().ToString(),
                     TableName  = "[PadAdvice]",
                     KeyField   = "PAID",
                     KeyValue   = advice.PAID,
                     ChangeType = "INSERT",
                     ChangeDate = iCommon.DateNow
                 };
                 conn.Insert(slLog);
             }
             conn.Commit();
         }
         catch (Exception ex)
         {
             exMsg = ex.Message;
             return(false);
         }
     }
     return(true);
 }
    private void RunSync(Func <CancellationToken, Task> sync)
    {
        // Cancel anything that might previously run
        Cancel();

        pnlLog.Visible = true;

        CurrentError = string.Empty;

        btnSyncAll.Enabled            = false;
        btnSyncContentTypes.Enabled   = false;
        btnSyncPages.Enabled          = false;
        btnSyncMediaLibraries.Enabled = false;

        SyncLog.CurrentLog = ctlAsyncLog.EnsureLog();

        var cancellation = _cancellation;

        ctlAsyncLog.RunAsync(
            parameter => Task.Run(async() =>
        {
            try
            {
                await sync(cancellation.Token);
            }
            catch (Exception ex)
            {
                SyncLog.LogException("KenticoKontentPublishing", "UNHANDLEDERROR", ex);
                ctlAsyncLog.ProcessData.Error = ex.Message;
            }
        }).Wait(),
            WindowsIdentity.GetCurrent()
            );
    }
        private void uploadFiles(List <FileItem> filesToUpload)
        {
            this.uploadedBytes.Clear();
            ManualResetEvent[] doneEvents = null;
            int taskMax = filesToUpload.Count;

            doneEvents       = new ManualResetEvent[taskMax];
            this.uploadInfos = new UploadInfo[taskMax];
            for (int taskId = 0; taskId < taskMax; taskId++)
            {
                this.uploadInfos[taskId] = new UploadInfo();
                doneEvents[taskId]       = new ManualResetEvent(false);
                FileUploader uploader = new FileUploader(this.syncSetting, doneEvents[taskId], this, taskId, upctl);
                ThreadPool.QueueUserWorkItem(new WaitCallback(uploader.uploadFile), filesToUpload[taskId]);
            }

            try
            {
                WaitHandle.WaitAll(doneEvents);
                CachedHash.BatchInsertOrUpdate(filesToUpload, localHashDB);
                SyncLog.BatchInsertOrUpdate(filesToUpload, syncLogDB);
            }
            catch (Exception ex)
            {
                Log.Error("wait for job to complete error, " + ex.Message);
            }
        }
Example #8
0
        // Token: 0x06000A1F RID: 2591 RVA: 0x000232F4 File Offset: 0x000214F4
        private ExTraceGlobals()
        {
            SyncLogConfiguration syncLogConfiguration = LogConfiguration.CreateSyncLogConfiguration();
            SyncLog syncLog = new SyncLog(syncLogConfiguration);

            ExTraceGlobals.syncLogSession = syncLog.OpenGlobalSession();
        }
Example #9
0
        public static void UpdateSyncStatus(SyncLog log)
        {
            var newValues = new Dictionary <string, object>();

            newValues.Add("SyncTime", DateTime.Now);
            newValues.Add("SyncStatus", log.SyncStatus);
            newValues.Add("Message", log.Message);
            mongo.UpdateMany <SyncLog>("SyncLog", c => c.Id == log.Id, newValues);
        }
Example #10
0
        public void StartSynchronization(SyncLog log)
        {
            if (!SfdcConfig.SyncLogsEnable)
            {
                return;
            }

            _logObject     = log;
            _isSyncStarted = true;
        }
        private void importFrom1C()
        {
            var    clock         = new Stopwatch();
            var    toDatabase    = new SqlConnection(_sqlConnectionString).Database;
            var    isSuccessfull = false;
            string syncType;
            var    syncLog = new SyncLog()
            {
                ID   = Guid.NewGuid(),
                From = _pathDB,
                To   = toDatabase
            };

            adaptor1C = new comClient1Cv77Adatpor(_userName, _password, _pathDB);
            if (adaptor1C.Login())
            {
                syncLog.Timestamp = DateTime.Now;
                clock.Start();

                if (Config.SyncDatabases.lastDays.HasValue)
                {
                    syncType = "Particular";
                    ParticularImportDataFrom1Cv77 data = new ParticularImportDataFrom1Cv77(adaptor1C, adaptorSql);
                    if (data.Sync())
                    {
                        isSuccessfull = true;
                        Logger.logger.Info(string.Format("Particular Sync OK 1C to MSSQL {0} ", _pathDB));
                    }
                }
                else
                {
                    syncType = "Full";
                    ImportSchemaFrom1Cv77 schema = new ImportSchemaFrom1Cv77(adaptor1C, adaptorSql);
                    if (schema.Sync())
                    {
                        ImportDataFrom1Cv77 data = new ImportDataFrom1Cv77(adaptor1C, adaptorSql);
                        if (data.Sync())
                        {
                            isSuccessfull = true;
                            Logger.logger.Info(string.Format("Full Sync OK 1C to MSSQL {0} ", _pathDB));
                        }
                    }
                }

                clock.Stop();

                syncLog.Description   = string.Format("{0} Sync from 1C ({1}) to MSSQL(Database={2})", syncType, _pathDB, toDatabase);
                syncLog.IsSuccessfull = isSuccessfull;
                syncLog.DurationInSec = clock.ElapsedMilliseconds / 1000;

                SyncDB.InsertSyncLog(syncLog);
            }
        }
        /// <summary>
        ///
        /// </summary>
        public void SetSyncNow()
        {
            var sl = siaqodb.Cast <SyncLog>().FirstOrDefault();

            if (sl == null)
            {
                sl = new SyncLog();
            }

            sl.LastSync = DateTime.Now;

            Save <SyncLog>(sl);
        }
Example #13
0
        private void createOptionalDB()
        {
            //check jobs db
            if (!File.Exists(this.jobsDbPath))
            {
                try
                {
                    SyncRecord.CreateSyncRecordDB(this.jobsDbPath);
                }
                catch (Exception ex)
                {
                    Log.Error(string.Format("create sync record db for job {0} failed due to {1}", this.jobId, ex.Message));
                }
            }
            else
            {
                DateTime syncDateTime = DateTime.Now;
                try
                {
                    SyncRecord.InsertRecord(this.jobId, syncDateTime, this.syncSetting, this.jobsDbPath);
                }
                catch (Exception ex)
                {
                    Log.Error(string.Format("record sync job failed for job {0} due to {1}", this.jobId, ex.Message));
                }
            }

            if (!File.Exists(this.localHashDBPath))
            {
                try
                {
                    CachedHash.CreateCachedHashDB(this.localHashDBPath);
                }
                catch (Exception ex)
                {
                    Log.Error("create cached hash db failed, " + ex.Message);
                }
            }

            if (!File.Exists(this.syncLogDBPath))
            {
                try
                {
                    SyncLog.CreateSyncLogDB(this.syncLogDBPath);
                }
                catch (Exception ex)
                {
                    Log.Error(string.Format("create sync log db for job {0} failed due to {1}", this.jobId, ex.Message));
                }
            }
        }
Example #14
0
        public static bool AddSync(SyncLog log)
        {
            try
            {
                var isexist = mongo.GetData <SyncLog>("SyncLog", l => l.SourcePath == log.SourcePath && l.DestinationPath == log.DestinationPath && l.SyncStatus == 0);
                if (isexist.Count() == 0)
                {
                    mongo.AddOne <SyncLog>("SyncLog", log);
                }

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Example #15
0
        //private JsonArray buildMessages(String path)
        //{
        //    var messages = new JsonArray();
        //    String nameFileMessage = path.Replace("iepcs", "message").Replace("oepcs", "message");
        //    using (CsvFileReader reader = new CsvFileReader(nameFileMessage))
        //    {
        //        CsvRow rowcsv = new CsvRow();
        //        while (reader.ReadRow(rowcsv))
        //        {
        //            messages.Add(rowcsv[0]);
        //        }
        //    }
        //    return messages;
        //}

        //private JsonObject LogToJson(SyncLog log)
        //{
        //    JsonObject json = new JsonObject();
        //    json.Add("client_id", log.client_id);
        //    json.Add("created_at", log.date_time);
        //    json.Add("updated_at", log.date_time);
        //    json.Add("user_id", log.user_id);
        //    json.Add("description", log.description);
        //    return json;
        //}

        private SyncLog deserealizeNameFileLog(string path)
        {
            //1_1_1234124412_14-11-29-013045
            string[] comp = path.Split(new Char[] { '_' });
            SyncLog  log  = null;

            try
            {
                log             = new SyncLog();
                log.client_id   = pclient_id;
                log.date_time   = FormatDateTime(comp[(int)SyncOrdenEsM.index.date_time].Replace(".csv", ""));
                log.user_id     = 1;
                log.description = ContentFile(path);
            }
            catch (Exception exc) { }
            return(log);
        }
Example #16
0
        public void DeleteCheckLog(Data.DoctorCheckLog CheckLog)
        {
            using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(iDB.DbFile))
            {
                string SqlCheckLog       = @"Delete From [DoctorCheckLog] Where [DCLID]=?";
                SQLite.SQLiteCommand cmd = conn.CreateCommand(SqlCheckLog, CheckLog.DCLID);
                cmd.ExecuteNonQuery();
                Data.SyncLog slCheckLog = new SyncLog()
                {
                    TableName  = "[DoctorCheckLog]",
                    KeyField   = "DCLID",
                    KeyValue   = CheckLog.DCLID,
                    ChangeType = "DELETE"
                };

                SaveSyncLog(conn, slCheckLog);
            }
        }
Example #17
0
        private void LogSyncException(Exception e, Guid pk, string type, string message)
        {
            this.logger.LogError(e, message);

            var syncEx = new SyncLog()
            {
                PaymentEntityPK  = pk,
                EntityType       = type,
                ExceptionMessage = message,
                StackTrace       = e.ToString(),
                CreatedOn        = DateTime.Now
            };

            if (type == nameof(Transaction))
            {
                syncEx.TransactionId = pk;
            }

            this.context.Add(syncEx);
        }
Example #18
0
        private void SaveLog(SyncLog log)
        {
            RegisterSoup();

            var record = JObject.FromObject(log, JsonSerializer.Create(CustomJsonSerializerSettings.Instance.Settings));

            record[SyncManager.Local] = true;

            var info = log.GetType().GetTypeInfo().GetCustomAttributes()
                       .SingleOrDefault(t => t is JsonObjectAttribute) as JsonObjectAttribute;

            if (info != null)
            {
                record[Constants.SobjectType] = string.Format(info.Title, SfdcConfig.CustomerPrefix);
            }

            record[SyncManager.LocallyCreated] = true;
            record[SyncManager.LocallyUpdated] = false;
            record[SyncManager.LocallyUpdated] = false;
            record[Constants.Id] = Guid.NewGuid();
            Store.Upsert(SoupName, record, Constants.Id, false);
        }
Example #19
0
        public void StartSynchronization(SynchronizationMode syncType)
        {
            if (DsaSyncLog.Instance.IsSyncStarted() || !SfdcConfig.SyncLogsEnable)
            {
                return;
            }

            var account           = AccountManager.GetAccount();
            var deviceInfo        = new EasClientDeviceInformation();
            var connectionProfile = NetworkInformation.GetInternetConnectionProfile();
            var version           = Package.Current.Id.Version;
            var logObject         = new SyncLog
            {
                AppVersion     = $"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}",
                DeviceType     = deviceInfo.SystemManufacturer + deviceInfo.SystemProductName,
                ConnectionType = GetConnectionType(connectionProfile),
                SyncType       = GetSyncType(syncType),
                StartTime      = DateTime.UtcNow,
                Username       = account.UserName
            };

            DsaSyncLog.Instance.StartSynchronization(logObject);
        }
Example #20
0
        public static DayCarePL.ResultStatus Save(string UserId, string DateTime)
        {
            clConnection.DoConnection();
            DayCareDataContext db = new DayCareDataContext();

            DayCarePL.ResultStatus objResultStatus = new DayCarePL.ResultStatus();
            SyncLog DBSyncLog = null;

            try
            {
                DBSyncLog          = new SyncLog();
                DBSyncLog.Id       = Guid.NewGuid();
                DBSyncLog.UserId   = new Guid(UserId);
                DBSyncLog.Datetime = Convert.ToDateTime(DateTime);
                db.SyncLogs.InsertOnSubmit(DBSyncLog);
                db.SubmitChanges();
                objResultStatus.Status = "true";
            }
            catch
            {
                objResultStatus.Status = "false";
            }
            return(objResultStatus);
        }
Example #21
0
        public HttpResponseMessage Create(HttpRequestMessage request, SyncLogViewModel syncLogViewModel)
        {
            return(CreateHttpResponse(request, () =>
            {
                HttpResponseMessage response = null;
                if (!ModelState.IsValid)
                {
                    response = request.CreateResponse(HttpStatusCode.BadRequest, ModelState);
                }
                else
                {
                    var newSyncLog = new SyncLog();
                    newSyncLog.UpdateSyncLog(syncLogViewModel);
                    newSyncLog.CreatedDate = DateTime.Now;
                    _syncLogService.Add(newSyncLog);
                    _syncLogService.Save();

                    var responseData = Mapper.Map <SyncLog, SyncLogViewModel>(newSyncLog);
                    response = request.CreateResponse(HttpStatusCode.Created, responseData);
                }

                return response;
            }));
        }
Example #22
0
 public SyncLog Add(SyncLog syncLog)
 {
     return(_syncLogRepository.Add(syncLog));
 }
Example #23
0
        /// <summary>
        /// Synchronise Async
        /// </summary>
        /// <returns>The async.</returns>
        /// <param name="subscriberId">Username.</param>
        /// <param name="password">Password.</param>
        /// <param name="url">URL.</param>
        async Task <SyncResult> SynchroniseAsync(Repository repository, string subscriberId, string password, string url, MobileDevice device)
        {
            var deviceManager = ServiceLocator.Current.GetInstance <IDeviceManager>();

            device.UniqueDeviceID = deviceManager.GetUniqueDeviceId();

            deviceManager.LogEvent($"Sync In Progress At: {DateTime.Now}");

            // clear sync logs
            _syncedDockets.Clear();
            _syncedNonDeliveries.Clear();

            var profile = repository.Profiles.FirstOrDefault();

            var syncLog = new SyncLog
            {
                SubscriberID = subscriberId,
                AppVersion   = AppInfo.VersionString,
                Build        = AppInfo.BuildString,
                DeviceID     = device.UniqueDeviceID,
                Model        = DeviceInfo.Model,
                Version      = DeviceInfo.VersionString,
                Manufacturer = DeviceInfo.Manufacturer
            };

            var request = new UploadRequest
            {
                MobileDevice = device,
                SyncLog      = syncLog
            };

            // get profile data
            if (profile != null)
            {
                // get runs
                request.Runs = repository.Runs
                               .Where(x => x.Timestamp >= profile.TimeStamp).ToList();

                // get calls
                request.Calls = repository.Calls
                                .Where(x => x.Timestamp >= profile.TimeStamp).ToList();

                var dockets = repository.DeliveryDockets
                              .Where(x => x.Committed && !x.Synced)
                              .ToList();

                dockets.ForEach(docket =>
                {
                    docket.DeliveryDocketItems = repository.DeliveryDocketItems
                                                 .Where(x => x.DeliveryDocketID == docket.DocketID)
                                                 .ToList();
                });

                // get dockets
                request.DeliveryDockets = dockets;

                _syncedDockets = request.DeliveryDockets
                                 .Select(x => x.DocketID)
                                 .ToList();

                // get non deliveries
                request.NonDeliveries = repository.NonDeliveries
                                        .ToList();

                _syncedNonDeliveries = request.NonDeliveries
                                       .Select(x => x.Id)
                                       .ToList();

                // get driver stock
                request.DriverStock = repository.DriverStock
                                      .ToList();

                // get completed orders
                request.CompletedOrders = repository.Orders
                                          .Where(x => x.Completed)
                                          .Select(x => x.OrderNumber)
                                          .ToList();

                request.Orders = repository.Orders
                                 .Where(x => x.Completed).ToList();

                if (request.DeliveryDockets.Any())
                {
                    request.MobileDevice.LatestDocketID = request.DeliveryDockets
                                                          .OrderByDescending(x => x.DateModifiedDate)
                                                          .First().DocketID;
                }

                request.MobileDevice.SyncDate = DateTime.Now.ToLocalTime();
            }

            // serialize sync request
            var content = SerializeSyncRequest(request);

            // set the authorization header
            SetAuthorizationHeader(subscriberId, password);

            SyncResult syncResult;

            try
            {
                using (var response = await _client.PostAsync(url, content).ConfigureAwait(false))
                    using (var stream = await response.Content.ReadAsStreamAsync())
                        using (var reader = new StreamReader(stream))
                            using (var json = new JsonTextReader(reader))
                            {
                                var dict = new Dictionary <string, string>
                                {
                                    { "User", subscriberId },
                                    { "Url", url },
                                    { "Status Code", response.StatusCode.ToString() },
                                    { "Reason Phrase", response.ReasonPhrase }
                                };

                                syncResult = new SyncResult
                                {
                                    IsSuccessStatusCode = response.IsSuccessStatusCode,
                                    ReasonPhrase        = response.ReasonPhrase,
                                    StatusCode          = response.StatusCode
                                };

                                deviceManager.LogEvent($"Sync Completed At: {DateTime.Now} With Status: {response.StatusCode}");

                                if (syncResult.IsSuccessStatusCode)
                                {
                                    syncResult.DownloadResponse = _serializer
                                                                  .Deserialize <DownloadResponse>(json);

                                    // store the password
                                    syncResult.Password = password;

                                    Merge(syncResult);
                                }
                            }


                //var response = await _client.PostAsync(url, content).ConfigureAwait(false);

                //var dict = new Dictionary<string, string>
                //{
                //    { "User", subscriberId },
                //    { "Url", url },
                //    { "Status Code", response.StatusCode.ToString() },
                //    { "Reason Phrase", response.ReasonPhrase }
                //};

                //deviceManager.LogEvent("SynchroniseAsync", dict);

                //syncResult = new SyncResult
                //{
                //    IsSuccessStatusCode = response.IsSuccessStatusCode,
                //    ReasonPhrase = response.ReasonPhrase,
                //    StatusCode = response.StatusCode
                //};

                //if (syncResult.IsSuccessStatusCode)
                //{
                //    using (var stream = await response.Content.ReadAsStreamAsync())
                //    using (var reader = new StreamReader(stream))
                //    using (var json = new JsonTextReader(reader))
                //    {
                //        syncResult.DownloadResponse = _serializer
                //            .Deserialize<DownloadResponse>(json);

                //        // store the password
                //        syncResult.Password = password;

                //        Merge(syncResult);

                //    }
                //}

                return(syncResult);
            }
            catch (Exception exception)
            {
                if (exception.InnerException != null)
                {
                    System.Diagnostics.Debug.WriteLine($"EXCEPTION: {exception.InnerException.Message}");
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"EXCEPTION: {exception.Message}");
                }

                deviceManager.LogException(exception);

                syncResult = new SyncResult()
                {
                    IsSuccessStatusCode = false,
                    StatusCode          = HttpStatusCode.RequestTimeout
                };

                return(syncResult);
            }
        }
 public SyncLogViewModel(SyncLog syncLog) =>