public Changeset GetParentCommit(Changeset commit)
        {
            var command = new LogCommand().WithRevision(new RevSpec("{0}^".Fmt(commit.Hash))).WithIncludePathActions();
            var changesets = _repository.Log(command);
			var changeset = changesets.FirstOrDefault();
            return changeset;
        }
        public void Log_WithUnknownArgument_ThrowsMercurialExecutionException()
        {
            Repo.Init();

            var command = new LogCommand();
            command.AdditionalArguments.Add("--dummyargument");

            Assert.Throws<MercurialExecutionException>(() => Repo.Execute(command));
        }
        public IEnumerable<RevisionRange> GetFromTillHead(DateTime from, int pageSize)
        {
	        var command = new LogCommand().WithAdditionalArgument("-d >{0:yyyy-MM-dd}".Fmt(from));
            var pages = _repository.Log(command)
				.Where(ch => ch.Timestamp >= from)
				.OrderBy(ch => ch.Timestamp)
				.ToArray()
				.Split(pageSize);

		    var result = pages.Select(page => new RevisionRange(page.First().ToRevisionId(), page.Last().ToRevisionId()));

		    return result;
		}
        public IEnumerable<RevisionRange> GetAfterTillHead(RevisionId revisionId, int pageSize)
        {
	        var revSpec = new RevSpec(revisionId.Value);
			var command = new LogCommand().WithRevision(RevSpec.From(revSpec) && !new RevSpec(revisionId.Value));
            var pages = _repository.Log(command)
                .OrderBy(ch => ch.Timestamp)
                .ToArray()
                .Split(pageSize);

            var result = pages.Select(page => new RevisionRange(page.First().ToRevisionId(), page.Last().ToRevisionId()));

            return result;
        }
        public IEnumerable<RevisionRange> GetFromAndBefore(RevisionId fromRevision, RevisionId toRevision, int pageSize)
        {
            var command = new LogCommand();
            var pages = _repository.Log(command)
                .Where(ch => (ch.Timestamp >= fromRevision.Time.Value && ch.Timestamp <= toRevision.Time.Value))
                .OrderBy(ch => ch.Timestamp)
                .ToArray()
                .Split(pageSize);

            var result = pages.Select(page => new RevisionRange(page.First().ToRevisionId(), page.Last().ToRevisionId()));

            return result;
        }
예제 #6
0
 public void AddEnvironmentVariables()
 {
     var localRoot = suiteRoot as LocalFileSystemDirectory;
     if (localRoot != null)
     {
         var logCommand = new LogCommand().WithRevision(RevSpec.WorkingDirectoryParent);
         Client.Execute(localRoot.AbsolutePath, logCommand);
         var changeSet = logCommand.Result.First();
         string revNo = changeSet.RevisionNumber.ToString(CultureInfo.InvariantCulture);
         log.DebugFormat("Mercurial current revision number is {0}", revNo);
         environmentVariableContext.Define("HG_REVNO", revNo);
     }
 }
        public IEnumerable<RevisionRange> GetFromAndBefore(RevisionId fromRevision, RevisionId toRevision, int pageSize)
        {
			var from = new RevSpec(fromRevision.Value);
			var to = new RevSpec(toRevision.Value);
	        var command = new LogCommand().WithRevision(RevSpec.Range(from, to));
            var pages = _repository.Log(command)
                .OrderBy(ch => ch.Timestamp)
                .ToArray()
                .Split(pageSize);

            var result = pages.Select(page => new RevisionRange(page.First().ToRevisionId(), page.Last().ToRevisionId()));

            return result;
        }
 /// <summary>
 /// A thread safe logger
 /// </summary>
 /// <param name="m"></param>
 public static void Log(LogCommand m)
 {
     if (!IsMainThread)
     {
         lock (syncRoot)
         {
             PendingLogs.Add(m);
         }
     }
     else
     {
         Write(m);
     }
 }
        public IEnumerable<RevisionRange> GetFromAndBefore(RevisionId fromRevision, RevisionId toRevision, int pageSize)
        {
	        var command = new LogCommand();
			if (string.IsNullOrEmpty(fromRevision.Value))
			{
				if (string.IsNullOrEmpty(toRevision.Value))
				{
					command = command.WithAdditionalArgument("-d {0:yyyy-MM-dd} to {1:yyyy-MM-dd}".Fmt(fromRevision.Time.Value, toRevision.Time.Value));
				}
				else
				{
					var to = new RevSpec(toRevision.Value);
					command = command.WithRevision(RevSpec.To(to));
					command = command.WithAdditionalArgument("-d >{0:yyyy-MM-dd}".Fmt(fromRevision.Time.Value));
				}
			}
			else
			{
				var from = new RevSpec(fromRevision.Value);
				if (string.IsNullOrEmpty(toRevision.Value))
				{
					command = command.WithAdditionalArgument("-d <{0:yyyy-MM-dd}".Fmt(toRevision.Time.Value));
					command = command.WithRevision(RevSpec.From(from));
				}
				else
				{
					var to = new RevSpec(toRevision.Value);
					command = command.WithRevision(RevSpec.Range(from, to));
				}
			}

            var pages = _repository.Log(command)
                .OrderBy(ch => ch.Timestamp)
                .ToArray()
                .Split(pageSize);

            var result = pages.Select(page => new RevisionRange(page.First().ToRevisionId(), page.Last().ToRevisionId()));

            return result;
        }
        public void Log_WithUnknownArgument_ThrowsMercurialExecutionExceptionThatMentionesArgument()
        {
            Repo.Init();

            var command = new LogCommand();
            command.AdditionalArguments.Add("--dummyargument");

            try
            {
                Repo.Execute(command);
            }
            catch (MercurialExecutionException ex)
            {
                Assert.That(ex.Message, Is.StringContaining("hg log: option --dummyargument not recognized"));
                return;
            }
            catch (Exception ex)
            {
                Assert.Fail(string.Format(CultureInfo.InvariantCulture, "Log with unknown argument should not have thrown {0}", ex.GetType().Name));
            }
            Assert.Fail("Log with unknown argument should have thrown MercurialExecutionException");
        }
예제 #11
0
        public async Task <IHttpActionResult> GetLeads(SearchLeadSimple leadSearcher)
        {
            //Log the request
            var logCommand = new LogCommand
            {
                User            = User,
                LoggingInstance = _loggingInstance,
                LogMessage      = $"LeadController.GetLead Starting input parameter LeadSearcher = {JsonConvert.SerializeObject(leadSearcher)}"
            };

            _logHandler.HandleLog(logCommand);

            //Await the response
            var results = await _leadService.GetLead(leadSearcher, logCommand);

            //Log the response
            logCommand.LogMessage =
                $"LeadController.GetLead completed. Output value = {JsonConvert.SerializeObject(results.Entity)}";
            _logHandler.HandleLog(logCommand);

            //Return the results
            return(ReturnFormattedResults(results));
        }
예제 #12
0
        public void Log_WithUnknownArgument_ThrowsMercurialExecutionExceptionThatMentionesArgument()
        {
            Repo.Init();

            var command = new LogCommand();

            command.AdditionalArguments.Add("--dummyargument");

            try
            {
                Repo.Execute(command);
            }
            catch (MercurialExecutionException ex)
            {
                Assert.That(ex.Message, Contains.Substring("hg log: option --dummyargument not recognized"));
                return;
            }
            catch (Exception ex)
            {
                Assert.Fail(string.Format(CultureInfo.InvariantCulture, "Log with unknown argument should not have thrown {0}", ex.GetType().Name));
            }
            Assert.Fail("Log with unknown argument should have thrown MercurialExecutionException");
        }
예제 #13
0
        public async Task <int> UpdateAccount(Account account, LogCommand logCommand)
        {
            //Logging Helper for Method
            const string methodName = "UpdateAccount";

            //Query Used by Dapper
            var query =
                $" update  from {AccountTable} " +
                " set [AccountStatusGuid] = @AccountStatusGuid " +
                ", JobId = @JobId " +
                " where SFAccountID = @SFAccountID  ";

            if (account.AccountStatusGuid == Guid.Empty)
            {
                throw new Exception("Missing Fields");
            }

            //Log the input
            logCommand.LogMessage = $"{Repository}.{methodName} Starting input parameter account={JsonConvert.SerializeObject(account)}" + Environment.NewLine +
                                    $"Query: {query}";
            _logHandler.HandleLog(logCommand);


            using (var connection = _connectionFactory.GetConnection)
            {
                //Await the response
                var Records = await connection.ExecuteAsync(query, account);

                connection.Close();

                //Log the output
                logCommand.LogMessage = $"{Repository}.{methodName} completed";
                _logHandler.HandleLog(logCommand);

                return(Records);
            }
        }
예제 #14
0
        public async Task <ERMSCustomer> GetERMSCustomer(Guid CustomerGuid, LogCommand logCommand)
        {
            try
            {
                //Logging Helper for Method
                const string methodName = "GetAccountFromGuid";

                //Query Used by Dapper
                var query =
                    $" select * from {ERMSCustomerTable} " +
                    " where CustomerGuid = @CustomerGuid ";

                //Log the input
                logCommand.LogMessage = $"{Repository}.{methodName} Starting input parameters: CustomerGuid={CustomerGuid}" + Environment.NewLine +
                                        $"Query: {query}";
                _logHandler.HandleLog(logCommand);

                using (var connection = _connectionFactory.GetConnection)
                {
                    //Await the response
                    var ermsCustomer = await connection.QueryFirstOrDefaultAsync <ERMSCustomer>(query, new { CustomerGuid });

                    connection.Close();

                    //Log the output
                    logCommand.LogMessage = $"{Repository}.{methodName} completed";
                    _logHandler.HandleLog(logCommand);

                    return(ermsCustomer);
                }
            }
            catch
            {
                return(new ERMSCustomer());
            }
        }
예제 #15
0
        /// <summary>
        /// Check user rights and execute command with logging
        /// </summary>
        /// <param name="commandType"></param>
        /// <param name="user"></param>
        /// <param name="CommandExecutor"></param>
        /// <returns></returns>
        public virtual LogCommand ExecuteNewCommand(CommandTypes commandType, FaceRecognitionUser user, Func <CommandTypes, CommandResults> CommandExecutor = null)
        {
            var command = new LogCommand(commandType);

            command.StartCommandDate = DateTime.UtcNow;
            LogCommandDAL.Add(command);

            if (!IsExecutionAllowed(user))
            {
                command.CommandResult = CommandResults.Fail;
                return(command);
            }

            if (CommandExecutor == null)
            {
                command.FinishCommandDate = DateTime.UtcNow;
                command.CommandResult     = CommandResults.Undefined;
                LogCommandDAL.Update(command);
                return(command);
            }

            if (command.CommandType == CommandTypes.DoNothingLogOnly)
            {
                command.FinishCommandDate = DateTime.UtcNow;
                command.CommandResult     = CommandResults.Success;
                LogCommandDAL.Update(command);
                return(command);
            }

            var result = CommandExecutor(commandType);

            command.CommandResult     = result;
            command.FinishCommandDate = DateTime.UtcNow;
            LogCommandDAL.Update(command);
            return(command);
        }
예제 #16
0
        public async Task <IEnumerable <Lead> > GetLeadByCustomerGuidAsync(Guid customerGuid, LogCommand logCommand)
        {
            //Logging Helper for Method
            const string methodName = "GetLeadByCustomerGuidAsync";

            //Query Used by Dapper
            var query = QueryResources.LeadQueries.ResourceManager.GetString("GetLeadByCustomerGuid");

            //Log the input
            logCommand.LogMessage = $"{Repository}.{methodName} Starting input parameter customerGuid={customerGuid}" + Environment.NewLine + $"Query: {query}";
            _logHandler.HandleLog(logCommand);


            using (var connection = _connectionFactory.GetConnection)
            {
                //Await the response
                var lead = await connection.QueryAsync <Lead>(query, new { customerGuid });

                connection.Close();

                //Log the output
                logCommand.LogMessage = $"{Repository}.{methodName} completed";
                _logHandler.HandleLog(logCommand);

                return(lead);
            }
        }
예제 #17
0
        public void sendCommand(LogCommand logCommand)
        {
            string message = JsonConvert.SerializeObject(logCommand);

            sendMessage(message);
        }
예제 #18
0
        private void LogModifications(DBLoggingAttribute LogAttribute, LogCommand Command)
        {
            Type            objectType = typeof(T);
            FieldInfo       IDproperty = objectType.GetField("_IDproperty", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
            PropertyInfo    IDField    = objectType.GetProperty(IDproperty.GetValue(null).ToString());
            List <LogValue> _LogValues = new List <LogValue>();

            if (Command == LogCommand.Save)
            {
                if (_initial == null)
                {
                    Command = LogCommand.Insert;
                }
                else
                if (Convert.ToInt64(IDField.GetValue(_initial, null)) == 0)
                {
                    Command = LogCommand.Insert;
                }
                else
                {
                    Command = LogCommand.Modify;
                }
            }

            LogEntry.TableName = "LogEntry_" + Assembly.GetEntryAssembly().GetName().Name;
            LogValue.TableName = "LogValue_" + Assembly.GetEntryAssembly().GetName().Name;

            foreach (PropertyInfo p in objectType.GetProperties())
            {
                bool _LogProperty = false;
                IList <BaseLogAttribute> CustomLogAttributes = p.GetCustomAttributes(typeof(BaseLogAttribute), true).Cast <BaseLogAttribute>().ToList();

                string OldValue = string.Empty;
                string NewValue = string.Empty;
                if (Command == LogCommand.Modify || Command == LogCommand.Delete)
                {
                    if (p.GetValue(_initial, null) != null)
                    {
                        switch (p.PropertyType.ToString())
                        {
                        case "System.DateTime":
                            if ((DateTime)p.GetValue(_initial, null) != DateTime.MinValue)
                            {
                                OldValue = ((DateTime)p.GetValue(_initial, null)).ToString("dd/MM/yyyy");
                            }
                            break;

                        case "System.TimeSpan":
                            OldValue = ((TimeSpan)p.GetValue(_initial, null)).Hours.ToString("00") + "h" + ((TimeSpan)p.GetValue(_initial, null)).Minutes.ToString("00");
                            break;

                        case "System.Decimal":
                            OldValue = ((decimal)p.GetValue(_initial, null)).ToString("0.00");
                            break;

                        case "System.Boolean":
                            if ((bool)p.GetValue(_initial, null))
                            {
                                OldValue = "X";
                            }
                            break;

                        default:
                            OldValue = p.GetValue(_initial, null).ToString();
                            break;
                        }
                    }
                }

                if (Command == LogCommand.Modify || Command == LogCommand.Insert)
                {
                    if (p.GetValue(this, null) != null)
                    {
                        switch (p.PropertyType.ToString())
                        {
                        case "System.DateTime":
                            if ((DateTime)p.GetValue(this, null) != DateTime.MinValue)
                            {
                                NewValue = ((DateTime)p.GetValue(this, null)).ToString("dd/MM/yyyy");
                            }
                            break;

                        case "System.TimeSpan":
                            NewValue = ((TimeSpan)p.GetValue(this, null)).Hours.ToString("00") + "h" + ((TimeSpan)p.GetValue(this, null)).Minutes.ToString("00");
                            break;

                        case "System.Decimal":
                            NewValue = ((decimal)p.GetValue(this, null)).ToString("0.00");
                            break;

                        case "System.Boolean":
                            if ((bool)p.GetValue(this, null))
                            {
                                NewValue = "X";
                            }
                            break;

                        default:
                            NewValue = p.GetValue(this, null).ToString();
                            break;
                        }
                    }
                }

                if (CustomLogAttributes.Count != 0)
                {
                    foreach (BaseLogAttribute CLA in CustomLogAttributes)
                    {
                        if (CLA is LogAttributes)
                        {
                            if (((LogAttributes)CLA).LogMe)
                            {
                                if (Command == LogCommand.Delete && ((LogAttributes)CLA).OnDelete)
                                {
                                    _LogProperty = true;
                                }
                                if (Command == LogCommand.Insert && ((LogAttributes)CLA).OnNew)
                                {
                                    _LogProperty = true;
                                }
                                if (Command == LogCommand.Modify && ((LogAttributes)CLA).OnEdit)
                                {
                                    _LogProperty = true;
                                }

                                if (((LogAttributes)CLA).QueryValue != "")
                                {
                                    if (OldValue != null && OldValue != "")
                                    {
                                        OldValue = (String)SynapseCore.Database.DBFunction.ExecuteScalarQuery(((LogAttributes)CLA).QueryValue + OldValue);
                                    }
                                    if (NewValue != null && NewValue != "")
                                    {
                                        NewValue = (String)SynapseCore.Database.DBFunction.ExecuteScalarQuery(((LogAttributes)CLA).QueryValue + NewValue);
                                    }
                                    if (OldValue == null)
                                    {
                                        OldValue = "";
                                    }
                                    if (NewValue == null)
                                    {
                                        NewValue = "";
                                    }
                                }
                            }
                        }
                        if (CLA is LogEntryAttributeValue)
                        {
                            if (this.LogEntryValue == null)
                            {
                                if (Command == LogCommand.Delete)
                                {
                                    this.LogEntryValue = OldValue;
                                }
                                else
                                {
                                    this.LogEntryValue = NewValue;
                                }
                            }
                            //_LogProperty = true;
                        }
                        if (CLA is LogEntryAttributeKey)
                        {
                            if (this.LogEntryKey == null)
                            {
                                this.LogEntryKey = NewValue;
                            }

                            //_LogProperty = true;
                        }
                    }
                }
                else
                {
                    if (p.Name != "LogEntryKey" && p.Name != "LogEntryValue" && p.Name != "IsDirty" && p.Name != "InitialValue")
                    {
                        _LogProperty = true;
                    }
                }

                if ((OldValue != NewValue && _LogProperty) || (Command == LogCommand.Delete && _LogProperty))
                {
                    LogValue _LogValue = new LogValue();
                    _LogValue.FIELD     = LogAttribute.EntityName + "." + p.Name;
                    _LogValue.OLD_VALUE = OldValue;
                    _LogValue.NEW_VALUE = NewValue;
                    _LogValues.Add(_LogValue);
                }
            }
            if (_LogValues.Count > 0)
            {
                try
                {
                    LogEntry _LogEntry = new LogEntry();

                    switch (Command)
                    {
                    case LogCommand.Delete:
                        _LogEntry.ACTION_CODE = "DELETE";
                        break;

                    case LogCommand.Insert:
                        _LogEntry.ACTION_CODE = "INSERT";
                        break;

                    case LogCommand.Modify:
                        _LogEntry.ACTION_CODE = "MODIFY";
                        break;
                    }

                    _LogEntry.USERID       = SynapseForm.FormUser.UserID;
                    _LogEntry.TIMESTAMP    = DateTime.Now;
                    _LogEntry.OBJECT_NAME  = LogAttribute.EntityName;
                    _LogEntry.OBJECT_VALUE = this.LogEntryValue;
                    _LogEntry.LOGKEY       = this.LogEntryKey;
                    _LogEntry.save();

                    try
                    {
                        foreach (LogValue lv in _LogValues)
                        {
                            lv.FK_LOGENTRY = _LogEntry.ID;
                        }
                        _LogValues.SaveCollection();
                    }
                    // TODO: Catch more specific exception
                    catch (Exception)
                    {
                        // TODO: Handle exception (e.g. log)
                    }
                }
                // TODO: Catch more specific exception
                catch (Exception)
                {
                    // TODO: Handle exception (e.g. log)
                }
            }
        }
예제 #19
0
        /// <summary>
        /// Produce the report
        /// Alternate interface for when we are given a server cooection
        /// This is needed for the SharpCvsLib command line client
        /// </summary>
        public LogReport Run(ICommandConnection connection)
        {
            // read Root and Repository from local directory
            if (null == this.cvsRoot)
            {
                Manager manager = new Manager(localDirectory);
                Root    root    = (Root)manager.FetchSingle(localDirectory,
                                                            Factory.FileType.Root);

                this.cvsRoot = new CvsRoot(root.FileContents);
            }

            if (null == workingDirectory)
            {
                Manager    manager    = new Manager(localDirectory);
                Repository repository = (Repository)manager.FetchSingle(localDirectory,
                                                                        Factory.FileType.Repository);

                this.workingDirectory = new WorkingDirectory(cvsRoot,
                                                             localDirectory,
                                                             repository.FileContents);
            }

            ILogCommand command;

            // Recursively add all cvs folders/files under the localDirectory
            System.Console.WriteLine("GNE workingDirectory.WorkingPath = {0}", workingDirectory.WorkingPath);
            System.Console.WriteLine("GNE localDirectory: {0}", localDirectory);
            //           if (Directory.Exists(workingDirectory.WorkingPath)) {
            if (Directory.Exists(localDirectory) && File.Exists(Path.Combine(localDirectory, "Repository")))
            {
                workingDirectory.FoldersToUpdate = FetchFiles(localDirectory);
                command =
                    new LogCommand(workingDirectory, this.workingDirectory.ModuleName, null);
            }
            else
            {
                command =
// GNE - this wont compile                   new LogCommand(workingDirectory, this.workingDirectory.ModuleName);
                    new RLogCommand(workingDirectory, this.workingDirectory.ModuleName);
            }

            // add any date restrictions
            if (hasStartDate && hasEndDate)
            {
                command.AddInclusiveDateRange(startDate, endDate);
            }
            else if (hasStartDate)
            {
                command.AddInclusiveDateStart(startDate);
            }
            else if (hasEndDate)
            {
                command.AddInclusiveDateEnd(endDate);
            }

            // Initialse state machine
            curLogReport   = new LogReport(); // this is what we are going to return to the caller
            curLogFile     = new LogFile(this.cvsRoot);
            curLogRevision = new LogRevision();
            logState       = LogState.WANT_FILE_HEADER_START;

            if (connection.GetType() == typeof(CVSServerConnection))
            {
                CVSServerConnection cvsServerConnection = (CVSServerConnection)connection;
                cvsServerConnection.MessageEvent.MessageEvent += new EncodedMessage.MessageHandler(OnMessage);
            }
            command.Execute(connection);

            // return curLogReport but clear our reference to it
            LogReport report = curLogReport;

            curLogReport = null;
            return(report);
        }
예제 #20
0
 static void Write(LogCommand m)
 {
     switch (m.Type)
     {
         case LogType.Warning:
             Debug.LogWarning(m.Message);
             break;
         case LogType.Error:
         case LogType.Exception:
             Debug.LogError(m.Message);
             break;
         case LogType.Log:
         case LogType.Assert:
             Debug.Log(m.Message);
             break;
     }
 }
예제 #21
0
 public Task <int> UpdateLeadFromLeadPayload(LeadPayload cDcResponseObject, LogCommand logCommand)
 {
     throw new NotImplementedException();
 }
        public string[] RetrieveAuthors(DateRange dateRange)
        {
            var command = new LogCommand();
            var authors = _repository.Log(command)
                .Where(ch => ch.Timestamp >= dateRange.StartDate && ch.Timestamp <= dateRange.EndDate)
                .Select(ch => ch.AuthorName)
                .Distinct()
                .ToArray();

            return authors;
        }
예제 #23
0
        public async Task <GenericServiceResponse> SimpleServiceAppointmentHandler(PayloadParent responseObject, LogCommand logCommand)
        {
            const string method           = "ServiceAppointmentUpdate";
            var          updateEventState = string.Empty;

            try
            {
                logCommand.LogMessage = $"{Service}.{method} Starting input parameter ResponseObject = {responseObject}";
                _logHandler.HandleLog(logCommand);

                var serviceAppointmentPayload = new ServiceAppointmentPayload(responseObject);

                logCommand.LogMessage = $"{Service}.{method} Starting input parameter serviceAppointmentPayload = {serviceAppointmentPayload}";
                _logHandler.HandleLog(logCommand);

                Guid programGuid;

                //ProgramGuid
                updateEventState = "Attempting To Get Program Guid" + Environment.NewLine;
                if (!string.IsNullOrEmpty(serviceAppointmentPayload._PayloadHeader.SalesforceProgramIDC))
                {
                    var program = await _programRepository.GetProgramFromSFID(serviceAppointmentPayload._PayloadHeader.SalesforceProgramIDC, logCommand);

                    programGuid = program.ProgramGuid;
                }
                else
                {
                    //SubProgramGuid	ProgramGuid
                    // programGuid = Guid.Parse("8CC20C6D-13C2-424B-9EB3-194F653CC778");
                    throw new Exception($"Error: {Service}.{method} -- Missing SalesforceProgramID ");
                }

                ////SubprogramGuid
                //updateEventState = "Attempting To Get SubProgram Guid" + Environment.NewLine;
                //if (!string.IsNullOrEmpty(serviceAppointmentPayload._PayloadHeader.SalesforceSubProgramIDC))
                //{
                //    var subprogram = await _programRepository.GetSubProgramSFID(serviceAppointmentPayload._PayloadHeader.SalesforceSubProgramIDC, logCommand);
                //    subprogramGuid = subprogram.SubProgramGuid;
                //}
                //else
                //{
                //    subprogramGuid = Guid.Parse("FB02657F-3985-4F06-84C3-1669BE2F2991");
                //}
                updateEventState = "Attempting to Check Dates" + Environment.NewLine;
                if (serviceAppointmentPayload._PayloadBody.ServiceAppointment.SchedStartTime == null)
                {
                    throw new Exception($"Error: {Service}.{method} -- Missing SchedStartTime ");
                }
                var scheduleStartTime = (DateTime)serviceAppointmentPayload._PayloadBody.ServiceAppointment.SchedStartTime;

                if (!DateTime.TryParse(serviceAppointmentPayload._PayloadBody.ServiceAppointment.LastModifiedDate,
                                       out var lastModifiedDate))
                {
                    lastModifiedDate = DateTime.Now;
                }

                updateEventState = "Attempting to Map dataObject" + Environment.NewLine;
                var schedulingDataObject = new SimpleScheduling
                {
                    SfRecordID           = serviceAppointmentPayload._PayloadHeader.RecordIdC,
                    ProgramGuid          = programGuid,
                    SalesforceUser       = serviceAppointmentPayload._PayloadBody.ServiceAppointment.LastModifiedById,
                    Technician           = serviceAppointmentPayload._PayloadBody.ServiceAppointment.TechnicianGuidC,
                    WorkOrderType        = serviceAppointmentPayload._PayloadBody.WorkOrder.WorkTypeId,
                    ScheduleBit          = true,
                    ScheduleDateTime     = scheduleStartTime,
                    LastModifiedDateTime = lastModifiedDate
                };

                if (string.IsNullOrEmpty(schedulingDataObject.SfRecordID) ||
                    string.IsNullOrEmpty(schedulingDataObject.WorkOrderType) ||
                    string.IsNullOrEmpty(schedulingDataObject.SalesforceUser))
                {
                    throw new Exception($"Error: {Service}.{method} -- Missing required fields");
                }

                updateEventState = "Attempting to Execute First" + Environment.NewLine;
                var recordsChanged = await _schedulingRepository.CreateSimpleSchedulingRecordFirst(schedulingDataObject, logCommand);

                if (recordsChanged > 0)
                {
                    ServiceResponse = new GenericServiceResponse
                    {
                        Entity             = $"Record Created in Simple Scheduling, rows affected = {recordsChanged}",
                        Success            = true,
                        RestResponseStatus = GenericServiceResponse.RestStatus.Success
                    };

                    logCommand.LogMessage = string.Format($"{Service}.{method} completed");
                    _logHandler.HandleLog(logCommand);

                    return(ServiceResponse);
                }

                updateEventState = "Attempting to get List" + Environment.NewLine;
                var simpleSchedulingList =
                    (await _schedulingRepository.GetSimpleScheduling(schedulingDataObject.SfRecordID, logCommand)).ToList();
                updateEventState = "Attempting to start reschedule logic" + Environment.NewLine;
                var simpleSchedulingList0 = simpleSchedulingList.Where(a => a.ScheduleBit == false).ToList();
                if (simpleSchedulingList0.Any())
                {
                    updateEventState = "Attempting to Rescheduled [1] " + Environment.NewLine;
                    var firstOrDefault = simpleSchedulingList0.OrderByDescending(a => a.SSID).FirstOrDefault();
                    if (
                        firstOrDefault != null && (schedulingDataObject.SalesforceUser != firstOrDefault.SalesforceUser &&
                                                   schedulingDataObject.LastModifiedDateTime > firstOrDefault.LastModifiedDateTime.AddMinutes(+5)
                                                   &&
                                                   (schedulingDataObject.WorkOrderType != firstOrDefault.WorkOrderType ||
                                                    schedulingDataObject.ScheduleDateTime != firstOrDefault.ScheduleDateTime ||
                                                    schedulingDataObject.Technician != firstOrDefault.Technician))
                        )
                    {
                        recordsChanged = await _schedulingRepository.CreateSimpleSchedulingRecordReschedule(schedulingDataObject,
                                                                                                            logCommand);
                    }
                }
                else
                {
                    updateEventState = "Attempting to Rescheduled [2] " + Environment.NewLine;
                    var firstOrDefault = simpleSchedulingList.OrderByDescending(a => a.SSID)
                                         .FirstOrDefault(a => a.ScheduleBit);
                    if (firstOrDefault == null)
                    {
                        throw new Exception($"Error: {Service}.{method} -- Missing Created Date Record on Reschedule ");
                    }
                    if (schedulingDataObject.SalesforceUser != firstOrDefault.SalesforceUser &&
                        schedulingDataObject.LastModifiedDateTime > firstOrDefault.LastModifiedDateTime.AddMinutes(+30))
                    {
                        recordsChanged = await _schedulingRepository.CreateSimpleSchedulingRecordReschedule(schedulingDataObject,
                                                                                                            logCommand);
                    }
                }
                updateEventState = "Executions Complete" + Environment.NewLine;

                ServiceResponse = await InsertAuditRecordAsync(logCommand, responseObject,
                                                               schedulingDataObject.GetType().FullName,
                                                               serviceAppointmentPayload._PayloadBody.ServiceAppointment.LastModifiedById);

                if (!ServiceResponse.Success)
                {
                    return(ServiceResponse);
                }

                if (recordsChanged >= 1)
                {
                    ServiceResponse = new GenericServiceResponse
                    {
                        Entity             = $"Successful: Update Scheduling Related Table, rows added/updated = {recordsChanged}",
                        Success            = true,
                        RestResponseStatus = GenericServiceResponse.RestStatus.Success
                    };
                }
                else
                {
                    ServiceResponse = new GenericServiceResponse
                    {
                        Entity             = $"Failure: Update Scheduling Related Table, rows added/updated = {recordsChanged}",
                        Success            = true,
                        RestResponseStatus = GenericServiceResponse.RestStatus.Empty
                    };
                }

                logCommand.LogMessage = string.Format($"{Service}.{method} completed");
                _logHandler.HandleLog(logCommand);

                return(ServiceResponse);
            }
            catch (Exception ex)
            {
                ex.Data.Add("Point of Failure", updateEventState);
                AppLogger.LogException(_loggingInstance, ex.Message, ex);
                return(ServiceHelper.SetErrorGenericServiceResponse(ex));
            }
        }
예제 #24
0
        public async Task <GenericServiceResponse> ServiceAppointmentUpdate(PayloadParent ResponseObject, LogCommand logCommand)
        {
            const string method           = "ServiceAppointmentUpdate";
            var          updateEventState = string.Empty;

            try
            {
                logCommand.LogMessage = $"{Service}.{method} Starting input parameter ResponseObject = {ResponseObject}";
                _logHandler.HandleLog(logCommand);

                var serviceAppointmentPayload = new ServiceAppointmentPayload(ResponseObject);

                logCommand.LogMessage = $"{Service}.{method} Starting input parameter serviceAppointmentPayload = {serviceAppointmentPayload}";
                _logHandler.HandleLog(logCommand);
                var recordsAffected = 0;

                Guid programGuid;
                Guid subprogramGuid;
                Guid WorkOrderScoreWeightingGuid;
                Guid StatusTypeGuid;
                Guid UsernameMappingGuid;

                //ProgramGuid
                updateEventState = "Attempting To Get Program Guid" + Environment.NewLine;
                if (!string.IsNullOrEmpty(serviceAppointmentPayload._PayloadHeader.SalesforceProgramIDC))
                {
                    var program = await _programRepository.GetProgramFromSFID(serviceAppointmentPayload._PayloadHeader.SalesforceProgramIDC, logCommand);

                    programGuid = program.ProgramGuid;
                }
                else
                {
                    //SubProgramGuid	ProgramGuid
                    // programGuid = Guid.Parse("8CC20C6D-13C2-424B-9EB3-194F653CC778");
                    throw new Exception($"Error: {Service}.{method} -- Missing SalesforceProgramID ");
                }

                //SubprogramGuid
                updateEventState = "Attempting To Get SubProgram Guid" + Environment.NewLine;
                if (!string.IsNullOrEmpty(serviceAppointmentPayload._PayloadHeader.SalesforceSubProgramIDC))
                {
                    var subprogram = await _programRepository.GetSubProgramSFID(serviceAppointmentPayload._PayloadHeader.SalesforceSubProgramIDC, logCommand);

                    subprogramGuid = subprogram.SubProgramGuid;
                }
                else
                {
                    subprogramGuid = Guid.Parse("FB02657F-3985-4F06-84C3-1669BE2F2991");
                }

                // Mapping SFUserid To AD Username
                updateEventState = "Attempting To Get Map Status GUid" + Environment.NewLine;
                if (!string.IsNullOrEmpty(serviceAppointmentPayload._PayloadBody.ServiceAppointment.Status))
                {
                    var lkpSchedulingType = await _schedulingRepository.GetLkpSchedulingTypeEnum(logCommand);

                    var statusTypeMapping = lkpSchedulingType.FirstOrDefault(a => string.Equals(a.SchedulingTypeName, serviceAppointmentPayload._PayloadBody.ServiceAppointment.Status, StringComparison.CurrentCultureIgnoreCase));
                    if (statusTypeMapping != null)
                    {
                        StatusTypeGuid = statusTypeMapping.LkpSchedulingTypeGuid;
                    }
                    else
                    {
                        throw new Exception($"Error: {Service}.{method} -- Cannot Status GUid ");
                    }
                }
                else
                {
                    throw new Exception($"Error: {Service}.{method} -- Cannot Status GUid ");
                }

                // LKPWorkOrderScoreMapping Workorder WorkTypeId
                updateEventState = "Attempting To Get Map Work Order Type Guid" + Environment.NewLine;
                if (!string.IsNullOrEmpty(serviceAppointmentPayload._PayloadBody.WorkOrder.WorkTypeId))
                {
                    var lkpAuditType = await _schedulingRepository.GetWorkOrderScoreWeightingEnum(logCommand);

                    var workOrderScoreMapping = lkpAuditType.FirstOrDefault(a => a.SalesforceRecordID == serviceAppointmentPayload._PayloadBody.WorkOrder.WorkTypeId);
                    if (workOrderScoreMapping != null)
                    {
                        WorkOrderScoreWeightingGuid = workOrderScoreMapping.WorkOrderScoreWeightingGuid;
                    }
                    else
                    {
                        throw new Exception($"Error: {Service}.{method} -- Cannot Map Work order Type ");
                    }
                }
                else
                {
                    throw new Exception($"Error: {Service}.{method} -- Cannot Map Work order Type ");
                }

                // LKPWorkOrderScoreMapping Workorder WorkTypeId
                updateEventState = "Attempting To Get Username Guid" + Environment.NewLine;
                if (!string.IsNullOrEmpty(serviceAppointmentPayload._PayloadBody.ServiceAppointment.LastModifiedById))
                {
                    var usernameMappingList = await _schedulingRepository.GetUsernameMappingSFtoADEnum(logCommand);

                    var usernameMapping = usernameMappingList.FirstOrDefault(a => a.SalesForceUserRecordID == serviceAppointmentPayload._PayloadBody.ServiceAppointment.LastModifiedById);
                    if (usernameMapping != null)
                    {
                        UsernameMappingGuid = usernameMapping.UsernameMappingSFtoADGuid;
                    }
                    else
                    {
                        throw new Exception($"Error: {Service}.{method} -- Cannot Map Username ");
                    }
                }
                else
                {
                    throw new Exception($"Error: {Service}.{method} -- Cannot Map Username");
                }
                updateEventState = "Attempting Execute" + Environment.NewLine;


                var schedulingDataObject = new Scheduling()
                {
                    SubprogramGuid = subprogramGuid,
                    ProgramGuid    = programGuid,
                    WorkOrderScoreWeightingGuid = WorkOrderScoreWeightingGuid,
                    UsernameMappingSFtoADGuid   = UsernameMappingGuid,
                    CreatedDateTime             = DateTime.Now,
                    LkpSchedulingTypeGuid       = StatusTypeGuid,
                    SalesforceRecordID          = serviceAppointmentPayload._PayloadHeader.RecordIdC
                };

                recordsAffected = await _schedulingRepository.CreateNewSchedulingRecord(schedulingDataObject, logCommand);

                ServiceResponse = await InsertAuditRecordAsync(logCommand, ResponseObject,
                                                               schedulingDataObject.GetType().FullName,
                                                               serviceAppointmentPayload._PayloadBody.ServiceAppointment.LastModifiedById);

                if (!ServiceResponse.Success)
                {
                    return(ServiceResponse);
                }

                updateEventState = "Executions Complete" + Environment.NewLine;


                ServiceResponse = new GenericServiceResponse
                {
                    Entity             = $"Update Scheduling Related Tables Successful, rows added/updated = {recordsAffected}",
                    Success            = true,
                    RestResponseStatus = GenericServiceResponse.RestStatus.Success
                };

                logCommand.LogMessage = string.Format($"{Service}.{method} completed");
                _logHandler.HandleLog(logCommand);

                return(ServiceResponse);
            }
            catch (Exception ex)
            {
                ex.Data.Add("Point of Failure", updateEventState);
                AppLogger.LogException(_loggingInstance, ex.Message, ex);
                return(ServiceHelper.SetErrorGenericServiceResponse(ex));
            }
        }
예제 #25
0
        public async Task <LkpLeadStatus> GetLkpLeadStatusFromGuid(Guid LkpLeadStatusGuid, LogCommand logCommand)
        {
            //Logging Helper for Method
            const string methodName = "GetLkpLeadStatusFromGuid";

            //Query Used by Dapper
            var query =
                " SELECT  * from " + RepositoryTable +
                " where LeadStatusGuid = @LkpLeadStatusGuid";

            //Log the input
            logCommand.LogMessage = $"{Repository}.{methodName} Starting input parameter LkpLeadStatusGuid={LkpLeadStatusGuid}" + Environment.NewLine +
                                    $"Query: {query}";
            _logHandler.HandleLog(logCommand);


            using (var connection = _connectionFactory.GetConnection)
            {
                //Await the response
                var _LkpLeadStatus = await connection.QueryFirstAsync <LkpLeadStatus>(query, new{ LkpLeadStatusGuid });

                connection.Close();

                //Log the output
                logCommand.LogMessage = $"{Repository}.{methodName} completed";
                _logHandler.HandleLog(logCommand);

                return(_LkpLeadStatus);
            }
        }
예제 #26
0
        public Task <GenericServiceResponse> CdcEventContactUpdate(JObject cdcPayload, LogCommand logCommand)
        {
            const string method = "CDCEventContactUpdate";

            try
            {
                logCommand.LogMessage = $"{Service}.{method} Starting input parameter CDCPayload = {cdcPayload}";
                _logHandler.HandleLog(logCommand);


                var response = new GenericServiceResponse
                {
                    Entity             = $"Ignoring Contact ",
                    Success            = true,
                    RestResponseStatus = GenericServiceResponse.RestStatus.Success
                };


                logCommand.LogMessage = string.Format($"{Service}.{method} completed");
                _logHandler.HandleLog(logCommand);

                return(Task.Run(() => response));
            }
            catch (Exception ex)
            {
                AppLogger.LogException(_loggingInstance, ex.Message, ex);
                return(Task.Run(() => ServiceHelper.SetErrorGenericServiceResponse(ex)));
            }
        }
예제 #27
0
        public async Task <GenericServiceResponse> CdcEventAddressUpdate(PayloadParent PayloadResponse, LogCommand logCommand)
        {
            const string method           = "UpdateLeadFromUpdateEvent";
            var          UpdateEventState = string.Empty;

            try
            {
                logCommand.LogMessage = $"{Service}.{method} Starting input parameter PayloadResponse = {PayloadResponse}";
                _logHandler.HandleLog(logCommand);

                var addressPayload = new AddressPayload(PayloadResponse);

                logCommand.LogMessage = $"{Service}.{method} Starting input parameter addressPayload = {addressPayload}";
                _logHandler.HandleLog(logCommand);
                var recordsAffected = 0;

                var response = new GenericServiceResponse
                {
                    Success            = true,
                    RestResponseStatus = GenericServiceResponse.RestStatus.Empty
                };

                Guid programGuid;
                Guid subprogramGuid;
                Guid addressTypeGuid;
                Guid countyGuid;
                Guid ownershipGuid;

                string ownershipTypeName = "Rented";
                //Customer Guid Check
                UpdateEventState = "Attempting to check CustomerGuid" + Environment.NewLine;
                if (addressPayload._PayloadHeader.CmcCustomerGuidC == null ||
                    addressPayload._PayloadHeader.CmcCustomerGuidC == Guid.Empty)
                {
                    throw new Exception($"Error: {Service}.{method} -- Missing Customer Guid ");
                }

                //Address Record ID
                UpdateEventState = "Attempting To check Address Record ID Guid" + Environment.NewLine;
                if (string.IsNullOrEmpty(addressPayload._PayloadHeader.RecordIdC))
                {
                    throw new Exception($"Error: {Service}.{method} -- Missing Record ID, Required for Update ");
                }

                //ProgramGuid
                UpdateEventState = "Attempting To Get Program Guid" + Environment.NewLine;
                if (!string.IsNullOrEmpty(addressPayload._PayloadHeader.SalesforceProgramIDC))
                {
                    var program = await _programRepository.GetProgramFromSFID(addressPayload._PayloadHeader.SalesforceProgramIDC, logCommand);

                    programGuid = program.ProgramGuid;
                }
                else
                {
                    throw new Exception($"Error: {Service}.{method} -- Missing SalesforceProgramID ");
                }

                //SubprogramGuid
                UpdateEventState = "Attempting To Get SubProgram Guid" + Environment.NewLine;
                if (!string.IsNullOrEmpty(addressPayload._PayloadHeader.SalesforceSubProgramIDC))
                {
                    var subprogram = await _programRepository.GetSubProgramSFID(addressPayload._PayloadHeader.SalesforceSubProgramIDC, logCommand);

                    subprogramGuid = subprogram.SubProgramGuid;
                }
                else
                {
                    subprogramGuid = Guid.Parse("FB02657F-3985-4F06-84C3-1669BE2F2991");
                }

                //addressTypeGuid setting it to default for now.
                UpdateEventState = "Attempting To Get addressTypeGuid" + Environment.NewLine;
                if (!string.IsNullOrEmpty(addressPayload._PayloadBody.AddressTypeC))
                {
                    var lkpAccountType = await _addressRepository.GetLKPAddressTypeFromAddressTypeName(addressPayload._PayloadBody.AddressTypeC, logCommand);

                    addressTypeGuid = lkpAccountType.AddressTypeGuid;
                }
                else
                {
                    logCommand.LogMessage = string.Format($"Error: {Service}.{method} -- Missing addressTypeGuid ");
                    _logHandler.HandleLog(logCommand);

                    return(response);
                }

                //CountyGuid setting it to default for now.
                UpdateEventState = "Attempting To Get CountyGuid" + Environment.NewLine;
                if (addressPayload._PayloadBody.AddressTypeC.ToLower() == "service")
                {
                    if (!string.IsNullOrEmpty(addressPayload._PayloadBody.CountyC))
                    {
                        var lkpCounties = await _addressRepository.GetLkpCountyFromCountyDescription(addressPayload._PayloadBody.CountyC, logCommand);

                        countyGuid = lkpCounties.CountyGuid;
                    }

                    else
                    {
                        logCommand.LogMessage = string.Format($"Error: {Service}.{method} -- Missing CountyGuid ");
                        _logHandler.HandleLog(logCommand);
                        return(response);
                    }
                }
                else
                {
                    countyGuid = Guid.Parse("24C3CDAC-2BB8-46A9-AF92-70E36D0B37F7");
                }

                //CountyGuid setting it to default for now.
                UpdateEventState = "Attempting To Get OwnershipGuid" + Environment.NewLine;
                if (ownershipTypeName == "Rented")
                {
                    var lkpOwnership = await _addressRepository.GetLkpOwnershipFromOwnershipType("Rented", logCommand);

                    ownershipGuid = lkpOwnership.OwnershipGuid;
                }
                else
                {
                    logCommand.LogMessage = string.Format($"Error: {Service}.{method} -- Missing OwnershipGuid ");
                    _logHandler.HandleLog(logCommand);
                }

                var address = new Address(addressPayload, addressTypeGuid, countyGuid, ownershipGuid);

                //Even though this is an address update PE message, it may be the initial insert of a landlord mailing address
                if (addressTypeGuid == Guid.Parse("431407C6-C889-48BF-9DFC-7CD879F85847")) //Landlord Mailing
                {
                    var existingLlAddress = await _addressRepository.GetAddressBySfIdAndAddressType(address, logCommand);

                    if (!existingLlAddress.Any())
                    {
                        recordsAffected += await _addressRepository.InsertAddress(address, logCommand);
                    }
                    else
                    {
                        //Update Address
                        recordsAffected += await _addressRepository.UpdateAddress(address, logCommand);
                    }

                    if (recordsAffected > 0)
                    {
                        response = new GenericServiceResponse
                        {
                            Entity             = $"Update Address Related Tables Successful, rows added/updated = {recordsAffected}",
                            Success            = true,
                            RestResponseStatus = GenericServiceResponse.RestStatus.Success
                        };
                    }
                    else
                    {
                        response = new GenericServiceResponse
                        {
                            Entity             = $"Address Does not Exist. Records Changed: {recordsAffected}. Could not update. ",
                            Success            = false,
                            RestResponseStatus = GenericServiceResponse.RestStatus.Success
                        };
                    }
                }

                logCommand.LogMessage = string.Format($"{Service}.{method} completed");
                _logHandler.HandleLog(logCommand);

                return(response);
            }
            catch (Exception ex)
            {
                ex.Data.Add("Point of Failure", UpdateEventState);
                AppLogger.LogException(_loggingInstance, ex.Message, ex);
                return(ServiceHelper.SetErrorGenericServiceResponse(ex));
            }
        }
 public Changeset GetParentCommit(Changeset commit)
 {
     var command = new LogCommand().WithIncludePathActions();
     var changeset = _repository.Log(command)
         .FirstOrDefault(ch => ch.RevisionNumber == (commit.RevisionNumber > 0 ? commit.RevisionNumber - 1 : commit.RevisionNumber));
     return changeset;
 }
예제 #29
0
        public async Task <int> UpdateLeadFromLeadPayload_GUID(LeadPayload leadPayload, LogCommand logCommand)
        {
            //Logging Helper for Method
            var method_name = "UpdateLeadFromLeadPayload_GUID";

            var UpdateQuery = " update _LeadTable " +
                              " set  " +
                              "  _LeadTable.[SFLeadID] = @ID " +
                              " ,_LeadTable.[LeadStatusGuid] = _LeadStatus.LeadStatusGuid " +
                              " ,_LeadTable.LeadSource = @LeadSource " +
                              " ,_LeadTable.QualifiedAuditTypeGuid = _AuditType.AuditTypeGuid " +

                              " From [CMC-SFDC_DEV].[Customer].[Lead] as _LeadTable " +
                              " join customer.LkpAuditType as _AuditType " +
                              " on _AuditType.AuditTypeName = @AuditTypeC " +
                              " join Customer.LkpLeadStatus as _LeadStatus " +
                              " on _LeadStatus.LeadStatusName = @Status " +
                              " where _LeadTable.CustomerGuid = @CmcCustomerGuidC ";


            //Log the input
            logCommand.LogMessage = $"{Repository}.{method_name} Starting input parameters CDCResponseObject = {JsonConvert.SerializeObject(leadPayload)}" + Environment.NewLine +
                                    $"Query: {UpdateQuery}";
            _logHandler.HandleLog(logCommand);


            using (var connection = _connectionFactory.GetConnection)
            {
                //Await the response
                var returnValue = await connection.ExecuteAsync(UpdateQuery, leadPayload);

                connection.Close();

                //Log the output
                logCommand.LogMessage = $"{Repository}.{method_name} completed";
                _logHandler.HandleLog(logCommand);

                return(returnValue);
            }
        }
        public Changeset GetCommit(RevisionId id)
        {
			var command = new LogCommand().WithRevision(RevSpec.ById(id.Value)).WithIncludePathActions();
            var changeset = _repository.Log(command).FirstOrDefault(ch => ch.Hash == id.Value);
            return changeset;
        }
예제 #31
0
        public async Task <int> LeadCreatedSetRecordId(Guid customerGuid, string sFLeadId, LogCommand logCommand)
        {
            //Logging Helper for Method
            const string methodName = "UpdateLeadFromLeadPayload_SFID";

            var updateQuery = $"update {LeadTable} " +
                              " set  SFLeadID = @SFLeadID " +
                              " where CustomerGuid = @CustomerGuid ";


            //Log the input
            logCommand.LogMessage = $"{Repository}.{methodName} Starting input parameters CustomerGuid = {customerGuid} || SFLeadID = {sFLeadId}" + Environment.NewLine +
                                    $"Query: {updateQuery}";
            _logHandler.HandleLog(logCommand);


            using (var connection = _connectionFactory.GetConnection)
            {
                //Await the response
                var returnValue = await connection.ExecuteAsync(updateQuery, new { CustomerGuid = customerGuid, SFLeadID = sFLeadId });

                connection.Close();

                //Log the output
                logCommand.LogMessage = $"{Repository}.{methodName} completed";
                _logHandler.HandleLog(logCommand);

                return(returnValue);
            }
        }
        public RevisionInfo[] GetRevisions(RevisionId fromChangeset, RevisionId toChangeset)
		{
			var from = new RevSpec(fromChangeset.Value);
			var to = new RevSpec(toChangeset.Value);
			var command = new LogCommand().WithRevision(RevSpec.Range(from, to)).WithIncludePathActions();
            var revisionInfos = _repository.Log(command)
                .Where(ch => ch.Timestamp >= fromChangeset.Time.Value && ch.Timestamp <= toChangeset.Time.Value)
                .Select(ch => ch.ToRevisionInfo())
                .ToArray();

            return revisionInfos;
        }
예제 #33
0
        public async Task <IEnumerable <Program> > FindProgram(SearchProgram _SearchProgram, LogCommand logCommand)
        {
            //Logging Helper for Method
            var method_name = "GetClientAsync";

            //Query Used by Dapper
            var query =
                " SELECT  * from " + ProgramTable +
                _SearchProgram.getWhereClause();


            //Log the input
            logCommand.LogMessage = $"{Repository}.{method_name} Starting input parameter _SearchProgram={JsonConvert.SerializeObject(_SearchProgram)}" + Environment.NewLine +
                                    $"Query: {query}";
            _logHandler.HandleLog(logCommand);


            using (var connection = _connectionFactory.GetConnection)
            {
                //Await the response
                var _Program = await connection.QueryAsync <Program>(query);

                connection.Close();

                //Log the output
                logCommand.LogMessage = $"{Repository}.{method_name} completed";
                _logHandler.HandleLog(logCommand);

                return(_Program);
            }
        }
예제 #34
0
        public async Task <LkpAuditType> GetLkpLeadAuditTypeFromName(string auditTypeName, LogCommand logCommand)
        {
            //Logging Helper for Method
            const string methodName = "GetLkpLeadAuditTypeFromName";


            if (string.IsNullOrEmpty(auditTypeName) ||
                auditTypeName.ToLower() != "not qualified" ||
                auditTypeName.ToLower() != "heating" ||
                auditTypeName.ToLower() != "baseload" ||
                auditTypeName.ToLower() != "apartment heating")
            {
                if (string.IsNullOrEmpty(auditTypeName))
                {
                    auditTypeName = "Not Qualified";
                }
                else if (auditTypeName.ToLower() == "wta")
                {
                    auditTypeName = "Baseload";
                }
                else if (auditTypeName.ToLower() == "bda")
                {
                    auditTypeName = "Heating";
                }
                else if (auditTypeName.ToLower() == "apt")
                {
                    auditTypeName = "Apartment Heating";
                }
                else if (auditTypeName.ToLower() == "not qualify")
                {
                    auditTypeName = "Not Qualified";
                }
            }

            //Query Used by Dapper
            var query =
                " SELECT  * from " + LeadAuditTypeTable +
                " where [AuditTypeName] = @AuditTypeName";

            //Log the input
            logCommand.LogMessage = $"{Repository}.{methodName} Starting input parameter AuditTypeName={auditTypeName}" + Environment.NewLine +
                                    $"Query: {query}";
            _logHandler.HandleLog(logCommand);


            using (var connection = _connectionFactory.GetConnection)
            {
                //Await the response
                var lkpAuditType = await connection.QueryFirstAsync <LkpAuditType>(query, new { AuditTypeName = auditTypeName });

                connection.Close();

                //Log the output
                logCommand.LogMessage = $"{Repository}.{methodName} completed";
                _logHandler.HandleLog(logCommand);

                return(lkpAuditType);
            }
        }
예제 #35
0
        public async Task <IEnumerable <Subprogram> > GetProgramAndSubprogramBySfSubProgramId(string sfSubProgramId, LogCommand logCommand)
        {
            //Logging Helper for Method
            var method_name = "GetProgramAndSubprogramBySfSubProgramId";

            //Query Used by Dapper
            var query =
                " SELECT ProgramGuid, SubProgramGuid, SubProgramName from Program.SubProgram " +
                $" WHERE SfSubProgramId = '{sfSubProgramId}'";

            //Log the input
            logCommand.LogMessage = $"{Repository}.{method_name} Starting input parameter: {sfSubProgramId} + Query: {query}";
            _logHandler.HandleLog(logCommand);


            using (var connection = _connectionFactory.GetConnection)
            {
                //Await the response
                var program = await connection.QueryAsync <Subprogram>(query);

                connection.Close();

                //Log the output
                logCommand.LogMessage = $"{Repository}.{method_name} completed";
                _logHandler.HandleLog(logCommand);

                return(program);
            }
        }
예제 #36
0
        public async Task <int> UpsertEmail(string Email, string FieldName, Guid ContactGuid, LogCommand logCommand)
        {
            //Logging Helper for Method
            var method_name = "UpsertEmail";

            var query = "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; " +
                        "BEGIN TRANSACTION; " +
                        $" UPDATE [Customer].Email  SET " +
                        $" [EmailAddress] = '{Email}' " +
                        $"  where [ContactGuid] = '{ContactGuid}' and [SFFieldName] = '{FieldName}'; " +
                        "IF @@ROWCOUNT = 0 " +
                        "BEGIN " +
                        " Insert into [CMC-SFDC_DEV].[Contact].[Email] " +
                        $" values (newID(), '{ContactGuid}', '{FieldName}', '{Email}' )" +
                        "END " +
                        "COMMIT TRANSACTION; ";

            //Log the input
            logCommand.LogMessage = $"{Repository}.{method_name} Starting input parameter " +
                                    $"Email={Email}" + Environment.NewLine +
                                    $"Email={Email}" + Environment.NewLine +
                                    $"Email={Email}" + Environment.NewLine +
                                    $"______________" + Environment.NewLine +
                                    $"Query: {query}";

            _logHandler.HandleLog(logCommand);


            using (var connection = _connectionFactory.GetConnection)
            {
                //Await the response
                var _Email = await connection.ExecuteAsync(query);

                connection.Close();

                //Log the output
                logCommand.LogMessage = $"{Repository}.{method_name} completed";
                _logHandler.HandleLog(logCommand);

                return(_Email);
            }
        }
예제 #37
0
        /// <summary>
        /// Function that connect the server to clients.
        /// </summary>
        public void ConnectServer()
        {
            Thread.Sleep(100);
            IPEndPoint  ep       = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888);
            TcpListener listener = new TcpListener(ep);

            //first of all start the listener for searching connections.
            listener.Start();
            Console.Write("Waiting for connection...");
            HandleLogs handleLogs = new HandleLogs();

            //thread for alwayes search for cnnections.
            Task ta = new Task(() =>
            {
                while (true)
                {
                    try
                    {
                        TcpClient client = listener.AcceptTcpClient();
                        //this.client = client;
                        Console.WriteLine("Connection accepted.");
                        m_logging.Log("Connection to server accepted", MessageTypeEnum.INFO);

                        mutex3.WaitOne();
                        NetworkStream ns = client.GetStream();
                        byte[] bytes     = new byte[1024];

                        //this.ns = client.GetStream();
                        int bytesRead = ns.Read(bytes, 0, bytes.Length);
                        string r      = Encoding.ASCII.GetString(bytes, 0, bytesRead);
                        mutex3.ReleaseMutex();

                        Task task2 = new Task(() =>
                        {
                            if (client.Connected)
                            {
                                if (r == "GetConfigCommand")
                                {
                                    ICommand command = new GetConfigCommand(this, client, m_controller);
                                    bool success;
                                    command.Execute(null, out success);

                                    //HandleSettings h = new HandleSettings(this, client, m_controller);
                                }
                                else if (r == "LogCommand")
                                {
                                    ICommand command = new LogCommand(handleLogs, this, m_logging, client);
                                    bool success;
                                    command.Execute(null, out success);

                                    //handleLogs.SetAllProt(this, m_logging , client);
                                }
                            }
                        }); task2.Start();

                        /*
                         * need to take care the close
                         * when the client close the screen we should out this while !
                         *
                         * */
                    }
                    catch (Exception e)
                    {
                        break;
                    }
                }
            });

            ta.Start();
            tcpListener = listener;
        }
예제 #38
0
        //Change Minor
        //TODO: HW This is temporary code Needs to be removed ASAP Hack to update Lead so that it will be excluded from GetPrioritizedLeads query if touched by user.
        public Task <GenericServiceResponse> TaskEventInsertUpdate(PayloadParent payloadResponse, LogCommand logCommand)
        {
            const string method = "TaskEventInsertUpdate";

            try
            {
                logCommand.LogMessage = $"{Service}.{method} Starting input parameter cdcPayload = {JsonConvert.SerializeObject(payloadResponse)}";
                _logHandler.HandleLog(logCommand);


                var response = AuditInsert.InsertAuditRecordAsync(logCommand, payloadResponse, "Shared.Entities.DTO.Customer.Lead", payloadResponse.CreatedById, _cdcRepository);
                logCommand.LogMessage = string.Format($"{Service}.{method} completed");
                _logHandler.HandleLog(logCommand);

                return(response);
            }
            catch (Exception ex)
            {
                AppLogger.LogException(_loggingInstance, ex.Message, ex);
                return(Task.Run(() => ServiceHelper.SetErrorGenericServiceResponse(ex)));
            }
        }
예제 #39
0
        /// <summary>
        /// Updates ReserveDateProperty of a Lead to 15 minutes from now
        /// </summary>
        /// <param name="customerGuid"></param>
        /// <param name="reservedDateTime"></param>
        /// <param name="logCommand"></param>
        /// <param name="trans"></param>
        /// <returns></returns>
        public async Task <int> UpdateReservedDateAsync(Guid customerGuid, DateTime reservedDateTime, LogCommand logCommand, IDbTransaction trans)
        {
            //Logging Helper for Method
            const string methodName = "UpdateReservedDateAsync";
            var          query      = $"Update Customer.Lead set ReservedDate = '{reservedDateTime}' where CustomerGuid = @CustomerGuid";

            //Log the input
            logCommand.LogMessage = $"{Repository}.{methodName} Starting input parameter: {customerGuid} " + Environment.NewLine + $"Query: {query}";
            _logHandler.HandleLog(logCommand);

            //NOTE: NO USING STATEMENT CALLING ROUTINE IN THE SERVICE LAYER NEEDS TO MANAGE THE CONNECTION !!!
            //Await the response
            var results = await trans.Connection.ExecuteAsync(query, new { @CustomerGuid = customerGuid }, trans, null, CommandType.Text);

            // connection.Close();

            //Log the output
            logCommand.LogMessage = $"{Repository}.{methodName} completed";
            _logHandler.HandleLog(logCommand);

            return(results);
        }
예제 #40
0
        public async Task <IEnumerable <LkpLeadStatus> > GetLkpLeadStatus(SearchLkpLeadStatus _SearchLkpLeadStatus, LogCommand logCommand)
        {
            //Logging Helper for Method
            const string methodName = "GetLkpLeadStatus";

            //Query Used by Dapper
            var whereClause = _SearchLkpLeadStatus.getWhereClause();

            var query =
                " SELECT  * from " + RepositoryTable + " "
                + whereClause;

            //Log the input
            logCommand.LogMessage = $"{Repository}.{methodName} Starting input parameter _SearchLkpLeadStatus={JsonConvert.SerializeObject(_SearchLkpLeadStatus)}" + Environment.NewLine +
                                    $"Query: {query}";
            _logHandler.HandleLog(logCommand);


            using (var connection = _connectionFactory.GetConnection)
            {
                //Await the response
                var _LkpLeadStatus = await connection.QueryAsync <LkpLeadStatus>(query);

                connection.Close();

                //Log the output
                logCommand.LogMessage = $"{Repository}.{methodName} completed";
                _logHandler.HandleLog(logCommand);

                return(_LkpLeadStatus);
            }
        }
예제 #41
0
        public async Task <GenericServiceResponse> CdcEventAddressCreate(PayloadParent cdcPayload, LogCommand logCommand)
        {
            const string method           = "CdcEventAddressCreate";
            var          UpdateEventState = string.Empty;

            try
            {
                logCommand.LogMessage = $"{Service}.{method} Starting input parameter cdcPayload = {cdcPayload}";
                _logHandler.HandleLog(logCommand);

                var addressPayload = new AddressPayload(cdcPayload);

                logCommand.LogMessage = $"{Service}.{method} Starting input parameter addressPayload = {addressPayload}";
                _logHandler.HandleLog(logCommand);
                var recordsAffected = 0;

                var response = new GenericServiceResponse
                {
                    Success            = true,
                    RestResponseStatus = GenericServiceResponse.RestStatus.Empty
                };

                Guid programGuid;
                Guid subprogramGuid;
                Guid addressTypeGuid;
                Guid countyGuid;
                Guid ownershipGuid;

                string ownershipTypeName = "Rented";

                //Customer Guid Check
                UpdateEventState = "Attempting to check CustomerGuid" + Environment.NewLine;
                if (addressPayload._PayloadHeader.CmcCustomerGuidC == null ||
                    addressPayload._PayloadHeader.CmcCustomerGuidC == Guid.Empty)
                {
                    throw new Exception($"Error: {Service}.{method} -- Missing Customer Guid ");
                }

                //Address Record ID
                UpdateEventState = "Attempting To check Address Record ID Guid" + Environment.NewLine;
                if (string.IsNullOrEmpty(addressPayload._PayloadHeader.RecordIdC))
                {
                    throw new Exception($"Error: {Service}.{method} -- Missing Record ID, Required for Update ");
                }

                //ProgramGuid
                UpdateEventState = "Attempting To Get Program Guid" + Environment.NewLine;
                if (!string.IsNullOrEmpty(addressPayload._PayloadHeader.SalesforceProgramIDC))
                {
                    var program = await _programRepository.GetProgramFromSFID(addressPayload._PayloadHeader.SalesforceProgramIDC, logCommand);

                    programGuid = program.ProgramGuid;
                }
                else
                {
                    throw new Exception($"Error: {Service}.{method} -- Missing SalesforceProgramID ");
                }

                //SubprogramGuid
                UpdateEventState = "Attempting To Get SubProgram Guid" + Environment.NewLine;
                if (!string.IsNullOrEmpty(addressPayload._PayloadHeader.SalesforceSubProgramIDC))
                {
                    var subprogram = await _programRepository.GetSubProgramSFID(addressPayload._PayloadHeader.SalesforceSubProgramIDC, logCommand);

                    subprogramGuid = subprogram.SubProgramGuid;
                }
                else
                {
                    subprogramGuid = Guid.Parse("FB02657F-3985-4F06-84C3-1669BE2F2991");
                }

                //addressTypeGuid setting it to default for now.
                UpdateEventState = "Attempting To Get addressTypeGuid" + Environment.NewLine;
                if (!string.IsNullOrEmpty(addressPayload._PayloadBody.AddressTypeC))
                {
                    var lkpAccountType = await _addressRepository.GetLKPAddressTypeFromAddressTypeName(addressPayload._PayloadBody.AddressTypeC, logCommand);

                    addressTypeGuid = lkpAccountType.AddressTypeGuid;
                }
                else
                {
                    logCommand.LogMessage = string.Format($"Error: {Service}.{method} -- Missing addressTypeGuid ");
                    _logHandler.HandleLog(logCommand);

                    response.Entity = "Empty Address Type";
                    return(response);
                }

                //CountyGuid setting it to default for now.
                UpdateEventState = "Attempting To Get CountyGuid" + Environment.NewLine;
                if (addressPayload._PayloadBody.AddressTypeC.ToLower() == "service")
                {
                    if (!string.IsNullOrEmpty(addressPayload._PayloadBody.CountyC))
                    {
                        var lkpCounties = await _addressRepository.GetLkpCountyFromCountyDescription(addressPayload._PayloadBody.CountyC, logCommand);

                        countyGuid = lkpCounties.CountyGuid;
                    }

                    else
                    {
                        logCommand.LogMessage = string.Format($"Error: {Service}.{method} -- Missing CountyGuid ");
                        _logHandler.HandleLog(logCommand);

                        response.Entity = "Empty County";
                        return(response);
                    }
                }
                else
                {
                    countyGuid = Guid.Parse("24C3CDAC-2BB8-46A9-AF92-70E36D0B37F7");
                }

                //OwnershipGuid setting it to default for now.
                UpdateEventState = "Attempting To Get OwnershipGuid" + Environment.NewLine;
                if (ownershipTypeName == "Rented")
                {
                    var lkpOwnership = await _addressRepository.GetLkpOwnershipFromOwnershipType("Rented", logCommand);

                    ownershipGuid = lkpOwnership.OwnershipGuid;
                }
                else
                {
                    logCommand.LogMessage = string.Format($"Error: {Service}.{method} -- Missing OwnershipGuid ");
                    _logHandler.HandleLog(logCommand);
                }

                UpdateEventState = "Attempting To Build Object" + Environment.NewLine;
                var address = new Address(addressPayload, addressTypeGuid, countyGuid, ownershipGuid);

                //Update Phone
                UpdateEventState = "Attempting To Insert/Update" + Environment.NewLine;
                if (addressPayload._PayloadBody.Address_SourceC.ToLower() == "program")
                {
                    recordsAffected += await _addressRepository.UpdateProgramServiceAddress(address, logCommand);

                    if (recordsAffected > 0)
                    {
                        response = new GenericServiceResponse
                        {
                            Entity             = $"Update Address Complete. Rows updated = {recordsAffected}",
                            Success            = true,
                            RestResponseStatus = GenericServiceResponse.RestStatus.Success
                        };
                    }
                    else
                    {
                        response = new GenericServiceResponse
                        {
                            Entity = $"Failure - Could not find Record for update, {recordsAffected}. " +
                                     $"Records Affected with required fields: " +
                                     $"-- Customer Guid: {addressPayload._PayloadBody.CmcCustomerGuidC} " +
                                     $"-- Address Source: {addressPayload._PayloadBody.Address_SourceC} " +
                                     $"-- Address Type: {addressPayload._PayloadBody.AddressTypeC} " +
                                     $"-- AddressTypeGuid: {addressTypeGuid} ",
                            Success            = false,
                            RestResponseStatus = GenericServiceResponse.RestStatus.Success
                        };
                    }
                }
                else
                {
                    recordsAffected += await _addressRepository.InsertAddress(address, logCommand);

                    if (recordsAffected > 0)
                    {
                        response = new GenericServiceResponse
                        {
                            Entity             = $"Insert Address Related Tables Successful, rows added/updated = {recordsAffected}",
                            Success            = true,
                            RestResponseStatus = GenericServiceResponse.RestStatus.Error
                        };
                    }
                    else
                    {
                        response = new GenericServiceResponse
                        {
                            Entity             = $"Failure - Could not insert into Address Table",
                            Success            = false,
                            RestResponseStatus = GenericServiceResponse.RestStatus.Error
                        };
                    }
                }

                logCommand.LogMessage = string.Format($"{Service}.{method} completed");
                _logHandler.HandleLog(logCommand);

                return(response);
            }
            catch (Exception ex)
            {
                ex.Data.Add("Point of Failure", UpdateEventState);
                AppLogger.LogException(_loggingInstance, ex.Message, ex);
                return(ServiceHelper.SetErrorGenericServiceResponse(ex));
            }
        }
예제 #42
0
 public Task <GenericServiceResponse> GetSchedulingList(LogCommand logCommand)
 {
     throw new NotImplementedException();
 }
예제 #43
0
        public async Task <Subprogram> GetSubProgramNameFromSubProgramGuid(Guid?SubProgramGuid, LogCommand logCommand)
        {
            //Logging Helper for Method
            const string methodName = "GetSubProgramNameFromSubProgramGuid";

            //Query Used by Dapper
            var query =
                $" select * from {SubProgramTable} " +
                " where SubProgramId = @SubProgramGuid  ";

            //Log the input
            logCommand.LogMessage = $"{Repository}.{methodName} Starting input parameter SubProgramGuid={SubProgramGuid}" + Environment.NewLine +
                                    $"Query: {query}";
            _logHandler.HandleLog(logCommand);


            using (var connection = _connectionFactory.GetConnection)
            {
                //Await the response
                var _SubProgram = await connection.QueryFirstAsync <Subprogram>(query, new { SubProgramGuid });

                connection.Close();

                //Log the output
                logCommand.LogMessage = $"{Repository}.{methodName} completed";
                _logHandler.HandleLog(logCommand);

                return(_SubProgram);
            }
        }
예제 #44
0
        /// <summary>
        ///     SendLog(). It is used to request for FreeSwitch log.
        /// </summary>
        /// <param name="level">The log level to specify</param>
        /// <returns></returns>
        public async Task SetLogLevel(EslLogLevels level)
        {
            var command = new LogCommand(level);

            await SendAsync(command);
        }
예제 #45
0
 public Task <Program> GetProgramFromCustomerGuid(Guid CustomerGuid, LogCommand logCommand)
 {
     throw new NotImplementedException();
 }