public override bool VerifyResults(bool success, string log) { switch (AstoriaTestProperties.DesignVersion) { case null: case "V1": case "V2": case "Dev10": return(success == true); default: AstoriaTestLog.FailAndThrow("Unknown /ClientVersion parameter value"); return(success == true); } }
private string getRemoteSystemDrive() { try { using (SqlConnection sqlConn = new SqlConnection(this.MachineConnectionString)) { sqlConn.Open(); SqlCommand sqlCmd = sqlConn.CreateCommand(); sqlCmd.CommandTimeout = 0; sqlCmd.CommandText = "exec master..xp_cmdshell N'echo %SYSTEMDRIVE%'"; String driveLetter = (String)sqlCmd.ExecuteScalar(); return(driveLetter); } } catch (Exception e) { AstoriaTestLog.FailAndThrow("Unable to retrieve %SYSTEMDRIVE% of remote DB Machine"); } return(null); }
//Get the expression tree public static String ProcessExpressionTree(Workspace w, QueryTreeInfo queryTreeInfo) { // Retrieve expression tree. AstoriaResponse rs; RequestUtil.GetAndVerifyStatusCode(w, w.ServiceUri + "/ExpToXml", HttpStatusCode.OK, out rs); if (rs.ActualStatusCode != HttpStatusCode.OK && rs.ActualStatusCode != HttpStatusCode.NotFound) { AstoriaTestLog.WriteLine("/ExpToXml returned error code " + rs.ActualStatusCode.ToString() + ", payload:"); AstoriaTestLog.FailAndThrow(rs.Payload); } // Extract XML document from response. XmlDocument xml = new XmlDocument(); xml.LoadXml(rs.Payload); // Skip verification in retail builds as they do not contain expression capture hook. string embeddedDocument = xml.DocumentElement.InnerText; AstoriaTestLog.WriteLine(embeddedDocument); if (embeddedDocument.StartsWith("WARNING")) { // Warn the user. AstoriaTestLog.WriteLine("WARNING: missing expression tree!"); AstoriaTestLog.Skip("Test variation skipped"); } // Separate string form and XML form. string[] pair = embeddedDocument.Split(new string[] { "[[===]]" }, StringSplitOptions.None); xml.LoadXml(pair[1].Replace("utf-16", "utf-8")); AstoriaTestLog.WriteLine(xml.OuterXml); if (queryTreeInfo != null) { queryTreeInfo.currentTreeXml = xml; } //return xml; return(pair[0]); }
public static void CompileCodeFiles(string[] codeFilePaths, string[] resourceFiles, string dllFilePath, string[] compilerDefines, WorkspaceLanguage language, Dictionary <string, string> providerOptions, string[] referencedAssemblies, bool compileExe) { CodeDomProvider compiler; if (language == WorkspaceLanguage.VB) { compiler = new VBCodeProvider(providerOptions); } else { compiler = new CSharpCodeProvider(providerOptions); } //Options CompilerParameters cp = new CompilerParameters(); cp.GenerateExecutable = compileExe; cp.IncludeDebugInformation = true; cp.OutputAssembly = dllFilePath; if (!Versioning.Server.SupportsV2Features) { cp.CompilerOptions = "/Define:ASTORIA_PRE_V2"; } if (compilerDefines != null) { foreach (string define in compilerDefines) { cp.CompilerOptions += " /Define:" + define; } } if (resourceFiles != null && resourceFiles.Length > 0) { foreach (string embeddedResourceFile in resourceFiles) { cp.CompilerOptions += " /res:" + embeddedResourceFile; } } Func <string, string> resolve = delegate(string f) { if (string.Equals(DataFxAssemblyRef.File.DataServicesClient, f, StringComparison.OrdinalIgnoreCase) || string.Equals(DataFxAssemblyRef.File.ODataLib, f, StringComparison.OrdinalIgnoreCase) || string.Equals(DataFxAssemblyRef.File.DataServices, f, StringComparison.OrdinalIgnoreCase)) { return(Environment.ExpandEnvironmentVariables(System.IO.Path.Combine(DataFxAssemblyRef.File.DS_ReferenceAssemblyPath, f))); } return(f); }; //References //Note: We don't hard-code the assmeblies, but obtain the name from the referenced types cp.ReferencedAssemblies.Clear(); cp.ReferencedAssemblies.AddRange(referencedAssemblies.Select(resolve).Distinct().ToArray()); //Compile CompilerResults cr = compiler.CompileAssemblyFromFile(cp, codeFilePaths); //Compiler Errors string completeError = ""; foreach (CompilerError error in cr.Errors) { switch (error.ErrorNumber) { case "CS0016": //File is locked (file already loaded) case "CS0042": //Failure to generate debug information (file already loaded) continue; } ; //Otherwise if (completeError.Length > 0) { completeError += "\r\n" + error.ToString(); } else { completeError = error.ToString(); } } if (completeError.Length > 0) { AstoriaTestLog.FailAndThrow(completeError); } }
public void GenerateServiceOperations(TemplateFile templateFile) { StringBuilder serviceOps = new StringBuilder(); foreach (MethodInfo method in typeof(NonClrTestWebService <>).GetMethods()) { object[] attribs = method.GetCustomAttributes(false); bool isSingleResult = false; foreach (object attrib in attribs) { if (attrib is Microsoft.OData.Service.SingleResultAttribute) { isSingleResult = true; break; } } foreach (object attrib in attribs) { if (attrib is System.ServiceModel.Web.WebGetAttribute || attrib is System.ServiceModel.Web.WebInvokeAttribute) { string kind; if (typeof(IQueryable).IsAssignableFrom(method.ReturnType)) { if (isSingleResult) { kind = "ServiceOperationResultKind.QueryWithSingleResult"; } else { kind = "ServiceOperationResultKind.QueryWithMultipleResults"; } } else if (typeof(IEnumerable).IsAssignableFrom(method.ReturnType) && !typeof(RowComplexType).IsAssignableFrom(method.ReturnType) && method.ReturnType != typeof(string) && method.ReturnType != typeof(byte[])) { // this will be incorrect for complex types which derive from IEnumerable, but its the best we can do for now kind = "ServiceOperationResultKind.Enumeration"; } else if (typeof(void).IsAssignableFrom(method.ReturnType)) { kind = "ServiceOperationResultKind.Void"; } else { // either primitive or complex kind = "ServiceOperationResultKind.DirectValue"; } string verb; if (attrib is System.ServiceModel.Web.WebGetAttribute) { verb = "GET"; } else { verb = (attrib as System.ServiceModel.Web.WebInvokeAttribute).Method; } serviceOps.AppendLine("serviceOpCreateParams.Add(new ServiceOperationCreationParams(\"" + method.Name + "\", " + kind + ", \"\", \"" + verb + "\"));"); break; } } } foreach (ServiceOperation op in _workspace.ServiceContainer.ResourceContainers.OfType <ServiceOperation>()) { if (!op.ServiceOperationResultKind.HasValue) { AstoriaTestLog.FailAndThrow("Cannot generate code for service operation because the result kind is not set"); } if (op.ExpectedTypeName == null) { AstoriaTestLog.FailAndThrow("Cannot generate code for service operation because the expected type name is not set"); } string kind = "ServiceOperationResultKind." + op.ServiceOperationResultKind.Value.ToString(); serviceOps.AppendLine("serviceOpCreateParams.Add(new ServiceOperationCreationParams(\"" + op.Name + "\", " + kind + ", \"" + op.BaseType.Name + "\", \"" + op.Verb.ToHttpMethod() + "\"));"); } templateFile.FileText = templateFile.FileText.Replace("[[GeneratedServiceOperations]]", serviceOps.ToString()); }
private string CreateProperty(ComplexType type, ResourceProperty property, bool lazyLoad) { StringBuilder propertyCode = new StringBuilder(); string typeName = type.Name.ToLowerInvariant(); string propertyDeclarationName = type.Name + property.Name + "Property"; string propertyNameParam = String.Format("\"{0}\"", property.Name); string propertyKindParam = GetPropertyKindString(property); string propertyTypeParam = GetPropertyTypeString(property); string propertyParams = string.Join(", ", new string[] { propertyNameParam, propertyKindParam, propertyTypeParam }); string existingName = ExistingPropertyName(propertyParams, property.Facets.IsClrProperty, propertyDeclarationName); if (existingName != null && !property.IsComplexType && !property.IsNavigation) { if (lazyLoad) { propertyCode.AppendLine(String.Format("{0}.AddLazyProperty({1});", typeName, existingName)); } else { propertyCode.AppendLine(String.Format("{0}.AddProperty({1});", typeName, existingName)); } } else { propertyCode.AppendLine(String.Format("ResourceProperty {0} = new ResourceProperty({1});", propertyDeclarationName, propertyParams)); if (property.Facets.IsClrProperty) { propertyCode.AppendLine(String.Format("{0}.CanReflectOnInstanceTypeProperty = true;", propertyDeclarationName)); } else { propertyCode.AppendLine(String.Format("{0}.CanReflectOnInstanceTypeProperty = false;", propertyDeclarationName)); } if (property.IsNavigation) { if (property.OtherSideNavigationProperty != null) { propertyCode.AppendLine(String.Format("{0}.CustomState = \"{1}\";", propertyDeclarationName, property.OtherSideNavigationProperty.ResourceAssociation.Name)); } else if (property.Facets.MestTag != null) { propertyCode.AppendLine(String.Format("{0}.CustomState = \"{1}\";", propertyDeclarationName, property.Facets.MestTag)); } } else if (property.Facets.ServerGenerated) { if (property.Type != Clr.Types.Int32) { AstoriaTestLog.FailAndThrow("Server-generated values only supported for ints"); } propertyCode.AppendLine(String.Format("{0}.CustomState = \"{1}\";", propertyDeclarationName, NonClr.NonClrContext.ServerGeneratedCustomState)); } if (lazyLoad) { propertyCode.AppendLine(String.Format("{0}.AddLazyProperty({1});", typeName, propertyDeclarationName)); } else { propertyCode.AppendLine(String.Format("{0}.AddProperty({1});", typeName, propertyDeclarationName)); } } return(propertyCode.ToString()); }
public static AstoriaWebDataService CreateAstoriaDataWebService(Workspace workspace, string webDataServicePrefixName, AstoriaDatabase database, bool skipDataServiceVerify) { AstoriaWebDataService service = null; //Base the creation on the AstoriaTestProperties switch (AstoriaTestProperties.Host) { case Host.WebServiceHost: case Host.IDSH: case Host.IDSH2: service = new AstoriaServiceHost(workspace, webDataServicePrefixName, Environment.MachineName, database); break; case Host.WebServiceHostRemote: service = new AstoriaServiceHost(workspace, webDataServicePrefixName, GetMachineName(), database); break; default: service = new IISWebDataService(workspace, webDataServicePrefixName, GetMachineName(), database); break; } // write out helpful debugging URIs if (AstoriaTestProperties.Client == ClientEnum.SILVERLIGHT) { WriteUriToList(service.ServiceRootUri + "Monitor.aspx"); WriteUriToList(service.ServiceRootUri + "SilverlightAstoriaTestPage.html"); WriteUriToList(service.ServiceUri); } // if running locally in partial trust, ensure that the trusted methods are available if (AstoriaTestProperties.IsLocalHost && AstoriaTestProperties.ServiceTrustLevel != TrustLevel.Full && AstoriaTestProperties.RuntimeEnvironment == TestRuntimeEnvironment.Lab) { Assembly trustedAssembly = typeof(FullTrust.TrustedMethods).Assembly; //if (!trustedAssembly.GlobalAssemblyCache) //{ // AstoriaTestLog.FailAndThrow("Assembly containing fully trusted components must be in the GAC. " + // "Run 'gacutil -if <dll>' on AstoriaTestFramework.FullTrust from a visual studio command prompt"); //} if (!trustedAssembly.IsFullyTrusted) { AstoriaTestLog.FailAndThrow("Assembly containing components requiring full trust is not trusted"); } } try { // push the verification step down to the derived classes so that a failure there can be handled accordingly // service.CreateWebService(!skipDataServiceVerify); } catch (Exception e) { // we need to make sure that we don't 'leak' services that fail to start, as it can mean a process is left running that will // cause subsequent ArtClean's to fail. This has caused build failures at least once. // if (AstoriaTestProperties.IsLabRun || AstoriaTestProperties.RuntimeEnvironment == TestRuntimeEnvironment.CheckinSuites) { service.Dispose(); } throw new TestFailedException("Failed to create web service", null, null, e); } if (skipDataServiceVerify) { // for call logging, we need the directory to exist, and the service doesn't necessarily have permission to create it // TODO: find some better, common place to put this for IIS, WebServiceHost, etc. Right now this is the best spot #if !ClientSKUFramework IOUtil.EnsureEmptyDirectoryExists(Path.Combine(service.DestinationFolder, CallOrder.APICallLog.DirectoryName)); #endif Thread.Sleep(5000); //To allow time for the service to start running before requests get made } return(service); }
public void VerifyService() { // for call logging, we need the directory to exist, and the service doesn't necessarily have permission to create it // TODO: find some better, common place to put this for IIS, WebServiceHost, etc. Right now this is the best spot #if !ClientSKUFramework IOUtil.EnsureEmptyDirectoryExists(Path.Combine(DestinationFolder, CallOrder.APICallLog.DirectoryName)); #endif const int retryCount = 10; const int sleepTime = 6000; AstoriaTestLog.WriteLineIgnore("Verifying web service: " + this.ServiceUri); HttpWebRequest request = null; HttpWebResponse response = null; WebException webException = null; for (int count = 0; count < retryCount; count++) { try { request = (HttpWebRequest)HttpWebRequest.Create(this.ServiceUri + "/$metadata"); request.UseDefaultCredentials = true; response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream())) reader.ReadToEnd(); if (response.StatusCode == HttpStatusCode.OK) { AstoriaTestLog.WriteLineIgnore("Service verified."); return; } else { // can this happen without throwing? AstoriaTestLog.WriteLine("\tUnexpected status code: " + response.StatusCode); } } catch (Exception e) { string indent = "\t"; while (e != null) { if (e is WebException) { webException = e as WebException; } AstoriaTestLog.WriteLine(indent + e.GetType().Name + ": " + e.Message); indent += "\t"; e = e.InnerException; } } Thread.Sleep(sleepTime); } if (webException != null) { AstoriaTestLog.TraceLine("Web exception:"); AstoriaTestLog.TraceLine(webException.ToString()); if (webException.Response != null) { string exceptionPayload; using (StreamReader reader = new StreamReader(webException.Response.GetResponseStream())) exceptionPayload = reader.ReadToEnd(); AstoriaTestLog.TraceLine("Exception Payload:"); AstoriaTestLog.TraceLine(exceptionPayload); } } AstoriaTestLog.FailAndThrow("Service could not be verified."); }
protected void WriteEntityTypeClass(ResourceType rt) { // write the key attribute CodeBuilder.WriteDataKeyAttribute(rt.Properties.OfType <ResourceProperty>().Where(rp => rp.PrimaryKey != null)); // write other attributes foreach (ResourceAttribute att in rt.Facets.Attributes) { att.Apply(CodeBuilder); } //// friendly feeds attributes are sometimes on the properties! //foreach (NodeProperty p in rt.Properties) //{ // FriendlyFeedsAttribute attribute; // if (FriendlyFeedsAttribute.TryGetAttribute(rt, p, out attribute)) // { // FriendlyFeedsAttribute fromBase; // if (rt.BaseType == null || !FriendlyFeedsAttribute.TryGetAttribute(rt.BaseType, p, out fromBase) || attribute != fromBase) // { // attribute.Apply(CodeBuilder); // } // } //} string baseType = null; if (rt.BaseType != null) { baseType = rt.BaseType.Name; } CodeBuilder.WriteBeginClass(rt.Name, baseType, null, rt.Facets.AbstractType); List <string> incrementers = new List <string>(); foreach (ResourceProperty rp in rt.Properties.OfType <ResourceProperty>().Where(p => p.Facets.ServerGenerated)) { if (rp.Type != Clr.Types.Int32) { AstoriaTestLog.FailAndThrow("Currently, we only code-gen server-generated ints"); } CodeBuilder.WriteLine("private static int _" + rp.Name + "_Counter = 0;"); incrementers.Add(rp.Name); } if (incrementers.Any()) { CodeBuilder.WriteLine(" public " + rt.Name + "()"); CodeBuilder.WriteLine(" {"); foreach (string propertyName in incrementers) { CodeBuilder.WriteLine(" this." + propertyName + " = _" + propertyName + "_Counter++;"); } CodeBuilder.WriteLine(" }"); } // write out the properties foreach (ResourceProperty rp in rt.Properties.OfType <ResourceProperty>()) { // if this property is not defined on the base type if (rt.BaseType == null || !rt.BaseType.Properties.Any(p => p.Name == rp.Name)) { if (rp.Facets.IsDeclaredProperty) { if (rp.IsNavigation) { CreateNavigationProperty(rp); } else { CreateValueProperty(rp); } } } } //Create a BiDirectionalRelationshipMap CodeBuilder.CreateNavigationMapMethod(rt); CodeBuilder.WriteEndClass(rt.Name); CodeBuilder.WriteLine(); }