Commit af09afd3 authored by David Kline's avatar David Kline Committed by GitHub
Browse files

Merge pull request #139 from WilliamsJason/master

Delete the last two test apps so I can generate proper code docs
parents 42f6b6b7 cf1f5bc9
Loading
Loading
Loading
Loading
+0 −6
Original line number Diff line number Diff line
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
</configuration>
 No newline at end of file
+0 −205
Original line number Diff line number Diff line
//----------------------------------------------------------------------------------------------
// <copyright file="DevicePortalConnection.cs" company="Microsoft Corporation">
//     Licensed under the MIT License. See LICENSE.TXT in the project root license information.
// </copyright>
//----------------------------------------------------------------------------------------------

using System;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using Microsoft.Tools.WindowsDevicePortal;
using static Microsoft.Tools.WindowsDevicePortal.DevicePortal;

namespace TestApp
{
    /// <summary>
    /// IDevicePortalConnection implementation for the core test project
    /// </summary>
    public class DevicePortalConnection : IDevicePortalConnection
    {
        /// <summary>
        /// The device's root certificate.
        /// </summary>
        private X509Certificate2 deviceCertificate = null;

        /// <summary>
        /// Initializes a new instance of the <see cref="DevicePortalConnection" /> class.
        /// </summary>
        /// <param name="address">The address of the device.</param>
        /// <param name="userName">The user name used in the connection credentials.</param>
        /// <param name="password">The password used in the connection credentials.</param>
        public DevicePortalConnection(
            string address,
            string userName,
            string password)
        {
            if (string.IsNullOrWhiteSpace(address))
            {
                address = "localhost:50443";
            }

            this.Connection = new Uri(string.Format("{0}://{1}", this.GetUriScheme(address), address));
            this.Credentials = new NetworkCredential(userName, password);
        }

        /// <summary>
        /// Gets the URI used to connect to the device.
        /// </summary>
        public Uri Connection
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets Web Socket Connection property
        /// </summary>
        public Uri WebSocketConnection
        {
            get
            {
                if (this.Connection == null)
                {
                    return null;
                }

                string absoluteUri = this.Connection.AbsoluteUri;

                if (absoluteUri.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    return new Uri(Regex.Replace(absoluteUri, "https", "wss", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant));
                }
                else
                {
                    return new Uri(Regex.Replace(absoluteUri, "http", "ws", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant));
                }
            }
        }

        /// <summary>
        /// Gets the credentials used to connect to the device.
        /// </summary>
        public NetworkCredential Credentials
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets or sets the device's operating system family.
        /// </summary>
        public string Family
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the device name.
        /// </summary>
        public string Name
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the operating system information.
        /// </summary>
        public OperatingSystemInformation OsInfo
        {
            get;
            set;
        }

        /// <summary>
        /// Gets the raw device certificate.
        /// </summary>
        /// <returns>Byte array containing the raw certificate data.</returns>
        public byte[] GetDeviceCertificateData()
        {
            return this.deviceCertificate.GetRawCertData();
        }

        /// <summary>
        /// Validates and sets the device certificate.
        /// </summary>
        /// <param name="certificate">The device's root certificate.</param>
        public void SetDeviceCertificate(X509Certificate2 certificate)
        {
            if (!certificate.IssuerName.Name.Contains(DevicePortalCertificateIssuer))
            {
                throw new DevicePortalException(
                    (HttpStatusCode)0,
                    "Invalid certificate issuer",
                    null,
                    "Failed to download device certificate");
            }

            this.deviceCertificate = certificate;
        }

        /// <summary>
        /// Updates the device's connection Uri.
        /// </summary>
        /// <param name="requiresHttps">Indicates whether or not to always require a secure connection.</param>
        public void UpdateConnection(bool requiresHttps)
        {
            string uriScheme = this.GetUriScheme(
                this.Connection.Authority, 
                requiresHttps);

            this.Connection = new Uri(
                string.Format(
                    "{0}://{1}:50443", 
                    uriScheme, 
                    this.Connection.Authority));
        }
        
        /// <summary>
        /// Updates the device's connection Uri.
        /// </summary>
        /// <param name="ipConfig">The device's IP configuration data.</param>
        /// <param name="requiresHttps">Indicates whether or not to always require a secure connection.</param>
        public void UpdateConnection(
            IpConfiguration ipConfig,
            bool requiresHttps = false)
        {
            Uri newConnection = null;

            foreach (NetworkAdapterInfo adapter in ipConfig.Adapters)
            {
                foreach (IpAddressInfo addressInfo in adapter.IpAddresses)
                {
                    // We take the first, non-169.x.x.x address we find that is not 0.0.0.0.
                    if ((addressInfo.Address != "0.0.0.0") && !addressInfo.Address.StartsWith("169."))
                    {
                        newConnection = new Uri(string.Format("{0}://{1}:50443", this.GetUriScheme(addressInfo.Address, requiresHttps), addressInfo.Address));
                        break;
                    }
                }

                if (newConnection != null)
                {
                    this.Connection = newConnection;
                    break;
                }
            }
        }

        /// <summary>
        /// Gets the URI scheme based on the specified address.
        /// </summary>
        /// <param name="address">The address of the device.</param>
        /// <param name="requiresHttps">True if a secure connection should always be required.</param>
        /// <returns>A string containing the URI scheme.</returns>
        private string GetUriScheme(
            string address,
            bool requiresHttps = true)
        {
            return "https"; // Desktop always uses https. 
                            //TODO: Replace with DNS-SD call. 
        }
    }
}
+0 −166
Original line number Diff line number Diff line
//----------------------------------------------------------------------------------------------
// <copyright file="Program.cs" company="Microsoft Corporation">
//     Licensed under the MIT License. See LICENSE.TXT in the project root license information.
// </copyright>
//----------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Tools.WindowsDevicePortal;

namespace TestApp
{
    /// <summary>
    /// Application class.
    /// </summary>
    internal class Program
    {
        /// <summary>
        /// The IP address of the device.
        /// </summary>
        private string ipAddress = null;

        /// <summary>
        /// The user name used when connecting to the device.
        /// </summary>
        private string userName = null;

        /// <summary>
        /// The password used when connecting to the device.
        /// </summary>
        private string password = null;

        /// <summary>
        /// The application entry point.
        /// </summary>
        /// <param name="args">Array of command line arguments.</param>
        public static void Main(string[] args)
        {
            Program app = new Program();

            try
            {
                app.ParseCommandLine(args);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("Usage: TestApp.exe [-ip:IP_ADDRESS:PORT] -user:USERNAME -pwd:PASSWORD");
                Console.WriteLine("\t TestApp.exe connects by default to localhost:50443");
                Console.WriteLine("\t -ip:IP_ADDRESS:PORT, connect to Device Portal running at the specified address.");
                return;
            }

            DevicePortal portal = new DevicePortal(new DevicePortalConnection(app.ipAddress, app.userName, app.password)); 
            Console.WriteLine("Connecting...");
            Task connectTask = portal.Connect();
            connectTask.Wait();
            Console.WriteLine("Connected to: " + portal.Address);
            Console.WriteLine("OS version: " + portal.OperatingSystemVersion);
            Console.WriteLine("Device family: " + portal.DeviceFamily);
            Console.WriteLine("Platform: " + portal.PlatformName + " (" + portal.Platform.ToString() + ")");

            Task<string> getNameTask = portal.GetDeviceName();
            getNameTask.Wait();
            Console.WriteLine("Device name: " + getNameTask.Result);

            TestTagListing(portal);

            TestDeviceList(portal);

            while (true)
            {
                System.Threading.Thread.Sleep(0);
            }
        }

        /// <summary>
        /// Tests the DNS-SD APIs
        /// </summary>
        /// <param name="portal">DevicePortal object used for testing</param>
        private static void TestTagListing(DevicePortal portal)
        {
            Task<List<string>> getTagsTask = portal.GetServiceTags();
            getTagsTask.Wait();
            Console.Write("Service Tags: ");
            if (getTagsTask.Result.Count == 0)
            {
                Console.Write("<none>");
            }

            foreach (string s in getTagsTask.Result)
            {
                Console.Write(s + ", ");
            }

            Console.WriteLine(string.Empty);
        }

        /// <summary>
        /// Tests the DeviceManager APIs
        /// </summary>
        /// <param name="portal">DevicePortal object used for testing</param>
        private static void TestDeviceList(DevicePortal portal)
        {
            Task<List<DevicePortal.Device>> getdeviceListTask = portal.GetDeviceList();
            getdeviceListTask.Wait();
            List<DevicePortal.Device> deviceList = getdeviceListTask.Result;

            DevicePortal.Device device = deviceList.Find(x => x.FriendlyName != null); //not all Devices come with a friendly name 
            Console.WriteLine("First Device: {0}", device.Description);
        }

        /// <summary>
        /// Parses the application's command line.
        /// </summary>
        /// <param name="args">Array of command line arguments.</param>
        private void ParseCommandLine(string[] args)
        {
            for (int i = 0; i < args.Length; i++)
            {
                string arg = args[i].ToLower();
                if (!arg.StartsWith("/") && !arg.StartsWith("-"))
                {
                    throw new Exception(string.Format("Unrecognized argument: {0}", args[i]));
                }

                arg = arg.Substring(1);

                if (arg.StartsWith("ip:"))
                {
                    this.ipAddress = this.GetArgData(args[i]);
                }
                else if (arg.StartsWith("user:"))
                {
                    this.userName = this.GetArgData(args[i]);
                }
                else if (arg.StartsWith("pwd:"))
                {
                    this.password = this.GetArgData(args[i]);
                }
                else
                {
                    throw new Exception(string.Format("Unrecognized argument: {0}", args[i]));
                }
            }

            // We require at least a user name and password to proceed.
            if (string.IsNullOrWhiteSpace(this.userName) || string.IsNullOrWhiteSpace(this.password))
            {
                throw new Exception("You must specify a user name and a password");
            }
        }

        /// <summary>
        /// Gets the value from a key:value command line argument.
        /// </summary>
        /// <param name="arg">A key:value command line argument.</param>
        /// <returns>String containing the argument value.</returns>
        private string GetArgData(string arg)
        {
            int idx = arg.IndexOf(':');
            return arg.Substring(idx + 1);
        }
    }
}
+0 −42
Original line number Diff line number Diff line
//----------------------------------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="Microsoft Corporation">
//     Licensed under the MIT License. See LICENSE.TXT in the project root license information.
// </copyright>
//----------------------------------------------------------------------------------------------

using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following 
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TestApp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TestApp")]
[assembly: AssemblyCopyright("Copyright ©  2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible 
// to COM components.  If you need to access a type in this assembly from 
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("46c9836d-211a-43b8-b032-076c53a3d57c")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version 
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers 
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
+0 −44
Original line number Diff line number Diff line
<StyleCopSettings Version="105">
  <Analyzers>
    <Analyzer AnalyzerId="StyleCop.CSharp.DocumentationRules">
      <Rules>
        <Rule Name="ElementDocumentationMustBeSpelledCorrectly">
          <RuleSettings>
            <BooleanProperty Name="Enabled">False</BooleanProperty>
          </RuleSettings>
        </Rule>
      </Rules>
      <AnalyzerSettings />
    </Analyzer>
    <Analyzer AnalyzerId="StyleCop.CSharp.LayoutRules">
      <Rules>
        <Rule Name="SingleLineCommentMustBePrecededByBlankLine">
          <RuleSettings>
            <BooleanProperty Name="Enabled">False</BooleanProperty>
          </RuleSettings>
        </Rule>
      </Rules>
      <AnalyzerSettings />
    </Analyzer>
    <Analyzer AnalyzerId="StyleCop.CSharp.OrderingRules">
      <Rules>
        <Rule Name="UsingDirectivesMustBePlacedWithinNamespace">
          <RuleSettings>
            <BooleanProperty Name="Enabled">False</BooleanProperty>
          </RuleSettings>
        </Rule>
      </Rules>
      <AnalyzerSettings />
    </Analyzer>
    <Analyzer AnalyzerId="StyleCop.CSharp.SpacingRules">
      <Rules>
        <Rule Name="SingleLineCommentsMustBeginWithSingleSpace">
          <RuleSettings>
            <BooleanProperty Name="Enabled">False</BooleanProperty>
          </RuleSettings>
        </Rule>
      </Rules>
      <AnalyzerSettings />
    </Analyzer>
  </Analyzers>
</StyleCopSettings>
 No newline at end of file
Loading