private void AttachDatabase() { if (_isLocal) { EnsureLocalLoginExists(); } DropDatabase(); AstoriaTestLog.WriteLineIgnore("-------AttachDb: {0}---------", this.MachineConnectionString); using (SqlConnection sqlConn = new SqlConnection(this.MachineConnectionString)) { sqlConn.Open(); using (SqlCommand sqlCmd = sqlConn.CreateCommand()) { sqlCmd.CommandTimeout = 0; CopyDatabaseFiles(); sqlCmd.CommandText = "sp_attach_db"; sqlCmd.CommandType = CommandType.StoredProcedure; sqlCmd.Parameters.Add(new SqlParameter("@dbname", this.DatabaseName)); sqlCmd.Parameters.Add(new SqlParameter("@filename1", AttachedMdf)); sqlCmd.Parameters.Add(new SqlParameter("@filename2", AttachedLdf)); sqlCmd.ExecuteNonQuery(); AstoriaTestLog.WriteLineIgnore(String.Format("Completed Attaching Db {0}", this.DatabaseName)); } } }
/// <summary>Copies an existing file to a new file.</summary> /// <param name="sourcePath">The file to copy.</param> /// <param name="destinationPath">The name of the destination file. This cannot be a directory or an existing file.</param> private static void FileCopy(string sourcePath, string destinationPath) { Debug.Assert(sourcePath != null, "sourcePath != null"); Debug.Assert(destinationPath != null, "destinationPath != null"); AstoriaTestLog.WriteLineIgnore("Copying \"" + sourcePath + "\" to \"" + destinationPath + "\"..."); bool impersonate = true; Account account = new Account(null, null, null); //If its running local no need to either if (AstoriaTestProperties.DataProviderMachineName.ToLower().Equals("local")) { impersonate = false; } ImpersonationWrapper.DoAction(account, impersonate, delegate { File.Copy(sourcePath, destinationPath); if (CompactUtil.IsFileCompressed(destinationPath)) { AstoriaTestLog.WriteLineIgnore("Uncompressing '" + destinationPath + "'..."); CompactUtil.UncompressFile(destinationPath); } }); }
internal void InsertLanguageData(Workspace workspace, ResourceType resourceType) { fxLanguages languages = new fxLanguages(); fxLanguage language = languages.Choose(); AstoriaTestLog.TraceInfo("Language Data: " + language.GetType().Name); // do them one at a time so that if one fails, we know which using (SqlConnection sqlConn = new SqlConnection(this.MachineConnectionString)) { sqlConn.Open(); for (int i = 0; i < 5; i++) { using (SqlCommand sqlCmd = sqlConn.CreateCommand()) { sqlCmd.CommandTimeout = 0; sqlCmd.CommandText = GetInsertString(workspace, resourceType, language, TestUtil.Random); try { sqlCmd.ExecuteNonQuery(); } catch (SqlException error) { AstoriaTestLog.WriteLineIgnore("Error while executing: " + sqlCmd.CommandText); throw; } } } } }
public void Delete() { AstoriaTestLog.WriteLineIgnore("-------Delete WebdataService ---------"); AstoriaTestLog.WriteLineIgnore("------- URI: {0}---------", this.ServiceUri); string args = String.Format("{0} {1}", Path.Combine(DestinationFolder_Local, "..\\DeleteVDir.vbs"), this.WebDataServiceName); RunProcess("cscript", args); }
public void Restore() { AstoriaTestLog.WriteLineIgnore("-------Restoring Database ---------"); AstoriaTestLog.WriteLineIgnore("------- DatabaseConnectionString: {0}---------", this.DatabaseConnectionString); if (IsEmpty) { CreateEmptyDatabase(); } else { AttachDatabase(); } }
private void CreateDatabase() { AstoriaTestLog.WriteLineIgnore("-------Create Database ---------"); AstoriaTestLog.WriteLineIgnore("------- DataLayerProviderMachineName: {0}---------", this.Machine); AstoriaTestLog.WriteLineIgnore("------- MachineConnectionString: {0}---------", this.MachineConnectionString); AstoriaTestLog.WriteLineIgnore("------- DatabaseName: {0}---------", this.DatabaseName); AstoriaTestLog.WriteLineIgnore("------- DatabaseConnectionString: {0}---------", this.DatabaseConnectionString); if (IsEmpty) { CreateEmptyDatabase(); } else { AttachDatabase(); } }
/// <summary> /// Runs the specifed application with the given arguments on the Machine /// for this service. /// </summary> /// <param name="appString">Application to run.</param> /// <param name="argString">Argument to application.</param> private void RunProcess(string appString, string argString) { if (ShouldWorkaroundDueToVistaUAC()) { Process[] processes = Process.GetProcessesByName("Commander.Server"); if (processes.Length > 0) { ProcessHelper.UseCommander(Environment.MachineName, delegate(Commander.RemoteServer remoteServer) { Commander.RemoteExecutableResults results = remoteServer.ExecuteScript(argString); if (results.ExitCode != 0) { throw new TestFailedException("Unable to run create website script:\n" + results.Output); } AstoriaTestLog.TraceLine(results.Output); }); } else { throw new TestFailedException("Expected a RemoteServer program called Commander.Server.exe to be running"); } } else if (ProcessHelper.IsLocalMachine(this.MachineName)) { // Run locally. ProcessStartInfo processStart = new ProcessStartInfo(appString, argString); processStart.UseShellExecute = false; processStart.CreateNoWindow = true; AstoriaTestLog.WriteLineIgnore(appString); AstoriaTestLog.WriteLineIgnore(argString); using (Process process = Process.Start(processStart)) { if (process != null) { const int timeoutMilliseconds = 20 * 1000; process.WaitForExit(timeoutMilliseconds); } } } }
private void CreateEmptyDatabase() { if (_isLocal) { EnsureLocalLoginExists(); } DropDatabase(); AstoriaTestLog.WriteLineIgnore("-------CreateEmptyDb: {0}---------", this.MachineConnectionString); using (SqlConnection sqlConn = new SqlConnection(this.MachineConnectionString)) { sqlConn.Open(); using (SqlCommand sqlCmd = sqlConn.CreateCommand()) { sqlCmd.CommandTimeout = 0; sqlCmd.CommandText = String.Format("CREATE DATABASE [{0}];", this.DatabaseName); sqlCmd.ExecuteNonQuery(); } } }
protected override void CreateWebService(bool verify) { try { if (AstoriaTestProperties.Host == Host.LocalIIS) { DestinationFolder = Path.Combine(Environment.GetEnvironmentVariable("SystemDrive") + @"\inetpub\wwwroot", this.WebDataServiceName); DestinationFolder_Local = DestinationFolder; } SourceFolder = Path.Combine(Path.Combine(Environment.CurrentDirectory, databaseFolder), this.WebDataServicePrefixName); SourceFolder = Path.Combine(SourceFolder, "DataService"); string sWindowsAuth = ""; string sAnonymousAuth = ""; AstoriaTestLog.WriteLineIgnore("Creating IIS webservice on: " + this.MachineName); this.CopySourceFolderToHost(); DeployWebConfig(); // if not full trust, then compiler options aren't allowed, so we need to add #defines to each file manually if (AstoriaTestProperties.ServiceTrustLevel != TrustLevel.Full) { List <string> toDefine = new List <string>() { Workspace.DataLayerProviderKind.ToString() }; if (!Versioning.Server.SupportsV2Features) { toDefine.Add("ASTORIA_PRE_V2"); } string defines = string.Join(Environment.NewLine, toDefine.Select(d => "#define " + d).ToArray()); foreach (string path in Directory.GetFiles(DestinationFolder, "*.cs", SearchOption.AllDirectories)) { string fileContent = File.ReadAllText(path); fileContent = defines + Environment.NewLine + fileContent; File.WriteAllText(path, fileContent); } } Assembly resourceAssembly = this.GetType().Assembly; IOUtil.FindAndWriteResourceToFile(resourceAssembly, Path.Combine(DestinationFolder, "CreateVDir.vbs")); IOUtil.FindAndWriteResourceToFile(resourceAssembly, Path.Combine(DestinationFolder, "..\\DeleteVDir.vbs")); if (AstoriaTestProperties.HostAuthenicationMethod == "Windows") { sWindowsAuth = "True"; sAnonymousAuth = "False"; } else if (AstoriaTestProperties.HostAuthenicationMethod == "None") { sWindowsAuth = "False"; sAnonymousAuth = "True"; } string args = String.Format("{0} {1} {2} {3} {4}", Path.Combine(DestinationFolder_Local, "CreateVDir.vbs"), this.WebDataServiceName, DestinationFolder_Local, sAnonymousAuth, sWindowsAuth); RunProcess("cscript", args); Thread.Sleep(2000); // set up service uris if (AstoriaTestProperties.TransportSecurityMode.Equals("transport", StringComparison.InvariantCultureIgnoreCase)) { ServiceRootUri = Uri.UriSchemeHttps + "://" + this.MachineName + "/" + this.WebDataServiceName + "/"; } else { ServiceRootUri = Uri.UriSchemeHttp + "://" + this.MachineName + "/" + this.WebDataServiceName + "/"; } ServiceUri = ServiceRootUri + Workspace.WebServiceFileName; if (AstoriaTestProperties.UseDomainServices) { ServiceUri = ServiceUri + "/dataservice/"; AstoriaTestLog.WriteLineIgnore("OData Endpoint is at : " + ServiceUri); } if (verify) { VerifyService(); } } catch (Exception e) { if (AstoriaTestProperties.Host == Host.LocalIIS) { throw new TestFailedException("Could not create IIS web service on local host", null, null, e); } } }
/// <summary>Create a populated database.</summary> private void CreatePopulatedDatabase() { if (_isLocal) { EnsureLocalLoginExists(); } DropDatabase(); AstoriaTestLog.WriteLineIgnore("-------CreatePopulatedDb: {0}---------", this.MachineConnectionString); using (SqlConnection sqlConn = new SqlConnection(this.MachineConnectionString)) { sqlConn.Open(); using (SqlCommand sqlCmd = sqlConn.CreateCommand()) { sqlCmd.CommandTimeout = 0; sqlCmd.CommandText = String.Format( "CREATE DATABASE [{0}]\n" + " CONTAINMENT = NONE\n" + " ON PRIMARY\n" + "(NAME = N'{0}', FILENAME = N'{1}', SIZE = 4288KB, MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB)\n" + " LOG ON\n" + "(NAME = N'{0}_log', FILENAME = N'{2}', SIZE = 3456KB, MAXSIZE = 2048GB, FILEGROWTH = 10 %)", this.DatabaseName, this.AttachedMdf, this.AttachedLdf); sqlCmd.ExecuteNonQuery(); } // Note: SSMS will create a file that ends with GO\n. The code // below expects that and won't execute an SQL fragment unless it is // followed by GO\n. String filePath = FindDatabaseFile(this.DatabasePrefixName + ".sql"); using (StreamReader reader = new StreamReader(filePath)) using (SqlCommand sqlCmd = sqlConn.CreateCommand()) { // Read from the file until it is empty. StringBuilder sqlStatements = new StringBuilder(); String fileLine = reader.ReadLine(); while (fileLine != null) { // If we find a "GO", execute everything we received up // to this point and ignore the "GO". if (fileLine == "GO") { if (sqlStatements.Length > 0) { // Get command and clean buffer. String sqlStatement = sqlStatements.ToString(); sqlStatements.Clear(); // Replace database name if needed. if (sqlStatement.Contains("{0}")) { sqlStatement = String.Format(sqlStatement, this.DatabaseName); } // Execute. sqlCmd.CommandText = sqlStatement; sqlCmd.CommandTimeout = 0; sqlCmd.ExecuteNonQuery(); } } else if (!String.IsNullOrEmpty(fileLine)) { // Buffer all statements up until "GO". sqlStatements.AppendLine(fileLine); } fileLine = reader.ReadLine(); } } AstoriaTestLog.WriteLineIgnore(String.Format("Completed Create Populated Db {0}", this.DatabaseName)); } }
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."); }