コード例 #1
0
        int IDebugRemoteCorDebug.DebugActiveProcessEx(IDebugPort2 pPort, uint id, int win32Attach, out object ppProcess)
        {
            ppProcess = null;
            try
            {
                MessageCentre.DebugMessage(Resources.ResourceStrings.Attach);
                AD_PROCESS_ID pid = new AD_PROCESS_ID();

                pid.ProcessIdType = (uint)AD_PROCESS_ID_TYPE.AD_PROCESS_ID_SYSTEM;

                pid.dwProcessId = id;

                IDebugProcess2 iDebugProcess;
                pPort.GetProcess(pid, out iDebugProcess);

                CorDebugProcess process = (CorDebugProcess)iDebugProcess;

                // StartDebugging() will either get a connected device into a debuggable state and start the dispatch thread, or throw.
                process.StartDebugging(this, false);
                ppProcess = process;

                return(COM_HResults.S_OK);
            }
            catch (ProcessExitException)
            {
                MessageCentre.DebugMessage(Resources.ResourceStrings.AttachFailedProcessDied);
                return(COM_HResults.S_FALSE);
            }
            catch (Exception ex)
            {
                MessageCentre.DebugMessage(Resources.ResourceStrings.AttachFailed);
                MessageCentre.InternalErrorMessage(false, ex.Message);
                return(COM_HResults.S_FALSE);
            }
        }
コード例 #2
0
        int IDebugRemoteCorDebug.CreateProcessEx(Microsoft.VisualStudio.Debugger.Interop.IDebugPort2 pPort, string lpApplicationName, string lpCommandLine, System.IntPtr lpProcessAttributes, System.IntPtr lpThreadAttributes, int bInheritHandles, uint dwCreationFlags, System.IntPtr lpEnvironment, string lpCurrentDirectory, ref CorDebugInterop._STARTUPINFO lpStartupInfo, ref CorDebugInterop._PROCESS_INFORMATION lpProcessInformation, uint debuggingFlags, out object ppProcess)
        {
            ppProcess = null;

            try
            {
                // CreateProcessEx() is guaranteed to return a valid process object, or throw an exception
                CorDebugProcess process = CorDebugProcess.CreateProcessEx(pPort, lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, ref lpStartupInfo, ref lpProcessInformation, debuggingFlags);

                // StartDebugging() will either get a connected device into a debuggable state and start the dispatch thread, or throw.
                process.StartDebugging(this, true);
                ppProcess = process;

                return(COM_HResults.S_OK);
            }
            catch (ProcessExitException)
            {
                MessageCentre.DebugMessage(Resources.ResourceStrings.InitializeProcessFailedProcessDied);
                return(COM_HResults.S_FALSE);
            }
            catch (Exception ex)
            {
                MessageCentre.DebugMessage(Resources.ResourceStrings.InitializeProcessFailed);
                MessageCentre.InternalErrorMessage(false, ex.Message);
                return(COM_HResults.S_FALSE);
            }
        }
        protected override byte[] GenerateCode(string inputFileName, string inputFileContent)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            MemoryStream outputStream = new MemoryStream();
            StreamWriter streamWriter = new StreamWriter(outputStream);
            string       inputFileNameWithoutExtension = Path.GetFileNameWithoutExtension(inputFileName);

            // get VS extension assembly to reach ProcessResourceFiles type
            Assembly buildTasks = GetType().Assembly;

            Type typ = buildTasks.GetType("nanoFramework.Tools.ProcessResourceFiles");

            if (typ != null)
            {
                object processResourceFiles = typ.GetConstructor(new Type[] { }).Invoke(null);

                typ.GetProperty("StronglyTypedClassName").SetValue(processResourceFiles, inputFileNameWithoutExtension, null);
                typ.GetProperty("StronglyTypedNamespace").SetValue(processResourceFiles, GetResourcesNamespace(), null);
                typ.GetProperty("GenerateNestedEnums").SetValue(processResourceFiles, m_fNestedEnums, null);
                typ.GetProperty("GenerateInternalClass").SetValue(processResourceFiles, m_fInternal, null);
                typ.GetProperty("IsMscorlib").SetValue(processResourceFiles, m_fMscorlib, null);

                string resourceName = (string)typ.GetProperty("StronglyTypedNamespace").GetValue(processResourceFiles, null);

                if (string.IsNullOrEmpty(resourceName))
                {
                    resourceName = inputFileNameWithoutExtension;
                }
                else
                {
                    resourceName = string.Format("{0}.{1}", resourceName, inputFileNameWithoutExtension);
                }

                typ.GetMethod("CreateStronglyTypedResources").Invoke(processResourceFiles, new object[] { inputFileName, CodeProvider, streamWriter, resourceName });
            }
            else
            {
                // this shouldn't happen
                MessageCentre.InternalErrorMessage("Exception when generating code-behind file. ProcessResourceFiles type missing. Please reinstall the nanoFramework extension.");
            }

            return(base.StreamToBytes(outputStream));
        }
コード例 #4
0
        public async Task DeployAsync(CancellationToken cancellationToken, TextWriter outputPaneWriter)
        {
            // just in case....
            if ((_viewModelLocator?.DeviceExplorer.SelectedDevice == null))
            {
                // can't debug
                // throw exception to signal deployment failure
                throw new Exception("There is no device selected. Please select a device in Device Explorer tool window.");
            }

            // get the device here so we are not always carrying the full path to the device
            NanoDeviceBase device = NanoDeviceCommService.Device;

            // user feedback
            await outputPaneWriter.WriteLineAsync($"Getting things ready to deploy assemblies to nanoFramework device: {device.Description}.");

            List <byte[]> assemblies = new List <byte[]>();

            // device needs to be in 'initialized state' for a successful and correct deployment
            // meaning that is not running nor stopped
            int  retryCount = 0;
            bool deviceIsInInitializeState = false;

            try
            {
                // check if debugger engine exists
                if (NanoDeviceCommService.Device.DebugEngine == null)
                {
                    NanoDeviceCommService.Device.CreateDebugEngine();
                }

                // connect to the device
                if (await device.DebugEngine.ConnectAsync(5000, true))
                {
                    // initial check
                    if (device.DebugEngine.IsDeviceInInitializeState())
                    {
                        // set flag
                        deviceIsInInitializeState = true;

                        // device is still in initialization state, try resume execution
                        device.DebugEngine.ResumeExecution();
                    }

                    // handle the workflow required to try resuming the execution on the device
                    // only required if device is not already there
                    // retry 5 times with a 500ms interval between retries
                    while (retryCount++ < _numberOfRetries && deviceIsInInitializeState)
                    {
                        if (!device.DebugEngine.IsDeviceInInitializeState())
                        {
                            // done here
                            deviceIsInInitializeState = false;
                            break;
                        }

                        // provide feedback to user on the 1st pass
                        if (retryCount == 0)
                        {
                            await outputPaneWriter.WriteLineAsync(ResourceStrings.WaitingDeviceInitialization);
                        }

                        if (device.DebugEngine.ConnectionSource == Tools.Debugger.WireProtocol.ConnectionSource.nanoBooter)
                        {
                            // request nanoBooter to load CLR
                            device.DebugEngine.ExecuteMemory(0);
                        }
                        else if (device.DebugEngine.ConnectionSource == Tools.Debugger.WireProtocol.ConnectionSource.nanoCLR)
                        {
                            // already running nanoCLR try rebooting the CLR
                            device.DebugEngine.RebootDevice(RebootOptions.ClrOnly);
                        }

                        // wait before next pass
                        await Task.Delay(TimeSpan.FromMilliseconds(_timeoutMiliseconds));
                    }
                    ;

                    Thread.Yield();

                    // check if device is still in initialized state
                    if (!deviceIsInInitializeState)
                    {
                        // device has left initialization state
                        await outputPaneWriter.WriteLineAsync(ResourceStrings.DeviceInitialized);

                        //////////////////////////////////////////////////////////
                        // sanity check for devices without native assemblies ?!?!
                        if (device.DeviceInfo.NativeAssemblies.Count == 0)
                        {
                            // there are no assemblies deployed?!
                            throw new DeploymentException($"Couldn't find any native assemblies deployed in {_viewModelLocator.DeviceExplorer.SelectedDevice.Description}! If the situation persists reboot the device.");
                        }

                        // For a known project output assembly path, this shall contain the corresponding
                        // ConfiguredProject:
                        Dictionary <string, ConfiguredProject> configuredProjectsByOutputAssemblyPath =
                            new Dictionary <string, ConfiguredProject>();

                        // For a known ConfiguredProject, this shall contain the corresponding project output assembly
                        // path:
                        Dictionary <ConfiguredProject, string> outputAssemblyPathsByConfiguredProject =
                            new Dictionary <ConfiguredProject, string>();

                        // Fill these two dictionaries for all projects contained in the solution
                        // (whether they belong to the deployment or not):
                        await ReferenceCrawler.CollectProjectsAndOutputAssemblyPathsAsync(
                            ProjectService,
                            configuredProjectsByOutputAssemblyPath,
                            outputAssemblyPathsByConfiguredProject);

                        // This HashSet shall contain a list of full paths to all assemblies to be deployed, including
                        // the compiled output assemblies of our solution's project and also all assemblies such as
                        // NuGet packages referenced by those projects.
                        // The HashSet will take care of only containing any string once even if added multiple times.
                        // However, this is dependent on getting all paths always in the same casing.
                        // Be aware that on file systems which ignore casing, we would end up having assemblies added
                        // more than once here if the GetFullPathAsync() methods used below should not always reliably
                        // return the path to the same assembly in the same casing.
                        HashSet <string> assemblyPathsToDeploy = new HashSet <string>();

                        // Starting with the startup project, collect all assemblies to be deployed.
                        // This will only add assemblies of projects which are actually referenced directly or
                        // indirectly by the startup project. Any project in the solution which is not referenced
                        // directly or indirectly by the startup project will not be included in the list of assemblies
                        // to be deployed.
                        await ReferenceCrawler.CollectAssembliesToDeployAsync(
                            configuredProjectsByOutputAssemblyPath,
                            outputAssemblyPathsByConfiguredProject,
                            assemblyPathsToDeploy,
                            Properties.ConfiguredProject);

                        // build a list with the full path for each DLL, referenced DLL and EXE
                        List <(string path, string version)> assemblyList = new List <(string path, string version)>();

                        foreach (string assemblyPath in assemblyPathsToDeploy)
                        {
                            // load assembly to get the version
                            var assembly = Assembly.Load(File.ReadAllBytes(assemblyPath)).GetName();
                            assemblyList.Add((assemblyPath, $"{assembly.Version.ToString(4)}"));
                        }

                        // if there are referenced project, the assembly list contains repeated assemblies so need to use Linq Distinct()
                        // build a list with the PE files corresponding to each DLL and EXE
                        List <(string path, string version)> peCollection = assemblyList.Distinct().Select(a => (a.path.Replace(".dll", ".pe").Replace(".exe", ".pe"), a.version)).ToList();

                        var checkAssembliesResult = await CheckNativeAssembliesAvailabilityAsync(device.DeviceInfo.NativeAssemblies, peCollection);

                        if (checkAssembliesResult != "")
                        {
                            // can't deploy
                            throw new DeploymentException(checkAssembliesResult);
                        }

                        // Keep track of total assembly size
                        long totalSizeOfAssemblies = 0;

                        // now we will re-deploy all system assemblies
                        foreach ((string path, string version)peItem in peCollection)
                        {
                            // append to the deploy blob the assembly
                            using (FileStream fs = File.Open(peItem.path, FileMode.Open, FileAccess.Read))
                            {
                                long length = (fs.Length + 3) / 4 * 4;
                                await outputPaneWriter.WriteLineAsync($"Adding {Path.GetFileNameWithoutExtension(peItem.path)} v{peItem.version} ({length.ToString()} bytes) to deployment bundle");

                                byte[] buffer = new byte[length];

                                await fs.ReadAsync(buffer, 0, (int)fs.Length);

                                assemblies.Add(buffer);

                                // Increment totalizer
                                totalSizeOfAssemblies += length;
                            }
                        }

                        await outputPaneWriter.WriteLineAsync($"Deploying {peCollection.Count:N0} assemblies to device... Total size in bytes is {totalSizeOfAssemblies.ToString()}.");

                        Thread.Yield();

                        if (!device.DebugEngine.DeploymentExecute(assemblies, false))
                        {
                            // throw exception to signal deployment failure
                            throw new DeploymentException("Deploy failed.");
                        }

                        Thread.Yield();

                        // deployment successful
                        await outputPaneWriter.WriteLineAsync("Deployment successful.");

                        // reset the hash for the connected device so the deployment information can be refreshed
                        _viewModelLocator.DeviceExplorer.LastDeviceConnectedHash = 0;
                    }
                    else
                    {
                        // after retry policy applied seems that we couldn't resume execution on the device...
                        // throw exception to signal deployment failure
                        throw new DeploymentException(ResourceStrings.DeviceInitializationTimeout);
                    }
                }
                else
                {
                    // throw exception to signal deployment failure
                    throw new DeploymentException($"{_viewModelLocator.DeviceExplorer.SelectedDevice.Description} is not responding. Please retry the deployment. If the situation persists reboot the device.");
                }
            }
            catch (DeploymentException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                MessageCentre.InternalErrorMessage($"Unhandled exception with deployment provider: {ex.Message}.");

                throw new Exception("Unexpected error. Please retry the deployment. If the situation persists reboot the device.");
            }
        }