public bool IsMet(Tasks.IUpdateTask task)
        {
            if (Timestamp == DateTime.MinValue)
                return true;

            string localPath = !string.IsNullOrEmpty(LocalPath)
                                   ? LocalPath
                                   : Utils.Reflection.GetNauAttribute(task, "LocalPath") as string;
            if (string.IsNullOrEmpty(localPath) || !File.Exists(localPath))
                return true;

            // File timestamps seem to be off by a little bit (conversion rounding?), so the code below
            // gets around that
            DateTime dt = File.GetLastWriteTime(localPath);
            long localPlus = dt.AddSeconds(2).ToFileTimeUtc();
            long localMinus = dt.AddSeconds(-2).ToFileTimeUtc();
            long remoteFileDateTime = Timestamp.ToFileTimeUtc();

            bool result;
            switch (ComparisonType)
            {
                case "newer":
                    result = localMinus > remoteFileDateTime;
                    break;
                case "is":
                    result = localMinus <= remoteFileDateTime && remoteFileDateTime <= localPlus;
                    break;
                default:
                    result = localPlus < remoteFileDateTime;
                    break;
            }
            return result;
        }
        public override void TaskComplete(Tasks.Base sender, ICommandReply reply)
        {
            Type t = sender.GetType();

            if (t == typeof(Tasks.DownloadResource))
            {
                Tasks.DownloadResource task = (Tasks.DownloadResource)sender;
                _reply = reply;
                Resource = task.Resource;
                Remainder = task.Remainder;
                RunTaskProcess(new Tasks.CheckResourcePermissions(_db, Resource, _requestingPartyType,
                    _session, Security.Authorization.ResourcePermissionType.Checkout, _sendTimeout, _receiveTimeout,
                    _sendBufferSize, _receiveBufferSize));
            }
            else if (t == typeof(Tasks.CheckResourcePermissions))
            {
                Tasks.CheckResourcePermissions task = (Tasks.CheckResourcePermissions)sender;
                if (!task.IsAuthorized)
                {
                    TriggerOnAuthorizationDenied(task);
                    return;
                }
                TriggerOnComplete(_reply, new Tuple<Data.Resource, JObject>(Resource, Remainder));
            }
            else
            {
                TriggerOnError(sender, reply.ToString(), null);
            }
        }
Beispiel #3
0
        /// <summary>
        /// Calls stored procedure to obtain list of alerts to be notified.
        /// </summary>
        /// <param name="toTime">Alerts scheduled till this time</param>
        /// <param name="fromTime">Alerts scheduled to run beginning this time</param>
        /// <returns>List of tasks</returns>
        internal Tasks<SearchAlertsTaskBEO> GetActiveAlerts(DateTime toTime, DateTime fromTime)
        {
            Tasks<SearchAlertsTaskBEO> tasks = new Tasks<SearchAlertsTaskBEO>();

            // create command object
            DbCommand dbCommand = AlertsDbManager.GetStoredProcCommand(Constants.STOREDPROCEDURE_GET_ALERTS_TOBE_NOTIFIED);

            // add in parameters
            // param - to time, alerts till what time to be retrieved.
            AlertsDbManager.AddInParameter(dbCommand, Constants.GA_TO_TIMESTAMP, DbType.DateTime, toTime);
            AlertsDbManager.AddInParameter(dbCommand, Constants.GA_FROM_TIMESTAMP, DbType.DateTime, fromTime);

            // call stored procedure
            DataSet dataset = AlertsDbManager.ExecuteDataSet(dbCommand);

            // Create tasks - each search alert to be notified is a task.
            // Get all Alerts and add them to tasks.
            if (dataset != null)
            {
                foreach (SearchAlertsTaskBEO tmpSearchAlertsTask in (from DataTable dataTable in dataset.Tables from DataRow dataRow in dataTable.Rows select dataRow).Select(ConvertToTask).Where(tmpSearchAlertsTask => tmpSearchAlertsTask != null))
                {
                    tasks.Add(tmpSearchAlertsTask);
                }
            }

            // return list of active alerts objects.
            return tasks;
        }
        public override void TaskComplete(Tasks.Base sender, ICommandReply reply)
        {
            Type t = sender.GetType();

            if (t == typeof(Tasks.DetermineIfExists))
            {
                if (reply.IsError)
                {
                    _onCompleteSent = true;
                    IsInstalled = false;
                    TriggerOnComplete(reply, IsInstalled);
                    return;
                }

                _count++;
                if (_count >= 5 && !_onCompleteSent)
                {
                    _onCompleteSent = true;
                    IsInstalled = true;
                    TriggerOnComplete(null, IsInstalled);
                }
            }
            else
            {
                TriggerOnError(sender, reply.ToString(), null);
            }
        }
Beispiel #5
0
        /// <summary>
        /// Возвращает задачу по идентификатору
        /// </summary>
        /// <param name="taskId">Идентификатор, тип Guid</param>
        /// <returns></returns>
        public Tasks GetTaskById(Guid taskId)
        {
            Tasks task=new Tasks();

            try
            {
                SqlCommand sqlCommand = new SqlCommand(string.Format("Select * FROM Tasks Where [TaskId]='{0}'", taskId), _sqlConn);
                _sqlConn.Open();
                SqlDataReader reader = sqlCommand.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        task = new Tasks(
                            reader.GetGuid(0), reader["Title"].ToString(), reader["Job"].ToString(),
                            (DateTime) reader["StartedOn"], (DateTime) reader["Finished"], reader.GetInt32(5),
                            reader.GetGuid(6));
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (_sqlConn.State == ConnectionState.Open)
                {
                    _sqlConn.Close();
                }
            }

            return task;
        }
 public override void TaskComplete(Tasks.Base sender, ICommandReply reply)
 {
     Tasks.DownloadUser task = (Tasks.DownloadUser)sender;
     Session = _sessionMgr.AuthenticateUser(_db, task.User, _password);
     IsAuthenticated = (Session != null);
     TriggerOnComplete(null, new Tuple<Security.Session, bool>(Session, IsAuthenticated));
 }
        public bool IsMet(Tasks.IUpdateTask task)
        {
            if (FileSize <= 0)
                return true;

            var localPath = !string.IsNullOrEmpty(LocalPath)
                ? LocalPath
                : Utils.Reflection.GetNauAttribute(task, "LocalPath") as string;

            // local path is invalid, we can't check for anything so we will return as if the condition was met
            if (string.IsNullOrEmpty(localPath))
                return true;

            long localFileSize = 0;
            if (File.Exists(localPath))
            {
                var fi = new FileInfo(localPath);
                localFileSize = fi.Length;
            }

            switch (ComparisonType)
            {
                case "above":
                    return FileSize < localFileSize;
                case "is":
                    return FileSize == localFileSize;
            }
            return FileSize > localFileSize;
        }
        public override void TaskComplete(Tasks.Base sender, ICommandReply reply)
        {
            Type t = sender.GetType();

            if (t == typeof(Tasks.DownloadGlobalPermissions))
            {
                Tasks.DownloadGlobalPermissions task = (Tasks.DownloadGlobalPermissions)sender;
                _gur = task.GlobalUsageRights;
                RunTaskProcess(new Tasks.CheckGlobalPermissions(_db, _gur, _requestingPartyType,
                    _session, Security.Authorization.GlobalPermissionType.CreateUser, _sendTimeout, _receiveTimeout,
                    _sendBufferSize, _receiveBufferSize));
            }
            else if (t == typeof(Tasks.CheckGlobalPermissions))
            {
                Tasks.CheckGlobalPermissions task = (Tasks.CheckGlobalPermissions)sender;
                if (!task.IsAuthorized)
                {
                    TriggerOnAuthorizationDenied(task);
                    return;
                }
                RunTaskProcess(new Tasks.UploadUser(_db, _user, _sendTimeout, _receiveTimeout,
                    _sendBufferSize, _receiveBufferSize));
            }
            else if (t == typeof(Tasks.UploadUser))
            {
                TriggerOnComplete(reply, _user);
            }
            else
            {
                TriggerOnError(sender, reply.ToString(), null);
            }
        }
Beispiel #9
0
 public SpringboardElement( Tasks.Task task, int layoutId, string iconStr, string elementLabel )
 {
     Task = task;
     LayoutId = layoutId;
     IconStr = iconStr;
     ElementLabel = elementLabel;
 }
Beispiel #10
0
        protected virtual void RunTaskProcess(Tasks.Base task)
        {
            task.OnActionChanged += delegate(Tasks.Base sender, EngineActionType actionType, bool willSendProgress)
            {
                TriggerOnActionChanged(sender, actionType, willSendProgress);
            };
            task.OnAuthorizationDenied += delegate(Tasks.Base sender)
            {
                TriggerOnAuthorizationDenied(sender);
            };
            task.OnComplete += TaskComplete;
            task.OnError += delegate(Tasks.Base sender, string message, Exception exception)
            {
                TriggerOnError(sender, message, exception);
            };
            task.OnProgress += delegate(Tasks.Base sender, OpenDMS.Networking.Protocols.Tcp.DirectionType direction, int packetSize, decimal sendPercentComplete, decimal receivePercentComplete)
            {
                TriggerOnProgress(sender, direction, packetSize, sendPercentComplete, receivePercentComplete);
            };
            task.OnTimeout += delegate(Tasks.Base sender)
            {
                TriggerOnTimeout(sender);
            };

            task.Process();
        }
		public bool IsMet(Tasks.IUpdateTask task)
		{
			var localPath = !string.IsNullOrEmpty(LocalPath)
				? LocalPath
				: Utils.Reflection.GetNauAttribute(task, "LocalPath") as string;

			// local path is invalid, we can't check for anything so we will return as if the condition was met
			if (string.IsNullOrEmpty(localPath))
				return true;

			// if the file doesn't exist it has a null version, and therefore the condition result depends on the ComparisonType
			if (!File.Exists(localPath))
				return ComparisonType.Equals("below", StringComparison.InvariantCultureIgnoreCase);

			var versionInfo = FileVersionInfo.GetVersionInfo(localPath);
			if (versionInfo.FileVersion == null) return true; // perform the update if no version info is found

			var localVersion = new Version(versionInfo.FileMajorPart, versionInfo.FileMinorPart, versionInfo.FileBuildPart, versionInfo.FilePrivatePart);
			var updateVersion = Version != null ? new Version(Version) : new Version();

			switch (ComparisonType)
			{
				case "above":
					return updateVersion < localVersion;
				case "is":
					return updateVersion == localVersion;
				default:
					return updateVersion > localVersion;
			}
		}
        public bool IsMet(Tasks.IUpdateTask task)
        {
            string localPath = !string.IsNullOrEmpty(LocalPath)
                                   ? LocalPath
                                   : Utils.Reflection.GetNauAttribute(task, "LocalPath") as string;
            if (string.IsNullOrEmpty(localPath) || !File.Exists(localPath))
                return true;

            var versionInfo = FileVersionInfo.GetVersionInfo(localPath);
            if (versionInfo.FileVersion == null) return true; // perform the update if no version info is found

            string versionString = versionInfo.FileVersion.Replace(", ", ".");
            Version localVersion = new Version(versionString);
            Version updateVersion = new Version(Version);

            switch (ComparisonType)
            {
                case "above":
                    return updateVersion < localVersion;
                case "is":
                    return updateVersion == localVersion;
                default:
                    return updateVersion > localVersion;
            }
        }
        void l_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Label l = (Label)sender;
            string s = l.Content.ToString();
            Tasks t = new Tasks();

            bodyBrowser.NavigateToString(t.FindTasksBySubject(s).Body);
        }
 private void Clean() {
     this.Sysid = null;
     this.Tasksysid = null;
     this.Tag = string.Empty;
     this.Createdate = null;
     this.Active = null;
     this.Tasks = null;
 }
Beispiel #15
0
        // .ctor
        public Scheduler()
        {
            m_Jobs = new Jobs();
            m_Triggers = new Triggers();
            m_Tasks = new Tasks();

            //_timer = new Timer(OnNextEvent, null, Timeout.Infinite, Timeout.Infinite);
        }
        public bool IsMet(Tasks.IUpdateTask task)
        {
            string localPath = !string.IsNullOrEmpty(LocalPath) ? LocalPath : Utils.Reflection.GetNauAttribute(task, "LocalPath") as string;
            if (string.IsNullOrEmpty(localPath))
                return true;

            return File.Exists(localPath);
        }
        public override void TaskComplete(Tasks.Base sender, ICommandReply reply)
        {
            Type t = sender.GetType();
            
            if (t == typeof(Tasks.CheckResourcePermissions))
            {
                Tasks.CheckResourcePermissions task = (Tasks.CheckResourcePermissions)sender;
                if (!task.IsAuthorized)
                {
                    TriggerOnAuthorizationDenied(task);
                    return;
                }

                // First, we load up revisions
                for (int i = 0; i < _resource.VersionIds.Count; i++)
                {
                    _revisions.Add(_resource.VersionIds[i], null);
                }

                // Now our _revisions holds indexes for all version ids
                // Dispatch all our heads to get the revisions
                // *note* do not combine these loops - we want the full dictionary before starting
                for (int i = 0; i < _resource.VersionIds.Count; i++)
                {
                    RunTaskProcess(new Tasks.HeadVersion(_db, _resource.VersionIds[i], _sendTimeout, 
                        _receiveTimeout, _sendBufferSize, _receiveBufferSize));
                }
            }
            else if (t == typeof(Tasks.HeadVersion))
            {
                Tasks.HeadVersion task = (Tasks.HeadVersion)sender;
                
                if (!_revisions.ContainsKey(task.VersionId))
                {
                    TriggerOnError(task, "The id '" + task.VersionId.ToString() + "' could not be found.", new KeyNotFoundException());
                    return;
                }
                
                lock (_revisions)
                {
                    _receivedCount++;
                    _revisions[task.VersionId] = task.Revision;
                    if (_revisions.Count == _receivedCount)
                    {
                        TriggerOnComplete(reply, _revisions);
                    }
                    else
                    {
                        TriggerOnProgress(task, Networking.Protocols.Tcp.DirectionType.Download, -1, -1,
                            ((decimal)((decimal)_receivedCount / (decimal)_revisions.Count)));
                    }
                }
            }
            else
            {
                TriggerOnError(sender, reply.ToString(), null);
            }
        }
 private void Clean() {
     this.Sysid = null;
     this.Publicid = null;
     this._tasksysid = null;
     this.Keypath = string.Empty;
     this.Keyvalue = string.Empty;
     this.Active = null;
     this.Tasks = null;
 }
        public override void TaskComplete(Tasks.Base sender, ICommandReply reply)
        {
            Type t = sender.GetType();

            if (t == typeof(Tasks.DownloadResource))
            {
                Tasks.DownloadResource task = (Tasks.DownloadResource)sender;
                _resource = task.Resource;
                _resourceRemainder = task.Remainder;
                RunTaskProcess(new Tasks.CheckResourcePermissions(_db, _resource, _requestingPartyType,
                    _session, Security.Authorization.ResourcePermissionType.Checkout, _sendTimeout, _receiveTimeout,
                    _sendBufferSize, _receiveBufferSize));
            }
            else if (t == typeof(Tasks.CheckResourcePermissions))
            {
                Tasks.CheckResourcePermissions task = (Tasks.CheckResourcePermissions)sender;
                if (!task.IsAuthorized)
                {
                    TriggerOnAuthorizationDenied(task);
                    return;
                }
                RunTaskProcess(new Tasks.MarkResourceForCheckout(_resource, _session.User.Username, _sendTimeout, _receiveTimeout,
                    _sendBufferSize, _receiveBufferSize));
            }
            else if (t == typeof(Tasks.MarkResourceForCheckout))
            {
                List<Exception> errors;
                Tasks.MarkResourceForCheckout task = (Tasks.MarkResourceForCheckout)sender;
                Transitions.Resource txResource = new Transitions.Resource();
                Model.Document doc = txResource.Transition(_resource, out errors);
                doc.CombineWith(_resourceRemainder);
                RunTaskProcess(new Tasks.UploadResource(_db, doc, _sendTimeout, _receiveTimeout,
                    _sendBufferSize, _receiveBufferSize));
            }
            else if (t == typeof(Tasks.UploadResource))
            {
                Tasks.UploadResource task = (Tasks.UploadResource)sender;
                if(reply.IsError)
                {
                    TriggerOnError(sender, reply.ToString(), null);
                    return;
                }
                RunTaskProcess(new Tasks.DownloadVersion(_db, _id, _sendTimeout, _receiveTimeout, 
                    _sendBufferSize, _receiveBufferSize));
            }
            else if (t == typeof(Tasks.DownloadVersion))
            {
                Tasks.DownloadVersion task = (Tasks.DownloadVersion)sender;
                Version = task.Version;
                Remainder = task.Remainder;
                TriggerOnComplete(reply, new Tuple<Data.Version, JObject>(Version, Remainder));
            }
            else
            {
                TriggerOnError(sender, reply.ToString(), null);
            }
        }
Beispiel #20
0
        public SaveService(Tasks tasks)
        {
            _tasks = tasks;

            _timer = new DispatcherTimer(DispatcherPriority.Normal);
            _timer.Tick += CheckToSave;
            
            // Don't set this too fast or you will lock up the connection pool with the maximum 25 connections
            _timer.Interval = TimeSpan.FromSeconds(1);
        }
 public IServiceResults<int> AddUserTask(Tasks model)
 {
     _task.Add(model);
     var saveResult = _uow.SaveChanges();
     return new ServiceResults<int>
     {
         IsSuccessfull = saveResult.ToBool(),
         Message = saveResult.ToMessage(BusinessMessage.Error),
         Result = model.TaskId
     };
 }
Beispiel #22
0
 protected void TriggerOnActionChanged(Tasks.Base task, EngineActionType actionType, bool willSendProgress)
 {
     try
     {
         if (OnActionChanged != null) OnActionChanged(this, task, actionType, willSendProgress);
     }
     catch (System.Exception e)
     {
         Logger.Storage.Error("An exception occurred while calling the OnActionChanged event.", e);
         throw;
     }
 }
Beispiel #23
0
 public ActionResult Create(Tasks model)
 {
     try
     {
         _taskService.CreateTask(model);
         return RedirectToAction("Index");
     }
     catch
     {
         _logger.Error(string.Format("Failed to create task : {0}:\n type {1}", model.Name, model.TaskType));
         return View();
     }
 }
Beispiel #24
0
 protected LogEntry(int eventId, Keywords keyword, Opcodes opcode, Tasks task, Levels level, EventSource eventSource, int version, string message, Payload payload, DateTime created)
 {
     Id = Guid.NewGuid();
     EventId = eventId;
     Keyword = keyword;
     Opcode = opcode;
     Task = task;
     Level = level;
     EventSource = eventSource;
     Version = version;
     Message = message;
     Payload = payload;
     Created = created;
 }
Beispiel #25
0
        public FtpLib(Tasks.TaskBase callingTask, Util.BuildProgressInformation buildProgressInformation)
        {
            CallingTask = callingTask;
            bpi = buildProgressInformation;

            this.FtpServer = new EnterpriseDT.Net.Ftp.FTPConnection();

            this.FtpServer.ReplyReceived += HandleMessages;

            this.FtpServer.CommandSent += HandleMessages;

            this.FtpServer.Downloaded += new EnterpriseDT.Net.Ftp.FTPFileTransferEventHandler(FtpServer_Downloaded);

            this.FtpServer.Uploaded += new EnterpriseDT.Net.Ftp.FTPFileTransferEventHandler(FtpServer_Uploaded);
        }
Beispiel #26
0
		// TODO: Work with enums on code and Attributes to get a proper and full OS version comparison
		// use http://stackoverflow.com/questions/545666/how-to-translate-ms-windows-os-version-numbers-into-product-names-in-net
		// and http://msdn.microsoft.com/en-us/library/ms724429(VS.85).aspx

		public bool IsMet(Tasks.IUpdateTask task)
		{
			var is64Bit = Is64BitOperatingSystem();

			if (OsBits == 32 && OsBits != 64)
				return true;

			// OS bitness check, if requested
			if (OsBits == 32 && is64Bit)
				return false;
			if (OsBits == 64 && !is64Bit)
				return false;

			return true;
		}
Beispiel #27
0
        protected void TriggerOnAuthorizationDenied(Tasks.Base task)
        {
            if (OnAuthorizationDenied == null)
                throw new NotImplementedException("OnAuthorizationDenied must be implemented.");

            try
            {
                OnAuthorizationDenied(this, task);
            }
            catch (System.Exception e)
            {
                Logger.Storage.Error("An exception occurred while calling the OnAuthorizationDenied event.", e);
                throw;
            }
        }
        public void visit(SingleTask task)
        {
            DataClassesDataContext local = new DataClassesDataContext();

            Tasks newTask = new Tasks();
            newTask.Title = task.Title;
            newTask.Description = task.Description;
            newTask.CreationDate = DateTime.Now;
            newTask.DueDate = task.DueDate;
            newTask.Owner = 0; //TODO: simplify the client database. This identifier is useless in local mode.
            //TODO: save task.context and task.reminder (add context to the Tasks table in both databases).

            local.Tasks.InsertOnSubmit(newTask);
            local.SubmitChanges();
        }
        public override void TaskComplete(Tasks.Base sender, ICommandReply reply)
        {
            Type t = sender.GetType();

            if (t == typeof(Tasks.DownloadResource))
            {
                Tasks.DownloadResource task = (Tasks.DownloadResource)sender;
                Resource = task.Resource;
                ResourceRemainder = task.Remainder;
                RunTaskProcess(new Tasks.CheckResourcePermissions(_db, Resource, _requestingPartyType,
                    _session, Security.Authorization.ResourcePermissionType.Checkout, _sendTimeout, _receiveTimeout,
                    _sendBufferSize, _receiveBufferSize));
            }
            else if (t == typeof(Tasks.CheckResourcePermissions))
            {
                Tasks.CheckResourcePermissions task = (Tasks.CheckResourcePermissions)sender;
                if (!task.IsAuthorized)
                {
                    TriggerOnAuthorizationDenied(task);
                    return;
                }
                RunTaskProcess(new Tasks.MarkResourceForCheckout(Resource, _session.User.Username, _sendTimeout, _receiveTimeout,
                    _sendBufferSize, _receiveBufferSize));
            }
            else if (t == typeof(Tasks.MarkResourceForCheckout))
            {
                Tasks.MarkResourceForCheckout task = (Tasks.MarkResourceForCheckout)sender;
                Resource = task.Resource;
                RunTaskProcess(new Tasks.UploadResource(_db, Resource, _sendTimeout, _receiveTimeout,
                    _sendBufferSize, _receiveBufferSize));
            }
            else if (t == typeof(Tasks.UploadResource))
            {
                RunTaskProcess(new Tasks.DownloadVersion(_db, Resource.CurrentVersionId, _sendTimeout, 
                    _receiveTimeout, _sendBufferSize, _receiveBufferSize));
            }
            else if (t == typeof(Tasks.DownloadVersion))
            {
                Tasks.DownloadVersion task = (Tasks.DownloadVersion)sender;
                Version = task.Version;
                VersionRemainder = task.Remainder;
                TriggerOnComplete(reply, new Tuple<Data.Resource, JObject, Data.Version, JObject>(Resource, ResourceRemainder, Version, VersionRemainder));
            }
            else
            {
                TriggerOnError(sender, reply.ToString(), null);
            }
        }
        public MainWindow()
        {
            Tasks t = new Tasks();
            TaskData td;
            MyTaskList = new TaskDataList();

            InitializeComponent();

            foreach (string s in t.RetrieveDistinctTaskCategories())
            {
                td = new TaskData();
                td.Category = s;
                MyTaskList.Add(td);
            }

            this.DataContext = this;
        }
        public bool Delete_Task(int taskID)
        {
            ChangeTracker.DetectChanges();

            Task taskBD = Tasks.Where(t => t.ID == taskID).FirstOrDefault();

            if (taskBD == null)
            {
                return(true);
            }

            //Проверим, есть ли задача в избранном у пользователей
            var userDeleteTask = UserTasks.Where(ut => ut.TaskID == taskBD.ID).ToList();

            if (userDeleteTask.Count > 0)
            {
                var users        = userDeleteTask.Select(u => u.User.UserName);
                var usersNames   = String.Join("\n", users);
                var dialogResult = System.Windows.MessageBox.Show($"Данная задача содержится в избранном у следующих пользователей:\n{usersNames}", "Предупреждение",
                                                                  MessageBoxButton.OK, MessageBoxImage.Information);
                return(false);
            }

            //Проверим, есть ли у пользователей работы по задаче
            var worksDeleteTask = Works.Where(w => w.TaskID == taskBD.ID).ToList();

            if (worksDeleteTask.Count > 0)
            {
                var users      = worksDeleteTask.Select(w => w.User.UserName);
                var usersNames = String.Join("\n", users);
                if (System.Windows.MessageBox.Show($"По задаче '{taskBD.TaskName}' есть работы у следующих пользователей:\n{usersNames}. Продолжить удаление?", "Предупреждение",
                                                   MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
                {
                    return(false);
                }
            }

            List <Task> childTasksBD = (from t in Tasks where t.ParentTaskID == taskID select t).ToList();

            foreach (var t in childTasksBD)
            {
                t.ParentTaskID = taskBD.ParentTaskID;
            }

            List <Work> worksBD = (from w in Works where w.TaskID == taskID select w).ToList();

            foreach (var w in worksBD)
            {
                Delete_AttrValuesFields_ForWork(w.ID);
                Works.Remove(w);
            }

            if (taskBD != null)
            {
                Tasks.Remove(taskBD);
            }

            WriteLog(taskID, taskBD.TaskName, DateTime.Now, "DELETE");
            SaveChanges();
            return(true);
        }
Beispiel #32
0
 public ActionResult EditTask(Tasks task)
 {
     TasksHelper.TaskHelper.EditTask(task);
     return(RedirectToAction("Index"));
 }
Beispiel #33
0
        public async Task <NewErrorModel> PrintAndSend(PrintAndSendModel printAndSendModel)
        {
            try
            {
                string       TaskId    = printAndSendModel.TaskId;
                string       UserId    = printAndSendModel.UserId;
                string       OldPath   = printAndSendModel.OldPath;
                PDFHelperNew pdfHelper = new PDFHelperNew();
                using (DDContext context = new DDContext())
                {
                    //获取表单信息
                    Tasks  tasks     = context.Tasks.Where(t => t.TaskId.ToString() == TaskId && t.NodeId == 0).First();
                    string FlowId    = tasks.FlowId.ToString();
                    string ProjectId = tasks.ProjectId;

                    //判断流程是否已结束
                    List <Tasks> tasksList = context.Tasks.Where(t => t.TaskId.ToString() == TaskId && t.IsSend != true && t.State == 0).ToList();
                    if (tasksList.Count > 0)
                    {
                        return(new NewErrorModel()
                        {
                            error = new Error(1, "流程未结束!", "")
                            {
                            },
                        });
                    }

                    List <Purchase> PurchaseList = context.Purchase.Where(u => u.TaskId == TaskId).ToList();

                    var SelectPurchaseList = from p in PurchaseList
                                             select new
                    {
                        p.DrawingNo,
                        p.Name,
                        p.Count,
                        p.MaterialScience,
                        p.Unit,
                        p.SingleWeight,
                        p.AllWeight,
                        p.Sorts,
                        p.NeedTime,
                        p.Mark
                    };

                    DataTable dtSourse = DtLinqOperators.CopyToDataTable(SelectPurchaseList);
                    //ClassChangeHelper.ToDataTable(SelectPurchaseList);
                    List <NodeInfo> NodeInfoList = context.NodeInfo.Where(u => u.FlowId == FlowId && u.NodeId != 0 && u.NodeName != "结束" && u.IsSend != true).ToList();
                    foreach (NodeInfo nodeInfo in NodeInfoList)
                    {
                        if (string.IsNullOrEmpty(nodeInfo.NodePeople))
                        {
                            string strNodePeople = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyMan;
                            string ApplyTime     = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyTime;
                            nodeInfo.NodePeople = strNodePeople + "  " + ApplyTime;
                        }
                        else
                        {
                            string ApplyTime = context.Tasks.Where(q => q.TaskId.ToString() == TaskId && q.NodeId == nodeInfo.NodeId).First().ApplyTime;
                            nodeInfo.NodePeople = nodeInfo.NodePeople + "  " + ApplyTime;
                        }
                    }
                    DataTable dtApproveView = ClassChangeHelper.ToDataTable(NodeInfoList);
                    string    FlowName      = context.Flows.Where(f => f.FlowId.ToString() == FlowId).First().FlowName.ToString();

                    ProjectInfo projectInfo = context.ProjectInfo.Where(p => p.ProjectId == ProjectId).First();
                    string      ProjectName = projectInfo.ProjectName;
                    string      ProjectNo   = projectInfo.ProjectId;
                    //绘制BOM表单PDF
                    List <string> contentList = new List <string>()
                    {
                        "序号", "代号", "名称", "数量", "材料", "单位", "单重", "总重", "类别", "需用日期", "备注"
                    };

                    float[] contentWithList = new float[]
                    {
                        50, 80, 80, 30, 60, 30, 60, 60, 60, 60, 60
                    };

                    string path = pdfHelper.GeneratePDF(FlowName, TaskId, tasks.ApplyMan, tasks.Dept, tasks.ApplyTime,
                                                        ProjectName, ProjectNo, "1", 380, 710, contentList, contentWithList, dtSourse, dtApproveView, null);
                    string RelativePath = "~/UploadFile/PDF/" + Path.GetFileName(path);

                    string[] Paths = OldPath.Split(',');

                    List <string> newPaths = new List <string>();
                    RelativePath = AppDomain.CurrentDomain.BaseDirectory + RelativePath.Substring(2, RelativePath.Length - 2).Replace('/', '\\');
                    newPaths.Add(RelativePath);
                    foreach (string pathChild in Paths)
                    {
                        string AbPath = AppDomain.CurrentDomain.BaseDirectory + pathChild.Substring(2, pathChild.Length - 2);
                        //PDF盖章 保存路径
                        newPaths.Add(pdfHelper.PDFWatermark(AbPath,
                                                            string.Format(@"{0}\UploadFile\PDF\{1}",
                                                                          AppDomain.CurrentDomain.BaseDirectory, Path.GetFileName(pathChild)),
                                                            string.Format(@"{0}\Content\images\受控章.png", AppDomain.CurrentDomain.BaseDirectory),
                                                            100, 100));
                    }
                    string SavePath = string.Format(@"{0}\UploadFile\Ionic\{1}.zip", AppDomain.CurrentDomain.BaseDirectory, "图纸审核" + DateTime.Now.ToString("yyyyMMddHHmmss"));
                    //文件压缩打包
                    IonicHelper.CompressMulti(newPaths, SavePath, false);

                    //上传盯盘获取MediaId
                    DingTalkServersController otherController = new DingTalkServersController();
                    SavePath = string.Format(@"~\UploadFile\Ionic\{0}", Path.GetFileName(SavePath));
                    var resultUploadMedia = await otherController.UploadMedia(SavePath);

                    //推送用户
                    FileSendModel fileSendModel = JsonConvert.DeserializeObject <FileSendModel>(resultUploadMedia);
                    fileSendModel.UserId = UserId;
                    var result = await otherController.SendFileMessage(fileSendModel);

                    return(new NewErrorModel()
                    {
                        error = new Error(0, "已推送至钉钉!", "")
                        {
                        },
                    });
                }
            }
            catch (Exception ex)
            {
                return(new NewErrorModel()
                {
                    error = new Error(2, ex.Message, "")
                    {
                    },
                });
            }
        }
Beispiel #34
0
        private async Task Backup()
        {
            StatusBarVm.statusBarViewModel.Reset();
            await Task.Run(() =>
            {
                DebugHelper.WriteLine("{0} {1} {2} {3}", "[FModel]", "[BackupMenuItemViewModel]", "[Create]", $"{_backupFileName} is about to be created");
                StatusBarVm.statusBarViewModel.Set($"{Properties.Settings.Default.PakPath}", Properties.Resources.Loading);

                using FileStream fileStream = new FileStream(_backupFilePath, FileMode.Create);
                using LZ4EncoderStream compressionStream = LZ4Stream.Encode(fileStream, LZ4Level.L00_FAST);
                using BinaryWriter writer = new BinaryWriter(compressionStream);
                foreach (PakFileReader pakFile in MenuItems.pakFiles.GetPakFileReaders())
                {
                    if (pakFile.Info.bEncryptedIndex && pakFile.AesKey == null)
                    {
                        continue;
                    }

                    if (!Globals.CachedPakFiles.ContainsKey(pakFile.FileName))
                    {
                        pakFile.ReadIndex(pakFile.AesKey);
                        Globals.CachedPakFiles[pakFile.FileName] = pakFile;
                        StatusBarVm.statusBarViewModel.Set(string.Format(Properties.Resources.MountedPakTo, pakFile.FileName, pakFile.MountPoint), Properties.Resources.Loading);
                    }

                    foreach (var(_, entry) in pakFile)
                    {
                        // uasset or umap or idk
                        writer.Write(entry.Offset);
                        writer.Write(entry.Size);
                        writer.Write(entry.UncompressedSize);
                        writer.Write(entry.Encrypted);
                        writer.Write(entry.StructSize);
                        writer.Write(pakFile.MountPoint + entry.Name);
                        writer.Write(entry.CompressionMethodIndex);

                        // uexp
                        if (entry.Uexp != null)
                        {
                            writer.Write(entry.Uexp.Offset);
                            writer.Write(entry.Uexp.Size);
                            writer.Write(entry.Uexp.UncompressedSize);
                            writer.Write(entry.Uexp.Encrypted);
                            writer.Write(entry.Uexp.StructSize);
                            writer.Write(pakFile.MountPoint + entry.Uexp.Name);
                            writer.Write(entry.Uexp.CompressionMethodIndex);
                        }
                        // ubulk
                        if (entry.Ubulk != null)
                        {
                            writer.Write(entry.Ubulk.Offset);
                            writer.Write(entry.Ubulk.Size);
                            writer.Write(entry.Ubulk.UncompressedSize);
                            writer.Write(entry.Ubulk.Encrypted);
                            writer.Write(entry.Ubulk.StructSize);
                            writer.Write(pakFile.MountPoint + entry.Ubulk.Name);
                            writer.Write(entry.Ubulk.CompressionMethodIndex);
                        }
                    }
                }
            }).ContinueWith(t =>
            {
                if (t.Exception != null)
                {
                    Tasks.TaskCompleted(t.Exception);
                }
                else if (new FileInfo(_backupFilePath).Length > 0)
                {
                    DebugHelper.WriteLine("{0} {1} {2} {3}", "[FModel]", "[BackupMenuItemViewModel]", "[Create]", $"{_backupFileName} successfully created");
                    StatusBarVm.statusBarViewModel.Set(string.Format(Properties.Resources.CreateSuccess, _backupFileName), Properties.Resources.Success);
                    Globals.gNotifier.ShowCustomMessage(Properties.Resources.Success, string.Format(Properties.Resources.CreateSuccess, _backupFileName), "/FModel;component/Resources/check-circle.ico", _backupFilePath);
                }
                else
                {
                    File.Delete(_backupFilePath);
                    DebugHelper.WriteLine("{0} {1} {2} {3}", "[FModel]", "[BackupMenuItemViewModel]", "[Create]", $"{_backupFileName} is empty, hence deleted");
                    StatusBarVm.statusBarViewModel.Set(string.Format(Properties.Resources.CreateError, _backupFileName), Properties.Resources.Error);
                    Globals.gNotifier.ShowCustomMessage(Properties.Resources.Error, string.Format(Properties.Resources.CreateError, _backupFileName), "/FModel;component/Resources/alert.ico");
                }
            },
                            TaskScheduler.FromCurrentSynchronizationContext());
        }
Beispiel #35
0
        public void TestRemoveCloudServiceWithoutDeployments()
        {
            RemoveDeployments();

            clientMocks.ComputeManagementClientMock.Setup(
                c => c.Deployments.BeginDeletingBySlotAsync(It.IsAny <string>(), DeploymentSlot.Production, It.IsAny <CancellationToken>()))
            .Returns((string s, DeploymentSlot slot, CancellationToken cancellationToken) => Tasks.FromResult(new AzureOperationResponse
            {
                RequestId  = "req0",
                StatusCode = HttpStatusCode.OK
            }));

            clientMocks.ComputeManagementClientMock.Setup(
                c => c.HostedServices.DeleteAsync(It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .Returns(Tasks.FromResult(new AzureOperationResponse
            {
                RequestId  = "request000",
                StatusCode = HttpStatusCode.OK
            }));

            // Test
            client.RemoveCloudService(serviceName);

            // Assert
            clientMocks.ComputeManagementClientMock.Verify(
                c => c.Deployments.BeginDeletingBySlotAsync(serviceName, DeploymentSlot.Production, It.IsAny <CancellationToken>()), Times.Never);

            clientMocks.ComputeManagementClientMock.Verify(
                c => c.HostedServices.DeleteAsync(serviceName, It.IsAny <CancellationToken>()), Times.Once);
        }
 /// <inheritdoc />
 public override Task OnGetAsync(ObjectBox <T> obj)
 {
     OnGetObject?.Invoke(obj);
     return(Tasks.CompletedTask());
 }
        private bool StartAllTasks()
        {
            _tasksToStart.Clear();

            var enabledTasks = Tasks.Where(s => s.Settings.IsEnabled).ToArray();

            if (enabledTasks.Length > 0)
            {
                foreach (var task in enabledTasks)
                {
                    task.AddInfoLog(LocalizedStrings.Str2906);

                    if (task.Settings.Securities.IsEmpty())
                    {
                        task.AddInfoLog(LocalizedStrings.Str2907);
                        continue;
                    }

                    _tasksToStart.Add(task);
                }
            }

            if (_tasksToStart.IsEmpty())
            {
                return(false);
            }

            foreach (var task in _tasksToStart)
            {
                task.Started += OnStartedTask;
                task.Stopped += OnStopedTask;

                task.Start();
            }

            // TODO
            //// группировка по "корням"
            //foreach (var taskGroup in _tasksToStart.GroupBy(t =>
            //{
            //	while (t.Settings.DependFrom != null)
            //		t = t.Settings.DependFrom;

            //	return t.Id;
            //}))
            //{
            //	var tasks = new CachedSynchronizedSet<IHydraTask>();
            //	tasks.AddRange(taskGroup);

            //	ThreadingHelper.Thread(() =>
            //	{
            //		try
            //		{
            //			foreach (var task in tasks.Cache)
            //			{
            //				task.Start();

            //				if (task.State != TaskStates.Started)
            //					tasks.Remove(task);
            //			}

            //			while (true)
            //			{
            //				if (tasks.Cache.Length == 0)
            //					break;

            //				foreach (var task in tasks.Cache)
            //				{
            //					task.Process();

            //					if (task.)
            //				}
            //			}
            //		}
            //		catch (Exception ex)
            //		{
            //			_logManager.Application.AddErrorLog(ex);
            //		}
            //	})
            //	.Name("{0} Task thread".Put(Name))
            //	.Launch();
            //}

            return(true);
        }
Beispiel #38
0
        protected void btnShow3_Click(object sender, EventArgs e)
        {
            wizardData wData = readWizardSteps();

            wData.Step          = 4;
            wData.SelectedTasks = new List <string>();
            foreach (GridDataItem item in gridTasks.MasterTableView.Items)
            {
                CheckBox chk   = (CheckBox)item.FindControl("chk");
                string   value = item.GetDataKeyValue("ID").ToString();
                if (chk.Checked)
                {
                    wData.SelectedTasks.Add(value);
                }
            }
            //Session["wizardStep"] = wData;
            //showWizardSteps(wData);
            //gridSales.Rebind();
            //wizardData wData = readWizardSteps();
            using (var dbContext = new OTERTConnStr()) {
                try {
                    dbContext.Configuration.ProxyCreationEnabled = false;
                    OTERT_Entity.Invoices curInvoice;
                    curInvoice             = new OTERT_Entity.Invoices();
                    curInvoice.CustomerID  = wData.CustomerID;
                    curInvoice.DateFrom    = wData.DateFrom;
                    curInvoice.DateTo      = wData.DateTo;
                    curInvoice.RegNo       = wData.Code;
                    curInvoice.IsLocked    = wData.locked;
                    curInvoice.DatePaid    = wData.DatePayed;
                    curInvoice.DateCreated = wData.DateCreated;
                    TasksController tcont          = new TasksController();
                    List <TaskB>    invTasks       = tcont.GetTasksForInvoice(curInvoice.CustomerID, wData.DateFrom, wData.DateTo, wData.SelectedJobs, wData.SelectedTasks);
                    decimal         totalTasksCost = 0;
                    foreach (TaskB curTask in invTasks)
                    {
                        totalTasksCost += curTask.CostActual.GetValueOrDefault();
                    }
                    curInvoice.TasksLineAmount = totalTasksCost;
                    dbContext.Invoices.Add(curInvoice);
                    dbContext.SaveChanges();
                    foreach (TaskB curTask in invTasks)
                    {
                        TasksLine newTaskLine = new TasksLine();
                        newTaskLine.InvoiceID = curInvoice.ID;
                        newTaskLine.TaskID    = curTask.ID;
                        newTaskLine.JobID     = curTask.JobID.GetValueOrDefault();
                        Tasks curTaskEntity = dbContext.Tasks.Where(s => s.ID == curTask.ID).First();
                        curTaskEntity.IsLocked = true;
                        DateTime dnow = DateTime.Now;
                        //curTaskEntity.PaymentDateActual = dnow;
                        curTaskEntity.PaymentDateCalculated = wData.DatePayed;
                        curTaskEntity.PaymentDateOrder      = wData.DateCreated;
                        dbContext.TasksLine.Add(newTaskLine);
                    }
                    dbContext.SaveChanges();
                }
                catch (Exception) { }
                Response.Redirect("~/Pages/Invoices/InvoiceShow.aspx", false);
            }
        }
Beispiel #39
0
        /// <summary>
        /// <see cref="ChartElementBase"/> 형식의 Element 객체들을 XML Element Node로 생성합니다.
        /// </summary>
        /// <param name="writer">Element를 쓸 Writer</param>
        protected override void GenerateXmlElements(System.Xml.XmlWriter writer)
        {
            base.GenerateXmlElements(writer);

            //if (_categoryCollections != null)
            //    foreach (var categoryCollection in _categoryCollections)
            //        categoryCollection.WriteXmlElement(writer);
            if (_categoriesList != null)
            {
                foreach (var categories in _categoriesList)
                {
                    categories.WriteXmlElement(writer);
                }
            }

            //if (_processes != null)
            //{
            //    _processes.WriteXmlElement(writer);

            //    // NOTE : Processes 아래에 Task를 넣을 수 있다. 이렇게 하면, Task의 ProcessID 속성이 자연스럽게 매핑되므로, 조작하기 더 쉽다.
            //    foreach (var process in _processes.ProcessElements)
            //        foreach (var task in process.Tasks.TaskElements)
            //            Tasks.TaskElements.Add(task);
            //}
            if (_processes != null)
            {
                _processes.WriteXmlElement(writer);
                foreach (var proc in _processes)
                {
                    foreach (var task in proc.Tasks)
                    {
                        Tasks.Add(task);
                    }
                }
            }

            if (_dataTable != null)
            {
                _dataTable.WriteXmlElement(writer);
            }

            if (_tasks != null)
            {
                _tasks.WriteXmlElement(writer);
            }

            if (_milestones != null)
            {
                _milestones.WriteXmlElement(writer);
            }
            if (_connectors != null)
            {
                _connectors.WriteXmlElement(writer);
            }
            if (_trendlines != null)
            {
                _trendlines.WriteXmlElement(writer);
            }
            if (_legend != null)
            {
                _legend.WriteXmlElement(writer);
            }
        }
Beispiel #40
0
        } //end;

        //public static bool ParamValuesOK(int versionID)
        //{
        //var
        //    bool AllOK = true;
        //    File ParamsF;   //    : text;
        //    double[] parameters = new double[MaxARTparamsNo]; // of real;
        //    int noValues;  //   : word;
        //    int simul, pn;  //  : word; // {parameter counter}
        //    char key;      //        : char;
        //    int i;         //:word;

        //    TextBackGround (1); //  {blue background}
        //    ClrScr;
        //    LoggedConsole.WriteLine;
        //    LoggedConsole.WriteLine ("  CHECKING PARAMETER VALUES for Net version ",ARTversion);
        //    LoggedConsole.WriteLine;

        //    assign (ParamsF, ParamsFPath);       // {prepare parameters file}
        //    reset  (ParamsF);
        //    readln (ParamsF, NoSimulationsInRun);

        //    for (int simul= 0; simul < noSimulationsInRun; simul++)
        //    {
        //        ReadParameterValues(noValues, ParamsF, parameters);
        //        LoggedConsole.WriteLine ("  Line "+simul+ " is OK");

        //        //if (noValues != MaxARTparamsNo-1 )
        //        //{
        //        //    for (pn = 1 to maxARTParamsNo-1)    //  {display all 8 parameter values}
        //        //    LoggedConsole.WriteLine ("  (",pn,") ",paramNames[versionID, pn]:10,"  = ",parameters[pn]:7:4);
        //        //    LoggedConsole.WriteLine;
        //        //    LoggedConsole.WriteLine ("  Fault in values for simulation ",simul);
        //        //    LoggedConsole.WriteLine ("  Must have exactly  ",maxARTparamsNo-1, " parameter values.");
        //        //    LoggedConsole.WriteLine ("  Press any key to return to main menu.");
        //        //    key = readkey;
        //        //    ParamvaluesOK = false;
        //        //    exit;
        //        //}  //end;

        //        //{make sure theta is less than 1/sqrM}
        //        //if  ((versionID != verFuzzyART)&& (versionID != verfuzzyARTMAP) )
        //        //    if (parameters[Theta] >= (1/Sqrt(F1SizeofNeta)) )  )
        //        //{
        //        //    parameters[Theta] = (1/Sqrt(F1SizeofNeta) - 0.01);
        //        //    //for (pn = 1 to maxARTParamsNo-1)  //{display first 7 parameter values}
        //        //    //LoggedConsole.WriteLine ("  (",pn,") ",paramNames[versionID, pn]:10,"  = ",parameters[pn]:7:4);
        //        //    LoggedConsole.WriteLine;
        //        //    LoggedConsole.WriteLine ("  Fault in values for simulation " + simul);
        //        //    LoggedConsole.WriteLine ("  Theta must be < 1/sqrtM ie 1/sqrt(F1size of net a)");
        //        //    LoggedConsole.WriteLine ("  Have automatically set  theta = 1/sqrtM - 0.01");
        //        //    LoggedConsole.WriteLine ("  Press any key to continue.");
        //        //    key = readkey;
        //        //}  //end;

        //        //{calc sigma and rho*}
        //        if (versionID == verART2a )
        //        {
        //            Sigma = (Params[c]*ARTParams[d]) / (1-ARTParams[d]);
        //            if (sigma > 1)
        //            {
        //                //for (pn = 1 to maxARTParamsNo-1)  //{display first 7 parameter values}
        //                //LoggedConsole.WriteLine ("  ("+pn+") "+paramNames[versionID, pn]:10+"  = "+parameters[pn]:7:4);
        //                LoggedConsole.WriteLine;
        //                LoggedConsole.WriteLine ("  Fault in values for simulation ",simul);
        //                LoggedConsole.WriteLine ("  Sigma = cd/1-d > 1.0. Choose proper values for c & d");
        //                LoggedConsole.WriteLine ("  Press any key to continue.");
        //                key = readkey;
        //                ParamvaluesOK = false;
        //                exit;
        //            }  //end;
        //        }  //end; {if verionsID = verART2a}

        //    }  //end; {for simul = 1 to noSimulationsInRun do}

        //    Close (ParamsF);
        //    if (AllOK )
        //    {
        //        LoggedConsole.WriteLine; write ("  ALL OK! Press any key to continue ... ");
        //        key = readkey;
        //        clrscr;
        //    }  //end;
        //    ParamvaluesOK = AllOK;
        //}  //end;

        //{This method finds the class which gained max Score for a given F2 unit
        //and assigns that class label to the unit. It also calculates a Class
        //probability Score ie ClassNumber/TotalNumber for each F2unit.}
        //    public static void ScoreTrainingResults (noCommitted, noClasses:word; var classLabel:array of word; var classProb:array of real)
        //    {
        ////var
        //  uNo, cNo : word; {unit and class counter}
        //  ScoreArray : array[1..maxClassNo] of word;
        //  index, count{dummy var}, maxValue, total : word;

        //for (uNo = 1 to noCommitted{nodes}) //for all units
        //  {
        //    //{first transfer F2 Scores to Score array. This is to avoid passing
        //    // the zero index in the F2ScoreMatrix to the MaxIndex procedure}
        //    total = 0;
        //    for cNo = 1 to noClasses do
        //    {
        //      total   = total + F2ScoreMatrix^[uNo][cNo]; {sum over classes}
        //      ScoreArray[cNo] = F2ScoreMatrix^[uNo, cNo];
        //    }  //end;
        //    {MaxIndex returns class with largest count. Random choice if =max}
        //    MaxIndex (noClasses, ScoreArray, index, count, maxValue);
        //    classLabel[uNo]= index+1; {+1 because array processed as 0 to n-1}

        //    if total = 0
        //      ) ClassProb[uNo] = 0
        //      else ClassProb[uNo] = maxValue/total;
        //    classLabel[0] = 0; {zero index will be used to indicate unmatched test sig}
        ////(***
        ////for cNo = 1 to noClasses do write (lst, F2ScoreMatrix^[uNo, cNo]:4);
        ////LoggedConsole.WriteLine (lst);
        ////LoggedConsole.WriteLine (lst, " max=",maxValue:3, " lbl=",classLabel[uNo]:3, " prob=",ClassProb[uNo]:4:1);
        ////***)
        //  }  //}  //end;  {of all units}

        //}  //}  //end; ScoreTrainingResults

        //public static void ScoreTestResults
        //{

        ////var
        //  oneVote      : array[0..maxClassNo]  of word;
        //  repeatsArray : array[1..MaxRepeatNo] of word;
        //  count:word; //{(! used. Returns # of first place getters in case tied vote}
        //  sigNum, rep, cls :word; {counters}
        //  maxVote, maxValue{(! used}, correctClass :word;

        //for sigNum = 1 to tstSetSize do {find the winning vote for every signal}
        //  {
        //    for cls= 0 to noClasses do oneVote[cls] = 0;      {init OneVote}
        //    {transfer votes from matrix to OneVote array and ) find the maximum}
        //    for rep = 1 to norepeats  do inc(oneVote[DecisionMatrix^[sigNum,rep] ]);
        //    maxIndex (noClasses+1, oneVote, maxVote, count, maxValue);
        //    decisionMatrix^[sigNum, 0] = maxVote;  {store vote winner in zero index}
        //  }  //end; {of all signals}

        //  //{summarise results for classified signals and store the test results
        //   in test Score matrix}
        //  for cls =  0 to noClasses+1 do
        //    for rep = 0 to norepeats  do
        //      tstScoreMatrix^[cls,rep] = 0;         {initialise test Score matrix}
        //  for sigNum = 1 to tstSetSize do
        //    for rep = 0 to norepeats do
        //    {
        //      correctClass = tstSetTargets^[sigNum];
        //      if decisionMatrix^[sigNum, rep] = 0 )
        //        inc (tstScoreMatrix^[ 0, rep]) //{skipped or no match sigs go in row 0}
        //      else
        //      if decisionMatrix^[sigNum, rep] = correctClass )
        //      {
        //        inc (tstScoreMatrix^[ correctClass, rep]);
        //        inc (tstScoreMatrix^[ noClasses+1,  rep]);
        //      }  //end;
        //    }  //end;

        //  for cls = 0 to noClasses+1 do
        //  {
        //   {first transfer rep Scores from matrix to an array which can be passed
        //    to the moment procedure which returns the statistics.}
        //    for rep = 1 to norepeats do
        //          repeatsArray[rep] = tstScoreMatrix^[cls, rep];
        //    moment(repeatsArray, norepeats, tstResult^[cls].mean,
        //                                    tstResult^[cls].sd,
        //                                    tstResult^[cls].min,
        //                                    tstResult^[cls].max);
        //    tstResult^[cls].vote = tstScoreMatrix^[cls,0]; {transfer vote counts}
        //    tstResult^[noClasses+1].tot = tstSetSize;
        //  }  //end;
        //}  //}  //end; ScoreTestResults

        //public static void WriteDecisionMatrix (var F: text)
        //{
        //    //var
        //  sigNum, rep, i  : word; {counter}

        //  LoggedConsole.WriteLine(F, "THE DECISION MATRIX");
        //  write  (F, "sig#  vote");
        //  for rep = 1 to norepeats do write(lst, rep:5);
        //  LoggedConsole.WriteLine (F, "   target");
        //  for i = 1 to 100 do write (F,"-"); LoggedConsole.WriteLine(F);  {draw horiz line}

        //  for sigNum = 1 to tstSetSize do
        //  {
        //    write (F, sigNum:4,"|");
        //    for rep = 0 to norepeats do
        //      write (F, decisionMatrix^[sigNum, rep]:5);
        //    LoggedConsole.WriteLine (F, "  |", tstSetTargets^[sigNum]:4);
        //  }  //end;
        //  LoggedConsole.WriteLine (F);
        //  LoggedConsole.WriteLine (F, formfeed);
        //} // }  //end; WriteDecisionMatrix

        //public static void writeTestResults (var F:text)
        //{
        ////var
        //  k : word;
        //  cls, rep: word;
        //  size : word;
        //  mean, sd : real;
        //  min, max : word;

        //  LoggedConsole.WriteLine (F, "TEST RESULTS/Score from file: ",ResultsFPath);
        //  printDateAndTime (F);
        //  LoggedConsole.WriteLine (F, "ART VERSION = ",versionNames[versionID]);
        //  write   (F, "Training Set file = ",TrnSetFPath);
        //  LoggedConsole.WriteLine (F, "   Train set size = ",trnSetSize, " signals");
        //  LoggedConsole.WriteLine (F, "Train target file = ",TrnTarFPath);
        //  write   (F, "Test Set     file = ",TstSetFPath);
        //  LoggedConsole.WriteLine (F, "   Test  set size = ",tstSetSize, " signals");
        //  LoggedConsole.WriteLine (F, "Test  target file = ",TstTarFPath);
        //  LoggedConsole.WriteLine (F, "Weights file      = ",wtsFpath);
        //  for k = 1 to MaxARTparamsNo do
        //    write (F, paramNames[versionID, k]:9);
        //  LoggedConsole.WriteLine (F);
        //  for k = 1 to MaxARTparamsNo do write (F, ARTparams[k]:9:4);
        //  LoggedConsole.WriteLine (F);
        //  LoggedConsole.WriteLine (F);

        //  write  (F, "rep number  ");
        //  for rep = 1 to norepeats do write(F, rep:6);
        //  LoggedConsole.WriteLine (F, "   av");
        //  for k = 1 to 80 do write (F,"-"); LoggedConsole.WriteLine(F);  {draw horiz line}
        //  write  (F, "categories  ");
        //  for rep = 1 to norepeats do write(F, noOfCommittedF2[rep]:6);
        //  moment(noOfCommittedF2, norepeats, mean, sd, min, max);
        //  LoggedConsole.WriteLine (F, mean:6:1,"+/-",sd:3:1);
        //  write  (F, "iter to conv");
        //  for rep = 1 to norepeats do write(F, iterToConv[rep]:6);
        //  moment(iterToConv, norepeats, mean, sd, min, max);
        //  LoggedConsole.WriteLine (F, mean:6:1,"+/-",sd:3:1);
        //  write  (F, "# skipped   ");
        //  for rep = 1 to norepeats do write(F, SkippedBecauseFull[rep]:6);
        //  LoggedConsole.WriteLine (F);
        //  LoggedConsole.WriteLine (F);

        //  size = tstResult^[noClasses+1].tot; {ie size of the test set or tstSetSize}
        //  LoggedConsole.WriteLine(F, "THE TEST Score MATRIX");
        //  write  (F, "class   vote");
        //  for rep = 1 to norepeats do write(F, rep:6);
        //  LoggedConsole.WriteLine (F);
        //  for k = 1 to 80 do write (F,"-"); LoggedConsole.WriteLine(F);  {draw horiz line}
        //  for cls= 0 to noClasses+1 do
        //  {
        //    write (F, cls:6);
        //    for rep = 0 to norepeats do
        //      write (F, tstScoreMatrix^[cls, rep]:6);
        //    if cls = 0 ) LoggedConsole.WriteLine (F, " <- no match")
        //    else
        //    if cls = noClasses+1 ) LoggedConsole.WriteLine (F," <- total correct")
        //    else LoggedConsole.WriteLine (F, " <- num correct in class");
        //  }  //end; {end of all classes}
        //  LoggedConsole.WriteLine (F);

        ////(****
        ////  LoggedConsole.WriteLine(lst);
        ////  LoggedConsole.WriteLine(lst,"Rep No:","":12,"No match   Classes 1 to ",noClasses,"  Total");
        ////  for rep=1 to norepeats do
        ////  {
        ////    write(lst, rep:2,"":9);
        ////    for cls = 0 to noClasses+1 do write (lst, tstScoreMatrix^[cls, rep]:5);
        ////    LoggedConsole.WriteLine(lst);
        ////  }  //end;
        ////  LoggedConsole.WriteLine(lst); LoggedConsole.WriteLine(lst);
        ////****)
        //  LoggedConsole.WriteLine (F,"No match":21, "Classes 1 to ":30, noClasses, "Total":20);
        //  write   (F,"totals  ");
        //  for cls= 0 to noClasses+1 do  write (F, tstResult^[cls].tot:14);
        //  LoggedConsole.WriteLine (F);

        //  write   (F, "mean    ");
        //  for cls= 0 to noClasses+1 do
        //    write (F, tstResult^[cls].mean:7:1,"(",pc(tstResult^[cls].mean, size):4:1,"%)");
        //  LoggedConsole.WriteLine (F);

        //  write   (F, "std dev ");
        //  for cls= 0 to noClasses+1 do
        //    write (F, tstResult^[cls].sd:7:1,  "(",pc(tstResult^[cls].sd,   size):4:1,"%)");
        //  LoggedConsole.WriteLine (F);

        //  write   (F, "minimum ");
        //  for cls= 0 to noClasses+1 do write (F, tstResult^[cls].min:14);
        //  LoggedConsole.WriteLine (F);

        //  write   (F, "maximum ");
        //  for cls= 0 to noClasses+1 do write (F, tstResult^[cls].max:14);
        //  LoggedConsole.WriteLine (F);

        //  write   (F, "VOTE    ");
        //  for cls= 0 to noClasses+1 do
        //    write (F, tstResult^[cls].vote:7,"(",pc(tstResult^[cls].vote, size):4:1,"%)");
        //  LoggedConsole.WriteLine (F);

        //  write (F, formFeed);
        //}  //}  //end;  writeTestResults (var F:text)

        //public static void MAINMENU()
        //{
        //    //var
        //    int i;  //      : word;
        //    string FPath; //  : PathStr;
        //    char choice, key;  // : char;
        //    //dirInfo: searchRec;

        //    Repeat
        //        ReadConfigFile;
        //        //TextBackGround (1);   //{blue background}
        //        //ClrScr;
        //        LoggedConsole.WriteLine();
        //        LoggedConsole.WriteLine ("                   ART MAIN MENU");
        //        LoggedConsole.WriteLine ("  All setting up to be entered in CONFIG file.");
        //        LoggedConsole.WriteLine();
        //        LoggedConsole.WriteLine ("  C) edit  CONFIGURATION file:- ",ConfigFpath);
        //        LoggedConsole.WriteLine ("  R) edit  PARAMETERS file   :- ",ParamsFpath);
        //        LoggedConsole.WriteLine ("  P) PRINT configuration file.");
        //        LoggedConsole.WriteLine ("  D) Display contents of OUTPUT directory.");
        //        LoggedConsole.WriteLine ("  T) Print TEXT file.");
        //        LoggedConsole.WriteLine ("  M) Print decision MATRIX.");
        //        LoggedConsole.WriteLine();
        //        LoggedConsole.WriteLine ("  O) OK, continue            Esc) HALT program");

        //    Repeat
        //        Choice = Upcase(readkey);
        //    Until choice in ["O", Esc, "R","C","P","D","M","T"];

        //    Case choice of
        //    "C":{
        //        SwapVectors;
        //        Exec("c:\\DOS\\edit.com", ConfigFPath);
        //        SwapVectors;
        //        If DOSError <> 0 ) LoggedConsole.WriteLine ("DOS Error # ",DosError);
        //        ClrScr;
        //        ReadConfigFile;
        //        DisplayConfiguration;
        //    }  //end;|
        //    "R":{
        //        SwapVectors;
        //        Exec("c:\\DOS\\edit.com", ParamsFPath);
        //        SwapVectors;
        //        If DOSError <> 0 ) LoggedConsole.WriteLine ("DOS Error # ",DosError);
        //        ClrScr;
        //      }  //end;
        //    "P":if (! printerOn ) Printer(!OnMessage
        //        else PrintTextFile(ConfigFName);
        //    "D":{
        //        ClrScr;
        //        LoggedConsole.WriteLine ("List of files in the directory :- ", OUTPUTdir);
        //        LoggedConsole.WriteLine;
        //        FindFirst (OUTPUTdir+"/*.*", AnyFile, DirInfo);
        //        i = 0;
        //        while (DosError = 0)  do
        //        {
        //          inc (i);
        //          write (DirInfo.name:15);
        //          FindNext (DirInfo);
        //          if (i MOD 5 = 0) ) LoggedConsole.WriteLine;
        //        }  //end;
        //        LoggedConsole.WriteLine;
        //        LoggedConsole.WriteLine ("Press <space bar> to return to main menu");
        //        key = readKey;
        //      }  //end;
        //    "T": {
        //        LoggedConsole.WriteLine;
        //        write ("   Enter full path name of text file to print -> ");
        //        readln (FPath);
        //        if (! FileExists(FPath) )
        //        {
        //          LoggedConsole.WriteLine;
        //          write (" File does (! exist!!   Press any key ->");
        //          key = readkey;
        //        end else
        //        if (! printerOn ) Printer(!OnMessage
        //                else printTextFile (FPath);
        //            }  //end;
        //    "M":if (! printerOn ) Printer(!OnMessage
        //        else writeDecisionMatrix (lst);
        //        Esc: HALT;
        //}  //end; {case choice of}

        //Until (choice = "O"{OK}) ;
        //}  //end;  MAINMENU

        //{***********************************************************************************************************************************}
        //{***********************************************************************************************************************************}
        //{***********************************************************************************************************************************}
        //{***********************************************************************************************************************************}
        //{***********************************************************************************************************************************}
        //{***********************************************************************************************************************************}
        //{***********************************************************************************************************************************}

        // {*** MAIN PROGRAM ***}

        public static void Main()
        {
            Tasks  task     = Tasks.TRAIN;
            string wtsFname = "output";

            double[,] trainingData = null;
            int trnSetSize = 0;

            //int tstSetSize = 0;
            int F1Size = 0;
            int F2Size = 0;

            bool[] uncommittedJ    = new bool[F2Size];           // : PtrToArrayOfBool;
            int[]  noOfCommittedF2 = new int[NumberOfRepeats];   // : array[1..MaxRepeatNo] of word;{# committed F2Neta units}
            int[]  iterToConv      = new int[NumberOfRepeats];   // : array[1..MaxRepeatNo] of word;{for training only}

            //char key = '0';        //      : char;
            int code = 0;        //        : word; {used for getting error messages}

            //int Score = 0;       //        : word;

            //double[]  DataArray  = new double[maxDataDim];
            //double[,] dataMatrix = new double[maxTrnSetSize, maxDataDim]; //of PdataArray;
            //int[]     keepScore = new int[maxTrnSetSize]; //stores the assigned class for every input signal. Used to test for stabilisation/convergence}
            //int[] SkippedBecauseFull = new int[numberOfRepeats];  // : array[1..MaxRepeatNo] of word;

            string wtsFpath     = string.Empty;
            string resultsFPath = string.Empty;   //  : PathStr;
            string trnSetFpath  = string.Empty;

            //string trnTarFpath = ""; //  : pathStr;
            string tstSetFpath = string.Empty;

            //string tstTarFpath = ""; //  : pathStr;
            //bool targetFileExists; // : boolean;
            //string ARTVersion;     //   : string[50];
            //int VersionID;         //    : integer;
            //int[] F2classLabel = new int[maxF2Size];       //: array [0..maxF2Size] of word;
            //double[] F2classProb = new double[maxF2Size];  // : array [0..maxF2Size] of real;
            //int KeepScore; //    : PKeepScore;

            //{************************** INITIALISE VALUES *************************}

            //F2ScoreMatrix = new ();   //{used to assign classes to F2 nodes after training}
            //decisionMatrix = new ();  //{matrix: tst sig number x repeats }
            //tstScoreMatrix = new ();  //{matrix: tst sig class  x repeats }
            //tstResult = new ();       //{array of record: class x tst Score results}
            //tstSetTargets = new ();

            //CONFIGURE AND CHECK PARAMETERS
            //ReadConfigFile;
            //code = 0;
            //CheckConfiguration (code);
            //if(code == 0) ParamValuesOK(versionID);

            if (task == Tasks.TRAIN || task == Tasks.TRAINTEST)
            {
                trnSetFpath  = DataFpath;
                trainingData = FileTools.ReadDoubles2Matrix(DataFpath);
                trnSetSize   = trainingData.GetLength(0);
                F1Size       = trainingData.GetLength(1);
                F2Size       = trainingData.GetLength(0);
            }

            double[,] parameters = ReadParameterValues(ParamsFpath);
            int simulationsCount = parameters.GetLength(0);
            int paramCount       = parameters.GetLength(1);

            ART_2A art2a = new ART_2A(F1Size, F2Size);

            if (task == Tasks.TEST) // {load the test file weights}
            {
                //Case versionID of
                //    verART2A      : ReadWtsART2a    (wtsFPath, F1SizeOfNeta, F2SizeOfNeta, F2classLabel, F2classProb, code);
                //    verFuzzyART   : ReadWtsFuzzyART (wtsFPath, F1SizeOfNeta, F2SizeOfNeta, F2classLabel, F2classProb, code);
                //    verARTMAP2a   : { {ReadWtsARTMAP2a;} }  //end;
                //    verFuzzyARTMAP: ReadWtsFuzzyARTMAP(wtsFPath, F2classLabel, F2classProb, code);
                //}  //end; {Case Les.algID of}
                //ReadWtsART2a    (wtsFPath, F1SizeOfNeta, F2SizeOfNeta, F2classLabel, F2classProb, code);
            }

            //if (code != 0)
            //{
            //    LoggedConsole.WriteLine("WARNING!!!!!!!! ERROR READING WTS FILE.");
            //    LoggedConsole.WriteLine(" F1 & F2 sizes in config file and wts file are NOT equal");
            //    LoggedConsole.WriteLine(" Press any key to return to main menu");
            //    key = readkey;
            //    goto TheBeginning;
            //}

            //{Initialise screen for graphics display of F2 weight graphs}
            //InitialiseGraphicsMode;

            //{********** DO SIMULATIONS WITH DIFFERENT PARAMETER VALUES ***********}
            for (int simul = 0; simul < simulationsCount; simul++)
            {
                //pass the eight params for this run of ART2A
                //alpha, beta, rho, theta, rhoStar
                art2a.SetParameterValues(parameters[simul, 0], parameters[simul, 1], parameters[simul, 2], parameters[simul, 3]);

                //set up file name for simulation test results}
                resultsFPath = ARTDir + wtsFname + "s" + simul.ToString("D2") + "_results.txt";

                //init array to count committed F2 nodes
                //int[] noOfCommittedF2 = new int[ART.numberOfRepeats];

                //initialise decision matrix for processing test data}
                //int[,] decisionMatrix = new int[tstSetSize,norepeats];  //{matrix: tst sig number x repeats }

                //{********** DO REPEATS ***********}
                for (int rep = 0; rep < NumberOfRepeats; rep++)
                {
                    LoggedConsole.WriteLine("RUN=", simul, " rep=", rep);

                    //{********* RUN NET for ONE SET OF PARAMETERS for ALL ITERATIONS *********}
                    if (task == Tasks.TRAIN)
                    {
                        art2a.InitialiseArrays();
                        code = 0;
                        art2a.TrainNet(trainingData, MaxIterations, simul, rep, code);

                        if (code != 0)
                        {
                            break;
                        }

                        noOfCommittedF2[rep] = art2a.CountCommittedF2Nodes();

                        //ScoreTrainingResults (noOfCommittedF2[rep], noClasses, F2classLabel, F2classProb);

                        wtsFpath = ARTDir + ART.WtsFname + "s" + simul + rep + WtsFExt;

                        //art2a.WriteWts(wtsFpath, F2classLabel, F2classProb);
                        if (DEBUG)
                        {
                            LoggedConsole.WriteLine("wts= " + wtsFpath + "  train set= " + trnSetFpath);
                        }
                    }

                    if (task == Tasks.TEST)
                    {
                        //{wts file was loaded above.
                        //art2a.TestNet(testData, simul, rep, code) ;
                        //if (code != 0) goto EndOfSimulations;
                        //if (DEBUG) LoggedConsole.WriteLine("wts= " + wtsFpath + "  test set= " + tstSetFpath);
                    }

                    if (task == Tasks.TRAINTEST)
                    {
                        //Case versionID of        {initialise the weight arrays}
                        //verART2A      : InitWtsART2a;
                        //verFuzzyART   : InitWtsFuzzyART;
                        //{   verARTMAP2a   : InitWtsARTMAP2a;  }
                        //verFuzzyARTMAP: InitWtsFuzzyARTMAP;
                        //}  //Case Les.algID of}
                        art2a.InitialiseArrays();
                        art2a.TrainNet(trainingData, MaxIterations, simul, rep, code);

                        if (code != 0)
                        {
                            break;
                        }

                        noOfCommittedF2[rep] = art2a.CountCommittedF2Nodes();

                        //ScoreTrainingResults (noOfCommittedF2[rep], noClasses, F2classLabel, F2classProb);

                        wtsFpath = ARTDir + ART.WtsFname + "s" + simul + rep + WtsFExt;

                        //Case versionID of
                        //verART2A      : WriteWtsART2a (wtsFPath, F1SizeOfNeta, F2SizeOfNeta, F2classLabel, F2classProb);
                        //verFuzzyART   : WriteWtsFuzzyART(wtsFPath, F1SizeOfNeta, F2SizeOfNeta,F2classLabel, F2classProb);
                        //verFuzzyARTMAP: WriteWtsFuzzyARTMAP(wtsFPath, F2classLabel, F2classProb);
                        //}  //Case Les.algID of}
                        //art2a.WriteWts(wtsFPath, F2classLabel, F2classProb);

                        //art2a.TestNet(testData, simul, rep, code);
                        //if (code != 0) goto EndOfSimulations;
                        if (DEBUG)
                        {
                            LoggedConsole.WriteLine("wts= " + wtsFpath + "  test set= " + tstSetFpath + "  Press any key");
                        }
                    }

                    //{************** DISPLAY RECONSTRUCTED SIGNALS **************}

                    //for F2uNo = 1 to F2SizeOfNeta do   {Calculate the average signal values}
                    //{
                    //  {for j = 0 to noClasses+1 do write (lst, F2ScoreMatrix^[F2uNo][j]:4);
                    //  LoggedConsole.WriteLine (lst);}
                    //  Score = F2ScoreMatrix^[F2uNo][noClasses+1];
                    //  for F1uNo = 1 to F1SizeOfNeta do
                    //    if  Score = 0 )
                    //         avSig^[F2uNo]^[F1uNo] = 0.0
                    //    else avSig^[F2uNo]^[F1uNo] = avSig^[F2uNo]^[F1uNo] /Score;
                    //}  //end;

                    //{*********** FinalScreenDisplay ***********}
                    //if (DEBUG)FinalScreenDisplay(F1sizeOfNeta,F2SizeOfNeta,F2ScoreMatrix,avSig^,WtsNeta^);
                    //{
                    //    InitialiseDisplayOfF2Weights (F1sizeOfNeta, noOfCommittedF2[rep]);
                    //    for (int F2uNo = 0; F2uNo < noOfCommittedF2[rep]; F2uNo++)
                    //    {
                    //        DisplayF2WtsAndSig(F2uNo, F1sizeOfNeta, noOfCommittedF2[rep], F2ScoreMatrix[F2uNo,noClasses+1],
                    //                    avSig[F2uNo], wtsNetA[F2uNo], avSigRange, wtsRange);
                    //    }
                    //} //end; {if display on do final display}
                } //end; {for rep   = 1 to norepeats do}       {***** END OF REPEATS *****}

                //ScoreTestResults;
                //if (printTestResults) writeTestResults(lst); //            {write to printer.....}
                //else   //{...else write to file}
                //{
                //  assign (resultsF, resultsFPath);
                //  rewrite(resultsF);
                //  writeTestResults (resultsF);
                //  close  (resultsF);
                //}  //end;

                //if (printDecisionMatrix) writeDecisionMatrix(lst);
            } //end; {for simul = 1 to noSimulationsInRun do}  {**** END OF SIMULATE *****}

            //if (printerOn) PrintTextFile(ConfigFpath);

            //{LABEL} EndOfSimulations:
            //close  (ParamsF);
            //CloseGraph;
            //Case versionID of
            //  verART2A      : DisposeART2a;
            //  verFuzzyART   : DisposeFuzzyART;
            //{  verARTMAP2a   : DisposeARTMAP2a;}
            //  verFuzzyARTMAP: DisposeFuzzyARTMAP;
            //}  //end; {Case Les.algID of}

            //GoTo TheBeginning;

            //    {****************** DISPOSE OF HEAP VARIABLES ******************}
            //for j = 1 to MaxTrnSetSize do dispose (DataMatrix[j]);
            //dispose (keepScore);
            //dispose (F2ScoreMatrix);   {used to assign classes to F2 nodes}
            //dispose (decisionMatrix);  {matrix: tst sig number x repeats }
            //dispose (tstScoreMatrix);  {matrix: tst sig class  x repeats }
            //dispose (tstResult);       {array of record: class x tst Score results}
            //dispose (TstSetTargets);
        } //END of MAIN METHOD.
Beispiel #41
0
 /// <summary>
 /// Dispose async
 /// </summary>
 /// <returns></returns>
 public ValueTask DisposeAsync() => new ValueTask(Tasks.CompletedTask());
Beispiel #42
0
        private static void Execute(string lua, byte[] bytes, Tasks task, State state)
        {
            var luaPath = Path.Combine(PathMgr.Local(task == Tasks.Decrypt ? "Decrypted_Lua" : "Encrypted_lua"), Path.GetFileName(lua));

            if (File.Exists(luaPath))
            {
                File.Delete(luaPath);
            }

            try
            {
                Utils.pInfof(string.Format("{0} {1}...", (task == Tasks.Decrypt ? "Decrypting" : "Encrypting"), Path.GetFileName(lua)));
                using (var stream = new MemoryStream(bytes))
                {
                    using (var reader = new BinaryReader(stream))
                    {
                        // ljd\rawdump\header.py + Perfare
                        var magic   = reader.ReadBytes(3);
                        var version = reader.ReadByte();
                        var bits    = reader.ReadUleb128();

                        var is_stripped = ((bits & 2u) != 0u);
                        if (!is_stripped)
                        {
                            var length = reader.ReadUleb128();
                            var name   = Encoding.UTF8.GetString(reader.ReadBytes((int)length));
                        }

                        while (reader.BaseStream.Position < reader.BaseStream.Length)
                        {
                            var size = reader.ReadUleb128();

                            if (size == 0)
                            {
                                break;
                            }

                            var next = reader.BaseStream.Position + size;
                            bits = reader.ReadByte();

                            var arguments_count         = reader.ReadByte();
                            var framesize               = reader.ReadByte();
                            var upvalues_count          = reader.ReadByte();
                            var complex_constants_count = reader.ReadUleb128();
                            var numeric_constants_count = reader.ReadUleb128();
                            var instructions_count      = reader.ReadUleb128();

                            var start = (int)reader.BaseStream.Position;

                            if (state == State.Encrypted && task == Tasks.Decrypt)
                            {
                                bytes[3] = 0x02;
                                bytes    = Unlock(start, bytes, (int)instructions_count);
                            }
                            else if (state == State.Decrypted && task == Tasks.Encrypt)
                            {
                                bytes[3] = 0x80;
                                bytes    = Lock(start, bytes, (int)instructions_count);
                            }
                            else
                            {
                                break;
                            }

                            reader.BaseStream.Position = next;
                        }
                    }
                }
                File.WriteAllBytes(luaPath, bytes);
            }
            catch (Exception e)
            {
                Utils.eLogger(string.Format("Exception detected during {0} {1}", (task == Tasks.Decrypt ? "decrypting" : "encrypting"), Path.GetFileName(lua)), e);
            }
            finally
            {
                if (File.Exists(luaPath))
                {
                    SuccessCount++;
                    Console.Write(" <Done>\n");
                }
                else
                {
                    Console.Write(" <Failed>\n");
                    FailedCount++;
                }
            }
        }
Beispiel #43
0
 protected override void Refresh()
 {
     Tasks.Fill(tsActionPanel, cmsActionPanel);
     base.Refresh();
 }
 /// <summary>
 /// Add the specified task to be executed.
 /// </summary>
 /// <param name="task">The task.</param>
 public void Add(Task task)
 {
     Tasks.Add(task);
 }
Beispiel #45
0
        /* --- not used, commented out for usage of hardcoded org ids
         * public int NationalPartyOrg (bool onlyIfMember)
         * {
         *  //TODO: Implement a flag in Organization
         *  int[] partyOrgs = new int[] { Organization.PPSEid, Organization.PPDKid, Organization.PPFIid };
         *  foreach (int orgId in partyOrgs)
         *  {
         *      if (this.MemberOf(orgId))
         *      {
         *          return orgId;
         *      }
         *  }
         *
         *  //no, wasnt a member, try by country
         *  if (!onlyIfMember)
         *  {
         *      foreach (int orgId in partyOrgs)
         *      {
         *          try
         *          {
         *              Organization org = Organization.FromIdentity(orgId);
         *              if (this.Country.Code == org.DefaultCountry.Code)
         *              {
         *                  return orgId;
         *              }
         *          }
         *          catch { }
         *      }
         *  }
         *  //didn't find any
         *  return 0;
         *
         * } */

        // ReSharper disable InconsistentNaming

        public Tasks GetTasksForOrganization(Organization organization)
        {
            return(Tasks.ForPersonOrganization(this, organization));
        }
        public ActionResult <Tasks> Create([FromBody] Tasks task)
        {
            _taskService.Create(task);

            return(task);
        }
Beispiel #47
0
            public string Validate(List <Entity <string, PMProjectRate, PMProject> > data1,
                                   List <Entity <string, PMTaskRate, PMTask> > data2,
                                   List <Entity <int?, PMAccountGroupRate, PMAccountGroup> > data3,
                                   List <Entity <int?, PMItemRate, InventoryItem> > data4,
                                   List <Entity <int?, PMEmployeeRate, BAccount> > data5)
            {
                string        errors = null;
                StringBuilder sb     = new StringBuilder();

                foreach (Entity <string, PMProjectRate, PMProject> i1 in data1)
                {
                    foreach (Entity <string, PMTaskRate, PMTask> i2 in data2)
                    {
                        foreach (Entity <int?, PMAccountGroupRate, PMAccountGroup> i3 in data3)
                        {
                            foreach (Entity <int?, PMItemRate, InventoryItem> i4 in data4)
                            {
                                foreach (Entity <int?, PMEmployeeRate, BAccount> i5 in data5)
                                {
                                    bool isDuplicate = true;

                                    if (i1.Key != null && !Projects.ContainsKey(i1.Key.ToUpper().Trim()))
                                    {
                                        isDuplicate = false;
                                        continue;
                                    }

                                    if (i2.Key != null && !Tasks.ContainsKey(i2.Key.ToUpper().Trim()))
                                    {
                                        isDuplicate = false;
                                        continue;
                                    }

                                    if (i3.Key != null && !AccountGroups.ContainsKey(i3.Key))
                                    {
                                        isDuplicate = false;
                                        continue;
                                    }

                                    if (i4.Key != null && !Inventory.ContainsKey(i4.Key))
                                    {
                                        isDuplicate = false;
                                        continue;
                                    }

                                    if (i5.Key != null && !Employees.ContainsKey(i5.Key))
                                    {
                                        isDuplicate = false;
                                        continue;
                                    }

                                    if (isDuplicate)
                                    {
                                        bool hasError = false;
                                        if (i1.Key != null)
                                        {
                                            sb.AppendFormat("{0}:{1}, ", PXMessages.LocalizeNoPrefix(Messages.Project), i1.Key);
                                            hasError = true;
                                        }

                                        if (i2.Key != null)
                                        {
                                            sb.AppendFormat("{0}:{1}, ", PXMessages.LocalizeNoPrefix(Messages.ProjectTask), i2.Key);

                                            hasError = true;
                                        }

                                        if (i3.Key != null)
                                        {
                                            sb.AppendFormat("{0}:{1}, ", PXMessages.LocalizeNoPrefix(Messages.AccountGroup), i3.Object.GroupCD);
                                            hasError = true;
                                        }

                                        if (i4.Key != null)
                                        {
                                            sb.AppendFormat("{0}:{1}, ", PXMessages.LocalizeNoPrefix(IN.Messages.InventoryItem), i4.Object.InventoryCD);
                                            hasError = true;
                                        }

                                        if (i5.Key != null)
                                        {
                                            sb.AppendFormat("{0}:{1}, ", PXMessages.LocalizeNoPrefix(EP.Messages.Employee), i5.Object.AcctCD);
                                            hasError = true;
                                        }

                                        if (hasError)
                                        {
                                            sb.AppendLine("");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                if (sb.Length > 0)
                {
                    errors = string.Format("{0} = {1} ", PXMessages.LocalizeNoPrefix(Messages.RateCode), RateCode) + sb.ToString();
                }

                return(errors);
            }
Beispiel #48
0
        public void TestRemoveCloudServiceWithStaging()
        {
            services.Clear()
            .Add(s =>
            {
                s.Name = serviceName;
                s.AddDeployment(d =>
                {
                    d.Name = "myStagingdeployment";
                    d.Slot = DeploymentSlot.Staging;
                });
            });

            clientMocks.ComputeManagementClientMock.Setup(
                c => c.Deployments.DeleteByNameAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <CancellationToken>()))
            .Returns((string s, string deploymentName, bool deleteAll, CancellationToken cancellationToken) => Tasks.FromResult(
                         CreateComputeOperationResponse("request001")));

            clientMocks.ComputeManagementClientMock.Setup(
                c => c.HostedServices.DeleteAsync(It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .Returns(Tasks.FromResult(new AzureOperationResponse
            {
                RequestId  = "request000",
                StatusCode = HttpStatusCode.OK
            }));

            // Test
            client.RemoveCloudService(serviceName);

            // Assert
            clientMocks.ComputeManagementClientMock.Verify(
                c => c.Deployments.DeleteByNameAsync(serviceName, "myStagingdeployment", false, It.IsAny <CancellationToken>()), Times.Once);

            clientMocks.ComputeManagementClientMock.Verify(
                c => c.HostedServices.DeleteAsync(serviceName, It.IsAny <CancellationToken>()), Times.Once);
        }
Beispiel #49
0
 public TaskViewModel(Tasks task)
 {
     this.Task = task;
 }
Beispiel #50
0
        public void Dispose()
        {
            if (disposed)
            {
                return;
            }

            // give it 3 seconds to complete requests
            for (int i = 0; i < 30 && Interlocked.Read(ref metricsCounters.ConcurrentRequestsCount) > 0; i++)
            {
                Thread.Sleep(100);
            }

            AppDomain.CurrentDomain.ProcessExit  -= ShouldDispose;
            AppDomain.CurrentDomain.DomainUnload -= ShouldDispose;

            disposed = true;

            var exceptionAggregator = new ExceptionAggregator(Log, "Could not properly dispose RavenFileSystem");

            if (synchronizationTask != null)
            {
                exceptionAggregator.Execute(synchronizationTask.Dispose);
            }

            if (storage != null)
            {
                exceptionAggregator.Execute(storage.Dispose);
            }

            if (search != null)
            {
                exceptionAggregator.Execute(search.Dispose);
            }

            if (sigGenerator != null)
            {
                exceptionAggregator.Execute(sigGenerator.Dispose);
            }

            if (BufferPool != null)
            {
                exceptionAggregator.Execute(BufferPool.Dispose);
            }

            if (metricsCounters != null)
            {
                exceptionAggregator.Execute(metricsCounters.Dispose);
            }

            if (Tasks != null)
            {
                Tasks.Dispose(exceptionAggregator);
            }

            if (TimerManager != null)
            {
                exceptionAggregator.Execute(TimerManager.Dispose);
            }

            if (Files != null)
            {
                exceptionAggregator.Execute(Files.Dispose);
            }

            exceptionAggregator.ThrowIfNeeded();
        }
Beispiel #51
0
        public void Add()
        {
            User user = new User
            {
                FirstName   = "Test",
                LastName    = "User",
                Username    = "******",
                DateCreated = DateTime.UtcNow,
                Id          = Guid.Parse("270dfcc8-baf6-11e9-a2a3-2a2ae2dbcce4")
            };

            Tasks tasks = new Tasks
            {
                Id              = task1WithSchedule,
                TaskType        = Enums.TaskType.GetDeviceInfo,
                Status          = Enums.Status.Waiting,
                IntervalDays    = 60,
                IntervalSeconds = 120,
                Device          = new Devices
                {
                    Id           = Guid.NewGuid(),
                    Name         = "TaskDeviceAddTest",
                    Model        = "TestMethodAddTaskDevice",
                    Manufacturer = "TestMethodAddTaskDevice",
                    User         = user
                }
            };
            Tasks updateTask = new Tasks
            {
                Id              = task3Update,
                TaskType        = Enums.TaskType.GetDeviceInfo,
                Status          = Enums.Status.Ready,
                IntervalDays    = 90,
                IntervalSeconds = 180,
                Device          = new Devices
                {
                    Id           = Guid.NewGuid(),
                    Name         = "TaskDeviceUpdateTest",
                    Model        = "TaskDeviceUpdateTest",
                    Manufacturer = "TaskDeviceUpdateTest",
                    User         = user
                },
            };
            Tasks deleteTask = new Tasks
            {
                Id       = task2Delete,
                TaskType = Enums.TaskType.GetDeviceInfo,
                Status   = Enums.Status.Ready,
                Device   = new Devices
                {
                    Id           = Guid.NewGuid(),
                    Name         = "TaskDeviceDeleteTest",
                    Model        = "TaskDeviceDeleteTest",
                    Manufacturer = "TaskDeviceDeleteTest",
                    User         = user
                },
            };
            Tasks withInternval = new Tasks
            {
                Id              = intervalTask,
                TaskType        = Enums.TaskType.GetDeviceInfo,
                Status          = Enums.Status.Ready,
                IntervalSeconds = 60,
                IntervalDays    = 30,
                Device          = new Devices
                {
                    Id           = Guid.NewGuid(),
                    Name         = "TaskDeviceIntervaleTest",
                    Model        = "TaskDeviceIntervaleTest",
                    Manufacturer = "TaskDeviceIntervaleTest",
                    User         = user
                },
            };

            UserRepository.Add(user, "test");
            TasksRepository.Add(updateTask);
            TasksRepository.Add(deleteTask);
            TasksRepository.Add(tasks);
            TasksRepository.Add(withInternval);

            int changes = TasksRepository.SaveChanges();

            Assert.Greater(changes, 0);
        }
Beispiel #52
0
 public bool Init(Tasks task)
 {
     return(jobsRepository.Init(task));
 }
Beispiel #53
0
 private CommandResult StopTasksCommand(ICommandSource src, ICommandArgs args)
 {
     Tasks.CancelAll();
     return(CommandResult.Success());
 }
 /// <summary>
 /// Clear all the tasks.
 /// </summary>
 public void Clear()
 {
     Tasks.Clear();
 }
 public FormToolGRoleRecover(Tasks model)
 {
     InitializeComponent();
     _model = model;
 }
Beispiel #56
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Project"/> class.
        /// </summary>
        /// <param name="name">The name of the project. Typically it is the name of the product to be installed.</param>
        /// <param name="items">The project installable items (e.g. directories, files, registry keys, Custom Actions).</param>
        public Project(string name, params WixObject[] items)
        {
            if (!Compiler.AutoGeneration.LegacyDefaultIdAlgorithm)
            {
                this.CustomIdAlgorithm = this.HashedTargetPathIdAlgorithm;
            }

            Name        = name;
            OutFileName = name;

            var dirs         = new List <Dir>();
            var actions      = new List <Action>();
            var regs         = new List <RegValue>();
            var props        = new List <Property>();
            var bins         = new List <Binary>();
            var genericItems = new List <IGenericEntity>();

            if (items.OfType <Media>().Any())
            {
                this.Media.Clear();
            }

            foreach (WixObject obj in items)
            {
                var rawItems = new List <WixObject>();
                if (obj is WixItems)
                {
                    rawItems.AddRange((obj as WixItems).Items);
                }
                else
                {
                    rawItems.Add(obj);
                }

                foreach (WixObject item in rawItems)
                {
                    if (item is LaunchCondition)
                    {
                        LaunchConditions.Add(item as LaunchCondition);
                    }
                    else if (item is Dir)
                    {
                        dirs.Add(item as Dir);
                    }
                    else if (item is Action)
                    {
                        actions.Add(item as Action);
                    }
                    else if (item is RegValue)
                    {
                        regs.Add(item as RegValue);
                    }
                    else if (item is RegFile)
                    {
                        var file   = item as RegFile;
                        var values = Tasks.ImportRegFile(file.Path);
                        if (file.ActualFeatures.Any())
                        {
                            values.ForEach(x =>
                            {
                                x.Feature  = file.Feature;
                                x.Features = file.Features;
                            });
                        }
                        regs.AddRange(values);
                    }
                    else if (item is Property || item is PropertyRef)
                    {
                        props.Add(item as Property);
                    }
                    else if (item is Binary)
                    {
                        bins.Add(item as Binary);
                    }
                    else if (item is WixGuid)
                    {
                        GUID = (item as WixGuid).Value;
                    }
                    else if (item is Media)
                    {
                        Media.Add(item as Media);
                    }
                    else if (item is IGenericEntity)
                    {
                        genericItems.Add(item as IGenericEntity);
                    }
                    else
                    {
                        throw new Exception("Unexpected object type is among Project constructor arguments: " + item.GetType().Name);
                    }
                }
            }

            Dirs         = dirs.ToArray();
            Actions      = actions.ToArray();
            RegValues    = regs.ToArray();
            Properties   = props.ToArray();
            Binaries     = bins.ToArray();
            GenericItems = genericItems.ToArray();
        }
Beispiel #57
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Project"/> class.
        /// </summary>
        /// <param name="name">The name of the project. Typically it is the name of the product to be installed.</param>
        /// <param name="items">The project installable items (e.g. directories, files, registry keys, Custom Actions).</param>
        public Project(string name, params WixObject[] items)
        {
            Name        = name;
            OutFileName = name;

            var dirs         = new List <Dir>();
            var actions      = new List <Action>();
            var regs         = new List <RegValue>();
            var envvars      = new List <EnvironmentVariable>();
            var props        = new List <Property>();
            var bins         = new List <Binary>();
            var users        = new List <User>();
            var sqls         = new List <SqlDatabase>();
            var certs        = new List <Certificate>();
            var genericItems = new List <IGenericEntity>();
            var fwexceptions = new List <FirewallException>();

            if (items.OfType <Media>().Any())
            {
                this.Media.Clear();
            }

            foreach (WixObject obj in items)
            {
                var rawItems = new List <WixObject>();
                if (obj is WixItems)
                {
                    rawItems.AddRange((obj as WixItems).Items);
                }
                else
                {
                    rawItems.Add(obj);
                }

                foreach (WixObject item in rawItems)
                {
                    if (item is LaunchCondition)
                    {
                        LaunchConditions.Add(item as LaunchCondition);
                    }
                    else if (item is Dir)
                    {
                        dirs.Add(item as Dir);
                    }
                    else if (item is Action)
                    {
                        actions.Add(item as Action);
                    }
                    else if (item is RegValue)
                    {
                        regs.Add(item as RegValue);
                    }
                    else if (item is EnvironmentVariable)
                    {
                        envvars.Add(item as EnvironmentVariable);
                    }
                    else if (item is FirewallException)
                    {
                        fwexceptions.Add(item as FirewallException);
                    }
                    else if (item is RegFile)
                    {
                        var file   = item as RegFile;
                        var values = Tasks.ImportRegFile(file.Path);
                        if (file.Feature != null)
                        {
                            values.ForEach(x =>
                            {
                                x.Feature  = file.Feature;
                                x.Features = file.Features;
                            });
                        }
                        regs.AddRange(values);
                    }
                    else if (item is Property || item is PropertyRef)
                    {
                        props.Add(item as Property);
                    }
                    else if (item is Binary)
                    {
                        bins.Add(item as Binary);
                    }
                    else if (item is WixGuid)
                    {
                        GUID = (item as WixGuid).Value;
                    }
                    else if (item is Media)
                    {
                        Media.Add(item as Media);
                    }
                    else if (item is User)
                    {
                        users.Add(item as User);
                    }
                    else if (item is SqlDatabase)
                    {
                        sqls.Add(item as SqlDatabase);
                    }
                    else if (item is Certificate)
                    {
                        certs.Add(item as Certificate);
                    }
                    else if (item is IGenericEntity)
                    {
                        genericItems.Add(item as IGenericEntity);
                    }
                    else
                    {
                        throw new Exception("Unexpected object type is among Project constructor arguments: " + item.GetType().Name);
                    }
                }
            }

            Dirs                 = dirs.ToArray();
            Actions              = actions.ToArray();
            RegValues            = regs.ToArray();
            Properties           = props.ToArray();
            Binaries             = bins.ToArray();
            EnvironmentVariables = envvars.ToArray();
            Users                = users.ToArray();
            SqlDatabases         = sqls.ToArray();
            Certificates         = certs.ToArray();
            FirewallExceptions   = fwexceptions.ToArray();
            GenericItems         = genericItems.ToArray();
        }
Beispiel #58
0
        private void Worker()
        {
            Port = DEFAULT_PORT;

            // Check the URL to reuse the port number if possible
            try
            {
                using (RegistryKey key = OutlookRegistryUtils.OpenOutlookKey(REG_KEY))
                {
                    if (key != null)
                    {
                        string oldURL = key.GetValueString(REG_VALUE);
                        if (oldURL.StartsWith(URL_BASE))
                        {
                            string rest = oldURL.Substring(URL_BASE.Length);
                            int    sep  = rest.IndexOf('/');
                            if (sep >= 0)
                            {
                                rest = rest.Substring(0, sep);
                            }
                            int port = int.Parse(rest);
                            if (port > 0 && port < 65536)
                            {
                                Port = port;
                            }
                        }
                    }
                }
            }
            catch (Exception) { Port = DEFAULT_PORT; }

            TcpListener listener;

            listener = new TcpListener(IPAddress.Loopback, Port);
            try
            {
                listener.Start();
            }
            catch (SocketException)
            {
                // Error opening port, try with a default one
                listener = new TcpListener(IPAddress.Loopback, 0);
                listener.Start();
                Port = ((IPEndPoint)listener.LocalEndpoint).Port;
            }

            // Register URL
            using (RegistryKey key = OutlookRegistryUtils.OpenOutlookKey(REG_KEY, Microsoft.Win32.RegistryKeyPermissionCheck.ReadWriteSubTree))
            {
                if (key != null)
                {
                    // Set only if empty or already our URL
                    string oldURL = key.GetValueString(REG_VALUE);
                    if (string.IsNullOrWhiteSpace(oldURL) || oldURL.Contains("/" + URL_IDENTIFIER + "/"))
                    {
                        key.SetValue(REG_VALUE, string.Format(URL, Port));
                    }
                }
            }

            FreeBusyServer server = new FreeBusyServer(this);

            // Run
            for (;;)
            {
                Interlocked.Increment(ref _iterationCount);
                try
                {
                    for (;;)
                    {
                        // Wait for a connection
                        TcpClient client = listener.AcceptTcpClient();
                        Interlocked.Increment(ref _requestCount);
                        // And handle it in the UI thread to allow GAB access
                        Tasks.Task(null, this, "FreeBusyHandler", () => server.HandleRequest(client));
                    }
                }
                catch (Exception e)
                {
                    Logger.Instance.Error(this, "Error in FreeBusy server: {0}", e);
                }
            }
        }
 public void SelectTask(Guid id)
 {
     SelectedTask = Tasks.SingleOrDefault(t => t.Id == id);
     TasksUpdated?.Invoke(this, null);
 }
Beispiel #60
0
    static public void Main()
    {
        Compiler.AutoGeneration.ValidateCAAssemblies = CAValidation.Disabled;

        var bin   = new Feature("MyApp Binaries");
        var tools = new Feature("MyApp Tools");

        var project =
            new ManagedProject("ManagedSetup",
                               //one of possible ways of setting custom INSTALLDIR (disabled for demo purposes)
                               new ManagedAction(Script.SetInstallDir,
                                                 Return.check,
                                                 When.Before,
                                                 Step.LaunchConditions,
                                                 Condition.NOT_Installed,
                                                 Sequence.InstallUISequence),
                               new Dir(@"%ProgramFiles%\My Company\My Product",
                                       new File(bin, @"..\Files\bin\MyApp.exe"),
                                       new Dir(bin, "Docs",
                                               new File(bin, "readme.txt"))),

                               new Dir(new Id("TOOLSDIR"), tools, "Tools",
                                       new File(tools, "setup.cs")),

                               //reading TOOLSDIR from registry; the alternative ways is project_UIInit
                               new RegValueProperty("TOOLSDIR",
                                                    RegistryHive.CurrentUser,
                                                    @"SOFTWARE\7-Zip",
                                                    "Path",
                                                    defaultValue: @"C:\My Company\tools")
                               );

        //project.ManagedUI = ManagedUI.Empty;
        project.ManagedUI = ManagedUI.Default; //Wix# ManagedUI
        //project.UI = WUI.WixUI_ProgressOnly; //native MSI UI

        project.UILoaded                  += project_UIInit;
        project.UIInitialized             += Project_UIInitialized;
        project.Load                      += project_Load;
        project.BeforeInstall             += project_BeforeInstall;
        project.AfterInstall              += project_AfterInstall;
        project.DefaultDeferredProperties += ",ADDLOCAL";

        project.BeforeInstall += args =>
        {
            if (!args.IsUninstalling)
            {
                Tasks.StopService("some_service", throwOnError: false);
            }
        };

        project.AfterInstall += args =>
        {
            if (!args.IsUninstalling)
            {
                Tasks.StartService("some_service", throwOnError: false);
            }
        };

        project.GUID = new Guid("6f330b47-2577-43ad-9095-1861ba25889b");
        // project.PreserveTempFiles = true;

        Compiler.BuildMsi(project);
    }