コード例 #1
0
        public ActionResult Create([Bind(Include = "ContactId,FirstName,LastName,EmailAddress,PhoneNumber")] Contact contact)
        {
            if (ModelState.IsValid)
            {
                db.Contacts.Add(contact);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(contact));
        }
コード例 #2
0
        public ActionResult Create([Bind(Include = "HardwareId,Board,Camera")] Hardware hardware)
        {
            if (ModelState.IsValid)
            {
                db.Hardware.Add(hardware);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(hardware));
        }
コード例 #3
0
        public ActionResult Create([Bind(Include = "CommandId,Cmd,Timestamp,CommandStatus,IsmDeviceId")] Command command)
        {
            if (ModelState.IsValid)
            {
                db.Commands.Add(command);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.IsmDeviceId = new SelectList(db.IsmDevices, "IsmDeviceId", "DeviceId", command.IsmDeviceId);
            return(View(command));
        }
コード例 #4
0
        public ActionResult Create([Bind(Include = "LocationId,Country,City,PostalCode,Street,StreetNumber,ContactId")] Location location)
        {
            if (ModelState.IsValid)
            {
                db.Locations.Add(location);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.ContactId = new SelectList(db.Contacts, "ContactId", "FirstName", location.ContactId);
            return(View(location));
        }
コード例 #5
0
        public ActionResult Create([Bind(Include = "FilamentDataId,Time,FC,FL,H1,H2,H3,H4,H5,H6,H7,H8,H9,H10,IsmDeviceId,DeviceId,BlobUriImg,BlobUriColoredImg")] FilamentData filamentData)
        {
            if (ModelState.IsValid)
            {
                db.FilamentData.Add(filamentData);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.IsmDeviceId = new SelectList(db.IsmDevices, "IsmDeviceId", "DeviceId", filamentData.IsmDeviceId);
            return(View(filamentData));
        }
コード例 #6
0
        public async Task <ActionResult> Approve(int?id)
        {
            // Check that an ID has been passed
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            var newDevice = db.NewDevices.Find(id);

            // Check that device exists
            if (newDevice == null)
            {
                return(HttpNotFound());
            }
            // If device has already been approved, don't go any further
            if (newDevice.Approved)
            {
                return(RedirectToAction("Index"));
            }
            // Create new IsmDevice to add to databasse
            var device = new IsmDevice
            {
                DeviceId     = newDevice.DeviceId,
                HardwareId   = newDevice.HardwareId,
                SoftwareId   = newDevice.ReleaseId,
                LocationId   = newDevice.LocationId,
                UpdateStatus = IsmIoTSettings.UpdateStatus.READY
            };

            // Add to DB
            db.IsmDevices.Add(device);
            db.SaveChanges();
            // Try to add to IoT Hub
            try
            {
                await AddDeviceAsync(device.DeviceId);

                // Approve device if exception hasn't been thrown
                newDevice.Approved = true;
                db.SaveChanges();
            }
            catch (Exception)
            {
                // Anzeigen, dass etwas schief ging
                // Eintrag aus DB entfernen
                db.IsmDevices.Remove(device);
                db.SaveChanges();
            }
            return(RedirectToAction("Index"));
        }
コード例 #7
0
ファイル: EventProcessor.cs プロジェクト: leononame/ismcloud
        private void UpdateFirmwareUpdateStatus(UpdateState updateState)
        {
            using (IsmIoTPortalContext db = new IsmIoTPortalContext())
            {
                // Get reference to device
                string deviceId = updateState.DeviceId;
                var    device   = db.IsmDevices.FirstOrDefault(d => d.DeviceId.Equals(deviceId));
                if (device == null)
                {
                    this.OnLogMessage(new LogMessageEventArgs(String.Format("{0} > UpdateFirmwareUpdateStatus Error: DeviceId unknown.<br>", DateTime.Now.ToString())));
                    return;
                }
                // Check update status for error
                if (updateState.FwUpdateStatus.Contains("Error"))
                {
                    device.UpdateStatus = updateState.FwUpdateStatus;
                }
                else
                {
                    device.UpdateStatus = IsmIoTSettings.UpdateStatus.READY;
                }

                // Get reference to release
                var release = db.Releases.FirstOrDefault(r => r.Name.Equals(updateState.Version));
                if (release == null)
                {
                    this.OnLogMessage(new LogMessageEventArgs(String.Format("{0} > UpdateFirmwareUpdateStatus Error: Release unknown.<br>", DateTime.Now.ToString())));
                    db.SaveChanges();
                    return;
                }
                device.UpdateMessage = updateState.Message;
                var updateLog = new UpdateLog
                {
                    IsmDeviceId = device.IsmDeviceId,
                    ReleaseId   = release.SoftwareId,
                    LogData     = updateState.Log,
                    Date        = DateTime.Now
                };
                db.UpdateLogs.Add(updateLog);
                device.SoftwareId = release.SoftwareId;
                db.SaveChanges();
                this.OnLogMessage(new LogMessageEventArgs(String.Format("{0} > UpdateFirmwareUpdateStatus Info: Update Log: {1} <br>", DateTime.Now.ToString(), updateState.Log)));
            }
        }
コード例 #8
0
        /// <summary>
        /// API call to add new device to database.
        /// </summary>
        /// <param name="id">Identifier of the device</param>
        /// <param name="loc">Location ID</param>
        /// <param name="hw">Hardware ID</param>
        /// <param name="sw">Software ID</param>
        /// <returns>Device that was created.</returns>
        public object Get(string id, int loc, int hw, int sw)
        {
            var err = new { Error = "An error occured." };

            // Check Device ID against a whitelist of values to prevent XSS
            if (!IsmIoTSettings.RegexHelper.Text.IsMatch(id))
            {
                return(err);
            }

            // If device with same ID already exists, return error
            if (db.IsmDevices.Any(d => d.DeviceId == id) || db.NewDevices.Any(d => d.DeviceId == id))
            {
                return new { Error = "This device ID is already taken." }
            }
            ;
            // Generate random password of length 32 with at least 1 non-alphanumerical character
            string password = System.Web.Security.Membership.GeneratePassword(32, 1);
            // We create a hash of the password to store it in Database
            // No need for salt since this scrypt implementation adds salt automatically (scrypt requires salt)
            string hash = new ScryptEncoder().Encode(password);
            var    dev  = new NewDevice
            {
                DeviceId   = id,
                HardwareId = hw,
                LocationId = loc,
                ReleaseId  = sw,
                Code       = generator.Next(0, 999999).ToString("D6"),
                Approved   = false,
                Password   = hash
            };

            db.NewDevices.Add(dev);
            db.SaveChanges();
            return(new
            {
                Id = dev.DeviceId,
                Code = dev.Code,
                Password = password
            });
        }
コード例 #9
0
        public async Task <ActionResult> Create([Bind(Include = "IsmDeviceId,DeviceId,LocationId,SoftwareId,HardwareId")] IsmDevice ismDevice)
        {
            if (ModelState.IsValid)
            {
                // Zuerst einmal in DB anlegen
                // Es darf nicht passieren, dass man einen eintrag in der Identity Registry anlegt
                // und diesen nicht in der DB registriert (= Device Leak)
                db.IsmDevices.Add(ismDevice);
                db.SaveChanges();

                try
                {
                    await AddDeviceAsync(ismDevice.DeviceId);
                }
                catch (Exception)
                {
                    // Anzeigen, dass etwas schief ging
                    // Eintrag aus DB entfernen
                }

                /*
                 * // Create Dashboard Queue for the new Device
                 * // http://stackoverflow.com/questions/30749945/create-azure-service-bus-queue-shared-access-policy-programmatically
                 * // http://www.cloudcasts.net/devguide/Default.aspx?id=12018
                 * //
                 * // Create a token provider with the relevant credentials.
                 * TokenProvider credentials = TokenProvider.CreateSharedAccessSignatureTokenProvider(IsmIoTSettings.Settings.sbRootSasName, IsmIoTSettings.Settings.sbRootSasKey);
                 * // Create a URI for the service bus.
                 * Uri serviceBusUri = ServiceBusEnvironment.CreateServiceUri("sb", IsmIoTSettings.Settings.sbNamespace, string.Empty);
                 * // Create a NamespaceManager for the specified namespace using the specified credentials.
                 * NamespaceManager namespaceManager = new NamespaceManager(serviceBusUri, credentials);
                 * string queueName = ismDevice.DeviceId; // Queue name equals DeviceId
                 * QueueDescription queueDescription = await namespaceManager.CreateQueueAsync(queueName);
                 */

                return(RedirectToAction("Index"));
            }

            ViewBag.HardwareId = new SelectList(db.Hardware, "HardwareId", "Board", ismDevice.HardwareId);
            ViewBag.LocationId = new SelectList(db.Locations, "LocationId", "Country", ismDevice.LocationId);
            ViewBag.SoftwareId = new SelectList(db.Software, "SoftwareId", "SoftwareVersion", ismDevice.SoftwareId);
            return(View(ismDevice));
        }
コード例 #10
0
        // GET: IsmDevices
        public async Task <ActionResult> Index()
        {
            var ismDevices = db.IsmDevices.Include(i => i.Hardware).Include(i => i.Location).Include(i => i.Software);

            // Get the whole Info from Identity Registry via a Device object for each DeviceId in DB
            Dictionary <string, Device> devices = new Dictionary <string, Device>();

            foreach (IsmDevice d in ismDevices)
            {
                Device device = await registryManager.GetDeviceAsync(d.DeviceId);

                // If a device was offline during last firmware update and is now online again,
                // Update the UpdateStatus to ready.
                if (d.UpdateStatus == IsmIoTSettings.UpdateStatus.OFFLINE && device.ConnectionState == DeviceConnectionState.Connected)
                {
                    d.UpdateStatus = IsmIoTSettings.UpdateStatus.READY;
                }
                devices.Add(d.DeviceId, device);
            }
            ViewBag.DeviceList = devices;
            db.SaveChanges();

            return(View(ismDevices.ToList()));
        }
コード例 #11
0
ファイル: WorkerRole.cs プロジェクト: leononame/ismcloud
        /*
         *  In the Changed event, RoleEnvironment.CurrentRoleInstance.Role.Instances returns the target role instances,
         *  not the original role instances. If you need to know about the original instances,
         *  you can save this information when the Changing event fires and access it from the Changed event
         *  (since these events are always fired in sequence).
         */
        private void RoleEnvironmentChanged(object sender, RoleEnvironmentChangedEventArgs e)
        {
            targetNumOfInstances = RoleEnvironment.CurrentRoleInstance.Role.Instances.Count;
            Logfile.Get(logfile).fTextout(Logging.Fontcolors.RED, "{0} > RoleEnvironmentChanged Eventhandler logging target instance count of {1} <br>", DateTime.Now.ToString(), targetNumOfInstances);
            Logfile.Get(logfile).Update();

            // The change is a downscale! Delete Mcr flag entry from db
            if (originalNumOfInstances > targetNumOfInstances)
            {
                using (IsmIoTPortalContext db = new IsmIoTPortalContext())
                {
                    try
                    {
                        // The highest role instance id was determined in the changing event
                        ImagingProcessorWorkerInstance entry = null;
                        var queryResults = db.ImagingProcessorWorkerInstances.Where(en => en.RoleInstanceId == highestRoleInstanceId);
                        if (queryResults.Count() > 0)
                        {
                            entry = queryResults.First();
                        }

                        if (lowestRoleInstanceId) // The role instance with the lowest id deletes the db entry in case of downscale.
                        {
                            Logfile.Get(logfile).fTextout(Logging.Fontcolors.RED, "{0} > Delete database entry with key {1} <br>", DateTime.Now.ToString(), highestRoleInstanceId);
                            Logfile.Get(logfile).Update();

                            // Delete entry from DB
                            db.ImagingProcessorWorkerInstances.Remove(entry);
                            db.SaveChanges();
                        }
                    }
                    catch (Exception ex)
                    {
                        Logfile.Get(logfile).fTextout(Logging.Fontcolors.RED, "{0} > Failed to delete McrInstalled flag DB entry. <br>", DateTime.Now.ToString());
                        Logfile.Get(logfile).fTextout(Logging.Fontcolors.RED, "{0} > Exception: {1} <br>", DateTime.Now.ToString(), ex.Message);
                        Logfile.Get(logfile).Update();
                        throw;
                    }
                }
            }
        }
コード例 #12
0
ファイル: WorkerRole.cs プロジェクト: leononame/ismcloud
        private static async Task ProcessCmdMessage(FeedbackRecord record)
        {
            using (var db = new IsmIoTPortalContext())
            {
                // Achtung .Substring(4), weil die ersten 3 Zeichen das Präfix "CMD" sind
                int CommandId = Convert.ToInt32(record.OriginalMessageId.Substring(4));   // Beim Senden des Commands wurde der Schlüssel des DB Eintrages als MessageId angegeben
                var entry     = db.Commands.Where(c => c.CommandId == CommandId).First(); // Es gibt natürlich nur ein DB Eintrag mit dem Schlüssel CommandId

                if (record.StatusCode == FeedbackStatusCode.Success)
                {
                    db.Entry(entry).Entity.CommandStatus = CommandStatus.SUCCESS;
                }
                else // Rejected,...
                {
                    db.Entry(entry).Entity.CommandStatus = CommandStatus.FAILURE;
                }

                db.Entry(entry).State = EntityState.Modified;
                db.SaveChanges();

                await signalRHelper.IsmDevicesIndexChangedTask();
            }
        }
コード例 #13
0
ファイル: WorkerRole.cs プロジェクト: leononame/ismcloud
        private async Task RunAsync(CancellationToken cancellationToken)
        {
            // 1. Check if this is after restart and "MCR is installed" already
            //
            bool   mcrAlreadyInstalled = false;
            string line = "";

            try
            {
                using (IsmIoTPortalContext db = new IsmIoTPortalContext())
                {
                    ImagingProcessorWorkerInstance entry = null;
                    var queryResults = db.ImagingProcessorWorkerInstances.Where(e => e.RoleInstanceId == RoleEnvironment.CurrentRoleInstance.Id);
                    if (queryResults.Count() > 0)
                    {
                        entry = queryResults.First(); // Es gibt natürlich nur ein DB Eintrag mit dem Schlüssel RoleInstanceId
                    }
                    if (entry == null)                // First start of this Instance -> Create and add new DB entry
                    {
                        //
                        entry = new ImagingProcessorWorkerInstance();
                        entry.RoleInstanceId = RoleEnvironment.CurrentRoleInstance.Id;
                        entry.McrInstalled   = false;
                        entry.Timestamp      = DateTime.UtcNow;
                        db.ImagingProcessorWorkerInstances.Add(entry);
                        db.SaveChanges();
                        // mcrAlreadyInstalled is still false
                    }
                    else
                    {
                        if (entry.McrInstalled == true)
                        {
                            mcrAlreadyInstalled = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logfile.Get(logfile).fTextout(Logging.Fontcolors.RED, "{0} > Failed to use McrInstalled flag. <br>", DateTime.Now.ToString());
                Logfile.Get(logfile).fTextout(Logging.Fontcolors.RED, "{0} > Exception: {1} <br>", DateTime.Now.ToString(), ex.Message);
                Logfile.Get(logfile).Update();
                mcrAlreadyInstalled = false;
            }

            // *************DEBUG*****************
            mcrAlreadyInstalled = true; // DEBUG


            // 2. Poll the MCR Installation Log if mcrAlreadyInstalled == false
            //
            Stopwatch stopWatch = new Stopwatch();
            bool      timeout   = false;

            stopWatch.Start();
            while (!mcrAlreadyInstalled && true)
            {
                try
                {
                    // Timeout
                    if (stopWatch.Elapsed > TimeSpan.FromMinutes(30))
                    {
                        timeout = true;
                        break;
                    }

                    // Sleep
                    await Task.Delay(TimeSpan.FromMinutes(5));

                    if (!File.Exists(mcrlog))
                    {
                        continue;
                    }

                    line = File.ReadLines(mcrlog).Last();
                    if (!line.Contains("End - Successful"))
                    {
                        continue;
                    }
                    else
                    {
                        break;
                    }
                }
                catch (Exception ex)
                {
                    // Probably file reading errors because the MCR installer uses the file
                    continue;
                }
            }


            //
            // MCR is installed now -->Set the flag in DB and Reboot
            if (!mcrAlreadyInstalled && timeout == false)
            {
                try
                {
                    using (IsmIoTPortalContext db = new IsmIoTPortalContext())
                    {
                        // Update DB entry and set the McrInstalled Flag to true
                        var entry = db.ImagingProcessorWorkerInstances.Where(e => e.RoleInstanceId == RoleEnvironment.CurrentRoleInstance.Id).First(); // // Es gibt natürlich nur ein DB Eintrag mit dem Schlüssel RoleInstanceId
                        db.Entry(entry).Entity.McrInstalled = true;
                        db.Entry(entry).Entity.Timestamp    = DateTime.UtcNow;
                        db.Entry(entry).State = EntityState.Modified;
                        db.SaveChanges();

                        // Restart Worker Role
                        // Update: Der User nach dem Startup Task darf wohl kein shuttdown ausführen --> benutze schtasks
                        //string stat = ExecuteCommandSync("shutdown /R /F");

                        // Mit schtasks
                        DateTime executionTime = DateTime.Now.Add(new TimeSpan(0, 1, 0));
                        string   date          = string.Format("{0}/{1}/{2}", executionTime.Month.ToString("d2"), executionTime.Day.ToString("d2"), executionTime.Year);
                        string   time          = string.Format("{0}:{1}", executionTime.Hour.ToString("d2"), executionTime.Minute.ToString("d2"));
                        string   cmd           = string.Format("schtasks /CREATE /TN RebootRoleInstance /SC ONCE /SD {0} /ST {1} /RL HIGHEST /RU scheduser /RP Qwer123 /TR \"shutdown /R /F\" /F", date, time);
                        string   stat          = ExecuteCommandSync(cmd);
                        Logfile.Get(logfile).fTextout(Logging.Fontcolors.RED, "{0} > {1} <br>", DateTime.Now.ToString(), stat);
                        Logfile.Get(logfile).Update();
                    }
                }
                catch (Exception ex)
                {
                    Logfile.Get(logfile).fTextout(Logging.Fontcolors.RED, "{0} > Failed writing to update McrInstalled flag and reboot. <br>", DateTime.Now.ToString());
                    Logfile.Get(logfile).fTextout(Logging.Fontcolors.RED, "{0} > Exception: {1} <br>", DateTime.Now.ToString(), ex.Message);
                    Logfile.Get(logfile).Update();
                }
            }
            // Timeout --> Write to log and do Not start Event Processor
            if (!mcrAlreadyInstalled && timeout == true)
            {
                Logfile.Get(logfile).fTextout(Logging.Fontcolors.RED, "{0} > Timeout occured during MCR Installation Polling. <br>", DateTime.Now.ToString());
                Logfile.Get(logfile).Update();
            }
            // Reboot and MCR is already installed --> Start Event Processor
            if (mcrAlreadyInstalled)
            {
                //
                // Create EventProcessorHost

                /*the iotHubD2cEndpoint in the example is the name of the device-to - cloud endpoint on your IoT hub.
                 * Technically, and IoT hub could have multiple endpoints that are compatible with Event Hubs.
                 * At this time the only Event Hubs - compatible endpoint is called "messages/events", so it is a fixed string. */
                string iotHubD2cEndpoint = "messages/events";
                string eventHubName      = CloudConfigurationManager.GetSetting("iotHubName"); //"IsmIoTHub";
                string consumerGroupName = EventHubConsumerGroup.DefaultGroupName;
                // Alternativ geht auch CurrentRoleInstance.Id (ist auch unique)
                //string eventProcessorHostName = Guid.NewGuid().ToString();

                string eventProcessorHostName = RoleEnvironment.CurrentRoleInstance.Id;
                // leaseContainerName-Parameter wie im scaled out event processing beispiel:
                // here it's using eventhub as lease name. but it can be specified as any you want.
                // if the host is having same lease name, it will be shared between hosts.
                // by default it is using eventhub name as lease name.
                eventProcessorHost = new EventProcessorHost(eventProcessorHostName,
                                                            iotHubD2cEndpoint,                                     // eigentlich steht hier der EventHub Name aber siehe Kommentar, bei IoTHubs ist hier der fixe string "messages/events" notwendig
                                                            consumerGroupName,
                                                                                                                   //iotHubConnectionString,
                                                            CloudConfigurationManager.GetSetting("ismiothub"),     //System.Configuration.ConfigurationSettings.AppSettings.Get("ismiothub"),
                                                                                                                   //EventProcessor.StorageConnectionString,
                                                            CloudConfigurationManager.GetSetting("ismiotstorage"), //System.Configuration.ConfigurationSettings.AppSettings.Get("ismiotstorage"),
                                                            eventHubName.ToLowerInvariant());

                factory = new EventProcessorFactory(logfile);
                await eventProcessorHost.RegisterEventProcessorFactoryAsync(factory);

                // Register EventProcessorHost
                Logfile.Get(logfile).fTextout("{0} > Registering EventProcessor... <br>", DateTime.Now.ToString());
                Logfile.Get(logfile).Update();

                // Ansatz ohne Factory. Hatte jedoch den Nachteil, dass man keine Referenz auf das EventProcessor Objekt
                // hat und somit z.B. keine Eventhandler registrieren konnte. Parameter an Konstruktor gigen ja auch nicht,
                // weil dieser niemals sichtbar aufgerufen wird bei dem Ansatz
                //eventProcessorHost.RegisterEventProcessorAsync<EventProcessor>().Wait();
            }

            while (!cancellationToken.IsCancellationRequested)
            {
                await Task.Delay(TimeSpan.FromHours(1), cancellationToken);
            }
        }
コード例 #14
0
        public Task <ActionResult> Create([Bind(Include = "SoftwareId,Name,Changelog")] Release release, string blobUrl)
        {
            if (ModelState.IsValid)
            {
                if (blobUrl != null && blobUrl.Length > 0)
                {
                    bool error = false;

                    // Check Software Version
                    var m = RegexHelper.SoftwareName.Match(release.Name);
                    if (!m.Success)
                    {
                        ViewBag.NameError = "Your prefix and suffix aren't valid values. The prefix is not optional.";
                        error             = true;
                    }
                    // If the uploaded file is not a tarfile, return with error
                    if (!RegexHelper.FwBlobUrl.IsMatch(blobUrl))
                    {
                        ViewBag.FileError = "URL must link to tarfile in an Azure BLOB storage container named 'fwupdates' packed with update data and a script named 'apply.sh'";
                        error             = true;
                    }
                    // If the software version already exists
                    if (db.Releases.Any(s => s.Name.ToLower().Equals(release.Name.ToLower())))
                    {
                        ViewBag.NameError = "This software version already exists.";
                        error             = true;
                    }
                    if (error)
                    {
                        return(Task.Factory.StartNew <ActionResult>(
                                   () => {
                            var softwareVersions = db.SoftwareVersions.ToList();
                            return View("Create", new SoftwareViewCreate
                            {
                                Release = null,
                                SoftwareVersions = softwareVersions
                            });
                        }));
                    }

                    // Ok, form is valid
                    // Read associated SoftwareVersion
                    // Get the group
                    var prefix          = m.Groups[1].Value;
                    var suffix          = m.Groups[4].Value;
                    var releaseNum      = Int32.Parse(m.Groups[2].Value);
                    var softwareVersion = db.SoftwareVersions.FirstOrDefault(sv => sv.Prefix.Equals(prefix) && sv.Suffix.Equals(suffix));
                    // If we don't find a SoftwareVersion in database, create a new one
                    if (softwareVersion == null)
                    {
                        softwareVersion = new SoftwareVersion
                        {
                            Prefix = prefix,
                            Suffix = suffix,
                            // First release
                            CurrentReleaseNum = 1
                        };
                        db.SoftwareVersions.Add(softwareVersion);
                    }
                    else
                    {
                        if (softwareVersion.CurrentReleaseNum + 1 != releaseNum)
                        {
                            ViewBag.NameError = "The release number is not correct.";
                            return(Task.Factory.StartNew <ActionResult>(
                                       () => {
                                var softwareVersions = db.SoftwareVersions.ToList();
                                return View("Create", new SoftwareViewCreate
                                {
                                    Release = null,
                                    SoftwareVersions = softwareVersions
                                });
                            }));
                        }
                        softwareVersion.CurrentReleaseNum = releaseNum;
                    }
                    // Add reference to SoftwareVersion to Release
                    release.SoftwareVersionId = softwareVersion.SoftwareVersionId;
                    release.Num = softwareVersion.CurrentReleaseNum;

                    try
                    {
                        release.Status = "Uploaded";
                        release.Author = "SWT";
                        release.Date   = DateTime.Now;
                        // Add to database
                        db.Releases.Add(release);
                        db.SaveChanges();

                        var location = Server.MapPath("~/sw-updates/" + release.Name);
                        PortalUtils.CreateNewFirmwareUpdateTask(blobUrl, location, release.SoftwareId);
                        return(Task.Factory.StartNew <ActionResult>(
                                   () => {
                            return RedirectToAction("Index");
                        }));
                        //return RedirectToAction("Index");
                    }
                    catch (Exception e)
                    {
                        release.Status = "Error during initialization";
                        db.SaveChanges();
                    }
                }
            }

            return(Task.Factory.StartNew <ActionResult>(
                       () => {
                return View(release);
            }));
        }
コード例 #15
0
ファイル: PortalUtils.cs プロジェクト: leononame/ismcloud
        /// <summary>
        /// This function rolls out a firmware update to a specified device asynchronously. Call without using await.
        /// </summary>
        /// <param name="device">Device ID.</param>
        /// <param name="serviceClient">Service Client used to call direct methods.</param>
        /// <param name="release">Refernce to the release we want to roll out</param>
        /// <returns></returns>
        public static async Task RolloutFwUpdateAsync(string device, ServiceClient serviceClient, Release release)
        {
            // Get reference to device
            var ismDevice = db.IsmDevices.FirstOrDefault(d => d.DeviceId.Equals(device));

            if (ismDevice == null)
            {
                return;
            }
            // Method to invoke
            var methodInvokation = new CloudToDeviceMethod("firmwareUpdate")
            {
                ResponseTimeout = TimeSpan.FromSeconds(30)
            };
            // Method payload
            var payload = JsonConvert.SerializeObject(new
            {
                blobUrl  = release.Url,
                fileName = release.Url.Split('/').Last(),
                version  = release.Name
            });

            methodInvokation.SetPayloadJson(payload);

            ismDevice.UpdateStatus = IsmIoTSettings.UpdateStatus.REQUESTED;
            db.SaveChanges();
            // Invoke method on device
            // Cancellation after 45 seconds
            var cts = new CancellationTokenSource();

            cts.CancelAfter(45000);
            var methodTask = serviceClient.InvokeDeviceMethodAsync(device, methodInvokation, cts.Token);

            //var timeoutTask = Task.WhenAny(methodTask, Task.Delay(3000));
            try
            {
                var response = await methodTask.ConfigureAwait(false);

                if (response.Status != 200)
                {
                    // Handle errors
                    ismDevice.UpdateStatus = IsmIoTSettings.UpdateStatus.ERROR;
                }
                else
                {
                    ismDevice.UpdateStatus = IsmIoTSettings.UpdateStatus.PROCESSING;
                }
            }
            catch (OperationCanceledException e)
            {
                ismDevice.UpdateStatus = IsmIoTSettings.UpdateStatus.CANCELATION;
            }
            catch (DeviceNotFoundException e)
            {
                ismDevice.UpdateStatus = IsmIoTSettings.UpdateStatus.OFFLINE;
            }
            catch (Exception e)
            {
                ismDevice.UpdateStatus = IsmIoTSettings.UpdateStatus.ERROR;
            }
            finally
            {
                db.SaveChanges();
            }
        }
コード例 #16
0
ファイル: PortalUtils.cs プロジェクト: leononame/ismcloud
        /// <summary>
        /// Creates a new firmware update ready to be rolled out. Call asynchronously because it can take some time. Don't use await.
        /// </summary>
        /// <param name="file">File of firmware update. Must be a tar.</param>
        /// <param name="location">Directory of where file will be stored on server.</param>
        /// <param name="id">Key of software version in databse.</param>
        /// <returns></returns>
        public static async Task CreateNewFirmwareUpdateTask(string fileUrl, string location, int id)
        {
            IsmIoTPortalContext db = new IsmIoTPortalContext();
            // Get reference to software
            var software = db.Releases.Find(id);

            try
            {
                // Filename is always the same
                var fileName = "update.tar";
                // Creates all directories in path that do not exist
                Directory.CreateDirectory(location);
                // Full path of file
                string filePath = Path.Combine(location, fileName);
                // Save file to disk
                var retval = await DownloadFromBlobStorage(fileUrl, filePath).ConfigureAwait(false);

                if (retval.Equals("Error"))
                {
                    // Update software status
                    software.Status = "Error during download of file.";
                    db.SaveChanges();
                    return;
                }
                // Update software status
                software.Status = "Saved";
                db.SaveChanges();

                // Calculate SHA 256 hash
                var checksum = await Sha256Sum(filePath).ConfigureAwait(false);

                // Get checksum string
                var checksum_string = BitConverter.ToString(checksum).Replace("-", String.Empty).ToLower();
                // Add checksum string to database
                software.Checksum = checksum_string;
                db.SaveChanges();

                // Get access to key vault
                var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetToken));
                // Sign Checksum
                var sig = await kv.SignAsync(
                    // Key ID is in appsettings
                    keyIdentifier : ConfigurationManager.AppSettings["kv:fw-signing-key"],
                    // Sign with RS256
                    algorithm : Microsoft.Azure.KeyVault.WebKey.JsonWebKeySignatureAlgorithm.RS256,
                    // We want to sign the checksum
                    digest : checksum).ConfigureAwait(false);

                // Save byte data as sig
                string checksumPath = Path.Combine(location, "sig");
                File.WriteAllBytes(checksumPath, sig.Result);
                software.Status = "Signed";
                db.SaveChanges();

                // Create tarball (.tar.gz file containing signed checksum and tarfile with update)
                var tarball = CreateTarBall(location);
                software.Status = "Compressed";
                db.SaveChanges();

                // Upload
                var uri = await UploadToBlobStorage(Path.GetFileName(tarball), tarball).ConfigureAwait(false);

                if (uri.Equals("Error"))
                {
                    software.Status = "Error during upload.";
                    db.SaveChanges();
                    return;
                }
                // Remove old file from BLOB storage
                var retVal = RemoveFromBlobStorage(fileUrl);
                if (retval.Equals("Error"))
                {
                    software.Status = "Error during removal of old file from BLOB storage.";
                    db.SaveChanges();
                    return;
                }
                // Everything is ok
                software.Status = "Ready";
                software.Url    = uri;
                db.SaveChanges();
            }
            catch (Exception e)
            {
                software.Status = "Error";
                db.SaveChanges();
            }
        }