private async Task Receive(WebSocket socket, Action <WebSocketReceiveResult, HardwareId, string> handleMessage)
        {
            while (socket.State == WebSocketState.Open)
            {
                ArraySegment <byte> buffer    = new ArraySegment <byte>(new byte[1024 * 4]);
                string message                = null;
                WebSocketReceiveResult result = null;
                try {
                    using (var ms = new MemoryStream()) {
                        do
                        {
                            result = await socket.ReceiveAsync(buffer, CancellationToken.None).ConfigureAwait(false);

                            ms.Write(buffer.Array, buffer.Offset, result.Count);
                        } while (!result.EndOfMessage);

                        ms.Seek(0, SeekOrigin.Begin);

                        using (var reader = new StreamReader(ms, Encoding.UTF8)) {
                            message = await reader.ReadToEndAsync().ConfigureAwait(false);
                        }
                    }

                    var fields     = message.Split(',');
                    var hardwareId = new HardwareId(fields[0]);

                    handleMessage(result, hardwareId, fields[1]);
                } catch (WebSocketException e) {
                    if (e.WebSocketErrorCode == WebSocketError.ConnectionClosedPrematurely)
                    {
                        socket.Abort();
                    }
                }
            }
        }
Beispiel #2
0
        public void Unreserve(HardwareId id)
        {
            IPlugin plugin;

            plugins.Remove(id, out plugin);
            plugin.Dispose();
        }
 public HardwareDetails(ControllerType controllerType, HardwareId hardwareId)
 {
     this.Id             = hardwareId;
     this.ControllerType = controllerType;
     this.BoardName      = null;
     this.PartName       = null;
     this.OtherPartNames = null;
 }
Beispiel #4
0
 public async Task <CommandResponse> CommandRequestAsync(
     HardwareId hardwareId,
     string command,
     List <string> args,
     int?timeout)
 {
     return(await plugins[hardwareId].CommandRequestAsync(command, args, timeout));
 }
Beispiel #5
0
 private JsonResult TimeoutResponse(Guid sessionId, HardwareId id, string action)
 {
     return(Json(new {
         sid = sessionId,
         hid = id.Value,
         status = "Timeout",
         message = $"Time out while {action}"
     }));
 }
        public (HardwareDetails, HardwareInfo[]) Reserve(Guid sessionId, HardwareId hardwareId)
        {
            var details = hardwareManager.GetDetails(hardware[hardwareId]);
            var plugin  = sessions[sessionId].Reserve(details);

            return(
                plugin.HardwareDetails,
                SetAvailability(sessionId, hardware.Values.ToList()));
        }
 public async Task <CommandResponse> CommandRequestAsync(
     Guid sessionId,
     HardwareId hardwareId,
     string command,
     List <string> args,
     int?timeout)
 {
     return(await sessions[sessionId].CommandRequestAsync(hardwareId, command, args, timeout));
 }
Beispiel #8
0
 /// <summary>
 ///     Serves as a hash function for a particular type.
 /// </summary>
 /// <returns>A hash code for the current <see cref="T:System.Object" />.</returns>
 public override int GetHashCode()
 {
     return((Architecture.GetHashCode())
            ^ (string.IsNullOrWhiteSpace(CompatibleIds) ? 0 : CompatibleIds.GetHashCode())
            ^ (string.IsNullOrWhiteSpace(ExcludeIds) ? 0 : ExcludeIds.GetHashCode())
            ^ (string.IsNullOrWhiteSpace(HardwareDescription) ? 0 : HardwareDescription.GetHashCode())
            ^ (string.IsNullOrWhiteSpace(HardwareId) ? 0 : HardwareId.GetHashCode())
            ^ (string.IsNullOrWhiteSpace(ManufacturerName) ? 0 : ManufacturerName.GetHashCode())
            ^ (string.IsNullOrWhiteSpace(ServerName) ? 0 : ServerName.GetHashCode()));
 }
Beispiel #9
0
        protected override bool Validate(out string validationMessage)
        {
            var res = base.Validate(out validationMessage);

            res = res && ProductId.Validate(out validationMessage, Const.PRODUCT_ID);
            res = res && HardwareId.Validate(out validationMessage, Const.HARDWARE_ID);
            res = res && DeactivationUtcTime.Validate(out validationMessage);
            res = res && ExpirationUtcTime.Validate(out validationMessage);
            return(res);
        }
Beispiel #10
0
        public RequestState Register(string key)
        {
            if (!_authenticated)
            {
                throw new Exception("Connection not encrypted");
            }

            var data = SendAndReceive($"4|{key.AESEncrypt(_aesKey)}|{HardwareId.GetHwid().AESEncrypt(_aesKey)}");

            return((RequestState)int.Parse(data[1].AESDecrypt(_aesKey)));
        }
Beispiel #11
0
        // checks if key is connected with hwid
        public bool Valid(string key)
        {
            if (!_authenticated)
            {
                throw new Exception("Connection not encrypted");
            }

            var data = SendAndReceive($"3|{key.AESEncrypt(_aesKey)}|{HardwareId.GetHwid().AESEncrypt(_aesKey)}");

            return(bool.Parse(data[1].AESDecrypt(_aesKey)));
        }
Beispiel #12
0
        public JsonResult Unreserve(Guid sid, string hid)
        {
            var hardwareId     = new HardwareId(hid);
            var info           = sessionManager.Unreserve(sid, hardwareId);
            var hardwareResult = info.Select(
                i => new { hid = i.Id, controller = i.ControllerType, state = i.Status });

            return(Json(new {
                sid = sid,
                hid = hid,
                hardware = hardwareResult.ToArray()
            }));
        }
Beispiel #13
0
        /// <summary>
        /// Gets a hash code based on the Host and HardwareId properties</summary>
        /// <returns>Hash code based on the Host and HardwareId properties</returns>
        public override int GetHashCode()
        {
            int hash = 0;

            if (Host != null)
            {
                hash ^= Host.GetHashCode();
            }

            if (HardwareId != null)
            {
                hash ^= HardwareId.GetHashCode();
            }

            return(hash);
        }
Beispiel #14
0
        public async Task <JsonResult> Command(Guid sid, string hid, [FromBody] CommandRequest request)
        {
            var hardwareId = new HardwareId(hid);
            var response   = await sessionManager.CommandRequestAsync(
                sid, hardwareId, request.command.name, request.command.args, request.timeout);

            if (response.TimedOut)
            {
                return(TimeoutResponse(sid, hardwareId, "reading response"));
            }
            else
            {
                return(Json(new {
                    sid = sid,
                    hid = hid,
                    command = new { send = response.CommandString, receive = response.ResponseString }
                }));
            }
        }
Beispiel #15
0
        public static string GetUniqueId()
        {
            string deviceUniqueId;
            ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;

            if (settings.Values.ContainsKey("DeviceUniqueId") == true)
            {
                deviceUniqueId = (string)settings.Values["DeviceUniqueId"];
            }
            else
            {
                HardwareToken token  = HardwareIdentification.GetPackageSpecificToken(null);
                IBuffer       buffer = token.Id;
                byte[]        bytes;
                using (var dataReader = DataReader.FromBuffer(buffer))
                {
                    bytes = new byte[buffer.Length];
                    dataReader.ReadBytes(bytes);
                }

                if (bytes.Length % 4 != 0)
                {
                    throw new ArgumentException("Invalid hardware id");
                }

                HardwareId[] hardwareIds = new HardwareId[bytes.Length / 4];
                for (int index = 0; index < hardwareIds.Length; index++)
                {
                    hardwareIds[index].type  = (HardwareIdType)BitConverter.ToUInt16(bytes, index * 4);
                    hardwareIds[index].value = BitConverter.ToUInt16(bytes, index * 4 + 2);
                }

                string cpu  = hardwareIds.Where(i => i.type == HardwareIdType.Processor).FirstOrDefault().value.ToString();
                string bios = hardwareIds.Where(i => i.type == HardwareIdType.SmBios).FirstOrDefault().value.ToString();
                string mac  = hardwareIds.Where(i => i.type == HardwareIdType.NetworkAdapter).FirstOrDefault().value.ToString();

                deviceUniqueId = cpu + "-" + bios + "-" + mac;
                settings.Values["DeviceUniqueId"] = deviceUniqueId;
            }

            return(deviceUniqueId);
        }
Beispiel #16
0
        public JsonResult Reserve(Guid sid, string hid)
        {
            var hardwareId = new HardwareId(hid);

            var(details, info) = sessionManager.Reserve(sid, hardwareId);
            var detailsResult = new {
                id             = details.Id,
                controller     = details.ControllerType,
                boardName      = details.BoardName,
                partName       = details.PartName,
                otherPartNames = details.OtherPartNames
            };
            var hardwareResult = info.Select(
                i => new { hid = i.Id, controller = i.ControllerType, state = i.Status });

            return(Json(new {
                sid = sid,
                hid = hid,
                details = detailsResult,
                hardware = hardwareResult.ToArray()
            }));
        }
Beispiel #17
0
        public override Dictionary <string, object> ToUpdate(IMemoryCache memoryCache, out BaseModel updatedElement)
        {
            Dictionary <string, object> changes = new Dictionary <string, object>();

            Device refInCache = null;

            if (Id != Guid.Empty)
            {
                refInCache = CacheHelper.GetDeviceFromCache(memoryCache, Id);

                if (refInCache != null)
                {
                    if (Name != null && !Name.Equals(refInCache.Name))
                    {
                        changes.Add("Name", Name);
                        refInCache.Name = Name;
                    }
                    if (HardwareId != null && !HardwareId.Equals(refInCache.HardwareId))
                    {
                        changes.Add("HardwareId", HardwareId);
                        refInCache.HardwareId = HardwareId;
                    }
                    if (SpaceId != null && !SpaceId.Equals(refInCache.SpaceId))
                    {
                        changes.Add("SpaceId", SpaceId);
                        refInCache.SpaceId = SpaceId;
                    }
                    if (Type != null && !Type.Equals(refInCache.Type))
                    {
                        changes.Add("Type", Type);
                        refInCache.Type = Type;
                    }
                    if (SubType != null && !SubType.Equals(refInCache.SubType))
                    {
                        changes.Add("SubType", SubType);
                        refInCache.SubType = SubType;
                    }
                }
                else
                {
                    refInCache = this;

                    if (Name != null)
                    {
                        changes.Add("Name", Name);
                    }
                    if (HardwareId != null)
                    {
                        changes.Add("HardwareId", HardwareId);
                    }
                    if (SpaceId != null)
                    {
                        changes.Add("SpaceId", SpaceId);
                    }
                    if (Type != null)
                    {
                        changes.Add("Type", Type);
                    }
                    if (SubType != null)
                    {
                        changes.Add("SubType", SubType);
                    }
                }
            }
            updatedElement = refInCache;
            return(changes);
        }
 public async Task SocketMessageAsync(Guid sessionId, HardwareId hardwareId, string message)
 {
     await sessions[sessionId].SocketMessageAsync(hardwareId, message);
 }
 public HardwareInfo[] Unreserve(Guid sessionId, HardwareId hardwareId)
 {
     sessions[sessionId].Unreserve(hardwareId);
     return(SetAvailability(sessionId, hardware.Values.ToList()));
 }
Beispiel #20
0
        public override Dictionary <string, object> ToUpdate(IMemoryCache memoryCache, out BaseModel updatedElement)
        {
            Dictionary <string, object> changes = new Dictionary <string, object>();
            Sensor refInCache = null;

            if (Id != Guid.Empty)
            {
                refInCache = CacheHelper.GetSensorFromCache(memoryCache, Id);

                if (refInCache != null)
                {
                    if (!DeviceId.Equals(refInCache.DeviceId))
                    {
                        changes.Add("DeviceId", DeviceId);
                        refInCache.DeviceId = DeviceId;
                    }
                    if (HardwareId != null && !HardwareId.Equals(refInCache.HardwareId))
                    {
                        changes.Add("HardwareId", HardwareId);
                        refInCache.HardwareId = HardwareId;
                    }
                    if (SpaceId != null && !SpaceId.Equals(refInCache.SpaceId))
                    {
                        changes.Add("SpaceId", SpaceId);
                        refInCache.SpaceId = SpaceId;
                    }
                    if (!PollRate.Equals(refInCache.PollRate))
                    {
                        changes.Add("PollRate", PollRate);
                        refInCache.PollRate = PollRate;
                    }
                    if (PortType != null && !PortType.Equals(refInCache.PortType))
                    {
                        changes.Add("PortType", PortType);
                        refInCache.PortType = PortType;
                    }
                    if (DataType != null && !DataType.Equals(refInCache.DataType))
                    {
                        changes.Add("DataType", DataType);
                        refInCache.DataType = DataType;
                    }
                    if (DataUnitType != null && !DataUnitType.Equals(refInCache.DataUnitType))
                    {
                        changes.Add("DataUnitType", DataUnitType);
                        refInCache.DataUnitType = DataUnitType;
                    }
                    if (DataSubtype != null && !DataSubtype.Equals(refInCache.DataSubtype))
                    {
                        changes.Add("DataSubtype", DataSubtype);
                        refInCache.DataSubtype = DataSubtype;
                    }
                }
                else
                {
                    refInCache = this;
                    if (DeviceId != null)
                    {
                        changes.Add("DeviceId", DeviceId);
                    }
                    if (HardwareId != null)
                    {
                        changes.Add("HardwareId", HardwareId);
                    }
                    if (SpaceId != null)
                    {
                        changes.Add("SpaceId", SpaceId);
                    }
                    if (PollRate != 0)
                    {
                        changes.Add("PollRate", PollRate);
                    }
                    if (PortType != null)
                    {
                        changes.Add("PortType", PortType);
                    }
                    if (DataType != null)
                    {
                        changes.Add("DataType", DataType);
                    }
                    if (DataUnitType != null)
                    {
                        changes.Add("DataUnitType", DataUnitType);
                    }
                    if (DataSubtype != null)
                    {
                        changes.Add("DataSubTypeId", DataSubTypeId);
                    }
                }
            }
            updatedElement = refInCache;
            return(changes);
        }
Beispiel #21
0
 private void Main_Load(object sender, EventArgs e)
 {
     textHardwareId.Text = HardwareId.GetHardwareId();
 }
Beispiel #22
0
 public bool IsReserved(HardwareId id)
 {
     return(plugins.ContainsKey(id));
 }
        /// <summary>
        /// In this method you should implement your business logic based on hardware ID.
        /// You should call this method after ValidateData to make sure id is trustable.
        /// </summary>
        /// <param name="id">Hardware id of the client device that was sent from the client metro app.</param>
        public static void ProcessData(byte[] id)
        {
            // Convert serialized hardwareId to well formed HardwareId structures so that 
            // it can be easily consumed. 
            if (id.Length % 4 != 0)
            {
                throw new ArgumentException("Invalid hardware id");
            }

            HardwareId[] hardwareIds = new HardwareId[id.Length / 4];
            for (int index = 0; index < hardwareIds.Length; index++)
            {
                hardwareIds[index].type = BitConverter.ToUInt16(id, index * 4);
                hardwareIds[index].value = BitConverter.ToUInt16(id, index * 4 + 2);

                switch ((HardwareIdType)hardwareIds[index].type)
                {
                    case HardwareIdType.Processor:
                        // implement your business logic based on hardwareIds[index].value 
                        break;

                    case HardwareIdType.Memory:
                        // implement your business logic based on hardwareIds[index].value 
                        break;

                    case HardwareIdType.NetworkAdapter:
                        // implement your business logic based on hardwareIds[index].value 
                        break;

                    // Add other case statements for the other Hardware types here.
                }
            }
        }
Beispiel #24
0
        /// <summary>
        /// Processes command line args and calls into HWDC
        /// </summary>
        /// <returns>Returns 0 success, non-zero on error</returns>
        private static async Task <ErrorCodes> MainAsync(string[] args)
        {
            ErrorCodes retval                  = ErrorCodes.SUCCESS;
            bool       show_help               = false;
            string     CreateOption            = null;
            bool       CommitOption            = false;
            string     ListOption              = null;
            string     ProductId               = null;
            string     SubmissionId            = null;
            string     ShippingLabelId         = null;
            string     PublisherId             = null;
            string     DownloadOption          = null;
            string     MetadataOption          = null;
            string     SubmissionPackagePath   = null;
            bool       WaitOption              = false;
            bool       WaitForMetaData         = false;
            bool       CreateMetaData          = false;
            bool       AudienceOption          = false;
            int        OverrideServer          = 0;
            bool       OverrideServerPresent   = false;
            string     CredentialsOption       = null;
            string     AADAuthenticationOption = null;
            string     TimeoutOption           = null;
            uint       HttpTimeout             = DEFAULT_TIMEOUT;
            bool       TranslateOption         = false;
            string     AnotherPartnerId        = null;

            OptionSet p = new OptionSet()
            {
                { "c|create=", "Path to json file with configuration to create", v => CreateOption = v },
                { "commit", "Commit submission with given ID", v => CommitOption = true },
                { "l|list=", "List a shippinglabel, product, submission or partnersubmission", v => ListOption = v },
                { "u|upload=", "Upload a package to a specific product and submission", v => SubmissionPackagePath = v },
                { "productid=", "Specify a specific ProductId", v => ProductId = v },
                { "submissionid=", "Specify a specific SubmissionId", v => SubmissionId = v },
                { "shippinglabelid=", "Specify a specific ShippingLabelId", v => ShippingLabelId = v },
                { "publisherid=", "Specify a specific PublisherId", v => PublisherId = v },
                { "partnerid=", "Specify PublisherId of the Partner to share the submission to via shipping label instead of Windows Update", v => AnotherPartnerId = v },
                { "v", "Increase debug message verbosity", v => { if (v != null)
                                                                  {
                                                                      ++verbosity;
                                                                  }
                  } },
                { "d|download=", "Download a submission to current directory or folder specified", v => DownloadOption = v ?? Environment.CurrentDirectory },
                { "m|metadata=", "Download a submission metadata to current directory or folder specified", v => MetadataOption = v ?? Environment.CurrentDirectory },
                { "h|help", "Show this message and exit", v => show_help = v != null },
                { "w|wait", "Wait for submission id to be done", v => WaitOption = true },
                { "waitmetadata", "Wait for metadata to be done as well in a submission", v => WaitForMetaData = true },
                { "createmetadata", "Requeset metadata creation for older submissions", v => CreateMetaData = true },
                { "a|audience", "List Audiences", v => AudienceOption = true },
                { "server=", "Specify target DevCenter server from CredSelect enum", v => { OverrideServer = int.Parse(v); OverrideServerPresent = true; } },
                { "creds=", "Option to specify app credentials.  Options: ENVOnly, FileOnly, AADOnly, AADThenFile (Default)", v => CredentialsOption = v },
                { "aad=", "Option to specify AAD auth behavior.  Options: Never (Default), Prompt, Always, RefreshSession, SelectAccount", v => AADAuthenticationOption = v },
                { "t|timeout=", $"Adjust the timeout for HTTP requests to specified seconds.  Default:{DEFAULT_TIMEOUT} seconds", v => TimeoutOption = v },
                { "translate", "Translate the given publisherid, productid and submissionid from a partner to the values visible in your HDC account", v => TranslateOption = true },
                { "?", "Show this message and exit", v => show_help = v != null },
            };

            Console.WriteLine("SurfaceDevCenterManager v" + Assembly.GetExecutingAssembly().GetName().Version);

            List <string> extra;

            try
            {
                extra = p.Parse(args);
            }
            catch (OptionException e)
            {
                ErrorParsingOptions(e.Message);
                Console.WriteLine("Try running with just '--help' for more information.");
                return(ErrorCodes.COMMAND_LINE_OPTION_PARSING_FAILED);
            }

            if (show_help)
            {
                ShowHelp(p);
                return(ErrorCodes.SUCCESS);
            }

            List <AuthorizationHandlerCredentials> myCreds = await DevCenterCredentialsHandler.GetApiCreds(CredentialsOption, AADAuthenticationOption);

            if (myCreds == null)
            {
                ErrorParsingOptions("Unable to get Dev Center Credentials");
                return(ErrorCodes.NO_DEV_CENTER_CREDENTIALS_FOUND);
            }

            if (OverrideServer < 0 || OverrideServer >= myCreds.Count)
            {
                ErrorParsingOptions("OverrideServer invalid - " + OverrideServer);
                return(ErrorCodes.OVERRIDE_SERVER_INVALID);
            }
            else
            {
                if (!OverrideServerPresent)
                {
                    string loopServersString = ConfigurationManager.AppSettings["loopservers"];
                    if (loopServersString != null)
                    {
                        string[] serversList = loopServersString.Split(',');
                        int      x           = (new Random()).Next(0, serversList.Length);
                        OverrideServer = int.Parse(serversList[x]);
                    }
                }
            }

            if (CreateOption != null && (!File.Exists(CreateOption)))
            {
                ErrorParsingOptions("CreateOption invalid - " + CreateOption);
                return(ErrorCodes.CREATE_INPUT_FILE_DOES_NOT_EXIST);
            }

            DevCenterHWSubmissionType ListOptionEnum = DevCenterHWSubmissionTypeCheck(ListOption);

            if (ListOption != null && ListOptionEnum == DevCenterHWSubmissionType.Invalid)
            {
                ErrorParsingOptions("ListOption invalid - " + ListOption);
                return(ErrorCodes.LIST_INVALID_OPTION);
            }

            if (TimeoutOption != null)
            {
                if (uint.TryParse(TimeoutOption, out uint inputParse))
                {
                    HttpTimeout = inputParse;
                    Console.WriteLine($"> HttpTimeout: {HttpTimeout} seconds");
                }
                else
                {
                    Console.WriteLine($"> HttpTimeout: Invalid value {TimeoutOption}, using default timeout");
                }
            }

            DevCenterOptions options = new DevCenterOptions()
            {
                CorrelationId = CorrelationId, HttpTimeoutSeconds = HttpTimeout, RequestDelayMs = 250, LastCommand = LastCommandSet
            };
            DevCenterHandler api = new DevCenterHandler(myCreds[OverrideServer], options);

            if (CreateOption != null)
            {
                Console.WriteLine("> Create Option");

                CreateInput createInput = JsonConvert.DeserializeObject <CreateInput>(File.ReadAllText(CreateOption));

                if (DevCenterHWSubmissionType.Product == createInput.CreateType)
                {
                    DevCenterResponse <Product> ret = await api.NewProduct(createInput.CreateProduct);

                    if (ret.Error != null)
                    {
                        DevCenterErrorDetailsDump(ret.Error);
                        retval = ErrorCodes.NEW_PRODUCT_API_FAILED;
                    }
                    else
                    {
                        ret.ReturnValue[0].Dump();
                    }
                }
                else if (DevCenterHWSubmissionType.Submission == createInput.CreateType)
                {
                    if (ProductId == null)
                    {
                        Console.WriteLine("> ERROR: productid not specified");
                        retval = ErrorCodes.NEW_SUBMISSION_PRODUCT_ID_MISSING;
                    }

                    if (retval == 0)
                    {
                        Console.WriteLine("> Creating Submission");
                        DevCenterResponse <Submission> ret = await api.NewSubmission(ProductId, createInput.CreateSubmission);

                        if (ret.Error != null)
                        {
                            DevCenterErrorDetailsDump(ret.Error);
                            retval = ErrorCodes.NEW_SUBMISSION_API_FAILED;
                        }
                        else
                        {
                            ret.ReturnValue[0].Dump();
                        }
                    }
                }
                else if (DevCenterHWSubmissionType.ShippingLabel == createInput.CreateType)
                {
                    if (ProductId == null)
                    {
                        Console.WriteLine("> ERROR: productid not specified");
                        retval = ErrorCodes.NEW_SHIPPING_LABEL_PRODUCT_ID_MISSING;
                    }

                    if (SubmissionId == null)
                    {
                        Console.WriteLine("> ERROR: submissionid not specified");
                        retval = ErrorCodes.NEW_SHIPPING_LABEL_SUBMISSION_ID_MISSING;
                    }

                    if (retval == 0)
                    {
                        Console.WriteLine("> Get Driver Metadata");
                        string tmpfile = System.IO.Path.GetTempFileName();

                        DevCenterResponse <Submission> retSubmission = await api.GetSubmission(ProductId, SubmissionId);

                        if (retSubmission.Error != null)
                        {
                            DevCenterErrorDetailsDump(retSubmission.Error);
                            retval = ErrorCodes.NEW_SHIPPING_LABEL_GET_SUBMISSION_API_FAILED;
                        }

                        List <Submission>    submissions = retSubmission.ReturnValue;
                        List <Download.Item> dls         = submissions[0].Downloads.Items;
                        foreach (Download.Item dl in dls)
                        {
                            if (dl.Type.ToLower() == Download.Type.driverMetadata.ToString().ToLower())
                            {
                                Console.WriteLine("> driverMetadata Url: " + dl.Url);
                                BlobStorageHandler bsh = new BlobStorageHandler(dl.Url.AbsoluteUri);
                                await bsh.Download(tmpfile);
                            }
                        }

                        string         jsonContent = System.IO.File.ReadAllText(tmpfile);
                        DriverMetadata metadata    = JsonConvert.DeserializeObject <DriverMetadata>(jsonContent);
                        System.IO.File.Delete(tmpfile);

                        List <HardwareId> labelHwids = new List <HardwareId>();

                        foreach (KeyValuePair <string, DriverMetadataDetails> bundleInfo in metadata.BundleInfoMap)
                        {
                            foreach (KeyValuePair <string, DriverMetadataInfDetails> infInfo in bundleInfo.Value.InfInfoMap)
                            {
                                foreach (KeyValuePair <string, Dictionary <string, DriverMetadataHWID> > osPnpInfo in infInfo.Value.OSPnPInfoMap)
                                {
                                    foreach (KeyValuePair <string, DriverMetadataHWID> pnpInfo in osPnpInfo.Value)
                                    {
                                        HardwareId labelHwid = new HardwareId
                                        {
                                            BundleId            = bundleInfo.Key,
                                            InfId               = infInfo.Key,
                                            OperatingSystemCode = osPnpInfo.Key,
                                            PnpString           = pnpInfo.Key.ToLower() // Recommendation from HDC team
                                        };
                                        labelHwids.Add(labelHwid);
                                    }
                                }
                            }
                        }

                        createInput.CreateShippingLabel.Targeting.HardwareIds = labelHwids;
                        createInput.CreateShippingLabel.PublishingSpecifications.GoLiveDate = DateTime.Now.AddDays(7);

                        if (AnotherPartnerId != null)
                        {
                            Console.WriteLine("> Shipping to Partner (not Windows Update): " + AnotherPartnerId);
                            createInput.CreateShippingLabel.Destination             = "anotherPartner";
                            createInput.CreateShippingLabel.RecipientSpecifications = new RecipientSpecifications()
                            {
                                EnforceChidTargeting = false,
                                ReceiverPublisherId  = AnotherPartnerId
                            };
                        }

                        Console.WriteLine("> Creating Shipping Label");
                        DevCenterResponse <ShippingLabel> ret = await api.NewShippingLabel(ProductId, SubmissionId, createInput.CreateShippingLabel);

                        if (ret.Error != null)
                        {
                            DevCenterErrorDetailsDump(ret.Error);
                            retval = ErrorCodes.NEW_SHIPPING_LABEL_CREATE_API_FAILED;
                        }
                        else
                        {
                            ret.ReturnValue[0].Dump();
                        }
                    }
                }
                else
                {
                    Console.WriteLine(">  Invalid Create Option selected");
                }
            }
            else if (CommitOption)
            {
                Console.WriteLine("> Commit Option");

                if (ProductId == null)
                {
                    Console.WriteLine("> ERROR: productid not specified");
                    retval = ErrorCodes.COMMIT_PRODUCT_ID_MISSING;
                }

                if (SubmissionId == null)
                {
                    Console.WriteLine("> ERROR: submissionid not specified");
                    retval = ErrorCodes.COMMIT_SUBMISSION_ID_MISSING;
                }

                if (retval == 0)
                {
                    Console.WriteLine("> Sending Commit");

                    DevCenterResponse <bool> ret = await api.CommitSubmission(ProductId, SubmissionId);

                    if (ret.Error != null)
                    {
                        DevCenterErrorDetailsDump(ret.Error);
                        retval = ErrorCodes.COMMIT_API_FAILED;
                    }
                    else
                    {
                        if (!ret.ReturnValue[0])
                        {
                            Console.WriteLine("> Commit Failed");
                            retval = ErrorCodes.COMMIT_API_FAILED;
                        }
                        else
                        {
                            Console.WriteLine("> Commit OK");
                        }
                    }
                }
            }
            else if (ListOption != null)
            {
                Console.WriteLine("> List Option {0}", ListOption);

                switch (ListOptionEnum)
                {
                case DevCenterHWSubmissionType.Product:
                {
                    DevCenterResponse <Product> ret = await api.GetProducts(ProductId);

                    if (ret.Error != null)
                    {
                        DevCenterErrorDetailsDump(ret.Error);
                        retval = ErrorCodes.LIST_GET_PRODUCTS_API_FAILED;
                    }
                    else
                    {
                        List <Product> products = ret.ReturnValue;
                        foreach (Product product in products)
                        {
                            product.Dump();
                        }
                    }
                }
                break;

                case DevCenterHWSubmissionType.Submission:
                {
                    DevCenterResponse <Submission> ret = await api.GetSubmission(ProductId, SubmissionId);

                    if (ret.Error != null)
                    {
                        DevCenterErrorDetailsDump(ret.Error);
                        retval = ErrorCodes.LIST_GET_SUBMISSION_API_FAILED;
                    }
                    else
                    {
                        List <Submission> submissions = ret.ReturnValue;
                        foreach (Submission submission in submissions)
                        {
                            submission.Dump();
                        }
                    }
                }
                break;

                case DevCenterHWSubmissionType.ShippingLabel:
                {
                    DevCenterResponse <ShippingLabel> ret = await api.GetShippingLabels(ProductId, SubmissionId, ShippingLabelId);

                    if (ret.Error != null)
                    {
                        DevCenterErrorDetailsDump(ret.Error);
                        retval = ErrorCodes.LIST_GET_SHIPPING_LABEL_API_FAILED;
                    }
                    else
                    {
                        List <ShippingLabel> shippingLabels = ret.ReturnValue;
                        foreach (ShippingLabel shippingLabel in shippingLabels)
                        {
                            shippingLabel.Dump();
                        }
                    }
                }
                break;

                case DevCenterHWSubmissionType.PartnerSubmission:
                {
                    DevCenterResponse <Submission> ret = await api.GetPartnerSubmission(PublisherId, ProductId, SubmissionId);

                    if (ret.Error != null)
                    {
                        DevCenterErrorDetailsDump(ret.Error);
                        retval = ErrorCodes.LIST_GET_PARTNER_SUBMISSION_API_FAILED;
                    }
                    else
                    {
                        List <Submission> submissions = ret.ReturnValue;
                        foreach (Submission submission in submissions)
                        {
                            submission.Dump();
                        }
                    }
                }
                break;

                default:
                    Console.WriteLine(">  Invalid List Option selected");
                    break;
                }
            }
            else if (DownloadOption != null)
            {
                Console.WriteLine("> Download Option {0}", DownloadOption);

                string pathNameFull = System.IO.Path.GetFullPath(DownloadOption);
                string FileNamePart = System.IO.Path.GetFileName(DownloadOption);
                string PathNamePart = System.IO.Path.GetDirectoryName(DownloadOption);

                if (!System.IO.Directory.Exists(PathNamePart))
                {
                    Console.WriteLine("> ERROR: Output path does not exist: " + PathNamePart);
                    retval = ErrorCodes.DOWNLOAD_OUTPUT_PATH_NOT_EXIST;
                }

                if (System.IO.File.Exists(DownloadOption))
                {
                    Console.WriteLine("> ERROR: Output file exists already: " + DownloadOption);
                    retval = ErrorCodes.DOWNLOAD_OUTPUT_FILE_ALREADY_EXISTS;
                }

                if (ProductId == null)
                {
                    Console.WriteLine("> ERROR: productid not specified");
                    retval = ErrorCodes.DOWNLOAD_PRODUCT_ID_MISSING;
                }

                if (SubmissionId == null)
                {
                    Console.WriteLine("> ERROR: submissionid not specified");
                    retval = ErrorCodes.DOWNLOAD_SUBMISSION_ID_MISSING;
                }

                if (retval == 0)
                {
                    Console.WriteLine("> Fetch Submission Info");
                    DevCenterResponse <Submission> ret = await api.GetSubmission(ProductId, SubmissionId);

                    if (ret.Error != null)
                    {
                        DevCenterErrorDetailsDump(ret.Error);
                        retval = ErrorCodes.DOWNLOAD_GET_SUBMISSION_API_FAILED;
                    }
                    List <Submission>    submissions = ret.ReturnValue;
                    List <Download.Item> dls         = submissions[0].Downloads.Items;
                    foreach (Download.Item dl in dls)
                    {
                        if (dl.Type.ToLower() == Download.Type.signedPackage.ToString().ToLower())
                        {
                            Console.WriteLine("> signedPackage Url: " + dl.Url);
                            BlobStorageHandler bsh = new BlobStorageHandler(dl.Url.AbsoluteUri);
                            await bsh.Download(DownloadOption);
                        }
                    }
                }
            }
            else if (MetadataOption != null)
            {
                Console.WriteLine("> Metadata Download Option {0}", MetadataOption);

                if (ProductId == null)
                {
                    Console.WriteLine("> ERROR: productid not specified");
                    retval = ErrorCodes.METADATA_PRODUCT_ID_MISSING;
                }

                if (SubmissionId == null)
                {
                    Console.WriteLine("> ERROR: submissionid not specified");
                    retval = ErrorCodes.METADATA_SUBMISSION_ID_MISSING;
                }

                if (retval == 0)
                {
                    Console.WriteLine("> Fetch Submission Info");
                    DevCenterResponse <Submission> ret = await api.GetSubmission(ProductId, SubmissionId);

                    if (ret.Error != null)
                    {
                        DevCenterErrorDetailsDump(ret.Error);
                        retval = ErrorCodes.METADATA_GET_SUBMISSION_API_FAILED;
                    }
                    List <Submission>    submissions = ret.ReturnValue;
                    List <Download.Item> dls         = submissions[0].Downloads.Items;
                    bool foundMetaData = false;
                    foreach (Download.Item dl in dls)
                    {
                        if (dl.Type.ToLower() == Download.Type.driverMetadata.ToString().ToLower())
                        {
                            Console.WriteLine("> driverMetadata Url: " + dl.Url);
                            BlobStorageHandler bsh = new BlobStorageHandler(dl.Url.AbsoluteUri);
                            await bsh.Download(MetadataOption);

                            foundMetaData = true;
                        }
                    }

                    if (!foundMetaData)
                    {
                        Console.WriteLine("> ERROR: No Metadata available for this submission");
                    }
                }
            }
            else if (SubmissionPackagePath != null)
            {
                Console.WriteLine("> Upload Option");

                if (ProductId == null)
                {
                    Console.WriteLine("> ERROR: productid not specified");
                    retval = ErrorCodes.UPLOAD_PRODUCT_ID_MISSING;
                }

                if (SubmissionId == null)
                {
                    Console.WriteLine("> ERROR: submissionid not specified");
                    retval = ErrorCodes.UPLOAD_SUBMISSION_ID_MISSING;
                }

                if (retval == 0)
                {
                    Console.WriteLine("> Fetch Submission Info");
                    DevCenterResponse <Submission> ret = await api.GetSubmission(ProductId, SubmissionId);

                    if (ret.Error != null)
                    {
                        DevCenterErrorDetailsDump(ret.Error);
                        retval = ErrorCodes.UPLOAD_GET_SUBMISSION_API_FAILED;
                    }
                    List <Submission>    submissions = ret.ReturnValue;
                    List <Download.Item> dls         = submissions[0].Downloads.Items;
                    foreach (Download.Item dl in dls)
                    {
                        if (dl.Type.ToLower() == Download.Type.initialPackage.ToString().ToLower())
                        {
                            Console.WriteLine("> initialPackage Url: " + dl.Url);
                            Console.WriteLine("> Uploading Submission Package");
                            BlobStorageHandler bsh = new BlobStorageHandler(dl.Url.AbsoluteUri);
                            await bsh.Upload(SubmissionPackagePath);
                        }
                    }
                }
            }
            else if (WaitOption)
            {
                Console.WriteLine("> Wait Option");

                if (ProductId == null)
                {
                    Console.WriteLine("> ERROR: productid not specified");
                    retval = ErrorCodes.WAIT_PRODUCT_ID_MISSING;
                }

                if (SubmissionId == null)
                {
                    Console.WriteLine("> ERROR: submissionid not specified");
                    retval = ErrorCodes.WAIT_SUBMISSION_ID_MISSING;
                }

                if (retval == 0)
                {
                    bool   done            = false;
                    string lastCurrentStep = "";
                    string lastState       = "";

                    while (!done)
                    {
                        if (ShippingLabelId == null)
                        {
                            DevCenterResponse <Submission> ret = await api.GetSubmission(ProductId, SubmissionId);

                            if (ret.Error != null)
                            {
                                DevCenterErrorDetailsDump(ret.Error);
                                done   = true;
                                retval = ErrorCodes.WAIT_GET_SUBMISSION_API_FAILED;
                                break;
                            }
                            List <Submission> submissions = ret.ReturnValue;
                            Submission        sub         = submissions[0];

                            if (!done)
                            {
                                if (sub.WorkflowStatus.CurrentStep != lastCurrentStep ||
                                    sub.WorkflowStatus.State != lastState)
                                {
                                    lastCurrentStep = sub.WorkflowStatus.CurrentStep;
                                    lastState       = sub.WorkflowStatus.State;
                                    await sub.WorkflowStatus.Dump();
                                }

                                bool haveMetadata      = false;
                                bool haveSignedPackage = false;
                                if (sub.Downloads != null)
                                {
                                    List <Download.Item> dls = sub.Downloads.Items;
                                    foreach (Download.Item dl in dls)
                                    {
                                        if (dl.Type.ToLower() == Download.Type.driverMetadata.ToString().ToLower())
                                        {
                                            Console.WriteLine("> driverMetadata Url: " + dl.Url);
                                            haveMetadata = true;
                                        }
                                        if (dl.Type.ToLower() == Download.Type.signedPackage.ToString().ToLower())
                                        {
                                            Console.WriteLine("> signedPackage Url: " + dl.Url);
                                            haveSignedPackage = true;
                                        }
                                    }
                                }

                                if (lastState == "failed")
                                {
                                    done   = true;
                                    retval = ErrorCodes.WAIT_SUBMISSION_FAILED_IN_HWDC;
                                }
                                else if (haveSignedPackage)
                                {
                                    if (WaitForMetaData)
                                    {
                                        if (haveMetadata)
                                        {
                                            done = true;
                                            Console.WriteLine("> Submission Ready with Metadata");
                                        }
                                    }
                                    else
                                    {
                                        done = true;
                                        Console.WriteLine("> Submission Ready");
                                    }
                                }

                                if (!done)
                                {
                                    await Task.Delay(5000);
                                }
                            }
                            else
                            {
                                Console.WriteLine("> Signed Package Ready");
                            }
                        }
                        else
                        {
                            DevCenterResponse <ShippingLabel> ret = await api.GetShippingLabels(ProductId, SubmissionId, ShippingLabelId);

                            if (ret.Error != null)
                            {
                                DevCenterErrorDetailsDump(ret.Error);
                                done   = true;
                                retval = ErrorCodes.WAIT_GET_SHIPPING_LABEL_API_FAILED;
                                break;
                            }
                            List <ShippingLabel> shippingLabels = ret.ReturnValue;
                            ShippingLabel        label          = shippingLabels[0];

                            if (label.WorkflowStatus.CurrentStep != lastCurrentStep ||
                                label.WorkflowStatus.State != lastState)
                            {
                                lastCurrentStep = label.WorkflowStatus.CurrentStep;
                                lastState       = label.WorkflowStatus.State;
                                await label.WorkflowStatus.Dump();
                            }

                            if (lastState == "failed")
                            {
                                done   = true;
                                retval = ErrorCodes.WAIT_SHIPPING_LABEL_FAILED_IN_HWDC;
                            }
                            else if (lastCurrentStep == "microsoftApproval")
                            {
                                done = true;
                                Console.WriteLine("> Shipping Label Ready");
                            }
                            else if (lastCurrentStep == "finalizeSharing" && lastState == "completed")
                            {
                                done = true;
                                Console.WriteLine("> Shipping Label for Sharing Ready");
                            }
                            else
                            {
                                await Task.Delay(5000);
                            }
                        }
                    }
                    Console.WriteLine("> Done");
                }
            }
            else if (AudienceOption)
            {
                Console.WriteLine("> Audience Option");

                DevCenterResponse <Audience> ret = await api.GetAudiences();

                if (ret.Error != null)
                {
                    DevCenterErrorDetailsDump(ret.Error);
                    retval = ErrorCodes.AUIDENCE_GET_AUDIENCE_API_FAILED;
                }
                else
                {
                    List <Audience> audiences = ret.ReturnValue;
                    foreach (Audience audience in audiences)
                    {
                        audience.Dump();
                    }
                }
            }
            else if (CreateMetaData)
            {
                Console.WriteLine("> Create MetaData Option");

                if (ProductId == null)
                {
                    Console.WriteLine("> ERROR: productid not specified");
                    retval = ErrorCodes.CREATEMETADATA_PRODUCT_ID_MISSING;
                }

                if (SubmissionId == null)
                {
                    Console.WriteLine("> ERROR: submissionid not specified");
                    retval = ErrorCodes.CREATEMETADATA_SUBMISSION_ID_MISSING;
                }

                if (retval == 0)
                {
                    Console.WriteLine("> Sending Create MetaData");
                    DevCenterResponse <bool> ret = await api.CreateMetaData(ProductId, SubmissionId);

                    if (ret.Error != null)
                    {
                        DevCenterErrorDetailsDump(ret.Error);
                        retval = ErrorCodes.CREATEMETADATA_API_FAILED;
                    }
                    else
                    {
                        if (!ret.ReturnValue[0])
                        {
                            Console.WriteLine("> Create MetaData Failed");
                            retval = ErrorCodes.CREATEMETADATA_API_FAILED;
                        }
                        else
                        {
                            Console.WriteLine("> Create MetaData OK");
                        }
                    }
                }
            }
            else if (TranslateOption)
            {
                Console.WriteLine("> Translate Option");

                if (PublisherId == null)
                {
                    Console.WriteLine("> ERROR: publisherid not specified");
                    retval = ErrorCodes.TRANSLATE_PUBLISHER_ID_MISSING;
                }

                if (ProductId == null)
                {
                    Console.WriteLine("> ERROR: productid not specified");
                    retval = ErrorCodes.TRANSLATE_PRODUCT_ID_MISSING;
                }

                if (SubmissionId == null)
                {
                    Console.WriteLine("> ERROR: submissionid not specified");
                    retval = ErrorCodes.TRANSLATE_SUBMISSION_ID_MISSING;
                }

                if (retval == 0)
                {
                    Console.WriteLine("> Requesting Translation");
                    DevCenterResponse <Submission> ret = await api.GetPartnerSubmission(PublisherId, ProductId, SubmissionId);

                    if (ret.Error != null)
                    {
                        DevCenterErrorDetailsDump(ret.Error);
                        retval = ErrorCodes.TRANSLATE_API_FAILED;
                    }
                    else
                    {
                        if (ret.ReturnValue.Count == 0)
                        {
                            Console.WriteLine("> Translate Failed");
                            retval = ErrorCodes.TRANSLATE_API_FAILED;
                        }
                        else
                        {
                            Console.WriteLine("> Translate OK");
                            ret.ReturnValue[0].Dump();
                        }
                    }
                }
            }
            return(retval);
        }
Beispiel #25
0
 public async Task SocketMessageAsync(HardwareId hardwareId, string message)
 {
     await plugins[hardwareId].SocketTextMessageAsync(message);
 }