Example #1
0
        public async Task SendMessage(Action action, Sensor sensor, double value)
        {
            var typedMessage = new TypedMessage();

            var taskDescriptor   = new TaskDescriptor();
            var actionDescriptor = new ActionDescriptor();

            actionDescriptor.Parameter = "true";
            actionDescriptor.Type      = Action.Indication;

            taskDescriptor.Action = actionDescriptor;

            var conditionDescriptor = new ConditionDescriptor();

            conditionDescriptor.ComparisonType = Condition.GreaterThan;
            conditionDescriptor.SensorType     = sensor;
            conditionDescriptor.Target         = value;
            taskDescriptor.Condition           = conditionDescriptor;

            taskDescriptor.DeviceId = "raspberry1";

            typedMessage.Data = taskDescriptor;
            typedMessage.Type = AutomationSystemCore.Management.MessageHeaders.CreateTask;

            string connectionString = "HostName=AutomationSystemHub.azure-devices.net;DeviceId=test;SharedAccessKey=O/B4sln1uG0KmnBeSeEZoxbVODL27q5coJmd8G/z2s4=";

            var deviceClientSend = DeviceClient.CreateFromConnectionString(connectionString);

            var messageString = JsonConvert.SerializeObject(typedMessage);
            var message       = new Microsoft.Azure.Devices.Client.Message(Encoding.ASCII.GetBytes(messageString));

            await deviceClientSend.SendEventAsync(message);

            Debug.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString);
        }
Example #2
0
        private static WorkItem _AddTask(TaskDescriptor task)
        {
            var taskFile = HttpRuntime.AppDomainAppPath + "app_data\\tasks\\" + task.Name + ".xml";

            if (!File.Exists(taskFile))
            {
                var workItem = new WorkItem()
                {
                    Title                = task.Title,
                    Name                 = task.Name,
                    Description          = task.Description,
                    File                 = taskFile,
                    JobType              = task.JobType,
                    Frequency            = task.Frequency,
                    StartAt              = task.StartAt,
                    NextStart            = task.GetNextStart(task.StartAt),
                    Recurs               = task.Recurs,
                    RecurringMonths      = task.RecurringMonths,
                    RecurringDaysOfMonth = task.RecurringDaysOfMonth,
                    RecurringDaysOfWeek  = task.RecurringDaysOfWeek
                };

                if (task.CommandData != null && task.CommandData.Count > 0)
                {
                    workItem.CommandData = task.CommandData;
                }

                workItem.Save();
                return(workItem);
            }
            return(null);
        }
        internal static async Task <TaskModel> MapAsync(this TaskDescriptor entity, TaskExecutionInfo lastExecutionInfo = null)
        {
            var model = new TaskModel();
            await entity.MapAsync(model, lastExecutionInfo);

            return(model);
        }
        internal static async Task MapAsync(this TaskDescriptor entity, TaskModel model, TaskExecutionInfo lastExecutionInfo = null)
        {
            dynamic parameters = new ExpandoObject();

            parameters.LastExecutionInfo = lastExecutionInfo;

            await MapperFactory.MapAsync(entity, model, parameters);
        }
Example #5
0
        /// <summary>
        /// Add a new task to scheduler
        /// </summary>
        /// <param name="task"></param>
        public static void AddTask(TaskDescriptor task)
        {
            var t = _AddTask(task);

            if (t != null)
            {
                Workers.Add(t);
            }
        }
Example #6
0
 public IActionResult OnGet(int id)
 {
     Descriptor = _taskManager.GeTask(id);
     if (Descriptor == null)
     {
         return(NotFound());
     }
     return(Page());
 }
Example #7
0
        private async Task <string> GetTaskMessage(TaskDescriptor task, string resourceKey)
        {
            var normalizedTypeName = _taskActivator.GetNormalizedTypeName(task);

            string message = normalizedTypeName.HasValue()
                ? await Services.Localization.GetResourceAsync(resourceKey + "." + normalizedTypeName, logIfNotFound : false, returnEmptyIfNotFound : true)
                : null;

            return(message.IsEmpty() ? T(resourceKey) : message);
        }
        public ActionResult Create(TaskDescriptor task, FormCollection forms)
        {
            var recurringDaysOfMonth = forms["RecurringDaysOfMonth"];
            var recurringDaysOfWeek  = forms["RecurringDaysOfWeek"];
            var recurringMonths      = forms["RecurringMonths"];
            var jobType = forms["JobType"];

            if (task.Frequency == Frequencies.Weekly)
            {
                if (recurringDaysOfWeek != null && recurringDaysOfWeek.Length > 0)
                {
                    task.RecurringDaysOfWeek = recurringDaysOfWeek.Split(',').Select(a => Convert.ToInt32(a)).ToArray();
                }
            }

            if (task.Frequency == Frequencies.Monthly)
            {
                if (recurringDaysOfMonth != null && recurringDaysOfMonth.Length > 0)
                {
                    task.RecurringDaysOfMonth = recurringDaysOfMonth.Split(',').Select(a => Convert.ToInt32(a)).ToArray();
                }

                if (recurringMonths != null && recurringMonths.Length > 0)
                {
                    task.RecurringMonths = recurringMonths.Split(',').Select(a => Convert.ToInt32(a)).ToArray();
                }
            }

            if (!string.IsNullOrEmpty(jobType))
            {
                task.JobType = Type.GetType(jobType);
                var props = task.JobType.GetProperties();
                task.CommandData = new System.Collections.Generic.Dictionary <string, object>();

                foreach (var pro in props)
                {
                    var key = task.JobType.Name + "." + pro.Name;
                    if (forms[key] != null)
                    {
                        task.CommandData.Add(pro.Name, Convert.ChangeType(forms[key], pro.PropertyType));
                    }
                }
            }

            task.Name = DNA.Utility.TextUtility.Slug(task.JobType.FullName + "." + System.IO.Path.GetRandomFileName().Replace(".", ""));
            Scheduler.AddTask(task);
            return(PartialView());
        }
        private void DigestMessage(TypedMessage msg)
        {
            switch (msg.Type)
            {
            case MessageHeaders.CreateTask:
                TaskDescriptor desc    = ((JObject)msg.Data).ToObject <TaskDescriptor>();
                AutomationTask newTask = new AutomationTask(thisDevice)
                {
                    Id = "0",

                    DeviceSensor  = desc.Condition.SensorType,
                    TaskCondition = desc.Condition.ComparisonType,
                    Value         = desc.Condition.Target,

                    ActionType      = desc.Action.Type,
                    ActionParameter = desc.Action.Parameter,
                };
                asdf = DateTime.Now;
                tasks.Add(newTask);
                break;
            }
        }
Example #10
0
        public virtual async Task <ExportProfile> InsertExportProfileAsync(
            string providerSystemName,
            string name,
            string fileExtension,
            ExportFeatures features,
            bool isSystemProfile     = false,
            string profileSystemName = null,
            int cloneFromProfileId   = 0)
        {
            Guard.NotEmpty(providerSystemName, nameof(providerSystemName));

            if (name.IsEmpty())
            {
                name = providerSystemName;
            }

            if (!isSystemProfile)
            {
                var profileCount = await _db.ExportProfiles.CountAsync(x => x.ProviderSystemName == providerSystemName);

                name = $"{T("Common.My").Value} {name} {profileCount + 1}";
            }

            TaskDescriptor task         = null;
            ExportProfile  cloneProfile = null;
            ExportProfile  profile      = null;

            if (cloneFromProfileId != 0)
            {
                cloneProfile = await _db.ExportProfiles
                               .Include(x => x.Task)
                               .Include(x => x.Deployments)
                               .FindByIdAsync(cloneFromProfileId);
            }

            if (cloneProfile == null)
            {
                task = new TaskDescriptor
                {
                    CronExpression = "0 */6 * * *",     // Every six hours.
                    Type           = nameof(DataExportTask),
                    Enabled        = false,
                    StopOnError    = false,
                    IsHidden       = true
                };
            }
            else
            {
                task = cloneProfile.Task.Clone();
            }

            task.Name = name + " Task";

            _db.TaskDescriptors.Add(task);

            // Get the task ID.
            await _db.SaveChangesAsync();

            if (cloneProfile == null)
            {
                profile = new ExportProfile
                {
                    FileNamePattern = _defaultFileNamePattern
                };

                if (isSystemProfile)
                {
                    profile.Enabled          = true;
                    profile.PerStore         = false;
                    profile.CreateZipArchive = false;
                    profile.Cleanup          = false;
                }
                else
                {
                    // What we do here is to preset typical settings for feed creation
                    // but on the other hand they may be untypical for generic data export\exchange.
                    var projection = new ExportProjection
                    {
                        RemoveCriticalCharacters = true,
                        CriticalCharacters       = "¼,½,¾",
                        PriceType         = PriceDisplayType.PreSelectedPrice,
                        NoGroupedProducts = features.HasFlag(ExportFeatures.CanOmitGroupedProducts),
                        OnlyIndividuallyVisibleAssociated = true,
                        DescriptionMerging = ExportDescriptionMerging.Description
                    };

                    var filter = new ExportFilter
                    {
                        IsPublished        = true,
                        ShoppingCartTypeId = (int)ShoppingCartType.ShoppingCart
                    };

                    using var writer1 = new StringWriter();
                    new XmlSerializer(typeof(ExportProjection)).Serialize(writer1, projection);
                    profile.Projection = writer1.ToString();

                    using var writer2 = new StringWriter();
                    new XmlSerializer(typeof(ExportFilter)).Serialize(writer2, projection);
                    profile.Filtering = writer2.ToString();
                }
            }
            else
            {
                profile = cloneProfile.Clone();
            }

            profile.IsSystemProfile    = isSystemProfile;
            profile.Name               = name;
            profile.ProviderSystemName = providerSystemName;
            profile.TaskId             = task.Id;

            var cleanedSystemName = providerSystemName
                                    .Replace("Exports.", string.Empty)
                                    .Replace("Feeds.", string.Empty)
                                    .Replace("/", string.Empty)
                                    .Replace("-", string.Empty);

            var directoryName = SeoHelper.BuildSlug(cleanedSystemName, true, false, false)
                                .ToValidPath()
                                .Truncate(_dataExchangeSettings.MaxFileNameLength);

            // TODO: (mg) (core) find out how to correctly build new app relative paths for ExportProfile.FolderName like x '~/App_Data/Tenants/Default/ExportProfiles/bmecatproductxml-1-2'
            // ExportProfile.FolderName must fulfil PathHelper.IsSafeAppRootPath! See also below.
            var tenantRoot       = DataSettings.Instance.TenantRoot;
            var profileDirectory = tenantRoot.GetDirectory("ExportProfiles");

            // TODO: (mg) (core) TenantRoot is rooted to the tenant dir and DOES NOT CONTAIN "App_Data/Tenants/{TenantName}" anymore.
            // The result will be "ExportProfiles/{UniqueDirName}, which conflicts with how we saved the path in the past ("~/App_Data/..."). You must
            // "upgrade" legacy pathes to new root whenever an entity is loaded and processed.
            profile.FolderName = tenantRoot.PathCombine(profileDirectory.SubPath, tenantRoot.CreateUniqueDirectoryName(profileDirectory.SubPath, directoryName));

            profile.SystemName = profileSystemName.IsEmpty() && isSystemProfile
                ? cleanedSystemName
                : profileSystemName;

            _db.ExportProfiles.Add(profile);

            // Get the export profile ID.
            await _db.SaveChangesAsync();

            task.Alias = profile.Id.ToString();

            if (fileExtension.HasValue() && !isSystemProfile)
            {
                if (cloneProfile == null)
                {
                    if (features.HasFlag(ExportFeatures.CreatesInitialPublicDeployment))
                    {
                        var subFolder = tenantRoot.CreateUniqueDirectoryName(DataExporter.PublicFolder, directoryName);

                        profile.Deployments.Add(new ExportDeployment
                        {
                            ProfileId      = profile.Id,
                            Enabled        = true,
                            DeploymentType = ExportDeploymentType.PublicFolder,
                            Name           = profile.Name,
                            SubFolder      = subFolder
                        });
                    }
                }
                else
                {
                    cloneProfile.Deployments.Each(x => profile.Deployments.Add(x.Clone()));
                }
            }

            // Finally update task and export profile.
            await _db.SaveChangesAsync();

            return(profile);
        }