/// <summary>
        /// A method is used to verify whether a WOPI resource URL mapping record exists in cache. The WOPI resource url record is determined by the domain\user and the file url.
        /// </summary>
        /// <param name="userName">A parameter represents the user name.</param>
        /// <param name="domain">A parameter represents the domain name.</param>
        /// <param name="absoluteFileUrl">A parameter represents the file URL. It must be absolute URL.</param>
        /// <param name="wopiResourceUrl">An out parameter represents the WOPI resource URL when this method returns. If this method could not get the WOPI resource URL, this value will be string.Empty.</param>
        /// <returns>Return 'true' indicating the WOPI resource URL record exists in cache and out put to the "wopiResourceUrl" parameter.</returns>
        public static bool TryGetWOPIResourceUrl(string userName, string domain, string absoluteFileUrl, out string wopiResourceUrl)
        {
            #region Verify parameter
            HelperBase.CheckInputParameterNullOrEmpty <string>(userName, "userName", "TryGetWOPIResourceUrl");
            HelperBase.CheckInputParameterNullOrEmpty <string>(domain, "domain", "TryGetWOPIResourceUrl");
            HelperBase.CheckInputParameterNullOrEmpty <string>(absoluteFileUrl, "absoluteFileUrl", "TryGetWOPIResourceUrl");

            Uri fileLocation;
            if (!Uri.TryCreate(absoluteFileUrl, UriKind.Absolute, out fileLocation))
            {
                throw new ArgumentException("The file url should be absolute url", "absoluteFileUrl");
            }

            #endregion

            string fullUserName = string.Format(@"{0}\{1}", domain, userName);
            Dictionary <string, string> urlMappingCollectionOfUser = GetUrlMappingCollectionByFullUserName(fullUserName, false);
            wopiResourceUrl = string.Empty;
            if (null == urlMappingCollectionOfUser || 0 == urlMappingCollectionOfUser.Count)
            {
                return(false);
            }

            var expectedWOPIResourceUrlItems = from wopiUrlMapping in urlMappingCollectionOfUser
                                               where wopiUrlMapping.Key.Equals(absoluteFileUrl, StringComparison.OrdinalIgnoreCase)
                                               select wopiUrlMapping.Value;

            if (0 == expectedWOPIResourceUrlItems.Count())
            {
                return(false);
            }

            wopiResourceUrl = expectedWOPIResourceUrlItems.ElementAt <string>(0);
            return(true);
        }
        /// <summary>
        /// A method is used to add a  WOPI resource URL mapping record into the cache. The record is determined by the domain\user and the file url.
        /// </summary>
        /// <param name="userName">A parameter represents the user name.</param>
        /// <param name="domain">A parameter represents the domain name.</param>
        /// <param name="absoluteFileUrl">A parameter represents the file URL. It must be absolute URL.</param>
        /// <param name="wopiResourceUrl">A parameter represents the WOPI resource URL.</param>
        public static void AddWOPIResourceUrl(string userName, string domain, string absoluteFileUrl, string wopiResourceUrl)
        {
            #region Verify parameter
            HelperBase.CheckInputParameterNullOrEmpty <string>(userName, "userName", "AddWOPIResourceUrl");
            HelperBase.CheckInputParameterNullOrEmpty <string>(domain, "domain", "AddWOPIResourceUrl");
            HelperBase.CheckInputParameterNullOrEmpty <string>(absoluteFileUrl, "absoluteFileUrl", "AddWOPIResourceUrl");
            HelperBase.CheckInputParameterNullOrEmpty <string>(wopiResourceUrl, "wopiResourceUrl", "AddWOPIResourceUrl");

            Uri filelocation;
            if (!Uri.TryCreate(absoluteFileUrl, UriKind.Absolute, out filelocation))
            {
                throw new ArgumentException("The file url should be absolute url", "absoluteFileUrl");
            }

            Uri wopiResourceLocation;
            if (!Uri.TryCreate(wopiResourceUrl, UriKind.Absolute, out wopiResourceLocation))
            {
                throw new ArgumentException("The WOPI resource url should be absolute url", "wopiResourceUrl");
            }

            #endregion

            string fullUserName = string.Format(@"{0}\{1}", domain, userName);
            Dictionary <string, string> urlMappingCollectionOfUser = GetUrlMappingCollectionByFullUserName(fullUserName);
            urlMappingCollectionOfUser.Add(absoluteFileUrl, wopiResourceUrl);
        }
Пример #3
0
        /// <summary>
        /// A method is used to read html contents from the http response. If could not read the html contents, it will throw an exception.
        /// </summary>
        /// <param name="response">A parameter represents http response which should contain html contents.</param>
        /// <returns>A return value represents the read html contents from http response.</returns>
        protected string ReadHtmlContentFromResponse(HttpWebResponse response)
        {
            HelperBase.CheckInputParameterNullOrEmpty <HttpWebResponse>(response, "response", "ReadHtmlContentsFromResponse");

            string htmlContent = string.Empty;
            Stream stream      = null;

            try
            {
                stream = response.GetResponseStream();
                Encoding encoding = Encoding.GetEncoding(response.CharacterSet);
                using (StreamReader reader = new StreamReader(stream, encoding))
                {
                    htmlContent = reader.ReadToEnd();
                }
            }
            finally
            {
                if (stream != null)
                {
                    stream.Dispose();
                }
            }

            if (string.IsNullOrEmpty(htmlContent))
            {
                string errorMsg = string.Format(@"Could not get the request view file's response from the WOPI server.");

                throw new InvalidOperationException(errorMsg);
            }

            return(htmlContent);
        }
Пример #4
0
        /// <summary>
        /// A method is used to get necessary internal http and internal https ct_netzone instances. This values is used to response to the WOPI server so that the WOPI server can use this test client as a WOPI client.
        /// </summary>
        /// <param name="currentTestClientName">A parameter represents the current test client name which run the test suite. This value is used to generated the WOPI client's app name.</param>
        /// <returns>A return value represents an array of ct_netzone type instances.</returns>
        private static ct_netzone[] GetNetZonesForWopiDiscoveryResponse(string currentTestClientName)
        {
            #region validate the parameter

            HelperBase.CheckInputParameterNullOrEmpty <string>(currentTestClientName, "currentTestClientName", "GetNetZoneForWopiDiscoveryResponse");

            #endregion

            string fakedWOPIClientActionHostName = string.Format(@"{0}.com", Guid.NewGuid().ToString("N"));

            // Http Net zone
            ct_netzone httpNetZone = GetSingleNetZoneForWopiDiscoveryResponse(st_wopizone.internalhttp, currentTestClientName, fakedWOPIClientActionHostName);

            // Https Net zone
            ct_netzone httpsNetZone = GetSingleNetZoneForWopiDiscoveryResponse(st_wopizone.internalhttps, currentTestClientName, fakedWOPIClientActionHostName);

            return(new ct_netzone[] { httpNetZone, httpsNetZone });
        }
        /// <summary>
        /// A method is used to get the WOPIsrc value and the token value.
        /// </summary>
        /// <param name="wopiResourceUrl">A parameter represents the WOPI resource URL</param>
        /// <returns>A return value represents a name-value pairs collection which includes the WOPIsrc value and the token value. The token value can be get by "Token" key, the WOPIsrc value can be get by "WOPISrc" key.</returns>
        protected static Dictionary <string, string> GetWOPISrcAndTokenValueFromWOPIResourceUrl(string wopiResourceUrl)
        {
            if (string.IsNullOrEmpty(wopiResourceUrl))
            {
                throw new ArgumentNullException("wopiResourceUrl");
            }

            Uri currentUri = null;

            if (!Uri.TryCreate(wopiResourceUrl, UriKind.Absolute, out currentUri))
            {
                throw new ArgumentException("It must be a valid absolute URL", "wopiResourceUrl");
            }

            #region verify the URL.

            NameValueCollection queryParameterValues = HttpUtility.ParseQueryString(currentUri.Query);
            if (null == queryParameterValues || 0 == queryParameterValues.Count)
            {
                string errorMsg = string.Format("The WOPI resource URL must contain the URL query parameter. current URL:[{0}] \r\n", wopiResourceUrl);
                HelperBase.AppendLogs(typeof(TokenAndRequestUrlHelper), errorMsg);
                throw new InvalidOperationException(errorMsg);
            }

            string expectedQueryParameter = @"access_token";

            // Verify the query parameters whether contain "access_token"
            if (!queryParameterValues.AllKeys.Any(Founder => Founder.Equals(expectedQueryParameter, StringComparison.OrdinalIgnoreCase)))
            {
                string errorMsg = string.Format("The WOPI resource URL must contain [access_token] parameter. current URL:[{0}] \r\n", wopiResourceUrl);
                HelperBase.AppendLogs(typeof(TokenAndRequestUrlHelper), errorMsg);
                throw new InvalidOperationException(errorMsg);
            }

            #endregion

            string wopiSrcUrl = currentUri.GetLeftPart(UriPartial.Path);
            Dictionary <string, string> wopiSrcAndTokenValues = new Dictionary <string, string>();
            wopiSrcAndTokenValues.Add("WOPISrc", wopiSrcUrl);
            wopiSrcAndTokenValues.Add("Token", queryParameterValues[expectedQueryParameter]);
            return(wopiSrcAndTokenValues);
        }
        /// <summary>
        /// A method is used to initialize the TokenAndRequestUrlHelper helper.
        /// </summary>
        /// <param name="managedCodeSutConrollerAdapterInstance">A parameter represents the IMS_WOPISUTManageCodeControlAdapter type instance, it is used to get WOPI root resource URL.</param>
        /// <param name="testSiteInstance">A parameter represents an ITestSite instance which is used to get test suite context.</param>
        public static void InitializeHelper(IMS_WOPIManagedCodeSUTControlAdapter managedCodeSutConrollerAdapterInstance, ITestSite testSiteInstance)
        {
            HelperBase.CheckInputParameterNullOrEmpty <IMS_WOPIManagedCodeSUTControlAdapter>(managedCodeSutConrollerAdapterInstance, "managedCodeSutConrollerAdapterInstance", "InitializeHelper");
            HelperBase.CheckInputParameterNullOrEmpty <ITestSite>(testSiteInstance, "testSiteInstance", "InitializeHelper");

            if (!hasInitializedTokenAndRequestUrlHelper)
            {
                if (string.IsNullOrEmpty(DefaultUserName))
                {
                    DefaultUserName = Common.GetConfigurationPropertyValue("UserName", testSiteInstance);
                    DefaultDomain   = Common.GetConfigurationPropertyValue("Domain", testSiteInstance);
                    DefaultPassword = Common.GetConfigurationPropertyValue("Password", testSiteInstance);
                }

                if (null == currentTestSite)
                {
                    currentTestSite = testSiteInstance;
                }

                CurrentHttpTransport = Common.GetConfigurationPropertyValue <TransportProtocol>("TransportType", testSiteInstance);
                hasInitializedTokenAndRequestUrlHelper = true;
            }
        }
        /// <summary>
        /// A method is used to get folder children's level URL.
        /// </summary>
        /// <param name="wopiRootResourceUrl">A parameter represents the WOPI resource URL for the folder level.</param>
        /// <param name="subResourceUrlType">A parameter represents the WOPI sub resource URL for the folder level.</param>
        /// <returns>A return value represents the folder children's level URL.</returns>
        public static string GetSubResourceUrl(string wopiRootResourceUrl, WOPISubResourceUrlType subResourceUrlType)
        {
            #region Verify parameter
            if (string.IsNullOrEmpty(wopiRootResourceUrl))
            {
                throw new ArgumentNullException("wopiRootResourceUrl");
            }

            Uri currentUri = null;
            if (!Uri.TryCreate(wopiRootResourceUrl, UriKind.Absolute, out currentUri))
            {
                throw new ArgumentException("It must be a valid absolute URL", "wopiRootResourceUrl");
            }

            string expectedIncludeStringValue    = string.Empty;
            string expectedPatternValue          = string.Empty;
            string expectedSubResourceUrlPostfix = string.Empty;
            WOPIRootResourceUrlType expectedRootResourceUrlType = WOPIRootResourceUrlType.FileLevel;
            switch (subResourceUrlType)
            {
            case WOPISubResourceUrlType.FolderChildrenLevel:
            {
                expectedIncludeStringValue    = @"/folders/";
                expectedPatternValue          = folderLevelPattern;
                expectedSubResourceUrlPostfix = @"/children";
                expectedRootResourceUrlType   = WOPIRootResourceUrlType.FolderLevel;
                break;
            }

            case WOPISubResourceUrlType.FileContentsLevel:
            {
                expectedIncludeStringValue    = @"/files/";
                expectedPatternValue          = fileLevelPattern;
                expectedSubResourceUrlPostfix = @"/contents";
                expectedRootResourceUrlType   = WOPIRootResourceUrlType.FileLevel;
                break;
            }

            default:
            {
                throw new InvalidOperationException(string.Format(@"The test suite only supports [{0}] and [{1}] two WOPI sub resource URL formats.", WOPISubResourceUrlType.FileContentsLevel, WOPISubResourceUrlType.FolderChildrenLevel));
            }
            }

            if (wopiRootResourceUrl.IndexOf(expectedIncludeStringValue, StringComparison.OrdinalIgnoreCase) < 0)
            {
                string errorMsg = string.Format(
                    @"To getting the [{0}] sub resource URL, the WOPI root resource URL must be [{1}] type, and its format must be [{2}] format.",
                    subResourceUrlType,
                    expectedRootResourceUrlType,
                    expectedPatternValue);

                HelperBase.AppendLogs(typeof(TokenAndRequestUrlHelper), errorMsg);
                throw new InvalidOperationException(errorMsg);
            }

            string pathValueOfUrl = currentUri.AbsolutePath;
            if (pathValueOfUrl.EndsWith(@"/contents", StringComparison.OrdinalIgnoreCase) ||
                pathValueOfUrl.EndsWith(@"/children", StringComparison.OrdinalIgnoreCase))
            {
                string errorMsg = string.Format(
                    @"The URL value has been WOPI sub resource URL:[{0}]",
                    wopiRootResourceUrl);
                HelperBase.AppendLogs(typeof(TokenAndRequestUrlHelper), errorMsg);
                throw new InvalidOperationException(errorMsg);
            }

            #endregion

            Dictionary <string, string> wopiSrcAndTokenValues = GetWOPISrcAndTokenValueFromWOPIResourceUrl(wopiRootResourceUrl);
            string wopiSrcValue = wopiSrcAndTokenValues["WOPISrc"];
            string tokenValue   = wopiSrcAndTokenValues["Token"];

            // Construct the sub WOPI resource URL.
            string wopiSubResourceUrl = string.Format(
                @"{0}{1}{2}{3}",
                wopiSrcValue,
                expectedSubResourceUrlPostfix,
                @"?access_token=",
                tokenValue);

            return(wopiSubResourceUrl);
        }