diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index 1ff0c42..0000000 --- a/.gitattributes +++ /dev/null @@ -1,63 +0,0 @@ -############################################################################### -# Set default behavior to automatically normalize line endings. -############################################################################### -* text=auto - -############################################################################### -# Set default behavior for command prompt diff. -# -# This is need for earlier builds of msysgit that does not have it on by -# default for csharp files. -# Note: This is only used by command line -############################################################################### -#*.cs diff=csharp - -############################################################################### -# Set the merge driver for project and solution files -# -# Merging from the command prompt will add diff markers to the files if there -# are conflicts (Merging from VS is not affected by the settings below, in VS -# the diff markers are never inserted). Diff markers may cause the following -# file extensions to fail to load in VS. An alternative would be to treat -# these files as binary and thus will always conflict and require user -# intervention with every merge. To do so, just uncomment the entries below -############################################################################### -#*.sln merge=binary -#*.csproj merge=binary -#*.vbproj merge=binary -#*.vcxproj merge=binary -#*.vcproj merge=binary -#*.dbproj merge=binary -#*.fsproj merge=binary -#*.lsproj merge=binary -#*.wixproj merge=binary -#*.modelproj merge=binary -#*.sqlproj merge=binary -#*.wwaproj merge=binary - -############################################################################### -# behavior for image files -# -# image files are treated as binary by default. -############################################################################### -#*.jpg binary -#*.png binary -#*.gif binary - -############################################################################### -# diff behavior for common document formats -# -# Convert binary document formats to text before diffing them. This feature -# is only available from the command line. Turn it on by uncommenting the -# entries below. -############################################################################### -#*.doc diff=astextplain -#*.DOC diff=astextplain -#*.docx diff=astextplain -#*.DOCX diff=astextplain -#*.dot diff=astextplain -#*.DOT diff=astextplain -#*.pdf diff=astextplain -#*.PDF diff=astextplain -#*.rtf diff=astextplain -#*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore deleted file mode 100644 index d22210f..0000000 --- a/.gitignore +++ /dev/null @@ -1,9 +0,0 @@ -################################################################################ -# This .gitignore file was automatically created by Microsoft(R) Visual Studio. -################################################################################ - -*.user -*.suo -packages/ -obj/ -bin/ \ No newline at end of file diff --git a/.gitreview b/.gitreview deleted file mode 100644 index c7779a4..0000000 --- a/.gitreview +++ /dev/null @@ -1,4 +0,0 @@ -[gerrit] -host=review.openstack.org -port=29418 -project=stackforge/openstack-sdk-dotnet.git diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index 39990e0..0000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,13 +0,0 @@ -# Release Notes - -This changelog contains the relevant feature additions and bug fixes. To obtain a complete diff between versions you can got to https://github.com/stackforge/openstack-sdk-dotnet/compare/XXX...XXX where the XXX values are two different tagged versions of the library. For example, https://github.com/stackforge/openstack-sdk-dotnet/compare/v0.9.0...v0.9.1 - -* v0.9.1 (2014-05-30) - - * Includes bug fixes for DevStack compatibility. - -* v0.9.0 (2014-05-12) - - * Initial release of the SDK. - * Includes basic support for authentication. - * Includes basic support for working with storage containers, objects and folders. \ No newline at end of file diff --git a/OpenStack/AssemblyVersionInfo.cs b/OpenStack/AssemblyVersionInfo.cs deleted file mode 100644 index 0661bcd..0000000 --- a/OpenStack/AssemblyVersionInfo.cs +++ /dev/null @@ -1,32 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// 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("0.9.1.0")] -[assembly: AssemblyFileVersion("0.9.1.0")] diff --git a/OpenStack/Build/readme.txt b/OpenStack/Build/readme.txt deleted file mode 100644 index 0c6af64..0000000 --- a/OpenStack/Build/readme.txt +++ /dev/null @@ -1 +0,0 @@ -This is where we would put things like fixcop and stylcop related stuff or any custom build targets that we would want to bring in... basically anything that is related to building the solution. diff --git a/OpenStack/Examples/CustomServiceClientExample/App.config b/OpenStack/Examples/CustomServiceClientExample/App.config deleted file mode 100644 index 8e15646..0000000 --- a/OpenStack/Examples/CustomServiceClientExample/App.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/OpenStack/Examples/CustomServiceClientExample/CustomServiceClientExample.csproj b/OpenStack/Examples/CustomServiceClientExample/CustomServiceClientExample.csproj deleted file mode 100644 index 8141156..0000000 --- a/OpenStack/Examples/CustomServiceClientExample/CustomServiceClientExample.csproj +++ /dev/null @@ -1,79 +0,0 @@ - - - - - Debug - AnyCPU - {83B16A76-A3DF-42E5-95A6-5BBE41FC7854} - Exe - Properties - CustomServiceClientExample - CustomServiceClientExample - v4.5 - 512 - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\Bin\Debug\Newtonsoft.Json.dll - - - False - ..\..\Bin\net45\Debug\OpenStack.dll - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/OpenStack/Examples/CustomServiceClientExample/EchoPocoClient.cs b/OpenStack/Examples/CustomServiceClientExample/EchoPocoClient.cs deleted file mode 100644 index a37cc62..0000000 --- a/OpenStack/Examples/CustomServiceClientExample/EchoPocoClient.cs +++ /dev/null @@ -1,41 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Threading.Tasks; -using Newtonsoft.Json.Linq; -using OpenStack.Common.ServiceLocation; - -namespace CustomServiceClientExample -{ - internal class EchoPocoClient : IEchoPocoClient - { - internal IServiceLocator ServiceLocator; - - public EchoPocoClient(IServiceLocator serviceLocator) - { - this.ServiceLocator = serviceLocator; - } - - public async Task Echo(string message) - { - var restClient = this.ServiceLocator.Locate().Create(this.ServiceLocator); - var resp = await restClient.Echo(message); - var payload = await resp.ReadContentAsStringAsync(); - var obj = JObject.Parse(payload); - return new EchoResponse((string)obj["args"]["m"], (string)obj["url"]); - } - } -} \ No newline at end of file diff --git a/OpenStack/Examples/CustomServiceClientExample/EchoPocoClientFactory.cs b/OpenStack/Examples/CustomServiceClientExample/EchoPocoClientFactory.cs deleted file mode 100644 index ff4de25..0000000 --- a/OpenStack/Examples/CustomServiceClientExample/EchoPocoClientFactory.cs +++ /dev/null @@ -1,28 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using OpenStack.Common.ServiceLocation; - -namespace CustomServiceClientExample -{ - internal class EchoPocoClientFactory : IEchoPocoClientFactory - { - public IEchoPocoClient Create(IServiceLocator serviceLocator) - { - return new EchoPocoClient(serviceLocator); - } - } -} \ No newline at end of file diff --git a/OpenStack/Examples/CustomServiceClientExample/EchoResponse.cs b/OpenStack/Examples/CustomServiceClientExample/EchoResponse.cs deleted file mode 100644 index abcf48a..0000000 --- a/OpenStack/Examples/CustomServiceClientExample/EchoResponse.cs +++ /dev/null @@ -1,31 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -namespace CustomServiceClientExample -{ - public class EchoResponse - { - public string Message { get; private set; } - - public string Url { get; private set; } - - public EchoResponse(string message, string url) - { - this.Message = message; - this.Url = url; - } - } -} diff --git a/OpenStack/Examples/CustomServiceClientExample/EchoRestClient.cs b/OpenStack/Examples/CustomServiceClientExample/EchoRestClient.cs deleted file mode 100644 index d6ec888..0000000 --- a/OpenStack/Examples/CustomServiceClientExample/EchoRestClient.cs +++ /dev/null @@ -1,45 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; -using OpenStack.Common.Http; -using OpenStack.Common.ServiceLocation; - -namespace CustomServiceClientExample -{ - internal class EchoRestClient : IEchoRestClient - { - internal const string serviceEndpoint = "http://httpbin.org/get"; - - internal IServiceLocator ServiceLocator; - - public EchoRestClient(IServiceLocator serviceLocator) - { - this.ServiceLocator = serviceLocator; - } - - public async Task Echo(string message) - { - var client = this.ServiceLocator.Locate().Create(CancellationToken.None); - client.Method = HttpMethod.Get; - client.Uri = new Uri(serviceEndpoint + "?m=" + message); - return await client.SendAsync(); - } - } -} diff --git a/OpenStack/Examples/CustomServiceClientExample/EchoRestClientFactory.cs b/OpenStack/Examples/CustomServiceClientExample/EchoRestClientFactory.cs deleted file mode 100644 index a57cfa2..0000000 --- a/OpenStack/Examples/CustomServiceClientExample/EchoRestClientFactory.cs +++ /dev/null @@ -1,28 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using OpenStack.Common.ServiceLocation; - -namespace CustomServiceClientExample -{ - internal class EchoRestClientFactory : IEchoRestClientFactory - { - public IEchoRestClient Create(IServiceLocator serviceLocator) - { - return new EchoRestClient(serviceLocator); - } - } -} \ No newline at end of file diff --git a/OpenStack/Examples/CustomServiceClientExample/EchoServiceClient.cs b/OpenStack/Examples/CustomServiceClientExample/EchoServiceClient.cs deleted file mode 100644 index 3b23c23..0000000 --- a/OpenStack/Examples/CustomServiceClientExample/EchoServiceClient.cs +++ /dev/null @@ -1,39 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Threading; -using System.Threading.Tasks; -using OpenStack.Common.ServiceLocation; -using OpenStack.Identity; - -namespace CustomServiceClientExample -{ - internal class EchoServiceClient : IEchoServiceClient - { - internal IServiceLocator ServiceLocator; - - public EchoServiceClient(ICredential credential, CancellationToken token, IServiceLocator serviceLocator) - { - this.ServiceLocator = serviceLocator; - } - - public async Task Echo(string message) - { - var pocoClient = this.ServiceLocator.Locate().Create(this.ServiceLocator); - return await pocoClient.Echo(message); - } - } -} \ No newline at end of file diff --git a/OpenStack/Examples/CustomServiceClientExample/EchoServiceClientDefinition.cs b/OpenStack/Examples/CustomServiceClientExample/EchoServiceClientDefinition.cs deleted file mode 100644 index c3a31ac..0000000 --- a/OpenStack/Examples/CustomServiceClientExample/EchoServiceClientDefinition.cs +++ /dev/null @@ -1,49 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; -using System.Threading; -using OpenStack; -using OpenStack.Common.ServiceLocation; -using OpenStack.Identity; - -namespace CustomServiceClientExample -{ - internal class EchoServiceClientDefinition : IOpenStackServiceClientDefinition - { - public string Name { get; private set; } - - public EchoServiceClientDefinition() - { - this.Name = typeof(EchoServiceClient).Name; - } - - public IOpenStackServiceClient Create(ICredential credential, string serviceName, CancellationToken cancellationToken, IServiceLocator serviceLocator) - { - return new EchoServiceClient(credential, cancellationToken, serviceLocator); - } - - public IEnumerable ListSupportedVersions() - { - return new List(); - } - - public bool IsSupported(ICredential credential, string serviceName) - { - return true; - } - } -} \ No newline at end of file diff --git a/OpenStack/Examples/CustomServiceClientExample/EchoServiceRegistrar.cs b/OpenStack/Examples/CustomServiceClientExample/EchoServiceRegistrar.cs deleted file mode 100644 index ac7a01c..0000000 --- a/OpenStack/Examples/CustomServiceClientExample/EchoServiceRegistrar.cs +++ /dev/null @@ -1,32 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using OpenStack; -using OpenStack.Common.ServiceLocation; - -namespace CustomServiceClientExample -{ - public class EchoServiceRegistrar : IServiceLocationRegistrar - { - public void Register(IServiceLocationManager manager, IServiceLocator locator) - { - manager.RegisterServiceInstance(typeof(IEchoPocoClientFactory), new EchoPocoClientFactory()); - manager.RegisterServiceInstance(typeof(IEchoRestClientFactory), new EchoRestClientFactory()); - var serviceManager = locator.Locate(); - serviceManager.RegisterServiceClient(new EchoServiceClientDefinition()); - } - } -} \ No newline at end of file diff --git a/OpenStack/Examples/CustomServiceClientExample/IEchoPocoClient.cs b/OpenStack/Examples/CustomServiceClientExample/IEchoPocoClient.cs deleted file mode 100644 index a6da5eb..0000000 --- a/OpenStack/Examples/CustomServiceClientExample/IEchoPocoClient.cs +++ /dev/null @@ -1,25 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Threading.Tasks; - -namespace CustomServiceClientExample -{ - public interface IEchoPocoClient - { - Task Echo(string message); - } -} \ No newline at end of file diff --git a/OpenStack/Examples/CustomServiceClientExample/IEchoPocoClientFactory.cs b/OpenStack/Examples/CustomServiceClientExample/IEchoPocoClientFactory.cs deleted file mode 100644 index 136f1af..0000000 --- a/OpenStack/Examples/CustomServiceClientExample/IEchoPocoClientFactory.cs +++ /dev/null @@ -1,25 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using OpenStack.Common.ServiceLocation; - -namespace CustomServiceClientExample -{ - public interface IEchoPocoClientFactory - { - IEchoPocoClient Create(IServiceLocator serviceLocator); - } -} \ No newline at end of file diff --git a/OpenStack/Examples/CustomServiceClientExample/IEchoRestClient.cs b/OpenStack/Examples/CustomServiceClientExample/IEchoRestClient.cs deleted file mode 100644 index ebe69c1..0000000 --- a/OpenStack/Examples/CustomServiceClientExample/IEchoRestClient.cs +++ /dev/null @@ -1,26 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Threading.Tasks; -using OpenStack.Common.Http; - -namespace CustomServiceClientExample -{ - public interface IEchoRestClient - { - Task Echo(string message); - } -} \ No newline at end of file diff --git a/OpenStack/Examples/CustomServiceClientExample/IEchoRestClientFactory.cs b/OpenStack/Examples/CustomServiceClientExample/IEchoRestClientFactory.cs deleted file mode 100644 index 1d83b22..0000000 --- a/OpenStack/Examples/CustomServiceClientExample/IEchoRestClientFactory.cs +++ /dev/null @@ -1,25 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using OpenStack.Common.ServiceLocation; - -namespace CustomServiceClientExample -{ - public interface IEchoRestClientFactory - { - IEchoRestClient Create(IServiceLocator serviceLocator); - } -} \ No newline at end of file diff --git a/OpenStack/Examples/CustomServiceClientExample/IEchoServiceClient.cs b/OpenStack/Examples/CustomServiceClientExample/IEchoServiceClient.cs deleted file mode 100644 index 2c9f003..0000000 --- a/OpenStack/Examples/CustomServiceClientExample/IEchoServiceClient.cs +++ /dev/null @@ -1,26 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Threading.Tasks; -using OpenStack; - -namespace CustomServiceClientExample -{ - public interface IEchoServiceClient : IOpenStackServiceClient - { - Task Echo(string message); - } -} \ No newline at end of file diff --git a/OpenStack/Examples/CustomServiceClientExample/Program.cs b/OpenStack/Examples/CustomServiceClientExample/Program.cs deleted file mode 100644 index 7a3a0e2..0000000 --- a/OpenStack/Examples/CustomServiceClientExample/Program.cs +++ /dev/null @@ -1,55 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Threading.Tasks; -using OpenStack; -using OpenStack.Identity; - -namespace CustomServiceClientExample -{ - class Program - { - static void Main(string[] args) - { - var authUri = new Uri("https://region.identity.host.com:12345/v2.0/tokens"); - var userName = "user name"; - var password = "password"; - var tenantId = "XXXXXXXXXXXXXX-Project"; - var echoMessage = "Hello world!"; - - Console.WriteLine("Calling remote service to echo the following message: '{0}'", echoMessage); - - var echoMessageTask = EchoMessage(echoMessage, authUri, userName, password, tenantId); - echoMessageTask.Wait(); - - Console.WriteLine("Response from remote service: '{0}'", echoMessageTask.Result); - Console.ReadLine(); - } - - public static async Task EchoMessage(string message, Uri authUri, string userName, string password, string tenantId) - { - var credential = new OpenStackCredential(authUri, userName, password, tenantId); - var client = OpenStackClientFactory.CreateClient(credential); - - await client.Connect(); - - var echoServiceClient = client.CreateServiceClient(); - var resp = await echoServiceClient.Echo(message); - return resp.Message; - } - } -} \ No newline at end of file diff --git a/OpenStack/Examples/CustomServiceClientExample/Properties/AssemblyInfo.cs b/OpenStack/Examples/CustomServiceClientExample/Properties/AssemblyInfo.cs deleted file mode 100644 index cba98de..0000000 --- a/OpenStack/Examples/CustomServiceClientExample/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -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("CustomServiceClientExample")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("CustomServiceClientExample")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2014")] -[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("4cc5544b-fdb5-43ef-8108-9ed8e995d114")] - -// 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")] diff --git a/OpenStack/Examples/Examples.sln b/OpenStack/Examples/Examples.sln deleted file mode 100644 index 0f4cf55..0000000 --- a/OpenStack/Examples/Examples.sln +++ /dev/null @@ -1,28 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0.30110.0 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleStorageExample", "SimpleStorageExample\SimpleStorageExample.csproj", "{A8BB096A-9E6F-4D84-B091-F1FCF4DDCBDC}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CustomServiceClientExample", "CustomServiceClientExample\CustomServiceClientExample.csproj", "{83B16A76-A3DF-42E5-95A6-5BBE41FC7854}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {A8BB096A-9E6F-4D84-B091-F1FCF4DDCBDC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A8BB096A-9E6F-4D84-B091-F1FCF4DDCBDC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A8BB096A-9E6F-4D84-B091-F1FCF4DDCBDC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A8BB096A-9E6F-4D84-B091-F1FCF4DDCBDC}.Release|Any CPU.Build.0 = Release|Any CPU - {83B16A76-A3DF-42E5-95A6-5BBE41FC7854}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {83B16A76-A3DF-42E5-95A6-5BBE41FC7854}.Debug|Any CPU.Build.0 = Debug|Any CPU - {83B16A76-A3DF-42E5-95A6-5BBE41FC7854}.Release|Any CPU.ActiveCfg = Release|Any CPU - {83B16A76-A3DF-42E5-95A6-5BBE41FC7854}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/OpenStack/Examples/SimpleStorageExample/App.config b/OpenStack/Examples/SimpleStorageExample/App.config deleted file mode 100644 index 8e15646..0000000 --- a/OpenStack/Examples/SimpleStorageExample/App.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/OpenStack/Examples/SimpleStorageExample/Program.cs b/OpenStack/Examples/SimpleStorageExample/Program.cs deleted file mode 100644 index 8e2e7cf..0000000 --- a/OpenStack/Examples/SimpleStorageExample/Program.cs +++ /dev/null @@ -1,71 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using OpenStack; -using OpenStack.Identity; -using OpenStack.Storage; - -namespace SimpleStorageExample -{ - class Program - { - static void Main(string[] args) - { - //enter your user name, password, tenant Id, and the authorization endpoint - //for the instance of OpenStack that you want to connect to. - var authUri = new Uri("https://region.identity.host.com:12345/v2.0/tokens"); - var userName = "user name"; - var password = "password"; - var tenantId = "tenant Id"; // e.g. XXXXXXXXXXXXX-Project - - //Construct an OpenStackCredential object that will be used to authenticate. - //The credential will also be useful later as it contains a reference to the service catalog, and access token. - var credential = new OpenStackCredential(authUri, userName, password, tenantId); - - //Create a new OpenStackClient object using the credentials you just created. - var client = OpenStackClientFactory.CreateClient(credential); - - //Connect the client to OpenStack. This will authenticate you, as well as construct the service catalog, - //and retrieve the access token that will be used in future calls to OpenStack services. - var connectTask = client.Connect(); - - //Console applications can't do async, so we need to wait on the task, - //in other contexts you can use the wait keyword. - connectTask.Wait(); - - //Once the OpenStackClient has been connected, you can request a service client from it. - //The service client will be created with the credentials that you have already specified, - //and do not need any additional information for you to interact with them. - var storageClient = client.CreateServiceClient(); - - //Once we have the storage service client, we can ask it for the details of the current storage account. - var getAccountTask = storageClient.GetStorageAccount(); - getAccountTask.Wait(); - var account = getAccountTask.Result; - - //Here we will write out the name of the account, and print out the names of each storage container in the account. - Console.WriteLine("Connected to storage account '{0}'", account.Name); - Console.WriteLine("Storage account '{0}' has the following containers:", account.Name); - foreach (var container in account.Containers) - { - Console.WriteLine("\t{0}",container.Name); - } - Console.WriteLine(string.Empty); - Console.ReadLine(); - } - } -} diff --git a/OpenStack/Examples/SimpleStorageExample/Properties/AssemblyInfo.cs b/OpenStack/Examples/SimpleStorageExample/Properties/AssemblyInfo.cs deleted file mode 100644 index 6f198e8..0000000 --- a/OpenStack/Examples/SimpleStorageExample/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -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("SimpleStorageExample")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("SimpleStorageExample")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2014")] -[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("095db9ea-9103-4a27-b7ec-e91bd1e0817c")] - -// 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")] diff --git a/OpenStack/Examples/SimpleStorageExample/SimpleStorageExample.csproj b/OpenStack/Examples/SimpleStorageExample/SimpleStorageExample.csproj deleted file mode 100644 index eeca3fa..0000000 --- a/OpenStack/Examples/SimpleStorageExample/SimpleStorageExample.csproj +++ /dev/null @@ -1,65 +0,0 @@ - - - - - Debug - AnyCPU - {A8BB096A-9E6F-4D84-B091-F1FCF4DDCBDC} - Exe - Properties - SimpleStorageExample - SimpleStorageExample - v4.5 - 512 - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\Bin\net45\Debug\Newtonsoft.Json.dll - - - False - ..\..\Bin\net45\Debug\OpenStack.dll - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/OpenStack/Externals/readme.txt b/OpenStack/Externals/readme.txt deleted file mode 100644 index 42d9446..0000000 --- a/OpenStack/Externals/readme.txt +++ /dev/null @@ -1 +0,0 @@ -This is a folder to bring in any non-NuGet external dependencies... \ No newline at end of file diff --git a/OpenStack/OpenStack.Test/Compute/ComputeFlavorPayloadConverterTests.cs b/OpenStack/OpenStack.Test/Compute/ComputeFlavorPayloadConverterTests.cs deleted file mode 100644 index 5b74cfd..0000000 --- a/OpenStack/OpenStack.Test/Compute/ComputeFlavorPayloadConverterTests.cs +++ /dev/null @@ -1,383 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Compute; - -namespace OpenStack.Test.Compute -{ - [TestClass] - public class ComputeFlavorPayloadConverterTests - { - internal string CreateFlavorJsonFixtrue(string name, string id, string ram, string disk, string vcpus, - string permaUri, string publicUri) - { - var ComputeFlavorJsonResponseFixture = @"{{ - ""flavor"" : {{ - ""name"": ""{0}"", - ""links"": [ - {{ - ""href"": ""{1}"", - ""rel"": ""self"" - }}, - {{ - ""href"": ""{2}"", - ""rel"": ""bookmark"" - }} - ], - ""ram"": {3}, - ""vcpus"": {4}, - ""disk"": {5}, - ""id"": ""{6}"" - }} - }}"; - - return string.Format(ComputeFlavorJsonResponseFixture, name, publicUri, permaUri, ram, vcpus, disk, id); - } - - internal string CreateFlavorSummaryJsonFixtrue(string name, string id, string permaUri, string publicUri) - { - var computeFlavorSummaryJsonResponseFixture = @"{{ - ""id"": ""{0}"", - ""links"": [ - {{ - ""href"": ""{1}"", - ""rel"": ""self"" - }}, - {{ - ""href"": ""{2}"", - ""rel"": ""bookmark"" - }} - ], - ""name"": ""{3}"" - }}"; - - return string.Format(computeFlavorSummaryJsonResponseFixture, id, publicUri, permaUri, name); - } - - [TestMethod] - public void CanConvertJsonPayloadToFlavor() - { - var flavorName = "m1.tiny"; - var flavorId = "1"; - var flavorPublicUri = "http://www.server.com/v2/flavors/1"; - var flavorPermUri = "http://www.server.com/flavors/1"; - var flavorRam = "512"; - var flavorDisk = "10"; - var flavorVcpus = "2"; - - var computeFlavorJsonResponseFixture = CreateFlavorJsonFixtrue(flavorName, flavorId, flavorRam, flavorDisk, - flavorVcpus, flavorPermUri, flavorPublicUri); - - var converter = new ComputeFlavorPayloadConverter(); - var flavor = converter.ConvertFlavor(computeFlavorJsonResponseFixture); - Assert.IsNotNull(flavor); - Assert.AreEqual(flavorName, flavor.Name); - Assert.AreEqual(flavorId, flavor.Id); - Assert.AreEqual(flavorRam, flavor.Ram); - Assert.AreEqual(flavorVcpus, flavor.Vcpus); - Assert.AreEqual(flavorDisk, flavor.Disk); - Assert.AreEqual(new Uri(flavorPermUri), flavor.PermanentUri); - Assert.AreEqual(new Uri(flavorPublicUri), flavor.PublicUri); - } - - [TestMethod] - public void CanConvertJsonPayloadMissingRamToFlavor() - { - var missingFixture = @"{ - ""flavor"": { - ""name"": ""m1.tiny"", - ""id"": ""1"", - ""links"": [ - { - ""href"": ""http://someuri.com/v2/flavors/1"", - ""rel"": ""self"" - }, - { - ""href"": ""http://someuri.com/flavors/1"", - ""rel"": ""bookmark"" - } - ], - ""vcpus"": 2, - ""disk"": 10 - } - }"; - - var converter = new ComputeFlavorPayloadConverter(); - var flavor = converter.ConvertFlavor(missingFixture); - Assert.IsNotNull(flavor); - Assert.AreEqual("m1.tiny", flavor.Name); - Assert.AreEqual("1", flavor.Id); - Assert.AreEqual("2", flavor.Vcpus); - Assert.AreEqual("10", flavor.Disk); - Assert.AreEqual(new Uri("http://someuri.com/flavors/1"), flavor.PermanentUri); - Assert.AreEqual(new Uri("http://someuri.com/v2/flavors/1"), flavor.PublicUri); - } - - [TestMethod] - public void CanConvertJsonPayloadMissingVcpusToFlavor() - { - var missingFixture = @"{ - ""flavor"": { - ""name"": ""m1.tiny"", - ""id"": ""1"", - ""links"": [ - { - ""href"": ""http://someuri.com/v2/flavors/1"", - ""rel"": ""self"" - }, - { - ""href"": ""http://someuri.com/flavors/1"", - ""rel"": ""bookmark"" - } - ], - ""ram"": 512, - ""disk"": 10 - } - }"; - - var converter = new ComputeFlavorPayloadConverter(); - var flavor = converter.ConvertFlavor(missingFixture); - Assert.IsNotNull(flavor); - Assert.AreEqual("m1.tiny", flavor.Name); - Assert.AreEqual("1", flavor.Id); - Assert.AreEqual("512", flavor.Ram); - Assert.AreEqual("10", flavor.Disk); - Assert.AreEqual(new Uri("http://someuri.com/flavors/1"), flavor.PermanentUri); - Assert.AreEqual(new Uri("http://someuri.com/v2/flavors/1"), flavor.PublicUri); - } - - [TestMethod] - public void CanConvertJsonPayloadMissingDiskToFlavor() - { - var missingFixture = @"{ - ""flavor"": { - ""name"": ""m1.tiny"", - ""id"": ""1"", - ""links"": [ - { - ""href"": ""http://someuri.com/v2/flavors/1"", - ""rel"": ""self"" - }, - { - ""href"": ""http://someuri.com/flavors/1"", - ""rel"": ""bookmark"" - } - ], - ""ram"": 512, - ""vcpus"": 2 - } - }"; - - var converter = new ComputeFlavorPayloadConverter(); - var flavor = converter.ConvertFlavor(missingFixture); - Assert.IsNotNull(flavor); - Assert.AreEqual("m1.tiny", flavor.Name); - Assert.AreEqual("1", flavor.Id); - Assert.AreEqual("512", flavor.Ram); - Assert.AreEqual("2", flavor.Vcpus); - Assert.AreEqual(new Uri("http://someuri.com/flavors/1"), flavor.PermanentUri); - Assert.AreEqual(new Uri("http://someuri.com/v2/flavors/1"), flavor.PublicUri); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertJsonPayloadMissingIdToFlavor() - { - var missingIdFixture = @"{ - ""flavor"" : { - ""name"": ""m1.tiny"", - ""links"": [ - { - ""href"": ""http://someuri.com/v2/flavors/1"", - ""rel"": ""self"" - }, - { - ""href"": ""http://someuri.com/flavors/1"", - ""rel"": ""bookmark"" - } - ], - ""ram"": 512, - ""vcpus"": 2, - ""disk"": 10 - } - }"; - - var converter = new ComputeFlavorPayloadConverter(); - converter.ConvertFlavor(missingIdFixture); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertJsonPayloadMissingNameToFlavor() - { - var missingTokenFixture = @"{ - ""flavor"": { - ""name"" : ""m1.tiny"", - ""links"": [ - { - ""href"": ""http://someuri.com/v2/flavors/1"", - ""rel"": ""self"" - }, - { - ""href"": ""http://someuri.com/flavors/1"", - ""rel"": ""bookmark"" - } - ], - ""ram"": 512, - ""vcpus"": 2, - ""disk"": 10 - } - }"; - - var converter = new ComputeFlavorPayloadConverter(); - converter.ConvertFlavor(missingTokenFixture); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertJsonPayloadEmptyObjectToFlavor() - { - var emptyObjectFixture = @"{ }"; - - var converter = new ComputeFlavorPayloadConverter(); - converter.ConvertFlavor(emptyObjectFixture); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertInvalidJsonToFlavor() - { - var badJsonFixture = @"{ NOT JSON"; - - var converter = new ComputeFlavorPayloadConverter(); - converter.ConvertFlavor(badJsonFixture); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertNonObjectJsonToFlavor() - { - var nonObjectJson = @"[]"; - - var converter = new ComputeFlavorPayloadConverter(); - converter.ConvertFlavor(nonObjectJson); - } - - [TestMethod] - public void CanParseValidFlavorsJsonPayloadWithMultipleFlavors() - { - var validMultipleFlavorsJsonFixture = @"{{ ""flavors"": [ {0} ] }}"; - var firstFlavor = CreateFlavorSummaryJsonFixtrue("m1.tiny", "1", "http://server.com/flavors/1", - "http://server.com/v2/flavors/1"); - var secondFlavor = CreateFlavorSummaryJsonFixtrue("m1.small", "2", "http://server.com/flavors/2", - "http://server.com/v2/flavors/2"); - - var validMultipleFlavorsJson = string.Format(validMultipleFlavorsJsonFixture, - string.Join(",", new List() {firstFlavor, secondFlavor})); - - var converter = new ComputeFlavorPayloadConverter(); - var flavors = converter.ConvertFlavors(validMultipleFlavorsJson).ToList(); - - Assert.AreEqual(2, flavors.Count()); - var flv1 = - flavors.First(o => string.Equals(o.Name, "m1.tiny", StringComparison.InvariantCultureIgnoreCase)); - var flv2 = - flavors.First(o => string.Equals(o.Name, "m1.small", StringComparison.InvariantCultureIgnoreCase)); - Assert.IsNotNull(flv1); - Assert.IsNotNull(flv2); - - Assert.AreEqual("1", flv1.Id); - Assert.AreEqual(new Uri("http://server.com/flavors/1"), flv1.PermanentUri); - Assert.AreEqual(new Uri("http://server.com/v2/flavors/1"), flv1.PublicUri); - - Assert.AreEqual("2", flv2.Id); - Assert.AreEqual(new Uri("http://server.com/flavors/2"), flv2.PermanentUri); - Assert.AreEqual(new Uri("http://server.com/v2/flavors/2"), flv2.PublicUri); - } - - [TestMethod] - public void CanConvertValidFlavorsJsonPayloadWithSingleFlavor() - { - var validFlavorsJsonFixture = @"{{ ""flavors"": [ {0} ] }}"; - var firstFlavor = CreateFlavorSummaryJsonFixtrue("m1.tiny", "1", "http://server.com/flavors/1", - "http://server.com/v2/flavors/1"); - var validMultipleFlavorsJson = string.Format(validFlavorsJsonFixture, firstFlavor); - - var converter = new ComputeFlavorPayloadConverter(); - var flavors = converter.ConvertFlavors(validMultipleFlavorsJson).ToList(); - - Assert.AreEqual(1, flavors.Count()); - var flv1 = - flavors.First(o => string.Equals(o.Name, "m1.tiny", StringComparison.InvariantCultureIgnoreCase)); - - Assert.IsNotNull(flv1); - - Assert.AreEqual("1", flv1.Id); - Assert.AreEqual(new Uri("http://server.com/flavors/1"), flv1.PermanentUri); - Assert.AreEqual(new Uri("http://server.com/v2/flavors/1"), flv1.PublicUri); - } - - [TestMethod] - public void CanParseValidFlavorsPayloadWithEmptyJsonArray() - { - var emptyJsonArray = @"{ ""flavors"": [ ] }"; - - var converter = new ComputeFlavorPayloadConverter(); - var containers = converter.ConvertFlavors(emptyJsonArray).ToList(); - - Assert.AreEqual(0, containers.Count()); - } - - [TestMethod] - public void CanParseAnEmptyFlavorsPayload() - { - var payload = string.Empty; - - var converter = new ComputeFlavorPayloadConverter(); - var containers = converter.ConvertFlavors(payload).ToList(); - - Assert.AreEqual(0, containers.Count()); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotParseANullFlavorsPayload() - { - var converter = new ComputeFlavorPayloadConverter(); - converter.ConvertFlavors(null); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseInvalidFlavorsJsonPayload() - { - var converter = new ComputeFlavorPayloadConverter(); - converter.ConvertFlavors("[ { \"SomeAtrib\" }]"); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseInvalidFlavorsPayload() - { - var converter = new ComputeFlavorPayloadConverter(); - converter.ConvertFlavors("NOT JSON"); - } - } -} diff --git a/OpenStack/OpenStack.Test/Compute/ComputeImagePayloadConverterTests.cs b/OpenStack/OpenStack.Test/Compute/ComputeImagePayloadConverterTests.cs deleted file mode 100644 index 73c781c..0000000 --- a/OpenStack/OpenStack.Test/Compute/ComputeImagePayloadConverterTests.cs +++ /dev/null @@ -1,640 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Compute; - -namespace OpenStack.Test.Compute -{ - [TestClass] - public class ComputeImagePayloadConverterTests - { - internal string CreateImageJsonFixtrue(string name, string id, string permaUri, string publicUri, string status, string minDisk, string minRam, string progress, string created, string updated) - { - var ComputeFlavorJsonResponseFixture = @"{{ - ""image"" : {{ - ""name"": ""{0}"", - ""status"": ""{1}"", - ""updated"": ""{2}"", - ""created"": ""{3}"", - ""minDisk"": {4}, - ""progress"": {5}, - ""minRam"": {6}, - ""links"": [ - {{ - ""href"": ""{7}"", - ""rel"": ""self"" - }}, - {{ - ""href"": ""{8}"", - ""rel"": ""bookmark"" - }} - ], - ""metadata"": {{ - ""kernel_id"": ""nokernel"", - ""ramdisk_id"": ""98765"" - }}, - ""id"": ""{9}"" - }} - }}"; - - return string.Format(ComputeFlavorJsonResponseFixture, name, status, updated, created, minDisk, progress, minRam, publicUri, permaUri, id); - } - - internal string CreateImageSummaryJsonFixtrue(string name, string id, string permaUri, string publicUri) - { - var computeImageSummaryJsonResponseFixture = @"{{ - ""id"": ""{0}"", - ""links"": [ - {{ - ""href"": ""{1}"", - ""rel"": ""self"" - }}, - {{ - ""href"": ""{2}"", - ""rel"": ""bookmark"" - }} - ], - ""name"": ""{3}"" - }}"; - - return string.Format(computeImageSummaryJsonResponseFixture, id, publicUri, permaUri, name); - } - - [TestMethod] - public void CanConvertJsonPayloadToImage() - { - var imageName = "myimage"; - var imageId = "12345"; - var imagePublicUri = "http://www.server.com/v2/images/12345"; - var imagePermUri = "http://www.server.com/images/12345"; - var minRam = 512; - var minDisk = 10; - var progress = 100; - var status = "ACTIVE"; - - var lastUpdate = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(10)); - var createdDate = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(100)); - var created = createdDate.ToLongTimeString(); - var updated = lastUpdate.ToLongTimeString(); - - var computeFlavorJsonResponseFixture = CreateImageJsonFixtrue(imageName, imageId, imagePermUri, imagePublicUri, - status, minDisk.ToString(), minRam.ToString(), progress.ToString(), created,updated); - - var converter = new ComputeImagePayloadConverter(); - var image = converter.ConvertImage(computeFlavorJsonResponseFixture); - Assert.IsNotNull(image); - Assert.AreEqual(imageName, image.Name); - Assert.AreEqual(imageId, image.Id); - Assert.AreEqual(minRam, image.MinimumRamSize); - Assert.AreEqual(progress, image.UploadProgress); - Assert.AreEqual(minDisk, image.MinimumDiskSize); - Assert.AreEqual(status, image.Status); - Assert.AreEqual(lastUpdate.ToLongTimeString(), image.LastUpdated.ToLongTimeString()); - Assert.AreEqual(createdDate.ToLongTimeString(), image.CreateDate.ToLongTimeString()); - Assert.AreEqual(new Uri(imagePermUri), image.PermanentUri); - Assert.AreEqual(new Uri(imagePublicUri), image.PublicUri); - Assert.AreEqual(2, image.Metadata.Count); - Assert.AreEqual("nokernel",image.Metadata["kernel_id"]); - Assert.AreEqual("98765",image.Metadata["ramdisk_id"]); - } - - [TestMethod] - public void CanConvertJsonPayloadMissingMinRamToImage() - { - var created = DateTime.Parse("2014-05-30T16:56:32Z").ToUniversalTime(); - var updated = DateTime.Parse("2014-06-30T16:56:32Z").ToUniversalTime(); - var missingFixture = @"{ - ""image"" : { - ""name"": ""image1"", - ""status"": ""ACTIVE"", - ""updated"": ""2014-06-30T16:56:32Z"", - ""created"": ""2014-05-30T16:56:32Z"", - ""minDisk"": 10, - ""progress"": 100, - ""links"": [ - { - ""href"": ""http://someuri.com/v2/images/12345"", - ""rel"": ""self"" - }, - { - ""href"": ""http://someuri.com/images/12345"", - ""rel"": ""bookmark"" - } - ], - ""id"": ""12345"" - } - }"; - - var converter = new ComputeImagePayloadConverter(); - var image = converter.ConvertImage(missingFixture); - Assert.IsNotNull(image); - Assert.AreEqual("image1", image.Name); - Assert.AreEqual("ACTIVE", image.Status); - Assert.AreEqual("12345", image.Id); - Assert.AreEqual(0, image.MinimumRamSize); - Assert.AreEqual(10, image.MinimumDiskSize); - Assert.AreEqual(100, image.UploadProgress); - Assert.AreEqual(created.ToLongTimeString(), image.CreateDate.ToLongTimeString()); - Assert.AreEqual(updated.ToLongTimeString(), image.LastUpdated.ToLongTimeString()); - Assert.AreEqual(new Uri("http://someuri.com/images/12345"), image.PermanentUri); - Assert.AreEqual(new Uri("http://someuri.com/v2/images/12345"), image.PublicUri); - } - - public void CanConvertJsonPayloadMissingMetadataToImage() - { - var created = DateTime.Parse("2014-05-30T16:56:32Z").ToUniversalTime(); - var updated = DateTime.Parse("2014-06-30T16:56:32Z").ToUniversalTime(); - var missingFixture = @"{ - ""image"" : { - ""name"": ""image1"", - ""status"": ""ACTIVE"", - ""updated"": ""2014-06-30T16:56:32Z"", - ""created"": ""2014-05-30T16:56:32Z"", - ""minDisk"": 10, - ""minRam"": 512, - ""progress"": 100, - ""links"": [ - { - ""href"": ""http://someuri.com/v2/images/12345"", - ""rel"": ""self"" - }, - { - ""href"": ""http://someuri.com/images/12345"", - ""rel"": ""bookmark"" - } - ], - ""id"": ""12345"" - } - }"; - - var converter = new ComputeImagePayloadConverter(); - var image = converter.ConvertImage(missingFixture); - Assert.IsNotNull(image); - Assert.AreEqual("image1", image.Name); - Assert.AreEqual("ACTIVE", image.Status); - Assert.AreEqual("12345", image.Id); - Assert.AreEqual(512, image.MinimumRamSize); - Assert.AreEqual(10, image.MinimumDiskSize); - Assert.AreEqual(100, image.UploadProgress); - Assert.AreEqual(created.ToLongTimeString(), image.CreateDate.ToLongTimeString()); - Assert.AreEqual(updated.ToLongTimeString(), image.LastUpdated.ToLongTimeString()); - Assert.AreEqual(new Uri("http://someuri.com/images/12345"), image.PermanentUri); - Assert.AreEqual(new Uri("http://someuri.com/v2/images/12345"), image.PublicUri); - Assert.AreEqual(0, image.Metadata.Count); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertJsonPayloadWithBadMetadataToImage() - { - var created = DateTime.Parse("2014-05-30T16:56:32Z").ToUniversalTime(); - var updated = DateTime.Parse("2014-06-30T16:56:32Z").ToUniversalTime(); - var missingFixture = @"{ - ""image"" : { - ""name"": ""image1"", - ""status"": ""ACTIVE"", - ""updated"": ""2014-06-30T16:56:32Z"", - ""created"": ""2014-05-30T16:56:32Z"", - ""minDisk"": 10, - ""minRam"": 512, - ""progress"": 100, - ""links"": [ - { - ""href"": ""http://someuri.com/v2/images/12345"", - ""rel"": ""self"" - }, - { - ""href"": ""http://someuri.com/images/12345"", - ""rel"": ""bookmark"" - } - ], - ""metadata"": { - ""kernel_id"": { ""NotExpectyed"" : ""SomeBadValue"" }, - ""ramdisk_id"": ""98765"" - }, - ""id"": ""12345"" - } - }"; - - var converter = new ComputeImagePayloadConverter(); - converter.ConvertImage(missingFixture); - } - - [TestMethod] - public void CanConvertJsonPayloadMissingMinDiskToImage() - { - var created = DateTime.Parse("2014-05-30T16:56:32Z").ToUniversalTime(); - var updated = DateTime.Parse("2014-06-30T16:56:32Z").ToUniversalTime(); - var missingFixture = @"{ - ""image"" : { - ""name"": ""image1"", - ""status"": ""ACTIVE"", - ""updated"": ""2014-06-30T16:56:32Z"", - ""created"": ""2014-05-30T16:56:32Z"", - ""progress"": 100, - ""minRam"": 512, - ""links"": [ - { - ""href"": ""http://someuri.com/v2/images/12345"", - ""rel"": ""self"" - }, - { - ""href"": ""http://someuri.com/images/12345"", - ""rel"": ""bookmark"" - } - ], - ""id"": ""12345"" - } - }"; - - var converter = new ComputeImagePayloadConverter(); - var image = converter.ConvertImage(missingFixture); - Assert.IsNotNull(image); - Assert.AreEqual("image1", image.Name); - Assert.AreEqual("ACTIVE", image.Status); - Assert.AreEqual("12345", image.Id); - Assert.AreEqual(512, image.MinimumRamSize); - Assert.AreEqual(0, image.MinimumDiskSize); - Assert.AreEqual(100, image.UploadProgress); - Assert.AreEqual(created.ToLongTimeString(), image.CreateDate.ToLongTimeString()); - Assert.AreEqual(updated.ToLongTimeString(), image.LastUpdated.ToLongTimeString()); - Assert.AreEqual(new Uri("http://someuri.com/images/12345"), image.PermanentUri); - Assert.AreEqual(new Uri("http://someuri.com/v2/images/12345"), image.PublicUri); - } - - [TestMethod] - public void CanConvertJsonPayloadMissingStatusToImage() - { - var created = DateTime.Parse("2014-05-30T16:56:32Z").ToUniversalTime(); - var updated = DateTime.Parse("2014-06-30T16:56:32Z").ToUniversalTime(); - var missingFixture = @"{ - ""image"" : { - ""name"": ""image1"", - ""updated"": ""2014-06-30T16:56:32Z"", - ""created"": ""2014-05-30T16:56:32Z"", - ""minDisk"": 10, - ""progress"": 100, - ""minRam"": 512, - ""links"": [ - { - ""href"": ""http://someuri.com/v2/images/12345"", - ""rel"": ""self"" - }, - { - ""href"": ""http://someuri.com/images/12345"", - ""rel"": ""bookmark"" - } - ], - ""id"": ""12345"" - } - }"; - - var converter = new ComputeImagePayloadConverter(); - var image = converter.ConvertImage(missingFixture); - Assert.IsNotNull(image); - Assert.AreEqual("image1", image.Name); - Assert.AreEqual(string.Empty, image.Status); - Assert.AreEqual("12345", image.Id); - Assert.AreEqual(512, image.MinimumRamSize); - Assert.AreEqual(10, image.MinimumDiskSize); - Assert.AreEqual(100, image.UploadProgress); - Assert.AreEqual(created.ToLongTimeString(), image.CreateDate.ToLongTimeString()); - Assert.AreEqual(updated.ToLongTimeString(), image.LastUpdated.ToLongTimeString()); - Assert.AreEqual(new Uri("http://someuri.com/images/12345"), image.PermanentUri); - Assert.AreEqual(new Uri("http://someuri.com/v2/images/12345"), image.PublicUri); - } - - [TestMethod] - public void CanConvertJsonPayloadMissingUpdateDateToImage() - { - var created = DateTime.Parse("2014-05-30T16:56:32Z").ToUniversalTime(); - var updated = DateTime.MinValue; - var missingFixture = @"{ - ""image"" : { - ""name"": ""image1"", - ""status"": ""ACTIVE"", - ""created"": ""2014-05-30T16:56:32Z"", - ""minDisk"": 10, - ""progress"": 100, - ""minRam"": 512, - ""links"": [ - { - ""href"": ""http://someuri.com/v2/images/12345"", - ""rel"": ""self"" - }, - { - ""href"": ""http://someuri.com/images/12345"", - ""rel"": ""bookmark"" - } - ], - ""id"": ""12345"" - } - }"; - - var converter = new ComputeImagePayloadConverter(); - var image = converter.ConvertImage(missingFixture); - Assert.IsNotNull(image); - Assert.AreEqual("image1", image.Name); - Assert.AreEqual("ACTIVE", image.Status); - Assert.AreEqual("12345", image.Id); - Assert.AreEqual(512, image.MinimumRamSize); - Assert.AreEqual(10, image.MinimumDiskSize); - Assert.AreEqual(100, image.UploadProgress); - Assert.AreEqual(created.ToLongTimeString(), image.CreateDate.ToLongTimeString()); - Assert.AreEqual(updated.ToLongTimeString(), image.LastUpdated.ToLongTimeString()); - Assert.AreEqual(new Uri("http://someuri.com/images/12345"), image.PermanentUri); - Assert.AreEqual(new Uri("http://someuri.com/v2/images/12345"), image.PublicUri); - } - - [TestMethod] - public void CanConvertJsonPayloadMissinCreatedDateToImage() - { - var created = DateTime.MinValue; - var updated = DateTime.Parse("2014-06-30T16:56:32Z").ToUniversalTime(); - var missingFixture = @"{ - ""image"" : { - ""name"": ""image1"", - ""status"": ""ACTIVE"", - ""updated"": ""2014-06-30T16:56:32Z"", - ""minDisk"": 10, - ""progress"": 100, - ""minRam"": 512, - ""links"": [ - { - ""href"": ""http://someuri.com/v2/images/12345"", - ""rel"": ""self"" - }, - { - ""href"": ""http://someuri.com/images/12345"", - ""rel"": ""bookmark"" - } - ], - ""id"": ""12345"" - } - }"; - - var converter = new ComputeImagePayloadConverter(); - var image = converter.ConvertImage(missingFixture); - Assert.IsNotNull(image); - Assert.AreEqual("image1", image.Name); - Assert.AreEqual("ACTIVE", image.Status); - Assert.AreEqual("12345", image.Id); - Assert.AreEqual(512, image.MinimumRamSize); - Assert.AreEqual(10, image.MinimumDiskSize); - Assert.AreEqual(100, image.UploadProgress); - Assert.AreEqual(created.ToLongTimeString(), image.CreateDate.ToLongTimeString()); - Assert.AreEqual(updated.ToLongTimeString(), image.LastUpdated.ToLongTimeString()); - Assert.AreEqual(new Uri("http://someuri.com/images/12345"), image.PermanentUri); - Assert.AreEqual(new Uri("http://someuri.com/v2/images/12345"), image.PublicUri); - } - - [TestMethod] - public void CanConvertJsonPayloadMissingProgressToImage() - { - var created = DateTime.Parse("2014-05-30T16:56:32Z").ToUniversalTime(); - var updated = DateTime.Parse("2014-06-30T16:56:32Z").ToUniversalTime(); - var missingFixture = @"{ - ""image"" : { - ""name"": ""image1"", - ""status"": ""ACTIVE"", - ""updated"": ""2014-06-30T16:56:32Z"", - ""created"": ""2014-05-30T16:56:32Z"", - ""minDisk"": 10, - ""minRam"": 512, - ""links"": [ - { - ""href"": ""http://someuri.com/v2/images/12345"", - ""rel"": ""self"" - }, - { - ""href"": ""http://someuri.com/images/12345"", - ""rel"": ""bookmark"" - } - ], - ""id"": ""12345"" - } - }"; - - var converter = new ComputeImagePayloadConverter(); - var image = converter.ConvertImage(missingFixture); - Assert.IsNotNull(image); - Assert.AreEqual("image1", image.Name); - Assert.AreEqual("ACTIVE", image.Status); - Assert.AreEqual("12345", image.Id); - Assert.AreEqual(512, image.MinimumRamSize); - Assert.AreEqual(10, image.MinimumDiskSize); - Assert.AreEqual(0, image.UploadProgress); - Assert.AreEqual(created, image.CreateDate); - Assert.AreEqual(updated, image.LastUpdated); - Assert.AreEqual(new Uri("http://someuri.com/images/12345"), image.PermanentUri); - Assert.AreEqual(new Uri("http://someuri.com/v2/images/12345"), image.PublicUri); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertJsonPayloadMissingIdToImage() - { - var missingFixture = @"{ - ""image"" : { - ""name"": ""image1"", - ""status"": ""ACTIVE"", - ""updated"": ""2014-06-30T16:56:32Z"", - ""created"": ""2014-05-30T16:56:32Z"", - ""minDisk"": 10, - ""progress"": 100, - ""minRam"": 512, - ""links"": [ - { - ""href"": ""http://someuri.com/v2/images/12345"", - ""rel"": ""self"" - }, - { - ""href"": ""http://someuri.com/images/12345"", - ""rel"": ""bookmark"" - } - ] - } - }"; - - var converter = new ComputeImagePayloadConverter(); - converter.ConvertImage(missingFixture); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertJsonPayloadMissingNameToImage() - { - var missingFixture = @"{ - ""image"" : { - ""status"": ""ACTIVE"", - ""updated"": ""2014-06-30T16:56:32Z"", - ""created"": ""2014-05-30T16:56:32Z"", - ""minDisk"": 10, - ""progress"": 100, - ""minRam"": 512, - ""links"": [ - { - ""href"": ""http://someuri.com/v2/images/12345"", - ""rel"": ""self"" - }, - { - ""href"": ""http://someuri.com/images/12345"", - ""rel"": ""bookmark"" - } - ], - ""id"": ""12345"" - } - }"; - - var converter = new ComputeImagePayloadConverter(); - converter.ConvertImage(missingFixture); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertJsonPayloadEmptyObjectToImage() - { - var emptyObjectFixture = @"{ }"; - - var converter = new ComputeImagePayloadConverter(); - converter.ConvertImage(emptyObjectFixture); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertInvalidJsonToImage() - { - var badJsonFixture = @"{ NOT JSON"; - - var converter = new ComputeImagePayloadConverter(); - converter.ConvertImage(badJsonFixture); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertNonObjectJsonToImage() - { - var nonObjectJson = @"[]"; - - var converter = new ComputeImagePayloadConverter(); - converter.ConvertImage(nonObjectJson); - } - - [TestMethod] - public void CanParseValidFlavorsJsonPayloadWithMultipleFlavors() - { - var validMultipleImagesJsonFixture = @"{{ ""images"": [ {0} ] }}"; - var firstImage = CreateImageSummaryJsonFixtrue("image1", "12345", "http://server.com/images/12345", - "http://server.com/v2/images/12345"); - var secondImage = CreateImageSummaryJsonFixtrue("image2", "23456", "http://server.com/images/23456", - "http://server.com/v2/images/23456"); - - var validMultipleImagesJson = string.Format(validMultipleImagesJsonFixture, - string.Join(",", new List() { firstImage, secondImage })); - - var converter = new ComputeImagePayloadConverter(); - var images = converter.ConvertImages(validMultipleImagesJson).ToList(); - - Assert.AreEqual(2, images.Count()); - var img1 = - images.First(o => string.Equals(o.Name, "image1", StringComparison.InvariantCultureIgnoreCase)); - var img2 = - images.First(o => string.Equals(o.Name, "image2", StringComparison.InvariantCultureIgnoreCase)); - Assert.IsNotNull(img1); - Assert.IsNotNull(img2); - - Assert.AreEqual("12345", img1.Id); - Assert.AreEqual(new Uri("http://server.com/images/12345"), img1.PermanentUri); - Assert.AreEqual(new Uri("http://server.com/v2/images/12345"), img1.PublicUri); - - Assert.AreEqual("23456", img2.Id); - Assert.AreEqual(new Uri("http://server.com/images/23456"), img2.PermanentUri); - Assert.AreEqual(new Uri("http://server.com/v2/images/23456"), img2.PublicUri); - } - - [TestMethod] - public void CanConvertValidFlavorsJsonPayloadWithSingleFlavor() - { - var validImagesJsonFixture = @"{{ ""images"": [ {0} ] }}"; - var firstImage = CreateImageSummaryJsonFixtrue("image1", "12345", "http://server.com/images/12345", - "http://server.com/v2/images/12345"); - var validImagesJson = string.Format(validImagesJsonFixture, firstImage); - - var converter = new ComputeImagePayloadConverter(); - var images = converter.ConvertImages(validImagesJson).ToList(); - - Assert.AreEqual(1, images.Count()); - var img1 = - images.First(o => string.Equals(o.Name, "image1", StringComparison.InvariantCultureIgnoreCase)); - - Assert.IsNotNull(img1); - - Assert.AreEqual("12345", img1.Id); - Assert.AreEqual(new Uri("http://server.com/images/12345"), img1.PermanentUri); - Assert.AreEqual(new Uri("http://server.com/v2/images/12345"), img1.PublicUri); - } - - [TestMethod] - public void CanParseValidImagesPayloadWithEmptyJsonArray() - { - var emptyJsonArray = @"{ ""images"": [ ] }"; - - var converter = new ComputeImagePayloadConverter(); - var containers = converter.ConvertImages(emptyJsonArray).ToList(); - - Assert.AreEqual(0, containers.Count()); - } - - [TestMethod] - public void CanParseAnEmptyImagesPayload() - { - var payload = string.Empty; - - var converter = new ComputeImagePayloadConverter(); - var containers = converter.ConvertImages(payload).ToList(); - - Assert.AreEqual(0, containers.Count()); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotParseANullImagesPayload() - { - var converter = new ComputeImagePayloadConverter(); - converter.ConvertImages(null); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseInvalidImagesJsonPayload() - { - var converter = new ComputeImagePayloadConverter(); - converter.ConvertImages("[ { \"SomeAtrib\" }]"); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseInvalidImagesPayload() - { - var converter = new ComputeImagePayloadConverter(); - converter.ConvertImages("NOT JSON"); - } - } -} diff --git a/OpenStack/OpenStack.Test/Compute/ComputeItemMetadataPayloadConverterTests.cs b/OpenStack/OpenStack.Test/Compute/ComputeItemMetadataPayloadConverterTests.cs deleted file mode 100644 index 0de42f1..0000000 --- a/OpenStack/OpenStack.Test/Compute/ComputeItemMetadataPayloadConverterTests.cs +++ /dev/null @@ -1,131 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Newtonsoft.Json.Linq; -using OpenStack.Compute; - -namespace OpenStack.Test.Compute -{ - [TestClass] - public class ComputeItemMetadataPayloadConverterTests - { - [TestMethod] - public void CanConvertJsonPayloadToMetadata() - { - var metadataPayload = @"{ - ""metadata"": { - ""item1"": ""value1"", - ""item2"": ""value2"" - } - }"; - - var converter = new ComputeItemMetadataPayloadConverter(); - var metadata = converter.Convert(metadataPayload); - - Assert.AreEqual(2, metadata.Count); - Assert.IsTrue(metadata.ContainsKey("item1")); - Assert.AreEqual("value1",metadata["item1"]); - Assert.IsTrue(metadata.ContainsKey("item2")); - Assert.AreEqual("value2", metadata["item2"]); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertJsonPayloadEmptyObjectToMetadata() - { - var emptyObjectFixture = @"{ }"; - - var converter = new ComputeItemMetadataPayloadConverter(); - converter.Convert(emptyObjectFixture); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertNonObjectJsonToMetadata() - { - var nonObjectJson = @"[]"; - - var converter = new ComputeItemMetadataPayloadConverter(); - converter.Convert(nonObjectJson); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertInvalidJsonToMetadata() - { - var badJsonFixture = @"{ NOT JSON"; - - var converter = new ComputeItemMetadataPayloadConverter(); - converter.Convert(badJsonFixture); - } - - [TestMethod] - public void CanConvertEmptyMetadataToJson() - { - var metadata = new Dictionary(); - - var converter = new ComputeItemMetadataPayloadConverter(); - var payload = converter.Convert(metadata); - - var jsonObj = JObject.Parse(payload); - var metadataToken = jsonObj["metadata"]; - Assert.IsNotNull(metadataToken); - Assert.AreEqual(0, metadataToken.Children().Count()); - } - - [TestMethod] - public void CanConvertSingleMetadataToJson() - { - var metadata = new Dictionary() { { "item1", "value1" } }; - - var converter = new ComputeItemMetadataPayloadConverter(); - var payload = converter.Convert(metadata); - - var jsonObj = JObject.Parse(payload); - var metadataToken = jsonObj["metadata"]; - Assert.IsNotNull(metadataToken); - Assert.AreEqual("value1", metadataToken["item1"]); - } - - [TestMethod] - public void CanConvertMultipleMetadataToJson() - { - var metadata = new Dictionary() {{"item1", "value1"}, {"item2", "value2"}}; - - var converter = new ComputeItemMetadataPayloadConverter(); - var payload = converter.Convert(metadata); - - var jsonObj = JObject.Parse(payload); - var metadataToken = jsonObj["metadata"]; - Assert.IsNotNull(metadataToken); - Assert.AreEqual("value1", metadataToken["item1"]); - Assert.AreEqual("value2", metadataToken["item2"]); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotConvertNullMetadataToJson() - { - IDictionary metadata = null; - var converter = new ComputeItemMetadataPayloadConverter(); - converter.Convert(metadata); - } - } -} diff --git a/OpenStack/OpenStack.Test/Compute/ComputeKeyPairPayloadConverterTests.cs b/OpenStack/OpenStack.Test/Compute/ComputeKeyPairPayloadConverterTests.cs deleted file mode 100644 index ca02c1c..0000000 --- a/OpenStack/OpenStack.Test/Compute/ComputeKeyPairPayloadConverterTests.cs +++ /dev/null @@ -1,232 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Compute; - -namespace OpenStack.Test.Compute -{ - [TestClass] - public class ComputeKeyPairPayloadConverterTests - { - internal string CreateKeyPairJsonFixtrue(string name, string publickKey, string fingerprint) - { - var ComputeKeyPairJsonResponseFixture = @"{{ - ""keypair"": {{ - ""public_key"": ""{1}"", - ""name"": ""{0}"", - ""fingerprint"": ""{2}"" - }} - }}"; - - return string.Format(ComputeKeyPairJsonResponseFixture, name, publickKey, fingerprint); - } - - [TestMethod] - public void CanConvertJsonPayloadToKeyPair() - { - var keyName = "Key1"; - var publicKey = "12345"; - var fingerprint = "abcdef"; - - var computeFlavorJsonResponseFixture = CreateKeyPairJsonFixtrue(keyName, publicKey, fingerprint); - - var converter = new ComputeKeyPairPayloadConverter(); - var keyPair = converter.Convert(computeFlavorJsonResponseFixture); - Assert.IsNotNull(keyPair); - Assert.AreEqual(keyName, keyPair.Name); - Assert.AreEqual(publicKey, keyPair.PublicKey); - Assert.AreEqual(fingerprint, keyPair.Fingerprint); - } - - [TestMethod] - public void CanConvertJsonPayloadMissingPublicKey() - { - var missingFixture = @"{ - ""keypair"": { - ""name"": ""Key1"", - ""fingerprint"": ""ABCDEF"" - } - }"; - - var converter = new ComputeKeyPairPayloadConverter(); - var keyPair = converter.Convert(missingFixture); - Assert.IsNotNull(keyPair); - Assert.AreEqual("Key1", keyPair.Name); - Assert.AreEqual(string.Empty, keyPair.PublicKey); - Assert.AreEqual("ABCDEF", keyPair.Fingerprint); - } - - [TestMethod] - public void CanConvertJsonPayloadMissingFingerprint() - { - var missingFixture = @"{ - ""keypair"": { - ""public_key"": ""12345"", - ""name"": ""Key1"" - } - }"; - - var converter = new ComputeKeyPairPayloadConverter(); - var keyPair = converter.Convert(missingFixture); - Assert.IsNotNull(keyPair); - Assert.AreEqual("Key1", keyPair.Name); - Assert.AreEqual("12345", keyPair.PublicKey); - Assert.AreEqual(string.Empty, keyPair.Fingerprint); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertJsonPayloadMissingName() - { - var missingFixture = @"{ - ""keypair"": { - ""public_key"": ""12345"", - ""fingerprint"": ""ABCDEF"" - } - }"; - - var converter = new ComputeKeyPairPayloadConverter(); - converter.Convert(missingFixture); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertJsonPayloadEmptyObjectToKeyPair() - { - var emptyObjectFixture = @"{ }"; - - var converter = new ComputeKeyPairPayloadConverter(); - converter.ConvertKeyPairs(emptyObjectFixture); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertInvalidJsonToKeyPair() - { - var badJsonFixture = @"{ NOT JSON"; - - var converter = new ComputeKeyPairPayloadConverter(); - converter.ConvertKeyPairs(badJsonFixture); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertNonObjectJsonToKeyPair() - { - var nonObjectJson = @"[]"; - - var converter = new ComputeKeyPairPayloadConverter(); - converter.ConvertKeyPairs(nonObjectJson); - } - - [TestMethod] - public void CanParseValidJsonPayloadWithMultipleKeyPairs() - { - var validMultipleKeyPairsJsonFixture = @"{{ ""keypairs"": [ {0} ] }}"; - var firstKey = CreateKeyPairJsonFixtrue("Key1", "12345", "abcdef"); - var secondKey = CreateKeyPairJsonFixtrue("Key2", "54321", "fedcba"); - - var validMultipleKeyPairsJson = string.Format(validMultipleKeyPairsJsonFixture, - string.Join(",", new List() {firstKey, secondKey})); - - var converter = new ComputeKeyPairPayloadConverter(); - var pairs = converter.ConvertKeyPairs(validMultipleKeyPairsJson).ToList(); - - Assert.AreEqual(2, pairs.Count()); - var key1 = - pairs.First(o => string.Equals(o.Name, "Key1", StringComparison.InvariantCultureIgnoreCase)); - var key2 = - pairs.First(o => string.Equals(o.Name, "Key2", StringComparison.InvariantCultureIgnoreCase)); - Assert.IsNotNull(key1); - Assert.IsNotNull(key2); - - Assert.AreEqual("12345", key1.PublicKey); - Assert.AreEqual("abcdef", key1.Fingerprint); - - Assert.AreEqual("54321", key2.PublicKey); - Assert.AreEqual("fedcba", key2.Fingerprint); - } - - [TestMethod] - public void CanConvertValidJsonPayloadWithSingleKeyPair() - { - var validKeyPairsJsonFixture = @"{{ ""keypairs"": [ {0} ] }}"; - var firstKey = CreateKeyPairJsonFixtrue("Key1", "12345", "abcdef"); - - var validKeyPairsJson = string.Format(validKeyPairsJsonFixture, firstKey); - - var converter = new ComputeKeyPairPayloadConverter(); - var pairs = converter.ConvertKeyPairs(validKeyPairsJson).ToList(); - - Assert.AreEqual(1, pairs.Count()); - var key1 = pairs.First(o => string.Equals(o.Name, "Key1", StringComparison.InvariantCultureIgnoreCase)); - Assert.IsNotNull(key1); - - Assert.AreEqual("12345", key1.PublicKey); - Assert.AreEqual("abcdef", key1.Fingerprint); - } - - [TestMethod] - public void CanParseValidKeyPairsPayloadWithEmptyJsonArray() - { - var emptyJsonArray = @"{ ""keypairs"": [ ] }"; - - var converter = new ComputeKeyPairPayloadConverter(); - var containers = converter.ConvertKeyPairs(emptyJsonArray).ToList(); - - Assert.AreEqual(0, containers.Count()); - } - - [TestMethod] - public void CanParseAnEmptyKeyPairsPayload() - { - var payload = string.Empty; - - var converter = new ComputeKeyPairPayloadConverter(); - var containers = converter.ConvertKeyPairs(payload).ToList(); - - Assert.AreEqual(0, containers.Count()); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotParseANullKeyPairsPayload() - { - var converter = new ComputeKeyPairPayloadConverter(); - converter.ConvertKeyPairs(null); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseInvalidKeyPairsJsonPayload() - { - var converter = new ComputeKeyPairPayloadConverter(); - converter.ConvertKeyPairs("[ { \"SomeAtrib\" }]"); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseInvalidKeyPairsPayload() - { - var converter = new ComputeKeyPairPayloadConverter(); - converter.ConvertKeyPairs("NOT JSON"); - } - } -} diff --git a/OpenStack/OpenStack.Test/Compute/ComputeRestSimulator.cs b/OpenStack/OpenStack.Test/Compute/ComputeRestSimulator.cs deleted file mode 100644 index ce1c907..0000000 --- a/OpenStack/OpenStack.Test/Compute/ComputeRestSimulator.cs +++ /dev/null @@ -1,733 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.Mime; -using System.Text; -using System.Threading; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using OpenStack.Common; -using OpenStack.Common.Http; -using OpenStack.Compute; - -namespace OpenStack.Test.Compute -{ - public class ComputeRestSimulator : RestSimulator - { - internal ICollection Flavors { get; private set; } - - internal ICollection Images { get; private set; } - - internal ICollection Servers { get; private set; } - - internal ICollection KeyPairs { get; private set; } - - public ComputeRestSimulator() : base() - { - this.Flavors = new List(); - this.Images = new List(); - this.Servers = new List(); - this.KeyPairs = new List(); - } - - public ComputeRestSimulator(CancellationToken token) : this() - { - } - - protected override IHttpResponseAbstraction HandleGet() - { - if (this.Uri.Segments.Count() >= 4) - { - switch (this.Uri.Segments[3].TrimEnd('/').ToLower()) - { - case "flavors": - return HandleGetFlavor(); - case "images": - return HandleGetImage(); - case "servers": - return HandleGetServer(); - case "os-keypairs": - return HandleGetKeyPairs(); - } - } - throw new NotImplementedException(); - } - - internal IHttpResponseAbstraction HandleGetFlavor() - { - Stream flavorContent; - switch (this.Uri.Segments.Count()) - { - case 5: - //flavor id given, list single flavor - var flavorId = this.Uri.Segments[4].TrimEnd('/'); - var flavor = - this.Flavors.FirstOrDefault( - f => string.Equals(f.Id, flavorId, StringComparison.OrdinalIgnoreCase)); - if (flavor == null) - { - return TestHelper.CreateResponse(HttpStatusCode.NotFound); - } - - flavorContent = TestHelper.CreateStream(GenerateFlavorPayload(flavor)); - break; - case 4: - //no flavor id given, list all flavors - flavorContent = TestHelper.CreateStream(GenerateItemsPayload(this.Flavors, "flavors")); - break; - default: - //Unknown Uri format - throw new NotImplementedException(); - } - - return TestHelper.CreateResponse(HttpStatusCode.OK, new Dictionary(), flavorContent); - } - - internal IHttpResponseAbstraction HandleGetKeyPairs() - { - Stream keyPairContent; - switch (this.Uri.Segments.Count()) - { - case 5: - var keyPairName = this.Uri.Segments[4].TrimEnd('/'); - var pair = - this.KeyPairs.FirstOrDefault( - kp => string.Equals(kp.Name, keyPairName, StringComparison.OrdinalIgnoreCase)); - if (pair == null) - { - return TestHelper.CreateResponse(HttpStatusCode.NotFound); - } - - keyPairContent = TestHelper.CreateStream(GenerateKeyPairPayload(pair)); - break; - case 4: - keyPairContent = TestHelper.CreateStream(GenerateKeyPairsPayload(this.KeyPairs)); - break; - default: - //Unknown Uri format - throw new NotImplementedException(); - } - - return TestHelper.CreateResponse(HttpStatusCode.OK, new Dictionary(), keyPairContent); - } - - internal IHttpResponseAbstraction HandleGetImage() - { - Stream imageContent; - switch (this.Uri.Segments.Count()) - { - case 5: - //image id given, list single image - var imageId = this.Uri.Segments[4].TrimEnd('/'); - if (imageId.ToLower() == "detail") - { - imageContent = TestHelper.CreateStream(GenerateItemsPayload(this.Images, "images")); - } - else - { - var image = - this.Images.FirstOrDefault( - f => string.Equals(f.Id, imageId, StringComparison.OrdinalIgnoreCase)); - if (image == null) - { - return TestHelper.CreateResponse(HttpStatusCode.NotFound); - } - - imageContent = TestHelper.CreateStream(GenerateImagePayload(image)); - } - break; - case 6: - if (this.Uri.Segments[5].TrimEnd('/').ToLower() != "metadata") - { - return TestHelper.CreateResponse(HttpStatusCode.NotFound); - } - var imgId = this.Uri.Segments[4].TrimEnd('/'); - var img = - this.Images.FirstOrDefault( - i => string.Equals(i.Id, imgId, StringComparison.OrdinalIgnoreCase)); - if (img == null) - { - return TestHelper.CreateResponse(HttpStatusCode.NotFound); - } - imageContent = TestHelper.CreateStream(GenerateMetadataPayload(img.Metadata)); - break; - default: - throw new NotImplementedException(); - } - - return TestHelper.CreateResponse(HttpStatusCode.OK, new Dictionary(), imageContent); - } - - internal IHttpResponseAbstraction HandleGetServer() - { - Stream serverContent; - - if (this.Uri.Segments.Count() < 5) - { - if (this.Uri.Segments.Count() == 4) - { - serverContent = TestHelper.CreateStream(GenerateItemsPayload(this.Flavors, "servers")); - return TestHelper.CreateResponse(HttpStatusCode.OK, new Dictionary(), serverContent); - } - throw new NotImplementedException(); - } - - var srvId = this.Uri.Segments[4].TrimEnd('/'); - var srv = - this.Servers.FirstOrDefault( - s => string.Equals(s.Id, srvId, StringComparison.OrdinalIgnoreCase)); - if (srv == null) - { - return TestHelper.CreateResponse(HttpStatusCode.NotFound); - } - - - switch (this.Uri.Segments.Count()) - { - case 6: - if (this.Uri.Segments[5].TrimEnd('/').ToLower() != "metadata") - { - return TestHelper.CreateResponse(HttpStatusCode.NotFound); - } - - serverContent = TestHelper.CreateStream(GenerateMetadataPayload(srv.Metadata)); - break; - case 5: - //server id given, list single server - serverContent = TestHelper.CreateStream(GenerateServerPayload(srv)); - break; - default: - //Unknown Uri format - throw new NotImplementedException(); - } - - return TestHelper.CreateResponse(HttpStatusCode.OK, new Dictionary(), serverContent); - } - - protected override IHttpResponseAbstraction HandlePost() - { - if (this.Uri.Segments.Count() >= 4) - { - switch (this.Uri.Segments[3].TrimEnd('/').ToLower()) - { - case "servers": - return HandlePostServer(); - case "images": - return HandlePostImage(); - } - } - throw new NotImplementedException(); - } - - protected override IHttpResponseAbstraction HandlePut() - { - throw new NotImplementedException(); - } - - internal IHttpResponseAbstraction HandlePostImage() - { - switch (this.Uri.Segments.Count()) - { - case 6: - if (this.Uri.Segments[5].TrimEnd('/').ToLower() != "metadata") - { - return TestHelper.CreateResponse(HttpStatusCode.NotFound); - } - var imgId = this.Uri.Segments[4].TrimEnd('/'); - var img = - this.Images.FirstOrDefault( - i => string.Equals(i.Id, imgId, StringComparison.OrdinalIgnoreCase)); - if (img == null) - { - return TestHelper.CreateResponse(HttpStatusCode.NotFound); - } - - ParseAndStoreMetadata(img, GetPayload(this.Content)); - break; - default: - throw new NotImplementedException(); - } - - return TestHelper.CreateResponse(HttpStatusCode.OK, new Dictionary()); - } - - internal IHttpResponseAbstraction HandlePostServer() - { - switch (this.Uri.Segments.Count()) - { - case 4: - return HandlePostNewServer(); - case 6: - var srvId = this.Uri.Segments[4].TrimEnd('/'); - var action = this.Uri.Segments[5].TrimEnd('/').ToLower(); - switch (action) - { - case "metadata": - return HandlePostServerMetadata(srvId); - case "action": - return HandlePostServerAction(srvId); - default: - throw new NotImplementedException(); - } - default: - throw new NotImplementedException(); - } - } - - internal IHttpResponseAbstraction HandlePostServerAction(string serverId) - { - this.Content.Position = 0; - var reqBody = TestHelper.GetStringFromStream(this.Content); - var body = JObject.Parse(reqBody); - if (body["addFloatingIp"] != null && body["addFloatingIp"]["address"] != null) - { - return TestHelper.CreateResponse(HttpStatusCode.Accepted, new Dictionary()); - } - - throw new NotImplementedException(); - } - - internal IHttpResponseAbstraction HandlePostServerMetadata(string serverId) - { - var srv = - this.Servers.FirstOrDefault( - s => string.Equals(s.Id, serverId, StringComparison.OrdinalIgnoreCase)); - if (srv == null) - { - return TestHelper.CreateResponse(HttpStatusCode.NotFound); - } - - ParseAndStoreMetadata(srv, GetPayload(this.Content)); - return TestHelper.CreateResponse(HttpStatusCode.OK, new Dictionary()); - } - - internal IHttpResponseAbstraction HandlePostNewServer() - { - var payload = TestHelper.GetStringFromStream(this.Content); - var obj = JObject.Parse(payload); - var name = (string)obj["server"]["name"]; - var srv = new ComputeServer(Guid.NewGuid().ToString(), name, "12345", new Uri("http://test.com"), new Uri("http://test.com"), new Dictionary()); - this.Servers.Add(srv); - var responsePayload = GenerateCreateServeResponse(srv); - - return TestHelper.CreateResponse(HttpStatusCode.Accepted, new Dictionary(), responsePayload.ConvertToStream()); - } - - protected override IHttpResponseAbstraction HandleDelete() - { - if (this.Uri.Segments.Count() >= 4) - { - switch (this.Uri.Segments[3].TrimEnd('/').ToLower()) - { - case "images": - return HandleDeleteImages(); - case "flavors": - return HandleDeleteFlavors(); - case "servers": - return HandleDeleteServers(); - } - } - return TestHelper.CreateResponse(HttpStatusCode.NotFound); - } - - private IHttpResponseAbstraction HandleDeleteImages() - { - if (this.Uri.Segments.Count() < 5) - { - throw new NotImplementedException(); - } - - var imageId = this.Uri.Segments[4].TrimEnd('/'); - var image = this.Images.FirstOrDefault(i => i.Id == imageId); - if (image == null) - { - return TestHelper.CreateResponse(HttpStatusCode.NotFound); - } - - switch (this.Uri.Segments.Count()) - { - case 5: - this.Images.Remove(image); - return TestHelper.CreateResponse(HttpStatusCode.OK); - case 7: - var key = this.Uri.Segments[6].TrimEnd('/'); - if (!image.Metadata.ContainsKey(key)) - { - return TestHelper.CreateResponse(HttpStatusCode.NotFound); - } - image.Metadata.Remove(key); - return TestHelper.CreateResponse(HttpStatusCode.OK); - default: - throw new NotImplementedException(); - } - } - - private IHttpResponseAbstraction HandleDeleteFlavors() - { - throw new NotImplementedException(); - } - - private IHttpResponseAbstraction HandleDeleteServers() - { - if (this.Uri.Segments.Count() < 5) - { - throw new NotImplementedException(); - } - - var srvId = this.Uri.Segments[4].TrimEnd('/'); - var srv = this.Servers.FirstOrDefault(s => s.Id == srvId); - if (srv == null) - { - return TestHelper.CreateResponse(HttpStatusCode.NotFound); - } - - switch (this.Uri.Segments.Count()) - { - case 5: - this.Servers.Remove(srv); - return TestHelper.CreateResponse(HttpStatusCode.OK); - case 7: - var key = this.Uri.Segments[6].TrimEnd('/'); - if (!srv.Metadata.ContainsKey(key)) - { - return TestHelper.CreateResponse(HttpStatusCode.NotFound); - } - srv.Metadata.Remove(key); - return TestHelper.CreateResponse(HttpStatusCode.OK); - default: - throw new NotImplementedException(); - } - } - - protected override IHttpResponseAbstraction HandleHead() - { - throw new NotImplementedException(); - } - - protected override IHttpResponseAbstraction HandleCopy() - { - throw new NotImplementedException(); - } - - private string GetPayload(Stream input) - { - using (var sr = new StreamReader(input)) - { - return sr.ReadToEnd(); - } - } - - private string GenerateItemsPayload(IEnumerable items, string collectionName ) - { - var payload = new StringBuilder(); - payload.Append(string.Format("{{ \"{0}\": [",collectionName)); - var first = true; - foreach (var item in items) - { - if (!first) - { - payload.Append(","); - } - - payload.Append("{"); - payload.Append(string.Format("\"id\": \"{0}\",", item.Id)); - payload.Append("\"links\": ["); - payload.Append("{"); - payload.Append(string.Format("\"href\": \"{0}\",", item.PublicUri.AbsoluteUri)); - payload.Append("\"rel\": \"self\""); - payload.Append("},{"); - payload.Append(string.Format("\"href\": \"{0}\",", item.PermanentUri.AbsoluteUri)); - payload.Append("\"rel\": \"bookmark\""); - payload.Append("}"); - payload.Append("],"); - payload.Append(string.Format("\"name\": \"{0}\"", item.Name)); - payload.Append("}"); - first = false; - } - payload.Append("] }"); - return payload.ToString(); - } - - private string GenerateKeyPairPayload(ComputeKeyPair keyPair) - { - var payloadFixture = @"{{ - ""keypair"": {{ - ""public_key"": ""{1}"", - ""name"": ""{0}"", - ""fingerprint"": ""{2}"" - }} - }}"; - return string.Format(payloadFixture, keyPair.Name, keyPair.PublicKey, keyPair.Fingerprint); - } - - private string GenerateKeyPairsPayload(IEnumerable keyPairs) - { - var payload = new StringBuilder(); - payload.Append("{ \"keypairs\": ["); - var first = true; - foreach (var keyPair in keyPairs) - { - if (!first) - { - payload.Append(","); - } - payload.Append(GenerateKeyPairPayload(keyPair)); - first = false; - } - - payload.Append("] }"); - return payload.ToString(); - } - - private string GenerateFlavorPayload(ComputeFlavor flavor) - { - var payloadFixture = @"{{ - ""flavor"" : {{ - ""name"": ""{0}"", - ""links"": [ - {{ - ""href"": ""{1}"", - ""rel"": ""self"" - }}, - {{ - ""href"": ""{2}"", - ""rel"": ""bookmark"" - }} - ], - ""ram"": {3}, - ""vcpus"": {4}, - ""disk"": {5}, - ""id"": ""{6}"" - }} - }}"; - return string.Format(payloadFixture, flavor.Name, flavor.PublicUri.AbsoluteUri, - flavor.PermanentUri.AbsoluteUri, flavor.Ram, flavor.Vcpus, flavor.Disk, flavor.Id); - } - - private string GenerateImagePayload(ComputeImage image) - { - var payloadFixture = @"{{ - ""image"" : {{ - ""name"": ""{0}"", - ""status"": ""{1}"", - ""updated"": ""{2}"", - ""created"": ""{3}"", - ""minDisk"": {4}, - ""progress"": {5}, - ""minRam"": {6}, - ""links"": [ - {{ - ""href"": ""{7}"", - ""rel"": ""self"" - }}, - {{ - ""href"": ""{8}"", - ""rel"": ""bookmark"" - }} - ], - ""id"": ""{9}"" - }} - }}"; - - return string.Format(payloadFixture, image.Name, image.Status, image.CreateDate, image.LastUpdated, - image.MinimumDiskSize, image.UploadProgress, image.MinimumRamSize, image.PublicUri.AbsoluteUri, - image.PermanentUri.AbsoluteUri, image.Id); - } - - internal string GenerateCreateServeResponse(ComputeServer server) - { - var payloadFixture = @"{{ - ""server"": {{ - ""security_groups"": [ - {{ - ""name"": ""default"" - }}, - {{ - ""name"": ""MyGroup"" - }} - ], - ""OS-DCF:diskConfig"": ""MANUAL"", - ""id"": ""{0}"", - ""links"": [ - {{ - ""href"": ""{2}"", - ""rel"": ""self"" - }}, - {{ - ""href"": ""{3}"", - ""rel"": ""bookmark"" - }} - ], - ""adminPass"": ""{1}"" - }} - }}"; - - return string.Format(payloadFixture, server.Id, server.AdminPassword, - server.PublicUri.AbsoluteUri, server.PermanentUri.AbsoluteUri); - } - - private string GenerateServerPayload(ComputeServer server) - { - var payloadFixture = @"{{ - ""server"": {{ - ""status"": ""{2}"", - ""updated"": ""2014-06-11T18:04:46Z"", - ""hostId"": ""bd5417ccb076908f6e0d639c37c053b0b6b9681db3464d19908dd4d9"", - ""addresses"": {{ - ""private"": [ - {{ - ""OS-EXT-IPS-MAC:mac_addr"": ""fa:16:3e:34:da:44"", - ""version"": 4, - ""addr"": ""10.0.0.2"", - ""OS-EXT-IPS:type"": ""fixed"" - }}, - {{ - ""OS-EXT-IPS-MAC:mac_addr"": ""fa:16:3e:34:da:44"", - ""version"": 4, - ""addr"": ""172.24.4.3"", - ""OS-EXT-IPS:type"": ""floating"" - }} - ] - }}, - ""links"": [ - {{ - ""href"": ""{4}"", - ""rel"": ""self"" - }}, - {{ - ""href"": ""{5}"", - ""rel"": ""bookmark"" - }} - ], - ""key_name"": null, - ""image"": {{ - ""id"": ""c650e788-3c46-4efc-bfa6-1d94a14d6405"", - ""links"": [ - {{ - ""href"": ""http://15.125.87.81:8774/ffe683d1060449d09dac0bf9d7a371cd/images/c650e788-3c46-4efc-bfa6-1d94a14d6405"", - ""rel"": ""bookmark"" - }} - ] - }}, - ""OS-EXT-STS:task_state"": null, - ""OS-EXT-STS:vm_state"": ""active"", - ""OS-SRV-USG:launched_at"": ""2014-06-11T18:04:45.000000"", - ""flavor"": {{ - ""id"": ""1"", - ""links"": [ - {{ - ""href"": ""http://15.125.87.81:8774/ffe683d1060449d09dac0bf9d7a371cd/flavors/1"", - ""rel"": ""bookmark"" - }} - ] - }}, - ""id"": ""{0}"", - ""security_groups"": [ - {{ - ""name"": ""MyGroup"" - }}, - {{ - ""name"": ""default"" - }} - ], - ""OS-SRV-USG:terminated_at"": null, - ""OS-EXT-AZ:availability_zone"": ""nova"", - ""user_id"": ""70d48d344b494a1cbe8adbf7c02be7b5"", - ""name"": ""{1}"", - ""created"": ""2014-06-11T18:04:25Z"", - ""tenant_id"": ""ffe683d1060449d09dac0bf9d7a371cd"", - ""OS-DCF:diskConfig"": ""AUTO"", - ""os-extended-volumes:volumes_attached"": [], - ""accessIPv4"": """", - ""accessIPv6"": """", - ""progress"": {3}, - ""OS-EXT-STS:power_state"": 1, - ""config_drive"": """", - ""metadata"": {{}} - }} - }}"; - return string.Format(payloadFixture, server.Id, server.Name, server.Status, server.Progress, server.PublicUri.AbsoluteUri, server.PermanentUri.AbsoluteUri); - } - - private string GenerateMetadataPayload(IDictionary metadata) - { - var payload = new StringBuilder(); - payload.Append("{ \"metadata\" : {"); - var isFirst = true; - - foreach (var item in metadata) - { - if (!isFirst) - { - payload.Append(","); - } - - payload.AppendFormat("\"{0}\":\"{1}\"", item.Key, item.Value); - isFirst = false; - } - - payload.Append("}}"); - return payload.ToString(); - } - - private void ParseAndStoreMetadata(MetadataComputeItem item, string payload) - { - var jObj = JObject.Parse(payload); - var metaToken = jObj["metadata"]; - var metdata = JsonConvert.DeserializeObject>(metaToken.ToString()); - item.Metadata = metdata; - } - } - - public class ComputeRestSimulatorFactory : IHttpAbstractionClientFactory - { - internal ComputeRestSimulator Simulator = null; - - public ComputeRestSimulatorFactory(ComputeRestSimulator simulator) - { - this.Simulator = simulator; - } - - public IHttpAbstractionClient Create() - { - throw new NotImplementedException(); - } - - public IHttpAbstractionClient Create(CancellationToken token) - { - if (this.Simulator != null) - { - this.Simulator.Headers.Clear(); - } - return this.Simulator ?? new ComputeRestSimulator(token); - } - - public IHttpAbstractionClient Create(TimeSpan timeout) - { - throw new NotImplementedException(); - } - - public IHttpAbstractionClient Create(TimeSpan timeout, CancellationToken token) - { - throw new NotImplementedException(); - } - } -} diff --git a/OpenStack/OpenStack.Test/Compute/ComputeServerPayloadConverterTests.cs b/OpenStack/OpenStack.Test/Compute/ComputeServerPayloadConverterTests.cs deleted file mode 100644 index a9bb00a..0000000 --- a/OpenStack/OpenStack.Test/Compute/ComputeServerPayloadConverterTests.cs +++ /dev/null @@ -1,756 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Compute; - -namespace OpenStack.Test.Compute -{ - [TestClass] - public class ComputeServerPayloadConverterTests - { - internal string CreateServerJsonFixtrue(string name, string id, string status, int progress, string publicUri, string permUri) - { - var payloadFixture = @"{{ - ""server"": {{ - ""status"": ""{2}"", - ""updated"": ""2014-06-11T18:04:46Z"", - ""hostId"": ""bd5417ccb076908f6e0d639c37c053b0b6b9681db3464d19908dd4d9"", - ""addresses"": {{ - ""private"": [ - {{ - ""OS-EXT-IPS-MAC:mac_addr"": ""fa:16:3e:34:da:44"", - ""version"": 4, - ""addr"": ""10.0.0.2"", - ""OS-EXT-IPS:type"": ""fixed"" - }}, - {{ - ""OS-EXT-IPS-MAC:mac_addr"": ""fa:16:3e:34:da:44"", - ""version"": 4, - ""addr"": ""172.24.4.3"", - ""OS-EXT-IPS:type"": ""floating"" - }} - ] - }}, - ""links"": [ - {{ - ""href"": ""{4}"", - ""rel"": ""self"" - }}, - {{ - ""href"": ""{5}"", - ""rel"": ""bookmark"" - }} - ], - ""key_name"": null, - ""image"": {{ - ""id"": ""c650e788-3c46-4efc-bfa6-1d94a14d6405"", - ""links"": [ - {{ - ""href"": ""http://15.125.87.81:8774/ffe683d1060449d09dac0bf9d7a371cd/images/c650e788-3c46-4efc-bfa6-1d94a14d6405"", - ""rel"": ""bookmark"" - }} - ] - }}, - ""OS-EXT-STS:task_state"": null, - ""OS-EXT-STS:vm_state"": ""active"", - ""OS-SRV-USG:launched_at"": ""2014-06-11T18:04:45.000000"", - ""flavor"": {{ - ""id"": ""1"", - ""links"": [ - {{ - ""href"": ""http://15.125.87.81:8774/ffe683d1060449d09dac0bf9d7a371cd/flavors/1"", - ""rel"": ""bookmark"" - }} - ] - }}, - ""id"": ""{0}"", - ""security_groups"": [ - {{ - ""name"": ""MyGroup"" - }}, - {{ - ""name"": ""default"" - }} - ], - ""OS-SRV-USG:terminated_at"": null, - ""OS-EXT-AZ:availability_zone"": ""nova"", - ""user_id"": ""70d48d344b494a1cbe8adbf7c02be7b5"", - ""name"": ""{1}"", - ""created"": ""2014-06-11T18:04:25Z"", - ""tenant_id"": ""ffe683d1060449d09dac0bf9d7a371cd"", - ""OS-DCF:diskConfig"": ""AUTO"", - ""os-extended-volumes:volumes_attached"": [], - ""accessIPv4"": """", - ""accessIPv6"": """", - ""progress"": {3}, - ""OS-EXT-STS:power_state"": 1, - ""config_drive"": """", - ""metadata"": {{}} - }} - }}"; - return string.Format(payloadFixture, id, name, status, progress, publicUri, permUri); - } - - internal string CreateServerRequstSummaryJsonFixtrue(string id, string permaUri, string publicUri, string adminPass) - { - var computeServerSummaryJsonResponseFixture = @"{{ - ""server"": {{ - ""security_groups"": [ - {{ - ""name"": ""default"" - }}, - {{ - ""name"": ""MyGroup"" - }} - ], - ""OS-DCF:diskConfig"": ""MANUAL"", - ""id"": ""{0}"", - ""links"": [ - {{ - ""href"": ""{1}"", - ""rel"": ""self"" - }}, - {{ - ""href"": ""{2}"", - ""rel"": ""bookmark"" - }} - ], - ""adminPass"": ""{3}"" - }} - }}"; - - return string.Format(computeServerSummaryJsonResponseFixture, id, publicUri, permaUri, adminPass); - } - - internal string CreateServersSummaryJsonFixtrue(string name, string id, string permaUri, string publicUri) - { - var computeServerSummaryJsonResponseFixture = @"{{ - ""id"": ""{0}"", - ""links"": [ - {{ - ""href"": ""{1}"", - ""rel"": ""self"" - }}, - {{ - ""href"": ""{2}"", - ""rel"": ""bookmark"" - }} - ], - ""name"": ""{3}"" - }}"; - - return string.Format(computeServerSummaryJsonResponseFixture, id, publicUri, permaUri, name); - } - - [TestMethod] - public void CanConvertJsonPayloadToServer() - { - var serverPublicUri = "http://www.server.com/v2/servers/1"; - var serverPermUri = "http://www.server.com/servers/1"; - var serverId = "12345"; - var serverName = "testServer"; - var serverProgress = 0; - var serverState = "ACTIVE"; - - var computeServerFixture = CreateServerJsonFixtrue(serverName, serverId, serverState, serverProgress, serverPublicUri, serverPermUri); - - var converter = new ComputeServerPayloadConverter(); - var server = converter.Convert(computeServerFixture); - - Assert.IsNotNull(server); - Assert.AreEqual(serverId, server.Id); - Assert.AreEqual(serverName, server.Name); - Assert.AreEqual(serverState.ToLower(), server.Status.ToString().ToLower()); - Assert.AreEqual(serverProgress, server.Progress); - Assert.AreEqual(new Uri(serverPermUri), server.PermanentUri); - Assert.AreEqual(new Uri(serverPublicUri), server.PublicUri); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertJsonPayloadMissingIdToServer() - { - var serverPublicUri = "http://www.server.com/v2/servers/1"; - var serverPermUri = "http://www.server.com/servers/1"; - var serverName = "testServer"; - var serverProgress = 0; - var serverState = "ACTIVE"; - - var payloadFixture = @"{{ - ""server"": {{ - ""status"": ""{1}"", - ""updated"": ""2014-06-11T18:04:46Z"", - ""links"": [ - {{ - ""href"": ""{3}"", - ""rel"": ""self"" - }}, - {{ - ""href"": ""{4}"", - ""rel"": ""bookmark"" - }} - ], - ""name"": ""{0}"", - ""created"": ""2014-06-11T18:04:25Z"", - ""progress"": {2} - }} - }}"; - - var missingFixture = string.Format(payloadFixture, serverName, serverState, serverProgress, serverPublicUri, serverPermUri); - - var converter = new ComputeServerPayloadConverter(); - converter.Convert(missingFixture); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertJsonPayloadMissingpublicUriToServer() - { - var serverPermUri = "http://www.server.com/servers/1"; - var serverId = "12345"; - var serverName = "testServer"; - var serverProgress = 0; - var serverState = "ACTIVE"; - - var payloadFixture = @"{{ - ""server"": {{ - ""status"": ""{2}"", - ""updated"": ""2014-06-11T18:04:46Z"", - ""links"": [ - {{ - ""rel"": ""self"" - }}, - {{ - ""href"": ""{4}"", - ""rel"": ""bookmark"" - }} - ], - ""id"": ""{0}"", - ""name"": ""{1}"", - ""created"": ""2014-06-11T18:04:25Z"", - ""progress"": {3} - }} - }}"; - - var missingFixture = string.Format(payloadFixture, serverId, serverName, serverState, serverProgress, serverPermUri); - - var converter = new ComputeServerPayloadConverter(); - converter.Convert(missingFixture); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertJsonPayloadMissingPermUriToServer() - { - var serverPublicUri = "http://www.server.com/v2/servers/1"; - var serverId = "12345"; - var serverName = "testServer"; - var serverProgress = 0; - var serverState = "ACTIVE"; - - var payloadFixture = @"{{ - ""server"": {{ - ""status"": ""{2}"", - ""updated"": ""2014-06-11T18:04:46Z"", - ""links"": [ - {{ - ""href"": ""{4}"", - ""rel"": ""self"" - }}, - {{ - ""rel"": ""bookmark"" - }} - ], - ""id"": ""{0}"", - ""name"": ""{1}"", - ""created"": ""2014-06-11T18:04:25Z"", - ""progress"": {3} - }} - }}"; - - var missingFixture = string.Format(payloadFixture, serverId, serverName, serverState, serverProgress, serverPublicUri); - - var converter = new ComputeServerPayloadConverter(); - converter.Convert(missingFixture); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertJsonPayloadMissingStatusToServer() - { - var serverPublicUri = "http://www.server.com/v2/servers/1"; - var serverPermUri = "http://www.server.com/servers/1"; - var serverId = "12345"; - var serverName = "testServer"; - var serverProgress = 0; - - var payloadFixture = @"{{ - ""server"": {{ - ""updated"": ""2014-06-11T18:04:46Z"", - ""links"": [ - {{ - ""href"": ""{3}"", - ""rel"": ""self"" - }}, - {{ - ""href"": ""{4}"", - ""rel"": ""bookmark"" - }} - ], - ""id"": ""{0}"", - ""name"": ""{1}"", - ""created"": ""2014-06-11T18:04:25Z"", - ""progress"": {2} - }} - }}"; - - var missingFixture = string.Format(payloadFixture, serverId, serverName, serverProgress, serverPublicUri, serverPermUri); - - var converter = new ComputeServerPayloadConverter(); - converter.Convert(missingFixture); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertJsonPayloadMissingNameToServer() - { - var serverPublicUri = "http://www.server.com/v2/servers/1"; - var serverPermUri = "http://www.server.com/servers/1"; - var serverId = "12345"; - var serverProgress = 0; - var serverState = "ACTIVE"; - - var payloadFixture = @"{{ - ""server"": {{ - ""status"": ""{1}"", - ""updated"": ""2014-06-11T18:04:46Z"", - ""links"": [ - {{ - ""href"": ""{3}"", - ""rel"": ""self"" - }}, - {{ - ""href"": ""{4}"", - ""rel"": ""bookmark"" - }} - ], - ""id"": ""{0}"", - ""created"": ""2014-06-11T18:04:25Z"", - ""progress"": {2} - }} - }}"; - - var missingFixture = string.Format(payloadFixture, serverId, serverState, serverProgress, serverPublicUri, serverPermUri); - - var converter = new ComputeServerPayloadConverter(); - converter.Convert(missingFixture); - } - - [TestMethod] - public void CanConvertJsonPayloadMissingProgressToServer() - { - var serverPublicUri = "http://www.server.com/v2/servers/1"; - var serverPermUri = "http://www.server.com/servers/1"; - var serverId = "12345"; - var serverName = "testServer"; - var serverState = "ACTIVE"; - - var payloadFixture = @"{{ - ""server"": {{ - ""status"": ""{2}"", - ""updated"": ""2014-06-11T18:04:46Z"", - ""links"": [ - {{ - ""href"": ""{3}"", - ""rel"": ""self"" - }}, - {{ - ""href"": ""{4}"", - ""rel"": ""bookmark"" - }} - ], - ""id"": ""{0}"", - ""name"": ""{1}"", - ""created"": ""2014-06-11T18:04:25Z"" - }} - }}"; - - var missingFixture = string.Format(payloadFixture, serverId, serverName, serverState, serverPublicUri, serverPermUri); - - var converter = new ComputeServerPayloadConverter(); - var server = converter.Convert(missingFixture); - - Assert.IsNotNull(server); - Assert.AreEqual(serverId, server.Id); - Assert.AreEqual(serverName, server.Name); - Assert.AreEqual(serverState.ToLower(), server.Status.ToString().ToLower()); - Assert.AreEqual(0, server.Progress); - Assert.AreEqual(new Uri(serverPermUri), server.PermanentUri); - Assert.AreEqual(new Uri(serverPublicUri), server.PublicUri); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertServerJsonPayloadEmptyObjectToServer() - { - var emptyObjectFixture = @"{ }"; - - var converter = new ComputeServerPayloadConverter(); - converter.Convert(emptyObjectFixture); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertInvalidServerJsonToServer() - { - var badJsonFixture = @"{ NOT JSON"; - - var converter = new ComputeServerPayloadConverter(); - converter.Convert(badJsonFixture); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertNonObjectServerJsonToServer() - { - var nonObjectJson = @"[]"; - - var converter = new ComputeServerPayloadConverter(); - converter.Convert(nonObjectJson); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotConvertNullJsonToServer() - { - var converter = new ComputeServerPayloadConverter(); - converter.Convert(null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public void CannotConvertEmptyStringJsonToServer() - { - var converter = new ComputeServerPayloadConverter(); - converter.Convert(string.Empty); - } - - [TestMethod] - public void CanConvertSummaryJsonPayloadToServer() - { - - var serverId = "1"; - var serverPublicUri = "http://www.server.com/v2/servers/1"; - var serverPermUri = "http://www.server.com/servers/1"; - var serverAdminPass = "ABCDE"; - - var computeServerFixture = CreateServerRequstSummaryJsonFixtrue(serverId, serverPermUri, serverPublicUri, serverAdminPass); - - var converter = new ComputeServerPayloadConverter(); - var server = converter.ConvertSummary(computeServerFixture); - - Assert.IsNotNull(server); - Assert.AreEqual(serverId, server.Id); - Assert.AreEqual(serverAdminPass, server.AdminPassword); - Assert.AreEqual(new Uri(serverPermUri), server.PermanentUri); - Assert.AreEqual(new Uri(serverPublicUri), server.PublicUri); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertSummaryJsonPayloadMissingIdToServer() - { - var serverPublicUri = "http://www.server.com/v2/servers/1"; - var serverPermUri = "http://www.server.com/servers/1"; - var serverAdminPass = "ABCDE"; - - var computeServerSummaryJsonResponseFixture = @"{{ - ""server"": {{ - ""security_groups"": [ - {{ - ""name"": ""default"" - }}, - {{ - ""name"": ""MyGroup"" - }} - ], - ""OS-DCF:diskConfig"": ""MANUAL"", - ""links"": [ - {{ - ""href"": ""{1}"", - ""rel"": ""self"" - }}, - {{ - ""href"": ""{0}"", - ""rel"": ""bookmark"" - }} - ], - ""adminPass"": ""{2}"" - }} - }}"; - - var missingFixture = string.Format(computeServerSummaryJsonResponseFixture, serverPermUri, serverPublicUri, serverAdminPass); - - var converter = new ComputeServerPayloadConverter(); - converter.ConvertSummary(missingFixture); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertSummaryJsonPayloadMissingpublicUriToServer() - { - var serverId = "1"; - var serverPermUri = "http://www.server.com/servers/1"; - var serverAdminPass = "ABCDE"; - - var computeServerSummaryJsonResponseFixture = @"{{ - ""server"": {{ - ""security_groups"": [ - {{ - ""name"": ""default"" - }}, - {{ - ""name"": ""MyGroup"" - }} - ], - ""OS-DCF:diskConfig"": ""MANUAL"", - ""id"": ""{0}"", - ""links"": [ - {{ - ""href"": ""{1}"", - ""rel"": ""bookmark"" - }} - ], - ""adminPass"": ""{2}"" - }} - }}"; - - var missingFixture = string.Format(computeServerSummaryJsonResponseFixture, serverId, serverPermUri, serverAdminPass); - - var converter = new ComputeServerPayloadConverter(); - converter.ConvertSummary(missingFixture); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertSummaryJsonPayloadMissingPermUriToServer() - { - var serverId = "1"; - var serverPublicUri = "http://www.server.com/v2/servers/1"; - var serverAdminPass = "ABCDE"; - - var computeServerSummaryJsonResponseFixture = @"{{ - ""server"": {{ - ""security_groups"": [ - {{ - ""name"": ""default"" - }}, - {{ - ""name"": ""MyGroup"" - }} - ], - ""OS-DCF:diskConfig"": ""MANUAL"", - ""id"": ""{0}"", - ""links"": [ - {{ - ""href"": ""{1}"", - ""rel"": ""self"" - }} - ], - ""adminPass"": ""{2}"" - }} - }}"; - - var missingFixture = string.Format(computeServerSummaryJsonResponseFixture, serverId, serverPublicUri, serverAdminPass); - - var converter = new ComputeServerPayloadConverter(); - converter.ConvertSummary(missingFixture); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertSummaryJsonPayloadMissingAdminPasswordToServer() - { - var serverId = "1"; - var serverPublicUri = "http://www.server.com/v2/servers/1"; - var serverPermUri = "http://www.server.com/servers/1"; - - var computeServerSummaryJsonResponseFixture = @"{{ - ""server"": {{ - ""security_groups"": [ - {{ - ""name"": ""default"" - }}, - {{ - ""name"": ""MyGroup"" - }} - ], - ""OS-DCF:diskConfig"": ""MANUAL"", - ""id"": ""{0}"", - ""links"": [ - {{ - ""href"": ""{1}"", - ""rel"": ""self"" - }}, - {{ - ""href"": ""{2}"", - ""rel"": ""bookmark"" - }} - ] - }} - }}"; - - var missingFixture = string.Format(computeServerSummaryJsonResponseFixture, serverId, serverPermUri, serverPublicUri); - - var converter = new ComputeServerPayloadConverter(); - converter.ConvertSummary(missingFixture); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertJsonPayloadEmptyObjectToServer() - { - var emptyObjectFixture = @"{ }"; - - var converter = new ComputeServerPayloadConverter(); - converter.ConvertSummary(emptyObjectFixture); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertInvalidJsonToServer() - { - var badJsonFixture = @"{ NOT JSON"; - - var converter = new ComputeServerPayloadConverter(); - converter.ConvertSummary(badJsonFixture); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertNonObjectJsonToServer() - { - var nonObjectJson = @"[]"; - - var converter = new ComputeServerPayloadConverter(); - converter.ConvertSummary(nonObjectJson); - } - - [TestMethod] - public void CanParseValidServersJsonPayloadWithMultipleFlavors() - { - var validMultipleServersJsonFixture = @"{{ ""servers"": [ {0} ] }}"; - var firstServer = CreateServersSummaryJsonFixtrue("srv1", "1", "http://server.com/servers/1", - "http://server.com/v2/servers/1"); - var secondServer = CreateServersSummaryJsonFixtrue("srv2", "2", "http://server.com/servers/2", - "http://server.com/v2/servers/2"); - - var validMultipleServersJson = string.Format(validMultipleServersJsonFixture, - string.Join(",", new List() { firstServer, secondServer })); - - var converter = new ComputeServerPayloadConverter(); - var servers = converter.ConvertServers(validMultipleServersJson).ToList(); - - Assert.AreEqual(2, servers.Count()); - var srv1 = - servers.First(o => string.Equals(o.Name, "srv1", StringComparison.InvariantCultureIgnoreCase)); - var srv2 = - servers.First(o => string.Equals(o.Name, "srv2", StringComparison.InvariantCultureIgnoreCase)); - Assert.IsNotNull(srv1); - Assert.IsNotNull(srv2); - - Assert.AreEqual("1", srv1.Id); - Assert.AreEqual(new Uri("http://server.com/servers/1"), srv1.PermanentUri); - Assert.AreEqual(new Uri("http://server.com/v2/servers/1"), srv1.PublicUri); - - Assert.AreEqual("2", srv2.Id); - Assert.AreEqual(new Uri("http://server.com/servers/2"), srv2.PermanentUri); - Assert.AreEqual(new Uri("http://server.com/v2/servers/2"), srv2.PublicUri); - } - - [TestMethod] - public void CanConvertValidServersJsonPayloadWithSingleFlavor() - { - var validFlavorsJsonFixture = @"{{ ""servers"": [ {0} ] }}"; - var firstServer = CreateServersSummaryJsonFixtrue("myserver", "1", "http://server.com/servers/1", - "http://server.com/v2/servers/1"); - var validSingleServerPayload = string.Format(validFlavorsJsonFixture, firstServer); - - var converter = new ComputeServerPayloadConverter(); - var servers = converter.ConvertServers(validSingleServerPayload).ToList(); - - Assert.AreEqual(1, servers.Count()); - var srv1 = - servers.First(o => string.Equals(o.Name, "myserver", StringComparison.InvariantCultureIgnoreCase)); - - Assert.IsNotNull(srv1); - - Assert.AreEqual("1", srv1.Id); - Assert.AreEqual(new Uri("http://server.com/servers/1"), srv1.PermanentUri); - Assert.AreEqual(new Uri("http://server.com/v2/servers/1"), srv1.PublicUri); - } - - [TestMethod] - public void CanParseValidServersPayloadWithEmptyJsonArray() - { - var emptyJsonArray = @"{ ""servers"": [ ] }"; - - var converter = new ComputeServerPayloadConverter(); - var containers = converter.ConvertServers(emptyJsonArray).ToList(); - - Assert.AreEqual(0, containers.Count()); - } - - [TestMethod] - public void CanParseAnEmptyServersPayload() - { - var payload = string.Empty; - - var converter = new ComputeServerPayloadConverter(); - var containers = converter.ConvertServers(payload).ToList(); - - Assert.AreEqual(0, containers.Count()); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotParseANullServersPayload() - { - var converter = new ComputeServerPayloadConverter(); - converter.ConvertServers(null); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseInvalidServersJsonPayload() - { - var converter = new ComputeServerPayloadConverter(); - converter.ConvertServers("[ { \"SomeAtrib\" }]"); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseInvalidServersPayload() - { - var converter = new ComputeServerPayloadConverter(); - converter.ConvertServers("NOT JSON"); - } - } -} diff --git a/OpenStack/OpenStack.Test/Compute/ComputeServiceClientTests.cs b/OpenStack/OpenStack.Test/Compute/ComputeServiceClientTests.cs deleted file mode 100644 index 9065cac..0000000 --- a/OpenStack/OpenStack.Test/Compute/ComputeServiceClientTests.cs +++ /dev/null @@ -1,773 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Common.ServiceLocation; -using OpenStack.Compute; -using OpenStack.Identity; - -namespace OpenStack.Test.Compute -{ - [TestClass] - public class ComputeServiceClientTests - { - internal TestComputeServicePocoClient ServicePocoClient; - - internal string authId = "12345"; - internal string endpoint = "http://testcomputeendpoint.com/v2/1234567890"; - internal ServiceLocator ServiceLocator; - - [TestInitialize] - public void TestSetup() - { - this.ServicePocoClient = new TestComputeServicePocoClient(); - this.ServiceLocator = new ServiceLocator(); - - var manager = this.ServiceLocator.Locate(); - manager.RegisterServiceInstance(typeof(IComputeServicePocoClientFactory), new TestComputeServicePocoClientFactory(this.ServicePocoClient)); - } - - [TestCleanup] - public void TestCleanup() - { - this.ServicePocoClient = new TestComputeServicePocoClient(); - this.ServiceLocator = new ServiceLocator(); - } - - IOpenStackCredential GetValidCreds() - { - var catalog = new OpenStackServiceCatalog(); - catalog.Add(new OpenStackServiceDefinition("Nova", "Compute Service", - new List() - { - new OpenStackServiceEndpoint(endpoint, string.Empty, "some version", "some version info", "1,2,3") - })); - - var creds = new OpenStackCredential(new Uri(this.endpoint), "SomeUser", "Password", "SomeTenant"); - creds.SetAccessTokenId(this.authId); - creds.SetServiceCatalog(catalog); - return creds; - } - - [TestMethod] - public async Task CanGetFlavors() - { - var flv1 = new ComputeFlavor("1", "m1.tiny", "512", "2", "10", new Uri("http://someuri.com/v2/flavors/1"), - new Uri("http://someuri.com/flavors/1"), new Dictionary()); - var flv2 = new ComputeFlavor("2", "m1.small", "1024", "4", "100", new Uri("http://someuri.com/v2/flavors/2"), - new Uri("http://someuri.com/flavors/2"), new Dictionary()); - var flavors = new List() {flv1, flv2}; - - this.ServicePocoClient.GetFlavorsDelegate = () => Task.Factory.StartNew(() => (IEnumerable)flavors); - - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - var resp = await client.GetFlavors(); - Assert.IsNotNull(resp); - - var respFlavors = resp.ToList(); - Assert.AreEqual(2, respFlavors.Count()); - Assert.AreEqual(flv1, respFlavors[0]); - Assert.AreEqual(flv2, respFlavors[1]); - } - - [TestMethod] - public async Task CanGetFlavor() - { - var expectedFlavor = new ComputeFlavor("1", "m1.tiny", "512", "2", "10", new Uri("http://someuri.com/v2/flavors/1"), - new Uri("http://someuri.com/flavors/1"), new Dictionary()); - - this.ServicePocoClient.GetFlavorDelegate = (id) => - { - Assert.AreEqual("1", id); - return Task.Factory.StartNew(() => expectedFlavor); - }; - - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - var flavor = await client.GetFlavor("1"); - - Assert.IsNotNull(flavor); - Assert.AreEqual(expectedFlavor, flavor); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task GetFlavorWithNullFlavorIdThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.GetFlavor(null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task GetFlavorWithEmptyFlavorIdThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.GetFlavor(string.Empty); - } - - [TestMethod] - public async Task CanCreateServer() - { - var serverName = "MyServer"; - var imageId = "56789"; - var keyName = "MyKey"; - var flavorId = "2"; - var networkId = "98765"; - var adminPassword = "ABCDE"; - var expServer = new ComputeServer("1235", serverName, adminPassword, new Uri("http://someuri.com/v2/servers/12345"), - new Uri("http://someuri.com/servers/12345"), new Dictionary()); - - this.ServicePocoClient.CreateServerDelegate = (name, imgId, flvId, ntwId, key, groups) => - { - Assert.AreEqual(serverName, name); - Assert.AreEqual(imageId, imgId); - Assert.AreEqual(flavorId, flvId); - Assert.AreEqual(networkId, ntwId); - Assert.AreEqual(keyName, key); - Assert.IsTrue(groups.Any(g => g == "default")); - return Task.Factory.StartNew(() => expServer); - }; - - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - var server = await client.CreateServer(serverName, imageId, flavorId, networkId, keyName, new List() { "default" }); - - Assert.IsNotNull(server); - Assert.AreEqual("1235", server.Id); - Assert.AreEqual(adminPassword, server.AdminPassword); - } - - [TestMethod] - public async Task CanCreateServerWithoutKeyName() - { - var serverName = "MyServer"; - var imageId = "56789"; - var flavorId = "2"; - var networkId = "98765"; - var adminPassword = "ABCDE"; - var expServer = new ComputeServer("1235", serverName, adminPassword, new Uri("http://someuri.com/v2/servers/12345"), - new Uri("http://someuri.com/servers/12345"), new Dictionary()); - - this.ServicePocoClient.CreateServerDelegate = (name, imgId, flvId, ntwId, key, groups) => - { - Assert.AreEqual(serverName, name); - Assert.AreEqual(imageId, imgId); - Assert.AreEqual(flavorId, flvId); - Assert.AreEqual(networkId, ntwId); - Assert.AreEqual(string.Empty, key); - Assert.IsTrue(groups.Any(g => g == "default")); - return Task.Factory.StartNew(() => expServer); - }; - - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - var server = await client.CreateServer(serverName, imageId, flavorId, networkId, new List() { "default" }); - - Assert.IsNotNull(server); - Assert.AreEqual("1235", server.Id); - Assert.AreEqual(adminPassword, server.AdminPassword); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CreateServerWithNullNameThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.CreateServer(null, "12345", "2", "54321", new List() { "default" }); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CreateServerWithEmptyNameThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.CreateServer(string.Empty, "12345", "2", "54321", new List() { "default" }); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CreateServerWithNullImageIdThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.CreateServer("MyServer", null, "2", "54321", new List() { "default" }); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CreateServerWithEmptyImageIdThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.CreateServer("MyServer", string.Empty, "2", "54321", new List() { "default" }); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CreateServerWithNullFlavorIdThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.CreateServer("MyServer", "12345", null, "54321", new List() { "default" }); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CreateServerWithEmptyFlavorIdThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.CreateServer("MyServer", "12345", string.Empty, "54321", new List() { "default" }); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CreateServerWithNullNetworkIdThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.CreateServer("MyServer", "12345", "2", null, new List() { "default" }); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CreateServerWithEmptyNetworkIdThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.CreateServer("MyServer", "12345", "2", string.Empty, new List() { "default" }); - } - - [TestMethod] - public async Task CanGetServers() - { - var expServer1 = new ComputeServer("1", "srv1", - new Uri("http://testcomputeendpoint.com/v2/1234567890/servers/1"), - new Uri("http://testcomputeendpoint.com/1234567890/servers/1"), new Dictionary()); - - var expServer2 = new ComputeServer("2", "srv2", - new Uri("http://testcomputeendpoint.com/v2/1234567890/servers/1"), - new Uri("http://testcomputeendpoint.com/1234567890/servers/1"), new Dictionary()); - var servers = new List() { expServer1, expServer2 }; - - this.ServicePocoClient.GetServersDelegate = () => Task.Factory.StartNew(() => (IEnumerable)servers); - - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - var resp = await client.GetServers(); - Assert.IsNotNull(resp); - - var respFlavors = resp.ToList(); - Assert.AreEqual(2, respFlavors.Count()); - Assert.AreEqual(expServer1, respFlavors[0]); - Assert.AreEqual(expServer2, respFlavors[1]); - } - - [TestMethod] - public async Task CanGetServer() - { - var serverId = "12345"; - var expServer = new ComputeServer(serverId, "tiny", - new Uri("http://testcomputeendpoint.com/v2/1234567890/servers/1"), - new Uri("http://testcomputeendpoint.com/1234567890/servers/1"), new Dictionary()); - - this.ServicePocoClient.GetServerDelegate = (id) => - { - Assert.AreEqual(serverId, id); - return Task.Factory.StartNew(() => expServer); - }; - - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - var server = await client.GetServer(serverId); - - Assert.IsNotNull(server); - Assert.AreEqual(expServer, server); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task GetServerWithNullIdThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.GetServer(null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task GetServerWithEmptyIdThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.GetServer(string.Empty); - } - - [TestMethod] - public async Task CanDeleteServer() - { - this.ServicePocoClient.DeleteServerDelegate = async (serverId) => - { - await Task.Run(() => Assert.AreEqual(serverId, "12345")); - }; - - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.DeleteServer("12345"); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task DeleteServerWithNullServerIdThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.DeleteServer(null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task DeleteServerWithEmptyServerIdThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.DeleteServer(string.Empty); - } - - [TestMethod] - public async Task CanAssignFloatingIp() - { - this.ServicePocoClient.AssignFloatingIpDelegate = async (serverId, ipAddress) => - { - await Task.Run(() => - { - Assert.AreEqual(serverId, "12345"); - Assert.AreEqual(ipAddress, "172.0.0.1"); - }); - }; - - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.AssignFloatingIp("12345", "172.0.0.1"); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task AssignFloatingIpWithNullServerIdThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.AssignFloatingIp(null, "172.0.0.1"); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task AssignFloatingIpWithEmptyServerIdThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.AssignFloatingIp(string.Empty, "172.0.0.1"); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task AssignFloatingIpWithNullIpAddressThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.AssignFloatingIp("12345", null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task AssignFloatingIpWithEmptyIpAddressThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.AssignFloatingIp("12345", string.Empty); - } - - [TestMethod] - public async Task CanGetServerMetadata() - { - var meta = new Dictionary() { { "item1", "value1" } }; - - this.ServicePocoClient.GetServerMetadataDelegate = (id) => - { - Assert.AreEqual("12345", id); - return Task.Factory.StartNew(() => (IDictionary)meta); - }; - - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - var metadata = await client.GetServerMetadata("12345"); - - Assert.IsNotNull(metadata); - Assert.AreEqual(meta, metadata); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task GetServerMetadataWithNullImageIdThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.GetServerMetadata(null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task GetServerMetadataWithEmptyImageIdThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.GetServerMetadata(string.Empty); - } - - [TestMethod] - public async Task CanDeleteServerMetadata() - { - this.ServicePocoClient.DeleteServerMetadataDelegate = async (flavorId, key) => - { - await Task.Run(() => - { - Assert.AreEqual(flavorId, "12345"); - Assert.AreEqual(key, "item1"); - }); - }; - - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.DeleteServerMetadata("12345", "item1"); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task DeleteServerMetadataWithNullImageIdThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.DeleteServerMetadata(null, "item1"); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task DeleteServerMetadataWithEmptyImageIdThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.DeleteServerMetadata(string.Empty, "item1"); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task DeleteServerMetadataWithEmptyKeyThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.DeleteServerMetadata("12345", string.Empty); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task DeleteServerMetadataWithNullKeyThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.DeleteServerMetadata("12345", null); - } - - [TestMethod] - public async Task CanUpdateServerMetadata() - { - var metadata = new Dictionary() { { "item1", "value1" } }; - this.ServicePocoClient.UpdateServerMetadataDelegate = async (flavorId, meta) => - { - await Task.Run(() => - { - Assert.AreEqual(flavorId, "12345"); - Assert.AreEqual(metadata, meta); - }); - }; - - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.UpdateServerMetadata("12345", metadata); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task UpdateServerMetadataWithNullImageIdThrows() - { - var metadata = new Dictionary() { { "item1", "value1" } }; - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.UpdateServerMetadata(null, metadata); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task UpdateServerMetadataWithEmptyImageIdThrows() - { - var metadata = new Dictionary() { { "item1", "value1" } }; - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.UpdateServerMetadata(string.Empty, metadata); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task UpdateServerMetadataWithNullMetadataThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.UpdateServerMetadata("12345", null); - } - - [TestMethod] - public async Task CanGetImages() - { - var img1 = new ComputeImage("12345", "image1", new Uri("http://someuri.com/v2/images/12345"), new Uri("http://someuri.com/images/12345"), new Dictionary(), "active", DateTime.Now, DateTime.Now, 10, 512, 100); - var img2 = new ComputeImage("23456", "image2", new Uri("http://someuri.com/v2/images/23456"), new Uri("http://someuri.com/images/23456"), new Dictionary(), "active", DateTime.Now, DateTime.Now, 10, 512, 100); - var images = new List() { img1, img2 }; - - this.ServicePocoClient.GetImagesDelegate = () => Task.Factory.StartNew(() => (IEnumerable)images); - - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - var resp = await client.GetImages(); - Assert.IsNotNull(resp); - - var respImage = resp.ToList(); - Assert.AreEqual(2, respImage.Count()); - Assert.AreEqual(img1, respImage[0]); - Assert.AreEqual(img2, respImage[1]); - } - - [TestMethod] - public async Task CanGetImage() - { - var img1 = new ComputeImage("12345", "image1", new Uri("http://someuri.com/v2/images/12345"), new Uri("http://someuri.com/images/12345"), new Dictionary(), "active", DateTime.Now, DateTime.Now, 10, 512, 100); - - this.ServicePocoClient.GetImageDelegate = (id) => - { - Assert.AreEqual("12345", id); - return Task.Factory.StartNew(() => img1); - }; - - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - var image = await client.GetImage("12345"); - - Assert.IsNotNull(image); - Assert.AreEqual(img1, image); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task GetImageWithNullImageIdThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.GetImage(null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task GetImageWithEmptyImageIdThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.GetImage(string.Empty); - } - - [TestMethod] - public async Task CanDeleteImage() - { - this.ServicePocoClient.DeleteImageDelegate = async (imageId) => - { - await Task.Run(() => Assert.AreEqual(imageId, "12345")); - }; - - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.DeleteImage("12345"); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task DeleteImageWithNullImageIdThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.DeleteImage(null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task DeleteImageWithEmptyImageIdThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.DeleteImage(string.Empty); - } - - [TestMethod] - public async Task CanGetImageMetadata() - { - var meta = new Dictionary() { { "item1", "value1" } }; - - this.ServicePocoClient.GetImageMetadataDelegate = (id) => - { - Assert.AreEqual("12345", id); - return Task.Factory.StartNew(() => (IDictionary)meta); - }; - - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - var metadata = await client.GetImageMetadata("12345"); - - Assert.IsNotNull(metadata); - Assert.AreEqual(meta, metadata); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task GetImageMetadataWithNullImageIdThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.GetImageMetadata(null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task GetImageMetadataWithEmptyImageIdThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.GetImageMetadata(string.Empty); - } - - [TestMethod] - public async Task CanDeleteImageMetadata() - { - this.ServicePocoClient.DeleteImageMetadataDelegate = async (imageId, key) => - { - await Task.Run(() => - { - Assert.AreEqual(imageId, "12345"); - Assert.AreEqual(key, "item1"); - }); - }; - - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.DeleteImageMetadata("12345", "item1"); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task DeleteImageMetadataWithNullImageIdThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.DeleteImageMetadata(null, "item1"); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task DeleteImageMetadataWithEmptyImageIdThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.DeleteImageMetadata(string.Empty, "item1"); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task DeleteImageMetadataWithEmptyKeyThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.DeleteImageMetadata("12345", string.Empty); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task DeleteImageMetadataWithNullKeyThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.DeleteImageMetadata("12345", null); - } - - [TestMethod] - public async Task CanUpdateImageMetadata() - { - var metadata = new Dictionary() { { "item1", "value1" } }; - this.ServicePocoClient.UpdateImageMetadataDelegate = async (imageId, meta) => - { - await Task.Run(() => - { - Assert.AreEqual(imageId, "12345"); - Assert.AreEqual(metadata, meta); - }); - }; - - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.UpdateImageMetadata("12345", metadata); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task UpdateImageMetadataWithNullImageIdThrows() - { - var metadata = new Dictionary() { { "item1", "value1" } }; - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.UpdateImageMetadata(null, metadata); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task UpdateImageMetadataWithEmptyImageIdThrows() - { - var metadata = new Dictionary() { { "item1", "value1" } }; - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.UpdateImageMetadata(string.Empty, metadata); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task UpdateImageMetadataWithNullMetadataThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.UpdateImageMetadata("12345", null); - } - - [TestMethod] - public async Task CanGetKeyPairs() - { - var expKeyPair1 = new ComputeKeyPair("1", "ABCDEF","12345"); - var expKeyPair2 = new ComputeKeyPair("2", "FEDCBA", "54321"); - var pairs = new List() { expKeyPair1, expKeyPair2 }; - - this.ServicePocoClient.GetKeyPairsDelegate = () => Task.Factory.StartNew(() => (IEnumerable)pairs); - - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - var resp = await client.GetKeyPairs(); - Assert.IsNotNull(resp); - - var respPairs = resp.ToList(); - Assert.AreEqual(2, respPairs.Count()); - Assert.AreEqual(expKeyPair1, respPairs[0]); - Assert.AreEqual(expKeyPair2, respPairs[1]); - } - - [TestMethod] - public async Task CanGetKeyPair() - { - var keyName = "1"; - var expKeyPair1 = new ComputeKeyPair(keyName, "ABCDEF", "12345"); - - this.ServicePocoClient.GetKeyPairDelegate = (name) => - { - Assert.AreEqual(keyName, name); - return Task.Factory.StartNew(() => expKeyPair1); - }; - - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - var keyPair = await client.GetKeyPair(keyName); - - Assert.IsNotNull(keyPair); - Assert.AreEqual(expKeyPair1, keyPair); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task GetKeyPairWithNullNameThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.GetKeyPair(null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task GetKeyPairWithEmptyNameThrows() - { - var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator); - await client.GetKeyPair(string.Empty); - } - } -} diff --git a/OpenStack/OpenStack.Test/Compute/ComputeServicePocoClientTests.cs b/OpenStack/OpenStack.Test/Compute/ComputeServicePocoClientTests.cs deleted file mode 100644 index 2578912..0000000 --- a/OpenStack/OpenStack.Test/Compute/ComputeServicePocoClientTests.cs +++ /dev/null @@ -1,1599 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using OpenStack.Common.Http; -using OpenStack.Common.ServiceLocation; -using OpenStack.Compute; -using OpenStack.Identity; - -namespace OpenStack.Test.Compute -{ - [TestClass] - public class ComputeServicePocoClientTests - { - internal TestComputeServiceRestClient ComputeServiceRestClient; - internal string authId = "12345"; - internal Uri endpoint = new Uri("http://testcomputeendpoint.com/v1/1234567890"); - internal IServiceLocator ServiceLocator; - - [TestInitialize] - public void TestSetup() - { - this.ComputeServiceRestClient = new TestComputeServiceRestClient(); - this.ServiceLocator = new ServiceLocator(); - - var manager = this.ServiceLocator.Locate(); - manager.RegisterServiceInstance(typeof(IComputeServiceRestClientFactory), new TestComputeServiceRestClientFactory(ComputeServiceRestClient)); - } - - [TestCleanup] - public void TestCleanup() - { - this.ComputeServiceRestClient = new TestComputeServiceRestClient(); - this.ServiceLocator = new ServiceLocator(); - } - - ServiceClientContext GetValidContext() - { - var creds = new OpenStackCredential(this.endpoint, "SomeUser", "Password", "SomeTenant", "region-a.geo-1"); - creds.SetAccessTokenId(this.authId); - - return new ServiceClientContext(creds, CancellationToken.None, "Object Storage", endpoint); - } - - private string GenerateMetadataPayload(IDictionary metadata) - { - var payload = new StringBuilder(); - payload.Append("{ \"metadata\" : {"); - var isFirst = true; - - foreach (var item in metadata) - { - if (!isFirst) - { - payload.Append(","); - } - - payload.AppendFormat("\"{0}\":\"{1}\"", item.Key, item.Value); - isFirst = false; - } - - payload.Append("}}"); - return payload.ToString(); - } - - private IDictionary ParseMetadataPayload(string payload) - { - var jObj = JObject.Parse(payload); - var metaToken = jObj["metadata"]; - return JsonConvert.DeserializeObject>(metaToken.ToString()); - } - - #region Get Compute Flavor Tests - - [TestMethod] - public async Task CanGetComputeFlavorWithOkResponse() - { - var payload = @"{ - ""flavor"": { - ""name"": ""m1.tiny"", - ""id"": ""1"", - ""links"": [ - { - ""href"": ""http://someuri.com/v2/flavors/1"", - ""rel"": ""self"" - }, - { - ""href"": ""http://someuri.com/flavors/1"", - ""rel"": ""bookmark"" - } - ], - ""ram"" : 512, - ""vcpus"": 2, - ""disk"": 10 - } - }"; - - var content = TestHelper.CreateStream(payload); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.OK); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.GetFlavor("1"); - - Assert.IsNotNull(result); - Assert.AreEqual("m1.tiny", result.Name); - Assert.AreEqual("1", result.Id); - Assert.AreEqual("512", result.Ram); - Assert.AreEqual("2", result.Vcpus); - Assert.AreEqual("10", result.Disk); - Assert.AreEqual(new Uri("http://someuri.com/v2/flavors/1"), result.PublicUri); - Assert.AreEqual(new Uri("http://someuri.com/flavors/1"), result.PermanentUri); - } - - [TestMethod] - public async Task CanGetComputeFlavorWithNonAuthoritativeResponse() - { - var payload = @"{ - ""flavor"": { - ""name"": ""m1.tiny"", - ""id"": ""1"", - ""links"": [ - { - ""href"": ""http://someuri.com/v2/flavors/1"", - ""rel"": ""self"" - }, - { - ""href"": ""http://someuri.com/flavors/1"", - ""rel"": ""bookmark"" - } - ], - ""ram"" : 512, - ""vcpus"": 2, - ""disk"": 10 - } - }"; - - var content = TestHelper.CreateStream(payload); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.NonAuthoritativeInformation); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.GetFlavor("1"); - - Assert.IsNotNull(result); - Assert.AreEqual("m1.tiny", result.Name); - Assert.AreEqual("1", result.Id); - Assert.AreEqual("512", result.Ram); - Assert.AreEqual("2", result.Vcpus); - Assert.AreEqual("10", result.Disk); - Assert.AreEqual(new Uri("http://someuri.com/v2/flavors/1"), result.PublicUri); - Assert.AreEqual(new Uri("http://someuri.com/flavors/1"), result.PermanentUri); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task CannotGetComputeFlavorWithNoContent() - { - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.NoContent); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetFlavor("1"); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingAComputeFlavorAndNotAuthed() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetFlavor("1"); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingAComputeFlavorAndServerError() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetFlavor("1"); - } - - #endregion - - #region Get Compute Flavors Tests - - [TestMethod] - public async Task CanGetComputeFlavorsWithOkResponse() - { - var payload = @"{ - ""flavors"": [ - { - ""id"": ""1"", - ""links"": [ - { - ""href"": ""http://someuri.com/v2/flavors/1"", - ""rel"": ""self"" - }, - { - ""href"": ""http://someuri.com/flavors/1"", - ""rel"": ""bookmark"" - } - ], - ""name"": ""m1.tiny"" - } - ] - }"; - - var content = TestHelper.CreateStream(payload); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.OK); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.GetFlavors(); - - Assert.IsNotNull(result); - - var flavors = result.ToList(); - Assert.AreEqual(1, flavors.Count()); - - var flavor = flavors.First(); - Assert.AreEqual("m1.tiny", flavor.Name); - Assert.AreEqual("1", flavor.Id); - Assert.AreEqual(new Uri("http://someuri.com/v2/flavors/1"), flavor.PublicUri); - Assert.AreEqual(new Uri("http://someuri.com/flavors/1"), flavor.PermanentUri); - } - - [TestMethod] - public async Task CanGetComputeFlavorsWithNonAuthoritativeResponse() - { - var payload = @"{ - ""flavors"": [ - { - ""id"": ""1"", - ""links"": [ - { - ""href"": ""http://someuri.com/v2/flavors/1"", - ""rel"": ""self"" - }, - { - ""href"": ""http://someuri.com/flavors/1"", - ""rel"": ""bookmark"" - } - ], - ""name"": ""m1.tiny"" - } - ] - }"; - - var content = TestHelper.CreateStream(payload); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.NonAuthoritativeInformation); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.GetFlavors(); - - Assert.IsNotNull(result); - - var flavors = result.ToList(); - Assert.AreEqual(1, flavors.Count()); - - var flavor = flavors.First(); - Assert.AreEqual("m1.tiny", flavor.Name); - Assert.AreEqual("1", flavor.Id); - Assert.AreEqual(new Uri("http://someuri.com/v2/flavors/1"), flavor.PublicUri); - Assert.AreEqual(new Uri("http://someuri.com/flavors/1"), flavor.PermanentUri); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task CannotGetComputeFlavorsWithNoContent() - { - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.NoContent); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetFlavors(); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingAComputeFlavorsAndNotAuthed() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetFlavors(); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingAComputeFlavorsAndServerError() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetFlavors(); - } - - #endregion - - #region Get Compute Server Metadata Tests - - [TestMethod] - public async Task CanGetComputeServerMetadataWithNonAuthoritativeResponse() - { - var metadata = new Dictionary() { { "item1", "value1" }, { "item2", "value2" } }; - var content = TestHelper.CreateStream(GenerateMetadataPayload(metadata)); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.NonAuthoritativeInformation); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - var respData = await client.GetServerMetadata("1"); - - Assert.AreEqual(2, respData.Count); - Assert.AreEqual("value1", respData["item1"]); - Assert.AreEqual("value2", respData["item2"]); - } - - [TestMethod] - public async Task CanGetComputeServerMetadataWithOkResponse() - { - var metadata = new Dictionary() { { "item1", "value1" }, { "item2", "value2" } }; - var content = TestHelper.CreateStream(GenerateMetadataPayload(metadata)); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.OK); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - var respData = await client.GetServerMetadata("1"); - - Assert.AreEqual(2, respData.Count); - Assert.AreEqual("value1", respData["item1"]); - Assert.AreEqual("value2", respData["item2"]); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingComputeServerMetadataAndNotAuthed() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetServerMetadata("12345"); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingComputeServerMetadataAndServerError() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetServerMetadata("12345"); - } - - #endregion - - #region Create Compute Server Tests - - [TestMethod] - public async Task CanCreateComputeServerWithAcceptedResponse() - { - var serverId = "98765"; - var keyName = "MyKey"; - var publicUrl = "http://15.125.87.81:8774/v2/ffe683d1060449d09dac0bf9d7a371cd/servers/" + serverId; - var permUrl = "http://15.125.87.81:8774/ffe683d1060449d09dac0bf9d7a371cd/servers/" + serverId; - var adminPassword = "ABCDEF"; - var serverFixture = @"{{ - ""server"": {{ - ""security_groups"": [ - {{ - ""name"": ""default"" - }}, - {{ - ""name"": ""MyGroup"" - }} - ], - ""OS-DCF:diskConfig"": ""MANUAL"", - ""id"": ""{0}"", - ""links"": [ - {{ - ""href"": ""{1}"", - ""rel"": ""self"" - }}, - {{ - ""href"": ""{2}"", - ""rel"": ""bookmark"" - }} - ], - ""adminPass"": ""{3}"" - }} - }}"; - - var payload = string.Format(serverFixture, serverId, publicUrl, permUrl, adminPassword); - var content = TestHelper.CreateStream(payload); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.Accepted); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.CreateServer("MyServer", "12345", "1", "54321", keyName, new List() { "MyGroup" }); - - Assert.IsNotNull(result); - - Assert.AreEqual(serverId, result.Id); - Assert.AreEqual(adminPassword, result.AdminPassword); - Assert.AreEqual(new Uri(publicUrl), result.PublicUri); - Assert.AreEqual(new Uri(permUrl), result.PermanentUri); - } - - [TestMethod] - public async Task CanCreateComputeServerWithOkResponse() - { - var serverId = "98765"; - var keyName = "MyKey"; - var publicUrl = "http://15.125.87.81:8774/v2/ffe683d1060449d09dac0bf9d7a371cd/servers/" + serverId; - var permUrl = "http://15.125.87.81:8774/ffe683d1060449d09dac0bf9d7a371cd/servers/" + serverId; - var adminPassword = "ABCDEF"; - var serverFixture = @"{{ - ""server"": {{ - ""security_groups"": [ - {{ - ""name"": ""default"" - }}, - {{ - ""name"": ""MyGroup"" - }} - ], - ""OS-DCF:diskConfig"": ""MANUAL"", - ""id"": ""{0}"", - ""links"": [ - {{ - ""href"": ""{1}"", - ""rel"": ""self"" - }}, - {{ - ""href"": ""{2}"", - ""rel"": ""bookmark"" - }} - ], - ""adminPass"": ""{3}"" - }} - }}"; - - var payload = string.Format(serverFixture, serverId, publicUrl, permUrl, adminPassword); - var content = TestHelper.CreateStream(payload); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.OK); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.CreateServer("MyServer", "12345", "1", "54321", keyName, new List() { "MyGroup" }); - - Assert.IsNotNull(result); - - Assert.AreEqual(serverId, result.Id); - Assert.AreEqual(adminPassword, result.AdminPassword); - Assert.AreEqual(new Uri(publicUrl), result.PublicUri); - Assert.AreEqual(new Uri(permUrl), result.PermanentUri); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenCreatingAComputeServerAndNotAuthed() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.CreateServer("MyServer", "12345", "1", "54321", string.Empty, new List() { "MyGroup" }); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenCreatingAComputeServerAndServerError() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.CreateServer("MyServer", "12345", "1", "54321", string.Empty, new List() { "MyGroup" }); - } - - #endregion - - #region Delete Compute Server Tests - - [TestMethod] - public async Task CanDeleteComputeServerWithOkResponse() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), - HttpStatusCode.OK); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteServer("12345"); - } - - [TestMethod] - public async Task CanDeleteComputeServerWithNoContentResponse() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), - HttpStatusCode.NoContent); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteServer("12345"); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenDeletingAComputeServerAndNotAuthed() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteServer("12345"); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenDeletingAComputeServerAndServerError() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteServer("12345"); - } - - #endregion - - #region Get Compute Servers Tests - - public string ServersPayload = @"{ - ""servers"": [ - { - ""id"": ""1"", - ""links"": [ - { - ""href"": ""http://someuri.com/v2/servers/1"", - ""rel"": ""self"" - }, - { - ""href"": ""http://someuri.com/servers/1"", - ""rel"": ""bookmark"" - } - ], - ""name"": ""server1"" - } - ] - }"; - - [TestMethod] - public async Task CanGetComputeServersWithOkResponse() - { - var content = TestHelper.CreateStream(ServersPayload); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.OK); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.GetServers(); - - Assert.IsNotNull(result); - - var servers = result.ToList(); - Assert.AreEqual(1, servers.Count()); - - var server = servers.First(); - Assert.AreEqual("server1", server.Name); - Assert.AreEqual("1", server.Id); - Assert.AreEqual(new Uri("http://someuri.com/v2/servers/1"), server.PublicUri); - Assert.AreEqual(new Uri("http://someuri.com/servers/1"), server.PermanentUri); - } - - [TestMethod] - public async Task CanGetComputeServersWithNonAuthoritativeResponse() - { - var content = TestHelper.CreateStream(ServersPayload); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.NonAuthoritativeInformation); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.GetServers(); - - Assert.IsNotNull(result); - - var servers = result.ToList(); - Assert.AreEqual(1, servers.Count()); - - var server = servers.First(); - Assert.AreEqual("server1", server.Name); - Assert.AreEqual("1", server.Id); - Assert.AreEqual(new Uri("http://someuri.com/v2/servers/1"), server.PublicUri); - Assert.AreEqual(new Uri("http://someuri.com/servers/1"), server.PermanentUri); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task CannotGetComputeServersWithNoContent() - { - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.NoContent); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetServers(); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingComputeServersAndNotAuthed() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetServers(); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingComputeServersAndServerError() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetServers(); - } - - #endregion - - #region Get Compute Server Tests - - public string ServerPayload = @"{ - ""server"": { - ""status"": ""ACTIVE"", - ""updated"": ""2014-06-11T18:04:46Z"", - ""hostId"": ""bd5417ccb076908f6e0d639c37c053b0b6b9681db3464d19908dd4d9"", - ""addresses"": { - ""private"": [ - { - ""OS-EXT-IPS-MAC:mac_addr"": ""fa:16:3e:34:da:44"", - ""version"": 4, - ""addr"": ""10.0.0.2"", - ""OS-EXT-IPS:type"": ""fixed"" - }, - { - ""OS-EXT-IPS-MAC:mac_addr"": ""fa:16:3e:34:da:44"", - ""version"": 4, - ""addr"": ""172.24.4.3"", - ""OS-EXT-IPS:type"": ""floating"" - } - ] - }, - ""links"": [ - { - ""href"": ""http://someuri.com/v2/servers/1"", - ""rel"": ""self"" - }, - { - ""href"": ""http://someuri.com/servers/1"", - ""rel"": ""bookmark"" - } - ], - ""key_name"": null, - ""image"": { - ""id"": ""c650e788-3c46-4efc-bfa6-1d94a14d6405"", - ""links"": [ - { - ""href"": ""http://15.125.87.81:8774/ffe683d1060449d09dac0bf9d7a371cd/images/c650e788-3c46-4efc-bfa6-1d94a14d6405"", - ""rel"": ""bookmark"" - } - ] - }, - ""OS-EXT-STS:task_state"": null, - ""OS-EXT-STS:vm_state"": ""active"", - ""OS-SRV-USG:launched_at"": ""2014-06-11T18:04:45.000000"", - ""flavor"": { - ""id"": ""1"", - ""links"": [ - { - ""href"": ""http://15.125.87.81:8774/ffe683d1060449d09dac0bf9d7a371cd/flavors/1"", - ""rel"": ""bookmark"" - } - ] - }, - ""id"": ""1"", - ""security_groups"": [ - { - ""name"": ""MyGroup"" - }, - { - ""name"": ""default"" - } - ], - ""OS-SRV-USG:terminated_at"": null, - ""OS-EXT-AZ:availability_zone"": ""nova"", - ""user_id"": ""70d48d344b494a1cbe8adbf7c02be7b5"", - ""name"": ""wfoley1"", - ""created"": ""2014-06-11T18:04:25Z"", - ""tenant_id"": ""ffe683d1060449d09dac0bf9d7a371cd"", - ""OS-DCF:diskConfig"": ""AUTO"", - ""os-extended-volumes:volumes_attached"": [], - ""accessIPv4"": """", - ""accessIPv6"": """", - ""progress"": 0, - ""OS-EXT-STS:power_state"": 1, - ""config_drive"": """", - ""metadata"": {} - } - }"; - - [TestMethod] - public async Task CanGetComputeServerWithOkResponse() - { - var content = TestHelper.CreateStream(ServerPayload); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.OK); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.GetServer("1"); - - Assert.IsNotNull(result); - Assert.AreEqual("wfoley1", result.Name); - Assert.AreEqual("1", result.Id); - Assert.AreEqual(ComputeServerStatus.Active, result.Status); - Assert.AreEqual(0, result.Progress); - Assert.AreEqual(new Uri("http://someuri.com/v2/servers/1"), result.PublicUri); - Assert.AreEqual(new Uri("http://someuri.com/servers/1"), result.PermanentUri); - } - - [TestMethod] - public async Task CanGetComputeServerWithNonAuthoritativeResponse() - { - var content = TestHelper.CreateStream(ServerPayload); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.NonAuthoritativeInformation); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.GetServer("1"); - - Assert.IsNotNull(result); - Assert.AreEqual("wfoley1", result.Name); - Assert.AreEqual("1", result.Id); - Assert.AreEqual(ComputeServerStatus.Active, result.Status); - Assert.AreEqual(0, result.Progress); - Assert.AreEqual(new Uri("http://someuri.com/v2/servers/1"), result.PublicUri); - Assert.AreEqual(new Uri("http://someuri.com/servers/1"), result.PermanentUri); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task CannotGetComputeServerWithNoContent() - { - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.NoContent); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetServer("1"); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingAComputeServerAndNotAuthed() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetServer("1"); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingAComputeServerAndServerError() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetServer("1"); - } - - #endregion - - #region Assign Floating IP Tests - - [TestMethod] - public async Task CanAssignFloatingIpWithOkResponse() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.OK); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.AssignFloatingIp("12345", "172.0.0.1"); - } - - [TestMethod] - public async Task CanDAssignFloatingIpWithAcceptedResponse() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Accepted); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.AssignFloatingIp("12345", "172.0.0.1"); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenAssigningAFloatingIpAndNotAuthed() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.AssignFloatingIp("12345", "172.0.0.1"); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhennAssigningAFloatingIpAndServerError() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.AssignFloatingIp("12345", "172.0.0.1"); - } - - #endregion - - #region Update Compute Server Metadata Tests - - [TestMethod] - public async Task CanUpdateComputeServerMetadataWithOkResponse() - { - var metadata = new Dictionary() { { "item1", "value1" }, { "item2", "value2" } }; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.OK); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.UpdateServerMetadata("1", metadata); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenUpdatingComputeServerMetadataAndNotAuthed() - { - var metadata = new Dictionary() { { "item1", "value1" }, { "item2", "value2" } }; - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.UpdateServerMetadata("12345", metadata); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenUpdatingComputeServerMetadataAndServerError() - { - var metadata = new Dictionary() { { "item1", "value1" }, { "item2", "value2" } }; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.UpdateServerMetadata("12345", metadata); - } - - #endregion - - #region Delete Compute Server Metadata Tests - - [TestMethod] - public async Task CanDeleteComputeServerMetadataWithNoContentResponse() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.NoContent); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteServerMetadata("1", "item1"); - } - - [TestMethod] - public async Task CanDeleteComputeServerMetadataWithOkResponse() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.OK); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteServerMetadata("1", "item1"); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenDeletingComputeServerMetadataAndNotAuthed() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteServerMetadata("1", "item1"); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenDeletingComputeServerMetadataAndServerError() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteServerMetadata("1", "item1"); - } - - #endregion - - #region Get Compute Image Tests - - [TestMethod] - public async Task CanGetComputeImageWithOkResponse() - { - var created = DateTime.Parse("2014-05-30T16:56:32Z").ToUniversalTime(); - var updated = DateTime.Parse("2014-06-30T16:56:32Z").ToUniversalTime(); - var payload = @"{ - ""image"" : { - ""name"": ""image1"", - ""status"": ""ACTIVE"", - ""updated"": ""2014-06-30T16:56:32Z"", - ""created"": ""2014-05-30T16:56:32Z"", - ""minRam"": 512, - ""minDisk"": 10, - ""progress"": 100, - ""links"": [ - { - ""href"": ""http://someuri.com/v2/images/12345"", - ""rel"": ""self"" - }, - { - ""href"": ""http://someuri.com/images/12345"", - ""rel"": ""bookmark"" - } - ], - ""id"": ""12345"" - } - }"; - - var content = TestHelper.CreateStream(payload); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.OK); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.GetImage("12345"); - - Assert.IsNotNull(result); - Assert.AreEqual("image1", result.Name); - Assert.AreEqual("ACTIVE", result.Status); - Assert.AreEqual("12345", result.Id); - Assert.AreEqual(512, result.MinimumRamSize); - Assert.AreEqual(10, result.MinimumDiskSize); - Assert.AreEqual(100, result.UploadProgress); - Assert.AreEqual(created.ToLongTimeString(), result.CreateDate.ToLongTimeString()); - Assert.AreEqual(updated.ToLongTimeString(), result.LastUpdated.ToLongTimeString()); - Assert.AreEqual(new Uri("http://someuri.com/images/12345"), result.PermanentUri); - Assert.AreEqual(new Uri("http://someuri.com/v2/images/12345"), result.PublicUri); - } - - [TestMethod] - public async Task CanGetComputeImageWithNonAuthoritativeResponse() - { - var created = DateTime.Parse("2014-05-30T16:56:32Z").ToUniversalTime(); - var updated = DateTime.Parse("2014-06-30T16:56:32Z").ToUniversalTime(); - var payload = @"{ - ""image"" : { - ""name"": ""image1"", - ""status"": ""ACTIVE"", - ""updated"": ""2014-06-30T16:56:32Z"", - ""created"": ""2014-05-30T16:56:32Z"", - ""minRam"": 512, - ""minDisk"": 10, - ""progress"": 100, - ""links"": [ - { - ""href"": ""http://someuri.com/v2/images/12345"", - ""rel"": ""self"" - }, - { - ""href"": ""http://someuri.com/images/12345"", - ""rel"": ""bookmark"" - } - ], - ""id"": ""12345"" - } - }"; - - var content = TestHelper.CreateStream(payload); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.NonAuthoritativeInformation); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.GetImage("12345"); - - Assert.IsNotNull(result); - Assert.AreEqual("image1", result.Name); - Assert.AreEqual("ACTIVE", result.Status); - Assert.AreEqual("12345", result.Id); - Assert.AreEqual(512, result.MinimumRamSize); - Assert.AreEqual(10, result.MinimumDiskSize); - Assert.AreEqual(100, result.UploadProgress); - Assert.AreEqual(created.ToLongTimeString(), result.CreateDate.ToLongTimeString()); - Assert.AreEqual(updated.ToLongTimeString(), result.LastUpdated.ToLongTimeString()); - Assert.AreEqual(new Uri("http://someuri.com/images/12345"), result.PermanentUri); - Assert.AreEqual(new Uri("http://someuri.com/v2/images/12345"), result.PublicUri); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task CannotGetComputeImageWithNoContent() - { - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.NoContent); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetImage("1"); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingAComputeImageAndNotAuthed() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetImage("1"); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingAComputeImageAndServerError() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetImage("1"); - } - - #endregion - - #region Get Compute Images Tests - - [TestMethod] - public async Task CanGetComputeImagesWithOkResponse() - { - var payload = @"{ - ""images"": [ - { - ""id"": ""12345"", - ""links"": [ - { - ""href"": ""http://someuri.com/v2/images/12345"", - ""rel"": ""self"" - }, - { - ""href"": ""http://someuri.com/images/12345"", - ""rel"": ""bookmark"" - } - ], - ""name"": ""image1"" - } - ] - }"; - - var content = TestHelper.CreateStream(payload); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.OK); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.GetImages(); - - Assert.IsNotNull(result); - - var images = result.ToList(); - Assert.AreEqual(1, images.Count()); - - var image = images.First(); - Assert.AreEqual("image1", image.Name); - Assert.AreEqual("12345", image.Id); - Assert.AreEqual(new Uri("http://someuri.com/v2/images/12345"), image.PublicUri); - Assert.AreEqual(new Uri("http://someuri.com/images/12345"), image.PermanentUri); - } - - [TestMethod] - public async Task CanGetComputeImagesWithNonAuthoritativeResponse() - { - var payload = @"{ - ""images"": [ - { - ""id"": ""12345"", - ""links"": [ - { - ""href"": ""http://someuri.com/v2/images/12345"", - ""rel"": ""self"" - }, - { - ""href"": ""http://someuri.com/images/12345"", - ""rel"": ""bookmark"" - } - ], - ""name"": ""image1"" - } - ] - }"; - - var content = TestHelper.CreateStream(payload); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.NonAuthoritativeInformation); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.GetImages(); - - Assert.IsNotNull(result); - - var images = result.ToList(); - Assert.AreEqual(1, images.Count()); - - var image = images.First(); - Assert.AreEqual("image1", image.Name); - Assert.AreEqual("12345", image.Id); - Assert.AreEqual(new Uri("http://someuri.com/v2/images/12345"), image.PublicUri); - Assert.AreEqual(new Uri("http://someuri.com/images/12345"), image.PermanentUri); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task CannotGetComputeImagesWithNoContent() - { - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.NoContent); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetImages(); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingAComputeImagesAndNotAuthed() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetImages(); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingAComputeImagesAndServerError() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetImages(); - } - - #endregion - - #region Delete Compute Image Tests - - [TestMethod] - public async Task CanDeleteComputeImageWithNoContentResponse() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.NoContent); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteImage("12345"); - } - - [TestMethod] - public async Task CanDeleteComputeImageWithOkResponse() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.OK); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteImage("12345"); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenDeletingAComputeImageAndNotAuthed() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteImage("12345"); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenDeletingAComputeImageAndServerError() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteImage("12345"); - } - - #endregion - - #region Get Compute Image Metadata Tests - - [TestMethod] - public async Task CanGetComputeImageMetadataWithNonAuthoritativeResponse() - { - var metadata = new Dictionary() { { "item1", "value1" }, { "item2", "value2" } }; - var content = TestHelper.CreateStream(GenerateMetadataPayload(metadata)); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.NonAuthoritativeInformation); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - var respData = await client.GetImageMetadata("12345"); - - Assert.AreEqual(2, respData.Count); - Assert.AreEqual("value1", respData["item1"]); - Assert.AreEqual("value2", respData["item2"]); - } - - [TestMethod] - public async Task CanGetComputeImageMetadataWithOkResponse() - { - var metadata = new Dictionary() { { "item1", "value1" }, { "item2", "value2" } }; - var content = TestHelper.CreateStream(GenerateMetadataPayload(metadata)); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.OK); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - var respData = await client.GetImageMetadata("12345"); - - Assert.AreEqual(2, respData.Count); - Assert.AreEqual("value1", respData["item1"]); - Assert.AreEqual("value2", respData["item2"]); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingComputeImageMetadataAndNotAuthed() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetImageMetadata("12345"); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingComputeImageMetadataAndServerError() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetImageMetadata("12345"); - } - - #endregion - - #region Update Compute Image Metadata Tests - - [TestMethod] - public async Task CanUpdateComputeImageMetadataWithOkResponse() - { - var metadata = new Dictionary() { { "item1", "value1" }, { "item2", "value2" } }; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.OK); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.UpdateImageMetadata("12345", metadata); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenUpdatingComputeImageMetadataAndNotAuthed() - { - var metadata = new Dictionary() { { "item1", "value1" }, { "item2", "value2" } }; - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.UpdateImageMetadata("12345", metadata); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenUpdatingComputeImageMetadataAndServerError() - { - var metadata = new Dictionary() { { "item1", "value1" }, { "item2", "value2" } }; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.UpdateImageMetadata("12345", metadata); - } - - #endregion - - #region Delete Compute Image Metadata Tests - - [TestMethod] - public async Task CanDeleteComputeImageMetadataWithNoContentResponse() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.NoContent); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteImageMetadata("12345", "item1"); - } - - [TestMethod] - public async Task CanDeleteComputeImageMetadataWithOkResponse() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.OK); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteImageMetadata("1", "item1"); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenDeletingComputeImageMetadataAndNotAuthed() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteImageMetadata("1", "item1"); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenDeletingComputeImageMetadataAndServerError() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteImageMetadata("1", "item1"); - } - - #endregion - - #region Get Compute Key Pairs Tests - - public string KeyPairsPayload = @"{ - ""keypairs"": [ - { - ""keypair"": { - ""public_key"": ""ABCDEF"", - ""name"": ""MyKey"", - ""fingerprint"": ""12345"" - } - } - ] - }"; - - [TestMethod] - public async Task CanGetComputeKeyPairsWithOkResponse() - { - var content = TestHelper.CreateStream(KeyPairsPayload); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.OK); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.GetKeyPairs(); - - Assert.IsNotNull(result); - - var pairs = result.ToList(); - Assert.AreEqual(1, pairs.Count()); - - var keyPair = pairs.First(); - Assert.AreEqual("MyKey", keyPair.Name); - Assert.AreEqual("ABCDEF", keyPair.PublicKey); - Assert.AreEqual("12345", keyPair.Fingerprint); - } - - [TestMethod] - public async Task CanGetComputeKeyPairsWithNonAuthoritativeResponse() - { - var content = TestHelper.CreateStream(KeyPairsPayload); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.NonAuthoritativeInformation); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.GetKeyPairs(); - - Assert.IsNotNull(result); - - var pairs = result.ToList(); - Assert.AreEqual(1, pairs.Count()); - - var keyPair = pairs.First(); - Assert.AreEqual("MyKey", keyPair.Name); - Assert.AreEqual("ABCDEF", keyPair.PublicKey); - Assert.AreEqual("12345", keyPair.Fingerprint); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task CannotGetComputeKeyPairsWithNoContent() - { - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.NoContent); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetKeyPairs(); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingComputeKeyPairsAndNotAuthed() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetKeyPairs(); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingComputeKeyPairsAndServerError() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetKeyPairs(); - } - - #endregion - - #region Get Compute Key Pair Tests - - public string KeyPairPayload = @"{ - ""keypair"": { - ""public_key"": ""ABCDEF"", - ""user_id"": ""70d48d344b494a1cbe8adbf7c02be7b5"", - ""name"": ""MyKey"", - ""deleted"": false, - ""created_at"": ""2014-08-11T21:15:53.000000"", - ""updated_at"": null, - ""fingerprint"": ""12345"", - ""deleted_at"": null, - ""id"": 1 - } - }"; - - [TestMethod] - public async Task CanGetComputeKeyPairWithOkResponse() - { - var content = TestHelper.CreateStream(KeyPairPayload); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.OK); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - var keyPair = await client.GetKeyPair("MyKey"); - - Assert.IsNotNull(keyPair); - Assert.AreEqual("MyKey", keyPair.Name); - Assert.AreEqual("ABCDEF", keyPair.PublicKey); - Assert.AreEqual("12345", keyPair.Fingerprint); - } - - [TestMethod] - public async Task CanGetComputeKeyPairWithNonAuthoritativeResponse() - { - var content = TestHelper.CreateStream(KeyPairPayload); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.NonAuthoritativeInformation); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - var keyPair = await client.GetKeyPair("MyKey"); - - Assert.IsNotNull(keyPair); - Assert.AreEqual("MyKey", keyPair.Name); - Assert.AreEqual("ABCDEF", keyPair.PublicKey); - Assert.AreEqual("12345", keyPair.Fingerprint); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task CannotGetComputeKeyPairWithNoContent() - { - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.NoContent); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetKeyPair("1"); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingAComputeKeyPairAndNotAuthed() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetKeyPair("1"); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingAComputeKeyPairAndServerError() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.ComputeServiceRestClient.Responses.Enqueue(restResp); - - var client = new ComputeServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetKeyPair("1"); - } - - #endregion - } -} diff --git a/OpenStack/OpenStack.Test/Compute/ComputeServiceRestClientTests.cs b/OpenStack/OpenStack.Test/Compute/ComputeServiceRestClientTests.cs deleted file mode 100644 index 5416531..0000000 --- a/OpenStack/OpenStack.Test/Compute/ComputeServiceRestClientTests.cs +++ /dev/null @@ -1,1134 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Newtonsoft.Json.Linq; -using OpenStack.Common.Http; -using OpenStack.Common.ServiceLocation; -using OpenStack.Compute; -using OpenStack.Identity; - -namespace OpenStack.Test.Compute -{ - [TestClass] - public class ComputeServiceRestClientTests - { - internal ComputeRestSimulator simulator; - internal string authId = "12345"; - internal Uri endpoint = new Uri("http://testcomputeendpoint.com/v2/1234567890"); - internal IServiceLocator ServiceLocator; - - [TestInitialize] - public void TestSetup() - { - this.simulator = new ComputeRestSimulator(); - this.ServiceLocator = new ServiceLocator(); - - var manager = this.ServiceLocator.Locate(); - manager.RegisterServiceInstance(typeof(IHttpAbstractionClientFactory), new ComputeRestSimulatorFactory(simulator)); - } - - [TestCleanup] - public void TestCleanup() - { - this.simulator = new ComputeRestSimulator(); - this.ServiceLocator = new ServiceLocator(); - } - - ServiceClientContext GetValidContext() - { - return GetValidContext(CancellationToken.None); - } - - ServiceClientContext GetValidContext(CancellationToken token) - { - var creds = new OpenStackCredential(this.endpoint, "SomeUser", "Password", "SomeTenant", "region-a.geo-1"); - creds.SetAccessTokenId(this.authId); - - return new ServiceClientContext(creds, token, "Nova", endpoint); - } - - #region Get Flavors Test - - [TestMethod] - public async Task GetComputeFlavorsIncludesAuthHeader() - { - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetFlavors(); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task GetComputeFlavorsFormsCorrectUrlAndMethod() - { - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetFlavors(); - - Assert.AreEqual(string.Format("{0}/flavors", endpoint), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Get, this.simulator.Method); - } - - [TestMethod] - public async Task CanGetFlavors() - { - this.simulator.Flavors.Add(new ComputeFlavor("1", "tiny", "4", "2", "10", new Uri("http://testcomputeendpoint.com/v2/1234567890/flavors/1"), new Uri("http://testcomputeendpoint.com/1234567890/flavors/1"), new Dictionary())); - - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetFlavors(); - - Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); - - var respContent = TestHelper.GetStringFromStream(resp.Content); - Assert.IsTrue(respContent.Length > 0); - } - - #endregion - - #region Get Flavor Test - - [TestMethod] - public async Task GetComputeFlavorIncludesAuthHeader() - { - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetFlavor("1"); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task GetComputeFlavorFormsCorrectUrlAndMethod() - { - var flavorId = "1"; - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetFlavor(flavorId); - - Assert.AreEqual(string.Format("{0}/flavors/{1}", endpoint, flavorId), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Get, this.simulator.Method); - } - - [TestMethod] - public async Task CanGetFlavor() - { - var flavorId = "1"; - this.simulator.Flavors.Add(new ComputeFlavor(flavorId, "tiny", "4", "2", "10", new Uri("http://testcomputeendpoint.com/v2/1234567890/flavors/1"), new Uri("http://testcomputeendpoint.com/1234567890/flavors/1"), new Dictionary())); - - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetFlavor(flavorId); - - Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); - - var respContent = TestHelper.GetStringFromStream(resp.Content); - Assert.IsTrue(respContent.Length > 0); - } - - #endregion - - #region Get Server Metadata Test - - [TestMethod] - public async Task GetComputeServerMetadataIncludesAuthHeader() - { - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetServerMetadata("12345"); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task GetComputeServerMetadataFormsCorrectUrlAndMethod() - { - var serverId = "12345"; - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetServerMetadata(serverId); - - Assert.AreEqual(string.Format("{0}/servers/{1}/metadata", endpoint, serverId), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Get, this.simulator.Method); - } - - [TestMethod] - public async Task CanGetServerMetadata() - { - var metadata = new Dictionary() { { "item1", "value1" }, { "item2", "value2" } }; - var serverId = "1"; - this.simulator.Servers.Add(new ComputeServer(serverId, "tiny", - new Uri("http://testcomputeendpoint.com/v2/1234567890/servers/1"), - new Uri("http://testcomputeendpoint.com/1234567890/servers/1"), metadata)); - - var client = new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetServerMetadata(serverId); - - Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); - - var respContent = TestHelper.GetStringFromStream(resp.Content); - Assert.IsTrue(respContent.Length > 0); - - var jObj = JObject.Parse(respContent); - var metaToken = jObj["metadata"]; - Assert.IsNotNull(metaToken); - - var item1 = metaToken["item1"]; - Assert.IsNotNull(item1); - Assert.AreEqual("value1", item1.Value()); - - var item2 = metaToken["item2"]; - Assert.IsNotNull(item2); - Assert.AreEqual("value2", item2.Value()); - } - - #endregion - - #region Create Server Test - - [TestMethod] - public async Task CreateComputeServerIncludesAuthHeader() - { - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.CreateServer("MyServer", "1245", "2", "54321", "key", new List() { "MyGroup" }); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task CreateComputeServerIncludesContentTypeHeader() - { - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.CreateServer("MyServer", "1245", "2", "54321", "key", new List() { "MyGroup" }); - - Assert.IsTrue(this.simulator.ContentType != string.Empty); - Assert.AreEqual("application/json", this.simulator.ContentType); - } - - [TestMethod] - public async Task CreateComputeServerFormsCorrectUrlAndMethod() - { - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.CreateServer("MyServer", "1245", "2", "54321", "key", new List() { "MyGroup" }); - - Assert.AreEqual(string.Format("{0}/servers", endpoint), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Post, this.simulator.Method); - } - - [TestMethod] - public async Task CanCreateComputeServer() - { - - var srvName = "MyServer"; - - var client = new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.CreateServer(srvName, "1245", "2", "54321", string.Empty, new List() { "MyGroup" }); - - Assert.AreEqual(HttpStatusCode.Accepted, resp.StatusCode); - - var respContent = TestHelper.GetStringFromStream(resp.Content); - Assert.IsTrue(respContent.Length > 0); - - Assert.IsTrue(this.simulator.Servers.Count == 1); - - var resSrv = this.simulator.Servers.First(); - Assert.AreEqual(srvName, resSrv.Name); - } - - [TestMethod] - public async Task CanCreateComputeServerWithKeyName() - { - - var srvName = "MyServer"; - var keyName = "MyKey"; - - var client = new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.CreateServer(srvName, "1245", "2", "54321", keyName, new List() { "MyGroup" }); - - Assert.AreEqual(HttpStatusCode.Accepted, resp.StatusCode); - - var respContent = TestHelper.GetStringFromStream(resp.Content); - Assert.IsTrue(respContent.Length > 0); - - Assert.IsTrue(this.simulator.Servers.Count == 1); - - var resSrv = this.simulator.Servers.First(); - Assert.AreEqual(srvName, resSrv.Name); - } - - [TestMethod] - public async Task CreateComputeServerWithKeyNameFormsCorrectBody() - { - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - var serverName = "MyServer"; - var keyName = "MyKey"; - var imageId = "12345"; - var flavorId = "2"; - var networkId = "54321"; - var secGroupName = "MyGroup"; - - await client.CreateServer(serverName, imageId, flavorId, networkId, keyName, new List() { secGroupName }); - - this.simulator.Content.Position = 0; - var reqContent = TestHelper.GetStringFromStream(this.simulator.Content); - - var srvObj = JObject.Parse(reqContent); - Assert.IsNotNull(srvObj["server"]); - Assert.IsNotNull(srvObj["server"]["name"]); - Assert.AreEqual(serverName, (string)srvObj["server"]["name"]); - - Assert.IsNotNull(srvObj["server"]["imageRef"]); - Assert.AreEqual(imageId, (string)srvObj["server"]["imageRef"]); - - Assert.IsNotNull(srvObj["server"]["flavorRef"]); - Assert.AreEqual(flavorId, (string)srvObj["server"]["flavorRef"]); - - Assert.IsNotNull(srvObj["server"]["max_count"]); - Assert.AreEqual(1, (int)srvObj["server"]["max_count"]); - - Assert.IsNotNull(srvObj["server"]["min_count"]); - Assert.AreEqual(1, (int)srvObj["server"]["min_count"]); - - Assert.IsNotNull(srvObj["server"]["key_name"]); - Assert.AreEqual(keyName, (string)srvObj["server"]["key_name"]); - - Assert.IsNotNull(srvObj["server"]["networks"]); - Assert.IsNotNull(srvObj["server"]["networks"][0]); - Assert.IsNotNull(srvObj["server"]["networks"][0]["uuid"]); - Assert.AreEqual(networkId, (string)srvObj["server"]["networks"][0]["uuid"]); - - Assert.IsNotNull(srvObj["server"]["security_groups"]); - Assert.IsNotNull(srvObj["server"]["security_groups"][0]); - Assert.IsNotNull(srvObj["server"]["security_groups"][0]["name"]); - Assert.AreEqual(secGroupName, (string)srvObj["server"]["security_groups"][0]["name"]); - } - - [TestMethod] - public async Task CreateComputeServerFormsCorrectBody() - { - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - var serverName = "MyServer"; - var imageId = "12345"; - var flavorId = "2"; - var networkId = "54321"; - var secGroupName = "MyGroup"; - - await client.CreateServer(serverName, imageId, flavorId, networkId, string.Empty, new List() { secGroupName }); - - this.simulator.Content.Position = 0; - var reqContent = TestHelper.GetStringFromStream(this.simulator.Content); - - var srvObj = JObject.Parse(reqContent); - Assert.IsNotNull(srvObj["server"]); - Assert.IsNotNull(srvObj["server"]["name"]); - Assert.AreEqual(serverName, (string)srvObj["server"]["name"]); - - Assert.IsNotNull(srvObj["server"]["imageRef"]); - Assert.AreEqual(imageId, (string)srvObj["server"]["imageRef"]); - - Assert.IsNotNull(srvObj["server"]["flavorRef"]); - Assert.AreEqual(flavorId, (string)srvObj["server"]["flavorRef"]); - - Assert.IsNotNull(srvObj["server"]["max_count"]); - Assert.AreEqual(1, (int)srvObj["server"]["max_count"]); - - Assert.IsNotNull(srvObj["server"]["min_count"]); - Assert.AreEqual(1, (int)srvObj["server"]["min_count"]); - - Assert.IsNotNull(srvObj["server"]["networks"]); - Assert.IsNotNull(srvObj["server"]["networks"][0]); - Assert.IsNotNull(srvObj["server"]["networks"][0]["uuid"]); - Assert.AreEqual(networkId, (string)srvObj["server"]["networks"][0]["uuid"]); - - Assert.IsNotNull(srvObj["server"]["security_groups"]); - Assert.IsNotNull(srvObj["server"]["security_groups"][0]); - Assert.IsNotNull(srvObj["server"]["security_groups"][0]["name"]); - Assert.AreEqual(secGroupName, (string)srvObj["server"]["security_groups"][0]["name"]); - } - - #endregion - - #region Get Servers Test - - [TestMethod] - public async Task GetComputeServersIncludesAuthHeader() - { - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetServers(); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task GetComputeServersFormsCorrectUrlAndMethod() - { - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetServers(); - - Assert.AreEqual(string.Format("{0}/servers", endpoint), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Get, this.simulator.Method); - } - - [TestMethod] - public async Task CanGetServers() - { - var serverId = "12345"; - var server = new ComputeServer(serverId, "tiny", - new Uri("http://testcomputeendpoint.com/v2/1234567890/servers/1"), - new Uri("http://testcomputeendpoint.com/1234567890/servers/1"), new Dictionary()); - this.simulator.Servers.Add(server); - - var client = new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetServers(); - - Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); - - var respContent = TestHelper.GetStringFromStream(resp.Content); - Assert.IsTrue(respContent.Length > 0); - } - - #endregion - - #region Get Server Test - - [TestMethod] - public async Task GetComputeServerIncludesAuthHeader() - { - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetServer("12345"); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task GetComputeServerFormsCorrectUrlAndMethod() - { - var serverId = "1"; - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetServer(serverId); - - Assert.AreEqual(string.Format("{0}/servers/{1}", endpoint, serverId), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Get, this.simulator.Method); - } - - [TestMethod] - public async Task CanGetServer() - { - var serverId = "12345"; - var server = new ComputeServer(serverId, "tiny", - new Uri("http://testcomputeendpoint.com/v2/1234567890/servers/1"), - new Uri("http://testcomputeendpoint.com/1234567890/servers/1"), new Dictionary()); - this.simulator.Servers.Add(server); - - var client = new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetServer(serverId); - Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); - - var respContent = TestHelper.GetStringFromStream(resp.Content); - Assert.IsTrue(respContent.Length > 0); - } - - #endregion - - #region Assign Floating Ip Test - - [TestMethod] - public async Task AssignFloatingIpIncludesAuthHeader() - { - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.AssignFloatingIp("12345", "172.0.0.1"); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task AssignFloatingIpIncludesContentTypeHeader() - { - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.AssignFloatingIp("12345", "172.0.0.1"); - - Assert.IsTrue(this.simulator.ContentType != string.Empty); - Assert.AreEqual("application/json", this.simulator.ContentType); - } - - [TestMethod] - public async Task AssignFloatingIpFormsCorrectUrlAndMethod() - { - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - var serverId = "12345"; - await client.AssignFloatingIp(serverId, "172.0.0.1"); - - Assert.AreEqual(string.Format("{0}/servers/{1}/action", endpoint, serverId), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Post, this.simulator.Method); - } - - [TestMethod] - public async Task CanAssignFloatingIp() - { - var serverId = "12345"; - var server = new ComputeServer(serverId, "tiny", - new Uri("http://testcomputeendpoint.com/v2/1234567890/servers/1"), - new Uri("http://testcomputeendpoint.com/1234567890/servers/1"), new Dictionary()); - this.simulator.Servers.Add(server); - var client = new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.AssignFloatingIp(serverId, "172.0.0.1"); - - Assert.AreEqual(HttpStatusCode.Accepted, resp.StatusCode); - } - - [TestMethod] - public async Task AssignFloatingIpFormsCorrectBody() - { - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - var serverId = "12345"; - var ipAddress = "172.0.0.1"; - - await client.AssignFloatingIp(serverId, ipAddress); - - this.simulator.Content.Position = 0; - var reqContent = TestHelper.GetStringFromStream(this.simulator.Content); - - var body = JObject.Parse(reqContent); - Assert.IsNotNull(body["addFloatingIp"]); - Assert.IsNotNull(body["addFloatingIp"]["address"]); - Assert.AreEqual(ipAddress, (string)body["addFloatingIp"]["address"]); - } - - #endregion - - #region Delete Server Test - - [TestMethod] - public async Task DeleteComputeServerIncludesAuthHeader() - { - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.DeleteServer("12345"); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task DeleteComputeServerFormsCorrectUrlAndMethod() - { - var serverId = "1"; - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.DeleteServer(serverId); - - Assert.AreEqual(string.Format("{0}/servers/{1}", endpoint, serverId), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Delete, this.simulator.Method); - } - - [TestMethod] - public async Task CanDeleteServer() - { - var serverId = "12345"; - var server = new ComputeServer(serverId, "tiny", - new Uri("http://testcomputeendpoint.com/v2/1234567890/servers/1"), - new Uri("http://testcomputeendpoint.com/1234567890/servers/1"), new Dictionary()); - this.simulator.Servers.Add(server); - - var client = new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.DeleteServer(serverId); - - Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); - Assert.AreEqual(0, this.simulator.Servers.Count); - } - - #endregion - - #region Update Server Metadata Test - - [TestMethod] - public async Task UpdateComputeServerMetadataIncludesAuthHeader() - { - var metadata = new Dictionary() { { "item1", "value1" }, { "item2", "value2" } }; - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.UpdateServerMetadata("1", metadata); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task UpdateComputeServerMetadataFormsCorrectUrlAndMethod() - { - var metadata = new Dictionary() { { "item1", "value1" }, { "item2", "value2" } }; - var serverId = "1"; - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.UpdateServerMetadata(serverId, metadata); - - Assert.AreEqual(string.Format("{0}/servers/{1}/metadata", endpoint, serverId), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Post, this.simulator.Method); - } - - [TestMethod] - public async Task CanUpdateServerMetadata() - { - var metadata = new Dictionary() { { "item1", "value1" }, { "item2", "value2" } }; - var serverId = "1"; - var server = new ComputeServer(serverId, "tiny", - new Uri("http://testcomputeendpoint.com/v2/1234567890/servers/1"), - new Uri("http://testcomputeendpoint.com/1234567890/servers/1"), new Dictionary()); - this.simulator.Servers.Add(server); - - var client = new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.UpdateServerMetadata(serverId, metadata); - - Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); - - Assert.AreEqual(2, server.Metadata.Count); - Assert.AreEqual("value1", server.Metadata["item1"]); - Assert.AreEqual("value2", server.Metadata["item2"]); - } - - #endregion - - #region Delete Server Metadata Test - - [TestMethod] - public async Task DeleteComputeServerMetadataIncludesAuthHeader() - { - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.DeleteServerMetadata("1", "item1"); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task DeleteComputeServerMetadataFormsCorrectUrlAndMethod() - { - var serverId = "1"; - var key = "item1"; - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.DeleteServerMetadata(serverId, key); - - Assert.AreEqual(string.Format("{0}/servers/{1}/metadata/{2}", endpoint, serverId, key), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Delete, this.simulator.Method); - } - - [TestMethod] - public async Task CanDeleteServerMetadata() - { - var metadata = new Dictionary() { { "item1", "value1" }, { "item2", "value2" } }; - var serverId = "1"; - var server = new ComputeServer(serverId, "tiny", - new Uri("http://testcomputeendpoint.com/v2/1234567890/servers/1"), - new Uri("http://testcomputeendpoint.com/1234567890/servers/1"), metadata); - this.simulator.Servers.Add(server); - - var client = new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.DeleteServerMetadata(serverId, "item1"); - - Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); - - Assert.AreEqual(1, server.Metadata.Count); - Assert.AreEqual("value2", server.Metadata["item2"]); - } - - #endregion - - #region Get Images Test - - [TestMethod] - public async Task GetComputeImagesIncludesAuthHeader() - { - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetImages(); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task GetComputeImagesFormsCorrectUrlAndMethod() - { - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetImages(); - - Assert.AreEqual(string.Format("{0}/images/detail", endpoint), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Get, this.simulator.Method); - } - - [TestMethod] - public async Task CanGetImages() - { - var created = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(10)); - var updated = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(1)); - this.simulator.Images.Add(new ComputeImage("1", "tiny", - new Uri("http://testcomputeendpoint.com/v2/1234567890/flavors/1"), - new Uri("http://testcomputeendpoint.com/1234567890/flavors/1"), new Dictionary(), "ACTIVE", created, updated, 10, 512, 100)); - - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetImages(); - - Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); - - var respContent = TestHelper.GetStringFromStream(resp.Content); - Assert.IsTrue(respContent.Length > 0); - } - - #endregion - - #region Get Image Test - - [TestMethod] - public async Task GetComputeImageIncludesAuthHeader() - { - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetImage("12345"); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task GetComputeImageFormsCorrectUrlAndMethod() - { - var imageId = "12345"; - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetImage(imageId); - - Assert.AreEqual(string.Format("{0}/images/{1}", endpoint, imageId), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Get, this.simulator.Method); - } - - [TestMethod] - public async Task CanGetImage() - { - var imageId = "12345"; - var created = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(10)); - var updated = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(1)); - this.simulator.Images.Add(new ComputeImage(imageId, "tiny", - new Uri("http://testcomputeendpoint.com/v2/1234567890/flavors/1"), - new Uri("http://testcomputeendpoint.com/1234567890/flavors/1"), new Dictionary(), "ACTIVE", created, updated, 10, 512, 100)); - - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetImage(imageId); - - Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); - - var respContent = TestHelper.GetStringFromStream(resp.Content); - Assert.IsTrue(respContent.Length > 0); - } - - #endregion - - #region Delete Image Test - - [TestMethod] - public async Task DeleteComputeImageIncludesAuthHeader() - { - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.DeleteImage("12345"); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task DeleteComputeImageFormsCorrectUrlAndMethod() - { - var imageId = "12345"; - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.DeleteImage(imageId); - - Assert.AreEqual(string.Format("{0}/images/{1}", endpoint, imageId), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Delete, this.simulator.Method); - } - - [TestMethod] - public async Task CanDeleteImage() - { - var imageId = "12345"; - var created = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(10)); - var updated = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(1)); - this.simulator.Images.Add(new ComputeImage(imageId, "tiny", - new Uri("http://testcomputeendpoint.com/v2/1234567890/flavors/1"), - new Uri("http://testcomputeendpoint.com/1234567890/flavors/1"), new Dictionary(), "ACTIVE", created, updated, 10, 512, 100)); - - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.DeleteImage(imageId); - - Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); - Assert.IsFalse(this.simulator.Images.Any()); - } - - #endregion - - #region Get Image Metadata Test - - [TestMethod] - public async Task GetComputeImageMetadataIncludesAuthHeader() - { - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetImageMetadata("12345"); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task GetComputeImageMetadataFormsCorrectUrlAndMethod() - { - var imageId = "12345"; - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetImageMetadata(imageId); - - Assert.AreEqual(string.Format("{0}/images/{1}/metadata", endpoint, imageId), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Get, this.simulator.Method); - } - - [TestMethod] - public async Task CanGetImageMetadata() - { - var imageId = "12345"; - var created = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(10)); - var updated = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(1)); - var metadata = new Dictionary() { { "item1", "value1" }, { "item2", "value2" } }; - this.simulator.Images.Add(new ComputeImage(imageId, "tiny", - new Uri("http://testcomputeendpoint.com/v2/1234567890/flavors/1"), - new Uri("http://testcomputeendpoint.com/1234567890/flavors/1"), metadata, "ACTIVE", created, updated, 10, 512, 100)); - - var client = new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetImageMetadata(imageId); - - Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); - - var respContent = TestHelper.GetStringFromStream(resp.Content); - Assert.IsTrue(respContent.Length > 0); - - var jObj = JObject.Parse(respContent); - var metaToken = jObj["metadata"]; - Assert.IsNotNull(metaToken); - - var item1 = metaToken["item1"]; - Assert.IsNotNull(item1); - Assert.AreEqual("value1",item1.Value()); - - var item2 = metaToken["item2"]; - Assert.IsNotNull(item2); - Assert.AreEqual("value2", item2.Value()); - } - - #endregion - - #region Update Image Metadata Test - - [TestMethod] - public async Task UpdateComputeImageMetadataIncludesAuthHeader() - { - var metadata = new Dictionary() { { "item1", "value1" }, { "item2", "value2" } }; - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.UpdateImageMetadata("12345", metadata); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task UpdateComputeImageMetadataFormsCorrectUrlAndMethod() - { - var metadata = new Dictionary() { { "item1", "value1" }, { "item2", "value2" } }; - var imageId = "12345"; - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.UpdateImageMetadata(imageId, metadata); - - Assert.AreEqual(string.Format("{0}/images/{1}/metadata", endpoint, imageId), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Post, this.simulator.Method); - } - - [TestMethod] - public async Task UpdateComputeImageMetadataSetsCorrectContentType() - { - var metadata = new Dictionary() { { "item1", "value1" }, { "item2", "value2" } }; - var imageId = "12345"; - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.UpdateImageMetadata(imageId, metadata); - - Assert.AreEqual("application/json",this.simulator.ContentType); - } - - [TestMethod] - public async Task CanUpdateImageMetadata() - { - var imageId = "12345"; - var created = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(10)); - var updated = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(1)); - var metadata = new Dictionary() { { "item1", "value1" }, { "item2", "value2" } }; - var image = new ComputeImage(imageId, "tiny", - new Uri("http://testcomputeendpoint.com/v2/1234567890/images/12345"), - new Uri("http://testcomputeendpoint.com/1234567890/images/12345"), new Dictionary(), - "ACTIVE", created, updated, 10, 512, 100); - this.simulator.Images.Add(image); - - var client = new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.UpdateImageMetadata(imageId, metadata); - - Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); - - Assert.AreEqual(2,image.Metadata.Count); - Assert.AreEqual("value1",image.Metadata["item1"]); - Assert.AreEqual("value2", image.Metadata["item2"]); - } - - #endregion - - #region Delete Image Metadata Test - - [TestMethod] - public async Task DeleteComputeImageMetadataIncludesAuthHeader() - { - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.DeleteImageMetadata("12345", "item1"); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task DeleteComputeImageMetadataFormsCorrectUrlAndMethod() - { - var imageId = "12345"; - var key = "item1"; - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.DeleteImageMetadata(imageId, key); - - Assert.AreEqual(string.Format("{0}/images/{1}/metadata/{2}", endpoint, imageId, key), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Delete, this.simulator.Method); - } - - [TestMethod] - public async Task CanDeleteImageMetadata() - { - var metadata = new Dictionary() { { "item1", "value1" }, { "item2", "value2" } }; - var created = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(10)); - var updated = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(1)); - var imageId = "12345"; - var image = new ComputeImage(imageId, "tiny", - new Uri("http://testcomputeendpoint.com/v2/1234567890/images/12345"), - new Uri("http://testcomputeendpoint.com/1234567890/images/12345"), metadata, - "ACTIVE", created, updated, 10, 512, 100); - this.simulator.Images.Add(image); - - var client = new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.DeleteImageMetadata(imageId, "item1"); - - Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); - - Assert.AreEqual(1, image.Metadata.Count); - Assert.AreEqual("value2", image.Metadata["item2"]); - } - - #endregion - - #region Get Key Pairs Test - - [TestMethod] - public async Task GetComputeKeyPairsIncludesAuthHeader() - { - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetKeyPairs(); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task GetComputeKeyPairsFormsCorrectUrlAndMethod() - { - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetKeyPairs(); - - Assert.AreEqual(string.Format("{0}/os-keypairs", endpoint), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Get, this.simulator.Method); - } - - [TestMethod] - public async Task CanGetKeyPairs() - { - var keyPairName = "Key1"; - var keyPair = new ComputeKeyPair(keyPairName, "12345", "ABCDEF"); - this.simulator.KeyPairs.Add(keyPair); - - var client = new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetKeyPairs(); - - Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); - - var respContent = TestHelper.GetStringFromStream(resp.Content); - Assert.IsTrue(respContent.Length > 0); - } - - #endregion - - #region Get Key Pair Test - - [TestMethod] - public async Task GetComputeKeyPairIncludesAuthHeader() - { - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetKeyPair("12345"); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task GetComputeKeyPairFormsCorrectUrlAndMethod() - { - var keyPairName = "1"; - var client = - new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetKeyPair(keyPairName); - - Assert.AreEqual(string.Format("{0}/os-keypairs/{1}", endpoint, keyPairName), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Get, this.simulator.Method); - } - - [TestMethod] - public async Task CanGetKeyPair() - { - var keyPairName = "Key1"; - var keyPair = new ComputeKeyPair(keyPairName, "12345", "ABCDEF"); - this.simulator.KeyPairs.Add(keyPair); - - var client = new ComputeServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetKeyPair(keyPairName); - Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); - - var respContent = TestHelper.GetStringFromStream(resp.Content); - Assert.IsTrue(respContent.Length > 0); - } - - #endregion - } -} diff --git a/OpenStack/OpenStack.Test/Compute/TestComputeServicePocoClient.cs b/OpenStack/OpenStack.Test/Compute/TestComputeServicePocoClient.cs deleted file mode 100644 index f3bb061..0000000 --- a/OpenStack/OpenStack.Test/Compute/TestComputeServicePocoClient.cs +++ /dev/null @@ -1,168 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using OpenStack.Common.ServiceLocation; -using OpenStack.Compute; - -namespace OpenStack.Test.Compute -{ - public class TestComputeServicePocoClient : IComputeServicePocoClient - { - public Func> GetFlavorDelegate { get; set; } - - public Func>> GetFlavorsDelegate { get; set; } - - public Func> GetImageDelegate { get; set; } - - public Func>> GetImagesDelegate { get; set; } - - public Func DeleteImageDelegate { get; set; } - - public Func, Task> CreateServerDelegate { get; set; } - - public Func DeleteServerDelegate { get; set; } - - public Func>> GetImageMetadataDelegate { get; set; } - - public Func, Task> UpdateImageMetadataDelegate { get; set; } - - public Func DeleteImageMetadataDelegate { get; set; } - - public Func>> GetServerMetadataDelegate { get; set; } - - public Func, Task> UpdateServerMetadataDelegate { get; set; } - - public Func DeleteServerMetadataDelegate { get; set; } - - public Func AssignFloatingIpDelegate { get; set; } - - public Func> GetServerDelegate { get; set; } - - public Func>> GetServersDelegate { get; set; } - - public Func> GetKeyPairDelegate { get; set; } - - public Func>> GetKeyPairsDelegate { get; set; } - - public async Task GetFlavor(string flavorId) - { - return await this.GetFlavorDelegate(flavorId); - } - - public async Task> GetServerMetadata(string serverId) - { - return await this.GetServerMetadataDelegate(serverId); - } - - public async Task UpdateServerMetadata(string serverId, IDictionary metadata) - { - await this.UpdateServerMetadataDelegate(serverId, metadata); - } - - public async Task DeleteServerMetadata(string serverId, string key) - { - await this.DeleteServerMetadataDelegate(serverId, key); - } - - public async Task> GetKeyPairs() - { - return await this.GetKeyPairsDelegate(); - } - - public async Task GetKeyPair(string keyPairName) - { - return await this.GetKeyPairDelegate(keyPairName); - } - - public async Task> GetImages() - { - return await this.GetImagesDelegate(); - } - - public async Task GetImage(string imageId) - { - return await this.GetImageDelegate(imageId); - } - - public async Task DeleteImage(string imageId) - { - await this.DeleteImageDelegate(imageId); - } - - public async Task CreateServer(string name, string imageId, string flavorId, string networkId, string keyName, IEnumerable securityGroups) - { - return await this.CreateServerDelegate(name, imageId, flavorId, networkId, keyName, securityGroups); - } - - public async Task DeleteServer(string serverId) - { - await this.DeleteServerDelegate(serverId); - } - - public async Task> GetServers() - { - return await this.GetServersDelegate(); - } - - public async Task GetServer(string serverId) - { - return await this.GetServerDelegate(serverId); - } - - public async Task AssignFloatingIp(string serverId, string ipAddress) - { - await this.AssignFloatingIpDelegate(serverId, ipAddress); - } - - public async Task> GetImageMetadata(string flavorId) - { - return await this.GetImageMetadataDelegate(flavorId); - } - - public async Task UpdateImageMetadata(string flavorId, IDictionary metadata) - { - await this.UpdateImageMetadataDelegate(flavorId, metadata); - } - - public async Task DeleteImageMetadata(string flavorId, string key) - { - await this.DeleteImageMetadataDelegate(flavorId, key); - } - - public async Task> GetFlavors() - { - return await this.GetFlavorsDelegate(); - } - } - - public class TestComputeServicePocoClientFactory : IComputeServicePocoClientFactory - { - internal IComputeServicePocoClient client; - - public TestComputeServicePocoClientFactory(IComputeServicePocoClient client) - { - this.client = client; - } - - public IComputeServicePocoClient Create(ServiceClientContext context, IServiceLocator serviceLocator) - { - return client; - } - } -} diff --git a/OpenStack/OpenStack.Test/Compute/TestComputeServiceRestClient.cs b/OpenStack/OpenStack.Test/Compute/TestComputeServiceRestClient.cs deleted file mode 100644 index e35610c..0000000 --- a/OpenStack/OpenStack.Test/Compute/TestComputeServiceRestClient.cs +++ /dev/null @@ -1,147 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; -using System.Threading.Tasks; -using OpenStack.Common.Http; -using OpenStack.Common.ServiceLocation; -using OpenStack.Compute; - -namespace OpenStack.Test.Compute -{ - public class TestComputeServiceRestClient : IComputeServiceRestClient - { - public TestComputeServiceRestClient() - { - this.Responses = new Queue(); - } - - public Queue Responses { get; set; } - - public Task GetFlavors() - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task GetFlavor(string flavorId) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task AssignFloatingIp(string serverId, string ipAddress) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task GetServerMetadata(string serverId) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task UpdateServerMetadata(string serverId, IDictionary metadata) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task DeleteServerMetadata(string serverId, string key) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task GetKeyPairs() - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task GetKeyPair(string keyPairName) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task GetImages() - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task GetImage(string imageId) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task DeleteImage(string imageId) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task GetImageMetadata(string imageId) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task UpdateImageMetadata(string imageId, IDictionary metadata) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task DeleteImageMetadata(string imageId, string key) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - /// - public Task CreateServer(string name, string imageId, string flavorId, string networkId, IEnumerable securityGroups) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task CreateServer(string name, string imageId, string flavorId, string networkId, string keyName, - IEnumerable securityGroups) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task GetServers() - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task GetServer(string serverId) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - /// - public Task DeleteServer(string serverId) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - } - - public class TestComputeServiceRestClientFactory : IComputeServiceRestClientFactory - { - internal IComputeServiceRestClient Client; - - public TestComputeServiceRestClientFactory(IComputeServiceRestClient client) - { - this.Client = client; - } - - public IComputeServiceRestClient Create(ServiceClientContext context, IServiceLocator serviceLocator) - { - return Client; - } - } -} diff --git a/OpenStack/OpenStack.Test/Helper.cs b/OpenStack/OpenStack.Test/Helper.cs deleted file mode 100644 index b604c10..0000000 --- a/OpenStack/OpenStack.Test/Helper.cs +++ /dev/null @@ -1,69 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; -using System.IO; -using System.Net; -using System.Text; -using OpenStack.Common.Http; - -namespace OpenStack.Test -{ - public static class TestHelper - { - public static MemoryStream CreateStream(string input) - { - byte[] byteArray = Encoding.ASCII.GetBytes(input); - return new MemoryStream(byteArray); - } - - public static string GetStringFromStream(Stream input) - { - var reader = new StreamReader(input); - return reader.ReadToEnd(); - } - - public static IHttpResponseAbstraction CreateErrorResponse() - { - return new HttpResponseAbstraction(null, new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - } - - public static IHttpResponseAbstraction CreateResponse(HttpStatusCode code) - { - return new HttpResponseAbstraction(null, new HttpHeadersAbstraction(), code); - } - - public static IHttpResponseAbstraction CreateResponse(HttpStatusCode code, IEnumerable> headers) - { - var abstractionHeaders = new HttpHeadersAbstraction(); - foreach (var header in headers) - { - abstractionHeaders.Add(header.Key, header.Value); - } - return new HttpResponseAbstraction(null, abstractionHeaders, code); - } - - public static IHttpResponseAbstraction CreateResponse(HttpStatusCode code, IEnumerable> headers, Stream content) - { - var abstractionHeaders = new HttpHeadersAbstraction(); - foreach (var header in headers) - { - abstractionHeaders.Add(header.Key, header.Value); - } - return new HttpResponseAbstraction(content, abstractionHeaders, code); - } - } -} diff --git a/OpenStack/OpenStack.Test/HttpAbstraction/HttpAbstractionClientTests.cs b/OpenStack/OpenStack.Test/HttpAbstraction/HttpAbstractionClientTests.cs deleted file mode 100644 index 96a67d5..0000000 --- a/OpenStack/OpenStack.Test/HttpAbstraction/HttpAbstractionClientTests.cs +++ /dev/null @@ -1,305 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Threading; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Common.Http; - -namespace OpenStack.Test.HttpAbstraction -{ - [TestClass] - public class HttpAbstractionClientTests - { - [TestMethod] - [TestCategory("Integration")] - [TestCategory("LongRunning")] - public void CanMakeGetRequest() - { - using (var client = new HttpAbstractionClientFactory().Create()) - { - client.Uri = new Uri("http://httpbin.org/get"); - client.Method = HttpMethod.Get; - - var responseTask = client.SendAsync(); - responseTask.Wait(); - var response = responseTask.Result; - - Assert.IsNotNull(response); - Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - - Assert.IsNotNull(response.Content); - var content = TestHelper.GetStringFromStream(response.Content); - Assert.AreNotEqual(0, content.Length); - } - } - - [TestMethod] - [TestCategory("Integration")] - [TestCategory("LongRunning")] - public void ResponsesIncludeContentHeaders() - { - using (var client = new HttpAbstractionClientFactory().Create(new TimeSpan(0, 5, 0), CancellationToken.None)) - { - client.Uri = new Uri("http://httpbin.org/get"); - client.Method = HttpMethod.Get; - - var responseTask = client.SendAsync(); - responseTask.Wait(); - var response = responseTask.Result; - - Assert.IsNotNull(response); - Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - - Assert.IsTrue(response.Headers.Contains("Content-Length")); - Assert.IsTrue(response.Headers.Contains("Content-Type")); - - Assert.IsTrue(int.Parse(response.Headers["Content-Length"].First()) > 100); - Assert.AreEqual("application/json", response.Headers["Content-Type"].First()); - - Assert.IsNotNull(response.Content); - var content = TestHelper.GetStringFromStream(response.Content); - Assert.AreNotEqual(0, content.Length); - } - } - - [TestMethod] - [TestCategory("Integration")] - [TestCategory("LongRunning")] - public void CanMakePutRequest() - { - using (var client = new HttpAbstractionClientFactory().Create()) - { - using (var content = TestHelper.CreateStream("Test Text")) - { - client.Uri = new Uri("http://httpbin.org/put"); - client.Method = HttpMethod.Put; - client.Content = content; - - var responseTask = client.SendAsync(); - responseTask.Wait(); - var response = responseTask.Result; - - Assert.IsNotNull(response); - Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - - Assert.IsNotNull(response.Content); - - var stringContent = TestHelper.GetStringFromStream(response.Content); - Assert.AreNotEqual(0, stringContent.Length); - Assert.IsTrue(stringContent.Contains("\"data\": \"Test Text\"")); - } - } - } - - [TestMethod] - [TestCategory("Integration")] - [TestCategory("LongRunning")] - public void CanMakePostRequest() - { - using (var client = new HttpAbstractionClientFactory().Create()) - { - using (var content = TestHelper.CreateStream("Test Text")) - { - client.Uri = new Uri("http://httpbin.org/post"); - client.Method = HttpMethod.Post; - client.Content = content; - - var responseTask = client.SendAsync(); - responseTask.Wait(); - var response = responseTask.Result; - - Assert.IsNotNull(response); - Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - - var stringContent = TestHelper.GetStringFromStream(response.Content); - - Assert.IsTrue(stringContent.Contains("\"data\": \"Test Text\"")); - } - } - } - - [TestMethod] - [TestCategory("Integration")] - [TestCategory("LongRunning")] - public void CanMakePostRequestWithNullContent() - { - using (var client = new HttpAbstractionClientFactory().Create()) - { - client.Uri = new Uri("http://httpbin.org/post"); - client.Method = HttpMethod.Post; - - var responseTask = client.SendAsync(); - responseTask.Wait(); - var response = responseTask.Result; - - Assert.IsNotNull(response); - Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - - var stringContent = TestHelper.GetStringFromStream(response.Content); - - Assert.IsTrue(stringContent.Contains("\"data\": \"\"")); - - } - } - - [TestMethod] - [TestCategory("Integration")] - [TestCategory("LongRunning")] - public void CanMakeDeleteRequest() - { - using (var client = new HttpAbstractionClientFactory().Create()) - { - - client.Uri = new Uri("http://httpbin.org/delete"); - client.Method = HttpMethod.Delete; - - var responseTask = client.SendAsync(); - responseTask.Wait(); - var response = responseTask.Result; - - Assert.IsNotNull(response); - Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - - Assert.IsNotNull(response.Content); - var content = TestHelper.GetStringFromStream(response.Content); - Assert.AreNotEqual(0, content.Length); - } - } - - [TestMethod] - [TestCategory("Integration")] - [TestCategory("LongRunning")] - public void CanMakeMultipleGetRequestsWithSameClient() - { - using (var client = new HttpAbstractionClientFactory().Create()) - { - - client.Uri = new Uri("http://httpbin.org/get"); - client.Method = HttpMethod.Get; - - var responseTask = client.SendAsync(); - responseTask.Wait(); - - responseTask = client.SendAsync(); - responseTask.Wait(); - } - } - - [TestMethod] - [TestCategory("Integration")] - [TestCategory("LongRunning")] - public void RequestsHonorsClientSideTimeout() - { - try - { - using (var client = new HttpAbstractionClientFactory().Create(TimeSpan.FromMilliseconds(100))) - { - client.Uri = new Uri("http://httpbin.org/delay/30000"); - - var responseTask = client.SendAsync(); - responseTask.Wait(); - } - } - catch (AggregateException ex) - { - var inner = ex.InnerException; - Assert.IsInstanceOfType(inner,typeof(TimeoutException)); - Assert.IsTrue(inner.Message.Contains("failed to complete in the given timeout period")); - } - } - - [TestMethod] - [TestCategory("Integration")] - [TestCategory("LongRunning")] - public void RequestsHonorsCancelationToken() - { - var token = new CancellationToken(true); - var startTime = DateTime.Now; - - try - { - using (var client = new HttpAbstractionClientFactory().Create(token)) - { - client.Uri = new Uri("http://httpbin.org/delay/30000"); - client.Timeout = TimeSpan.FromSeconds(31); - - var responseTask = client.SendAsync(); - responseTask.Wait(); - } - } - catch (AggregateException ex) - { - var inner = ex.InnerException; - Assert.IsTrue(DateTime.Now - startTime < TimeSpan.FromSeconds(30)); - Assert.IsTrue(inner.Message.Contains("was canceled")); - } - } - - [TestMethod] - [TestCategory("Integration")] - [TestCategory("LongRunning")] - public void RequestsHandlesHttpErrors() - { - using (var client = new HttpAbstractionClientFactory().Create()) - { - client.Uri = new Uri("http://httpbin.org/status/404"); - - var responseTask = client.SendAsync(); - responseTask.Wait(); - var response = responseTask.Result; - - Assert.IsNotNull(response); - Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); - - var stringContent = TestHelper.GetStringFromStream(response.Content); - - Assert.AreEqual(string.Empty, stringContent); - } - } - - [TestMethod] - [TestCategory("Integration")] - [TestCategory("LongRunning")] - public void RequestsCanSendHeaders() - { - using (var client = new HttpAbstractionClientFactory().Create()) - { - client.Uri = new Uri("http://httpbin.org/get"); - client.Headers.Add("X-Test-Header","TEST"); - - //Added in order to force httpbin not to cache the responses from any prior get requests/unit tests. - client.Headers.Add("Cache-Control", "max-age=0"); - - var responseTask = client.SendAsync(); - - responseTask.Wait(); - var response = responseTask.Result; - Assert.IsNotNull(response); - Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - - Assert.IsNotNull(response.Content); - var content = TestHelper.GetStringFromStream(response.Content); - Assert.AreNotEqual(0, content.Length); - - Assert.IsTrue(content.Contains("\"X-Test-Header\": \"TEST\"")); - } - } - } -} diff --git a/OpenStack/OpenStack.Test/HttpAbstraction/HttpHeadersAbstractionTests.cs b/OpenStack/OpenStack.Test/HttpAbstraction/HttpHeadersAbstractionTests.cs deleted file mode 100644 index ac0838b..0000000 --- a/OpenStack/OpenStack.Test/HttpAbstraction/HttpHeadersAbstractionTests.cs +++ /dev/null @@ -1,85 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Common.Http; - -namespace OpenStack.Test.HttpAbstraction -{ - [TestClass] - public class HttpHeadersAbstractionTests - { - [TestMethod] - public void CanAddHeaders() - { - var headers = new HttpHeadersAbstraction(); - headers.Add("Test","Value"); - Assert.IsTrue(headers.Contains("Test")); - Assert.AreEqual("Value",headers["Test"].First()); - } - - [TestMethod] - public void CanAddRangeHeaders() - { - var headers = new HttpHeadersAbstraction(); - - var rspMsg = new HttpResponseMessage(); - rspMsg.Headers.Add("Test", "Value"); - - headers.AddRange(rspMsg.Headers); - Assert.IsTrue(headers.Contains("Test")); - Assert.AreEqual("Value", headers["Test"].First()); - } - - [TestMethod] - public void CanClearHeaders() - { - var headers = new HttpHeadersAbstraction(); - headers.Add("Test", "Value"); - Assert.IsTrue(headers.Contains("Test")); - - headers.Clear(); - Assert.AreEqual(0,headers.Count()); - } - - [TestMethod] - public void CanGetValuesHeaders() - { - var headers = new HttpHeadersAbstraction(); - var values = new List() {"value1", "value2"}; - headers.Add("Test", values); - Assert.IsTrue(headers.Contains("Test")); - Assert.AreEqual(values, headers.GetValues("Test")); - } - - [TestMethod] - public void CanTryGetValuesHeaders() - { - var headers = new HttpHeadersAbstraction(); - var values = new List() { "value1", "value2" }; - headers.Add("Test", values); - - IEnumerable resValues = new List(); - Assert.IsTrue(headers.TryGetValue("Test", out resValues)); - - Assert.AreEqual(2,resValues.Count()); - Assert.AreEqual(values, resValues); - } - } -} diff --git a/OpenStack/OpenStack.Test/Identity/AccessTokenPayloadConverterTests.cs b/OpenStack/OpenStack.Test/Identity/AccessTokenPayloadConverterTests.cs deleted file mode 100644 index dca6c92..0000000 --- a/OpenStack/OpenStack.Test/Identity/AccessTokenPayloadConverterTests.cs +++ /dev/null @@ -1,112 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Web; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Identity; - -namespace OpenStack.Test.Identity -{ - [TestClass] - public class AccessTokenPayloadConverterTests - { - [TestMethod] - public void CanConvertJsonPayload() - { - var AuthJsonResponseFixture = @"{ - ""access"": { - ""token"": { - ""expires"": ""2014-03-18T10:59:46.355Z"", - ""id"": ""HPAuth10_af3d1bfe456d18e8d4793e54922f839fa051d9f60f115aca52c9a44f9e3d96fb"", - ""tenant"": { - ""id"": ""10244656540440"", - ""name"": ""10255892528404-Project"" - } - } - } - }"; - - var expectedToken = "HPAuth10_af3d1bfe456d18e8d4793e54922f839fa051d9f60f115aca52c9a44f9e3d96fb"; - var converter = new AccessTokenPayloadConverter(); - var token = converter.Convert(AuthJsonResponseFixture); - Assert.IsNotNull(token); - Assert.AreEqual(expectedToken, token); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertJsonPayloadMissingTokenId() - { - var missingTokenIdFixture = @"{ - ""access"": { - ""token"": { - ""expires"": ""2014-03-18T10:59:46.355Z"", - ""tenant"": { - ""id"": ""10244656540440"", - ""name"": ""10255892528404-Project"" - } - } - } - }"; - - var converter = new AccessTokenPayloadConverter(); - converter.Convert(missingTokenIdFixture); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertJsonPayloadMissingToken() - { - var missingTokenFixture = @"{ - ""access"": { } - }"; - - var converter = new AccessTokenPayloadConverter(); - converter.Convert(missingTokenFixture); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertJsonPayloadEmptyObject() - { - var emptyObjectFixture = @"{ }"; - - var converter = new AccessTokenPayloadConverter(); - converter.Convert(emptyObjectFixture); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertInvalidJson() - { - var badJsonFixture = @"{ NOT JSON"; - - var converter = new AccessTokenPayloadConverter(); - converter.Convert(badJsonFixture); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertNonObjectJson() - { - var nonObjectJson = @"[]"; - - var converter = new AccessTokenPayloadConverter(); - converter.Convert(nonObjectJson); - } - } -} diff --git a/OpenStack/OpenStack.Test/Identity/IdentityRestServiceSimulator.cs b/OpenStack/OpenStack.Test/Identity/IdentityRestServiceSimulator.cs deleted file mode 100644 index b479e38..0000000 --- a/OpenStack/OpenStack.Test/Identity/IdentityRestServiceSimulator.cs +++ /dev/null @@ -1,200 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Net; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; -using OpenStack.Common; -using OpenStack.Common.Http; - -namespace OpenStack.Test.Identity -{ - public class IdentityRestServiceSimulator : DisposableClass, IHttpAbstractionClient - { - #region Authentication Json Response Fixture - - internal string AuthJsonResponseFixture = @"{ - ""access"": { - ""token"": { - ""expires"": ""2014-03-18T10:59:46.355Z"", - ""id"": ""HPAuth10_af3d1bfe456d18e8d4793e54922f839fa051d9f60f115aca52c9a44f9e3d96fb"", - ""tenant"": { - ""id"": ""10244656540440"", - ""name"": ""10255892528404-Project"" - } - }, - ""user"": { - ""id"": ""10391119133001"", - ""name"": ""wayne.foley"", - ""otherAttributes"": { - ""domainStatus"": ""enabled"", - ""domainStatusCode"": ""00"" - }, - ""roles"": [ ] - }, - ""serviceCatalog"": [ - { - ""name"": ""Networking"", - ""type"": ""network"", - ""endpoints"": [ - { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-a.geo-1.network.hpcloudsvc.com"", - ""publicURL2"": """", - ""region"": ""region-a.geo-1"", - ""versionId"": ""2.0"", - ""versionInfo"": ""https://region-a.geo-1.network.hpcloudsvc.com"", - ""versionList"": ""https://region-a.geo-1.network.hpcloudsvc.com"" - } - ] - }, - { - ""name"": ""Object Storage"", - ""type"": ""object-store"", - ""endpoints"": [ - { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1/10244656540440"", - ""region"": ""region-a.geo-1"", - ""versionId"": ""1.0"", - ""versionInfo"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1.0/"", - ""versionList"": ""https://region-a.geo-1.objects.hpcloudsvc.com"" - }, - { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/10244656540440"", - ""region"": ""region-b.geo-1"", - ""versionId"": ""1"", - ""versionInfo"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/"", - ""versionList"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443"" - } - ] - }, - { - ""name"": ""Identity"", - ""type"": ""identity"", - ""endpoints"": [ - { - ""publicURL"": ""https://region-a.geo-1.identity.hpcloudsvc.com:35357/v2.0/"", - ""region"": ""region-a.geo-1"", - ""versionId"": ""2.0"", - ""versionInfo"": ""https://region-a.geo-1.identity.hpcloudsvc.com:35357/v2.0/"", - ""versionList"": ""https://region-a.geo-1.identity.hpcloudsvc.com:35357"" - }, - { - ""publicURL"": ""https://region-a.geo-1.identity.hpcloudsvc.com:35357/v3/"", - ""region"": ""region-a.geo-1"", - ""versionId"": ""3.0"", - ""versionInfo"": ""https://region-a.geo-1.identity.hpcloudsvc.com:35357/v3/"", - ""versionList"": ""https://region-a.geo-1.identity.hpcloudsvc.com:35357"" - }, - { - ""publicURL"": ""https://region-b.geo-1.identity.hpcloudsvc.com:35357/v2.0/"", - ""region"": ""region-b.geo-1"", - ""versionId"": ""2.0"", - ""versionInfo"": ""https://region-b.geo-1.identity.hpcloudsvc.com:35357/v2.0/"", - ""versionList"": ""https://region-b.geo-1.identity.hpcloudsvc.com:35357"" - }, - { - ""publicURL"": ""https://region-b.geo-1.identity.hpcloudsvc.com:35357/v3/"", - ""region"": ""region-b.geo-1"", - ""versionId"": ""3.0"", - ""versionInfo"": ""https://region-b.geo-1.identity.hpcloudsvc.com:35357/v3/"", - ""versionList"": ""https://region-b.geo-1.identity.hpcloudsvc.com:35357"" - } - ] - }, - { - ""name"": ""Compute"", - ""type"": ""compute"", - ""endpoints"": [ - { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-a.geo-1.compute.hpcloudsvc.com/v2/10244656540440"", - ""region"": ""region-a.geo-1"", - ""versionId"": ""2"", - ""versionInfo"": ""https://region-a.geo-1.compute.hpcloudsvc.com/v2/"", - ""versionList"": ""https://region-a.geo-1.compute.hpcloudsvc.com"" - } - ] - } - ] - } - }"; - - - #endregion - - public HttpMethod Method { get; set; } - public Uri Uri { get; set; } - public Stream Content { get; set; } - public IDictionary Headers { get; private set; } - public string ContentType { get; set; } - public TimeSpan Timeout { get; set; } - //public event EventHandler HttpReceiveProgress; - //public event EventHandler HttpSendProgress; - - public IdentityRestServiceSimulator() - { - this.Headers = new Dictionary(); - } - - public Task SendAsync() - { - var resp = TestHelper.CreateResponse(HttpStatusCode.OK, new List>(), - this.AuthJsonResponseFixture.ConvertToStream()); - return Task.Factory.StartNew(() => resp); - } - } - - public class IdentityRestServiceSimulatorFactory : IHttpAbstractionClientFactory - { - internal IdentityRestServiceSimulator Simulator; - - public IdentityRestServiceSimulatorFactory(IdentityRestServiceSimulator simulator) - { - this.Simulator = simulator; - } - - public IHttpAbstractionClient Create() - { - throw new NotImplementedException(); - } - - public IHttpAbstractionClient Create(CancellationToken token) - { - if (this.Simulator != null) - { - this.Simulator.Headers.Clear(); - } - return this.Simulator ?? new IdentityRestServiceSimulator(); - } - - public IHttpAbstractionClient Create(TimeSpan timeout) - { - throw new NotImplementedException(); - } - - public IHttpAbstractionClient Create(TimeSpan timeout, CancellationToken token) - { - throw new NotImplementedException(); - } - } -} diff --git a/OpenStack/OpenStack.Test/Identity/IdentityServiceClientDefinitionTests.cs b/OpenStack/OpenStack.Test/Identity/IdentityServiceClientDefinitionTests.cs deleted file mode 100644 index 396e02b..0000000 --- a/OpenStack/OpenStack.Test/Identity/IdentityServiceClientDefinitionTests.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Common; -using OpenStack.Identity; - -namespace OpenStack.Test.Identity -{ - [TestClass] - public class IdentityServiceClientDefinitionTests - { - public IOpenStackCredential GetValidCredentials() - { - var endpoint = new Uri("https://someidentityendpoint:35357/v2.0"); - var userName = "TestUser"; - var password = "RandomPassword"; - var tenantId = "12345"; - - return new OpenStackCredential(endpoint, userName, password, tenantId); - } - - [TestMethod] - public void CanSupportVersion2() - { - var client = new IdentityServiceClientDefinition(); - - Assert.IsTrue(client.IsSupported(GetValidCredentials(), string.Empty)); - } - - [TestMethod] - public void CannotSupportVersion1() - { - var endpoint = new Uri("https://someidentityendpoint:35357/v1.0/tokens"); - var userName = "TestUser"; - var password = "RandomPassword"; - var tenantId = "12345"; - - var creds = new OpenStackCredential(endpoint, userName, password, tenantId); - - var client = new IdentityServiceClientDefinition(); - - Assert.IsFalse(client.IsSupported(creds, string.Empty)); - } - - [TestMethod] - public void Version2Supported() - { - var client = new IdentityServiceClientDefinition(); - Assert.IsTrue(client.ListSupportedVersions().Contains("2.0.0.0")); - } - } -} diff --git a/OpenStack/OpenStack.Test/Identity/IdentityServiceClientTests.cs b/OpenStack/OpenStack.Test/Identity/IdentityServiceClientTests.cs deleted file mode 100644 index 6e2ca86..0000000 --- a/OpenStack/OpenStack.Test/Identity/IdentityServiceClientTests.cs +++ /dev/null @@ -1,79 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Common; -using OpenStack.Common.ServiceLocation; -using OpenStack.Identity; - -namespace OpenStack.Test.Identity -{ - [TestClass] - public class IdentityServiceClientTests - { - internal TestIdentityServicePocoClient pocoClient; - internal IServiceLocator ServiceLocator; - - [TestInitialize] - public void TestSetup() - { - this.ServiceLocator = new ServiceLocator(); - this.pocoClient = new TestIdentityServicePocoClient(); - - var manager = this.ServiceLocator.Locate(); - manager.RegisterServiceInstance(typeof(IIdentityServicePocoClientFactory), new TestIdentityServicePocoClientFactory(pocoClient)); - } - - [TestCleanup] - public void TestCleanup() - { - this.pocoClient = new TestIdentityServicePocoClient(); - this.ServiceLocator = new ServiceLocator(); - } - - public IOpenStackCredential GetValidCredentials() - { - var endpoint = new Uri("https://someidentityendpoint:35357/v2.0/tokens"); - var userName = "TestUser"; - var password = "RandomPassword"; - var tenantId = "12345"; - - return new OpenStackCredential(endpoint, userName, password, tenantId); - } - - [TestMethod] - public async Task CanAuthenticate() - { - var creds = GetValidCredentials(); - var token = "someToken"; - - this.pocoClient.AuthenticationDelegate = () => - { - creds.SetAccessTokenId(token); - return Task.Factory.StartNew(() => creds); - }; - - var client = new IdentityServiceClientDefinition().Create(GetValidCredentials(), string.Empty, CancellationToken.None, this.ServiceLocator) as IdentityServiceClient; - var resp = await client.Authenticate(); - - Assert.AreEqual(creds, resp); - Assert.AreEqual(creds,client.Credential); - } - } -} diff --git a/OpenStack/OpenStack.Test/Identity/IdentityServicePocoClientTests.cs b/OpenStack/OpenStack.Test/Identity/IdentityServicePocoClientTests.cs deleted file mode 100644 index e85f199..0000000 --- a/OpenStack/OpenStack.Test/Identity/IdentityServicePocoClientTests.cs +++ /dev/null @@ -1,342 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.IO; -using System.Linq; -using System.Net; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Common; -using OpenStack.Common.Http; -using OpenStack.Common.ServiceLocation; -using OpenStack.Identity; - -namespace OpenStack.Test.Identity -{ - [TestClass] - public class IdentityServicePocoClientTests - { - internal TestIdentityServiceRestClient RestClient; - internal string defaultRegion = "region-a.geo-1"; - internal IServiceLocator ServiceLocator; - - [TestInitialize] - public void TestSetup() - { - this.RestClient = new TestIdentityServiceRestClient(); - this.ServiceLocator = new ServiceLocator(); - this.ServiceLocator.EnsureAssemblyRegistration(typeof(ServiceLocator).Assembly); - - var manager = this.ServiceLocator.Locate(); - manager.RegisterServiceInstance(typeof(IIdentityServiceRestClientFactory), new TestIdentityServiceRestClientFactory(RestClient)); - manager.RegisterServiceInstance(typeof(IOpenStackRegionResolver), new TestOpenStackRegionResolver(defaultRegion)); - } - - [TestCleanup] - public void TestCleanup() - { - this.RestClient = new TestIdentityServiceRestClient(); - this.ServiceLocator = new ServiceLocator(); - } - - public IOpenStackCredential GetValidCredentials() - { - var endpoint = new Uri("https://auth.someplace.com/authme"); - var userName = "TestUser"; - var password = "RandomPassword"; - var tenantId = "12345"; - - return new OpenStackCredential(endpoint, userName, password, tenantId); - } - - - [TestMethod] - public async Task CanAuthenticateWithOkResponse() - { - var creds = GetValidCredentials(); - - var expectedToken = "HPAuth10_af3d1bfe456d18e8d4793e54922f839fa051d9f60f115aca52c9a44f9e3d96fb"; - - var payload = @"{ - ""access"": { - ""token"": { - ""expires"": ""2014-03-18T10:59:46.355Z"", - ""id"": ""HPAuth10_af3d1bfe456d18e8d4793e54922f839fa051d9f60f115aca52c9a44f9e3d96fb"", - ""tenant"": { - ""id"": ""10244656540440"", - ""name"": ""10255892528404-Project"" - } - }, - ""serviceCatalog"":[{ - ""name"": ""Object Storage"", - ""type"": ""object-store"", - ""endpoints"": [ - { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1/10244656540440"", - ""region"": ""region-a.geo-1"", - ""versionId"": ""1.0"", - ""versionInfo"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1.0/"", - ""versionList"": ""https://region-a.geo-1.objects.hpcloudsvc.com"" - }, - { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/10244656540440"", - ""region"": ""region-b.geo-1"", - ""versionId"": ""1"", - ""versionInfo"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/"", - ""versionList"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443"" - } - ] - }] - } - }"; - - var content = TestHelper.CreateStream(payload); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.OK); - this.RestClient.Response = restResp; - - var client = - new IdentityServicePocoClientFactory().Create(creds, "Swift", CancellationToken.None, this.ServiceLocator) as - IdentityServicePocoClient; - var result = await client.Authenticate(); - - Assert.IsNotNull(result); - Assert.AreEqual(creds.UserName, result.UserName); - Assert.AreEqual(creds.Password, result.Password); - Assert.AreEqual(creds.TenantId, result.TenantId); - Assert.AreEqual(expectedToken, result.AccessTokenId); - Assert.AreEqual(1,result.ServiceCatalog.Count()); - } - - [TestMethod] - public async Task CanAuthenticateWithNonAuthoritativeInfoResponse() - { - var creds = GetValidCredentials(); - - var expectedToken = "HPAuth10_af3d1bfe456d18e8d4793e54922f839fa051d9f60f115aca52c9a44f9e3d96fb"; - - var payload = @"{ - ""access"": { - ""token"": { - ""expires"": ""2014-03-18T10:59:46.355Z"", - ""id"": ""HPAuth10_af3d1bfe456d18e8d4793e54922f839fa051d9f60f115aca52c9a44f9e3d96fb"", - ""tenant"": { - ""id"": ""10244656540440"", - ""name"": ""10255892528404-Project"" - } - }, - ""serviceCatalog"":[{ - ""name"": ""Object Storage"", - ""type"": ""object-store"", - ""endpoints"": [ - { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1/10244656540440"", - ""region"": ""region-a.geo-1"", - ""versionId"": ""1.0"", - ""versionInfo"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1.0/"", - ""versionList"": ""https://region-a.geo-1.objects.hpcloudsvc.com"" - }, - { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/10244656540440"", - ""region"": ""region-b.geo-1"", - ""versionId"": ""1"", - ""versionInfo"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/"", - ""versionList"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443"" - } - ] - }] - } - }"; - - var content = TestHelper.CreateStream(payload); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.NonAuthoritativeInformation); - this.RestClient.Response = restResp; - - var client = new IdentityServicePocoClient(creds, "Swift", CancellationToken.None, this.ServiceLocator); - var result = await client.Authenticate(); - - Assert.IsNotNull(result); - Assert.AreEqual(creds.UserName, result.UserName); - Assert.AreEqual(creds.Password, result.Password); - Assert.AreEqual(creds.TenantId, result.TenantId); - Assert.AreEqual(expectedToken, result.AccessTokenId); - Assert.AreEqual(1, result.ServiceCatalog.Count()); - } - - [TestMethod] - public async Task AuthenticationDoesNotResolveRegionIfCredRegionSupplied() - { - var expectedRegion = "Some region"; - var creds = GetValidCredentials(); - creds.SetRegion(expectedRegion); - var payload = @"{ - ""access"": { - ""token"": { - ""expires"": ""2014-03-18T10:59:46.355Z"", - ""id"": ""HPAuth10_af3d1bfe456d18e8d4793e54922f839fa051d9f60f115aca52c9a44f9e3d96fb"", - ""tenant"": { - ""id"": ""10244656540440"", - ""name"": ""10255892528404-Project"" - } - }, - ""serviceCatalog"":[{ - ""name"": ""Object Storage"", - ""type"": ""object-store"", - ""endpoints"": [ - { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1/10244656540440"", - ""region"": ""region-a.geo-1"", - ""versionId"": ""1.0"", - ""versionInfo"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1.0/"", - ""versionList"": ""https://region-a.geo-1.objects.hpcloudsvc.com"" - }, - { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/10244656540440"", - ""region"": ""region-b.geo-1"", - ""versionId"": ""1"", - ""versionInfo"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/"", - ""versionList"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443"" - } - ] - }] - } - }"; - - var content = TestHelper.CreateStream(payload); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.NonAuthoritativeInformation); - this.RestClient.Response = restResp; - - var client = new IdentityServicePocoClient(creds, "Swift", CancellationToken.None, this.ServiceLocator); - var result = await client.Authenticate(); - - Assert.AreEqual(expectedRegion, result.Region); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task CannotAuthenticateWithUnauthorizedResponse() - { - var creds = GetValidCredentials(); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.RestClient.Response = restResp; - - var client = new IdentityServicePocoClient(creds, "Swift", CancellationToken.None, this.ServiceLocator); - await client.Authenticate(); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task CannotAuthenticateWithBadRequestResponse() - { - var creds = GetValidCredentials(); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.BadRequest); - this.RestClient.Response = restResp; - - var client = new IdentityServicePocoClient(creds, "Swift", CancellationToken.None, this.ServiceLocator); - await client.Authenticate(); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task CannotAuthenticateWithInternalServerErrorResponse() - { - var creds = GetValidCredentials(); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.RestClient.Response = restResp; - - var client = new IdentityServicePocoClient(creds, "Swift", CancellationToken.None, this.ServiceLocator); - await client.Authenticate(); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task CannotAuthenticateWithForbiddenResponse() - { - var creds = GetValidCredentials(); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Forbidden); - this.RestClient.Response = restResp; - - var client = new IdentityServicePocoClient(creds, "Swift", CancellationToken.None, this.ServiceLocator); - await client.Authenticate(); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task CannotAuthenticateWithBadMethodResponse() - { - var creds = GetValidCredentials(); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.MethodNotAllowed); - this.RestClient.Response = restResp; - - var client = new IdentityServicePocoClient(creds, "Swift", CancellationToken.None, this.ServiceLocator); - await client.Authenticate(); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task CannotAuthenticateWithOverLimitResponse() - { - var creds = GetValidCredentials(); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.RequestEntityTooLarge); - this.RestClient.Response = restResp; - - var client = new IdentityServicePocoClient(creds, "Swift", CancellationToken.None, this.ServiceLocator); - await client.Authenticate(); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task CannotAuthenticateWithServiceUnavailableResponse() - { - var creds = GetValidCredentials(); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.ServiceUnavailable); - this.RestClient.Response = restResp; - - var client = new IdentityServicePocoClient(creds, "Swift", CancellationToken.None, this.ServiceLocator); - await client.Authenticate(); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task CannotAuthenticateWithNotFoundResponse() - { - var creds = GetValidCredentials(); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.NotFound); - this.RestClient.Response = restResp; - - var client = new IdentityServicePocoClient(creds, "Swift", CancellationToken.None, this.ServiceLocator); - await client.Authenticate(); - } - } -} diff --git a/OpenStack/OpenStack.Test/Identity/IdentityServiceRestClientTests.cs b/OpenStack/OpenStack.Test/Identity/IdentityServiceRestClientTests.cs deleted file mode 100644 index a70c433..0000000 --- a/OpenStack/OpenStack.Test/Identity/IdentityServiceRestClientTests.cs +++ /dev/null @@ -1,119 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Newtonsoft.Json.Linq; -using OpenStack.Common; -using OpenStack.Common.Http; -using OpenStack.Common.ServiceLocation; -using OpenStack.Identity; - -namespace OpenStack.Test.Identity -{ - [TestClass] - public class IdentityServiceRestClientTests - { - internal IdentityRestServiceSimulator simulator; - internal IServiceLocator ServiceLocator; - - [TestInitialize] - public void TestSetup() - { - this.simulator = new IdentityRestServiceSimulator(); - this.ServiceLocator = new ServiceLocator(); - - var manager = this.ServiceLocator.Locate(); - manager.RegisterServiceInstance(typeof(IHttpAbstractionClientFactory), new IdentityRestServiceSimulatorFactory(simulator)); - } - - [TestCleanup] - public void TestCleanup() - { - this.simulator = new IdentityRestServiceSimulator(); - this.ServiceLocator = new ServiceLocator(); - } - - public IOpenStackCredential GetValidCredentials() - { - var endpoint = new Uri("https://auth.someplace.com/authme"); - var userName = "TestUser"; - var password = "RandomPassword"; - var tenantId = "12345"; - - return new OpenStackCredential(endpoint, userName, password, tenantId); - } - - [TestMethod] - public async Task AuthenticationMethodAndUriAreValid() - { - var creds = GetValidCredentials(); - var client = new IdentityServiceRestClientFactory().Create(creds,CancellationToken.None, this.ServiceLocator); - - await client.Authenticate(); - var expectedUri = new Uri(string.Format("{0}/tokens", creds.AuthenticationEndpoint)); - Assert.AreEqual(expectedUri, this.simulator.Uri); - Assert.AreEqual(HttpMethod.Post, this.simulator.Method); - } - - [TestMethod] - public async Task AuthenticateIncludesCorrectHeaders() - { - var creds = GetValidCredentials(); - var client = new IdentityServiceRestClient(creds, CancellationToken.None, this.ServiceLocator); - - await client.Authenticate(); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("Accept")); - Assert.AreEqual("application/json", this.simulator.Headers["Accept"]); - Assert.AreEqual("application/json", this.simulator.ContentType); - } - - [TestMethod] - public async Task AuthenticateIncludesPayload() - { - var creds = GetValidCredentials(); - var client = new IdentityServiceRestClient(creds, CancellationToken.None, this.ServiceLocator); - - await client.Authenticate(); - - Assert.IsNotNull(this.simulator.Content); - - var content = TestHelper.GetStringFromStream(this.simulator.Content); - Assert.IsTrue(content.Length > 0); - } - - [TestMethod] - public void AuthenticationPayloadIsGeneratedCorrectly() - { - var creds = GetValidCredentials(); - var payload = IdentityServiceRestClient.CreateAuthenticationJsonPayload(creds); - - var obj = JObject.Parse(payload); - var userName = obj["auth"]["passwordCredentials"]["username"]; - var password = obj["auth"]["passwordCredentials"]["password"]; - var tenantId = obj["auth"]["tenantName"]; - - Assert.AreEqual(creds.UserName, userName); - Assert.AreEqual(creds.Password, password); - Assert.AreEqual(creds.TenantId, tenantId); - } - - } -} diff --git a/OpenStack/OpenStack.Test/Identity/OpenStackCredentialTests.cs b/OpenStack/OpenStack.Test/Identity/OpenStackCredentialTests.cs deleted file mode 100644 index 8c1a7ec..0000000 --- a/OpenStack/OpenStack.Test/Identity/OpenStackCredentialTests.cs +++ /dev/null @@ -1,180 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Common; -using OpenStack.Identity; - -namespace OpenStack.Test.Identity -{ - [TestClass] - public class OpenStackCredentialTests - { - [TestMethod] - public void CanCreateAnOpenStackCredential() - { - var endpoint = new Uri("https://auth.someplace.com/authme"); - var userName = "TestUser"; - var password = "RandomPassword"; - var tenantId = "12345"; - - var cred = new OpenStackCredential(endpoint, userName, password, tenantId); - - Assert.IsNotNull(cred); - Assert.AreEqual(userName, cred.UserName); - Assert.AreEqual(endpoint, cred.AuthenticationEndpoint); - Assert.IsNotNull(cred.Password); - Assert.AreEqual(tenantId, cred.TenantId); - } - - [TestMethod] - public void CanSetAcessTokenId() - { - var endpoint = new Uri("https://auth.someplace.com/authme"); - var userName = "TestUser"; - var password = "RandomPassword"; - var tenantId = "12345"; - var token = "someToken"; - - var cred = new OpenStackCredential(endpoint, userName, password, tenantId); - cred.SetAccessTokenId(token); - - Assert.AreEqual(token, cred.AccessTokenId); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotSetAcessTokenIdWithNullToken() - { - var endpoint = new Uri("https://auth.someplace.com/authme"); - var userName = "TestUser"; - var password = "RandomPassword"; - var tenantId = "12345"; - - var cred = new OpenStackCredential(endpoint, userName, password, tenantId); - cred.SetAccessTokenId(null); - } - - [TestMethod] - public void CanSetServiceCatalog() - { - var endpoint = new Uri("https://auth.someplace.com/authme"); - var userName = "TestUser"; - var password = "RandomPassword"; - var tenantId = "12345"; - - var catalog = new OpenStackServiceCatalog(); - - var cred = new OpenStackCredential(endpoint, userName, password, tenantId); - cred.SetServiceCatalog(catalog); - - Assert.AreEqual(catalog, cred.ServiceCatalog); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotSetServiceCatalogWithNullToken() - { - var endpoint = new Uri("https://auth.someplace.com/authme"); - var userName = "TestUser"; - var password = "RandomPassword"; - var tenantId = "12345"; - - var cred = new OpenStackCredential(endpoint, userName, password, tenantId); - cred.SetServiceCatalog(null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public void CannotSetAcessTokenIdWithEmptyToken() - { - var endpoint = new Uri("https://auth.someplace.com/authme"); - var userName = "TestUser"; - var password = "RandomPassword"; - var tenantId = "12345"; - - var cred = new OpenStackCredential(endpoint, userName, password, tenantId); - cred.SetAccessTokenId(string.Empty); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotCreateAnOpenStackCredentialWithNullEndpoint() - { - var userName = "TestUser"; - var password = "RandomPassword"; - var tenantId = "12345"; - - var cred = new OpenStackCredential(null, userName, password, tenantId); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotCreateAnOpenStackCredentialWithNullUserName() - { - var endpoint = new Uri("https://auth.someplace.com/authme"); - var password = "RandomPassword"; - var tenantId = "12345"; - - var cred = new OpenStackCredential(endpoint, null, password, tenantId); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public void CannotCreateAnOpenStackCredentialWithEmptyUserName() - { - var endpoint = new Uri("https://auth.someplace.com/authme"); - var password = "RandomPassword"; - var tenantId = "12345"; - - var cred = new OpenStackCredential(endpoint, string.Empty, password, tenantId); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotCreateAnOpenStackCredentialWithNullPassword() - { - var endpoint = new Uri("https://auth.someplace.com/authme"); - var userName = "TestUser"; - var tenantId = "12345"; - - var cred = new OpenStackCredential(endpoint, userName, null, tenantId); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotCreateAnOpenStackCredentialWithNullTenantId() - { - var endpoint = new Uri("https://auth.someplace.com/authme"); - var userName = "TestUser"; - var password = "RandomPassword"; - - var cred = new OpenStackCredential(endpoint, userName, password, null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public void CannotCreateAnOpenStackCredentialWithEmptyTenantId() - { - var endpoint = new Uri("https://auth.someplace.com/authme"); - var userName = "TestUser"; - var password = "RandomPassword"; - - var cred = new OpenStackCredential(endpoint, userName, password, string.Empty); - } - } -} diff --git a/OpenStack/OpenStack.Test/Identity/OpenStackRegionResolverTests.cs b/OpenStack/OpenStack.Test/Identity/OpenStackRegionResolverTests.cs deleted file mode 100644 index 8dd5ec5..0000000 --- a/OpenStack/OpenStack.Test/Identity/OpenStackRegionResolverTests.cs +++ /dev/null @@ -1,167 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Identity; - -namespace OpenStack.Test.Identity -{ - [TestClass] - public class OpenStackRegionResolverTests - { - [TestMethod] - public void CanResolveRegion() - { - var expectedRegion = "some region"; - var catalog = new OpenStackServiceCatalog(); - catalog.Add(new OpenStackServiceDefinition("Test Service", "Test-Service", - new List() - { - new OpenStackServiceEndpoint("http://other.endpoint.org", expectedRegion , "1.0", - "http://www.someplace.com", "http://www.someplace.com") - })); - - catalog.Add(new OpenStackServiceDefinition("Other Test Service", "Test-Service", - new List() - { - new OpenStackServiceEndpoint("http://other.endpoint.org", "some other region", "1.0", - "http://www.someplace.com", "http://www.someplace.com") - })); - var resolver = new OpenStackRegionResolver(); - var region = resolver.Resolve(new Uri("http://other.endpoint.org/v2/tokens"), catalog, "Test Service"); - Assert.AreEqual(expectedRegion, region); - } - - [TestMethod] - public void CannotResolveRegionWhenNoEnpointMatches() - { - var expectedRegion = string.Empty; - var catalog = new OpenStackServiceCatalog(); - catalog.Add(new OpenStackServiceDefinition("Test Service", "Test-Service", - new List() - { - new OpenStackServiceEndpoint("http://other.endpoint.org", "Some Region" , "1.0", - "http://www.someplace.com", "http://www.someplace.com") - })); - - catalog.Add(new OpenStackServiceDefinition("Other Test Service", "Test-Service", - new List() - { - new OpenStackServiceEndpoint("http://other.endpoint.org", "some other region", "1.0", - "http://www.someplace.com", "http://www.someplace.com") - })); - var resolver = new OpenStackRegionResolver(); - var region = resolver.Resolve(new Uri("http://nomatching.endpoint.org/v2/tokens"), catalog, "Test Service"); - Assert.AreEqual(expectedRegion, region); - } - - [TestMethod] - public void CannotResolveRegionWhenNoMatchingServices() - { - var expectedRegion = string.Empty; - var catalog = new OpenStackServiceCatalog(); - catalog.Add(new OpenStackServiceDefinition("Test Service", "Test-Service", - new List() - { - new OpenStackServiceEndpoint("http://other.endpoint.org", "Some Region" , "1.0", - "http://www.someplace.com", "http://www.someplace.com") - })); - - catalog.Add(new OpenStackServiceDefinition("Other Test Service", "Test-Service", - new List() - { - new OpenStackServiceEndpoint("http://other.endpoint.org", "some other region", "1.0", - "http://www.someplace.com", "http://www.someplace.com") - })); - var resolver = new OpenStackRegionResolver(); - var region = resolver.Resolve(new Uri("http://nomatching.endpoint.org/v2/tokens"), catalog, "No Matching Service"); - Assert.AreEqual(expectedRegion, region); - } - - [TestMethod] - public void CanResolveRegionWhenNoMatchingServicesButMatchingEndpoint() - { - var expectedRegion = "Some Region"; - var catalog = new OpenStackServiceCatalog(); - catalog.Add(new OpenStackServiceDefinition("Test Service", "Test-Service", - new List() - { - new OpenStackServiceEndpoint("http://the.endpoint.org", "Some Region" , "1.0", - "http://www.someplace.com", "http://www.someplace.com") - })); - - catalog.Add(new OpenStackServiceDefinition("Other Test Service", "Test-Service", - new List() - { - new OpenStackServiceEndpoint("http://other.endpoint.org", "some other region", "1.0", - "http://www.someplace.com", "http://www.someplace.com") - })); - var resolver = new OpenStackRegionResolver(); - var region = resolver.Resolve(new Uri("http://the.endpoint.org/v2/tokens"), catalog, "No Matching Service"); - Assert.AreEqual(expectedRegion, region); - } - - [TestMethod] - public void CannotResolveRegionWhenMatchingEndpointHasEmptyRegion() - { - var expectedRegion = string.Empty; - var catalog = new OpenStackServiceCatalog(); - catalog.Add(new OpenStackServiceDefinition("Test Service", "Test-Service", - new List() - { - new OpenStackServiceEndpoint("http://other.endpoint.org", "Some Region" , "1.0", - "http://www.someplace.com", "http://www.someplace.com") - })); - - catalog[0].Endpoints.First().Region = string.Empty; - - catalog.Add(new OpenStackServiceDefinition("Other Test Service", "Test-Service", - new List() - { - new OpenStackServiceEndpoint("http://other.endpoint.org", "some other region", "1.0", - "http://www.someplace.com", "http://www.someplace.com") - })); - var resolver = new OpenStackRegionResolver(); - var region = resolver.Resolve(new Uri("http://nomatching.endpoint.org/v2/tokens"), catalog, "Test Service"); - Assert.AreEqual(expectedRegion, region); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotResolveRegionWithNullCatalog() - { - var resolver = new OpenStackRegionResolver(); - resolver.Resolve(new Uri("http://other.endpoint.org/v2/tokens"), null, "Test Service"); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotResolveRegionWithNullEndpoint() - { - var catalog = new OpenStackServiceCatalog(); - - var resolver = new OpenStackRegionResolver(); - resolver.Resolve(null, catalog, "Test Service"); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotResolveRegionWithNullServiceName() - { - var catalog = new OpenStackServiceCatalog(); - - var resolver = new OpenStackRegionResolver(); - resolver.Resolve(new Uri("http://other.endpoint.org/v2/tokens"), catalog, null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public void CannotResolveRegionWithEmptyServiceName() - { - var catalog = new OpenStackServiceCatalog(); - - var resolver = new OpenStackRegionResolver(); - resolver.Resolve(new Uri("http://other.endpoint.org/v2/tokens"), catalog, string.Empty); - } - } -} diff --git a/OpenStack/OpenStack.Test/Identity/OpenStackServiceCatalogPayloadConverterTests.cs b/OpenStack/OpenStack.Test/Identity/OpenStackServiceCatalogPayloadConverterTests.cs deleted file mode 100644 index 0e4a455..0000000 --- a/OpenStack/OpenStack.Test/Identity/OpenStackServiceCatalogPayloadConverterTests.cs +++ /dev/null @@ -1,190 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Common.ServiceLocation; -using OpenStack.Identity; - -namespace OpenStack.Test.Identity -{ - [TestClass] - public class OpenStackServiceCatalogPayloadConverterTests - { - [TestMethod] - public void CanConvertJsonPayload() - { - var expectedName = "Object Storage"; - var expectedType = "object-store"; - - var serviceCatalogPayload = @"{ - ""access"": { - - ""serviceCatalog"":[{ - ""name"": ""Object Storage"", - ""type"": ""object-store"", - ""endpoints"": [ - { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1/10244656540440"", - ""region"": ""region-a.geo-1"", - ""versionId"": ""1.0"", - ""versionInfo"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1.0/"", - ""versionList"": ""https://region-a.geo-1.objects.hpcloudsvc.com"" - }, - { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/10244656540440"", - ""region"": ""region-b.geo-1"", - ""versionId"": ""1"", - ""versionInfo"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/"", - ""versionList"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443"" - } - ] - }]}}"; - - var converter = new OpenStackServiceCatalogPayloadConverter(new ServiceLocator()); - var serviceDefs = converter.Convert(serviceCatalogPayload).ToList(); - - Assert.AreEqual(1, serviceDefs.Count()); - - var service = serviceDefs.First(i => i.Name == expectedName); - Assert.IsNotNull(service); - Assert.AreEqual(expectedName, service.Name); - Assert.AreEqual(expectedType, service.Type); - Assert.AreEqual(2, service.Endpoints.Count()); - } - - [TestMethod] - public void CanConvertJsonPayloadWithMultipleServiceDefs() - { - var expectedName1 = "Object Storage"; - var expectedType1 = "object-store"; - - var expectedName2 = "Some Other Service"; - var expectedType2 = "other-service"; - - var serviceCatalogPayload = @"{ - ""access"": { - - ""serviceCatalog"":[{ - ""name"": ""Object Storage"", - ""type"": ""object-store"", - ""endpoints"": [ - { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1/10244656540440"", - ""region"": ""region-a.geo-1"", - ""versionId"": ""1.0"", - ""versionInfo"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1.0/"", - ""versionList"": ""https://region-a.geo-1.objects.hpcloudsvc.com"" - }, - { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/10244656540440"", - ""region"": ""region-b.geo-1"", - ""versionId"": ""1"", - ""versionInfo"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/"", - ""versionList"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443"" - } - ] - }, - { - ""name"": ""Some Other Service"", - ""type"": ""other-service"", - ""endpoints"": [ - { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1/10244656540440"", - ""region"": ""region-a.geo-1"", - ""versionId"": ""1.0"", - ""versionInfo"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1.0/"", - ""versionList"": ""https://region-a.geo-1.objects.hpcloudsvc.com"" - } - ] - }]}}"; - - var converter = new OpenStackServiceCatalogPayloadConverter(new ServiceLocator()); - var serviceDefs = converter.Convert(serviceCatalogPayload).ToList(); - - Assert.AreEqual(2, serviceDefs.Count()); - - var service1 = serviceDefs.First(i => i.Name == expectedName1); - Assert.IsNotNull(service1); - Assert.AreEqual(expectedName1, service1.Name); - Assert.AreEqual(expectedType1, service1.Type); - Assert.AreEqual(2, service1.Endpoints.Count()); - - var service2 = serviceDefs.First(i => i.Name == expectedName2); - Assert.IsNotNull(service1); - Assert.AreEqual(expectedName2, service2.Name); - Assert.AreEqual(expectedType2, service2.Type); - Assert.AreEqual(1, service2.Endpoints.Count()); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertJsonPayloadWithMissingCatalog() - { - var serviceCatalogPayload = @"{ - ""access"": { - - }}"; - - var converter = new OpenStackServiceCatalogPayloadConverter(new ServiceLocator()); - converter.Convert(serviceCatalogPayload); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertJsonPayloadWithEmptyObject() - { - var serviceDefPayload = @" { }"; - - var converter = new OpenStackServiceCatalogPayloadConverter(new ServiceLocator()); - converter.Convert(serviceDefPayload); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotConvertWithNullJsonPayload() - { - var converter = new OpenStackServiceCatalogPayloadConverter(new ServiceLocator()); - converter.Convert(null); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertInvalidJsonPayload() - { - var serviceDefPayload = @" { NOT JSON"; - - var converter = new OpenStackServiceCatalogPayloadConverter(new ServiceLocator()); - converter.Convert(serviceDefPayload); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertNonObjectJsonPayload() - { - var serviceDefPayload = @"[]"; - - var converter = new OpenStackServiceCatalogPayloadConverter(new ServiceLocator()); - converter.Convert(serviceDefPayload); - } - } -} diff --git a/OpenStack/OpenStack.Test/Identity/OpenStackServiceCatalogTests.cs b/OpenStack/OpenStack.Test/Identity/OpenStackServiceCatalogTests.cs deleted file mode 100644 index 359c759..0000000 --- a/OpenStack/OpenStack.Test/Identity/OpenStackServiceCatalogTests.cs +++ /dev/null @@ -1,203 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Identity; - -namespace OpenStack.Test.Identity -{ - [TestClass] - public class OpenStackServiceCatalogTests - { - [TestMethod] - public void IfAServiceExistsCatalogReturnsTrue() - { - var expectedEndpoint = new Uri("http://public.endpoint.org"); - var serviceDef = new OpenStackServiceDefinition("Test Service", "Test-Service", - new List() - { - new OpenStackServiceEndpoint(expectedEndpoint.ToString(), "some region", "1.0", - "http://www.someplace.com", "http://www.someplace.com") - }); - var catalog = new OpenStackServiceCatalog { serviceDef }; - Assert.IsTrue(catalog.Exists("Test Service")); - } - - [TestMethod] - public void IfAServiceDoesNotExistsCatalogReturnsFalse() - { - var expectedEndpoint = new Uri("http://public.endpoint.org"); - var serviceDef = new OpenStackServiceDefinition("Test Service", "Test-Service", - new List() - { - new OpenStackServiceEndpoint(expectedEndpoint.ToString(), "some region", "1.0", - "http://www.someplace.com", "http://www.someplace.com") - }); - var catalog = new OpenStackServiceCatalog { serviceDef }; - Assert.IsFalse(catalog.Exists("NOT IN CATALOG")); - } - - [TestMethod] - public void CanGetServicesInRegion() - { - var expectedEndpoint = new Uri("http://public.endpoint.org"); - var serviceDef = new OpenStackServiceDefinition("Test Service", "Test-Service", - new List() - { - new OpenStackServiceEndpoint(expectedEndpoint.ToString(), "some region", "1.0", - "http://www.someplace.com", "http://www.someplace.com") - }); - var catalog = new OpenStackServiceCatalog { serviceDef }; - var services = catalog.GetServicesInAvailabilityZone("some region").ToList(); - Assert.AreEqual(1,services.Count()); - Assert.AreEqual("Test Service",services.First().Name); - } - - [TestMethod] - public void CanGetServicesInRegionWithMultipleServices() - { - var catalog = new OpenStackServiceCatalog(); - catalog.Add(new OpenStackServiceDefinition("Test Service", "Test-Service", - new List() - { - new OpenStackServiceEndpoint("http://some.endpoint.com", "some region", "1.0", - "http://www.someplace.com", "http://www.someplace.com") - })); - - catalog.Add(new OpenStackServiceDefinition("Other Test Service", "Test-Service", - new List() - { - new OpenStackServiceEndpoint("http://other.endpoint.org", "some region", "1.0", - "http://www.someplace.com", "http://www.someplace.com") - })); - - var services = catalog.GetServicesInAvailabilityZone("some region").ToList(); - Assert.AreEqual(2, services.Count()); - } - - [TestMethod] - public void GettingServicesInRegionWhenNonExistReturnsAnEmptyCollection() - { - var expectedEndpoint = new Uri("http://public.endpoint.org"); - var serviceDef = new OpenStackServiceDefinition("Test Service", "Test-Service", - new List() - { - new OpenStackServiceEndpoint(expectedEndpoint.ToString(), "some region", "1.0", - "http://www.someplace.com", "http://www.someplace.com") - }); - var catalog = new OpenStackServiceCatalog { serviceDef }; - var services = catalog.GetServicesInAvailabilityZone("some other region").ToList(); - Assert.AreEqual(0, services.Count()); - } - - [TestMethod] - public void CanGetServicesForRegionWithMultipleEndpoints() - { - var expectedEndpoint = new Uri("http://public.endpoint.org"); - var serviceDef = new OpenStackServiceDefinition("Test Service", "Test-Service", - new List() - { - new OpenStackServiceEndpoint(expectedEndpoint.ToString(), "some region", "1.0", - "http://www.someplace.com", "http://www.someplace.com"), - new OpenStackServiceEndpoint(expectedEndpoint.ToString(), "some other region", "1.0", - "http://www.someplace.com", "http://www.someplace.com") - }); - var catalog = new OpenStackServiceCatalog { serviceDef }; - var services = catalog.GetServicesInAvailabilityZone("some other region").ToList(); - Assert.AreEqual(1, services.Count()); - } - - [TestMethod] - public void CanGetPublicEndpointForAService() - { - var serviceName = "Test Service"; - var regionName = "some region"; - var expectedEndpoint = "http://public.endpoint.org"; - var serviceDef = new OpenStackServiceDefinition(serviceName, "Test-Service", - new List() - { - new OpenStackServiceEndpoint(expectedEndpoint, "some region", "1.0", - "http://www.someplace.com", "http://www.someplace.com") - }); - - var catalog = new OpenStackServiceCatalog { serviceDef }; - var endpoint = catalog.GetPublicEndpoint(serviceName, regionName); - Assert.AreEqual(expectedEndpoint, endpoint); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotGetPublicEndpointWithANullServiceName() - { - var catalog = new OpenStackServiceCatalog(); - catalog.GetPublicEndpoint(null, "Some region"); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotGetPublicEndpointWithANullRegion() - { - var catalog = new OpenStackServiceCatalog(); - catalog.GetPublicEndpoint("Test Service", null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public void CannotGetPublicEndpointWithAnEmptyServiceName() - { - var catalog = new OpenStackServiceCatalog(); - catalog.GetPublicEndpoint(string.Empty, "Some region"); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public void CannotGetPublicEndpointForAServiceThatIsNotInTheCatalog() - { - var serviceName = "Test Service"; - var regionName = "some region"; - var expectedEndpoint = "http://public.endpoint.org"; - var serviceDef = new OpenStackServiceDefinition(serviceName, "Test-Service", - new List() - { - new OpenStackServiceEndpoint(expectedEndpoint, "some region", "1.0", - "http://www.someplace.com", "http://www.someplace.com") - }); - - var catalog = new OpenStackServiceCatalog { serviceDef }; - catalog.GetPublicEndpoint("Not-In-Catalog", regionName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public void CannotGetPublicEndpointForAServiceThatIsNotInTheRegion() - { - var serviceName = "Test Service"; - var expectedEndpoint = "http://public.endpoint.org"; - var serviceDef = new OpenStackServiceDefinition(serviceName, "Test-Service", - new List() - { - new OpenStackServiceEndpoint(expectedEndpoint, "some region", "1.0", - "http://www.someplace.com", "http://www.someplace.com") - }); - - var catalog = new OpenStackServiceCatalog { serviceDef }; - catalog.GetPublicEndpoint(serviceName, "Not-in-catalog"); - } - } -} diff --git a/OpenStack/OpenStack.Test/Identity/OpenStackServiceDefinitionPayloadConverterTests.cs b/OpenStack/OpenStack.Test/Identity/OpenStackServiceDefinitionPayloadConverterTests.cs deleted file mode 100644 index e37766e..0000000 --- a/OpenStack/OpenStack.Test/Identity/OpenStackServiceDefinitionPayloadConverterTests.cs +++ /dev/null @@ -1,178 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Linq; -using System.Web; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Common.ServiceLocation; -using OpenStack.Identity; - -namespace OpenStack.Test.Identity -{ - [TestClass] - public class OpenStackServiceDefinitionPayloadConverterTests - { - [TestMethod] - public void CanConvertJsonPayload() - { - var expectedName = "Object Storage"; - var expectedType = "object-store"; - - var serviceDefPayload = @" { - ""name"": ""Object Storage"", - ""type"": ""object-store"", - ""endpoints"": [ - { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1/10244656540440"", - ""region"": ""region-a.geo-1"", - ""versionId"": ""1.0"", - ""versionInfo"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1.0/"", - ""versionList"": ""https://region-a.geo-1.objects.hpcloudsvc.com"" - }, - { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/10244656540440"", - ""region"": ""region-b.geo-1"", - ""versionId"": ""1"", - ""versionInfo"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/"", - ""versionList"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443"" - } - ] - }"; - - var converter = new OpenStackServiceDefinitionPayloadConverter(new ServiceLocator()); - var service = converter.Convert(serviceDefPayload); - - Assert.IsNotNull(service); - Assert.AreEqual(expectedName, service.Name); - Assert.AreEqual(expectedType, service.Type); - Assert.AreEqual(2, service.Endpoints.Count()); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertJsonPayloadWithMissingName() - { - var serviceDefPayload = @"{ - ""type"": ""object-store"", - ""endpoints"": [ - { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1/10244656540440"", - ""region"": ""region-a.geo-1"", - ""versionId"": ""1.0"", - ""versionInfo"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1.0/"", - ""versionList"": ""https://region-a.geo-1.objects.hpcloudsvc.com"" - }, - { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/10244656540440"", - ""region"": ""region-b.geo-1"", - ""versionId"": ""1"", - ""versionInfo"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/"", - ""versionList"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443"" - } - ] - }"; - - var converter = new OpenStackServiceDefinitionPayloadConverter(new ServiceLocator()); - converter.Convert(serviceDefPayload); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertJsonPayloadWithMissingType() - { - var serviceDefPayload = @"{ - ""name"": ""Object Storage"", - ""endpoints"": [ - { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1/10244656540440"", - ""region"": ""region-a.geo-1"", - ""versionId"": ""1.0"", - ""versionInfo"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1.0/"", - ""versionList"": ""https://region-a.geo-1.objects.hpcloudsvc.com"" - }, - { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/10244656540440"", - ""region"": ""region-b.geo-1"", - ""versionId"": ""1"", - ""versionInfo"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/"", - ""versionList"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443"" - } - ] - }"; - - var converter = new OpenStackServiceDefinitionPayloadConverter(new ServiceLocator()); - converter.Convert(serviceDefPayload); - } - - [TestMethod] - [ExpectedException(typeof (FormatException))] - public void CannotConvertJsonPayloadWithMissingEndpoints() - { - var serviceDefPayload = @"{ - ""name"": ""Object Storage"", - ""type"": ""object-store"", - }"; - - var converter = new OpenStackServiceDefinitionPayloadConverter(new ServiceLocator()); - converter.Convert(serviceDefPayload); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertJsonPayloadWithEmptyObject() - { - var serviceDefPayload = @" { }"; - - var converter = new OpenStackServiceDefinitionPayloadConverter(new ServiceLocator()); - converter.Convert(serviceDefPayload); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotConvertWithNullJsonPayload() - { - var converter = new OpenStackServiceDefinitionPayloadConverter(new ServiceLocator()); - converter.Convert(null); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertInvalidJsonPayload() - { - var serviceDefPayload = @" { NOT JSON"; - - var converter = new OpenStackServiceDefinitionPayloadConverter(new ServiceLocator()); - converter.Convert(serviceDefPayload); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertNonObjectJsonPayload() - { - var serviceDefPayload = @"[]"; - - var converter = new OpenStackServiceDefinitionPayloadConverter(new ServiceLocator()); - converter.Convert(serviceDefPayload); - } - } -} diff --git a/OpenStack/OpenStack.Test/Identity/OpenStackServiceEndpointPayloadConverterTests.cs b/OpenStack/OpenStack.Test/Identity/OpenStackServiceEndpointPayloadConverterTests.cs deleted file mode 100644 index 207304a..0000000 --- a/OpenStack/OpenStack.Test/Identity/OpenStackServiceEndpointPayloadConverterTests.cs +++ /dev/null @@ -1,252 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Web; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Identity; - -namespace OpenStack.Test.Identity -{ - [TestClass] - public class OpenStackServiceEndpointPayloadConverterTests - { - [TestMethod] - public void CanConvertJsonPayload() - { - var expectedPublicUri = "https://region-a.geo-1.block.hpcloudsvc.com/v1/10244656540440"; - var expectedRegion = "region-a.geo-1"; - var expectedVersion = "1.0"; - var expectedVersionList = "https://region-a.geo-1.block.hpcloudsvc.com"; - var expectedVersionInfo = "https://region-a.geo-1.block.hpcloudsvc.com/v1"; - - var endpointPayload = @" { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1/10244656540440"", - ""publicURL2"": """", - ""region"": ""region-a.geo-1"", - ""versionId"": ""1.0"", - ""versionInfo"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1"", - ""versionList"": ""https://region-a.geo-1.block.hpcloudsvc.com"" - }"; - - var converter = new OpenStackServiceEndpointPayloadConverter(); - var endpoint = converter.Convert(endpointPayload); - - Assert.IsNotNull(endpoint); - Assert.AreEqual(expectedPublicUri, endpoint.PublicUri.ToString()); - Assert.AreEqual(expectedRegion, endpoint.Region); - Assert.AreEqual(expectedVersion, endpoint.Version); - Assert.AreEqual(expectedVersionInfo, endpoint.VersionInformation.ToString()); - Assert.AreEqual(expectedVersionList, endpoint.VersionList.ToString()); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotConvertWithNullJsonPayload() - { - var converter = new OpenStackServiceEndpointPayloadConverter(); - converter.Convert(null); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertJsonPayloadWithMissingPublicUri() - { - var endpointPayload = @" { - ""tenantId"": ""10244656540440"", - ""publicURL2"": """", - ""region"": ""region-a.geo-1"", - ""versionId"": ""1.0"", - ""versionInfo"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1"", - ""versionList"": ""https://region-a.geo-1.block.hpcloudsvc.com"" - }"; - - var converter = new OpenStackServiceEndpointPayloadConverter(); - converter.Convert(endpointPayload); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertJsonPayloadWithMissingRegion() - { - var endpointPayload = @" { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1/10244656540440"", - ""publicURL2"": """", - ""versionId"": ""1.0"", - ""versionInfo"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1"", - ""versionList"": ""https://region-a.geo-1.block.hpcloudsvc.com"" - }"; - - var converter = new OpenStackServiceEndpointPayloadConverter(); - converter.Convert(endpointPayload); - } - - [TestMethod] - public void CanConvertJsonPayloadWithMissingVersion() - { - var endpointPayload = @" { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1/10244656540440"", - ""publicURL2"": """", - ""region"": ""region-a.geo-1"", - ""versionInfo"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1"", - ""versionList"": ""https://region-a.geo-1.block.hpcloudsvc.com"" - }"; - - var converter = new OpenStackServiceEndpointPayloadConverter(); - converter.Convert(endpointPayload); - } - - [TestMethod] - public void CanConvertJsonPayloadWithMissingVersionInfoUri() - { - var endpointPayload = @" { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1/10244656540440"", - ""publicURL2"": """", - ""region"": ""region-a.geo-1"", - ""versionId"": ""1.0"", - ""versionList"": ""https://region-a.geo-1.block.hpcloudsvc.com"" - }"; - - var converter = new OpenStackServiceEndpointPayloadConverter(); - converter.Convert(endpointPayload); - } - - [TestMethod] - public void CanConvertJsonPayloadWithMissingVersionListUri() - { - var endpointPayload = @" { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1/10244656540440"", - ""publicURL2"": """", - ""region"": ""region-a.geo-1"", - ""versionId"": ""1.0"", - ""versionInfo"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1"" - }"; - - var converter = new OpenStackServiceEndpointPayloadConverter(); - converter.Convert(endpointPayload); - } - - [TestMethod] - public void CanConvertJsonPayloadWithBadPublicUri() - { - var endpointPayload = @" { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""httpsBAD://reg&VERYBAD&ion-a.geo-1.block.hpcloudsvc.com/v1/10244656540440"", - ""publicURL2"": """", - ""region"": ""region-a.geo-1"", - ""versionId"": ""1.0"", - ""versionInfo"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1"", - ""versionList"": ""https://region-a.geo-1.block.hpcloudsvc.com"" - }"; - - var converter = new OpenStackServiceEndpointPayloadConverter(); - converter.Convert(endpointPayload); - } - - [TestMethod] - public void CanConvertJsonPayloadWithBadVersionInfoUri() - { - var endpointPayload = @" { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1/10244656540440"", - ""publicURL2"": """", - ""region"": ""region-a.geo-1"", - ""versionId"": ""1.0"", - ""versionInfo"": ""htBADtps://region&BAD&-a.geo-1.block.hpcloudsvc.com/v1"", - ""versionList"": ""https://region-a.geo-1.block.hpcloudsvc.com"" - }"; - - var converter = new OpenStackServiceEndpointPayloadConverter(); - converter.Convert(endpointPayload); - } - - [TestMethod] - public void CanConvertJsonPayloadWithBadVersionListcUri() - { - var endpointPayload = @" { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1/10244656540440"", - ""publicURL2"": """", - ""region"": ""region-a.geo-1"", - ""versionId"": ""1.0"", - ""versionInfo"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1"", - ""versionList"": ""htBADtps://region-a.ge&BAD&o-1.block.hpcloudsvc.com"" - }"; - - var converter = new OpenStackServiceEndpointPayloadConverter(); - converter.Convert(endpointPayload); - } - - [TestMethod] - public void CanConvertJsonPayloadWithEmptyVersionInfoUri() - { - var endpointPayload = @" { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1/10244656540440"", - ""publicURL2"": """", - ""region"": ""region-a.geo-1"", - ""versionId"": ""1.0"", - ""versionInfo"": """", - ""versionList"": ""https://region-a.geo-1.block.hpcloudsvc.com"" - }"; - - var converter = new OpenStackServiceEndpointPayloadConverter(); - converter.Convert(endpointPayload); - } - - [TestMethod] - public void CanConvertJsonPayloadWithEmptyVersionListcUri() - { - var endpointPayload = @" { - ""tenantId"": ""10244656540440"", - ""publicURL"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1/10244656540440"", - ""publicURL2"": """", - ""region"": ""region-a.geo-1"", - ""versionId"": ""1.0"", - ""versionInfo"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1"", - ""versionList"": """" - }"; - - var converter = new OpenStackServiceEndpointPayloadConverter(); - converter.Convert(endpointPayload); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertInvalidJsonPayload() - { - var endpointPayload = @" { NOT JSON"; - - var converter = new OpenStackServiceEndpointPayloadConverter(); - converter.Convert(endpointPayload); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotConvertNonObjectJsonPayload() - { - var endpointPayload = @" [] "; - - var converter = new OpenStackServiceEndpointPayloadConverter(); - converter.Convert(endpointPayload); - } - } -} diff --git a/OpenStack/OpenStack.Test/Identity/TestIdentityServicePocoClient.cs b/OpenStack/OpenStack.Test/Identity/TestIdentityServicePocoClient.cs deleted file mode 100644 index d4886b3..0000000 --- a/OpenStack/OpenStack.Test/Identity/TestIdentityServicePocoClient.cs +++ /dev/null @@ -1,49 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Threading; -using System.Threading.Tasks; -using OpenStack.Common.ServiceLocation; -using OpenStack.Identity; - -namespace OpenStack.Test.Identity -{ - public class TestIdentityServicePocoClient : IIdentityServicePocoClient - { - public Func> AuthenticationDelegate { get; set; } - - public Task Authenticate() - { - return AuthenticationDelegate(); - } - } - - public class TestIdentityServicePocoClientFactory : IIdentityServicePocoClientFactory - { - internal IIdentityServicePocoClient client; - - public TestIdentityServicePocoClientFactory(IIdentityServicePocoClient client) - { - this.client = client; - } - - public IIdentityServicePocoClient Create(IOpenStackCredential credentials, string serviceName, CancellationToken token, IServiceLocator serviceLocator) - { - return client; - } - } -} diff --git a/OpenStack/OpenStack.Test/Identity/TestIdentityServiceRestClient.cs b/OpenStack/OpenStack.Test/Identity/TestIdentityServiceRestClient.cs deleted file mode 100644 index 8918d7a..0000000 --- a/OpenStack/OpenStack.Test/Identity/TestIdentityServiceRestClient.cs +++ /dev/null @@ -1,49 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Threading; -using System.Threading.Tasks; -using OpenStack.Common.Http; -using OpenStack.Common.ServiceLocation; -using OpenStack.Identity; - -namespace OpenStack.Test.Identity -{ - public class TestIdentityServiceRestClient : IIdentityServiceRestClient - { - public IHttpResponseAbstraction Response { get; set; } - - public Task Authenticate() - { - return Task.Factory.StartNew(() => Response); - } - } - - public class TestIdentityServiceRestClientFactory : IIdentityServiceRestClientFactory - { - internal IIdentityServiceRestClient Client; - - public TestIdentityServiceRestClientFactory(IIdentityServiceRestClient client) - { - this.Client = client; - } - - public IIdentityServiceRestClient Create(IOpenStackCredential credential, CancellationToken cancellationToken, IServiceLocator serviceLocator) - { - return Client; - } - } -} diff --git a/OpenStack/OpenStack.Test/Network/FloatingIpPayloadConverterTests.cs b/OpenStack/OpenStack.Test/Network/FloatingIpPayloadConverterTests.cs deleted file mode 100644 index 519682f..0000000 --- a/OpenStack/OpenStack.Test/Network/FloatingIpPayloadConverterTests.cs +++ /dev/null @@ -1,186 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Compute; -using OpenStack.Network; - -namespace OpenStack.Test.Network -{ - [TestClass] - public class FloatingIpPayloadConverterTests - { - internal string CreateFloatingIpJsonFixtrue(string id, string ipAddress, FloatingIpStatus status) - { - var payloadFixture = @"{{ - ""router_id"": ""fafac59b-a94a-4525-8700-f4f448e0ac97"", - ""status"": ""{1}"", - ""tenant_id"": ""ffe683d1060449d09dac0bf9d7a371cd"", - ""floating_network_id"": ""3eaab3f7-d3f2-430f-aa73-d07f39aae8f4"", - ""fixed_ip_address"": ""10.0.0.2"", - ""floating_ip_address"": ""{2}"", - ""port_id"": ""9da94672-6e6b-446c-9579-3dd5484b31fd"", - ""id"": ""{0}"" - }}"; - - return string.Format(payloadFixture, id, status, ipAddress); - } - - [TestMethod] - public void CanParseValidFloatingIpsJsonPayloadWithMultipleIps() - { - var validMultipleIpJsonFixture = @"{{ ""floatingips"": [ {0} ] }}"; - var firstIp = CreateFloatingIpJsonFixtrue("12345", "172.0.0.1", FloatingIpStatus.Active); - var secondIp = CreateFloatingIpJsonFixtrue("54321", "172.0.0.2", FloatingIpStatus.Down); - - var validMultipleIpsJson = string.Format(validMultipleIpJsonFixture, - string.Join(",", new List() { firstIp, secondIp })); - - var converter = new FloatingIpPayloadConverter(); - var floatingIps = converter.ConvertFloatingIps(validMultipleIpsJson).ToList(); - - Assert.AreEqual(2, floatingIps.Count()); - var ip1 = - floatingIps.First(o => string.Equals(o.Id, "12345", StringComparison.InvariantCultureIgnoreCase)); - var ip2 = - floatingIps.First(o => string.Equals(o.Id, "54321", StringComparison.InvariantCultureIgnoreCase)); - Assert.IsNotNull(ip1); - Assert.IsNotNull(ip2); - - Assert.AreEqual("12345", ip1.Id); - Assert.AreEqual("172.0.0.1", ip1.FloatingIpAddress); - Assert.AreEqual(FloatingIpStatus.Active, ip1.Status); - - Assert.AreEqual("54321", ip2.Id); - Assert.AreEqual("172.0.0.2", ip2.FloatingIpAddress); - Assert.AreEqual(FloatingIpStatus.Down, ip2.Status); - } - - [TestMethod] - public void CanConvertValidFloatingIpsJsonPayloadWithSingleNetwork() - { - var validSingleIpJsonPayload = @"{{ ""floatingips"": [ {0} ] }}"; - var firstIp = CreateFloatingIpJsonFixtrue("12345", "172.0.0.1", FloatingIpStatus.Active); - - var validSingleIpPayload = string.Format(validSingleIpJsonPayload, - string.Join(",", new List() { firstIp })); - - var converter = new FloatingIpPayloadConverter(); - var floatingIps = converter.ConvertFloatingIps(validSingleIpPayload).ToList(); - - Assert.AreEqual(1, floatingIps.Count()); - var ip1 = - floatingIps.First(o => string.Equals(o.Id, "12345", StringComparison.InvariantCultureIgnoreCase)); - - Assert.IsNotNull(ip1); - - Assert.AreEqual("12345", ip1.Id); - Assert.AreEqual("172.0.0.1", ip1.FloatingIpAddress); - Assert.AreEqual(FloatingIpStatus.Active, ip1.Status); - } - - [TestMethod] - public void CanParseValidFloatingIpsPayloadWithEmptyJsonArray() - { - var emptyJsonArray = @"{ ""floatingips"": [ ] }"; - - var converter = new FloatingIpPayloadConverter(); - var networks = converter.ConvertFloatingIps(emptyJsonArray).ToList(); - - Assert.AreEqual(0, networks.Count()); - } - - [TestMethod] - public void CanParseAnEmptyFloatingIpsPayload() - { - var payload = string.Empty; - - var converter = new FloatingIpPayloadConverter(); - var networks = converter.ConvertFloatingIps(payload).ToList(); - - Assert.AreEqual(0, networks.Count()); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotParseANullFloatingIpsPayload() - { - var converter = new FloatingIpPayloadConverter(); - converter.ConvertFloatingIps(null); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseInvalidFloatingIpsJsonPayload() - { - var converter = new FloatingIpPayloadConverter(); - converter.ConvertFloatingIps("[ { \"SomeAtrib\" }]"); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseInvalidFloatingIpsPayload() - { - var converter = new FloatingIpPayloadConverter(); - converter.ConvertFloatingIps("NOT JSON"); - } - - [TestMethod] - public void CanConvertValidFloatingIpJsonPayload() - { - var validSingleIpJsonPayload = @"{{ ""floatingip"": {0} }}"; - var firstIp = CreateFloatingIpJsonFixtrue("12345", "172.0.0.1", FloatingIpStatus.Active); - - var validSingleIpPayload = string.Format(validSingleIpJsonPayload, - string.Join(",", new List() { firstIp })); - - var converter = new FloatingIpPayloadConverter(); - var ip1 = converter.Convert(validSingleIpPayload); - - Assert.IsNotNull(ip1); - Assert.AreEqual("12345", ip1.Id); - Assert.AreEqual("172.0.0.1", ip1.FloatingIpAddress); - Assert.AreEqual(FloatingIpStatus.Active, ip1.Status); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotParseANullFloatingIpPayload() - { - var converter = new FloatingIpPayloadConverter(); - converter.Convert(null); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseInvalidFloatingIpJsonPayload() - { - var converter = new FloatingIpPayloadConverter(); - converter.Convert("[ { \"SomeAtrib\" }]"); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseInvalidFloatingIpPayload() - { - var converter = new FloatingIpPayloadConverter(); - converter.Convert("NOT JSON"); - } - } -} diff --git a/OpenStack/OpenStack.Test/Network/NetworkPayloadConverterTests.cs b/OpenStack/OpenStack.Test/Network/NetworkPayloadConverterTests.cs deleted file mode 100644 index 3e5b2eb..0000000 --- a/OpenStack/OpenStack.Test/Network/NetworkPayloadConverterTests.cs +++ /dev/null @@ -1,146 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Compute; -using OpenStack.Network; - -namespace OpenStack.Test.Network -{ - [TestClass] - public class NetworkPayloadConverterTests - { - internal string CreateNetworkJsonFixtrue(string id, string name, NetworkStatus status) - { - var NetworkJsonResponseFixture = @"{{ - ""status"": ""{2}"", - ""subnets"": [ - ""d3839504-ec4c-47a4-b7c7-07af079a48bb"" - ], - ""name"": ""{1}"", - ""router:external"": false, - ""tenant_id"": ""ffe683d1060449d09dac0bf9d7a371cd"", - ""admin_state_up"": true, - ""shared"": false, - ""id"": ""{0}"" - }}"; - - return string.Format(NetworkJsonResponseFixture, id, name, status); - } - - [TestMethod] - public void CanParseValidNetworksJsonPayloadWithMultipleNetworks() - { - var validMultipleNetworkJsonFixture = @"{{ ""networks"": [ {0} ] }}"; - var firstNetwork = CreateNetworkJsonFixtrue("12345", "MyNetwork", NetworkStatus.Active); - var secondNetwork = CreateNetworkJsonFixtrue("54321", "NetworkMy", NetworkStatus.Down); - - var validMultipleNetworksJson = string.Format(validMultipleNetworkJsonFixture, - string.Join(",", new List() { firstNetwork, secondNetwork })); - - var converter = new NetworkPayloadConverter(); - var networks = converter.ConvertNetworks(validMultipleNetworksJson).ToList(); - - Assert.AreEqual(2, networks.Count()); - var ntw1 = - networks.First(o => string.Equals(o.Id, "12345", StringComparison.InvariantCultureIgnoreCase)); - var ntw2 = - networks.First(o => string.Equals(o.Id, "54321", StringComparison.InvariantCultureIgnoreCase)); - Assert.IsNotNull(ntw1); - Assert.IsNotNull(ntw2); - - Assert.AreEqual("12345", ntw1.Id); - Assert.AreEqual("MyNetwork", ntw1.Name); - Assert.AreEqual(NetworkStatus.Active, ntw1.Status); - - Assert.AreEqual("54321", ntw2.Id); - Assert.AreEqual("NetworkMy", ntw2.Name); - Assert.AreEqual(NetworkStatus.Down, ntw2.Status); - } - - [TestMethod] - public void CanConvertValidNetworksJsonPayloadWithSingleNetwork() - { - var validMultipleNetworkJsonFixture = @"{{ ""networks"": [ {0} ] }}"; - var firstNetwork = CreateNetworkJsonFixtrue("12345", "MyNetwork", NetworkStatus.Active); - - var validMultipleNetworksJson = string.Format(validMultipleNetworkJsonFixture, - string.Join(",", new List() { firstNetwork })); - - var converter = new NetworkPayloadConverter(); - var networks = converter.ConvertNetworks(validMultipleNetworksJson).ToList(); - - Assert.AreEqual(1, networks.Count()); - var ntw1 = - networks.First(o => string.Equals(o.Id, "12345", StringComparison.InvariantCultureIgnoreCase)); - - Assert.IsNotNull(ntw1); - - Assert.AreEqual("12345", ntw1.Id); - Assert.AreEqual("MyNetwork", ntw1.Name); - Assert.AreEqual(NetworkStatus.Active, ntw1.Status); - } - - [TestMethod] - public void CanParseValidNetworksPayloadWithEmptyJsonArray() - { - var emptyJsonArray = @"{ ""networks"": [ ] }"; - - var converter = new NetworkPayloadConverter(); - var networks = converter.ConvertNetworks(emptyJsonArray).ToList(); - - Assert.AreEqual(0, networks.Count()); - } - - [TestMethod] - public void CanParseAnEmptyNetworksPayload() - { - var payload = string.Empty; - - var converter = new NetworkPayloadConverter(); - var networks = converter.ConvertNetworks(payload).ToList(); - - Assert.AreEqual(0, networks.Count()); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotParseANullNetworksPayload() - { - var converter = new NetworkPayloadConverter(); - converter.ConvertNetworks(null); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseInvalidNetworksJsonPayload() - { - var converter = new NetworkPayloadConverter(); - converter.ConvertNetworks("[ { \"SomeAtrib\" }]"); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseInvalidNetworksPayload() - { - var converter = new NetworkPayloadConverter(); - converter.ConvertNetworks("NOT JSON"); - } - } -} diff --git a/OpenStack/OpenStack.Test/Network/NetworkRestSimulator.cs b/OpenStack/OpenStack.Test/Network/NetworkRestSimulator.cs deleted file mode 100644 index f3b8bb2..0000000 --- a/OpenStack/OpenStack.Test/Network/NetworkRestSimulator.cs +++ /dev/null @@ -1,277 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.CodeDom.Compiler; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.Mime; -using System.Text; -using System.Threading; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using OpenStack.Common; -using OpenStack.Common.Http; -using OpenStack.Network; - -namespace OpenStack.Test.Network -{ - public class NetworkRestSimulator : RestSimulator - { - internal ICollection Networks { get; private set; } - - internal ICollection FloatingIps { get; private set; } - - public NetworkRestSimulator() : base() - { - this.Networks = new List(); - this.FloatingIps = new List(); - } - - public NetworkRestSimulator(CancellationToken token) - : this() - { - } - - protected override IHttpResponseAbstraction HandleGet() - { - if (this.Uri.Segments.Count() >= 3) - { - switch (this.Uri.Segments[2].TrimEnd('/').ToLower()) - { - case "networks": - return HandleGetNetworks(); - case "floatingips": - return HandleGetFloatingIps(); - } - } - throw new NotImplementedException(); - } - - internal IHttpResponseAbstraction HandleGetNetworks() - { - Stream networkContent; - switch (this.Uri.Segments.Count()) - { - case 3: - //no flavor id given, list all flavors - networkContent = TestHelper.CreateStream(GenerateCollectionPayload(this.Networks, this.GenerateNetworkPayload, "networks")); - break; - default: - //Unknown Uri format - throw new NotImplementedException(); - } - - return TestHelper.CreateResponse(HttpStatusCode.OK, new Dictionary(), networkContent); - } - - internal IHttpResponseAbstraction HandleGetFloatingIps() - { - Stream floatingIpContent; - switch (this.Uri.Segments.Count()) - { - case 3: - floatingIpContent = TestHelper.CreateStream(GenerateCollectionPayload(this.FloatingIps, this.GenerateFloatingIpPayload, "floatingips")); - break; - case 4: - var floatId = this.Uri.Segments[3].TrimEnd('/').ToLower(); - return HandleGetFloatingIp(floatId); - default: - //Unknown Uri format - throw new NotImplementedException(); - } - - return TestHelper.CreateResponse(HttpStatusCode.OK, new Dictionary(), floatingIpContent); - } - - internal IHttpResponseAbstraction HandleGetFloatingIp(string floatingIpId) - { - var payloadFixture = @"{{ - ""floatingip"": {0} - }}"; - - var floatIp = this.FloatingIps.FirstOrDefault(ip => ip.Id == floatingIpId); - if (floatIp == null) - { - return TestHelper.CreateResponse(HttpStatusCode.NotFound); - } - - var floatIpContent = string.Format(payloadFixture, GenerateFloatingIpPayload(floatIp)).ConvertToStream(); - return TestHelper.CreateResponse(HttpStatusCode.OK, new Dictionary(), floatIpContent); - } - - protected override IHttpResponseAbstraction HandlePost() - { - if (this.Uri.Segments.Count() >= 3) - { - switch (this.Uri.Segments[2].TrimEnd('/').ToLower()) - { - case "floatingips": - return HandleCreateFloatingIp(); - } - } - throw new NotImplementedException(); - } - - internal IHttpResponseAbstraction HandleCreateFloatingIp() - { - var payloadFixture = @"{{ - ""floatingip"": {0} - }}"; - - var ip = new FloatingIp(Guid.NewGuid().ToString(), "172.0.0." +(this.FloatingIps.Count +1), FloatingIpStatus.Active); - this.FloatingIps.Add(ip); - var floatIpContent = string.Format(payloadFixture, GenerateFloatingIpPayload(ip)).ConvertToStream(); - return TestHelper.CreateResponse(HttpStatusCode.Created, new Dictionary(), floatIpContent); - } - - protected override IHttpResponseAbstraction HandlePut() - { - throw new NotImplementedException(); - } - - protected override IHttpResponseAbstraction HandleDelete() - { - if (this.Uri.Segments.Count() >= 3) - { - switch (this.Uri.Segments[2].TrimEnd('/').ToLower()) - { - case "floatingips": - if (this.Uri.Segments.Count() == 4) - { - var floatId = this.Uri.Segments[3].TrimEnd('/').ToLower(); - return HandleDeleteFloatingIps(floatId); - } - break; - default: - throw new NotImplementedException(); - } - } - throw new NotImplementedException(); - } - - internal IHttpResponseAbstraction HandleDeleteFloatingIps(string floatingIpId) - { - var floatIp = this.FloatingIps.FirstOrDefault(ip => ip.Id == floatingIpId); - if (floatIp == null) - { - return TestHelper.CreateResponse(HttpStatusCode.NotFound); - } - - this.FloatingIps.Remove(floatIp); - return TestHelper.CreateResponse(HttpStatusCode.NoContent, new Dictionary()); - } - - - protected override IHttpResponseAbstraction HandleHead() - { - throw new NotImplementedException(); - } - - protected override IHttpResponseAbstraction HandleCopy() - { - throw new NotImplementedException(); - } - - private string GenerateCollectionPayload(IEnumerable collection, Func genFunc, - string collectionName) - { - var payload = new StringBuilder(); - payload.Append(string.Format("{{ \"{0}\": [", collectionName)); - var first = true; - foreach (var item in collection) - { - if (!first) - { - payload.Append(","); - } - - payload.Append(genFunc(item)); - first = false; - } - payload.Append("] }"); - return payload.ToString(); - } - - private string GenerateNetworkPayload(OpenStack.Network.Network network) - { - var payloadFixture = @"{{ - ""status"": ""{2}"", - ""subnets"": [ - ""d3839504-ec4c-47a4-b7c7-07af079a48bb"" - ], - ""name"": ""{0}"", - ""router:external"": false, - ""tenant_id"": ""ffe683d1060449d09dac0bf9d7a371cd"", - ""admin_state_up"": true, - ""shared"": false, - ""id"": ""{1}"" - }}"; - return string.Format(payloadFixture, network.Name, network.Id, network.Status.ToString().ToUpper()); - } - - private string GenerateFloatingIpPayload(FloatingIp floatingIp) - { - var payloadFixture = @"{{ - ""router_id"": ""fafac59b-a94a-4525-8700-f4f448e0ac97"", - ""status"": ""{1}"", - ""tenant_id"": ""ffe683d1060449d09dac0bf9d7a371cd"", - ""floating_network_id"": ""3eaab3f7-d3f2-430f-aa73-d07f39aae8f4"", - ""fixed_ip_address"": ""10.0.0.2"", - ""floating_ip_address"": ""{2}"", - ""port_id"": ""9da94672-6e6b-446c-9579-3dd5484b31fd"", - ""id"": ""{0}"" - }}"; - return string.Format(payloadFixture, floatingIp.Id, floatingIp.Status.ToString().ToUpper(), floatingIp.FloatingIpAddress); - } - } - - public class NetworkRestSimulatorFactory : IHttpAbstractionClientFactory - { - internal NetworkRestSimulator Simulator = null; - - public NetworkRestSimulatorFactory(NetworkRestSimulator simulator) - { - this.Simulator = simulator; - } - - public IHttpAbstractionClient Create() - { - throw new NotImplementedException(); - } - - public IHttpAbstractionClient Create(CancellationToken token) - { - if (this.Simulator != null) - { - this.Simulator.Headers.Clear(); - } - return this.Simulator ?? new NetworkRestSimulator(token); - } - - public IHttpAbstractionClient Create(TimeSpan timeout) - { - throw new NotImplementedException(); - } - - public IHttpAbstractionClient Create(TimeSpan timeout, CancellationToken token) - { - throw new NotImplementedException(); - } - } -} diff --git a/OpenStack/OpenStack.Test/Network/NetworkServiceClientTests.cs b/OpenStack/OpenStack.Test/Network/NetworkServiceClientTests.cs deleted file mode 100644 index 513278e..0000000 --- a/OpenStack/OpenStack.Test/Network/NetworkServiceClientTests.cs +++ /dev/null @@ -1,192 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Common.ServiceLocation; -using OpenStack.Identity; -using OpenStack.Network; - -namespace OpenStack.Test.Network -{ - [TestClass] - public class NetworkServiceClientTests - { - internal TestNetworkServicePocoClient ServicePocoClient; - - internal string authId = "12345"; - internal string endpoint = "http://testcomputeendpoint.com/v2/1234567890"; - internal ServiceLocator ServiceLocator; - - [TestInitialize] - public void TestSetup() - { - this.ServicePocoClient = new TestNetworkServicePocoClient(); - this.ServiceLocator = new ServiceLocator(); - - var manager = this.ServiceLocator.Locate(); - manager.RegisterServiceInstance(typeof(INetworkServicePocoClientFactory), new TestNetworkServicePocoClientFactory(this.ServicePocoClient)); - } - - [TestCleanup] - public void TestCleanup() - { - this.ServicePocoClient = new TestNetworkServicePocoClient(); - this.ServiceLocator = new ServiceLocator(); - } - - IOpenStackCredential GetValidCreds() - { - var catalog = new OpenStackServiceCatalog(); - catalog.Add(new OpenStackServiceDefinition("Neutron", "Network Service", - new List() - { - new OpenStackServiceEndpoint(endpoint, string.Empty, "some version", "some version info", "1,2,3") - })); - - var creds = new OpenStackCredential(new Uri(this.endpoint), "SomeUser", "Password", "SomeTenant"); - creds.SetAccessTokenId(this.authId); - creds.SetServiceCatalog(catalog); - return creds; - } - - [TestMethod] - public async Task CanGetNetworks() - { - var ntw1 = new OpenStack.Network.Network("12345","MyNetwork", NetworkStatus.Active); - var ntw2 = new OpenStack.Network.Network("54321", "NetworkMy", NetworkStatus.Down); - var networks = new List() { ntw1, ntw2 }; - - this.ServicePocoClient.GetNetworksDelegate = () => Task.Factory.StartNew(() => (IEnumerable)networks); - - var client = new NetworkServiceClient(GetValidCreds(), "Neutron", CancellationToken.None, this.ServiceLocator); - var resp = await client.GetNetworks(); - Assert.IsNotNull(resp); - - var respNetworks = resp.ToList(); - Assert.AreEqual(2, respNetworks.Count()); - Assert.AreEqual(ntw1, respNetworks[0]); - Assert.AreEqual(ntw2, respNetworks[1]); - } - - [TestMethod] - public async Task CanGetFloatingIps() - { - var ip1 = new OpenStack.Network.FloatingIp("12345", "172.0.0.1", FloatingIpStatus.Active); - var ip2 = new OpenStack.Network.FloatingIp("54321", "172.0.0.2", FloatingIpStatus.Down); - var ips = new List() { ip1, ip2 }; - - this.ServicePocoClient.GetFloatingIpsDelegate = () => Task.Factory.StartNew(() => (IEnumerable)ips); - - var client = new NetworkServiceClient(GetValidCreds(), "Neutron", CancellationToken.None, this.ServiceLocator); - var resp = await client.GetFloatingIps(); - Assert.IsNotNull(resp); - - var respIps = resp.ToList(); - Assert.AreEqual(2, respIps.Count()); - Assert.AreEqual(ip1, respIps[0]); - Assert.AreEqual(ip2, respIps[1]); - } - - [TestMethod] - public async Task CanGetFloatingIp() - { - var ip1 = new OpenStack.Network.FloatingIp("12345", "172.0.0.1", FloatingIpStatus.Active); - - this.ServicePocoClient.GetFloatingIpDelegate = (ip) => Task.Factory.StartNew(() => ip1); - - var client = new NetworkServiceClient(GetValidCreds(), "Neutron", CancellationToken.None, this.ServiceLocator); - var resp = await client.GetFloatingIp("12345"); - Assert.IsNotNull(resp); - Assert.AreEqual(ip1, resp); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task GetFloatingIpWithNullFloatingIpIdThrows() - { - var client = new NetworkServiceClient(GetValidCreds(), "Neutron", CancellationToken.None, this.ServiceLocator); - await client.GetFloatingIp(null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task GetFloatingIpWithEmptyFloatingIpIdThrows() - { - var client = new NetworkServiceClient(GetValidCreds(), "Neutron", CancellationToken.None, this.ServiceLocator); - await client.GetFloatingIp(string.Empty); - } - - [TestMethod] - public async Task CanCreateFloatingIp() - { - var ip1 = new OpenStack.Network.FloatingIp("12345", "172.0.0.1", FloatingIpStatus.Active); - - this.ServicePocoClient.CreateFloatingIpDelegate = (ip) => Task.Factory.StartNew(() => ip1); - - var client = new NetworkServiceClient(GetValidCreds(), "Neutron", CancellationToken.None, this.ServiceLocator); - var resp = await client.CreateFloatingIp("12345"); - Assert.IsNotNull(resp); - Assert.AreEqual(ip1, resp); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CreateFloatingIpWithNullNetworkIdThrows() - { - var client = new NetworkServiceClient(GetValidCreds(), "Neutron", CancellationToken.None, this.ServiceLocator); - await client.CreateFloatingIp(null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CreateFloatingIpWithEmptyNetworkIdThrows() - { - var client = new NetworkServiceClient(GetValidCreds(), "Neutron", CancellationToken.None, this.ServiceLocator); - await client.CreateFloatingIp(string.Empty); - } - - [TestMethod] - public async Task CanDeleteFloatingIp() - { - var ipId = "12345"; - this.ServicePocoClient.DeleteFloatingIpDelegate = (ip) => Task.Factory.StartNew(() => Assert.AreEqual(ipId, ip)); - - var client = new NetworkServiceClient(GetValidCreds(), "Neutron", CancellationToken.None, this.ServiceLocator); - await client.DeleteFloatingIp(ipId); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task DeleteFloatingIpWithNullFloatingIpIdThrows() - { - var client = new NetworkServiceClient(GetValidCreds(), "Neutron", CancellationToken.None, this.ServiceLocator); - await client.DeleteFloatingIp(null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task DeleteFloatingIpWithEmptyFloatingIpIdThrows() - { - var client = new NetworkServiceClient(GetValidCreds(), "Neutron", CancellationToken.None, this.ServiceLocator); - await client.DeleteFloatingIp(string.Empty); - } - } -} diff --git a/OpenStack/OpenStack.Test/Network/NetworkServicePocoClientTests.cs b/OpenStack/OpenStack.Test/Network/NetworkServicePocoClientTests.cs deleted file mode 100644 index 79cfe84..0000000 --- a/OpenStack/OpenStack.Test/Network/NetworkServicePocoClientTests.cs +++ /dev/null @@ -1,363 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using OpenStack.Common.Http; -using OpenStack.Common.ServiceLocation; -using OpenStack.Identity; -using OpenStack.Network; - -namespace OpenStack.Test.Network -{ - [TestClass] - public class NetworkServicePocoClientTests - { - internal TestNetworkServiceRestClient NetworkServiceRestClient; - internal string authId = "12345"; - internal Uri endpoint = new Uri("http://testnetworkendpoint.com/v2.0/1234567890"); - internal IServiceLocator ServiceLocator; - - [TestInitialize] - public void TestSetup() - { - this.NetworkServiceRestClient = new TestNetworkServiceRestClient(); - this.ServiceLocator = new ServiceLocator(); - - var manager = this.ServiceLocator.Locate(); - manager.RegisterServiceInstance(typeof(INetworkServiceRestClientFactory), new TestNetworkServiceRestClientFactory(this.NetworkServiceRestClient)); - } - - [TestCleanup] - public void TestCleanup() - { - this.NetworkServiceRestClient = new TestNetworkServiceRestClient(); - this.ServiceLocator = new ServiceLocator(); - } - - ServiceClientContext GetValidContext() - { - var creds = new OpenStackCredential(this.endpoint, "SomeUser", "Password", "SomeTenant", "region-a.geo-1"); - creds.SetAccessTokenId(this.authId); - - return new ServiceClientContext(creds, CancellationToken.None, "Object Storage", endpoint); - } - - #region Get Networks Tests - - [TestMethod] - public async Task CanGetNetworksWithOkResponse() - { - var payload = @"{ - ""networks"": [ - { - ""status"": ""ACTIVE"", - ""subnets"": [ - ""d3839504-ec4c-47a4-b7c7-07af079a48bb"" - ], - ""name"": ""myNetwork"", - ""router:external"": false, - ""tenant_id"": ""ffe683d1060449d09dac0bf9d7a371cd"", - ""admin_state_up"": true, - ""shared"": false, - ""id"": ""12345"" - } - ] - }"; - - var content = TestHelper.CreateStream(payload); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.OK); - this.NetworkServiceRestClient.Responses.Enqueue(restResp); - - var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.GetNetworks(); - - Assert.IsNotNull(result); - - var networks = result.ToList(); - Assert.AreEqual(1, networks.Count()); - - var network = networks.First(); - Assert.AreEqual("myNetwork", network.Name); - Assert.AreEqual("12345", network.Id); - Assert.AreEqual(NetworkStatus.Active, network.Status); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task CannotGetNetworksWithNoContent() - { - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.NoContent); - this.NetworkServiceRestClient.Responses.Enqueue(restResp); - - var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetNetworks(); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingNetworksAndNotAuthed() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.NetworkServiceRestClient.Responses.Enqueue(restResp); - - var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetNetworks(); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingNetworksAndServerError() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.NetworkServiceRestClient.Responses.Enqueue(restResp); - - var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetNetworks(); - } - - #endregion - - #region Get Floating IPs Tests - - [TestMethod] - public async Task CanGetFloatingIpsWithOkResponse() - { - var payload = @"{ - ""floatingips"": [ - { - ""router_id"": ""fafac59b-a94a-4525-8700-f4f448e0ac97"", - ""status"": ""ACTIVE"", - ""tenant_id"": ""ffe683d1060449d09dac0bf9d7a371cd"", - ""floating_network_id"": ""3eaab3f7-d3f2-430f-aa73-d07f39aae8f4"", - ""fixed_ip_address"": ""10.0.0.2"", - ""floating_ip_address"": ""172.0.0.1"", - ""port_id"": ""9da94672-6e6b-446c-9579-3dd5484b31fd"", - ""id"": ""12345"" - } - ] - }"; - - var content = TestHelper.CreateStream(payload); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.OK); - this.NetworkServiceRestClient.Responses.Enqueue(restResp); - - var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.GetFloatingIps(); - - Assert.IsNotNull(result); - - var floatingIps = result.ToList(); - Assert.AreEqual(1, floatingIps.Count()); - - var floatingIp = floatingIps.First(); - Assert.AreEqual("12345", floatingIp.Id); - Assert.AreEqual("172.0.0.1", floatingIp.FloatingIpAddress); - Assert.AreEqual(FloatingIpStatus.Active, floatingIp.Status); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingFloatingIpsAndNotAuthed() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.NetworkServiceRestClient.Responses.Enqueue(restResp); - - var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetFloatingIps(); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingFloatingIpsAndServerError() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.NetworkServiceRestClient.Responses.Enqueue(restResp); - - var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetFloatingIps(); - } - - #endregion - - #region Get Floating IP Tests - - [TestMethod] - public async Task CanGetFloatingIpWithOkResponse() - { - var payload = @"{ - ""floatingip"": - { - ""router_id"": ""fafac59b-a94a-4525-8700-f4f448e0ac97"", - ""status"": ""ACTIVE"", - ""tenant_id"": ""ffe683d1060449d09dac0bf9d7a371cd"", - ""floating_network_id"": ""3eaab3f7-d3f2-430f-aa73-d07f39aae8f4"", - ""fixed_ip_address"": ""10.0.0.2"", - ""floating_ip_address"": ""172.0.0.1"", - ""port_id"": ""9da94672-6e6b-446c-9579-3dd5484b31fd"", - ""id"": ""12345"" - } - }"; - - var content = TestHelper.CreateStream(payload); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.OK); - this.NetworkServiceRestClient.Responses.Enqueue(restResp); - - var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.GetFloatingIp("12345"); - - Assert.IsNotNull(result); - - Assert.AreEqual("12345", result.Id); - Assert.AreEqual("172.0.0.1", result.FloatingIpAddress); - Assert.AreEqual(FloatingIpStatus.Active, result.Status); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingFloatingIpAndNotAuthed() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.NetworkServiceRestClient.Responses.Enqueue(restResp); - - var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetFloatingIp("12345"); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingFloatingIpAndServerError() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.NetworkServiceRestClient.Responses.Enqueue(restResp); - - var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetFloatingIp("12345"); - } - - #endregion - - #region Create Floating IP Tests - - [TestMethod] - public async Task CanCreateFloatingIpWithCreatedResponse() - { - var payload = @"{ - ""floatingip"": - { - ""router_id"": ""fafac59b-a94a-4525-8700-f4f448e0ac97"", - ""status"": ""ACTIVE"", - ""tenant_id"": ""ffe683d1060449d09dac0bf9d7a371cd"", - ""floating_network_id"": ""3eaab3f7-d3f2-430f-aa73-d07f39aae8f4"", - ""fixed_ip_address"": ""10.0.0.2"", - ""floating_ip_address"": ""172.0.0.1"", - ""port_id"": ""9da94672-6e6b-446c-9579-3dd5484b31fd"", - ""id"": ""12345"" - } - }"; - - var content = TestHelper.CreateStream(payload); - - var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.Created); - this.NetworkServiceRestClient.Responses.Enqueue(restResp); - - var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.CreateFloatingIp("12345"); - - Assert.IsNotNull(result); - - Assert.AreEqual("12345", result.Id); - Assert.AreEqual("172.0.0.1", result.FloatingIpAddress); - Assert.AreEqual(FloatingIpStatus.Active, result.Status); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenCreatingFloatingIpAndNotAuthed() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.NetworkServiceRestClient.Responses.Enqueue(restResp); - - var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.CreateFloatingIp("12345"); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenCreatingFloatingIpAndServerError() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.NetworkServiceRestClient.Responses.Enqueue(restResp); - - var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.CreateFloatingIp("12345"); - } - - #endregion - - #region Delete Floating IP Tests - - [TestMethod] - public async Task CanDeleteFloatingIpWithNoContentResponse() - { - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.NoContent); - this.NetworkServiceRestClient.Responses.Enqueue(restResp); - - var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteFloatingIp("12345"); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenDeletingFloatingIpAndNotAuthed() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.NetworkServiceRestClient.Responses.Enqueue(restResp); - - var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteFloatingIp("12345"); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenDeletingFloatingIpAndServerError() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.NetworkServiceRestClient.Responses.Enqueue(restResp); - - var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteFloatingIp("12345"); - } - - #endregion - - } -} diff --git a/OpenStack/OpenStack.Test/Network/NetworkServiceRestClientTests.cs b/OpenStack/OpenStack.Test/Network/NetworkServiceRestClientTests.cs deleted file mode 100644 index bbabb1c..0000000 --- a/OpenStack/OpenStack.Test/Network/NetworkServiceRestClientTests.cs +++ /dev/null @@ -1,308 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Newtonsoft.Json.Linq; -using OpenStack.Common.Http; -using OpenStack.Common.ServiceLocation; -using OpenStack.Compute; -using OpenStack.Identity; -using OpenStack.Network; - -namespace OpenStack.Test.Network -{ - [TestClass] - public class NetworkServiceRestClientTests - { - internal NetworkRestSimulator simulator; - internal string authId = "12345"; - internal Uri endpoint = new Uri("http://testnetworkendpoint.com"); - internal IServiceLocator ServiceLocator; - - [TestInitialize] - public void TestSetup() - { - this.simulator = new NetworkRestSimulator(); - this.ServiceLocator = new ServiceLocator(); - - var manager = this.ServiceLocator.Locate(); - manager.RegisterServiceInstance(typeof(IHttpAbstractionClientFactory), new NetworkRestSimulatorFactory(simulator)); - } - - [TestCleanup] - public void TestCleanup() - { - this.simulator = new NetworkRestSimulator(); - this.ServiceLocator = new ServiceLocator(); - } - - ServiceClientContext GetValidContext() - { - return GetValidContext(CancellationToken.None); - } - - ServiceClientContext GetValidContext(CancellationToken token) - { - var creds = new OpenStackCredential(this.endpoint, "SomeUser", "Password", "SomeTenant", "region-a.geo-1"); - creds.SetAccessTokenId(this.authId); - - return new ServiceClientContext(creds, token, "Nova", endpoint); - } - - #region Get Networks Test - - [TestMethod] - public async Task GetNetworksIncludesAuthHeader() - { - var client = - new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetNetworks(); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task GetNetworksFormsCorrectUrlAndMethod() - { - var client = - new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetNetworks(); - - Assert.AreEqual(string.Format("{0}/networks", endpoint +"v2.0"), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Get, this.simulator.Method); - } - - [TestMethod] - public async Task CanGetNetworks() - { - this.simulator.Networks.Add(new OpenStack.Network.Network("12345","MyNetwork", NetworkStatus.Active)); - - var client = - new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetNetworks(); - - Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); - - var respContent = TestHelper.GetStringFromStream(resp.Content); - Assert.IsTrue(respContent.Length > 0); - } - - #endregion - - #region Get FloatingIps Tests - - [TestMethod] - public async Task GetFloatingIpsIncludesAuthHeader() - { - var client = - new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetFloatingIps(); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task GetFloatingIpsFormsCorrectUrlAndMethod() - { - var client = - new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetFloatingIps(); - - Assert.AreEqual(string.Format("{0}/floatingips", endpoint + "v2.0"), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Get, this.simulator.Method); - } - - [TestMethod] - public async Task CanGetFloatingIps() - { - this.simulator.FloatingIps.Add(new OpenStack.Network.FloatingIp("12345", "172.0.0.1", FloatingIpStatus.Active)); - - var client = - new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetFloatingIps(); - - Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); - - var respContent = TestHelper.GetStringFromStream(resp.Content); - Assert.IsTrue(respContent.Length > 0); - } - - #endregion - - #region Get FloatingIp Tests - - [TestMethod] - public async Task GetFloatingIpIncludesAuthHeader() - { - var client = - new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetNetworks(); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task GetFloatingIpFormsCorrectUrlAndMethod() - { - var client = - new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetFloatingIp("12345"); - - Assert.AreEqual(string.Format("{0}/floatingips/12345", endpoint + "v2.0"), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Get, this.simulator.Method); - } - - [TestMethod] - public async Task CanGetFloatinIp() - { - this.simulator.FloatingIps.Add(new OpenStack.Network.FloatingIp("12345", "172.0.0.1", FloatingIpStatus.Active)); - - var client = - new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetFloatingIp("12345"); - - Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); - - var respContent = TestHelper.GetStringFromStream(resp.Content); - Assert.IsTrue(respContent.Length > 0); - } - - #endregion - - #region Create FloatingIp Tests - - [TestMethod] - public async Task CreateFloatingIpIncludesAuthHeader() - { - var client = - new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.CreateFloatingIp("12345"); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task CreateFloatingIpFormsCorrectUrlAndMethod() - { - var client = - new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.CreateFloatingIp("12345"); - - Assert.AreEqual(string.Format("{0}/floatingips", endpoint + "v2.0"), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Post, this.simulator.Method); - } - - [TestMethod] - public async Task CanCreateFloatinIp() - { - var client = - new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.CreateFloatingIp("12345"); - - Assert.AreEqual(HttpStatusCode.Created, resp.StatusCode); - - var respContent = TestHelper.GetStringFromStream(resp.Content); - Assert.IsTrue(respContent.Length > 0); - } - - [TestMethod] - public async Task CreateFloatinIpFormCorrectBody() - { - var client = - new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.CreateFloatingIp("12345"); - - Assert.AreEqual(HttpStatusCode.Created, resp.StatusCode); - - this.simulator.Content.Position = 0; - var body = TestHelper.GetStringFromStream(this.simulator.Content); - var ipObj = JObject.Parse(body); - Assert.IsNotNull(ipObj); - Assert.IsNotNull(ipObj["floatingip"]); - Assert.IsNotNull(ipObj["floatingip"]["floating_network_id"]); - Assert.AreEqual("12345", (string)ipObj["floatingip"]["floating_network_id"]); - } - - #endregion - - #region Delete Floating Ip Tests - - [TestMethod] - public async Task DeleteFloatingIpIncludesAuthHeader() - { - var client = - new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.DeleteFloatingIp("12345"); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task DeleteFloatingIpFormsCorrectUrlAndMethod() - { - var floatingIpId = "12345"; - var client = - new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.DeleteFloatingIp(floatingIpId); - - Assert.AreEqual(string.Format("{0}/floatingips/{1}", endpoint + "v2.0", floatingIpId), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Delete, this.simulator.Method); - } - - [TestMethod] - public async Task CanDeleteFloatinIp() - { - this.simulator.FloatingIps.Add(new FloatingIp("12345", "172.0.0.1", FloatingIpStatus.Active)); - var client = - new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.DeleteFloatingIp("12345"); - - Assert.AreEqual(HttpStatusCode.NoContent, resp.StatusCode); - - Assert.AreEqual(0, this.simulator.FloatingIps.Count); - } - - #endregion - } -} diff --git a/OpenStack/OpenStack.Test/Network/TestNetworkServicePocoClient.cs b/OpenStack/OpenStack.Test/Network/TestNetworkServicePocoClient.cs deleted file mode 100644 index eeafa80..0000000 --- a/OpenStack/OpenStack.Test/Network/TestNetworkServicePocoClient.cs +++ /dev/null @@ -1,77 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using OpenStack.Common.ServiceLocation; -using OpenStack.Network; - -namespace OpenStack.Test.Network -{ - public class TestNetworkServicePocoClient : INetworkServicePocoClient - { - public Func>> GetNetworksDelegate { get; set; } - - public Func>> GetFloatingIpsDelegate { get; set; } - - public Func> GetFloatingIpDelegate { get; set; } - - public Func> CreateFloatingIpDelegate { get; set; } - - public Func DeleteFloatingIpDelegate { get; set; } - - public async Task> GetNetworks() - { - return await this.GetNetworksDelegate(); - } - - public async Task> GetFloatingIps() - { - return await GetFloatingIpsDelegate(); - } - - public async Task GetFloatingIp(string floatingIpId) - { - return await GetFloatingIpDelegate(floatingIpId); - } - - public async Task CreateFloatingIp(string networkId) - { - return await CreateFloatingIpDelegate(networkId); - } - - public async Task DeleteFloatingIp(string floatingIpId) - { - await DeleteFloatingIpDelegate(floatingIpId); - } - } - - public class TestNetworkServicePocoClientFactory : INetworkServicePocoClientFactory - { - internal INetworkServicePocoClient client; - - public TestNetworkServicePocoClientFactory(INetworkServicePocoClient client) - { - this.client = client; - } - - public INetworkServicePocoClient Create(ServiceClientContext context, IServiceLocator serviceLocator) - { - return client; - } - } -} diff --git a/OpenStack/OpenStack.Test/Network/TestNetworkServiceRestClient.cs b/OpenStack/OpenStack.Test/Network/TestNetworkServiceRestClient.cs deleted file mode 100644 index edd03d3..0000000 --- a/OpenStack/OpenStack.Test/Network/TestNetworkServiceRestClient.cs +++ /dev/null @@ -1,74 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; -using System.Threading.Tasks; -using OpenStack.Common.Http; -using OpenStack.Common.ServiceLocation; -using OpenStack.Network; - -namespace OpenStack.Test.Network -{ - public class TestNetworkServiceRestClient : INetworkServiceRestClient - { - public TestNetworkServiceRestClient() - { - this.Responses = new Queue(); - } - - public Queue Responses { get; set; } - - public Task GetNetworks() - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task GetFloatingIps() - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task GetFloatingIp(string floatingIpId) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task CreateFloatingIp(string networkId) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task DeleteFloatingIp(string floatingIpId) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - } - - public class TestNetworkServiceRestClientFactory : INetworkServiceRestClientFactory - { - internal INetworkServiceRestClient Client; - - public TestNetworkServiceRestClientFactory(INetworkServiceRestClient client) - { - this.Client = client; - } - - public INetworkServiceRestClient Create(ServiceClientContext context, IServiceLocator serviceLocator) - { - return Client; - } - } -} diff --git a/OpenStack/OpenStack.Test/OpenStack.Test.csproj b/OpenStack/OpenStack.Test/OpenStack.Test.csproj deleted file mode 100644 index 8acbb39..0000000 --- a/OpenStack/OpenStack.Test/OpenStack.Test.csproj +++ /dev/null @@ -1,161 +0,0 @@ - - - - Debug - AnyCPU - {7AF6DEC5-2257-4A29-BB55-66711DE3055D} - Library - Properties - OpenStack.Test - OpenStack.Test - v4.5 - 512 - {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - 10.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages - False - UnitTest - - - true - full - false - ..\bin\net45\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - ..\bin\net45\Release\ - TRACE - prompt - 4 - - - - False - ..\packages\Newtonsoft.Json.6.0.2\lib\net45\Newtonsoft.Json.dll - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Properties\AssemblyVersionInfo.cs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {5660f8aa-14d5-4b3b-ada0-f79a286ef483} - OpenStack45-PCL - - - - - - - False - - - False - - - False - - - False - - - - - - - - \ No newline at end of file diff --git a/OpenStack/OpenStack.Test/OpenStackClientManagerTests.cs b/OpenStack/OpenStack.Test/OpenStackClientManagerTests.cs deleted file mode 100644 index 729c0ca..0000000 --- a/OpenStack/OpenStack.Test/OpenStackClientManagerTests.cs +++ /dev/null @@ -1,358 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Common.ServiceLocation; -using OpenStack.Identity; - -namespace OpenStack.Test -{ - [TestClass] - public class OpenStackClientManagerTests - { - internal class TestCredential : ICredential - { - public Uri AuthenticationEndpoint { get; private set; } - public string AccessTokenId { get; private set; } - - public OpenStackServiceCatalog ServiceCatalog - { - get - { - var catalog = - new OpenStackServiceCatalog - { - new OpenStackServiceDefinition("Test", "Test", - new List() - { - new OpenStackServiceEndpoint("http://someplace.com", "somewhere", "2.0.0.0", - "http://www.someplace.com", "http://www.someplace.com") - }) - }; - return catalog; - } - } - } - - internal class TestOpenStackClient : IOpenStackClient - { - #region Test Client Impl - - public IOpenStackCredential Credential { get; private set; } - - public TestOpenStackClient(ICredential cred, CancellationToken token, IServiceLocator locator) - { - - } - - public Task Connect() - { - throw new NotImplementedException(); - } - - public void SetRegion(string region) - { - throw new NotImplementedException(); - } - - public T CreateServiceClient() where T : IOpenStackServiceClient - { - throw new NotImplementedException(); - } - - public T CreateServiceClient(string version) where T : IOpenStackServiceClient - { - throw new NotImplementedException(); - } - - public T CreateServiceClientByName(string serviceName) where T : IOpenStackServiceClient - { - throw new NotImplementedException(); - } - - public T CreateServiceClientByName(string serviceName, string version) where T : IOpenStackServiceClient - { - throw new NotImplementedException(); - } - - public IEnumerable GetSupportedVersions() - { - throw new NotImplementedException(); - } - - public bool IsSupported(ICredential credential, string version) - { - return credential is TestCredential; - } - - #endregion - } - - internal class OtherTestOpenStackClient : IOpenStackClient - { - #region Test Client Impl - - public IOpenStackCredential Credential { get; private set; } - - public Task Connect() - { - throw new NotImplementedException(); - } - - public void SetRegion(string region) - { - throw new NotImplementedException(); - } - - public T CreateServiceClient() where T : IOpenStackServiceClient - { - throw new NotImplementedException(); - } - - public T CreateServiceClient(string version) where T : IOpenStackServiceClient - { - throw new NotImplementedException(); - } - - public T CreateServiceClientByName(string serviceName) where T : IOpenStackServiceClient - { - throw new NotImplementedException(); - } - - public T CreateServiceClientByName(string serviceName, string version) where T : IOpenStackServiceClient - { - throw new NotImplementedException(); - } - - public IEnumerable GetSupportedVersions() - { - throw new NotImplementedException(); - } - - public bool IsSupported(ICredential credential, string version) - { - return credential is OpenStackCredential; - } - - #endregion - } - - internal class NonDefaultTestOpenStackClient : IOpenStackClient - { - public NonDefaultTestOpenStackClient(string parameter) - { - //forces a non-default ctor - } - - #region Test Client Impl - - public IOpenStackCredential Credential { get; private set; } - - public Task Connect() - { - throw new NotImplementedException(); - } - - public void SetRegion(string region) - { - throw new NotImplementedException(); - } - - public T CreateServiceClient() where T : IOpenStackServiceClient - { - throw new NotImplementedException(); - } - - public T CreateServiceClient(string version) where T : IOpenStackServiceClient - { - throw new NotImplementedException(); - } - - public T CreateServiceClientByName(string serviceName) where T : IOpenStackServiceClient - { - throw new NotImplementedException(); - } - - public T CreateServiceClientByName(string serviceName, string version) where T : IOpenStackServiceClient - { - throw new NotImplementedException(); - } - - public IEnumerable GetSupportedVersions() - { - throw new NotImplementedException(); - } - - public bool IsSupported(ICredential credential, string version) - { - return credential is OpenStackCredential; - } - - #endregion - } - - [TestMethod] - public void CanRegisterANewClient() - { - var manager = new OpenStackClientManager(new ServiceLocator()); - manager.RegisterClient(); - - Assert.AreEqual(1, manager.clients.Count); - Assert.AreEqual(typeof(TestOpenStackClient), manager.clients.First()); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public void CannotRegisterTheSameClientTwice() - { - var manager = new OpenStackClientManager(new ServiceLocator()); - manager.RegisterClient(); - manager.RegisterClient(); - } - - [TestMethod] - public void CanRegisterMultipleClients() - { - //var manager = OpenStackClientManager.Instance as OpenStackClientManager; - var manager = new OpenStackClientManager(new ServiceLocator()); - manager.RegisterClient(); - manager.RegisterClient(); - - Assert.AreEqual(2, manager.clients.Count); - Assert.IsTrue(manager.clients.Contains(typeof(TestOpenStackClient))); - Assert.IsTrue(manager.clients.Contains(typeof(OtherTestOpenStackClient))); - } - - [TestMethod] - public void CanListAvailableClients() - { - var manager = new OpenStackClientManager(new ServiceLocator()); - manager.clients.Add(typeof(TestOpenStackClient)); - manager.clients.Add(typeof(OtherTestOpenStackClient)); - - var clients = manager.ListAvailableClients().ToList(); - - Assert.AreEqual(2, clients.Count()); - Assert.IsTrue(clients.Contains(typeof(TestOpenStackClient))); - Assert.IsTrue(clients.Contains(typeof(OtherTestOpenStackClient))); - } - - [TestMethod] - public void CanCreateAClient() - { - var manager = new OpenStackClientManager(new ServiceLocator()); - manager.clients.Add(typeof(TestOpenStackClient)); - - var client = manager.CreateClient(new TestCredential()); - - Assert.IsNotNull(client); - Assert.IsInstanceOfType(client, typeof(TestOpenStackClient)); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public void CannotCreateAClientIfCredentialIsNotSupported() - { - var manager = new OpenStackClientManager(new ServiceLocator()); - manager.clients.Add(typeof(OtherTestOpenStackClient)); - - manager.CreateClient(new TestCredential()); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public void CannotCreateAClientIfNoClientsAreRegistered() - { - var manager = new OpenStackClientManager(new ServiceLocator()); - manager.CreateClient(new TestCredential()); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotCreateAClientWithNullCredential() - { - var manager = new OpenStackClientManager(new ServiceLocator()); - manager.clients.Add(typeof(TestOpenStackClient)); - - manager.CreateClient((ICredential)null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotCreateAClientWithNullCredentialAndVersion() - { - var manager = new OpenStackClientManager(new ServiceLocator()); - manager.clients.Add(typeof(TestOpenStackClient)); - - manager.CreateClient(null, "1.0.0..0"); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotCreateAClientWithCredentialAndNullVersion() - { - var manager = new OpenStackClientManager(new ServiceLocator()); - manager.clients.Add(typeof(TestOpenStackClient)); - - manager.CreateClient(new TestCredential(), null); - } - - [TestMethod] - public void CanCreateAnInstanceOfAClient() - { - var manager = new OpenStackClientManager(new ServiceLocator()); - var creds = new OpenStackCredential(new Uri("http://someurl.com"), "user", "password", "12345"); - - var client = manager.CreateClientInstance(typeof(TestOpenStackClient), creds, CancellationToken.None); - Assert.IsNotNull(client); - Assert.IsInstanceOfType(client, typeof(TestOpenStackClient)); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CanCreateAnInstanceOfAClientWithNullType() - { - var manager = new OpenStackClientManager(new ServiceLocator()); - var creds = new OpenStackCredential(new Uri("http://someurl.com"), "user", "password", "12345"); - - manager.CreateClientInstance((Type)null, creds, CancellationToken.None); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public void CannotCreateAnInstanceOfANonOpenStackClient() - { - var manager = new OpenStackClientManager(new ServiceLocator()); - var creds = new OpenStackCredential(new Uri("http://someurl.com"), "user", "password", "12345"); - manager.CreateClientInstance(typeof(Object), creds, CancellationToken.None); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public void CannotCreateAnInstanceOfAOpenStackClientWithoutADefaultCtor() - { - var manager = new OpenStackClientManager(new ServiceLocator()); - var creds = new OpenStackCredential(new Uri("http://someurl.com"), "user", "password", "12345"); - - manager.CreateClientInstance(typeof(NonDefaultTestOpenStackClient), creds, CancellationToken.None); - } - } -} diff --git a/OpenStack/OpenStack.Test/OpenStackClientTests.cs b/OpenStack/OpenStack.Test/OpenStackClientTests.cs deleted file mode 100644 index a908aa0..0000000 --- a/OpenStack/OpenStack.Test/OpenStackClientTests.cs +++ /dev/null @@ -1,166 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Security; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Common.ServiceLocation; -using OpenStack.Identity; - -namespace OpenStack.Test -{ - [TestClass] - public class OpenStackClientTests - { - internal IServiceLocator ServiceLocator; - - internal class TestIdentityServiceClient : IIdentityServiceClient - { - internal IOpenStackCredential cred; - internal CancellationToken token; - - public TestIdentityServiceClient(IOpenStackCredential cred, CancellationToken token) - { - this.cred = cred; - this.token = token; - } - - public async Task Authenticate() - { - return await Task.Run(() => - { - this.cred.SetAccessTokenId("12345"); - return cred; - } ); - } - } - - internal class TestIdentityServiceClientDefinition : IOpenStackServiceClientDefinition - { - public string Name { get; private set; } - - public IOpenStackServiceClient Create(ICredential credential, string serviceName, CancellationToken cancellationToken, IServiceLocator serviceLocator) - { - return new TestIdentityServiceClient((IOpenStackCredential)credential, cancellationToken); - } - - public IEnumerable ListSupportedVersions() - { - return new List(); - } - - public bool IsSupported(ICredential credential, string serviceName) - { - return true; - } - } - - [TestInitialize] - public void TestSetup() - { - this.ServiceLocator = new ServiceLocator(); - - var manager = this.ServiceLocator.Locate(); - var serviceManager = new OpenStackServiceClientManager(this.ServiceLocator); - serviceManager.RegisterServiceClient(new TestIdentityServiceClientDefinition()); - manager.RegisterServiceInstance(typeof(IOpenStackServiceClientManager), serviceManager); - } - - [TestCleanup] - public void TestCleanup() - { - this.ServiceLocator = new ServiceLocator(); - } - - [TestMethod] - public async Task CanConnect() - { - var client = - new OpenStackClient( - new OpenStackCredential(new Uri("http://someplace.org"), "someuser", "password", - "sometenant"), CancellationToken.None, this.ServiceLocator); - await client.Connect(); - Assert.AreEqual("12345", client.Credential.AccessTokenId); - } - - [TestMethod] - public void CanSetRegion() - { - var expectedRegion = "newregion"; - var client = new OpenStackClient( - new OpenStackCredential(new Uri("http://someplace.org"), "someuser", "password", - "sometenant", "oldregion"), CancellationToken.None, this.ServiceLocator); - client.SetRegion(expectedRegion); - - Assert.AreEqual(expectedRegion, client.Credential.Region); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotSetRegionWithNull() - { - var client = new OpenStackClient( - new OpenStackCredential(new Uri("http://someplace.org"), "someuser", "password", - "sometenant", "oldregion"), CancellationToken.None, this.ServiceLocator); - client.SetRegion(null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public void CannotSetRegionWithEmptyString() - { - var client = new OpenStackClient( - new OpenStackCredential(new Uri("http://someplace.org"), "someuser", "password", - "sometenant", "oldregion"), CancellationToken.None, this.ServiceLocator); - client.SetRegion(string.Empty); - } - - [TestMethod] - public void CanSupportAnyVersion() - { - var client = new OpenStackClient(); - var versions = client.GetSupportedVersions(); - Assert.IsTrue(versions.Contains("Any")); - } - - [TestMethod] - public void CanSupportOpenStackCredential() - { - var cred = new OpenStackCredential(new Uri("http://someplace.org"), "someuser", "password", "sometenant"); - var client = new OpenStackClient(); - Assert.IsTrue(client.IsSupported(cred,string.Empty)); - } - - [TestMethod] - public void CannotSupportNullCredential() - { - var client = new OpenStackClient(); - Assert.IsFalse(client.IsSupported(null, string.Empty)); - } - - [TestMethod] - public void CanSupportNullVersion() - { - var cred = new OpenStackCredential(new Uri("http://someplace.org"), "someuser", "password", "sometenant"); - var client = new OpenStackClient(); - Assert.IsTrue(client.IsSupported(cred, null)); - } - } -} diff --git a/OpenStack/OpenStack.Test/OpenStackServiceClientManagerTests.cs b/OpenStack/OpenStack.Test/OpenStackServiceClientManagerTests.cs deleted file mode 100644 index 3ab6f50..0000000 --- a/OpenStack/OpenStack.Test/OpenStackServiceClientManagerTests.cs +++ /dev/null @@ -1,237 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Common.ServiceLocation; -using OpenStack.Identity; - -namespace OpenStack.Test -{ - [TestClass] - public class OpenStackServiceClientManagerTests - { - internal class TestOpenStackServiceClient : IOpenStackServiceClient - { - public TestOpenStackServiceClient(ICredential credential, CancellationToken token) - { - - } - } - - internal class TestOpenStackServiceClientDefinition : IOpenStackServiceClientDefinition - { - public string Name { get; private set; } - - public IOpenStackServiceClient Create(ICredential credential, string serviceName, CancellationToken token, IServiceLocator serviceLocator) - { - return new TestOpenStackServiceClient(credential, token); - } - - public IEnumerable ListSupportedVersions() - { - throw new NotImplementedException(); - } - - public bool IsSupported(ICredential credential, string serviceName) - { - return true; - } - } - - internal class OtherTestOpenStackServiceClient : IOpenStackServiceClient - { - public OtherTestOpenStackServiceClient(ICredential credential, CancellationToken token) - { - - } - - public IEnumerable ListSupportedVersions() - { - throw new NotImplementedException(); - } - - public bool IsSupported() - { - return false; - } - - public static IOpenStackServiceClient Create(ICredential credential, CancellationToken token) - { - return new OtherTestOpenStackServiceClient(credential, token); - } - } - - internal class OtherTestOpenStackServiceClientDefinition : IOpenStackServiceClientDefinition - { - public string Name { get; private set; } - - public IOpenStackServiceClient Create(ICredential credential, string serviceName, CancellationToken token, IServiceLocator serviceLocator) - { - return new OtherTestOpenStackServiceClient(credential, token); - } - - public IEnumerable ListSupportedVersions() - { - throw new NotImplementedException(); - } - - public bool IsSupported(ICredential credential, string serviceName) - { - return false; - } - } - - internal class NoValidCtroTestOpenStackServiceClient : IOpenStackServiceClient - { - public IEnumerable ListSupportedVersions() - { - throw new NotImplementedException(); - } - - public bool IsSupported() - { - return true; - } - } - - [TestMethod] - public void CanRegisterANewService() - { - var manager = new OpenStackServiceClientManager(new ServiceLocator()); - manager.RegisterServiceClient(new TestOpenStackServiceClientDefinition()); - - Assert.AreEqual(1, manager.serviceClientDefinitions.Count); - Assert.IsTrue(manager.serviceClientDefinitions.ContainsKey(typeof(TestOpenStackServiceClient))); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public void CannotRegisterTheSameServiceTwice() - { - var manager = new OpenStackServiceClientManager(new ServiceLocator()); - manager.RegisterServiceClient(new TestOpenStackServiceClientDefinition()); - manager.RegisterServiceClient(new TestOpenStackServiceClientDefinition()); - } - - [TestMethod] - public void CanRegisterMultipleServices() - { - var manager = new OpenStackServiceClientManager(new ServiceLocator()); - manager.RegisterServiceClient(new TestOpenStackServiceClientDefinition()); - manager.RegisterServiceClient(new OtherTestOpenStackServiceClientDefinition()); - - Assert.AreEqual(2, manager.serviceClientDefinitions.Count); - Assert.IsTrue(manager.serviceClientDefinitions.ContainsKey(typeof(TestOpenStackServiceClient))); - Assert.IsTrue(manager.serviceClientDefinitions.ContainsKey(typeof(OtherTestOpenStackServiceClient))); - } - - [TestMethod] - public void CanListAvailableClients() - { - var manager = new OpenStackServiceClientManager(new ServiceLocator()); - manager.serviceClientDefinitions.Add(typeof(TestOpenStackServiceClient), new TestOpenStackServiceClientDefinition()); - manager.serviceClientDefinitions.Add(typeof(OtherTestOpenStackServiceClient), new OtherTestOpenStackServiceClientDefinition()); - - var services = manager.ListAvailableServiceClients().ToList(); - - Assert.AreEqual(2, services.Count()); - Assert.IsTrue(services.Contains(typeof(TestOpenStackServiceClient))); - Assert.IsTrue(services.Contains(typeof(OtherTestOpenStackServiceClient))); - } - - [TestMethod] - public void CanCreateAClient() - { - var manager = new OpenStackServiceClientManager(new ServiceLocator()); - manager.serviceClientDefinitions.Add(typeof(TestOpenStackServiceClient), new TestOpenStackServiceClientDefinition()); - - var service = manager.CreateServiceClient(new OpenStackClientManagerTests.TestCredential(), CancellationToken.None); - - Assert.IsNotNull(service); - Assert.IsInstanceOfType(service, typeof(TestOpenStackServiceClient)); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public void CannotCreateAServiceIfVersionIsNotSupported() - { - var manager = new OpenStackServiceClientManager(new ServiceLocator()); - manager.serviceClientDefinitions.Add(typeof(OtherTestOpenStackServiceClient), new OtherTestOpenStackServiceClientDefinition()); - - manager.CreateServiceClient(new OpenStackClientManagerTests.TestCredential(), CancellationToken.None); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public void CannotCreateAClientIfNoServicesAreRegistered() - { - var manager = new OpenStackServiceClientManager(new ServiceLocator()); - manager.CreateServiceClient(new OpenStackClientManagerTests.TestCredential(), CancellationToken.None); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotCreateAServiceWithNullCredential() - { - var manager = new OpenStackServiceClientManager(new ServiceLocator()); - manager.serviceClientDefinitions.Add(typeof(TestOpenStackServiceClient), new TestOpenStackServiceClientDefinition()); - - manager.CreateServiceClient((ICredential)null, CancellationToken.None); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotCreateAServiceWithNullCredentialAndVersion() - { - var manager = new OpenStackServiceClientManager(new ServiceLocator()); - manager.serviceClientDefinitions.Add(typeof(TestOpenStackServiceClient), new TestOpenStackServiceClientDefinition()); - - manager.CreateServiceClient((ICredential)null, CancellationToken.None); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public void CannotCreateAServiceWithCredentialAndNullFactory() - { - var manager = new OpenStackServiceClientManager(new ServiceLocator()); - manager.serviceClientDefinitions.Add(typeof(TestOpenStackServiceClient), null); - - manager.CreateServiceClient(new OpenStackClientManagerTests.TestCredential(), CancellationToken.None); - } - - [TestMethod] - public void CanCreateAnInstanceOfAService() - { - var manager = new OpenStackServiceClientManager(new ServiceLocator()); - - var service = manager.CreateServiceClientInstance(new TestOpenStackServiceClientDefinition(), new OpenStackClientManagerTests.TestCredential(), string.Empty, CancellationToken.None); - Assert.IsNotNull(service); - Assert.IsInstanceOfType(service, typeof(TestOpenStackServiceClient)); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CanCreateAnInstanceOfAServiceWithNullFactory() - { - var manager = new OpenStackServiceClientManager(new ServiceLocator()); - manager.CreateServiceClientInstance(null, new OpenStackClientManagerTests.TestCredential(), string.Empty, CancellationToken.None); - } - } -} diff --git a/OpenStack/OpenStack.Test/Properties/AssemblyInfo.cs b/OpenStack/OpenStack.Test/Properties/AssemblyInfo.cs deleted file mode 100644 index f819a00..0000000 --- a/OpenStack/OpenStack.Test/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,39 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Reflection; -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("OpenStack.Test")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("OpenStack.org")] -[assembly: AssemblyProduct("OpenStack.Test")] -[assembly: AssemblyCopyright("")] -[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("47bc2198-4d59-47a0-9b5f-a3985ff6ab5a")] - diff --git a/OpenStack/OpenStack.Test/RestSimulator.cs b/OpenStack/OpenStack.Test/RestSimulator.cs deleted file mode 100644 index 134a7b5..0000000 --- a/OpenStack/OpenStack.Test/RestSimulator.cs +++ /dev/null @@ -1,102 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Net; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; -using OpenStack.Common.Http; - -namespace OpenStack.Test -{ - public abstract class RestSimulator : DisposableClass, IHttpAbstractionClient - { - protected RestSimulator() - { - this.Headers = new Dictionary(); - this.Delay = TimeSpan.FromMilliseconds(0); - } - - protected RestSimulator(CancellationToken token) : this() - { - } - - public HttpMethod Method { get; set; } - - public Uri Uri { get; set; } - - public Stream Content { get; set; } - - public IDictionary Headers { get; private set; } - - public string ContentType { get; set; } - - public TimeSpan Timeout { get; set; } - - public TimeSpan Delay { get; set; } - - public Task SendAsync() - { - if (!this.Headers.ContainsKey("X-Auth-Token") || this.Headers["X-Auth-Token"] != "12345") - { - return Task.Factory.StartNew(() => TestHelper.CreateResponse(HttpStatusCode.Unauthorized)); - } - IHttpResponseAbstraction retVal; - switch (this.Method.ToString().ToLowerInvariant()) - { - case "get": - retVal = HandleGet(); - break; - case "post": - retVal = HandlePost(); - break; - case "put": - retVal = HandlePut(); - break; - case "delete": - retVal = HandleDelete(); - break; - case "head": - retVal = HandleHead(); - break; - case "copy": - retVal = HandleCopy(); - break; - default: - retVal = TestHelper.CreateErrorResponse(); - break; - } - - Thread.Sleep(Delay); - return Task.Factory.StartNew(() => retVal); - } - - protected abstract IHttpResponseAbstraction HandleGet(); - - protected abstract IHttpResponseAbstraction HandlePost(); - - protected abstract IHttpResponseAbstraction HandlePut(); - - protected abstract IHttpResponseAbstraction HandleDelete(); - - protected abstract IHttpResponseAbstraction HandleHead(); - - protected abstract IHttpResponseAbstraction HandleCopy(); - } -} diff --git a/OpenStack/OpenStack.Test/ServiceLocation/ServiceLocationAssemblyScannerTests.cs b/OpenStack/OpenStack.Test/ServiceLocation/ServiceLocationAssemblyScannerTests.cs deleted file mode 100644 index e16a74d..0000000 --- a/OpenStack/OpenStack.Test/ServiceLocation/ServiceLocationAssemblyScannerTests.cs +++ /dev/null @@ -1,222 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Web.Management; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Test.ServiceLocation -{ - [TestClass] - public class ServiceLocationAssemblyScannerTests - { - internal class TestRegistrar : IServiceLocationRegistrar - { - public void Register(IServiceLocationManager manager, IServiceLocator locator) - { - - } - } - - internal class OtherTestRegistrar : IServiceLocationRegistrar - { - public void Register(IServiceLocationManager manager, IServiceLocator locator) - { - - } - } - - internal class NonDefaultTestRegistrar : IServiceLocationRegistrar - { - public NonDefaultTestRegistrar(string beans) - { - //this is here to force a non-default constructor, this should not be loaded as a registrar. - } - - public void Register(IServiceLocationManager manager, IServiceLocator locator) - { - throw new NotImplementedException(); - } - } - - [TestMethod] - public void CanAddNewAssembly() - { - var sweeper = new ServiceLocationAssemblyScanner(); - var assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList(); - var temp = assemblies.First(); - - Assert.IsFalse(sweeper.HasNewAssemblies); - - sweeper.AddAssembly(temp); - - Assert.IsTrue(sweeper.HasNewAssemblies); - Assert.AreEqual(1,sweeper._assemblies.Count); - } - - [TestMethod] - public void CanAddExistingAssembly() - { - var sweeper = new ServiceLocationAssemblyScanner(); - var assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList(); - var temp = assemblies.First(); - - Assert.IsFalse(sweeper.HasNewAssemblies); - sweeper.AddAssembly(temp); - Assert.IsTrue(sweeper.HasNewAssemblies); - - sweeper.AddAssembly(temp); - - Assert.IsTrue(sweeper.HasNewAssemblies); - Assert.AreEqual(1, sweeper._assemblies.Count); - } - - [TestMethod] - public void CanGetRegistrarTypes() - { - var sweeper = new ServiceLocationAssemblyScanner(); - Assert.IsFalse(sweeper.HasNewAssemblies); - - sweeper.AddAssembly(this.GetType().Assembly); - Assert.IsTrue(sweeper.HasNewAssemblies); - - var types = sweeper.GetRegistrarTypes().ToList(); - Assert.IsTrue(sweeper.HasNewAssemblies); - Assert.AreEqual(2, types.Count()); - Assert.IsTrue(types.Contains(typeof(TestRegistrar))); - Assert.IsTrue(types.Contains(typeof(OtherTestRegistrar))); - } - - [TestMethod] - public void CanGetRegistrarTypesWithAssemblyThatHasNoRegistrars() - { - var sweeper = new ServiceLocationAssemblyScanner(); - Assert.IsFalse(sweeper.HasNewAssemblies); - var assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList(); - var temp = assemblies.First(); - - sweeper.AddAssembly(temp); - Assert.IsTrue(sweeper.HasNewAssemblies); - - var types = sweeper.GetRegistrarTypes().ToList(); - Assert.IsTrue(sweeper.HasNewAssemblies); - - Assert.AreEqual(0, types.Count()); - } - - [TestMethod] - public void CanGetRegistrarTypesWithEmptyAssembliesCollection() - { - var sweeper = new ServiceLocationAssemblyScanner(); - Assert.IsFalse(sweeper.HasNewAssemblies); - - var types = sweeper.GetRegistrarTypes().ToList(); - Assert.IsFalse(sweeper.HasNewAssemblies); - - Assert.AreEqual(0, types.Count()); - } - - [TestMethod] - public void NoNewRegistrarsIfNoNewAssemblies() - { - bool getRegistrarsCalled = false; - var sweeper = new ServiceLocationAssemblyScanner(); - sweeper.GetRegistrarTypes = () => { getRegistrarsCalled = false; - return new List(); - }; - - var regs = sweeper.GetRegistrars(); - Assert.IsFalse(getRegistrarsCalled); - Assert.AreEqual(0, regs.Count()); - } - - [TestMethod] - public void NewRegistrarsIfNewAssembliesPresent() - { - bool getRegistrarsCalled = false; - var sweeper = new ServiceLocationAssemblyScanner(); - sweeper.HasNewAssemblies = true; - sweeper.GetRegistrarTypes = () => - { - getRegistrarsCalled = true; - return new List() { typeof(TestRegistrar)}; - }; - - var regs = sweeper.GetRegistrars().ToList(); - Assert.IsTrue(getRegistrarsCalled); - Assert.AreEqual(1, regs.Count()); - Assert.IsTrue(regs.First() is TestRegistrar); - } - - [TestMethod] - public void ExistingRegistrarIsOverwritenWhenNewAssemblyFoundThatContainsIt() - { - bool getRegistrarsCalled = false; - var sweeper = new ServiceLocationAssemblyScanner(); - sweeper._registrars.Add(typeof(TestRegistrar)); - sweeper.HasNewAssemblies = true; - sweeper.GetRegistrarTypes = () => - { - getRegistrarsCalled = true; - return new List() { typeof(TestRegistrar) }; - }; - - var regs = sweeper.GetRegistrars().ToList(); - Assert.IsTrue(getRegistrarsCalled); - Assert.AreEqual(1, regs.Count()); - Assert.IsTrue(regs.First() is TestRegistrar); - Assert.AreEqual(1, sweeper._registrars.Count); - Assert.AreEqual(typeof(TestRegistrar), sweeper._registrars.First()); - } - - [TestMethod] - public void CanGetOnlyRegistrars() - { - var sweeper = new ServiceLocationAssemblyScanner(); - var assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList(); - assemblies.Remove(this.GetType().Assembly); - assemblies.ForEach(sweeper.AddAssembly); - Assert.IsTrue(sweeper.HasNewAssemblies); - - var registrars = sweeper.GetRegistrars(); - Assert.IsFalse(sweeper.HasNewAssemblies); - Assert.AreEqual(1, registrars.Count()); - } - - [TestMethod] - public void CanGetNewRegistrars() - { - var sweeper = new ServiceLocationAssemblyScanner(); - var assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList(); - Assert.IsFalse(sweeper.HasNewAssemblies); - - var registrars = sweeper.GetRegistrars(); - Assert.IsFalse(sweeper.HasNewAssemblies); - Assert.AreEqual(0, registrars.Count()); - - sweeper.AddAssembly( this.GetType().Assembly ); - Assert.IsTrue(sweeper.HasNewAssemblies); - - registrars = sweeper.GetRegistrars(); - Assert.IsFalse(sweeper.HasNewAssemblies); - Assert.AreEqual(2, registrars.Count()); - } - } -} diff --git a/OpenStack/OpenStack.Test/ServiceLocation/ServiceLocatorTests.cs b/OpenStack/OpenStack.Test/ServiceLocation/ServiceLocatorTests.cs deleted file mode 100644 index 42c100a..0000000 --- a/OpenStack/OpenStack.Test/ServiceLocation/ServiceLocatorTests.cs +++ /dev/null @@ -1,236 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Linq; -using System.Reflection; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Test.ServiceLocation -{ - - [TestClass] - public class ServiceLocatorTests - { - public interface ITestEchoService - { - string Echo(string msg); - } - - public class TestEchoService : ITestEchoService - { - public string Echo(string msg) - { - return msg; - } - } - - public class TestReverseEchoService : ITestEchoService - { - public string Echo(string msg) - { - return new string(msg.Reverse().ToArray()); - } - } - - internal class TestServiceLocator : IServiceLocator - { - public T Locate() - { - throw new NotImplementedException(); - } - - public void EnsureAssemblyRegistration(Assembly target) - { - throw new NotImplementedException(); - } - } - - internal class TestServiceManager : IServiceLocationRuntimeManager - { - public void RegisterServiceInstance(TService instance) - { - throw new NotImplementedException(); - } - - public void RegisterServiceInstance(Type type, object instance) - { - throw new NotImplementedException(); - } - - public void RegisterServiceType(Type type) - { - throw new NotImplementedException(); - } - - public void RegisterServiceType() where TConcretion : class, TInterface - { - throw new NotImplementedException(); - } - - public void RegisterServiceType(Type type, Type registrationValue) - { - throw new NotImplementedException(); - } - } - - internal class TestServiceOverrideManager : IServiceLocationOverrideManager - { - public void RegisterServiceInstance(TService instance) - { - throw new NotImplementedException(); - } - - public void RegisterServiceInstance(Type type, object instance) - { - throw new NotImplementedException(); - } - - public void RegisterServiceType(Type type) - { - throw new NotImplementedException(); - } - - public void RegisterServiceType() where TConcretion : class, TInterface - { - throw new NotImplementedException(); - } - - public void RegisterServiceType(Type type, Type registrationValue) - { - throw new NotImplementedException(); - } - } - - [TestInitialize] - public void Initialize() - { - } - - [TestCleanup] - public void TestCleanup() - { - } - - [TestMethod] - public void CanRegisterAndLocateAService() - { - var locator = new ServiceLocator(); - var myServiceInstance = new TestEchoService(); - var manager = locator.Locate(); - - Assert.IsNotNull(manager); - manager.RegisterServiceInstance(myServiceInstance); - - var service = locator.Locate(); - - Assert.IsNotNull(service); - Assert.AreEqual("Works", service.Echo("Works")); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public void CannotLocateAServiceThatHasNotBeenRegistered() - { - var locator = new ServiceLocator(); - locator.Locate(); - } - - [TestMethod] - public void CanOverrideAndLocateAService() - { - var locator = new ServiceLocator(); - var echoServiceInstance = new TestEchoService(); - var reverseEchoServiceInstance = new TestReverseEchoService(); - var runtimeManager = locator.Locate(); - var overrrideManager = locator.Locate(); - - Assert.IsNotNull(runtimeManager); - Assert.IsNotNull(overrrideManager); - - runtimeManager.RegisterServiceInstance(echoServiceInstance); - overrrideManager.RegisterServiceInstance(reverseEchoServiceInstance); - - - var service = locator.Locate(); - - Assert.IsNotNull(service); - Assert.IsInstanceOfType(service, typeof(TestReverseEchoService)); - Assert.AreEqual("skroW", service.Echo("Works")); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public void CannotRegisterNullService() - { - var locator = new ServiceLocator(); - var runtimeManager = locator.Locate(); - - runtimeManager.RegisterServiceInstance(null); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public void CannotRegisterNullType() - { - var locator = new ServiceLocator(); - var runtimeManager = locator.Locate(); - - runtimeManager.RegisterServiceInstance(null,new TestEchoService()); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public void CannotRegisterNonInterface() - { - var locator = new ServiceLocator(); - var runtimeManager = locator.Locate(); - - runtimeManager.RegisterServiceInstance("Hello!"); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public void CannotRegisterAServiceLocator() - { - var locator = new ServiceLocator(); - var runtimeManager = locator.Locate(); - - runtimeManager.RegisterServiceInstance(new TestServiceLocator()); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public void CannotRegisterAServiceManager() - { - var locator = new ServiceLocator(); - var runtimeManager = locator.Locate(); - - runtimeManager.RegisterServiceInstance(new TestServiceManager()); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public void CannotRegisterAnOverrideManager() - { - var locator = new ServiceLocator(); - var runtimeManager = locator.Locate(); - - runtimeManager.RegisterServiceInstance(new TestServiceOverrideManager()); - } - } -} diff --git a/OpenStack/OpenStack.Test/Storage/LargeStorageObjectProviderTests.cs b/OpenStack/OpenStack.Test/Storage/LargeStorageObjectProviderTests.cs deleted file mode 100644 index 560e2bd..0000000 --- a/OpenStack/OpenStack.Test/Storage/LargeStorageObjectProviderTests.cs +++ /dev/null @@ -1,1224 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Text; -using System.Threading.Tasks; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Common; -using OpenStack.Storage; - -namespace OpenStack.Test.Storage -{ - [TestClass] - public class LargeStorageObjectProviderTests - { - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public void GetChunkSizeWithZeroSize() - { - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - provider.GetChunkSize(0, 10); - } - - [TestMethod] - public void GetChunkSizeWithZeroSegments() - { - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - var size = provider.GetChunkSize(100, 0); - - //If no segments are requested, then the whole length should be returned. - Assert.AreEqual(100, size); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public void GetChunkSizeWithNegativeLength() - { - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - provider.GetChunkSize(-1, 0); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public void GetChunkSizeWithNegativeSegments() - { - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - provider.GetChunkSize(100, -1); - } - - [TestMethod] - public void GetChunkSizeWithMoreSegmentsThenLength() - { - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - var size = provider.GetChunkSize(10, 100); - - //If the chunk size is calculated to less then zero, it should be rounded up to 1 - Assert.AreEqual(1, size); - } - - [TestMethod] - public void GetChunkSizeWithOneSegment() - { - var fileLength = 100; - var segments = 1; - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - var size = provider.GetChunkSize(fileLength, segments); - - //If there is just one segment, then the size should be the whole length - Assert.AreEqual(fileLength, size); - } - - [TestMethod] - public void GetChunkSizeWithEvenSegmentSplit() - { - var fileLength = 100; - var segments = 10; - var expectedSize = 10; - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - var size = provider.GetChunkSize(fileLength, segments); - - //If there is just one segment, then the size should be the whole length - Assert.AreEqual(expectedSize, size); - } - - [TestMethod] - public void GetChunkSizeWithUnevenSplitLessThenHalf() - { - var fileLength = 103; - var segments = 10; - var expectedSize = 11; - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - var size = provider.GetChunkSize(fileLength, segments); - - //Chunk size should be rounded up, in this case 103 / 10 = 10.3 -> 11 - Assert.AreEqual(expectedSize, size); - } - - [TestMethod] - public void GetChunkSizeWithUnevenSplitMoreThenHalf() - { - var fileLength = 107; - var segments = 10; - var expectedSize = 11; - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - var size = provider.GetChunkSize(fileLength, segments); - - //Chunk size should be rounded up, in this case 107 / 10 = 10.7 -> 11 - Assert.AreEqual(expectedSize, size); - } - - [TestMethod] - public void GetSegmentIdFromKeyWithValidFormat() - { - var segment = 1234567890; - var sObject = new StorageObject(segment.ToString("D10"),"TestContainer",new Dictionary()); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - var segmentId = provider.GetSegmentIdFromKey(sObject); - - Assert.IsNotNull(segmentId); - Assert.AreEqual(segmentId, segmentId); - } - - [TestMethod] - [ExpectedException(typeof(System.FormatException))] - public void GetSegmentIdFromKeyWithTrailingPeriod() - { - var segment = 1234567890; - var sObject = new StorageObject(segment.ToString("D10") +".", "TestContainer", new Dictionary()); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - provider.GetSegmentIdFromKey(sObject); - } - - [TestMethod] - [ExpectedException(typeof(System.FormatException))] - public void GetSegmentIdFromKeyWithNonNumberText() - { - var segment = 1234567890; - var sObject = new StorageObject("File.txt." + segment.ToString("D7") + "BAD", "TestContainer", new Dictionary()); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - provider.GetSegmentIdFromKey(sObject); - } - - [TestMethod] - [ExpectedException(typeof(System.FormatException))] - public void GetSegmentIdFromKeyWithWayTooBigNumber() - { - var segment = 123456789012345; - var sObject = new StorageObject(segment.ToString("D15"), "TestContainer", new Dictionary()); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - provider.GetSegmentIdFromKey(sObject); - } - - [TestMethod] - [ExpectedException(typeof(System.FormatException))] - public void GetSegmentIdFromKeyMaxInt32PlusOne() - { - long segment = Int32.MaxValue; - segment++; - - var sObject = new StorageObject(segment.ToString("D10"), "TestContainer", new Dictionary()); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - provider.GetSegmentIdFromKey(sObject); - } - - [TestMethod] - [ExpectedException(typeof(System.FormatException))] - public void GetSegmentIdFromKeyWithNegativeSegmentNumber() - { - long segment = -12345; - - var sObject = new StorageObject(segment.ToString("D10"), "TestContainer", new Dictionary()); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - provider.GetSegmentIdFromKey(sObject); - } - - [TestMethod] - public void GetLastSegmentIdAndObjectWithNoObjects() - { - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - var segmentFolder = new StorageFolder("myFile", new List(), new List()); - - var segment = provider.GetLastSegmentIdAndName(segmentFolder); - - Assert.IsNotNull(segment); - Assert.AreEqual(0, segment.Key); - Assert.AreEqual(string.Empty, segment.Value); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void GetLastSegmentIdAndObjectWithNullFolder() - { - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - provider.GetLastSegmentIdAndName(null); - } - - [TestMethod] - public void GetLastSegmentIdAndObjectWithOneObjectWithIdZero() - { - var sObject = new StorageObject("0000000000", "TestContainer", new Dictionary()); - var segmentFolder = new StorageFolder("myFile", new List(), new List() { sObject }); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - var segment = provider.GetLastSegmentIdAndName(segmentFolder); - - Assert.IsNotNull(segment); - Assert.AreEqual(0, segment.Key); - Assert.IsNotNull(segment.Value); - Assert.AreEqual(sObject.Name, segment.Value); - } - - [TestMethod] - public void GetLastSegmentIdAndObjectWithOneObjectWithNonZeroId() - { - var segmentId = 1234567890; - var sObject = new StorageObject(segmentId.ToString("D10"), "TestContainer", new Dictionary()); - var segmentFolder = new StorageFolder("myFile", new List(), new List() { sObject }); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - var segment = provider.GetLastSegmentIdAndName(segmentFolder); - - Assert.IsNotNull(segment); - Assert.AreEqual(segmentId, segment.Key); - Assert.IsNotNull(segment.Value); - Assert.AreEqual(sObject.Name, segment.Value); - } - - [TestMethod] - public void GetLastSegmentIdAndObjectWithMultipleObjects() - { - var segmentOne = 0; - var segmentTwo = 1; - var sObjectOne = new StorageObject(segmentOne.ToString("D10"), "TestContainer", new Dictionary()); - var sObjectTwo = new StorageObject(segmentTwo.ToString("D10"), "TestContainer", new Dictionary()); - var segmentFolder = new StorageFolder("myFile", new List(), new List() { sObjectOne, sObjectTwo }); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - var segment = provider.GetLastSegmentIdAndName(segmentFolder); - - Assert.IsNotNull(segment); - Assert.AreEqual(segmentTwo, segment.Key); - Assert.IsNotNull(segment.Value); - Assert.AreEqual(sObjectTwo.Name, segment.Value); - } - - [TestMethod] - public void GetLastSegmentIdAndObjectWithMultipleObjectsOutOfOrder() - { - var segmentOne = 0; - var segmentTwo = 1; - var sObjectOne = new StorageObject(segmentOne.ToString("D10"), "TestContainer", new Dictionary()); - var sObjectTwo = new StorageObject(segmentTwo.ToString("D10"), "TestContainer", new Dictionary()); - var segmentFolder = new StorageFolder("myFile", new List(), new List() { sObjectTwo, sObjectOne }); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - var segment = provider.GetLastSegmentIdAndName(segmentFolder); - - Assert.IsNotNull(segment); - Assert.AreEqual(segmentTwo, segment.Key); - Assert.IsNotNull(segment.Value); - Assert.AreEqual(sObjectTwo.Name, segment.Value); - } - - [TestMethod] - public void GetLastSegmentIdAndObjectWithMultipleObjectsOutOfOrderAndAcrossAlphaSortBoundry() - { - var segmentOne = 1; - var segmentTen = 10; - var segmentTwo = 2; - var sObjectOne = new StorageObject(segmentOne.ToString("D10"), "TestContainer", new Dictionary()); - var sObjectTwo = new StorageObject(segmentTwo.ToString("D10"), "TestContainer", new Dictionary()); - var sObjectTen = new StorageObject(segmentTen.ToString("D10"), "TestContainer", new Dictionary()); - var segmentFolder = new StorageFolder("myFile", new List(), new List() { sObjectTwo, sObjectTen, sObjectOne }); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - var segment = provider.GetLastSegmentIdAndName(segmentFolder); - - Assert.IsNotNull(segment); - Assert.AreEqual(segmentTen, segment.Key); - Assert.IsNotNull(segment.Value); - Assert.AreEqual(sObjectTen.Name, segment.Value); - } - - [TestMethod] - public void GetLastSegmentIdAndObjectWithOneObjectWithBadSegmentId() - { - var sObjectTen = new StorageObject("THIS IS NOT A NUMBER", "TestContainer", new Dictionary()); - var segmentFolder = new StorageFolder("myFile", new List(), new List() {sObjectTen}); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - var segment = provider.GetLastSegmentIdAndName(segmentFolder); - - Assert.IsNotNull(segment); - Assert.AreEqual(0, segment.Key); - Assert.AreEqual(string.Empty, segment.Value); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public void GetFileChunkWithNegativeChunkSize() - { - long chunkSize = -10; - var stream = new MemoryStream(); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - provider.GetObjectChunk(stream, chunkSize); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void GetFileChunkWithNullStream() - { - long chunkSize = 100; - Stream stream = null; - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - provider.GetObjectChunk(stream, chunkSize); - } - - [TestMethod] - public void GetFileChunkWithEmptyStream() - { - long chunkSize = 100; - Stream stream = new MemoryStream(); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - var chunk = provider.GetObjectChunk(stream, chunkSize); - - Assert.IsNotNull(chunk); - Assert.AreEqual(chunkSize, chunk.Length); - var memChunk = chunk as MemoryStream; - Assert.IsTrue(memChunk.ToArray().All(b => b == default(Byte))); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public void GetFileChunkWithClosedStream() - { - long chunkSize = 100; - var str = "some random data"; - byte[] bytes = new byte[str.Length * sizeof(char)]; - System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); - Stream stream = new MemoryStream(bytes); - stream.Close(); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - provider.GetObjectChunk(stream, chunkSize); - } - - [TestMethod] - public void GetFileChunkWithValidStreamAndChunkSize() - { - long chunkSize = 10; - var str = "some random data"; - byte[] bytes = new byte[str.Length * sizeof(char)]; - System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); - Stream stream = new MemoryStream(bytes); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - var chunk = provider.GetObjectChunk(stream, chunkSize); - - Assert.IsNotNull(chunk); - Assert.AreEqual(chunkSize, chunk.Length); - Assert.AreEqual(chunkSize, stream.Position); - Assert.IsTrue(stream.CanRead); - } - - [TestMethod] - public void GetFileChunkWithValidStreamStopsOnEOF() - { - long chunkSize = 1000; - var str = "some random data"; - byte[] bytes = new byte[str.Length * sizeof(char)]; - System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); - Stream stream = new MemoryStream(bytes); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - var chunk = provider.GetObjectChunk(stream, chunkSize); - - Assert.IsNotNull(chunk); - Assert.AreEqual(chunkSize, chunk.Length); - Assert.AreEqual(stream.Length, stream.Position); - Assert.IsTrue(stream.CanRead); - } - - [TestMethod] - public void BuildSegmentIdWithValidSegmentNumber() - { - var key = "a/b/"; - var segment = 12345; - var expectedKey = "a/b/0000012345"; - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - var segmentKey = provider.BuildSegmentKey(key, segment); - - Assert.AreEqual(expectedKey, segmentKey); - } - - [TestMethod] - public void BuildSegmentIdWithValidSegmentNumberAndLeadingSlashInFolderName() - { - var key = "/a/b/"; - var segment = 12345; - var expectedKey = "a/b/0000012345"; - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - var segmentKey = provider.BuildSegmentKey(key, segment); - - Assert.AreEqual(expectedKey, segmentKey); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public void BuildSegmentIdWithValidNegativeSegmentNumber() - { - var key = "key"; - var segment = -12345; - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - provider.BuildSegmentKey(key, segment); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void BuildSegmentIdWithNullKey() - { - string key = null; - var segment = 12345; - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - provider.BuildSegmentKey(key, segment); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public void BuildSegmentIdWithEmptyKey() - { - string key = string.Empty; - var segment = 12345; - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - provider.BuildSegmentKey(key, segment); - } - - [TestMethod] - [ExpectedException(typeof (ArgumentNullException))] - public void BuildStorageManifestWithNullSegmentCollection() - { - var segmentContainer = "segments"; - var containerName = "TestContainer"; - var manifestname = "TestManifest"; - var metadata = new Dictionary(); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - provider.BuildStorageManifest(containerName, manifestname, metadata, null, segmentContainer); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public void BuildStorageManifestWithEmptySegmentCollection() - { - var segmentContainer = "segments"; - var containerName = "TestContainer"; - var manifestname = "TestManifest"; - var metadata = new Dictionary(); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - provider.BuildStorageManifest(containerName, manifestname, metadata, new List(), segmentContainer); - } - - [TestMethod] - public void HasMinSizeSegmentsWithEmptySegmentCollection() - { - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - Assert.IsFalse(provider.HasMinSizeSegments(new List(), 1048576)); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void HasMinSizeSegmentsWithNullSegmentCollection() - { - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - Assert.IsFalse(provider.HasMinSizeSegments(null, 1048576)); - } - - [TestMethod] - public void BuildStorageManifestWithSingleSegmentOfValidSize() - { - var segmentContainer = "segments"; - var containerName = "TestContainer"; - var manifestname = "TestManifest"; - var metadata = new Dictionary(); - var sObject = new StorageObject("TestObject", containerName, DateTime.UtcNow, "12345", 2048576, "text"); - var segments = new List() { sObject }; - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - var manifest = provider.BuildStorageManifest(containerName, manifestname, metadata, segments, segmentContainer); - - Assert.IsInstanceOfType(manifest, typeof(StaticLargeObjectManifest)); - } - - [TestMethod] - public void BuildStorageManifestWithSingleSegmentOfLessThenMinSize() - { - var segmentContainer = "segments"; - var containerName = "TestContainer"; - var manifestname = "TestManifest"; - var metadata = new Dictionary(); - var sObject = new StorageObject("TestObject", containerName, DateTime.UtcNow, "12345", 48576, "text"); - var segments = new List() { sObject }; - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - var manifest = provider.BuildStorageManifest(containerName, manifestname, metadata, segments, segmentContainer); - - Assert.IsInstanceOfType(manifest, typeof(DynamicLargeObjectManifest)); - Assert.AreEqual(string.Format("{0}/{1}/", segmentContainer, manifestname), ((DynamicLargeObjectManifest)manifest).SegmentsPath); - } - - [TestMethod] - public void BuildStorageManifestWithMultipleSegmentOfValidSize() - { - var segmentContainer = "segments"; - var containerName = "TestContainer"; - var manifestname = "TestManifest"; - var metadata = new Dictionary(); - var sObject = new StorageObject("TestObject", containerName, DateTime.UtcNow, "12345", 2048576, "text"); - var sObject2 = new StorageObject("TestObject", containerName, DateTime.UtcNow, "12345", 2048576, "text"); - var segments = new List() { sObject, sObject2 }; - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - var manifest = provider.BuildStorageManifest(containerName, manifestname, metadata, segments, segmentContainer); - - Assert.IsInstanceOfType(manifest, typeof(StaticLargeObjectManifest)); - } - - [TestMethod] - public void BuildStorageManifestWithMultipleSegmentAndOneLessthenMinSize() - { - var segmentContainer = "segments"; - var containerName = "TestContainer"; - var manifestname = "TestManifest"; - var metadata = new Dictionary(); - var sObject = new StorageObject("TestObject", containerName, DateTime.UtcNow, "12345", 2048576, "text"); - var sObject2 = new StorageObject("TestObject", containerName, DateTime.UtcNow, "12345", 576, "text"); - var sObject3 = new StorageObject("TestObject", containerName, DateTime.UtcNow, "12345", 2048576, "text"); - var segments = new List() { sObject, sObject2, sObject3 }; - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - var manifest = provider.BuildStorageManifest(containerName, manifestname, metadata, segments, segmentContainer); - - Assert.IsInstanceOfType(manifest, typeof(DynamicLargeObjectManifest)); - } - - [TestMethod] - public void BuildStorageManifestWithMultipleSegmentOfValidSizeAndLastSegmentUnderMin() - { - var segmentContainer = "segments"; - var containerName = "TestContainer"; - var manifestname = "TestManifest"; - var metadata = new Dictionary(); - var sObject = new StorageObject("TestObject", containerName, DateTime.UtcNow, "12345", 2048576, "text"); - var sObject2 = new StorageObject("TestObject", containerName, DateTime.UtcNow, "12345", 48576, "text"); - var segments = new List() { sObject, sObject2 }; - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - var manifest = provider.BuildStorageManifest(containerName, manifestname, metadata, segments, segmentContainer); - - Assert.IsInstanceOfType(manifest, typeof(StaticLargeObjectManifest)); - } - - [TestMethod] - public void BuildStorageManifestWithOverTheMaxNumberOfSegmentsForStatic() - { - var segmentContainer = "segments"; - var containerName = "TestContainer"; - var manifestname = "TestManifest"; - var metadata = new Dictionary(); - var segments = new List(); - for (var i = 0; i < 1050; i++) - { - segments.Add( new StorageObject("TestObject", containerName, DateTime.UtcNow, "12345", 2048576, "text")); - } - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - var manifest = provider.BuildStorageManifest(containerName, manifestname, metadata, segments, segmentContainer); - - Assert.IsInstanceOfType(manifest, typeof(DynamicLargeObjectManifest)); - } - - [TestMethod] - public void BuildStorageManifestWithOverTheMaxSizeForStatic() - { - var segmentContainer = "segments"; - var containerName = "TestContainer"; - var manifestname = "TestManifest"; - var metadata = new Dictionary(); - var segments = new List(); - for (var i = 0; i < 999; i++) - { - segments.Add(new StorageObject("TestObject", containerName, DateTime.UtcNow, "12345", 82048576, "text")); - } - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - - var manifest = provider.BuildStorageManifest(containerName, manifestname, metadata, segments, segmentContainer); - - Assert.IsInstanceOfType(manifest, typeof(DynamicLargeObjectManifest)); - } - - [TestMethod] - public async Task CanCreateStorageManifestWithStaticManifest() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - var client = new TestStorageServiceClient(); - var staticManifestCreateWasCalled = false; - - var manifest = new StaticLargeObjectManifest(containerName, objectName, new Dictionary(), new List()); - - client.CreateStaticStorageManifestDelegate = async (c, o, m, objs) => - { - Assert.AreEqual(containerName, c); - Assert.AreEqual(objectName, o); - staticManifestCreateWasCalled = true; - return await Task.Run(() => manifest); - }; - - var provider = new LargeStorageObjectCreator(client); - await provider.CreateStorageManifest(manifest); - Assert.IsTrue(staticManifestCreateWasCalled); - } - - [TestMethod] - public async Task CanCreateStorageManifestWithDynamicManifest() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - var segPath = "a/b/"; - var client = new TestStorageServiceClient(); - var dynamicManifestCreateWasCalled = false; - - var manifest = new DynamicLargeObjectManifest(containerName, objectName, new Dictionary(), segPath); - - client.CreateDynamicStorageManifestDelegate = async (c, o, m, segs) => - { - Assert.AreEqual(c, containerName); - Assert.AreEqual(o, objectName); - Assert.AreEqual(segs, segPath); - dynamicManifestCreateWasCalled = true; - return await Task.Run(() => manifest); - }; - - var provider = new LargeStorageObjectCreator(client); - await provider.CreateStorageManifest(manifest); - Assert.IsTrue(dynamicManifestCreateWasCalled); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CanCreateStorageManifestWithNullManifest() - { - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - await provider.CreateStorageManifest(null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CannotCreateStorageManifestWithUnsupportedManifest() - { - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - await provider.CreateStorageManifest(new TestStorageManifest("a", "a/b/c")); - } - - [TestMethod] - public async Task CanCreateLargeObjectWithStaticManifest() - { - var client = new TestStorageServiceClient(); - var segmentContainer = "LargeObjectSegments"; - var containerName = "TestContainer"; - var objectName = "TestObject"; - var metadata = new Dictionary(); - var segPath = "segs"; - var content = "THIS IS A LOT OF CONTENT THAT WILL AND CAN BE CHOPPED UP"; - var contentStream = content.ConvertToStream(); - var currentSegment = 0; - var resContent = new StringBuilder(); - - var segmentsFolder = new StorageFolder(objectName, new List()); - var segmentsContainer = new StorageContainer(segmentContainer, new Dictionary()); - segmentsContainer.Folders = new List() { segmentsFolder }; - - var manifestAsObj = new StorageObject(containerName, objectName, DateTime.UtcNow, "12345", 2048576, "text"); - var manifest = new DynamicLargeObjectManifest(containerName, objectName, segPath); - - client.GetStorageContainerDelegate = async (c) => - { - Assert.AreEqual(segmentContainer, c); - return await Task.Run(() => segmentsContainer); - }; - - client.CreateStaticStorageManifestDelegate = async (c,o,m,objs) => - { - Assert.AreEqual(containerName, c); - Assert.AreEqual(objectName, o); - Assert.AreEqual(3, objs.Count()); - return await Task.Run(() => manifest); - }; - - client.GetStorageObjectDelegate = async (c, o) => - { - Assert.AreEqual(containerName, c); - Assert.AreEqual(objectName, o); - return await Task.Run(() => manifestAsObj); - }; - - client.GetStorageFolderDelegate = async (c, o) => - { - Assert.AreEqual(segmentContainer, c); - Assert.AreEqual(objectName, o); - return await Task.Run(() => segmentsFolder); - }; - - client.CreateStorageObjectDelegate = async (c, o, m, s) => - { - Assert.AreEqual(segmentContainer, c); - Assert.AreEqual(objectName + "/" + currentSegment.ToString("D10"), o); - var item = new StorageObject(c, o, DateTime.UtcNow, "12345", 2048576, "text", m); - segmentsFolder.Objects.Add(item); - currentSegment++; - using (var sr = new StreamReader(s)) - { - resContent.Append(sr.ReadToEnd()); - } - return await Task.Run(() => item); - }; - - var provider = new LargeStorageObjectCreator(client); - var res = await provider.Create(containerName, objectName, metadata, contentStream, 3, segmentContainer); - - Assert.AreEqual(manifestAsObj, res); - Assert.AreEqual(3, currentSegment); - Assert.AreEqual(content, resContent.ToString()); - } - - [TestMethod] - public async Task CanCreateLargeObjectWithDynamicManifest() - { - var client = new TestStorageServiceClient(); - var segmentContainer = "LargeObjectSegments"; - var containerName = "TestContainer"; - var objectName = "TestObject"; - var metadata = new Dictionary(); - var segPath = segmentContainer +"/" + objectName +"/"; - var content = "THIS IS A LOT OF CONTENT THAT WILL AND CAN BE CHOPPED UP"; - var contentStream = content.ConvertToStream(); - var currentSegment = 0; - var resContent = new StringBuilder(); - - var segmentsFolder = new StorageFolder(objectName, new List()); - var segmentsContainer = new StorageContainer(segmentContainer, new Dictionary()); - segmentsContainer.Folders = new List() { segmentsFolder }; - - var manifestAsObj = new StorageObject(containerName, objectName, DateTime.UtcNow, "12345", 2048576, "text"); - var manifest = new DynamicLargeObjectManifest(containerName, objectName, segPath); - - client.GetStorageContainerDelegate = async (c) => - { - Assert.AreEqual(segmentContainer, c); - return await Task.Run(() => segmentsContainer); - }; - - client.CreateDynamicStorageManifestDelegate = async (c, o, m, segs) => - { - Assert.AreEqual(containerName, c); - Assert.AreEqual(objectName, o); - Assert.AreEqual(segPath, segs); - return await Task.Run(() => manifest); - }; - - client.GetStorageObjectDelegate = async (c, o) => - { - Assert.AreEqual(containerName, c); - Assert.AreEqual(objectName, o); - return await Task.Run(() => manifestAsObj); - }; - - client.GetStorageFolderDelegate = async (c, o) => - { - Assert.AreEqual(segmentContainer, c); - Assert.AreEqual(objectName, o); - return await Task.Run(() => segmentsFolder); - }; - - client.CreateStorageObjectDelegate = async (c, o, m, s) => - { - Assert.AreEqual(segmentContainer, c); - Assert.AreEqual(objectName + "/" + currentSegment.ToString("D10"), o); - var item = new StorageObject(c, o, DateTime.UtcNow, "12345", 576, "text", m); - segmentsFolder.Objects.Add(item); - currentSegment++; - using (var sr = new StreamReader(s)) - { - resContent.Append(sr.ReadToEnd()); - } - return await Task.Run(() => item); - }; - - var provider = new LargeStorageObjectCreator(client); - var res = await provider.Create(containerName, objectName, metadata, contentStream, 3, segmentContainer); - - Assert.AreEqual(manifestAsObj, res); - Assert.AreEqual(3, currentSegment); - Assert.AreEqual(content, resContent.ToString()); - } - - [TestMethod] - public async Task CanCreateLargeObjectWithExistingSegments() - { - var client = new TestStorageServiceClient(); - var segmentContainer = "LargeObjectSegments"; - var containerName = "TestContainer"; - var objectName = "TestObject"; - var metadata = new Dictionary(); - var segPath = "segs"; - var content = "THIS IS A LOT OF CONTENT THAT WILL AND CAN BE CHOPPED UP"; - var contentStream = content.ConvertToStream(); - - var currentSegment = 1; - var resContent = new StringBuilder().Append("THIS IS A LOT OF CO"); - - var segmentsFolder = new StorageFolder(objectName, new List()); - segmentsFolder.Objects.Add(new StorageObject(objectName + "/" + 0.ToString("D10"), segmentContainer, DateTime.UtcNow, "1234", 2048576, "text")); - var badSegment = new StorageObject(objectName + "/" + 1.ToString("D10"), segmentContainer, DateTime.UtcNow, "1234", 2048576, "text"); - segmentsFolder.Objects.Add(badSegment); - - var segmentsContainer = new StorageContainer(segmentContainer, new Dictionary()); - segmentsContainer.Folders = new List() { segmentsFolder }; - - var manifestAsObj = new StorageObject(containerName, objectName, DateTime.UtcNow, "12345", 2048576, "text"); - var manifest = new DynamicLargeObjectManifest(containerName, objectName, segPath); - - client.DeleteStorageObjectDelegate = async (c, o) => - { - await Task.Run(() => - { - Assert.AreEqual(c, segmentContainer); - Assert.AreEqual(objectName + "/" + 1.ToString("D10"), o); - segmentsFolder.Objects.Remove(badSegment); - }); - }; - - client.GetStorageContainerDelegate = async (c) => - { - Assert.AreEqual(segmentContainer, c); - return await Task.Run(() => segmentsContainer); - }; - - client.CreateStaticStorageManifestDelegate = async (c, o, m, objs) => - { - Assert.AreEqual(containerName, c); - Assert.AreEqual(objectName, o); - Assert.AreEqual(3, objs.Count()); - return await Task.Run(() => manifest); - }; - - client.GetStorageObjectDelegate = async (c, o) => - { - Assert.AreEqual(containerName, c); - Assert.AreEqual(objectName, o); - return await Task.Run(() => manifestAsObj); - }; - - client.GetStorageFolderDelegate = async (c, o) => - { - Assert.AreEqual(segmentContainer, c); - Assert.AreEqual(objectName, o); - return await Task.Run(() => segmentsFolder); - }; - - client.CreateStorageObjectDelegate = async (c, o, m, s) => - { - Assert.AreEqual(segmentContainer, c); - Assert.AreEqual(objectName + "/" + currentSegment.ToString("D10"), o); - var item = new StorageObject(c, o, DateTime.UtcNow, "12345", 2048576, "text", m); - segmentsFolder.Objects.Add(item); - currentSegment++; - using (var sr = new StreamReader(s)) - { - resContent.Append(sr.ReadToEnd()); - } - return await Task.Run(() => item); - }; - - var provider = new LargeStorageObjectCreator(client); - var res = await provider.Create(containerName, objectName, metadata, contentStream, 3, segmentContainer); - - Assert.AreEqual(manifestAsObj, res); - Assert.AreEqual(3, currentSegment); - Assert.AreEqual(content, resContent.ToString()); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CannotCreateLargeObjectWithNullContainerName() - { - var segmentContainer = "LargeObjectSegments"; - var objectName = "TestObject"; - var metadata = new Dictionary(); - var content = "THIS IS A LOT OF CONTENT THAT WILL AND CAN BE CHOPPED UP"; - var contentStream = content.ConvertToStream(); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - var res = await provider.Create(null, objectName, metadata, contentStream, 3, segmentContainer); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CannotCreateLargeObjectWithEmptyContainerName() - { - var segmentContainer = "LargeObjectSegments"; - var objectName = "TestObject"; - var metadata = new Dictionary(); - var content = "THIS IS A LOT OF CONTENT THAT WILL AND CAN BE CHOPPED UP"; - var contentStream = content.ConvertToStream(); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - var res = await provider.Create(string.Empty, objectName, metadata, contentStream, 3, segmentContainer); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CannotCreateLargeObjectWithNullObjectName() - { - var segmentContainer = "LargeObjectSegments"; - var containerName = "TestContainer"; - var metadata = new Dictionary(); - var content = "THIS IS A LOT OF CONTENT THAT WILL AND CAN BE CHOPPED UP"; - var contentStream = content.ConvertToStream(); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - var res = await provider.Create(containerName, null, metadata, contentStream, 3, segmentContainer); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CannotCreateLargeObjectWithEmptyObjectName() - { - var segmentContainer = "LargeObjectSegments"; - var containerName = "TestContainer"; - var metadata = new Dictionary(); - var content = "THIS IS A LOT OF CONTENT THAT WILL AND CAN BE CHOPPED UP"; - var contentStream = content.ConvertToStream(); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - var res = await provider.Create(containerName, string.Empty, metadata, contentStream, 3, segmentContainer); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CannotCreateLargeObjectWithNullMetadata() - { - var segmentContainer = "LargeObjectSegments"; - var containerName = "TestContainer"; - var objectName = "TestObject"; - var content = "THIS IS A LOT OF CONTENT THAT WILL AND CAN BE CHOPPED UP"; - var contentStream = content.ConvertToStream(); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - var res = await provider.Create(containerName, objectName, null, contentStream, 3, segmentContainer); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CannotCreateLargeObjectWithNullContent() - { - var segmentContainer = "LargeObjectSegments"; - var containerName = "TestContainer"; - var objectName = "TestObject"; - var metadata = new Dictionary(); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - var res = await provider.Create(containerName, objectName, metadata, null, 3, segmentContainer); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CannotCreateLargeObjectWithNullSegmentContainerName() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - var metadata = new Dictionary(); - var content = "THIS IS A LOT OF CONTENT THAT WILL AND CAN BE CHOPPED UP"; - var contentStream = content.ConvertToStream(); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - var res = await provider.Create(containerName, objectName, metadata, contentStream, 3, null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CannotCreateLargeObjectWithEmptySegmentContainerName() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - var metadata = new Dictionary(); - var content = "THIS IS A LOT OF CONTENT THAT WILL AND CAN BE CHOPPED UP"; - var contentStream = content.ConvertToStream(); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - var res = await provider.Create(containerName, objectName, metadata, contentStream, 3, string.Empty); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CannotCreateLargeObjectWithNegativeSegmentCount() - { - var segmentContainer = "LargeObjectSegments"; - var containerName = "TestContainer"; - var objectName = "TestObject"; - var metadata = new Dictionary(); - var content = "THIS IS A LOT OF CONTENT THAT WILL AND CAN BE CHOPPED UP"; - var contentStream = content.ConvertToStream(); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - var res = await provider.Create(containerName, objectName, metadata, contentStream, -3, segmentContainer); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CannotCreateLargeObjectWithZeroSegmentCount() - { - var segmentContainer = "LargeObjectSegments"; - var containerName = "TestContainer"; - var objectName = "TestObject"; - var metadata = new Dictionary(); - var content = "THIS IS A LOT OF CONTENT THAT WILL AND CAN BE CHOPPED UP"; - var contentStream = content.ConvertToStream(); - - var provider = new LargeStorageObjectCreator(new TestStorageServiceClient()); - var res = await provider.Create(containerName, objectName, metadata, contentStream, 0, segmentContainer); - } - - [TestMethod] - public async Task CanGetSegmentsFolderWithContainerAndFolder() - { - var client = new TestStorageServiceClient(); - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var container = new StorageContainer(containerName, new Dictionary()); - var folder = new StorageFolder(objectName, new List()); - container.Folders = new List() { folder }; - - client.GetStorageContainerDelegate = async (c) => - { - Assert.AreEqual(c, container.Name); - return await Task.Run(() => container); - }; - - var provider = new LargeStorageObjectCreator(client); - var res = await provider.GetSegmentsFolder(containerName, objectName); - - Assert.AreEqual(folder, res); - } - - [TestMethod] - public async Task CanGetSegmentsFolderWithContainerAndNoFolder() - { - var client = new TestStorageServiceClient(); - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var container = new StorageContainer(containerName, new Dictionary()); - var folder = new StorageFolder(objectName, new List()); - container.Folders = new List() { folder }; - - client.GetStorageContainerDelegate = async (c) => - { - Assert.AreEqual(container.Name, c); - return await Task.Run(() => container); - }; - - client.CreateStorageFolderDelegate = async (c, f) => - { - await Task.Run(() => - { - Assert.AreEqual(container.Name, c); - Assert.AreEqual(folder.FullName, f); - }); - }; - - client.GetStorageFolderDelegate = async (c, f) => - { - Assert.AreEqual(container.Name, c); - Assert.AreEqual(folder.FullName, f); - return await Task.Run(() => folder); - }; - - var provider = new LargeStorageObjectCreator(client); - var res = await provider.GetSegmentsFolder(containerName, objectName); - - Assert.AreEqual(folder, res); - } - - [TestMethod] - public async Task CanGetSegmentsFolderWithNoContainer() - { - var client = new TestStorageServiceClient(); - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var container = new StorageContainer(containerName, new Dictionary()); - var folder = new StorageFolder(objectName, new List()); - container.Folders = new List() { folder }; - - client.GetStorageContainerDelegate = (c) => - { - throw new InvalidOperationException(string.Format("Failed to get storage container '{0}'. The remote server returned the following status code: '{1}'.", containerName, HttpStatusCode.NotFound)); - }; - - client.CreateStorageContainerDelegate = async (c, m) => - { - await Task.Run(() => Assert.AreEqual(container.Name, c)); - }; - - client.CreateStorageFolderDelegate = async (c, f) => - { - await Task.Run(() => - { - Assert.AreEqual(container.Name, c); - Assert.AreEqual(folder.FullName, f); - }); - }; - - client.GetStorageFolderDelegate = async (c, f) => - { - Assert.AreEqual(container.Name, c); - Assert.AreEqual(folder.FullName, f); - return await Task.Run(() => folder); - }; - - var provider = new LargeStorageObjectCreator(client); - var res = await provider.GetSegmentsFolder(containerName, objectName); - - Assert.AreEqual(folder, res); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task CannotGetSegmentsFolderWhenGetContainerFailsWithNon404() - { - var client = new TestStorageServiceClient(); - var containerName = "TestContainer"; - var objectName = "TestObject"; - - client.GetStorageContainerDelegate = (c) => - { - throw new InvalidOperationException(string.Format("Failed to get storage container '{0}'. The remote server returned the following status code: '500'.", containerName)); - }; - - var provider = new LargeStorageObjectCreator(client); - await provider.GetSegmentsFolder(containerName, objectName); - } - } -} diff --git a/OpenStack/OpenStack.Test/Storage/StorageAccountPayloadConverterTests.cs b/OpenStack/OpenStack.Test/Storage/StorageAccountPayloadConverterTests.cs deleted file mode 100644 index 9d92c77..0000000 --- a/OpenStack/OpenStack.Test/Storage/StorageAccountPayloadConverterTests.cs +++ /dev/null @@ -1,270 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Common.Http; -using OpenStack.Common.ServiceLocation; -using OpenStack.Storage; - -namespace OpenStack.Test.Storage -{ - [TestClass] - public class StorageAccountPayloadConverterTests - { - [TestMethod] - public void CanParseAccountWithValidJsonPayloadAndHeaders() - { - var accountName = "1234567890"; - var validSingleContainerJson = @"[ - { - ""count"": 1, - ""bytes"": 7, - ""name"": ""TestContainer"" - }]"; - - var headers = new HttpHeadersAbstraction - { - {"X-Account-Bytes-Used", "12345"}, - {"X-Account-Object-Count", "1"}, - {"X-Account-Container-Count", "1"} - }; - - var converter = new StorageAccountPayloadConverter(new ServiceLocator()); - var account = converter.Convert(accountName, headers, validSingleContainerJson); - - Assert.IsNotNull(account); - Assert.AreEqual(accountName, account.Name); - Assert.AreEqual(12345, account.TotalBytesUsed); - Assert.AreEqual(1, account.TotalObjectCount); - Assert.AreEqual(1, account.TotalContainerCount); - Assert.AreEqual(1, account.Containers.ToList().Count()); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseAccountWithMissingBytesUsedHeader() - { - var accountName = "1234567890"; - var validSingleContainerJson = @"[ - { - ""count"": 1, - ""bytes"": 7, - ""name"": ""TestContainer"" - }]"; - - var headers = new HttpHeadersAbstraction - { - {"X-Account-Object-Count", "1"}, - {"X-Account-Container-Count", "1"} - }; - - var converter = new StorageAccountPayloadConverter(new ServiceLocator()); - converter.Convert(accountName, headers, validSingleContainerJson); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseAccountWithMissingObjectCountHeader() - { - var accountName = "1234567890"; - var validSingleContainerJson = @"[ - { - ""count"": 1, - ""bytes"": 7, - ""name"": ""TestContainer"" - }]"; - - var headers = new HttpHeadersAbstraction - { - {"X-Account-Bytes-Used", "12345"}, - {"X-Account-Container-Count", "1"} - }; - - var converter = new StorageAccountPayloadConverter(new ServiceLocator()); - converter.Convert(accountName, headers, validSingleContainerJson); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseAccountWithMissingContainerCountHeader() - { - var accountName = "1234567890"; - var validSingleContainerJson = @"[ - { - ""count"": 1, - ""bytes"": 7, - ""name"": ""TestContainer"" - }]"; - - var headers = new HttpHeadersAbstraction - { - {"X-Account-Bytes-Used", "12345"}, - {"X-Account-Object-Count", "1"} - }; - - var converter = new StorageAccountPayloadConverter(new ServiceLocator()); - converter.Convert(accountName, headers, validSingleContainerJson); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseAccountWithBadBytesUsedHeader() - { - var accountName = "1234567890"; - var validSingleContainerJson = @"[ - { - ""count"": 1, - ""bytes"": 7, - ""name"": ""TestContainer"" - }]"; - - var headers = new HttpHeadersAbstraction - { - {"X-Account-Bytes-Used", "NOT A NUMBER"}, - {"X-Account-Object-Count", "1"}, - {"X-Account-Container-Count", "1"} - }; - - var converter = new StorageAccountPayloadConverter(new ServiceLocator()); - converter.Convert(accountName, headers, validSingleContainerJson); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseAccountWithBadObjectCountHeader() - { - var accountName = "1234567890"; - var validSingleContainerJson = @"[ - { - ""count"": 1, - ""bytes"": 7, - ""name"": ""TestContainer"" - }]"; - - var headers = new HttpHeadersAbstraction - { - {"X-Account-Bytes-Used", "12345"}, - {"X-Account-Object-Count", "NOT A NUMBER"}, - {"X-Account-Container-Count", "1"} - }; - - var converter = new StorageAccountPayloadConverter(new ServiceLocator()); - converter.Convert(accountName, headers, validSingleContainerJson); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseAccountWithBadContainerCountHeader() - { - var accountName = "1234567890"; - var validSingleContainerJson = @"[ - { - ""count"": 1, - ""bytes"": 7, - ""name"": ""TestContainer"" - }]"; - - var headers = new HttpHeadersAbstraction - { - {"X-Account-Bytes-Used", "12345"}, - {"X-Account-Object-Count", "1"}, - {"X-Account-Container-Count", "NOT A NUMBER"} - }; - - var converter = new StorageAccountPayloadConverter(new ServiceLocator()); - converter.Convert(accountName, headers, validSingleContainerJson); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseAccountWithBadPayload() - { - var accountName = "1234567890"; - var invalidSingleContainerJson = @"[ - { - ""bytes"": 7, - ""name"": ""TestContainer"" - }]"; - - var headers = new HttpHeadersAbstraction - { - {"X-Account-Bytes-Used", "12345"}, - {"X-Account-Object-Count", "1"}, - {"X-Account-Container-Count", "1"} - }; - - var converter = new StorageAccountPayloadConverter(new ServiceLocator()); - converter.Convert(accountName, headers, invalidSingleContainerJson); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotParseAccountWithNullName() - { - var validSingleContainerJson = @"[ - { - ""count"": 1, - ""bytes"": 7, - ""name"": ""TestContainer"" - }]"; - - var headers = new HttpHeadersAbstraction - { - {"X-Account-Bytes-Used", "12345"}, - {"X-Account-Object-Count", "1"}, - {"X-Account-Container-Count", "1"} - }; - - var converter = new StorageAccountPayloadConverter(new ServiceLocator()); - converter.Convert(null, headers, validSingleContainerJson); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotParseAccountWithNullHeaders() - { - var accountName = "1234567890"; - var validSingleContainerJson = @"[ - { - ""count"": 1, - ""bytes"": 7, - ""name"": ""TestContainer"" - }]"; - - var converter = new StorageAccountPayloadConverter(new ServiceLocator()); - converter.Convert(accountName, null, validSingleContainerJson); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotParseAccountWithNullPayload() - { - var accountName = "1234567890"; - - var headers = new HttpHeadersAbstraction - { - {"X-Account-Bytes-Used", "12345"}, - {"X-Account-Object-Count", "1"}, - {"X-Account-Container-Count", "1"} - }; - - var converter = new StorageAccountPayloadConverter(new ServiceLocator()); - converter.Convert(accountName, headers, null); - } - } -} diff --git a/OpenStack/OpenStack.Test/Storage/StorageContainerPayloadConverterTests.cs b/OpenStack/OpenStack.Test/Storage/StorageContainerPayloadConverterTests.cs deleted file mode 100644 index 3df32cb..0000000 --- a/OpenStack/OpenStack.Test/Storage/StorageContainerPayloadConverterTests.cs +++ /dev/null @@ -1,530 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Common.Http; -using OpenStack.Common.ServiceLocation; -using OpenStack.Storage; - -namespace OpenStack.Test.Storage -{ - [TestClass] - public class StorageContainerPayloadConverterTests - { - [TestMethod] - public void CanParseValidJsonPayloadWithMultipleObjects() - { - var validMultipleContainerJson = @"[ - { - ""count"": 1, - ""bytes"": 7, - ""name"": ""TestContainer"" - }, - { - ""count"": 5, - ""bytes"": 2000, - ""name"": ""OtherTestContainer"" - } - ]"; - - var converter = new StorageContainerPayloadConverter(new ServiceLocator()); - var containers = converter.Convert(validMultipleContainerJson).ToList(); - - Assert.AreEqual(2, containers.Count()); - var obj1 = - containers.First(o => string.Equals(o.Name, "TestContainer", StringComparison.InvariantCultureIgnoreCase)); - var obj2 = - containers.First(o => string.Equals(o.Name, "OtherTestContainer", StringComparison.InvariantCultureIgnoreCase)); - Assert.IsNotNull(obj1); - Assert.IsNotNull(obj2); - - Assert.AreEqual(7, obj1.TotalBytesUsed); - Assert.AreEqual("TestContainer", obj1.Name); - Assert.AreEqual(1, obj1.TotalObjectCount); - - Assert.AreEqual(2000, obj2.TotalBytesUsed); - Assert.AreEqual("OtherTestContainer", obj2.Name); - Assert.AreEqual(5, obj2.TotalObjectCount); - } - - [TestMethod] - public void CanParseValidJsonPayloadWithSingleObject() - { - var validSingleContainerJson = @"[ - { - ""count"": 1, - ""bytes"": 7, - ""name"": ""TestContainer"" - }]"; - - var converter = new StorageContainerPayloadConverter(new ServiceLocator()); - var containers = converter.Convert(validSingleContainerJson).ToList(); - - Assert.AreEqual(1, containers.Count()); - var obj1 = - containers.First(o => string.Equals(o.Name, "TestContainer", StringComparison.InvariantCultureIgnoreCase)); - Assert.IsNotNull(obj1); - - Assert.AreEqual(7, obj1.TotalBytesUsed); - Assert.AreEqual("TestContainer", obj1.Name); - Assert.AreEqual(1, obj1.TotalObjectCount); - } - - [TestMethod] - public void CanParseValidEmptyJsonArrayPayload() - { - var emptyJsonArray = @"[]"; - - var converter = new StorageContainerPayloadConverter(new ServiceLocator()); - var containers = converter.Convert(emptyJsonArray).ToList(); - - Assert.AreEqual(0, containers.Count()); - } - - [TestMethod] - public void CanParseAnEmptyPayload() - { - var payload = string.Empty; - - var converter = new StorageContainerPayloadConverter(new ServiceLocator()); - var containers = converter.Convert(payload).ToList(); - - Assert.AreEqual(0, containers.Count()); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotParseANullPayload() - { - var converter = new StorageContainerPayloadConverter(new ServiceLocator()); - converter.Convert(null); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseInvalidJsonPayload() - { - var converter = new StorageContainerPayloadConverter(new ServiceLocator()); - converter.Convert("[ { \"SomeAtrib\" }]"); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseInvalidPayload() - { - var converter = new StorageContainerPayloadConverter(new ServiceLocator()); - converter.Convert("NOT JSON"); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseJsonPayloadWithMissingBytesProperty() - { - var InvalidJsonWithoutBytes = @"[ - { - ""count"": 1, - ""name"": ""TestContainer"" - }]"; - - var converter = new StorageContainerPayloadConverter(new ServiceLocator()); - converter.Convert(InvalidJsonWithoutBytes); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseJsonPayloadWithMissingCountProperty() - { - string InvalidJsonWithoutCount = @"[ - { - ""bytes"": 7, - ""name"": ""TestContainer"" - }]"; - - var converter = new StorageContainerPayloadConverter(new ServiceLocator()); - converter.Convert(InvalidJsonWithoutCount); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseJsonPayloadWithMissingNameProperty() - { - string InvalidJsonWithoutName = @"[ - { - ""count"": 1, - ""bytes"": 7 - }]"; - - var converter = new StorageContainerPayloadConverter(new ServiceLocator()); - converter.Convert(InvalidJsonWithoutName); - } - - [TestMethod] - public void ParseExceptionIncludesNameWhenPossible() - { - string InvalidJsonWithoutBytes = @"[ - { - ""count"": 1, - ""name"": ""TestContainer"" - }]"; - - var converter = new StorageContainerPayloadConverter(new ServiceLocator()); - try - { - converter.Convert(InvalidJsonWithoutBytes); - Assert.Fail("Parsing did not fail as expected."); - } - catch (FormatException ex) - { - Assert.IsTrue(ex.Message.StartsWith("Storage Container 'TestContainer'")); - } - - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseJsonPayloadWithBadBytesValue() - { - string InvalidJsonWithBadBytesValue = @"[ - { - ""count"": 1, - ""bytes"": ""NOT A NUMBER"", - ""name"": ""TestContainer"" - }]"; - - var converter = new StorageContainerPayloadConverter(new ServiceLocator()); - converter.Convert(InvalidJsonWithBadBytesValue); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseJsonPayloadWithBadCountValue() - { - string InvalidJsonWithBadCountValue = @"[ - { - ""count"": ""NOT A NUMBER"", - ""bytes"": 12345, - ""name"": ""TestContainer"" - }]"; - - var converter = new StorageContainerPayloadConverter(new ServiceLocator()); - converter.Convert(InvalidJsonWithBadCountValue); - } - - [TestMethod] - public void CanParseContainerWithValidJsonPayloadAndHeaders() - { - var containerName = "TestContainer"; - var validObjectJson = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": 0, - ""name"": ""BLAH"", - ""content_type"": ""application/octet-stream"" - }]"; - - var converter = new StorageContainerPayloadConverter(new ServiceLocator()); - var headers = new HttpHeadersAbstraction - { - {"X-Container-Bytes-Used", "12345"}, - {"X-Container-Object-Count", "1"} - }; - - var container = converter.Convert(containerName, headers, validObjectJson); - Assert.IsNotNull(container); - Assert.AreEqual(containerName,container.Name); - Assert.AreEqual(12345, container.TotalBytesUsed); - Assert.AreEqual(1, container.TotalObjectCount); - Assert.AreEqual(1, container.Objects.ToList().Count()); - } - - [TestMethod] - public void CanParseContainerWithValidJsonPayloadWithNestedFoldersAndObjects() - { - var containerName = "TestContainer"; - var validObjectJson = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-27T20:57:11.150910"", - ""bytes"": 0, - ""name"": ""a/"", - ""content_type"": ""application/octet-stream"" - }, - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-27T20:57:36.676350"", - ""bytes"": 0, - ""name"": ""a/b/"", - ""content_type"": ""application/octet-stream"" - }, - { - ""hash"": ""437b930db84b8079c2dd804a71936b5f"", - ""last_modified"": ""2014-03-27T20:58:36.676620"", - ""bytes"": 9, - ""name"": ""a/b/b"", - ""content_type"": ""text/plain;charset=UTF-8"" - }, - { - ""hash"": ""437b930db84b8079c2dd804a71936b5f"", - ""last_modified"": ""2014-03-27T20:58:43.935540"", - ""bytes"": 9, - ""name"": ""a/b/c"", - ""content_type"": ""text/plain;charset=UTF-8"" - }, - { - ""hash"": ""437b930db84b8079c2dd804a71936b5f"", - ""last_modified"": ""2014-03-27T20:58:54.142580"", - ""bytes"": 9, - ""name"": ""a/b/c/object3"", - ""content_type"": ""text/plain;charset=UTF-8"" - }, - { - ""hash"": ""437b930db84b8079c2dd804a71936b5f"", - ""last_modified"": ""2014-03-27T20:58:25.771530"", - ""bytes"": 9, - ""name"": ""a/object2"", - ""content_type"": ""text/plain;charset=UTF-8"" - }, - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-27T20:57:47.122360"", - ""bytes"": 0, - ""name"": ""a/x/"", - ""content_type"": ""application/octet-stream"" - }, - { - ""hash"": ""437b930db84b8079c2dd804a71936b5f"", - ""last_modified"": ""2014-03-27T20:58:15.696360"", - ""bytes"": 9, - ""name"": ""object1"", - ""content_type"": ""text/plain;charset=UTF-8"" - } - ]"; - - var converter = new StorageContainerPayloadConverter(new ServiceLocator()); - var headers = new HttpHeadersAbstraction - { - {"X-Container-Bytes-Used", "45"}, - {"X-Container-Object-Count", "8"} - }; - - var container = converter.Convert(containerName, headers, validObjectJson); - Assert.IsNotNull(container); - Assert.AreEqual(containerName, container.Name); - Assert.AreEqual(45, container.TotalBytesUsed); - Assert.AreEqual(8, container.TotalObjectCount); - Assert.AreEqual(8, container.Objects.ToList().Count()); - Assert.IsTrue(container.Objects.ToList().Any(o => o.Name == "object1")); - - var folders = container.Folders.ToList(); - Assert.AreEqual(1, folders.Count()); - - var aNode = folders.First(); - Assert.AreEqual("a", aNode.Name); - Assert.AreEqual(2, aNode.Folders.Count); - Assert.AreEqual(1, aNode.Objects.Count); - Assert.IsTrue(aNode.Objects.Any(f => f.FullName == "a/object2")); - - var xNode = aNode.Folders.First(f => f.Name == "x"); - Assert.AreEqual(0, xNode.Folders.Count); - Assert.AreEqual(0, xNode.Objects.Count); - - var bNode = aNode.Folders.First(f => f.Name == "b"); - Assert.AreEqual(1, bNode.Folders.Count); - Assert.AreEqual(2, bNode.Objects.Count); - Assert.IsTrue(bNode.Folders.Any(f => f.Name == "c")); - Assert.IsTrue(bNode.Objects.Any(f => f.FullName == "a/b/c")); - Assert.IsTrue(bNode.Objects.Any(f => f.FullName == "a/b/b")); - - var cNode = bNode.Folders.First(f => f.Name == "c"); - Assert.AreEqual(0, cNode.Folders.Count); - Assert.AreEqual(1, cNode.Objects.Count); - Assert.IsTrue(cNode.Objects.Any(f => f.FullName == "a/b/c/object3")); - - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseContainerWithMissingBytesUsedHeader() - { - var containerName = "TestContainer"; - var validObjectJson = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": 0, - ""name"": ""BLAH"", - ""content_type"": ""application/octet-stream"" - }]"; - - var converter = new StorageContainerPayloadConverter(new ServiceLocator()); - var headers = new HttpHeadersAbstraction - { - {"X-Container-Object-Count", "1"} - }; - - converter.Convert(containerName, headers, validObjectJson); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseContainerWithMissingObjectCountHeader() - { - var containerName = "TestContainer"; - var validObjectJson = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": 0, - ""name"": ""BLAH"", - ""content_type"": ""application/octet-stream"" - }]"; - - var converter = new StorageContainerPayloadConverter(new ServiceLocator()); - var headers = new HttpHeadersAbstraction - { - {"X-Container-Bytes-Used", "12345"} - }; - - converter.Convert(containerName, headers, validObjectJson); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseContainerWithBadBytesUsedHeader() - { - var containerName = "TestContainer"; - var validObjectJson = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": 0, - ""name"": ""BLAH"", - ""content_type"": ""application/octet-stream"" - }]"; - - var converter = new StorageContainerPayloadConverter(new ServiceLocator()); - var headers = new HttpHeadersAbstraction - { - {"X-Container-Bytes-Used", "This is not a number"}, - {"X-Container-Object-Count", "1"} - }; - - converter.Convert(containerName, headers, validObjectJson); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseContainerWithBadObjectCountHeader() - { - var containerName = "TestContainer"; - var validObjectJson = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": 0, - ""name"": ""BLAH"", - ""content_type"": ""application/octet-stream"" - }]"; - - var converter = new StorageContainerPayloadConverter(new ServiceLocator()); - var headers = new HttpHeadersAbstraction - { - {"X-Container-Bytes-Used", "12345"}, - {"X-Container-Object-Count", "This is not a number"} - }; - - converter.Convert(containerName, headers, validObjectJson); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseContainerWithBadPayload() - { - var containerName = "TestContainer"; - var validObjectJson = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"":"; - - var converter = new StorageContainerPayloadConverter(new ServiceLocator()); - var headers = new HttpHeadersAbstraction - { - {"X-Container-Bytes-Used", "12345"}, - {"X-Container-Object-Count", "1"} - }; - - converter.Convert(containerName, headers, validObjectJson); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotParseContainerWithNullName() - { - var validObjectJson = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": 0, - ""name"": ""BLAH"", - ""content_type"": ""application/octet-stream"" - }]"; - - var converter = new StorageContainerPayloadConverter(new ServiceLocator()); - var headers = new HttpHeadersAbstraction - { - {"X-Container-Bytes-Used", "12345"}, - {"X-Container-Object-Count", "1"} - }; - - converter.Convert(null, headers, validObjectJson); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotParseContainerWithNullHeaders() - { - var validObjectJson = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": 0, - ""name"": ""BLAH"", - ""content_type"": ""application/octet-stream"" - }]"; - - var converter = new StorageContainerPayloadConverter(new ServiceLocator()); - - converter.Convert("Name", null, validObjectJson); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotParseContainerWithNullPayload() - { - var converter = new StorageContainerPayloadConverter(new ServiceLocator()); - var headers = new HttpHeadersAbstraction - { - {"X-Container-Bytes-Used", "12345"}, - {"X-Container-Object-Count", "1"} - }; - - converter.Convert("Name", headers, null); - } - } -} diff --git a/OpenStack/OpenStack.Test/Storage/StorageFolderPayloadConverterTests.cs b/OpenStack/OpenStack.Test/Storage/StorageFolderPayloadConverterTests.cs deleted file mode 100644 index 3a1504a..0000000 --- a/OpenStack/OpenStack.Test/Storage/StorageFolderPayloadConverterTests.cs +++ /dev/null @@ -1,432 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Common.ServiceLocation; -using OpenStack.Storage; - -namespace OpenStack.Test.Storage -{ - [TestClass] - public class StorageFolderPayloadConverterTests - { - [TestMethod] - public void CanAddFolderWithNestedFolders() - { - var objects = new List() { new StorageObject("a/b/c/d/","a") }; - var converter = new StorageFolderPayloadConverter(new ServiceLocator()); - var folders = converter.Convert(objects).ToList(); - - Assert.AreEqual(1,folders.Count); - Assert.AreEqual("a",folders[0].Name); - Assert.AreEqual(1, folders[0].Folders.Count); - Assert.AreEqual("b", folders[0].Folders.First().Name); - Assert.AreEqual(1, folders[0].Folders.First().Folders.Count); - Assert.AreEqual("c", folders[0].Folders.First().Folders.First().Name); - Assert.AreEqual(1, folders[0].Folders.First().Folders.First().Folders.Count); - Assert.AreEqual("d", folders[0].Folders.First().Folders.First().Folders.First().Name); - } - - [TestMethod] - public void CanAddFolderWithNestedFoldersAndDuplicateNames() - { - var objects = new List() { new StorageObject("a/c/c/c/", "a") }; - var converter = new StorageFolderPayloadConverter(new ServiceLocator()); - var folders = converter.Convert(objects).ToList(); - - Assert.AreEqual(1, folders.Count); - Assert.AreEqual("a", folders[0].Name); - Assert.AreEqual(1, folders[0].Folders.Count); - Assert.AreEqual("c", folders[0].Folders.First().Name); - Assert.AreEqual(1, folders[0].Folders.First().Folders.Count); - Assert.AreEqual("c", folders[0].Folders.First().Folders.First().Name); - Assert.AreEqual(1, folders[0].Folders.First().Folders.First().Folders.Count); - Assert.AreEqual("c", folders[0].Folders.First().Folders.First().Folders.First().Name); - } - - [TestMethod] - public void CanAddSingleFolder() - { - var objects = new List() { new StorageObject("a/", "a") }; - var converter = new StorageFolderPayloadConverter(new ServiceLocator()); - var folders = converter.Convert(objects).ToList(); - - Assert.AreEqual(1, folders.Count); - Assert.AreEqual("a", folders[0].Name); - Assert.AreEqual(0, folders[0].Folders.Count); - } - - [TestMethod] - - [ExpectedException(typeof(ArgumentNullException))] - public void CanAddFolderWithNullObjectList() - { - var converter = new StorageFolderPayloadConverter(new ServiceLocator()); - converter.Convert(null); - } - - [TestMethod] - public void CanAddNestedFoldersWhenRootExists() - { - var objects = new List() { new StorageObject("a/", "a"), new StorageObject("a/b/c/d/", "a") }; - - var converter = new StorageFolderPayloadConverter(new ServiceLocator()); - var folders = converter.Convert(objects).ToList(); - - Assert.AreEqual(1, folders.Count); - Assert.AreEqual("a", folders[0].Name); - Assert.AreEqual(1, folders[0].Folders.Count); - Assert.AreEqual("b", folders[0].Folders.First().Name); - Assert.AreEqual(1, folders[0].Folders.First().Folders.Count); - Assert.AreEqual("c", folders[0].Folders.First().Folders.First().Name); - Assert.AreEqual(1, folders[0].Folders.First().Folders.First().Folders.Count); - Assert.AreEqual("d", folders[0].Folders.First().Folders.First().Folders.First().Name); - } - - [TestMethod] - public void CanAddNestedFoldersWhenRootExistsWithObjectsAtLeaf() - { - var objects = new List() { new StorageObject("a/b/c/d/foo", "a"), new StorageObject("a/b/c/d/bar", "a") }; - - var converter = new StorageFolderPayloadConverter(new ServiceLocator()); - var folders = converter.Convert(objects).ToList(); - - Assert.AreEqual(1, folders.Count); - Assert.AreEqual("a", folders[0].Name); - Assert.AreEqual(1, folders[0].Folders.Count); - Assert.AreEqual("b", folders[0].Folders.First().Name); - Assert.AreEqual(1, folders[0].Folders.First().Folders.Count); - Assert.AreEqual("c", folders[0].Folders.First().Folders.First().Name); - Assert.AreEqual(1, folders[0].Folders.First().Folders.First().Folders.Count); - - var leaf = folders[0].Folders.First().Folders.First().Folders.First(); - Assert.AreEqual("d", leaf.Name); - Assert.AreEqual(2,leaf.Objects.Count); - Assert.IsTrue(leaf.Objects.Any(o => o.FullName == "a/b/c/d/foo")); - Assert.IsTrue(leaf.Objects.Any(o => o.FullName == "a/b/c/d/bar")); - } - - [TestMethod] - public void CanAddNestedFoldersWhenRootExistsWithObjectsAtLeafAndRoot() - { - var objects = new List() { new StorageObject("a/b/c/d/foo", "a"), new StorageObject("a/b/c/d/bar", "a"), new StorageObject("xyz", "a") }; - - var converter = new StorageFolderPayloadConverter(new ServiceLocator()); - var folders = converter.Convert(objects).ToList(); - - Assert.AreEqual(1, folders.Count); - Assert.AreEqual("a", folders[0].Name); - Assert.AreEqual(1, folders[0].Folders.Count); - Assert.AreEqual("b", folders[0].Folders.First().Name); - Assert.AreEqual(1, folders[0].Folders.First().Folders.Count); - Assert.AreEqual("c", folders[0].Folders.First().Folders.First().Name); - Assert.AreEqual(1, folders[0].Folders.First().Folders.First().Folders.Count); - - var leaf = folders[0].Folders.First().Folders.First().Folders.First(); - Assert.AreEqual("d", leaf.Name); - Assert.AreEqual(2, leaf.Objects.Count); - Assert.IsTrue(leaf.Objects.Any(o => o.FullName == "a/b/c/d/foo")); - Assert.IsTrue(leaf.Objects.Any(o => o.FullName == "a/b/c/d/bar")); - } - - [TestMethod] - public void CanAddNestedFoldersWhenRootExistsWithObjectsAtLeafAndLongNameAtRoot() - { - var objects = new List() { new StorageObject("a/b/c/d/foo", "a"), new StorageObject("a/b/c/d/bar", "a"), new StorageObject("thiswillsorttothetopofthelist", "a") }; - - var converter = new StorageFolderPayloadConverter(new ServiceLocator()); - var folders = converter.Convert(objects).ToList(); - - Assert.AreEqual(1, folders.Count); - Assert.AreEqual("a", folders[0].Name); - Assert.AreEqual(1, folders[0].Folders.Count); - Assert.AreEqual("b", folders[0].Folders.First().Name); - Assert.AreEqual(1, folders[0].Folders.First().Folders.Count); - Assert.AreEqual("c", folders[0].Folders.First().Folders.First().Name); - Assert.AreEqual(1, folders[0].Folders.First().Folders.First().Folders.Count); - - var leaf = folders[0].Folders.First().Folders.First().Folders.First(); - Assert.AreEqual("d", leaf.Name); - Assert.AreEqual(2, leaf.Objects.Count); - Assert.IsTrue(leaf.Objects.Any(o => o.FullName == "a/b/c/d/foo")); - Assert.IsTrue(leaf.Objects.Any(o => o.FullName == "a/b/c/d/bar")); - } - - [TestMethod] - public void CanAddNestedFoldersWhenRootExistsWithObjectsAtManyLevels() - { - var objects = new List() { new StorageObject("a/b/c/d/foo", "a"), - new StorageObject("a/b/bar", "a"), - new StorageObject("a/b/c/beans", "a"), - new StorageObject("a/string", "a"), - new StorageObject("a/b/c/d/", "a") , - new StorageObject("a/b/c/", "a") , - new StorageObject("a/", "a") - }; - - var converter = new StorageFolderPayloadConverter(new ServiceLocator()); - var folders = converter.Convert(objects).ToList(); - - var aNode = folders[0]; - var bNode = folders[0].Folders.First(); - var cNode = folders[0].Folders.First().Folders.First(); - var dNode = folders[0].Folders.First().Folders.First().Folders.First(); - - Assert.AreEqual(1, folders.Count); - - Assert.AreEqual("a", aNode.Name); - Assert.AreEqual(1, aNode.Folders.Count); - Assert.AreEqual(1, aNode.Objects.Count); - Assert.IsTrue(aNode.Objects.Any(o => o.FullName == "a/string")); - - Assert.AreEqual("b", bNode.Name); - Assert.AreEqual("a/b", bNode.FullName); - Assert.AreEqual(1, bNode.Folders.Count); - Assert.AreEqual(1, bNode.Objects.Count); - Assert.IsTrue(bNode.Objects.Any(o => o.FullName == "a/b/bar")); - - Assert.AreEqual("c", cNode.Name); - Assert.AreEqual("a/b/c", cNode.FullName); - Assert.AreEqual(1, cNode.Folders.Count); - Assert.AreEqual(1, cNode.Objects.Count); - Assert.IsTrue(cNode.Objects.Any(o => o.FullName == "a/b/c/beans")); - - Assert.AreEqual("d", dNode.Name); - Assert.AreEqual("a/b/c/d", dNode.FullName); - Assert.AreEqual(1, dNode.Objects.Count); - Assert.IsTrue(dNode.Objects.Any(o => o.FullName == "a/b/c/d/foo")); - } - - [TestMethod] - public void CanConvertFoldersWithObjects() - { - var objects = new List() - { - new StorageObject("a", "a"), - new StorageObject("a/", "a"), - new StorageObject("b//", "a"), - new StorageObject("//a/", "a"), - new StorageObject("a/b/", "a", DateTime.Now, "12345", 100, "application/directory") - }; - - var converter = new StorageFolderPayloadConverter(new ServiceLocator()); - var resp = converter.Convert(objects).ToList(); - - Assert.AreEqual(1, resp.Count); - - var aNode = resp.First(); - Assert.AreEqual("a", aNode.Name); - Assert.AreEqual(1, aNode.Folders.Count); - Assert.AreEqual(0, aNode.Objects.Count); - - var bNode = aNode.Folders.First(); - Assert.AreEqual("b", bNode.Name); - Assert.AreEqual("a/b", bNode.FullName); - Assert.AreEqual(0, bNode.Folders.Count); - Assert.AreEqual(0, bNode.Objects.Count); - - Assert.AreEqual(5, objects.Count); - } - - [TestMethod] - public void CanConvertFoldersWithNoInputObjects() - { - var objects = new List(); - - var converter = new StorageFolderPayloadConverter(new ServiceLocator()); - var resp = converter.Convert(objects).ToList(); - - Assert.AreEqual(0, resp.Count); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotConvertFoldersWithNullObjectList() - { - var converter = new StorageFolderPayloadConverter(new ServiceLocator()); - var resp = converter.Convert(null); - } - - [TestMethod] - public void CanConvertFolderWithValidJsonAndNoSubFoldersOrFolderObject() - { - var containerName = "container"; - var folderName = "a/b/c/"; - var payload = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": 0, - ""name"": ""a/b/c/BLAH"", - ""content_type"": ""application/octet-stream"" - }]"; - - var converter = new StorageFolderPayloadConverter(new ServiceLocator()); - var resp = converter.Convert(containerName, folderName, payload); - - Assert.AreEqual(1, resp.Objects.Count); - Assert.AreEqual(0, resp.Folders.Count); - Assert.AreEqual("a/b/c/", resp.FullName); - Assert.AreEqual("c", resp.Name); - - var obj = resp.Objects.First(); - Assert.AreEqual("a/b/c/BLAH", obj.FullName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidDataException))] - public void CannotConvertEmptyJsonArrayPayload() - { - var containerName = "container"; - var folderName = "a/b/c/"; - var payload = @"[]"; - - var converter = new StorageFolderPayloadConverter(new ServiceLocator()); - converter.Convert(containerName, folderName, payload); - } - - [TestMethod] - public void CanConvertFolderWithValidJsonFolderObjectAndNoSubFolders() - { - var containerName = "container"; - var folderName = "a/b/c/"; - var payload = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": 0, - ""name"": ""a/b/c/"", - ""content_type"": ""application/octet-stream"" - }, - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": 0, - ""name"": ""a/b/c/BLAH"", - ""content_type"": ""application/octet-stream"" - }]"; - - var converter = new StorageFolderPayloadConverter(new ServiceLocator()); - var resp = converter.Convert(containerName, folderName, payload); - - Assert.AreEqual(1, resp.Objects.Count); - Assert.AreEqual(0, resp.Folders.Count); - Assert.AreEqual("a/b/c/", resp.FullName); - Assert.AreEqual("c", resp.Name); - - var obj = resp.Objects.First(); - Assert.AreEqual("a/b/c/BLAH", obj.FullName); - } - - [TestMethod] - public void CanConvertFolderWithValidJsonSubFoldersAndNoFolderObject() - { - var containerName = "container"; - var folderName = "a/b/c/"; - var payload = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": 0, - ""name"": ""a/b/c/BLAH"", - ""content_type"": ""application/octet-stream"" - }, - { - ""subdir"": ""a/b/c/d/"" - }, - { - ""subdir"": ""a/b/c/x/"" - }]"; - - var converter = new StorageFolderPayloadConverter(new ServiceLocator()); - var resp = converter.Convert(containerName, folderName, payload); - - Assert.AreEqual(1, resp.Objects.Count); - Assert.AreEqual(2, resp.Folders.Count); - Assert.AreEqual("a/b/c/", resp.FullName); - Assert.AreEqual("c", resp.Name); - - var obj = resp.Objects.First(); - Assert.AreEqual("a/b/c/BLAH", obj.FullName); - - var dNode = resp.Folders.First(f => f.FullName == "a/b/c/d/"); - var xNode = resp.Folders.First(f => f.FullName == "a/b/c/x/"); - - Assert.AreEqual("d", dNode.Name); - Assert.AreEqual(0, dNode.Folders.Count); - Assert.AreEqual(0, dNode.Objects.Count); - - Assert.AreEqual("x", xNode.Name); - Assert.AreEqual(0, xNode.Folders.Count); - Assert.AreEqual(0, xNode.Objects.Count); - } - - [TestMethod] - public void CanConvertFolderWithValidJsonFolderObjectAndSubFolders() - { - var containerName = "container"; - var folderName = "a/b/c/"; - var payload = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": 0, - ""name"": ""a/b/c/"", - ""content_type"": ""application/octet-stream"" - }, - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": 0, - ""name"": ""a/b/c/BLAH"", - ""content_type"": ""application/octet-stream"" - }, - { - ""subdir"": ""a/b/c/d/"" - }, - { - ""subdir"": ""a/b/c/x/"" - } - ]"; - - var converter = new StorageFolderPayloadConverter(new ServiceLocator()); - var resp = converter.Convert(containerName, folderName, payload); - - Assert.AreEqual("c", resp.Name); - Assert.AreEqual("a/b/c/", resp.FullName); - Assert.AreEqual(1, resp.Objects.Count); - Assert.AreEqual(2, resp.Folders.Count); - - var obj = resp.Objects.First(); - Assert.AreEqual("a/b/c/BLAH", obj.FullName); - - var dNode = resp.Folders.First(f => f.FullName == "a/b/c/d/"); - var xNode = resp.Folders.First(f => f.FullName == "a/b/c/x/"); - - Assert.AreEqual("d", dNode.Name); - Assert.AreEqual(0, dNode.Folders.Count); - Assert.AreEqual(0, dNode.Objects.Count); - - Assert.AreEqual("x", xNode.Name); - Assert.AreEqual(0, xNode.Folders.Count); - Assert.AreEqual(0, xNode.Objects.Count); - } - } -} diff --git a/OpenStack/OpenStack.Test/Storage/StorageFolderTests.cs b/OpenStack/OpenStack.Test/Storage/StorageFolderTests.cs deleted file mode 100644 index 798ef46..0000000 --- a/OpenStack/OpenStack.Test/Storage/StorageFolderTests.cs +++ /dev/null @@ -1,68 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Storage; - -namespace OpenStack.Test.Storage -{ - [TestClass] - public class StorageFolderTests - { - [TestMethod] - public void CanCreateFolder() - { - var folder = new StorageFolder("MyFolder", new List()); - Assert.AreEqual("MyFolder", folder.FullName); - Assert.AreEqual("MyFolder", folder.Name); - Assert.AreEqual(0,folder.Folders.Count()); - } - - [TestMethod] - public void CanCreateFolderWithLeadingSlashes() - { - var expectedFullFolderName = "//MyFolder"; - var expectedFolderName = "MyFolder"; - var folder = new StorageFolder("//MyFolder", new List()); - Assert.AreEqual(expectedFullFolderName, folder.FullName); - Assert.AreEqual(expectedFolderName, folder.Name); - Assert.AreEqual(0, folder.Folders.Count()); - } - - [TestMethod] - public void CanCreateFolderWithTrailingSlashes() - { - var expectedFullFolderName = "MyFolder//"; - var expectedFolderName = "MyFolder"; - var folder = new StorageFolder("MyFolder//", new List()); - Assert.AreEqual(expectedFullFolderName, folder.FullName); - Assert.AreEqual(expectedFolderName, folder.Name); - Assert.AreEqual(0, folder.Folders.Count()); - } - - [TestMethod] - public void CanCreateFolderWithMultipleFoldersInName() - { - var expectedFolderName = "MyFolder"; - var folder = new StorageFolder("//Some/Folder/MyFolder", new List()); - Assert.AreEqual("//Some/Folder/MyFolder", folder.FullName); - Assert.AreEqual(expectedFolderName, folder.Name); - Assert.AreEqual(0, folder.Folders.Count()); - } - } -} diff --git a/OpenStack/OpenStack.Test/Storage/StorageItemTests.cs b/OpenStack/OpenStack.Test/Storage/StorageItemTests.cs deleted file mode 100644 index b07eea9..0000000 --- a/OpenStack/OpenStack.Test/Storage/StorageItemTests.cs +++ /dev/null @@ -1,105 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Storage; - -namespace OpenStack.Test.Storage -{ - [TestClass] - public class StorageItemTests - { - [TestMethod] - public void CanExtractNameWithNoSlashes() - { - var expectedFolderName = "myFolder"; - var folderName = StorageItem.ExtractName("myFolder"); - Assert.AreEqual(expectedFolderName, folderName); - } - - [TestMethod] - public void CanExtractNameWithLeadingSlash() - { - var expectedFolderName = "myFolder"; - var folderName = StorageItem.ExtractName("/myFolder"); - Assert.AreEqual(expectedFolderName, folderName); - } - - [TestMethod] - public void CanExtractNameWithTrailingSlash() - { - var expectedFolderName = "myFolder"; - var folderName = StorageItem.ExtractName("myFolder/"); - Assert.AreEqual(expectedFolderName, folderName); - } - - [TestMethod] - public void CanExtractNameWithTrailingAndLeadingSlash() - { - var expectedFolderName = "myFolder"; - var folderName = StorageItem.ExtractName("/myFolder/"); - Assert.AreEqual(expectedFolderName, folderName); - } - - [TestMethod] - public void CanExtractNameWithJustSlash() - { - var expectedFolderName = string.Empty; - var folderName = StorageItem.ExtractName("/"); - Assert.AreEqual(expectedFolderName, folderName); - } - - [TestMethod] - public void CanExtractNameWithDoubleLeadingSlash() - { - var expectedFolderName = "MyFolder"; - var folderName = StorageItem.ExtractName("//MyFolder"); - Assert.AreEqual(expectedFolderName, folderName); - } - - [TestMethod] - public void CanExtractNameWithDoubleTrailingSlash() - { - var expectedFolderName = "MyFolder"; - var folderName = StorageItem.ExtractName("MyFolder//"); - Assert.AreEqual(expectedFolderName, folderName); - } - - [TestMethod] - public void CanExtractNameWithDoubleTrailingAndLeadingSlashes() - { - var expectedFolderName = "MyFolder"; - var folderName = StorageItem.ExtractName("//MyFolder//"); - Assert.AreEqual(expectedFolderName, folderName); - } - - [TestMethod] - public void CanExtractNameWithMultipleFolders() - { - var expectedFolderName = "MyFolder"; - var folderName = StorageItem.ExtractName("Folder1/Folder2/Folder3/MyFolder"); - Assert.AreEqual(expectedFolderName, folderName); - } - - [TestMethod] - public void CanExtractNameWithMultipleFoldersAndSlashes() - { - var expectedFolderName = "MyFolder"; - var folderName = StorageItem.ExtractName("Folder1//Folder2/Folder3//MyFolder/"); - Assert.AreEqual(expectedFolderName, folderName); - } - } -} diff --git a/OpenStack/OpenStack.Test/Storage/StorageObjectPayloadConverterTests.cs b/OpenStack/OpenStack.Test/Storage/StorageObjectPayloadConverterTests.cs deleted file mode 100644 index 204cb0b..0000000 --- a/OpenStack/OpenStack.Test/Storage/StorageObjectPayloadConverterTests.cs +++ /dev/null @@ -1,834 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Newtonsoft.Json.Linq; -using OpenStack.Common.Http; -using OpenStack.Storage; - -namespace OpenStack.Test.Storage -{ - [TestClass] - public class StorageObjectPayloadConverterTests - { - [TestMethod] - public void CanParseValidJsonPayloadWithMultipleObjects() - { - var validMultipleObjectJson = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": 0, - ""name"": ""BLAH"", - ""content_type"": ""application/octet-stream"" - }, - { - ""hash"": ""97cdd4bb45c3d5d652c0079901fb4eec"", - ""last_modified"": ""2014-03-05T01:10:22.786140"", - ""bytes"": 2147483649, - ""name"": ""LargeFile.bin"", - ""content_type"": ""application/octet-stream"" - } - ]"; - - var converter = new StorageObjectPayloadConverter(); - var objects = converter.Convert("TestContainer", validMultipleObjectJson).ToList(); - - Assert.AreEqual(2,objects.Count()); - var obj1 = - objects.First(o => string.Equals(o.Name, "BLAH", StringComparison.InvariantCultureIgnoreCase)); - var obj2 = - objects.First(o => string.Equals(o.Name, "LargeFile.bin", StringComparison.InvariantCultureIgnoreCase)); - Assert.IsNotNull(obj1); - Assert.IsNotNull(obj2); - - Assert.AreEqual(0,obj1.Length); - Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", obj1.ETag); - Assert.AreEqual("application/octet-stream", obj1.ContentType); - Assert.AreEqual(DateTime.Parse("2014-03-07T21:31:31.588170"), obj1.LastModified); - Assert.AreEqual("BLAH", obj1.Name); - Assert.AreEqual("TestContainer", obj1.ContainerName); - - Assert.AreEqual(2147483649, obj2.Length); - Assert.AreEqual("97cdd4bb45c3d5d652c0079901fb4eec", obj2.ETag); - Assert.AreEqual("application/octet-stream", obj2.ContentType); - Assert.AreEqual(DateTime.Parse("2014-03-05T01:10:22.786140"), obj2.LastModified); - Assert.AreEqual("LargeFile.bin", obj2.Name); - Assert.AreEqual("TestContainer", obj2.ContainerName); - } - - [TestMethod] - public void CanParseValidJsonPayloadWithSingleObject() - { - var validSingleObjectJson = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": 0, - ""name"": ""BLAH"", - ""content_type"": ""application/octet-stream"" - }]"; - - var converter = new StorageObjectPayloadConverter(); - var objects = converter.Convert("TestContainer", validSingleObjectJson).ToList(); - - Assert.AreEqual(1, objects.Count()); - var obj1 = - objects.First(o => string.Equals(o.Name, "BLAH", StringComparison.InvariantCultureIgnoreCase)); - Assert.IsNotNull(obj1); - - Assert.AreEqual(0, obj1.Length); - Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", obj1.ETag); - Assert.AreEqual("application/octet-stream", obj1.ContentType); - Assert.AreEqual(DateTime.Parse("2014-03-07T21:31:31.588170"), obj1.LastModified); - Assert.AreEqual("BLAH", obj1.Name); - Assert.AreEqual("TestContainer", obj1.ContainerName); - } - - [TestMethod] - public void CanParseValidEmptyJsonArrayPayload() - { - var emptyJsonArray = @"[]"; - - var converter = new StorageObjectPayloadConverter(); - var objects = converter.Convert("TestContainer", emptyJsonArray).ToList(); - - Assert.AreEqual(0, objects.Count()); - } - - [TestMethod] - public void CanParseAnEmptyPayload() - { - var payload = string.Empty; - - var converter = new StorageObjectPayloadConverter(); - var objects = converter.Convert("TestContainer", payload).ToList(); - - Assert.AreEqual(0, objects.Count()); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotParseANullPayload() - { - var converter = new StorageObjectPayloadConverter(); - converter.Convert("TestContainer", null); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseInvalidJsonPayload() - { - var converter = new StorageObjectPayloadConverter(); - converter.Convert("TestContainer", "[ { \"SomeAtrib\" }]"); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseInvalidPayload() - { - var converter = new StorageObjectPayloadConverter(); - converter.Convert("TestContainer", "NOT JSON"); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseJsonPayloadWithMissingBytesProperty() - { - string InvalidJsonWithoutBytes = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""name"": ""BLAH"", - ""content_type"": ""application/octet-stream"" - } - ]"; - - var converter = new StorageObjectPayloadConverter(); - converter.Convert("TestContainer", InvalidJsonWithoutBytes); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseJsonPayloadWithMissingHashProperty() - { - string InvalidJsonWithoutHash = @"[ - { - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": 0, - ""name"": ""BLAH"", - ""content_type"": ""application/octet-stream"" - }]"; - - var converter = new StorageObjectPayloadConverter(); - converter.Convert("TestContainer", InvalidJsonWithoutHash); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseJsonPayloadWithMissingModifiedProperty() - { - string InvalidJsonWithoutLastModified = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""bytes"": 0, - ""name"": ""BLAH"", - ""content_type"": ""application/octet-stream"" - }]"; - - var converter = new StorageObjectPayloadConverter(); - converter.Convert("TestContainer", InvalidJsonWithoutLastModified); - } - - [TestMethod] - public void CannotParseJsonPayloadWithMissingNameProperty() - { - string InvalidJsonWithoutName = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": 0, - ""content_type"": ""application/octet-stream"" - }]"; - - var converter = new StorageObjectPayloadConverter(); - - try - { - converter.Convert("TestContainer", InvalidJsonWithoutName); - Assert.Fail("Parsing did not fail as expected."); - } - catch (FormatException ex) - { - Assert.IsTrue(ex.Message.StartsWith("Storage Object payload could not be parsed.")); - } - } - - [TestMethod] - public void ParseExceptionIncludesNameWhenPossible() - { - string InvalidJsonWithoutHash = @"[ - { - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": 0, - ""name"": ""BLAH"", - ""content_type"": ""application/octet-stream"" - }]"; - - var converter = new StorageObjectPayloadConverter(); - try - { - converter.Convert("TestContainer", InvalidJsonWithoutHash); - Assert.Fail("Parsing did not fail as expected."); - } - catch (FormatException ex) - { - Assert.IsTrue(ex.Message.StartsWith("Storage Object 'BLAH'")); - } - - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseJsonPayloadWithMissingContentTypeProperty() - { - string InvalidJsonWithoutContentType = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": 0, - ""name"": ""BLAH"" - }]"; - - var converter = new StorageObjectPayloadConverter(); - converter.Convert("TestContainer", InvalidJsonWithoutContentType); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseJsonPayloadWithBadModifiedDate() - { - string InvalidJsonWithBadDateType = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""This is not a date"", - ""bytes"": 0, - ""name"": ""BLAH"", - ""content_type"": ""application/octet-stream"" - }]"; - - var converter = new StorageObjectPayloadConverter(); - converter.Convert("TestContainer", InvalidJsonWithBadDateType); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseJsonPayloadWithBadBytesValue() - { - string InvalidJsonWithBadBytesValue = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": ""This is not a number"", - ""name"": ""BLAH"", - ""content_type"": ""application/octet-stream"" - }]"; - - var converter = new StorageObjectPayloadConverter(); - converter.Convert("TestContainer", InvalidJsonWithBadBytesValue); - } - - [TestMethod] - public void CanParseObjectFromHeaders() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"ETag", "d41d8cd98f00b204e9800998ecf8427e"} - }; - - var converter = new StorageObjectPayloadConverter(); - var obj = converter.Convert(containerName, objectName, headers); - - Assert.IsNotNull(obj); - Assert.IsInstanceOfType(obj, typeof(StorageObject)); - Assert.AreEqual(1234, obj.Length); - Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", obj.ETag); - Assert.AreEqual("application/octet-stream", obj.ContentType); - Assert.AreEqual(DateTime.Parse("Wed, 12 Mar 2014 23:42:23 GMT"), obj.LastModified); - Assert.AreEqual(objectName, obj.Name); - Assert.AreEqual(containerName, obj.ContainerName); - } - - [TestMethod] - public void CanParseObjectFromHeadersAndSpecificObjectLength() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"ETag", "d41d8cd98f00b204e9800998ecf8427e"} - }; - - var converter = new StorageObjectPayloadConverter(); - var obj = converter.Convert(containerName, objectName, headers, 100); - - Assert.IsNotNull(obj); - Assert.IsInstanceOfType(obj, typeof(StorageObject)); - Assert.AreEqual(100, obj.Length); - Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", obj.ETag); - Assert.AreEqual("application/octet-stream", obj.ContentType); - Assert.AreEqual(DateTime.Parse("Wed, 12 Mar 2014 23:42:23 GMT"), obj.LastModified); - Assert.AreEqual(objectName, obj.Name); - Assert.AreEqual(containerName, obj.ContainerName); - } - - [TestMethod] - public void CanParseObjectFromHeadersWithMetadata() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"ETag", "d41d8cd98f00b204e9800998ecf8427e"}, - {"X-Object-Meta-Test1","Test1"} - }; - - var converter = new StorageObjectPayloadConverter(); - var obj = converter.Convert(containerName, objectName, headers); - - Assert.IsNotNull(obj); - Assert.IsInstanceOfType(obj, typeof(StorageObject)); - Assert.AreEqual(1234, obj.Length); - Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", obj.ETag); - Assert.AreEqual("application/octet-stream", obj.ContentType); - Assert.AreEqual(DateTime.Parse("Wed, 12 Mar 2014 23:42:23 GMT"), obj.LastModified); - Assert.AreEqual(objectName, obj.Name); - Assert.AreEqual(containerName, obj.ContainerName); - Assert.AreEqual(1, obj.Metadata.Count()); - Assert.IsTrue(obj.Metadata.ContainsKey("Test1")); - Assert.AreEqual("Test1", obj.Metadata["Test1"]); - } - - [TestMethod] - public void CanParseStaticManifestFromHeadersWithMetadata() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"ETag", "d41d8cd98f00b204e9800998ecf8427e"}, - {"X-Object-Meta-Test1","Test1"}, - {"X-Static-Large-Object","True"} - }; - - var converter = new StorageObjectPayloadConverter(); - var obj = converter.Convert(containerName, objectName, headers); - - Assert.IsNotNull(obj); - Assert.IsInstanceOfType(obj, typeof(StaticLargeObjectManifest)); - Assert.AreEqual(1234, obj.Length); - Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", obj.ETag); - Assert.AreEqual("application/octet-stream", obj.ContentType); - Assert.AreEqual(DateTime.Parse("Wed, 12 Mar 2014 23:42:23 GMT"), obj.LastModified); - Assert.AreEqual(objectName, obj.Name); - Assert.AreEqual(containerName, obj.ContainerName); - Assert.AreEqual(1, obj.Metadata.Count()); - Assert.IsTrue(obj.Metadata.ContainsKey("Test1")); - Assert.AreEqual("Test1", obj.Metadata["Test1"]); - } - - [TestMethod] - public void CanParseObjectFromHeadersWithStaticManifestFlagSetToNonTrue() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"ETag", "d41d8cd98f00b204e9800998ecf8427e"}, - {"X-Object-Meta-Test1","Test1"}, - {"X-Static-Large-Object","False"} - }; - - var converter = new StorageObjectPayloadConverter(); - var obj = converter.Convert(containerName, objectName, headers); - - Assert.IsNotNull(obj); - Assert.IsInstanceOfType(obj, typeof(StorageObject)); - Assert.AreEqual(1234, obj.Length); - Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", obj.ETag); - Assert.AreEqual("application/octet-stream", obj.ContentType); - Assert.AreEqual(DateTime.Parse("Wed, 12 Mar 2014 23:42:23 GMT"), obj.LastModified); - Assert.AreEqual(objectName, obj.Name); - Assert.AreEqual(containerName, obj.ContainerName); - Assert.AreEqual(1, obj.Metadata.Count()); - Assert.IsTrue(obj.Metadata.ContainsKey("Test1")); - Assert.AreEqual("Test1", obj.Metadata["Test1"]); - } - - [TestMethod] - public void CanParseObjectFromHeadersWithStaticManifestFlagSetToNull() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"ETag", "d41d8cd98f00b204e9800998ecf8427e"}, - {"X-Object-Meta-Test1","Test1"}, - {"X-Static-Large-Object", (string)null} - }; - - var converter = new StorageObjectPayloadConverter(); - var obj = converter.Convert(containerName, objectName, headers); - - Assert.IsNotNull(obj); - Assert.IsInstanceOfType(obj, typeof(StorageObject)); - Assert.AreEqual(1234, obj.Length); - Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", obj.ETag); - Assert.AreEqual("application/octet-stream", obj.ContentType); - Assert.AreEqual(DateTime.Parse("Wed, 12 Mar 2014 23:42:23 GMT"), obj.LastModified); - Assert.AreEqual(objectName, obj.Name); - Assert.AreEqual(containerName, obj.ContainerName); - Assert.AreEqual(1, obj.Metadata.Count()); - Assert.IsTrue(obj.Metadata.ContainsKey("Test1")); - Assert.AreEqual("Test1", obj.Metadata["Test1"]); - } - - [TestMethod] - public void CanParseObjectFromHeadersWithDynamicFlagSetToNull() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"ETag", "d41d8cd98f00b204e9800998ecf8427e"}, - {"X-Object-Meta-Test1","Test1"}, - {"X-Object-Manifest", (string)null} - }; - - var converter = new StorageObjectPayloadConverter(); - var obj = converter.Convert(containerName, objectName, headers); - - Assert.IsNotNull(obj); - Assert.IsInstanceOfType(obj, typeof(StorageObject)); - Assert.AreEqual(1234, obj.Length); - Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", obj.ETag); - Assert.AreEqual("application/octet-stream", obj.ContentType); - Assert.AreEqual(DateTime.Parse("Wed, 12 Mar 2014 23:42:23 GMT"), obj.LastModified); - Assert.AreEqual(objectName, obj.Name); - Assert.AreEqual(containerName, obj.ContainerName); - Assert.AreEqual(1, obj.Metadata.Count()); - Assert.IsTrue(obj.Metadata.ContainsKey("Test1")); - Assert.AreEqual("Test1", obj.Metadata["Test1"]); - } - - [TestMethod] - public void CanParseObjectFromHeadersWithDynamicFlagSetToEmpty() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"ETag", "d41d8cd98f00b204e9800998ecf8427e"}, - {"X-Object-Meta-Test1","Test1"}, - {"X-Object-Manifest", string.Empty} - }; - - var converter = new StorageObjectPayloadConverter(); - var obj = converter.Convert(containerName, objectName, headers); - - Assert.IsNotNull(obj); - Assert.IsInstanceOfType(obj, typeof(StorageObject)); - Assert.AreEqual(1234, obj.Length); - Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", obj.ETag); - Assert.AreEqual("application/octet-stream", obj.ContentType); - Assert.AreEqual(DateTime.Parse("Wed, 12 Mar 2014 23:42:23 GMT"), obj.LastModified); - Assert.AreEqual(objectName, obj.Name); - Assert.AreEqual(containerName, obj.ContainerName); - Assert.AreEqual(1, obj.Metadata.Count()); - Assert.IsTrue(obj.Metadata.ContainsKey("Test1")); - Assert.AreEqual("Test1", obj.Metadata["Test1"]); - } - - [TestMethod] - public void CanParseDynamicManifestFromHeadersWithMetadata() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"ETag", "d41d8cd98f00b204e9800998ecf8427e"}, - {"X-Object-Meta-Test1","Test1"}, - {"X-Object-Manifest","a/b"} - }; - - var converter = new StorageObjectPayloadConverter(); - var obj = converter.Convert(containerName, objectName, headers); - - Assert.IsNotNull(obj); - Assert.IsInstanceOfType(obj, typeof(DynamicLargeObjectManifest)); - Assert.AreEqual(1234, obj.Length); - Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", obj.ETag); - Assert.AreEqual("application/octet-stream", obj.ContentType); - Assert.AreEqual(DateTime.Parse("Wed, 12 Mar 2014 23:42:23 GMT"), obj.LastModified); - Assert.AreEqual(objectName, obj.Name); - Assert.AreEqual(containerName, obj.ContainerName); - Assert.AreEqual(1, obj.Metadata.Count()); - Assert.IsTrue(obj.Metadata.ContainsKey("Test1")); - Assert.AreEqual("Test1", obj.Metadata["Test1"]); - - var manifest = obj as DynamicLargeObjectManifest; - Assert.AreEqual("a/b", manifest.SegmentsPath); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotParseWithANullObjectName() - { - var containerName = "TestContainer"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"Etag", "d41d8cd98f00b204e9800998ecf8427e"} - }; - - var converter = new StorageObjectPayloadConverter(); - converter.Convert(containerName, null, headers); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public void CannotParseWithAnEmptyConatinerName() - { - var containerName = string.Empty; - var objectName = "TestObject"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"Etag", "d41d8cd98f00b204e9800998ecf8427e"} - }; - - var converter = new StorageObjectPayloadConverter(); - converter.Convert(containerName, objectName, headers); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotParseWithNullHeaders() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var converter = new StorageObjectPayloadConverter(); - converter.Convert(containerName, objectName, null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public void CannotParseWithAnEmptyObjectName() - { - var containerName = "TestContainer"; - var objectName =string.Empty; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"Etag", "d41d8cd98f00b204e9800998ecf8427e"} - }; - - var converter = new StorageObjectPayloadConverter(); - converter.Convert(containerName, objectName, headers); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotParseWithNullConatinerName() - { - var objectName = "TestObject"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"Etag", "d41d8cd98f00b204e9800998ecf8427e"} - }; - - var converter = new StorageObjectPayloadConverter(); - converter.Convert(null, objectName, headers); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseWithMissingContentLengthHeader() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"Etag", "d41d8cd98f00b204e9800998ecf8427e"} - }; - - var converter = new StorageObjectPayloadConverter(); - converter.Convert(containerName, objectName, headers); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseWithMissingETagHeader() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"} - }; - - var converter = new StorageObjectPayloadConverter(); - converter.Convert(containerName, objectName, headers); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseWithMissingModifiedHeader() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Etag", "d41d8cd98f00b204e9800998ecf8427e"} - }; - - var converter = new StorageObjectPayloadConverter(); - converter.Convert(containerName, objectName, headers); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseWithMissingContentTypeHeader() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"Etag", "d41d8cd98f00b204e9800998ecf8427e"} - }; - - var converter = new StorageObjectPayloadConverter(); - converter.Convert(containerName, objectName, headers); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseWithBadModifiedDateHeader() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "This is not a date"}, - {"Etag", "d41d8cd98f00b204e9800998ecf8427e"} - }; - - var converter = new StorageObjectPayloadConverter(); - converter.Convert(containerName, objectName, headers); - } - - [TestMethod] - [ExpectedException(typeof(FormatException))] - public void CannotParseWithBadBytesHeader() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "This is not a number"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"Etag", "d41d8cd98f00b204e9800998ecf8427e"} - }; - - var converter = new StorageObjectPayloadConverter(); - converter.Convert(containerName, objectName, headers); - } - - [TestMethod] - public void CanConvertSingleStorageObjectToJson() - { - var obj = new StorageObject("a/b/c", "TestContainer", DateTime.UtcNow, "12345", 54321, string.Empty, - new Dictionary()); - - var converter = new StorageObjectPayloadConverter(); - var payload = converter.Convert(new List() { obj}); - - var result = JArray.Parse(payload); - Assert.AreEqual(1,result.Count); - - var item = result[0]; - Assert.AreEqual("TestContainer/a/b/c", item["path"]); - Assert.AreEqual(54321, item["size_bytes"]); - Assert.AreEqual("12345", item["etag"]); - } - - [TestMethod] - public void CanConvertMultipleStorageObjectToJson() - { - var obj = new StorageObject("a/b/c", "TestContainer", DateTime.UtcNow, "12345", 54321, string.Empty, - new Dictionary()); - - var obj2 = new StorageObject("a/b/d", "TestContainer", DateTime.UtcNow, "00000", 11111, string.Empty, - new Dictionary()); - - var converter = new StorageObjectPayloadConverter(); - var payload = converter.Convert(new List() { obj, obj2 }); - - var result = JArray.Parse(payload); - Assert.AreEqual(2, result.Count); - - var item = result[0]; - Assert.AreEqual("TestContainer/a/b/c", item["path"]); - Assert.AreEqual(54321, item["size_bytes"]); - Assert.AreEqual("12345", item["etag"]); - - var item2 = result[1]; - Assert.AreEqual("TestContainer/a/b/d", item2["path"]); - Assert.AreEqual(11111, item2["size_bytes"]); - Assert.AreEqual("00000", item2["etag"]); - } - - [TestMethod] - public void CanConvertEmptyStorageObjectsToJson() - { - var converter = new StorageObjectPayloadConverter(); - var payload = converter.Convert(new List()); - var result = JArray.Parse(payload); - Assert.AreEqual(0, result.Count); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public void CannotConvertNullStorageObjectsToJson() - { - var converter = new StorageObjectPayloadConverter(); - converter.Convert(null); - } - } -} diff --git a/OpenStack/OpenStack.Test/Storage/StorageRestSimulator.cs b/OpenStack/OpenStack.Test/Storage/StorageRestSimulator.cs deleted file mode 100644 index e461cc8..0000000 --- a/OpenStack/OpenStack.Test/Storage/StorageRestSimulator.cs +++ /dev/null @@ -1,484 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Security.Cryptography; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using OpenStack.Common.Http; - -namespace OpenStack.Test.Storage -{ - public class StorageRestSimulator : RestSimulator - { - internal class StorageItem - { - public string Name { get; set; } - - public IDictionary MetaData { get; set; } - - public Stream Content { get; set; } - - public StorageItem() - { - this.MetaData = new Dictionary(); - } - - public StorageItem(string name) : this() - { - this.Name = name; - } - - public void ProcessMetaDataFromHeaders(IDictionary headers) - { - headers.Keys.Where(k => k.ToLowerInvariant().StartsWith("x-object-meta-")).ToList().ForEach(i => this.MetaData.Add(i, headers[i])); - headers.Keys.Where(k => k.ToLowerInvariant().StartsWith("x-container-meta-")).ToList().ForEach(i => this.MetaData.Add(i, headers[i])); - } - - public void LoadContent(Stream content) - { - var memStream = new MemoryStream(); - if (content != null) - { - content.CopyTo(memStream); - memStream.Position = 0; - } - this.Content = memStream; - } - } - - public StorageRestSimulator() : base() - { - this.Containers = new Dictionary(); - this.Objects = new Dictionary(); - this.IsContainerEmpty = true; - } - - public StorageRestSimulator(CancellationToken token) : this() - { - } - - internal Dictionary Containers { get; set; } - - internal Dictionary Objects { get; set; } - - public bool IsContainerEmpty { get; set; } - - //public event EventHandler HttpReceiveProgress; - //public event EventHandler HttpSendProgress; - - protected override IHttpResponseAbstraction HandleCopy() - { - var containerName = GetContainerName(this.Uri.Segments); - var objectName = GetObjectName(this.Uri.Segments); - - if (containerName == null && objectName == null) - { - return TestHelper.CreateErrorResponse(); - } - - //cannot copy a container - if (objectName == null) - { - return TestHelper.CreateResponse(HttpStatusCode.MethodNotAllowed); - } - - if (!this.Containers.ContainsKey(containerName)) - { - return TestHelper.CreateResponse(HttpStatusCode.NotFound); - } - - if (!this.Headers.ContainsKey("Destination")) - { - return TestHelper.CreateResponse(HttpStatusCode.PreconditionFailed); - } - - if (!this.Objects.ContainsKey(objectName)) - { - return TestHelper.CreateResponse(HttpStatusCode.NotFound); - } - - var destination = this.Headers["Destination"]; - var destinationSegs = destination.Split('/'); - if (destinationSegs.Count() < 2) - { - return TestHelper.CreateResponse(HttpStatusCode.PreconditionFailed); - } - - if (destinationSegs[1] == string.Empty) - { - return TestHelper.CreateResponse(HttpStatusCode.MethodNotAllowed); - } - - if (!this.Containers.ContainsKey(destinationSegs[0])) - { - return TestHelper.CreateResponse(HttpStatusCode.NotFound); - } - - var destObjectName = string.Join("", destinationSegs.Skip(1)); - var srcObj = this.Objects[objectName]; - - var obj = new StorageItem(destObjectName); - obj.MetaData = srcObj.MetaData; - obj.ProcessMetaDataFromHeaders(this.Headers); - var content = new MemoryStream(); - srcObj.Content.CopyTo(content); - srcObj.Content.Position = 0; - content.Position = 0; - obj.Content = content; - - this.Objects[obj.Name] = obj; - - var headers = GenerateObjectResponseHeaders(obj); - - return TestHelper.CreateResponse(HttpStatusCode.Created, headers); - - } - - protected override IHttpResponseAbstraction HandleHead() - { - var containerName = GetContainerName(this.Uri.Segments); - var objectName = GetObjectName(this.Uri.Segments); - - if (containerName == null && objectName == null) - { - return TestHelper.CreateErrorResponse(); - } - - var headers = new Dictionary(); - - if (objectName != null) - { - if (!this.Objects.ContainsKey(objectName)) - { - return TestHelper.CreateResponse(HttpStatusCode.NotFound); - } - headers = GenerateObjectResponseHeaders(this.Objects[objectName]); - } - else - { - if (!this.Containers.ContainsKey(containerName)) - { - return TestHelper.CreateResponse(HttpStatusCode.NotFound); - } - headers = GenerateContainerResponseHeaders(this.Containers[containerName]); - } - - return TestHelper.CreateResponse(HttpStatusCode.NoContent, headers); - } - - protected override IHttpResponseAbstraction HandleDelete() - { - var containerName = GetContainerName(this.Uri.Segments); - var objectName = GetObjectName(this.Uri.Segments); - - if (containerName == null && objectName == null) - { - return TestHelper.CreateErrorResponse(); - } - - if (objectName != null) - { - if (!this.Objects.ContainsKey(objectName)) - { - return TestHelper.CreateResponse(HttpStatusCode.NotFound); - } - - this.Objects.Remove(objectName); - - return TestHelper.CreateResponse(HttpStatusCode.NoContent, GenerateDeleteHeaders()); - } - - if (!this.Containers.ContainsKey(containerName)) - { - return TestHelper.CreateResponse(HttpStatusCode.NotFound); - } - - var statusCode = HttpStatusCode.NoContent; - - if (!this.IsContainerEmpty) - { - statusCode = HttpStatusCode.Conflict; - } - else - { - this.Containers.Remove(containerName); - } - - return TestHelper.CreateResponse(statusCode, GenerateDeleteHeaders()); - } - - protected override IHttpResponseAbstraction HandlePut() - { - var containerName = GetContainerName(this.Uri.Segments); - var objectName = GetObjectName(this.Uri.Segments); - - if (containerName == null && objectName == null) - { - return TestHelper.CreateErrorResponse(); - } - - if (objectName != null) - { - var obj = new StorageItem(objectName); - obj.ProcessMetaDataFromHeaders(this.Headers); - obj.LoadContent(this.Content); - this.Objects[obj.Name] = obj; - - var headers = GenerateObjectResponseHeaders(obj); - - return TestHelper.CreateResponse(HttpStatusCode.Created, headers); - } - else - { - var container = new StorageItem(containerName); - container.ProcessMetaDataFromHeaders(this.Headers); - - var containerUpdated = this.Containers.Keys.Any(k => String.Equals(k, container.Name, StringComparison.InvariantCultureIgnoreCase)); - - this.Containers[container.Name] = container; - - return TestHelper.CreateResponse(containerUpdated ? HttpStatusCode.Accepted : HttpStatusCode.Created); - } - } - - protected override IHttpResponseAbstraction HandlePost() - { - var containerName = GetContainerName(this.Uri.Segments); - var objectName = GetObjectName(this.Uri.Segments); - - if (containerName == null && objectName == null) - { - return TestHelper.CreateErrorResponse(); - } - - StorageItem storageItem; - - if (objectName != null) - { - if (!this.Objects.ContainsKey(objectName)) - { - return TestHelper.CreateResponse(HttpStatusCode.NotFound); - } - - storageItem = this.Objects[objectName]; - } - else - { - if (!this.Containers.ContainsKey(containerName)) - { - return TestHelper.CreateResponse(HttpStatusCode.NotFound); - } - - storageItem = this.Containers[containerName]; - } - - storageItem.MetaData.Clear(); - storageItem.ProcessMetaDataFromHeaders(this.Headers); - - return TestHelper.CreateResponse(HttpStatusCode.Accepted); - } - - protected override IHttpResponseAbstraction HandleGet() - { - var containerName = GetContainerName(this.Uri.Segments); - var objectName = GetObjectName(this.Uri.Segments); - var accountName = GetAccountName(this.Uri.Segments); - - if (containerName == null && objectName == null) - { - if (accountName == null) - { - return TestHelper.CreateErrorResponse(); - } - - var accountHeaders = GenerateAccountResponseHeaders(); - var accountContent = TestHelper.CreateStream(GenerateAccountPayload()); - - return TestHelper.CreateResponse(HttpStatusCode.OK, accountHeaders, accountContent); - - } - - if (objectName != null) - { - return this.GetObject(objectName); - } - - var query = this.Uri.ParseQueryString(); - if (query.HasKeys() && query["prefix"] != null && query["delimiter"] != null) - { - return this.GetObject(query["prefix"]); - } - - if (!this.Containers.ContainsKey(containerName)) - { - return TestHelper.CreateResponse(HttpStatusCode.NotFound); - } - - var container = this.Containers[containerName]; - var headers = GenerateContainerResponseHeaders(container); - var content = TestHelper.CreateStream("[]"); - - return TestHelper.CreateResponse(HttpStatusCode.OK, headers, content); - } - - public IHttpResponseAbstraction GetObject(string objectName) - { - if (!this.Objects.ContainsKey(objectName)) - { - return TestHelper.CreateResponse(HttpStatusCode.NotFound); - } - - var obj = this.Objects[objectName]; - var objectHeaders = GenerateObjectResponseHeaders(obj); - - return TestHelper.CreateResponse(HttpStatusCode.OK, objectHeaders, obj.Content); - } - - public string GetContainerName(string[] uriSegments) - { - return uriSegments.Count() < 4 ? null : uriSegments[3].TrimEnd('/'); - } - - public string GetAccountName(string[] uriSegments) - { - return uriSegments.Count() < 3 ? null : uriSegments[2].TrimEnd('/'); - } - - public string GetObjectName(string[] uriSegments) - { - if (uriSegments.Count() < 5) - { - return null; - } - return string.Join("", uriSegments.Skip(4)); - } - - private string GenerateAccountPayload() - { - var payload = new StringBuilder(); - payload.Append("["); - var first = true; - foreach (var container in this.Containers) - { - if (!first) - { - payload.Append(","); - first = false; - } - - payload.Append("{"); - payload.Append("\"count\": 42,"); - payload.Append("\"bytes\": 12345,"); - payload.Append(string.Format("\"name\": \"{0}\"",container.Value.Name)); - payload.Append("}"); - } - payload.Append("]"); - return payload.ToString(); - } - - private IEnumerable> GenerateAccountResponseHeaders() - { - return new Dictionary() - { - {"X-Account-Bytes-Used", "12345"}, - {"X-Account-Container-Count", this.Containers.Count.ToString()}, - {"X-Account-Object-Count", this.Objects.Count.ToString()}, - {"Content-Type", this.ContentType}, - {"X-Trans-Id", "12345"}, - {"Date", DateTime.UtcNow.ToShortTimeString()}, - {"X-Timestamp", "1234567890.98765"} - }; - } - - internal Dictionary GenerateObjectResponseHeaders(StorageItem obj) - { - var etag = Convert.ToBase64String(MD5.Create().ComputeHash(obj.Content)); - obj.Content.Position = 0; - - return new Dictionary(obj.MetaData) - { - {"ETag", etag}, - {"Content-Type", this.ContentType}, - {"X-Trans-Id", "12345"}, - {"Date", DateTime.UtcNow.ToShortTimeString()}, - {"X-Timestamp", "1234567890.98765"} - }; - } - - internal Dictionary GenerateContainerResponseHeaders(StorageItem obj) - { - return new Dictionary(obj.MetaData) - { - {"X-Container-Bytes-Used", "0"}, - {"Content-Type", this.ContentType}, - {"X-Container-Object-Count", "0"}, - {"Date", DateTime.UtcNow.ToShortTimeString()}, - {"X-Container-Read", ".r.*,.rlistings"}, - {"X-Trans-Id", "12345"}, - {"X-Timestamp", "1234567890.98765"} - }; - } - - internal Dictionary GenerateDeleteHeaders() - { - return new Dictionary() - { - {"X-Trans-Id", "12345"}, - {"Date", DateTime.UtcNow.ToShortTimeString()} - }; - } - } - - public class StorageRestSimulatorFactory : IHttpAbstractionClientFactory - { - internal StorageRestSimulator Simulator = null; - public StorageRestSimulatorFactory(StorageRestSimulator simulator) - { - this.Simulator = simulator; - } - - public IHttpAbstractionClient Create() - { - throw new NotImplementedException(); - } - - public IHttpAbstractionClient Create(CancellationToken token) - { - if (this.Simulator != null) - { - this.Simulator.Headers.Clear(); - } - return this.Simulator ?? new StorageRestSimulator(token); - } - - public IHttpAbstractionClient Create(TimeSpan timeout) - { - throw new NotImplementedException(); - } - - public IHttpAbstractionClient Create(TimeSpan timeout, CancellationToken token) - { - throw new NotImplementedException(); - } - } -} diff --git a/OpenStack/OpenStack.Test/Storage/StorageServiceClientDefinitionTests.cs b/OpenStack/OpenStack.Test/Storage/StorageServiceClientDefinitionTests.cs deleted file mode 100644 index d0142bc..0000000 --- a/OpenStack/OpenStack.Test/Storage/StorageServiceClientDefinitionTests.cs +++ /dev/null @@ -1,89 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Common; -using OpenStack.Identity; -using OpenStack.Storage; - -namespace OpenStack.Test.Storage -{ - [TestClass] - public class StorageServiceClientDefinitionTests - { - IOpenStackCredential GetValidCreds() - { - var authId = "12345"; - var endpoint = "http://teststorageendpoint.com/v1/1234567890"; - - var creds = new OpenStackCredential(new Uri(endpoint), "SomeUser", "Password", "SomeTenant"); - creds.SetAccessTokenId(authId); - return creds; - } - - [TestMethod] - public void CanSupportVersion1() - { - var client = new StorageServiceClientDefinition(); - var creds = GetValidCreds(); - var catalog = - new OpenStackServiceCatalog - { - new OpenStackServiceDefinition("Swift", "Test", - new List() - { - new OpenStackServiceEndpoint("http://someplace.com", "somewhere", "1.0", - "http://www.someplace.com", "http://www.someplace.com") - }) - }; - creds.SetServiceCatalog(catalog); - Assert.IsTrue(client.IsSupported(creds, "Swift")); - } - - [TestMethod] - public void CannotSupportVersion2() - { - var client = new StorageServiceClientDefinition(); - var creds = GetValidCreds(); - var catalog = - new OpenStackServiceCatalog - { - new OpenStackServiceDefinition("Swift", "Test", - new List() - { - new OpenStackServiceEndpoint("http://someplace.com", "somewhere", "2.0.0.0", - "http://www.someplace.com", "http://www.someplace.com") - }) - }; - creds.SetServiceCatalog(catalog); - Assert.IsFalse(client.IsSupported(creds, "Swift")); - } - - [TestMethod] - public void CannotSupportUnknownServiceName() - { - var client = new StorageServiceClientDefinition(); - var creds = GetValidCreds(); - var catalog = - new OpenStackServiceCatalog - { - new OpenStackServiceDefinition("Swift", "Test", - new List() - { - new OpenStackServiceEndpoint("http://someplace.com", "somewhere", "1.0", - "http://www.someplace.com", "http://www.someplace.com") - }) - }; - creds.SetServiceCatalog(catalog); - Assert.IsFalse(client.IsSupported(creds, "BadServiceName")); - } - - [TestMethod] - public void Version1Supported() - { - var client = new StorageServiceClientDefinition(); - Assert.IsTrue(client.ListSupportedVersions().Contains("1.0")); - Assert.IsTrue(client.ListSupportedVersions().Contains("1")); - } - } -} diff --git a/OpenStack/OpenStack.Test/Storage/StorageServiceClientTests.cs b/OpenStack/OpenStack.Test/Storage/StorageServiceClientTests.cs deleted file mode 100644 index 271e946..0000000 --- a/OpenStack/OpenStack.Test/Storage/StorageServiceClientTests.cs +++ /dev/null @@ -1,1416 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Common; -using OpenStack.Common.ServiceLocation; -using OpenStack.Identity; -using OpenStack.Storage; - -namespace OpenStack.Test.Storage -{ - [TestClass] - public class StorageServiceClientTests - { - internal TestStorageServicePocoClient ServicePocoClient; - internal TestLargeStorageObjectCreator loCreator; - - internal string authId = "12345"; - internal string endpoint = "http://teststorageendpoint.com/v1/1234567890"; - internal ServiceLocator ServiceLocator; - - [TestInitialize] - public void TestSetup() - { - this.ServicePocoClient = new TestStorageServicePocoClient(); - this.loCreator = new TestLargeStorageObjectCreator(); - this.ServiceLocator = new ServiceLocator(); - - var manager = this.ServiceLocator.Locate(); - manager.RegisterServiceInstance(typeof(IStorageServicePocoClientFactory), new TestStorageServicePocoClientFactory(this.ServicePocoClient)); - manager.RegisterServiceInstance(typeof(ILargeStorageObjectCreatorFactory), new TestLargeStorageObjectCreatorFactory(this.loCreator)); - } - - [TestCleanup] - public void TestCleanup() - { - this.ServicePocoClient = new TestStorageServicePocoClient(); - this.loCreator = new TestLargeStorageObjectCreator(); - this.ServiceLocator = new ServiceLocator(); - } - - IOpenStackCredential GetValidCreds() - { - var catalog = new OpenStackServiceCatalog(); - catalog.Add(new OpenStackServiceDefinition("Swift", "Storage Service", - new List() - { - new OpenStackServiceEndpoint(endpoint, string.Empty, "some version", "some version info", "1,2,3") - })); - - var creds = new OpenStackCredential(new Uri(this.endpoint), "SomeUser", "Password", "SomeTenant"); - creds.SetAccessTokenId(this.authId); - creds.SetServiceCatalog(catalog); - return creds; - } - - [TestMethod] - public async Task CanListStorageObjects() - { - var containerName = "TestContainer"; - var numberObjCalls = 0; - var obj = new StorageObject("TestObj", containerName, DateTime.UtcNow, "12345", 12345, - "application/octet-stream", new Dictionary()); - - var container = new StorageContainer(containerName, 100, 1, new Dictionary(), - new List() {obj}); - this.ServicePocoClient.GetStorageContainerDelegate = s => - { - Assert.AreEqual(container.Name, s); - return Task.Factory.StartNew(() => container); - }; - this.ServicePocoClient.GetStorageObjectDelegate = (s, s1) => - { - numberObjCalls++; - Assert.AreEqual(s, obj.ContainerName); - Assert.AreEqual(s1, obj.Name); - return Task.Factory.StartNew(() => obj); - }; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.ListStorageObjects(containerName); - - Assert.AreEqual(1,numberObjCalls); - } - - [TestMethod] - public async Task CanListStorageObjectsWith404() - { - var containerName = "TestContainer"; - var obj = new StorageObject("TestObj", containerName, DateTime.UtcNow, "12345", 12345, - "application/octet-stream", new Dictionary()); - - var container = new StorageContainer(containerName, 100, 1, new Dictionary(), - new List() { obj }); - this.ServicePocoClient.GetStorageContainerDelegate = s => - { - Assert.AreEqual(container.Name, s); - return Task.Factory.StartNew(() => container); - }; - this.ServicePocoClient.GetStorageObjectDelegate = (s, s1) => - { - throw new InvalidOperationException("Cannot get storage object. '" +HttpStatusCode.NotFound +"'"); - }; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - var resp = await client.ListStorageObjects(containerName); - - Assert.AreEqual(0, resp.Count()); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task ListingStorageObjectsWithNullContainerNameThrows() - { - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.ListStorageObjects(null); - } - - [TestMethod] - public async Task CanListStorageContainers() - { - var containerName = "TestContainer"; - var numberContainerCalls = 0; - - var container = new StorageContainer(containerName, 100, 1, new Dictionary(), - new List()); - - var account = new StorageAccount("1234567890", 100, 1, 1, new List() { container }); - - this.ServicePocoClient.GetStorageContainerDelegate = s => - { - numberContainerCalls++; - Assert.AreEqual(container.Name, s); - return Task.Factory.StartNew(() => container); - }; - - this.ServicePocoClient.GetStorageAccountDelegate = () => Task.Factory.StartNew(() => account); - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - var resp = await client.ListStorageContainers(); - var containers = resp.ToList(); - - Assert.AreEqual(1, containers.Count); - Assert.AreEqual(1, numberContainerCalls); - } - - [TestMethod] - public async Task CanGetStorageAccount() - { - var account = new StorageAccount("1234567890", 100, 10, 1, new List()); - - this.ServicePocoClient.GetStorageAccountDelegate = () => - { - Assert.AreEqual("1234567890", account.Name); - return Task.Factory.StartNew(() => account); - }; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - var resp = await client.GetStorageAccount(); - - Assert.AreEqual(account, resp); - } - - [TestMethod] - public async Task CanGetStorageObjects() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var obj = new StorageObject(objectName, containerName, DateTime.UtcNow, "12345", 12345, - "application/octet-stream", new Dictionary()); - - this.ServicePocoClient.GetStorageObjectDelegate = (s, s1) => - { - Assert.AreEqual(s, obj.ContainerName); - Assert.AreEqual(s1, obj.Name); - return Task.Factory.StartNew(() => obj); - }; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - var resp = await client.GetStorageObject(containerName, objectName); - - Assert.AreEqual(obj, resp); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task GettingStorageObjectsWithNullContainerNameThrows() - { - var objectName = "TestObject"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.GetStorageObject(null, objectName); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task GettingStorageObjectsWithEmptyContainerNameThrows() - { - var objectName = "TestObject"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.GetStorageObject(string.Empty, objectName); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task GettingStorageObjectsWithNullObjectNameThrows() - { - var containerName = "TestContainer"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.GetStorageObject(containerName, null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task GettingStorageObjectsWithEmptyObjectNameThrows() - { - var containerName = "TestContainer"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.GetStorageObject(containerName, string.Empty); - } - - [TestMethod] - public async Task CanGetStorageManifest() - { - var containerName = "TestContainer"; - var manifestName = "TestManifest"; - - var obj = new StaticLargeObjectManifest(manifestName, containerName, DateTime.UtcNow, "12345", 12345, - "application/octet-stream", new Dictionary()); - - this.ServicePocoClient.GetStorageManifestDelegate = (s, s1) => - { - Assert.AreEqual(s, obj.ContainerName); - Assert.AreEqual(s1, obj.FullName); - return Task.Factory.StartNew(() => (StorageManifest)obj); - }; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - var resp = await client.GetStorageManifest(containerName, manifestName); - - Assert.AreEqual(obj, resp); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task GettingStorageManifestWithNullContainerNameThrows() - { - var manifestName = "TestManifest"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.GetStorageManifest(null, manifestName); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task GettingStorageManifestWithEmptyContainerNameThrows() - { - var manifestName = "TestManifest"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.GetStorageObject(string.Empty, manifestName); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task GettingStorageManifestWithNullObjectNameThrows() - { - var containerName = "TestContainer"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.GetStorageManifest(containerName, null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task GettingStorageManifestWithEmptyObjectNameThrows() - { - var containerName = "TestContainer"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.GetStorageManifest(containerName, string.Empty); - } - - [TestMethod] - public async Task CanGetStorageFolder() - { - var containerName = "TestContainer"; - var folderName = "TestFolder/"; - - var obj = new StorageFolder(folderName, new List()); - - this.ServicePocoClient.GetStorageFolderDelegate = (s, s1) => - { - Assert.AreEqual(s, containerName); - Assert.AreEqual(s1, folderName); - return Task.Factory.StartNew(() => obj); - }; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - var resp = await client.GetStorageFolder(containerName, folderName); - - Assert.AreEqual(obj, resp); - } - - [TestMethod] - public async Task CanGetStorageFolderWithoutTrailingSlash() - { - var containerName = "TestContainer"; - var folderName = "TestFolder"; - - var obj = new StorageFolder(folderName, new List()); - - this.ServicePocoClient.GetStorageFolderDelegate = (s, s1) => - { - Assert.AreEqual(s, containerName); - Assert.AreEqual(s1, folderName +"/"); - return Task.Factory.StartNew(() => obj); - }; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - var resp = await client.GetStorageFolder(containerName, folderName); - - Assert.AreEqual(obj, resp); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task GettingStorageFolderWithNullContainerNameThrows() - { - var folderName = "TestFolder"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.GetStorageFolder(null, folderName); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task GettingStorageFolderWithEmptyContainerNameThrows() - { - var folderName = "TestFolder"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.GetStorageFolder(string.Empty, folderName); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task GettingStorageFolderWithNullObjectNameThrows() - { - var containerName = "TestContainer"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.GetStorageFolder(containerName, null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task GettingStorageFolderWithEmptyObjectNameThrows() - { - var containerName = "TestContainer"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.GetStorageFolder(containerName, string.Empty); - } - - [TestMethod] - public async Task CanCreateStorageObjects() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - var content = TestHelper.CreateStream("Some Data"); - - var obj = new StorageObject(objectName, containerName, DateTime.UtcNow, "12345", 12345, - "application/octet-stream", new Dictionary()); - - this.ServicePocoClient.CreateStorageObjectDelegate = async (s, stream) => - { - Assert.AreEqual(s.ContainerName, obj.ContainerName); - Assert.AreEqual(s.Name, obj.Name); - Assert.AreEqual(stream, content); - return await Task.Run(()=>obj); - }; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - var resp = await client.CreateStorageObject(containerName, objectName, new Dictionary(), content); - - Assert.AreEqual(obj, resp); - } - - [TestMethod] - public async Task CanCopyStorageObjects() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - var targetContainerName = "TargetTestContainer"; - - var obj = new StorageObject(objectName, targetContainerName, DateTime.UtcNow, "12345", 12345, - "application/octet-stream", new Dictionary()); - - this.ServicePocoClient.CopyStorageObjectDelegate = async (s, container, destinationObjectName) => - { - Assert.AreEqual(container, obj.ContainerName); - Assert.AreEqual(s.Name, obj.Name); - - return await Task.Run(() => obj); - }; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - var resp = await client.CopyStorageObject(containerName, objectName, targetContainerName); - - Assert.AreEqual(obj, resp); - } - - [TestMethod] - public async Task CanCopyStorageObjectsAndChangeName() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - var targetObjectName = "TargetTestObject"; - var targetContainerName = "TargetTestContainer"; - - var obj = new StorageObject(targetObjectName, targetContainerName, DateTime.UtcNow, "12345", 12345, - "application/octet-stream", new Dictionary()); - - this.ServicePocoClient.CopyStorageObjectDelegate = async (s, container, destinationObjectName) => - { - Assert.AreEqual(container, obj.ContainerName); - Assert.AreEqual(destinationObjectName, obj.Name); - - return await Task.Run(() => obj); - }; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - var resp = await client.CopyStorageObject(containerName, objectName, targetContainerName, targetObjectName); - - Assert.AreEqual(obj, resp); - } - - [TestMethod] - public async Task CreatingAnObjectLargerThanTheThresholdCreatesObjectWithSegments() - { - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - - var containerName = "TestContainer"; - var objectName = "TestObject"; - var content = "This is a lot of text that is bigger then the threshold that I set.".ConvertToStream(); - var metadata = new Dictionary(); - - var obj = new StorageObject(objectName, containerName, DateTime.UtcNow, "12345", 12345, - "application/octet-stream", new Dictionary()); - - this.loCreator.CreateDelegate = async (c, o, m, s, n, sc) => - { - Assert.AreEqual(containerName, c); - Assert.AreEqual(objectName, o); - Assert.AreEqual(metadata, m); - Assert.AreEqual(s, content); - Assert.AreEqual(client.LargeObjectSegments, n); - Assert.AreEqual(client.LargeObjectSegmentContainer, sc); - return await Task.Run(() => obj); - }; - - - client.LargeObjectThreshold = 10; - - var resp = await client.CreateStorageObject(containerName, objectName, metadata, content); - - Assert.AreEqual(obj, resp); - } - - [TestMethod] - public async Task CanCreateLargeObject() - { - var segmentsContainer = "LargeObjectSegments"; - var containerName = "TestContainer"; - var objectName = "TestObject"; - var metadata = new Dictionary(); - var content = "THIS IS A LOT OF CONTENT THAT WILL AND CAN BE CHOPPED UP"; - var contentStream = content.ConvertToStream(); - - - this.loCreator.CreateDelegate = async (c, o, m, s, n, sc) => - { - Assert.AreEqual(containerName, c); - Assert.AreEqual(objectName, o); - Assert.AreEqual(metadata, m); - Assert.AreEqual(s, contentStream); - Assert.AreEqual(3, n); - Assert.AreEqual(segmentsContainer, sc); - return await Task.Run(() => new StorageObject(o,c)); - }; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - var res = await client.CreateLargeStorageObject(containerName, objectName, metadata, contentStream, 3); - - Assert.AreEqual(containerName, res.ContainerName); - Assert.AreEqual(objectName, res.FullName); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CannotCreateLargeObjectWithNullContainerName() - { - var objectName = "TestObject"; - var metadata = new Dictionary(); - var content = "THIS IS A LOT OF CONTENT THAT WILL AND CAN BE CHOPPED UP"; - var contentStream = content.ConvertToStream(); - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - var res = await client.CreateLargeStorageObject(null, objectName, metadata, contentStream, 3); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CannotCreateLargeObjectWithEmptyContainerName() - { - var objectName = "TestObject"; - var metadata = new Dictionary(); - var content = "THIS IS A LOT OF CONTENT THAT WILL AND CAN BE CHOPPED UP"; - var contentStream = content.ConvertToStream(); - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - var res = await client.CreateLargeStorageObject(string.Empty, objectName, metadata, contentStream, 3); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CannotCreateLargeObjectWithNullObjectName() - { - var containerName = "TestContainer"; - var metadata = new Dictionary(); - var content = "THIS IS A LOT OF CONTENT THAT WILL AND CAN BE CHOPPED UP"; - var contentStream = content.ConvertToStream(); - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - var res = await client.CreateLargeStorageObject(containerName, null, metadata, contentStream, 3); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CannotCreateLargeObjectWithEmptyObjectName() - { - var containerName = "TestContainer"; - var metadata = new Dictionary(); - var content = "THIS IS A LOT OF CONTENT THAT WILL AND CAN BE CHOPPED UP"; - var contentStream = content.ConvertToStream(); - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - var res = await client.CreateLargeStorageObject(containerName, string.Empty, metadata, contentStream, 3); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CannotCreateLargeObjectWithNullMetadata() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - var content = "THIS IS A LOT OF CONTENT THAT WILL AND CAN BE CHOPPED UP"; - var contentStream = content.ConvertToStream(); - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - var res = await client.CreateLargeStorageObject(containerName, objectName, null, contentStream, 3); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CannotCreateLargeObjectWithNullContent() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - var metadata = new Dictionary(); - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - var res = await client.CreateLargeStorageObject(containerName, objectName, metadata, null, 3); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CannotCreateLargeObjectWithNegativeSegmentCount() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - var metadata = new Dictionary(); - var content = "THIS IS A LOT OF CONTENT THAT WILL AND CAN BE CHOPPED UP"; - var contentStream = content.ConvertToStream(); - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - var res = await client.CreateLargeStorageObject(containerName, objectName, metadata, contentStream, -3); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CannotCreateLargeObjectWithZeroSegmentCount() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - var metadata = new Dictionary(); - var content = "THIS IS A LOT OF CONTENT THAT WILL AND CAN BE CHOPPED UP"; - var contentStream = content.ConvertToStream(); - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - var res = await client.CreateLargeStorageObject(containerName, objectName, metadata, contentStream, 0); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CreatingStorageObjectsWithNullContainerNameThrows() - { - var objectName = "TestObject"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageObject(null, objectName, new Dictionary(), new MemoryStream()); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CreatingStorageObjectsWithEmptyContainerNameThrows() - { - var objectName = "TestObject"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageObject(string.Empty, objectName, new Dictionary(), new MemoryStream()); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CreatingStorageObjectsWithNullObjectNameThrows() - { - var containerName = "TestContainer"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageObject(containerName, null, new Dictionary(), new MemoryStream()); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CreatingStorageObjectsWithEmptyObjectNameThrows() - { - var containerName = "TestContainer"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageObject(containerName, string.Empty, new Dictionary(), new MemoryStream()); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CreatingStorageObjectsWithNullStreamThrows() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageObject(containerName, objectName, new Dictionary(), null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CreatingStorageObjectsWithNullMetadataThrows() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageObject(containerName, objectName, null, new MemoryStream()); - } - - #region Copy Storage Objects Tests - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CopyStorageObjectsWithNullContainerNameThrows() - { - var objectName = "TestObject"; - var targetContainerName = "TargetTestContainer"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CopyStorageObject(null, objectName, targetContainerName); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CopyStorageObjectsWithEmptyContainerNameThrows() - { - var objectName = "TestObject"; - var targetContainerName = "TargetTestContainer"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CopyStorageObject(string.Empty, objectName, targetContainerName); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CopyStorageObjectsWithNullObjectNameThrows() - { - var containerName = "TestContainer"; - var targetContainerName = "TargetTestContainer"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CopyStorageObject(containerName, null, targetContainerName); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CopyStorageObjectsWithEmptyObjectNameThrows() - { - var containerName = "TestContainer"; - var targetContainerName = "TargetTestContainer"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CopyStorageObject(containerName, string.Empty, targetContainerName); - - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CopyStorageObjectsWithNullTargetContainerThrows() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CopyStorageObject(containerName, objectName, null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CopyStorageObjectsWithEmptyTargetContainerThrows() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CopyStorageObject(containerName, objectName, string.Empty); - } - - #endregion - - [TestMethod] - public async Task CanCreateStaticStorageManifest() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var obj = new StorageObject(objectName, containerName, DateTime.UtcNow, "12345", 12345, - "application/octet-stream", new Dictionary()); - - this.ServicePocoClient.CreateStorageManifestDelegate = async (m) => - { - Assert.IsInstanceOfType(m,typeof(StaticLargeObjectManifest)); - return await Task.Run(() => m); - }; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageManifest(containerName, objectName, new Dictionary(), new List() { obj }); - } - - [TestMethod] - public async Task CanCreateDynamicStorageManifest() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - this.ServicePocoClient.CreateStorageManifestDelegate = async (m) => - { - Assert.IsInstanceOfType(m, typeof(DynamicLargeObjectManifest)); - return await Task.Run(() => m); - }; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageManifest(containerName, objectName, new Dictionary(), "segments"); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CreatingDynamicStorageManifestWithNullContainerNameThrows() - { - var manifestName = "TestManifest"; - var segmentPath = "segments"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageManifest(null, manifestName, new Dictionary(), segmentPath); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CreatingDynamicStorageManifestWithEmptyContainerNameThrows() - { - var manifestName = "TestManifest"; - var segmentPath = "segments"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageManifest(string.Empty, manifestName, new Dictionary(), segmentPath); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CreatingDynamicStorageManifestWithNullManifestNameThrows() - { - var containerName = "TestContainer"; - var segmentPath = "segments"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageManifest(containerName, null, new Dictionary(), segmentPath); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CreatingDynamicStorageManifestWithEmptyManifestNameThrows() - { - var containerName = "TestContainer"; - var segmentPath = "segments"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageManifest(containerName, string.Empty, new Dictionary(), segmentPath); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CreatingDynamicStorageManifestWithNullSegmentPathThrows() - { - var containerName = "TestContainer"; - var manifestName = "TestManifest"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageManifest(containerName, manifestName, new Dictionary(), (string)null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CreatingDynamicStorageManifestWithEmptySegmentPathThrows() - { - var containerName = "TestContainer"; - var manifestName = "TestManifest"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageManifest(containerName, manifestName, new Dictionary(), string.Empty); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CreatingDynamicStorageManifestWithNullMetadataThrows() - { - var containerName = "TestContainer"; - var manifestName = "TestManifest"; - var segmentPath = "segments"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageManifest(containerName, manifestName, null, segmentPath); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CreatingStaticStorageManifestWithNullContainerNameThrows() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var obj = new StorageObject(objectName, containerName, DateTime.UtcNow, "12345", 12345, - "application/octet-stream", new Dictionary()); - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageManifest(null, objectName, new Dictionary(), new List() { obj }); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CreatingStaticStorageManifestWithEmptyContainerNameThrows() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var obj = new StorageObject(objectName, containerName, DateTime.UtcNow, "12345", 12345, - "application/octet-stream", new Dictionary()); - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageManifest(string.Empty, objectName, new Dictionary(), new List() { obj }); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CreatingStaticStorageManifestWithNullManifestNameThrows() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var obj = new StorageObject(objectName, containerName, DateTime.UtcNow, "12345", 12345, - "application/octet-stream", new Dictionary()); - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageManifest(containerName, null, new Dictionary(), new List() { obj }); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CreatingStaticStorageManifestWithEmptyManifestNameThrows() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var obj = new StorageObject(objectName, containerName, DateTime.UtcNow, "12345", 12345, - "application/octet-stream", new Dictionary()); - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageManifest(containerName, string.Empty, new Dictionary(), new List() { obj }); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CreatingStaticStorageManifestWithNullObjectListThrows() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageManifest(containerName, objectName, new Dictionary(), (List)null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CreatingStaticStorageManifestWithNullMetadataThrows() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var obj = new StorageObject(objectName, containerName, DateTime.UtcNow, "12345", 12345, - "application/octet-stream", new Dictionary()); - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageManifest(containerName, objectName, null, new List() { obj }); - } - - [TestMethod] - public async Task CanCreateStorageFolder() - { - var containerName = "TestContainer"; - var folderName = "TestFolder/"; - - var obj = new StorageFolder(folderName, new List()); - - this.ServicePocoClient.CreateStorageFolderDelegate = async (s, s1) => - { - await Task.Run(() => - { - Assert.AreEqual(s1, folderName); - Assert.AreEqual(s, containerName); - }); - }; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageFolder(containerName, folderName); - } - - [TestMethod] - public async Task CanCreateStorageFolderWithoutTrailingSlash() - { - var containerName = "TestContainer"; - var folderName = "TestFolder"; - - var obj = new StorageFolder(folderName, new List()); - - this.ServicePocoClient.CreateStorageFolderDelegate = async (s, s1) => - { - await Task.Run(() => - { - Assert.AreEqual(s1, folderName +"/"); - Assert.AreEqual(s, containerName); - }); - }; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageFolder(containerName, folderName); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CreatingStorageFolderWithInvalidFolderNameThrows() - { - var containerName = "someContainer"; - var folderName = "Test//Folder"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageFolder(containerName, folderName); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CreatingStorageFolderWithNullContainerNameThrows() - { - var folderName = "TestFolder"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageFolder(null, folderName); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CreatingStorageFolderWithEmptyContainerNameThrows() - { - var folderName = "TestFolder"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageFolder(string.Empty, folderName); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CreatingStorageFolderWithNullObjectNameThrows() - { - var containerName = "TestContainer"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageFolder(containerName, null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CreatingStorageFolderWithEmptyObjectNameThrows() - { - var containerName = "TestContainer"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageFolder(containerName, string.Empty); - } - - [TestMethod] - public async Task CanCreateStorageContainers() - { - var containerName = "TestContainer"; - - var obj = new StorageContainer(containerName, new Dictionary()); - - this.ServicePocoClient.CreateStorageContainerDelegate = async (s) => - { - Assert.AreEqual(s.Name, obj.Name); - return await Task.Run(()=>obj); - }; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageContainer(containerName, new Dictionary()); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CreatingStorageContainersWithNullContainerNameThrows() - { - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageContainer(null, new Dictionary()); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CreatingStorageContainersWithEmptyContainerNameThrows() - { - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageContainer(string.Empty, new Dictionary()); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CreatingStorageContainersWithNullMetadataThrows() - { - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.CreateStorageContainer("TestContainer", null); - } - - [TestMethod] - public async Task CanGetStorageContainer() - { - var containerName = "TestContainer"; - - var obj = new StorageContainer(containerName, new Dictionary()); - - this.ServicePocoClient.GetStorageContainerDelegate = (s) => - { - Assert.AreEqual(s, obj.Name); - return Task.Factory.StartNew(() => obj); - }; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - var resp = await client.GetStorageContainer(containerName); - - Assert.AreEqual(obj, resp); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task GettingStorageContainersWithNullContainerNameThrows() - { - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.GetStorageContainer(null); - } - - [TestMethod] - [ExpectedException(typeof (ArgumentException))] - public async Task GettingStorageContainersWithEmptyContainerNameThrows() - { - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.GetStorageContainer(string.Empty); - } - - [TestMethod] - public async Task CanUpdateStorageContainer() - { - var containerName = "TestContainer"; - - var obj = new StorageContainer(containerName, new Dictionary()); - - this.ServicePocoClient.UpdateStorageContainerDelegate = async (s) => - { - await Task.Run(() => Assert.AreEqual(s.Name, obj.Name)); - }; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.UpdateStorageContainer(obj); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task UpdatingStorageContainersWithNullContainerThrows() - { - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.UpdateStorageContainer(null); - } - - [TestMethod] - public async Task CanDeleteStorageContainer() - { - var containerName = "TestContainer"; - - var obj = new StorageContainer(containerName, new Dictionary()); - - this.ServicePocoClient.DeleteStorageConainerDelegate = async (s) => - { - await Task.Run(()=>Assert.AreEqual(s, obj.Name)); - }; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.DeleteStorageContainer(obj.Name); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task DeletingStorageContainersWithNullContainerNameThrows() - { - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.DeleteStorageContainer(null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task DeletingStorageContainersWithEmptyContainerNameThrows() - { - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.DeleteStorageContainer(string.Empty); - } - - [TestMethod] - public async Task CanDeleteStorageObject() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var obj = new StorageObject(objectName, containerName, DateTime.UtcNow, "12345", 12345, - "application/octet-stream", new Dictionary()); - - this.ServicePocoClient.DeleteStorageObjectDelegate = async (s, s1) => - { - await Task.Run(() => - { - Assert.AreEqual(s, obj.ContainerName); - Assert.AreEqual(s1, obj.Name); - }); - }; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.DeleteStorageObject(obj.ContainerName,obj.Name); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task DeletingStorageObjectWithNullContainerNameThrows() - { - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.DeleteStorageObject(null,"TestObject"); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task DeletingStorageObjectsWithEmptyContainerNameThrows() - { - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.DeleteStorageObject(string.Empty, "TestObject"); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task DeletingStorageObjectWithNullObjectNameThrows() - { - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.DeleteStorageObject("TestContainer", null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task DeletingStorageObjectsWithEmptyObjectNameThrows() - { - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.DeleteStorageObject("TestContainer", string.Empty); - } - - [TestMethod] - public async Task CanDeleteStorageFolder() - { - var containerName = "TestContainer"; - var folderName = "TestFolder/"; - - this.ServicePocoClient.DeleteStorageFolderDelegate = async (s, s1) => - { - await Task.Run(() => - { - Assert.AreEqual(s, containerName); - Assert.AreEqual(s1, folderName); - }); - }; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.DeleteStorageFolder(containerName, folderName); - } - - [TestMethod] - public async Task CanDeleteStorageFolderWithoutTrailingSlash() - { - var containerName = "TestContainer"; - var folderName = "TestFolder"; - - this.ServicePocoClient.DeleteStorageFolderDelegate = async (s, s1) => - { - await Task.Run(() => - { - Assert.AreEqual(s, containerName); - Assert.AreEqual(s1, folderName +"/"); - }); - }; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.DeleteStorageFolder(containerName, folderName); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task DeletingStorageFolderWithNullContainerNameThrows() - { - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.DeleteStorageFolder(null, "TestFolder"); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task DeletingStorageFolderWithEmptyContainerNameThrows() - { - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.DeleteStorageFolder(string.Empty, "TestFolder"); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task DeletingStorageFolderWithNullObjectNameThrows() - { - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.DeleteStorageFolder("TestContainer", null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task DeletingStorageFolderWithEmptyObjectNameThrows() - { - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.DeleteStorageFolder("TestContainer", string.Empty); - } - - [TestMethod] - public async Task CanUpdateStorageObject() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var obj = new StorageObject(objectName, containerName, DateTime.UtcNow, "12345", 12345, - "application/octet-stream", new Dictionary()); - - this.ServicePocoClient.UpdateStorageObjectDelegate = async (s) => - { - await Task.Run(() => - { - Assert.AreEqual(s.ContainerName, obj.ContainerName); - Assert.AreEqual(s.Name, obj.Name); - }); - }; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.UpdateStorageObject(obj); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task UpdatingStorageObjectWithNullContainerThrows() - { - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.UpdateStorageObject(null); - } - - [TestMethod] - public async Task CanDownloadStorageObjects() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - var data = "some data"; - var content = TestHelper.CreateStream(data); - var respStream = new MemoryStream(); - - var obj = new StorageObject(objectName, containerName, DateTime.UtcNow, "12345", 12345, - "application/octet-stream", new Dictionary()); - - this.ServicePocoClient.DownloadStorageObjectDelegate = async (s, s1, stream) => - { - Assert.AreEqual(s, obj.ContainerName); - Assert.AreEqual(s1, obj.Name); - - await content.CopyToAsync(stream); - - return obj; - }; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - var resp = await client.DownloadStorageObject(containerName, objectName, respStream); - respStream.Position = 0; - - Assert.AreEqual(obj, resp); - Assert.AreEqual(data,TestHelper.GetStringFromStream(respStream)); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task DownloadingStorageObjectsWithNullContainerNameThrows() - { - var objectName = "TestObject"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.DownloadStorageObject(null, objectName, new MemoryStream()); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task DownloadingStorageObjectsWithEmptyContainerNameThrows() - { - var objectName = "TestObject"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.DownloadStorageObject(string.Empty, objectName, new MemoryStream()); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task DownloadingStorageObjectsWithNullObjectNameThrows() - { - var containerName = "TestContainer"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.DownloadStorageObject(containerName, null, new MemoryStream() ); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task DownloadingStorageObjectsWithEmptyObjectNameThrows() - { - var containerName = "TestContainer"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.DownloadStorageObject(containerName, string.Empty, new MemoryStream()); - } - - [TestMethod] - [ExpectedException(typeof (ArgumentNullException))] - public async Task DownloadingStorageObjectsWithNullStreamThrows() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var client = new StorageServiceClient(GetValidCreds(), "Swift", CancellationToken.None, this.ServiceLocator); - await client.DownloadStorageObject(containerName, objectName, null); - } - } -} diff --git a/OpenStack/OpenStack.Test/Storage/StorageServicePocoClientTests.cs b/OpenStack/OpenStack.Test/Storage/StorageServicePocoClientTests.cs deleted file mode 100644 index 13f77c0..0000000 --- a/OpenStack/OpenStack.Test/Storage/StorageServicePocoClientTests.cs +++ /dev/null @@ -1,2030 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Common.Http; -using OpenStack.Common.ServiceLocation; -using OpenStack.Identity; -using OpenStack.Storage; - -namespace OpenStack.Test.Storage -{ - [TestClass] - public class StorageServicePocoClientTests - { - internal TestStorageServiceRestClient StorageServiceRestClient; - internal string authId = "12345"; - internal Uri endpoint = new Uri("http://teststorageendpoint.com/v1/1234567890"); - internal IServiceLocator ServiceLocator; - - [TestInitialize] - public void TestSetup() - { - this.StorageServiceRestClient = new TestStorageServiceRestClient(); - this.ServiceLocator = new ServiceLocator(); - - var manager = this.ServiceLocator.Locate(); - manager.RegisterServiceInstance(typeof(IStorageServiceRestClientFactory), new TestStorageServiceRestClientFactory(StorageServiceRestClient)); - } - - [TestCleanup] - public void TestCleanup() - { - this.StorageServiceRestClient = new TestStorageServiceRestClient(); - this.ServiceLocator = new ServiceLocator(); - } - - ServiceClientContext GetValidContext() - { - var creds = new OpenStackCredential(this.endpoint, "SomeUser", "Password", "SomeTenant", "region-a.geo-1"); - creds.SetAccessTokenId(this.authId); - - return new ServiceClientContext(creds, CancellationToken.None, "Object Storage", endpoint); - } - - #region Get Storage Container Tests - - [TestMethod] - public async Task CanGetStorageContainerWithOkResponse() - { - var containerName = "TestContainer"; - var headers = new HttpHeadersAbstraction() - { - {"X-Container-Bytes-Used", "1234"}, - {"X-Container-Object-Count", "1"} - }; - - var payload = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": 0, - ""name"": ""BLAH"", - ""content_type"": ""application/octet-stream"" - }]"; - - var content = TestHelper.CreateStream(payload); - - var restResp = new HttpResponseAbstraction(content, headers, HttpStatusCode.OK); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClientFactory().Create(GetValidContext(), this.ServiceLocator) as StorageServicePocoClient; - var result = await client.GetStorageContainer(containerName); - - Assert.IsNotNull(result); - Assert.AreEqual(containerName, result.Name); - Assert.AreEqual(1234, result.TotalBytesUsed); - Assert.AreEqual(1, result.TotalObjectCount); - Assert.IsNotNull(result.Objects); - Assert.AreEqual(1, result.Objects.Count()); - } - - [TestMethod] - public async Task CanGetStorageContainerWithNoContent() - { - var containerName = "TestContainer"; - var headers = new HttpHeadersAbstraction() - { - {"X-Container-Bytes-Used", "0"}, - {"X-Container-Object-Count", "0"} - }; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), headers, HttpStatusCode.NoContent); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.GetStorageContainer(containerName); - - Assert.IsNotNull(result); - Assert.AreEqual(containerName, result.Name); - Assert.AreEqual(0, result.TotalBytesUsed); - Assert.AreEqual(0, result.TotalObjectCount); - Assert.IsNotNull(result.Objects); - Assert.AreEqual(0, result.Objects.Count()); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingAStorageContainerThatDoesNotExist() - { - var containerName = "TestContainer"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.NotFound); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetStorageContainer(containerName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingAStorageContainerAndNotAuthed() - { - var containerName = "TestContainer"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetStorageContainer(containerName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingAStorageContainerAndServerError() - { - var containerName = "TestContainer"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetStorageContainer(containerName); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CannotGetStorageContainerWithNullName() - { - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetStorageContainer(null); - } - - #endregion - - #region Get Storage Account Tests - - [TestMethod] - public async Task CanGetStorageAccountWithOkResponse() - { - var accountName = "1234567890"; - var headers = new HttpHeadersAbstraction() - { - {"X-Account-Bytes-Used", "1234"}, - {"X-Account-Object-Count", "1"}, - {"X-Account-Container-Count", "1"} - }; - - var payload = @"[ - { - ""count"": 1, - ""bytes"": 7, - ""name"": ""TestContainer"" - }]"; - - var content = TestHelper.CreateStream(payload); - - var restResp = new HttpResponseAbstraction(content, headers, HttpStatusCode.OK); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.GetStorageAccount(); - - Assert.IsNotNull(result); - Assert.AreEqual(accountName, result.Name); - Assert.AreEqual(1234, result.TotalBytesUsed); - Assert.AreEqual(1, result.TotalObjectCount); - Assert.AreEqual(1, result.TotalContainerCount); - Assert.IsNotNull(result.Containers); - Assert.AreEqual(1, result.Containers.Count()); - } - - [TestMethod] - public async Task CanGetStorageAccontWithNoContent() - { - var accountName = "1234567890"; - var headers = new HttpHeadersAbstraction() - { - {"X-Account-Bytes-Used", "1234"}, - {"X-Account-Object-Count", "1"}, - {"X-Account-Container-Count", "1"} - }; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), headers, HttpStatusCode.NoContent); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.GetStorageAccount(); - - Assert.IsNotNull(result); - Assert.AreEqual(accountName, result.Name); - Assert.AreEqual(1234, result.TotalBytesUsed); - Assert.AreEqual(1, result.TotalObjectCount); - Assert.AreEqual(1, result.TotalContainerCount); - Assert.IsNotNull(result.Containers); - Assert.AreEqual(0, result.Containers.Count()); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingAStorageAccountAndNotAuthed() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetStorageAccount(); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingAStorageAccountAndServerError() - { - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetStorageAccount(); - } - - #endregion - - #region Download Storage Object Tests - - [TestMethod] - public async Task CanDownloadStorageObjectWithOkResponse() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"ETag", "d41d8cd98f00b204e9800998ecf8427e"} - }; - - var data = "some data"; - var content = TestHelper.CreateStream(data); - - var restResp = new HttpResponseAbstraction(content, headers, HttpStatusCode.OK); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - - var respContent = new MemoryStream(); - var result = await client.DownloadStorageObject(containerName, objectName, respContent); - - Assert.IsNotNull(result); - Assert.AreEqual(objectName, result.Name); - Assert.AreEqual(containerName, result.ContainerName); - Assert.AreEqual(1234, result.Length); - Assert.AreEqual("application/octet-stream", result.ContentType); - Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", result.ETag); - Assert.AreEqual(DateTime.Parse("Wed, 12 Mar 2014 23:42:23 GMT"), result.LastModified); - Assert.AreEqual(data,TestHelper.GetStringFromStream(respContent)); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenDownloadingAStorageObjectThatDoesNotExist() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.NotFound); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DownloadStorageObject(containerName, objectName, new MemoryStream()); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenDownloadingAStorageObjectAndNotAuthed() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DownloadStorageObject(containerName, objectName, new MemoryStream()); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenDownloadingAStorageObjectAndServerError() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DownloadStorageObject(containerName, objectName, new MemoryStream()); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CannotDownloadStorageObjectWithNullContainerName() - { - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DownloadStorageObject(null, "object", new MemoryStream()); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CannotDownloadStorageObjectWithNullObjectName() - { - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DownloadStorageObject("container", null, new MemoryStream()); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CannotDownloadStorageObjectWithEmptyContainerName() - { - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DownloadStorageObject(string.Empty, "object", new MemoryStream()); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CannotDownloadStorageObjectWithEmptyObjectName() - { - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DownloadStorageObject("container", string.Empty, new MemoryStream()); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CannotDownloadStorageObjectWithnullOutputStream() - { - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DownloadStorageObject("container", "object", null); - } - - #endregion - - #region Get Storage Object Tests - - [TestMethod] - public async Task CanGetStorageObjectWithOkResponse() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"ETag", "d41d8cd98f00b204e9800998ecf8427e"} - }; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), headers, HttpStatusCode.OK); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.GetStorageObject(containerName, objectName); - - Assert.IsNotNull(result); - Assert.IsInstanceOfType(result,typeof(StorageObject)); - Assert.IsNotInstanceOfType(result, typeof(StorageManifest)); - Assert.AreEqual(objectName, result.Name); - Assert.AreEqual(containerName, result.ContainerName); - Assert.AreEqual(1234, result.Length); - Assert.AreEqual("application/octet-stream", result.ContentType); - Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", result.ETag); - Assert.AreEqual(DateTime.Parse("Wed, 12 Mar 2014 23:42:23 GMT"), result.LastModified); - } - - [TestMethod] - public async Task CanGetStorageObjectWithOkResponseThatIsAManifest() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"ETag", "d41d8cd98f00b204e9800998ecf8427e"}, - {"X-Object-Meta-Test1","Test1"}, - {"X-Static-Large-Object","True"} - }; - - var payload = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": 54321, - ""name"": ""a/b/c/BLAH"", - ""content_type"": ""application/octet-stream"" - }]"; - - var content = TestHelper.CreateStream(payload); - - var restResp = new HttpResponseAbstraction(content, headers, HttpStatusCode.OK); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.GetStorageObject(containerName, objectName); - - Assert.IsNotNull(result); - Assert.IsInstanceOfType(result, typeof(StaticLargeObjectManifest)); - Assert.AreEqual(objectName, result.Name); - Assert.AreEqual(containerName, result.ContainerName); - Assert.AreEqual(1234, result.Length); - Assert.AreEqual("application/octet-stream", result.ContentType); - Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", result.ETag); - Assert.AreEqual(DateTime.Parse("Wed, 12 Mar 2014 23:42:23 GMT"), result.LastModified); - } - - [TestMethod] - public async Task CanGetStorageObjectWithNoContent() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"ETag", "d41d8cd98f00b204e9800998ecf8427e"} - }; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), headers, HttpStatusCode.NoContent); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.GetStorageObject(containerName, objectName); - - Assert.IsNotNull(result); - Assert.AreEqual(objectName, result.Name); - Assert.AreEqual(containerName, result.ContainerName); - Assert.AreEqual(1234, result.Length); - Assert.AreEqual("application/octet-stream", result.ContentType); - Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", result.ETag); - Assert.AreEqual(DateTime.Parse("Wed, 12 Mar 2014 23:42:23 GMT"), result.LastModified); - } - - [TestMethod] - public async Task CanGetStorageObjectWithHeaders() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"ETag", "d41d8cd98f00b204e9800998ecf8427e"}, - {"X-Object-Meta-Test1","Test1"} - }; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), headers, HttpStatusCode.NoContent); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.GetStorageObject(containerName, objectName); - - Assert.IsNotNull(result); - Assert.AreEqual(objectName, result.Name); - Assert.AreEqual(containerName, result.ContainerName); - Assert.AreEqual(1234, result.Length); - Assert.AreEqual("application/octet-stream", result.ContentType); - Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", result.ETag); - Assert.AreEqual(DateTime.Parse("Wed, 12 Mar 2014 23:42:23 GMT"), result.LastModified); - Assert.AreEqual(1, result.Metadata.Count()); - Assert.IsTrue(result.Metadata.ContainsKey("Test1")); - Assert.AreEqual("Test1", result.Metadata["Test1"]); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingAStorageObjectThatDoesNotExist() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.NotFound); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetStorageObject(containerName, objectName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingAStorageObjectAndNotAuthed() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetStorageObject(containerName, objectName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingAStorageObjectAndServerError() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetStorageObject(containerName, objectName); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CannotGetStorageObjectWithNullContainerName() - { - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetStorageObject(null,"object"); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CannotGetStorageObjectWithNullObjectName() - { - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetStorageObject("container", null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CannotGetStorageObjectWithEmptyContainerName() - { - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetStorageObject(string.Empty, "object"); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CannotGetStorageObjectWithEmptyObjectName() - { - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetStorageObject("container", string.Empty); - } - - #endregion - - #region Get Storage Manifest Tests - - [TestMethod] - public async Task CanGetStaticStorageManifestWithOkResponseAndPayload() - { - var containerName = "TestContainer"; - var manifestName = "a/b/c/manifest"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"ETag", "d41d8cd98f00b204e9800998ecf8427e"}, - {"X-Object-Meta-Test1","Test1"}, - {"X-Static-Large-Object","True"} - }; - - var payload = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": 0, - ""name"": ""a/b/c/BLAH"", - ""content_type"": ""application/octet-stream"" - }]"; - - var content = TestHelper.CreateStream(payload); - - var restResp = new HttpResponseAbstraction(content, headers, HttpStatusCode.OK); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClientFactory().Create(GetValidContext(), this.ServiceLocator) as StorageServicePocoClient; - var result = await client.GetStorageManifest(containerName, manifestName); - - Assert.IsNotNull(result); - Assert.IsInstanceOfType(result, typeof(StaticLargeObjectManifest)); - Assert.AreEqual(manifestName, result.FullName); - Assert.AreEqual("manifest", result.Name); - - var manifest = result as StaticLargeObjectManifest; - Assert.IsNotNull(manifest.Objects); - Assert.AreEqual(1, manifest.Objects.Count()); - Assert.AreEqual("a/b/c/BLAH", manifest.Objects.First().FullName); - } - - [TestMethod] - public async Task CanGetDynamicStorageManifestWithOkResponseAndPayload() - { - var containerName = "TestContainer"; - var manifestName = "a/b/c/manifest"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"ETag", "d41d8cd98f00b204e9800998ecf8427e"}, - {"X-Object-Meta-Test1","Test1"}, - {"X-Object-Manifest","a/b"} - }; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), headers, HttpStatusCode.NoContent); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClientFactory().Create(GetValidContext(), this.ServiceLocator) as StorageServicePocoClient; - var result = await client.GetStorageManifest(containerName, manifestName); - - Assert.IsNotNull(result); - Assert.IsInstanceOfType(result, typeof(DynamicLargeObjectManifest)); - Assert.AreEqual(manifestName, result.FullName); - Assert.AreEqual("manifest", result.Name); - var manifest = result as DynamicLargeObjectManifest; - Assert.AreEqual("a/b", manifest.SegmentsPath); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task CannotGetStaticStorageManifestWhenObjectIsNotManifest() - { - var containerName = "TestContainer"; - var manifestName = "a/b/c/manifest"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"ETag", "d41d8cd98f00b204e9800998ecf8427e"}, - {"X-Object-Meta-Test1","Test1"}, - {"X-Static-Large-Object","False"} - }; - - var payload = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": 0, - ""name"": ""a/b/c/BLAH"", - ""content_type"": ""application/octet-stream"" - }]"; - - var content = TestHelper.CreateStream(payload); - - var restResp = new HttpResponseAbstraction(content, headers, HttpStatusCode.OK); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClientFactory().Create(GetValidContext(), this.ServiceLocator) as StorageServicePocoClient; - await client.GetStorageManifest(containerName, manifestName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingAStorageManifestThatDoesNotExist() - { - var containerName = "TestContainer"; - var manifestName = "a/b/b/manifest"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.NotFound); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetStorageManifest(containerName, manifestName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingAStoragManifestAndNotAuthed() - { - var containerName = "TestContainer"; - var manifestName = "a/b/b/manifest"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetStorageManifest(containerName, manifestName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingAStorageManifestAndServerError() - { - var containerName = "TestContainer"; - var manifestName = "a/b/b/manifest"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetStorageManifest(containerName, manifestName); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CannotGetStorageManifestWithNullContainerName() - { - var client = new StorageServicePocoClientFactory().Create(GetValidContext(), this.ServiceLocator) as StorageServicePocoClient; - await client.GetStorageManifest(null, "a/b/c/manifest"); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CannotGetStorageManifestWithNullFolderName() - { - var client = new StorageServicePocoClientFactory().Create(GetValidContext(), this.ServiceLocator) as StorageServicePocoClient; - await client.GetStorageManifest("container", null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CannotGetStorageManifestWithEmptyContainerName() - { - var client = new StorageServicePocoClientFactory().Create(GetValidContext(), this.ServiceLocator) as StorageServicePocoClient; - await client.GetStorageManifest(string.Empty, "a/b/c/manifest"); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CannotGetStorageManifestWithEmptyFolderName() - { - var client = new StorageServicePocoClientFactory().Create(GetValidContext(), this.ServiceLocator) as StorageServicePocoClient; - await client.GetStorageManifest("container", string.Empty); - } - - #endregion - - #region Get Storage Folder Tests - - [TestMethod] - public async Task CanGetStorageFolderWithOkResponseAndNoSubFolders() - { - var containerName = "TestContainer"; - var folderName = "a/b/c/"; - var headers = new HttpHeadersAbstraction() - { - {"X-Container-Bytes-Used", "1234"}, - {"X-Container-Object-Count", "1"} - }; - - var payload = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": 0, - ""name"": ""a/b/c/BLAH"", - ""content_type"": ""application/octet-stream"" - }]"; - - var content = TestHelper.CreateStream(payload); - - var restResp = new HttpResponseAbstraction(content, headers, HttpStatusCode.OK); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClientFactory().Create(GetValidContext(), this.ServiceLocator) as StorageServicePocoClient; - var result = await client.GetStorageFolder(containerName, folderName); - - Assert.IsNotNull(result); - Assert.AreEqual("a/b/c/", result.FullName); - Assert.AreEqual("c", result.Name); - Assert.IsNotNull(result.Objects); - Assert.AreEqual(1, result.Objects.Count()); - Assert.IsNotNull(result.Folders); - Assert.AreEqual(0, result.Folders.Count()); - } - - [TestMethod] - public async Task CanGetStorageFolderWithNoContentResponse() - { - var containerName = "TestContainer"; - var folderName = "a/b/c/"; - var headers = new HttpHeadersAbstraction() - { - {"X-Container-Bytes-Used", "1234"}, - {"X-Container-Object-Count", "1"} - }; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), headers, HttpStatusCode.NoContent); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClientFactory().Create(GetValidContext(), this.ServiceLocator) as StorageServicePocoClient; - var result = await client.GetStorageFolder(containerName, folderName); - - Assert.IsNotNull(result); - Assert.AreEqual("a/b/c/", result.FullName); - Assert.AreEqual("c", result.Name); - Assert.IsNotNull(result.Objects); - Assert.AreEqual(0, result.Objects.Count()); - Assert.IsNotNull(result.Folders); - Assert.AreEqual(0, result.Folders.Count()); - } - - [TestMethod] - public async Task CanGetStorageFolderWithOkResponseAndSubFolders() - { - var containerName = "TestContainer"; - var folderName = "a/b/c/"; - var headers = new HttpHeadersAbstraction() - { - {"X-Container-Bytes-Used", "1234"}, - {"X-Container-Object-Count", "1"} - }; - - var payload = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": 0, - ""name"": ""a/b/c/"", - ""content_type"": ""application/octet-stream"" - }, - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": 0, - ""name"": ""a/b/c/BLAH"", - ""content_type"": ""application/octet-stream"" - }, - { - ""subdir"": ""a/b/c/d/"" - }, - { - ""subdir"": ""a/b/c/x/"" - } - ]"; - - var content = TestHelper.CreateStream(payload); - - var restResp = new HttpResponseAbstraction(content, headers, HttpStatusCode.OK); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClientFactory().Create(GetValidContext(), this.ServiceLocator) as StorageServicePocoClient; - var resp = await client.GetStorageFolder(containerName, folderName); - - Assert.AreEqual("c", resp.Name); - Assert.AreEqual("a/b/c/", resp.FullName); - Assert.AreEqual(1, resp.Objects.Count); - Assert.AreEqual(2, resp.Folders.Count); - - var obj = resp.Objects.First(); - Assert.AreEqual("a/b/c/BLAH", obj.FullName); - - var dNode = resp.Folders.First(f => f.FullName == "a/b/c/d/"); - var xNode = resp.Folders.First(f => f.FullName == "a/b/c/x/"); - - Assert.AreEqual("d", dNode.Name); - Assert.AreEqual(0, dNode.Folders.Count); - Assert.AreEqual(0, dNode.Objects.Count); - - Assert.AreEqual("x", xNode.Name); - Assert.AreEqual(0, xNode.Folders.Count); - Assert.AreEqual(0, xNode.Objects.Count); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingAStorageFolderThatDoesNotExistAndCannotBeInferred() - { - var containerName = "TestContainer"; - var folderName = "a/b/c/"; - var headers = new HttpHeadersAbstraction() - { - {"X-Container-Bytes-Used", "1234"}, - {"X-Container-Object-Count", "1"} - }; - - var payload = @"[]"; - - var content = TestHelper.CreateStream(payload); - - var restResp = new HttpResponseAbstraction(content, headers, HttpStatusCode.OK); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClientFactory().Create(GetValidContext(), this.ServiceLocator) as StorageServicePocoClient; - var resp = await client.GetStorageFolder(containerName, folderName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingAStorageFolderThatDoesNotExist() - { - var containerName = "TestContainer"; - var fodlerName = "a/b/b/"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.NotFound); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetStorageFolder(containerName, fodlerName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingAStoragFolderAndNotAuthed() - { - var containerName = "TestContainer"; - var fodlerName = "a/b/b/"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetStorageFolder(containerName, fodlerName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionthrownWhenGettingAStorageFolderAndServerError() - { - var containerName = "TestContainer"; - var fodlerName = "a/b/b/"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.GetStorageFolder(containerName, fodlerName); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CannotGetStorageFolderWithNullContainerName() - { - var client = new StorageServicePocoClientFactory().Create(GetValidContext(), this.ServiceLocator) as StorageServicePocoClient; - await client.GetStorageFolder(null, "a/b/c/"); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CannotGetStorageFolderWithNullFolderName() - { - var client = new StorageServicePocoClientFactory().Create(GetValidContext(), this.ServiceLocator) as StorageServicePocoClient; - await client.GetStorageFolder("container", null); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CannotGetStorageFolderWithEmptyContainerName() - { - var client = new StorageServicePocoClientFactory().Create(GetValidContext(), this.ServiceLocator) as StorageServicePocoClient; - await client.GetStorageFolder(string.Empty, "a/b/c/"); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CannotGetStorageFolderWithEmptyFolderName() - { - var client = new StorageServicePocoClientFactory().Create(GetValidContext(), this.ServiceLocator) as StorageServicePocoClient; - await client.GetStorageFolder("container", string.Empty); - } - - #endregion - - #region Create Storage Manifest Tests - - [TestMethod] - public async Task CanCreateStaticManifestWithCreatedResponse() - { - var containerName = "TestContainer"; - var manifestName = "a/b/c/manifest"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"ETag", "d41d8cd98f00b204e9800998ecf8427e"} - }; - - var headers2 = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"ETag", "d41d8cd98f00b204e9800998ecf8427e"}, - {"X-Static-Large-Object","True"} - }; - - var payload = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": 0, - ""name"": ""a/b/c/BLAH"", - ""content_type"": ""application/octet-stream"" - }]"; - - var content = TestHelper.CreateStream(payload); - - var restResp1 = new HttpResponseAbstraction(new MemoryStream(), headers, HttpStatusCode.Created); - var restResp2 = new HttpResponseAbstraction(content, headers2, HttpStatusCode.OK); - this.StorageServiceRestClient.Responses.Enqueue(restResp1); - this.StorageServiceRestClient.Responses.Enqueue(restResp2); - - var client = new StorageServicePocoClientFactory().Create(GetValidContext(), this.ServiceLocator) as StorageServicePocoClient; - - var manifest = new StaticLargeObjectManifest(containerName, manifestName, - new List() - { - new StorageObject("a/b/c/BLAH", containerName, new Dictionary()) - }); - - var result = await client.CreateStorageManifest(manifest); - - Assert.IsTrue(this.StorageServiceRestClient.CreateStaticManifestCalled); - Assert.IsInstanceOfType(result, typeof(StaticLargeObjectManifest)); - Assert.AreEqual(manifestName, result.FullName); - Assert.AreEqual(containerName, result.ContainerName); - Assert.AreEqual(1, ((StaticLargeObjectManifest)result).Objects.Count); - Assert.AreEqual("a/b/c/BLAH", ((StaticLargeObjectManifest)result).Objects.First().FullName); - } - - [TestMethod] - public async Task CanCreateDynamicManifestWithCreatedResponse() - { - var containerName = "TestContainer"; - var manifestName = "a/b/c/manifest"; - var segPath = "TestContainer/a/b/c"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"ETag", "d41d8cd98f00b204e9800998ecf8427e"} - }; - - var headers2 = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"ETag", "d41d8cd98f00b204e9800998ecf8427e"}, - {"X-Object-Manifest",segPath} - }; - - var restResp1 = new HttpResponseAbstraction(new MemoryStream(), headers, HttpStatusCode.Created); - var restResp2 = new HttpResponseAbstraction(new MemoryStream(), headers2, HttpStatusCode.OK); - this.StorageServiceRestClient.Responses.Enqueue(restResp1); - this.StorageServiceRestClient.Responses.Enqueue(restResp2); - - var client = new StorageServicePocoClientFactory().Create(GetValidContext(), this.ServiceLocator) as StorageServicePocoClient; - - var manifest = new DynamicLargeObjectManifest(containerName, manifestName, segPath); - - var result = await client.CreateStorageManifest(manifest); - - Assert.IsTrue(this.StorageServiceRestClient.CreatedDynamicManifestCalled); - Assert.IsInstanceOfType(result, typeof(DynamicLargeObjectManifest)); - Assert.AreEqual(manifestName, result.FullName); - Assert.AreEqual(containerName, result.ContainerName); - Assert.AreEqual(segPath, ((DynamicLargeObjectManifest)result).SegmentsPath); - } - - - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task CannotCreateManifestWithUnknownManifestType() - { - var containerName = "TestContainer"; - var manifestName = "a/b/c/manifest"; - - var client = new StorageServicePocoClientFactory().Create(GetValidContext(), this.ServiceLocator) as StorageServicePocoClient; - - var manifest = new TestStorageManifest(containerName, manifestName); - - await client.CreateStorageManifest(manifest); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CannotCreateManifestWithNullContainerName() - { - var manifestName = "a/b/c/manifest"; - - var client = new StorageServicePocoClientFactory().Create(GetValidContext(), this.ServiceLocator) as StorageServicePocoClient; - - var manifest = new TestStorageManifest(null, manifestName); - - await client.CreateStorageManifest(manifest); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CannotCreateManifestWithEmptyContainerName() - { - var manifestName = "a/b/c/manifest"; - - var client = new StorageServicePocoClientFactory().Create(GetValidContext(), this.ServiceLocator) as StorageServicePocoClient; - - var manifest = new TestStorageManifest(string.Empty, manifestName); - - await client.CreateStorageManifest(manifest); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CannotCreateManifestWithNullManifestName() - { - var containerName = "TestContainer"; - - var client = new StorageServicePocoClientFactory().Create(GetValidContext(), this.ServiceLocator) as StorageServicePocoClient; - - var manifest = new TestStorageManifest(containerName, null); - - await client.CreateStorageManifest(manifest); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CannotCreateManifestWithEmptyManifestName() - { - var containerName = "TestContainer"; - - var client = new StorageServicePocoClientFactory().Create(GetValidContext(), this.ServiceLocator) as StorageServicePocoClient; - - var manifest = new TestStorageManifest(containerName, string.Empty); - - await client.CreateStorageManifest(manifest); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentNullException))] - public async Task CannotCreateManifestWithNullManifest() - { - var client = new StorageServicePocoClientFactory().Create(GetValidContext(), this.ServiceLocator) as StorageServicePocoClient; - - await client.CreateStorageManifest(null); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenCreatingaStorageManifestWithBadAuth() - { - var containerName = "TestContainer"; - var manifestName = "a/b/c/manifest"; - var segPath = "TestContainer/a/b/c"; - - var manifest = new DynamicLargeObjectManifest(containerName, manifestName, segPath); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.CreateStorageManifest(manifest); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenCreatingaStorageManifestHasInternalServerError() - { - var containerName = "TestContainer"; - var manifestName = "a/b/c/manifest"; - var segPath = "TestContainer/a/b/c"; - - var manifest = new DynamicLargeObjectManifest(containerName, manifestName, segPath); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.CreateStorageManifest(manifest); - } - - #endregion - - #region Create Storage Object Tests - - [TestMethod] - public async Task CanCreateStorageObjectWithCreatedResponse() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "0"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"ETag", "d41d8cd98f00b204e9800998ecf8427e"} - }; - - var objRequest = new StorageObject(objectName, containerName); - var content = TestHelper.CreateStream("Some Content"); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), headers, HttpStatusCode.Created); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.CreateStorageObject(objRequest, content); - - Assert.IsNotNull(result); - Assert.AreEqual(objectName, result.Name); - Assert.AreEqual(containerName, result.ContainerName); - Assert.AreEqual(12, result.Length); //length of content stream - Assert.AreEqual("application/octet-stream", result.ContentType); - Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", result.ETag); - Assert.AreEqual(DateTime.Parse("Wed, 12 Mar 2014 23:42:23 GMT"), result.LastModified); - } - - [TestMethod] - public async Task CanCreateStorageObjectWithFoldersAndCreatedResponse() - { - var containerName = "TestContainer"; - var objectName = "a/b/TestObject"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "0"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"ETag", "d41d8cd98f00b204e9800998ecf8427e"} - }; - - var objRequest = new StorageObject(objectName, containerName); - var content = TestHelper.CreateStream("Some Content"); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), headers, HttpStatusCode.Created); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.CreateStorageObject(objRequest, content); - - Assert.IsNotNull(result); - Assert.AreEqual(objectName, result.FullName); - Assert.AreEqual(containerName, result.ContainerName); - Assert.AreEqual(12, result.Length);//12 length of the content stream - Assert.AreEqual("application/octet-stream", result.ContentType); - Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", result.ETag); - Assert.AreEqual(DateTime.Parse("Wed, 12 Mar 2014 23:42:23 GMT"), result.LastModified); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenCreatingaStorageObjectMissingLength() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var objRequest = new StorageObject(objectName, containerName); - var content = TestHelper.CreateStream("Some Content"); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.LengthRequired); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.CreateStorageObject(objRequest, content); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenCreatingaStorageObjectWithBadETag() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var objRequest = new StorageObject(objectName, containerName); - var content = TestHelper.CreateStream("Some Content"); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), (HttpStatusCode)422); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.CreateStorageObject(objRequest, content); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenCreatingaStorageObjectWithBadAuth() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var objRequest = new StorageObject(objectName, containerName); - var content = TestHelper.CreateStream("Some Content"); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.CreateStorageObject(objRequest, content); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenCreatingaStorageObjectHasInternalServerError() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var objRequest = new StorageObject(objectName, containerName); - var content = TestHelper.CreateStream("Some Content"); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.CreateStorageObject(objRequest, content); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenCreatingaStorageObjectTimesOut() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var objRequest = new StorageObject(objectName, containerName); - var content = TestHelper.CreateStream("Some Content"); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.RequestTimeout); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.CreateStorageObject(objRequest, content); - } - - #endregion - - #region Copy Storage Object Tests - - [TestMethod] - public async Task CanCopyStorageObjectWithCreatedResponse() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - var targetContainerName = "TargetTestContainer"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "0"}, - {"Content-Type", "application/octet-stream"}, - {"X-Copied-From-Last-Modified","Wed, 12 Mar 2014 22:42:23 GMT"}, - {"X-Copied-From" , "TestContainer/TestObject"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"ETag", "d41d8cd98f00b204e9800998ecf8427e"} - }; - - var objRequest = new StorageObject(objectName, containerName); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), headers, HttpStatusCode.Created); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.CopyStorageObject(objRequest, targetContainerName); - - Assert.IsNotNull(result); - Assert.AreEqual(objectName, result.Name); - Assert.AreEqual(containerName, result.ContainerName); - Assert.AreEqual(0, result.Length); //length of content stream - Assert.AreEqual("application/octet-stream", result.ContentType); - Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", result.ETag); - Assert.AreEqual(DateTime.Parse("Wed, 12 Mar 2014 23:42:23 GMT"), result.LastModified); - } - - [TestMethod] - public async Task CanCopyStorageObjectWithFoldersAndCreatedResponse() - { - var containerName = "TestContainer"; - var objectName = "a/b/TestObject"; - var targetContainerName = "TargetTestContainer"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "0"}, - {"Content-Type", "application/octet-stream"}, - {"X-Copied-From-Last-Modified","Wed, 12 Mar 2014 22:42:23 GMT"}, - {"X-Copied-From" , "TestContainer/a/b/TestObject"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"ETag", "d41d8cd98f00b204e9800998ecf8427e"} - }; - - var objRequest = new StorageObject(objectName, containerName); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), headers, HttpStatusCode.Created); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - var result = await client.CopyStorageObject(objRequest, targetContainerName); - - Assert.IsNotNull(result); - Assert.AreEqual(objectName, result.FullName); - Assert.AreEqual(containerName, result.ContainerName); - Assert.AreEqual(0, result.Length); - Assert.AreEqual("application/octet-stream", result.ContentType); - Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", result.ETag); - Assert.AreEqual(DateTime.Parse("Wed, 12 Mar 2014 23:42:23 GMT"), result.LastModified); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenCopyingaStorageObjectWithMissingLength() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - var targetContainerName = "TargetTestContainer"; - - var objRequest = new StorageObject(objectName, containerName); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.LengthRequired); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.CopyStorageObject(objRequest, targetContainerName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenCopyingaStorageObjectWithBadETag() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - var targetContainerName = "TargetTestContainer"; - - var objRequest = new StorageObject(objectName, containerName); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), (HttpStatusCode)422); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.CopyStorageObject(objRequest, targetContainerName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenCopyingaStorageObjectWithBadAuth() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - var targetContainerName = "TargetTestContainer"; - - var objRequest = new StorageObject(objectName, containerName); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.CopyStorageObject(objRequest, targetContainerName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenCopyingaStorageObjectHasInternalServerError() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - var targetContainerName = "TargetTestContainer"; - - var objRequest = new StorageObject(objectName, containerName); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.CopyStorageObject(objRequest, targetContainerName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenCopyingaStorageObjectTimesOut() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - var targetContainerName = "TargetTestContainer"; - - var objRequest = new StorageObject(objectName, containerName); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.RequestTimeout); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.CopyStorageObject(objRequest, targetContainerName); - } - #endregion - - #region Create Storage Folder Tests - - [TestMethod] - public async Task CanCreateStorageFolderWithCreatedResponse() - { - var containerName = "TestContainer"; - var folderName = "a/b/b/"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"ETag", "d41d8cd98f00b204e9800998ecf8427e"} - }; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), headers, HttpStatusCode.Created); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.CreateStorageFolder(containerName, folderName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenCreatingaStorageFolderMissingLength() - { - var containerName = "TestContainer"; - var folderName = "a/b/b/"; - - var headers = new HttpHeadersAbstraction() - { - {"Content-Length", "1234"}, - {"Content-Type", "application/octet-stream"}, - {"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}, - {"ETag", "d41d8cd98f00b204e9800998ecf8427e"} - }; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), headers, HttpStatusCode.LengthRequired); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.CreateStorageFolder(containerName, folderName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenCreatingaStorageFolderWithBadETag() - { - var containerName = "TestContainer"; - var folderName = "a/b/b/"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), (HttpStatusCode)422); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.CreateStorageFolder(containerName, folderName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenCreatingaStorageFolderWithBadAuth() - { - var containerName = "TestContainer"; - var folderName = "a/b/b/"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.CreateStorageFolder(containerName, folderName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenCreatingaStorageFolderHasInternalServerError() - { - var containerName = "TestContainer"; - var folderName = "a/b/b/"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.CreateStorageFolder(containerName, folderName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenCreatingaStorageFolderTimesOut() - { - var containerName = "TestContainer"; - var folderName = "a/b/b/"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.RequestTimeout); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.CreateStorageFolder(containerName, folderName); - } - - #endregion - - #region Create Storage Container Tests - - [TestMethod] - public async Task CanCreateStorageContainerWithCreatedResponse() - { - var containerName = "TestContainer"; - - var headers = new HttpHeadersAbstraction - { - {"X-Container-Bytes-Used", "12345"}, - {"X-Container-Object-Count", "1"} - }; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), headers, HttpStatusCode.Created); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var containerReq = new StorageContainer(containerName, new Dictionary()); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.CreateStorageContainer(containerReq); - - //Assert.IsNotNull(container); - //Assert.AreEqual(containerName, container.Name); - //Assert.AreEqual(12345, container.TotalBytesUsed); - } - - [TestMethod] - public async Task CanCreateStorageContainerWithNoContentResponse() - { - var containerName = "TestContainer"; - - var headers = new HttpHeadersAbstraction - { - {"X-Container-Bytes-Used", "12345"}, - {"X-Container-Object-Count", "1"} - }; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), headers, HttpStatusCode.NoContent); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var containerReq = new StorageContainer(containerName, new Dictionary()); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.CreateStorageContainer(containerReq); - - //Assert.IsNotNull(container); - //Assert.AreEqual(containerName, container.Name); - //Assert.AreEqual(12345, container.TotalBytesUsed); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenCreatingaStorageContainerWithBadAuth() - { - var containerName = "TestContainer"; - - var containerReq = new StorageContainer(containerName, new Dictionary()); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.CreateStorageContainer(containerReq); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenCreatingaStorageContainerHasInternalServerError() - { - var containerName = "TestContainer"; - - var containerReq = new StorageContainer(containerName, new Dictionary()); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.CreateStorageContainer(containerReq); - } - - #endregion - - #region Delete Storage Container Tests - - [TestMethod] - public async Task CanDeleteStorageContainerWithNoContentResponse() - { - var containerName = "TestContainer"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.NoContent); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteStorageContainer(containerName); - } - - [TestMethod] - public async Task CanDeleteStorageContainerWithOkResponse() - { - var containerName = "TestContainer"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.OK); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteStorageContainer(containerName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenDeletingAStorageContainerWithObjects() - { - var containerName = "TestContainer"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Conflict); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteStorageContainer(containerName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenDeletingAStorageContainerWithBadAuth() - { - var containerName = "TestContainer"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteStorageContainer(containerName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenDeletingAStorageContainerWithInternalServerError() - { - var containerName = "TestContainer"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteStorageContainer(containerName); - } - - #endregion - - #region Delete Storage Object Tests - - [TestMethod] - public async Task CanDeleteStorageObjectWithNoContentResponse() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.NoContent); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteStorageObject(containerName, objectName); - } - - [TestMethod] - public async Task CanDeleteStorageObjectWithOkResponse() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.OK); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteStorageObject(containerName, objectName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenDeletingAStorageObjectWithBadAuth() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteStorageObject(containerName, objectName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenDeletingAStorageObjectWithInternalServerError() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteStorageObject(containerName, objectName); - } - - #endregion - - #region Delete Storage Folder Tests - - [TestMethod] - public async Task CanDeleteStorageFolderWithNoContentResponse() - { - var containerName = "TestContainer"; - var folderName = "a/b/c/"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.NoContent); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteStorageFolder(containerName, folderName); - } - - [TestMethod] - public async Task CanDeleteStorageFolderWithOkResponse() - { - var containerName = "TestContainer"; - var folderName = "a/b/c/"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.OK); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteStorageFolder(containerName, folderName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenDeletingAStorageFolderThatHasChildren() - { - var containerName = "TestContainer"; - var folderName = "a/b/c/"; - var headers = new HttpHeadersAbstraction() - { - {"X-Container-Bytes-Used", "1234"}, - {"X-Container-Object-Count", "1"} - }; - - var payload = @"[ - { - ""hash"": ""d41d8cd98f00b204e9800998ecf8427e"", - ""last_modified"": ""2014-03-07T21:31:31.588170"", - ""bytes"": 0, - ""name"": ""a/b/c/BLAH"", - ""content_type"": ""application/octet-stream"" - }]"; - - var content = TestHelper.CreateStream(payload); - - var restResp = new HttpResponseAbstraction(content, headers, HttpStatusCode.OK); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteStorageFolder(containerName, folderName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenDeletingAStorageFolderWithBadAuth() - { - var containerName = "TestContainer"; - var folderName = "a/b/c/"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteStorageFolder(containerName, folderName); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenDeletingAStorageFolderWithInternalServerError() - { - var containerName = "TestContainer"; - var folderName = "a/b/c/"; - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.DeleteStorageFolder(containerName, folderName); - } - - #endregion - - #region Update Storage Container Tests - - [TestMethod] - public async Task CanUpdateAStorageContainerWithNoContentResponse() - { - var containerName = "TestContainer"; - var containerReq = new StorageContainer(containerName, new Dictionary()); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.NoContent); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.UpdateStorageContainer(containerReq); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenUpdatingAStorageContainerWithBadAuth() - { - var containerName = "TestContainer"; - var containerReq = new StorageContainer(containerName, new Dictionary()); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.UpdateStorageContainer(containerReq); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenUpdatingAStorageContainerWithInternalServerError() - { - var containerName = "TestContainer"; - var containerReq = new StorageContainer(containerName, new Dictionary()); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.UpdateStorageContainer(containerReq); - } - - #endregion - - #region Update Storage Object Tests - - [TestMethod] - public async Task CanUpdateAStorageObjectWithAcceptedResponse() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var objectReq = new StorageObject(containerName, objectName); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Accepted); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.UpdateStorageObject(objectReq); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenUpdatingAStorageObjectWithBadAuth() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var objectReq = new StorageObject(containerName, objectName); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.UpdateStorageObject(objectReq); - } - - [TestMethod] - [ExpectedException(typeof(InvalidOperationException))] - public async Task ExceptionThrownWhenUpdatingAStorageObjectWithInternalServerError() - { - var containerName = "TestContainer"; - var objectName = "TestObject"; - - var objectReq = new StorageObject(containerName, objectName); - - var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError); - this.StorageServiceRestClient.Responses.Enqueue(restResp); - - var client = new StorageServicePocoClient(GetValidContext(), this.ServiceLocator); - await client.UpdateStorageObject(objectReq); - } - - #endregion - } -} diff --git a/OpenStack/OpenStack.Test/Storage/StorageServiceRestClientTests.cs b/OpenStack/OpenStack.Test/Storage/StorageServiceRestClientTests.cs deleted file mode 100644 index 6e7468f..0000000 --- a/OpenStack/OpenStack.Test/Storage/StorageServiceRestClientTests.cs +++ /dev/null @@ -1,1558 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Security.Cryptography; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using OpenStack.Common.Http; -using OpenStack.Common.ServiceLocation; -using OpenStack.Identity; -using OpenStack.Storage; - -namespace OpenStack.Test.Storage -{ - [TestClass] - public class StorageServiceRestClientTests - { - internal StorageRestSimulator simulator; - internal string authId = "12345"; - internal Uri endpoint = new Uri("http://teststorageendpoint.com/v1/1234567890"); - internal IServiceLocator ServiceLocator; - - [TestInitialize] - public void TestSetup() - { - this.simulator = new StorageRestSimulator(); - this.ServiceLocator = new ServiceLocator(); - - var manager = this.ServiceLocator.Locate(); - manager.RegisterServiceInstance(typeof(IHttpAbstractionClientFactory), new StorageRestSimulatorFactory(simulator)); - } - - [TestCleanup] - public void TestCleanup() - { - this.simulator = new StorageRestSimulator(); - this.ServiceLocator = new ServiceLocator(); - } - - ServiceClientContext GetValidContext() - { - return GetValidContext(CancellationToken.None); - } - - ServiceClientContext GetValidContext(CancellationToken token) - { - var creds = new OpenStackCredential(this.endpoint, "SomeUser", "Password", "SomeTenant", "region-a.geo-1"); - creds.SetAccessTokenId(this.authId); - - return new ServiceClientContext(creds, token, "Object Storage", endpoint); - } - - #region CreateManifest Tests - - [TestMethod] - public async Task CreateStaticStorageManifestIncludesAuthHeader() - { - var manifestName = "NewManifest"; - var containerName = "newContainer"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - var data = "Some random data"; - var content = TestHelper.CreateStream(data); - - await client.CreateStaticManifest(containerName, manifestName, new Dictionary(), content); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task CreateDynamicStorageManifestIncludesAuthHeader() - { - var manifestName = "NewManifest"; - var segPath = "blah/blah"; - var containerName = "newContainer"; - - var client = new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.CreateDynamicManifest(containerName, manifestName, new Dictionary(), segPath); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task CreateStaticManifestFormsCorrectUrlAndMethod() - { - var manifestName = "NewManifest"; - var containerName = "newContainer"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - var data = "Some random data"; - var content = TestHelper.CreateStream(data); - - await client.CreateStaticManifest(containerName, manifestName, new Dictionary(), content); - - Assert.AreEqual(string.Format("{0}/{1}/{2}?multipart-manifest=put", endpoint, containerName, manifestName), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Put, this.simulator.Method); - } - - [TestMethod] - public async Task CreateDynamicManifestFormsCorrectUrlMethodAndHeader() - { - var manifestName = "NewManifest"; - var segPath = "blah/blah"; - var containerName = "newContainer"; - - var client = new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.CreateDynamicManifest(containerName, manifestName, new Dictionary(), segPath); - - Assert.AreEqual(string.Format("{0}/{1}/{2}", endpoint, containerName, manifestName), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Put, this.simulator.Method); - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Object-Manifest")); - Assert.AreEqual(segPath, this.simulator.Headers["X-Object-Manifest"]); - } - - #endregion - - #region CreateObject Tests - - [TestMethod] - public async Task CreateStorageObjectIncludesAuthHeader() - { - - var objectName = "NewObject"; - var containerName = "newContainer"; - - - var client = new StorageServiceRestClientFactory().Create(GetValidContext(), this.ServiceLocator) as StorageServiceRestClient; - - var data = "Some random data"; - var content = TestHelper.CreateStream(data); - - await client.CreateObject(containerName, objectName, new Dictionary(), content); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task CreateStorageObjectFormsCorrectUrlAndMethod() - { - var objectName = "NewObject"; - var containerName = "newContainer"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - var data = "Some random data"; - var content = TestHelper.CreateStream(data); - - await client.CreateObject(containerName, objectName, new Dictionary(), content); - - Assert.AreEqual(string.Format("{0}/{1}/{2}", endpoint, containerName, objectName), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Put, this.simulator.Method); - } - - [TestMethod] - public async Task CanCreateStorageObject() - { - var objectName = "NewObject"; - var containerName = "newContainer"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - var data = "Some random data"; - var content = TestHelper.CreateStream(data); - - var resp = await client.CreateObject(containerName, objectName, new Dictionary(), content); - - Assert.AreEqual(HttpStatusCode.Created, resp.StatusCode); - Assert.IsTrue(this.simulator.Objects.ContainsKey(objectName)); - - var objectContent = TestHelper.GetStringFromStream(this.simulator.Objects[objectName].Content); - Assert.AreEqual(data,objectContent); - } - - [TestMethod] - public async Task CreatingStorageObjectMultipleTimesOverwrites() - { - var containerName = "newContainer"; - var objectName = "NewObject"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var data = "Some random data"; - var content = TestHelper.CreateStream(data); - - var resp = await client.CreateObject(containerName, objectName, new Dictionary(), content); - - Assert.AreEqual(HttpStatusCode.Created, resp.StatusCode); - Assert.IsTrue(this.simulator.Objects.ContainsKey(objectName)); - - var otherData = "Other data that is longer"; - var otherContent = TestHelper.CreateStream(otherData); - - resp = await client.CreateObject(containerName, objectName, new Dictionary(), otherContent); - - Assert.AreEqual(HttpStatusCode.Created, resp.StatusCode); - Assert.IsTrue(this.simulator.Objects.ContainsKey(objectName)); - - var objectContent = TestHelper.GetStringFromStream(this.simulator.Objects[objectName].Content); - Assert.AreEqual(otherData, objectContent); - } - - [TestMethod] - public async Task CreatedStorageObjectHasETag() - { - var objectName = "NewObject"; - var containerName = "newContainer"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - var data = "Some random data"; - var content = TestHelper.CreateStream(data); - var hash = Convert.ToBase64String(MD5.Create().ComputeHash(content)); - content.Position = 0; - - var resp = await client.CreateObject(containerName, objectName, new Dictionary(), content); - - Assert.AreEqual(HttpStatusCode.Created, resp.StatusCode); - - Assert.IsTrue(resp.Headers.Any(kvp => kvp.Key == "ETag")); - Assert.AreEqual(hash, resp.Headers.First(kvp => kvp.Key == "ETag").Value.First()); - - Assert.IsTrue(this.simulator.Objects.ContainsKey(objectName)); - - var objectContent = TestHelper.GetStringFromStream(this.simulator.Objects[objectName].Content); - Assert.AreEqual(data, objectContent); - } - - [TestMethod] - public async Task CanCreateStorageObjectWithMetaData() - { - var objectName = "NewObject"; - var containerName = "newContainer"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - var data = "Some random data"; - var content = TestHelper.CreateStream(data); - - var metaData = new Dictionary {{"Test1", "Test1"}, {"Test2", "Test2"}}; - - var resp = await client.CreateObject(containerName, objectName, metaData, content); - - Assert.AreEqual(HttpStatusCode.Created, resp.StatusCode); - Assert.IsTrue(this.simulator.Objects.ContainsKey(objectName)); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Object-Meta-Test1")); - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Object-Meta-Test2")); - Assert.AreEqual("Test1", this.simulator.Headers["X-Object-Meta-Test1"]); - Assert.AreEqual("Test2", this.simulator.Headers["X-Object-Meta-Test2"]); - - var objectContent = TestHelper.GetStringFromStream(this.simulator.Objects[objectName].Content); - Assert.AreEqual(data, objectContent); - } - - [TestMethod] - public async Task CreateStorageObjectWithTrailingForwardSlashesInName() - { - var objectName = "NewObject/////"; - var containerName = "newContainer"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - var data = "Some random data"; - var content = TestHelper.CreateStream(data); - - var resp = await client.CreateObject(containerName, objectName, new Dictionary(), content); - - Assert.AreEqual(string.Format("{0}/{1}/{2}", endpoint, containerName, objectName), this.simulator.Uri.ToString()); - - Assert.AreEqual(HttpStatusCode.Created, resp.StatusCode); - Assert.IsTrue(this.simulator.Objects.ContainsKey(objectName)); - - var objectContent = TestHelper.GetStringFromStream(this.simulator.Objects[objectName].Content); - Assert.AreEqual(data, objectContent); - } - - [TestMethod] - public async Task CreateStorageObjectWithLeadingForwardSlashesInName() - { - var objectName = "//NewObject"; - var containerName = "newContainer"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - var data = "Some random data"; - var content = TestHelper.CreateStream(data); - - var resp = await client.CreateObject(containerName, objectName, new Dictionary(), content); - - Assert.AreEqual(string.Format("{0}/{1}/{2}", endpoint, containerName, objectName), this.simulator.Uri.ToString()); - - Assert.AreEqual(HttpStatusCode.Created, resp.StatusCode); - Assert.IsTrue(this.simulator.Objects.ContainsKey(objectName)); - - var objectContent = TestHelper.GetStringFromStream(this.simulator.Objects[objectName].Content); - Assert.AreEqual(data, objectContent); - } - - [TestMethod] - public async Task CreateStorageObjectWithForwardSlashesInName() - { - var objectName = "New/Object"; - var containerName = "newContainer"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - var data = "Some random data"; - var content = TestHelper.CreateStream(data); - - var resp = await client.CreateObject(containerName, objectName, new Dictionary(), content); - - Assert.AreEqual(string.Format("{0}/{1}/{2}", this.endpoint, containerName, objectName), this.simulator.Uri.ToString()); - - Assert.AreEqual(HttpStatusCode.Created, resp.StatusCode); - Assert.IsTrue(this.simulator.Objects.ContainsKey(objectName)); - - var objectContent = TestHelper.GetStringFromStream(this.simulator.Objects[objectName].Content); - Assert.AreEqual(data, objectContent); - } - - [TestMethod] - public async Task CreateStorageObjectWithNullContent() - { - var objectName = "NewObject/////"; - var containerName = "newContainer"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.CreateObject(containerName, objectName, new Dictionary(), null); - - Assert.AreEqual(HttpStatusCode.Created, resp.StatusCode); - Assert.IsTrue(this.simulator.Objects.ContainsKey(objectName)); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CreateStorageObjectWithSlashesInContainerName() - { - var objectName = "NewObject"; - var containerName = "new/Container"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.CreateObject(containerName, objectName, new Dictionary(), null); - } - - [TestMethod] - public async Task TryingToCreateAnObjectWithBadAuthenticationFails() - { - var authId = "54321"; - var objectName = "NewObject"; - var containerName = "newContainer"; - - var context = GetValidContext(); - context.Credential.SetAccessTokenId(authId); - var client = - new StorageServiceRestClient(context, this.ServiceLocator); - - var data = "Some random data"; - var content = TestHelper.CreateStream(data); - - var resp = await client.CreateObject(containerName, objectName, new Dictionary(), content); - - Assert.AreEqual(HttpStatusCode.Unauthorized, resp.StatusCode); - Assert.IsFalse(this.simulator.Objects.ContainsKey(objectName)); - } - - [TestMethod] - public async Task TryingToCreateAnObjectAndCancelThrowsException() - { - var objectName = "NewObject"; - var containerName = "newContainer"; - var token = new CancellationToken(true); - this.simulator.Delay = TimeSpan.FromMilliseconds(500); - - var client = - new StorageServiceRestClient(GetValidContext(token), this.ServiceLocator); - var data = "Some random data"; - var content = TestHelper.CreateStream(data); - - try - { - await client.CreateObject(containerName, objectName, new Dictionary(), content); - } - catch (Exception ex) - { - Assert.IsInstanceOfType(ex,typeof(OperationCanceledException)); - Assert.IsFalse(this.simulator.Objects.ContainsKey(objectName)); - } - } - - #endregion - - #region Create Container Tests - - [TestMethod] - public async Task CreateStorageContainerIncludesAuthHeader() - { - var containerName = "newContainer"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.CreateContainer(containerName, new Dictionary()); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task CreateStorageContainerFormsCorrectUrlAndMethod() - { - var containerName = "newContainer"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.CreateContainer(containerName, new Dictionary()); - - Assert.AreEqual(string.Format("{0}/{1}", endpoint, containerName), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Put, this.simulator.Method); - } - - [TestMethod] - public async Task CanCreateStorageContainer() - { - var containerName = "newContainer"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.CreateContainer(containerName, new Dictionary()); - - Assert.AreEqual(HttpStatusCode.Created, resp.StatusCode); - Assert.IsTrue(this.simulator.Containers.ContainsKey(containerName)); - } - - [TestMethod] - [ExpectedException(typeof(ArgumentException))] - public async Task CreateStorageConainerWithSlashesInContainerName() - { - var containerName = "new/Container"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.CreateContainer(containerName, new Dictionary()); - } - - [TestMethod] - public async Task CanCreateStorageContainerWithMetaData() - { - var containerName = "newContainer"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var metaData = new Dictionary { { "Test1", "Test1" }, { "Test2", "Test2" } }; - - var resp = await client.CreateContainer(containerName, metaData); - - Assert.AreEqual(HttpStatusCode.Created, resp.StatusCode); - Assert.IsTrue(this.simulator.Containers.ContainsKey(containerName)); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Container-Meta-Test1")); - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Container-Meta-Test2")); - Assert.AreEqual("Test1", this.simulator.Headers["X-Container-Meta-Test1"]); - Assert.AreEqual("Test2", this.simulator.Headers["X-Container-Meta-Test2"]); - } - - [TestMethod] - public async Task CreatingStorageContainerMultipleTimesOverwrites() - { - var containerName = "newContainer"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.CreateContainer(containerName, new Dictionary()); - - Assert.AreEqual(HttpStatusCode.Created, resp.StatusCode); - Assert.IsTrue(this.simulator.Containers.ContainsKey(containerName)); - - var metaData = new Dictionary { { "Test1", "Test1" }, { "Test2", "Test2" } }; - - resp = await client.CreateContainer(containerName, metaData); - - Assert.AreEqual(HttpStatusCode.Accepted, resp.StatusCode); - Assert.IsTrue(this.simulator.Containers.ContainsKey(containerName)); - Assert.IsTrue(this.simulator.Containers[containerName].MetaData.ContainsKey("X-Container-Meta-Test1")); - } - - #endregion - - #region Get Container Tests - - [TestMethod] - public async Task GetStorageContainerIncludesAuthHeader() - { - var containerName = "newContainer"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetContainer(containerName); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task GetStorageContainerFormsCorrectUrlAndMethod() - { - var containerName = "newContainer"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetContainer(containerName); - - Assert.AreEqual(string.Format("{0}/{1}", endpoint, containerName), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Get, this.simulator.Method); - } - - [TestMethod] - public async Task ErrorIsReturnedWhenContainerIsNotFound() - { - var containerName = "newContainer"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetContainer(containerName); - - Assert.AreEqual(HttpStatusCode.NotFound, resp.StatusCode); - - //Add some assert here to validate that we got all the headers we expected... - } - - [TestMethod] - public async Task CanGetStorageContainer() - { - var containerName = "newContainer"; - - this.simulator.Containers.Add(containerName, new StorageRestSimulator.StorageItem(containerName)); - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetContainer(containerName); - - Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); - - //Add some assert here to validate that we got all the headers we expected... - } - - [TestMethod] - public async Task CanGetStorageContainerWithMetadata() - { - var containerName = "newContainer"; - - var metaData = new Dictionary { { "X-Object-Meta-Test1", "Test1" }, { "X-Object-Meta-Test2", "Test2" } }; - - this.simulator.Containers.Add(containerName, new StorageRestSimulator.StorageItem(containerName) { MetaData = metaData}); - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetContainer(containerName); - - Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); - - - Assert.IsTrue(resp.Headers.Any(kvp => kvp.Key == "X-Object-Meta-Test2")); - Assert.AreEqual("Test2", resp.Headers.First(kvp => kvp.Key == "X-Object-Meta-Test2").Value.First()); - } - - #endregion - - #region Get Storage Object Tests - - [TestMethod] - public async Task GetStorageObjectIncludesAuthHeader() - { - var containerName = "newContainer"; - var objectName = "newObject"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetObject(containerName, objectName); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task GetStorageObjectFormsCorrectUrlAndMethod() - { - var containerName = "newContainer"; - var objectName = "newObject"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetObject(containerName, objectName); - - Assert.AreEqual(string.Format("{0}/{1}/{2}", endpoint, containerName, objectName), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Get, this.simulator.Method); - } - - [TestMethod] - public async Task ErrorIsReturnedWhenObjectIsNotFound() - { - var containerName = "newContainer"; - var objectName = "newObject"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetObject(containerName, objectName); - - Assert.AreEqual(HttpStatusCode.NotFound, resp.StatusCode); - } - - [TestMethod] - public async Task CanGetStorageObject() - { - var containerName = "newContainer"; - var objectName = "newObject"; - var data = "Some Data"; - - var content = TestHelper.CreateStream(data); - var hash = Convert.ToBase64String(MD5.Create().ComputeHash(content)); - content.Position = 0; - - this.simulator.Objects.Add(objectName, new StorageRestSimulator.StorageItem(objectName) { Content = content }); - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetObject(containerName, objectName); - - Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); - - var respContent = TestHelper.GetStringFromStream(resp.Content); - Assert.AreEqual(data, respContent); - - Assert.IsTrue(resp.Headers.Any(kvp => kvp.Key == "ETag")); - Assert.AreEqual(hash, resp.Headers.First(kvp => kvp.Key == "ETag").Value.First()); - } - - [TestMethod] - public async Task CanGetStorageObjectWithMetadata() - { - var containerName = "newContainer"; - var objectName = "newObject"; - var data = "Some Data"; - - var content = TestHelper.CreateStream(data); - - var metaData = new Dictionary { { "X-Object-Meta-Test1", "Test1" }, { "X-Object-Meta-Test2", "Test2" }}; - - this.simulator.Objects.Add(objectName, new StorageRestSimulator.StorageItem(objectName) { MetaData = metaData, Content = content}); - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetObject(containerName, objectName); - - Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); - - Assert.IsTrue(resp.Headers.Any(kvp => kvp.Key == "X-Object-Meta-Test2")); - Assert.AreEqual("Test2", resp.Headers.First(kvp => kvp.Key == "X-Object-Meta-Test2").Value.First()); - - var respContent = TestHelper.GetStringFromStream(resp.Content); - Assert.AreEqual(data,respContent); - } - - #endregion - - #region Delete Storage Object Tests - - [TestMethod] - public async Task DeleteStorageObjectIncludesAuthHeader() - { - var containerName = "newContainer"; - var objectName = "newObject"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.DeleteObject(containerName, objectName); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task DeleteStorageObjectFormsCorrectUrlAndMethod() - { - var containerName = "newContainer"; - var objectName = "newObject"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.DeleteObject(containerName, objectName); - - Assert.AreEqual(string.Format("{0}/{1}/{2}", endpoint, containerName, objectName), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Delete, this.simulator.Method); - } - - [TestMethod] - public async Task ErrorIsReturnedWhenDeletingAnObjectThatIsNotFound() - { - var containerName = "newContainer"; - var objectName = "newObject"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.DeleteObject(containerName, objectName); - - Assert.AreEqual(HttpStatusCode.NotFound, resp.StatusCode); - } - - [TestMethod] - public async Task CanDeleteStorageObject() - { - var containerName = "newContainer"; - var objectName = "newObject"; - var data = "Some Data"; - - var content = TestHelper.CreateStream(data); - - this.simulator.Objects.Add(objectName, new StorageRestSimulator.StorageItem(objectName) {Content = content}); - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.DeleteObject(containerName, objectName); - - Assert.AreEqual(HttpStatusCode.NoContent, resp.StatusCode); - Assert.IsFalse(this.simulator.Objects.ContainsKey(objectName)); - } - - #endregion - - #region Delete Container Tests - - [TestMethod] - public async Task DeleteStorageContainerIncludesAuthHeader() - { - var containerName = "newContainer"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.DeleteContainer(containerName); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task DeleteStorageContainerFormsCorrectUrlAndMethod() - { - var containerName = "newContainer"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.DeleteContainer(containerName); - - Assert.AreEqual(string.Format("{0}/{1}", endpoint, containerName), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Delete, this.simulator.Method); - } - - [TestMethod] - public async Task ErrorIsReturnedWhenDeletingAContainerThatIsNotFound() - { - var containerName = "newContainer"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.DeleteContainer(containerName); - - Assert.AreEqual(HttpStatusCode.NotFound, resp.StatusCode); - } - - [TestMethod] - public async Task ErrorIsReturnedWhenDeletingAContainerThatIsNotEmpty() - { - var containerName = "newContainer"; - - this.simulator.Containers.Add(containerName, new StorageRestSimulator.StorageItem(containerName)); - this.simulator.IsContainerEmpty = false; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.DeleteContainer(containerName); - - Assert.AreEqual(HttpStatusCode.Conflict, resp.StatusCode); - Assert.IsTrue(this.simulator.Containers.ContainsKey(containerName)); - } - - [TestMethod] - public async Task CanDeleteStorageContainer() - { - var containerName = "newContainer"; - - this.simulator.Containers.Add(containerName, new StorageRestSimulator.StorageItem(containerName)); - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.DeleteContainer(containerName); - - Assert.AreEqual(HttpStatusCode.NoContent, resp.StatusCode); - Assert.IsFalse(this.simulator.Containers.ContainsKey(containerName)); - } - - #endregion - - #region Update Storage Object Tests - - [TestMethod] - public async Task UpdateStorageObjectIncludesAuthHeader() - { - var containerName = "newContainer"; - var objectName = "newObject"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var metadata = new Dictionary { { "Test1", "Test1" }, { "Test2", "Test2" } }; - - await client.UpdateObject(containerName, objectName, metadata); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task UpdateStorageObjectFormsCorrectUrlAndMethod() - { - var containerName = "newContainer"; - var objectName = "newObject"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var metadata = new Dictionary { { "Test1", "Test1" }, { "Test2", "Test2" } }; - - await client.UpdateObject(containerName, objectName, metadata); - - Assert.AreEqual(string.Format("{0}/{1}/{2}", endpoint, containerName, objectName), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Post, this.simulator.Method); - } - - [TestMethod] - public async Task ErrorIsReturnedWhenUpdatingAnObjectThatIsNotFound() - { - var containerName = "newContainer"; - var objectName = "newObject"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var metadata = new Dictionary { { "Test1", "Test1" }, { "Test2", "Test2" } }; - - var resp = await client.UpdateObject(containerName, objectName, metadata); - - Assert.AreEqual(HttpStatusCode.NotFound, resp.StatusCode); - } - - public async Task CanUpdateAStorageObject() - { - var containerName = "newContainer"; - var objectName = "newObject"; - - var origMetaData = new Dictionary { { "X-Object-Meta-Test1", "Test1" }}; - - this.simulator.Objects.Add(objectName, new StorageRestSimulator.StorageItem(objectName) { MetaData = origMetaData }); - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var metadata = new Dictionary { { "Test2", "Test2" } }; - - var resp = await client.UpdateObject(containerName, objectName, metadata); - - Assert.AreEqual(HttpStatusCode.Accepted, resp.StatusCode); - - Assert.IsTrue(resp.Headers.Any(kvp => kvp.Key == "X-Object-Meta-Test2")); - Assert.IsFalse(resp.Headers.Any(kvp => kvp.Key == "X-Object-Meta-Test1")); - Assert.AreEqual("Test2", resp.Headers.First(kvp => kvp.Key == "X-Object-Meta-Test2").Value.First()); - } - - #endregion - - #region Update Storage Container Tests - - [TestMethod] - public async Task UpdateStorageContainerIncludesAuthHeader() - { - var containerName = "newContainer"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var metadata = new Dictionary { { "Test1", "Test1" }, { "Test2", "Test2" } }; - - await client.UpdateContainer(containerName, metadata); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task UpdateStorageContainerFormsCorrectUrlAndMethod() - { - var containerName = "newContainer"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var metadata = new Dictionary { { "Test1", "Test1" }, { "Test2", "Test2" } }; - - await client.UpdateContainer(containerName, metadata); - - Assert.AreEqual(string.Format("{0}/{1}", endpoint, containerName), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Post, this.simulator.Method); - } - - [TestMethod] - public async Task ErrorIsReturnedWhenUpdatingAContainerThatIsNotFound() - { - var containerName = "newContainer"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var metadata = new Dictionary { { "Test1", "Test1" }, { "Test2", "Test2" } }; - - var resp = await client.UpdateContainer(containerName, metadata); - - Assert.AreEqual(HttpStatusCode.NotFound, resp.StatusCode); - } - - [TestMethod] - public async Task CanUpdateAStorageContainer() - { - var containerName = "newContainer"; - - var origMetaData = new Dictionary { { "X-Container-Meta-Test1", "Test1" } }; - - this.simulator.Containers.Add(containerName, new StorageRestSimulator.StorageItem(containerName) { MetaData = origMetaData }); - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var metadata = new Dictionary { { "Test2", "Test2" } }; - - var resp = await client.UpdateContainer(containerName, metadata); - Assert.AreEqual(HttpStatusCode.Accepted, resp.StatusCode); - - resp = await client.GetContainer(containerName); - - Assert.IsTrue(resp.Headers.Any(kvp => kvp.Key == "X-Container-Meta-Test2")); - Assert.IsFalse(resp.Headers.Any(kvp => kvp.Key == "X-Container-Meta-Test1")); - Assert.AreEqual("Test2", resp.Headers.First(kvp => kvp.Key == "X-Container-Meta-Test2").Value.First()); - } - - #endregion - - #region Get Storage Container Metadata Tests - - [TestMethod] - public async Task GetStorageContainerMetadataIncludesAuthHeader() - { - var containerName = "newContainer"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetContainerMetadata(containerName); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task GetStorageContainerMetadataFormsCorrectUrlAndMethod() - { - var containerName = "newContainer"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetContainerMetadata(containerName); - - Assert.AreEqual(string.Format("{0}/{1}", endpoint, containerName), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Head, this.simulator.Method); - } - - [TestMethod] - public async Task ErrorIsReturnedWhenGettingMetadataForAContainerThatIsNotFound() - { - var containerName = "newContainer"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetContainerMetadata(containerName); - - Assert.AreEqual(HttpStatusCode.NotFound, resp.StatusCode); - } - - [TestMethod] - public async Task CanGetMetadataForAStorageContainer() - { - var containerName = "newContainer"; - - var origMetaData = new Dictionary { { "X-Object-Meta-Test1", "Test1" } }; - - this.simulator.Containers.Add(containerName, new StorageRestSimulator.StorageItem(containerName) { MetaData = origMetaData }); - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetContainerMetadata(containerName); - - Assert.AreEqual(HttpStatusCode.NoContent, resp.StatusCode); - - Assert.IsTrue(resp.Headers.Any(kvp => kvp.Key == "X-Object-Meta-Test1")); - Assert.AreEqual("Test1", resp.Headers.First(kvp => kvp.Key == "X-Object-Meta-Test1").Value.First()); - } - - #endregion - - #region Get Storage Object Metadata Tests - - [TestMethod] - public async Task GetStorageObjectMetadataIncludesAuthHeader() - { - var containerName = "newContainer"; - var objectName = "newObject"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetObjectMetadata(containerName, objectName); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task GetStorageObjectMetadataFormsCorrectUrlAndMethod() - { - var containerName = "newContainer"; - var objectName = "newObject"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetObjectMetadata(containerName, objectName); - - Assert.AreEqual(string.Format("{0}/{1}/{2}", endpoint, containerName, objectName), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Head, this.simulator.Method); - } - - [TestMethod] - public async Task ErrorIsReturnedWhenGettingMetadataForAnObjectThatIsNotFound() - { - var containerName = "newContainer"; - var objectName = "newObject"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetObjectMetadata(containerName, objectName); - - Assert.AreEqual(HttpStatusCode.NotFound, resp.StatusCode); - } - - [TestMethod] - public async Task CanGetMetadataForAStorageObject() - { - var containerName = "newContainer"; - var objectName = "newObject"; - - var origMetaData = new Dictionary { { "X-Object-Meta-Test1", "Test1" } }; - var content = TestHelper.CreateStream("Some Data"); - - this.simulator.Objects.Add(objectName, new StorageRestSimulator.StorageItem(objectName) { MetaData = origMetaData, Content = content }); - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetObjectMetadata(containerName, objectName); - - Assert.AreEqual(HttpStatusCode.NoContent, resp.StatusCode); - - Assert.IsTrue(resp.Headers.Any(kvp => kvp.Key == "X-Object-Meta-Test1")); - Assert.AreEqual("Test1", resp.Headers.First(kvp => kvp.Key == "X-Object-Meta-Test1").Value.First()); - } - - #endregion - - #region Copy Storage Object Tests - - [TestMethod] - public async Task CopyStorageObjectMetadataIncludesAuthHeader() - { - var sourceContainerName = "oldContainer"; - var sourceObjectName = "oldObject"; - var targetContainerName = "newContainer"; - var targetObjectName = "newObject"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.CopyObject(sourceContainerName, sourceObjectName, targetContainerName, targetObjectName); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task CopyStorageObjectMetadataIncludesDestinationHeader() - { - var sourceContainerName = "oldContainer"; - var sourceObjectName = "oldObject"; - var targetContainerName = "newContainer"; - var targetObjectName = "newObject"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.CopyObject(sourceContainerName, sourceObjectName, targetContainerName, targetObjectName); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("Destination")); - Assert.AreEqual(string.Format("{0}/{1}", targetContainerName, targetObjectName), this.simulator.Headers["Destination"]); - } - - [TestMethod] - public async Task CopyStorageObjectMetadataFormsCorrectUrlAndMethod() - { - var sourceContainerName = "oldContainer"; - var sourceObjectName = "oldObject"; - var targetContainerName = "newContainer"; - var targetObjectName = "newObject"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.CopyObject(sourceContainerName, sourceObjectName, targetContainerName, targetObjectName); - - Assert.AreEqual(string.Format("{0}/{1}/{2}", endpoint, sourceContainerName, sourceObjectName), this.simulator.Uri.ToString()); - Assert.AreEqual(new HttpMethod("COPY"), this.simulator.Method); - } - - [TestMethod] - public async Task ErrorIsReturnedWhenCopyingAnObjectAndSourceObjectIsNotFound() - { - var sourceContainerName = "oldContainer"; - var sourceObjectName = "oldObject"; - var targetContainerName = "newContainer"; - var targetObjectName = "newObject"; - - this.simulator.Containers.Add(sourceContainerName, new StorageRestSimulator.StorageItem(sourceContainerName)); - this.simulator.Containers.Add(targetContainerName, new StorageRestSimulator.StorageItem(targetContainerName)); - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.CopyObject(sourceContainerName, sourceObjectName, targetContainerName, targetObjectName); - - Assert.AreEqual(HttpStatusCode.NotFound, resp.StatusCode); - } - - [TestMethod] - public async Task ErrorIsReturnedWhenCopyingAnObjectAndSourceContainerIsNotFound() - { - var sourceContainerName = "oldContainer"; - var sourceObjectName = "oldObject"; - var targetContainerName = "newContainer"; - var targetObjectName = "newObject"; - - var origMetaData = new Dictionary { { "X-Object-Meta-Test1", "Test1" } }; - var content = TestHelper.CreateStream("Some Data"); - - this.simulator.Containers.Add(targetContainerName, new StorageRestSimulator.StorageItem(targetContainerName)); - this.simulator.Objects.Add(sourceObjectName, new StorageRestSimulator.StorageItem(sourceObjectName) { MetaData = origMetaData, Content = content }); - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.CopyObject(sourceContainerName, sourceObjectName, targetContainerName, targetObjectName); - - Assert.AreEqual(HttpStatusCode.NotFound, resp.StatusCode); - } - - [TestMethod] - public async Task ErrorIsReturnedWhenCopyingAnObjectAndDestinationContainerIsNotFound() - { - var sourceContainerName = "oldContainer"; - var sourceObjectName = "oldObject"; - var targetContainerName = "newContainer"; - var targetObjectName = "newObject"; - - var origMetaData = new Dictionary { { "X-Object-Meta-Test1", "Test1" } }; - var content = TestHelper.CreateStream("Some Data"); - - this.simulator.Containers.Add(sourceContainerName, new StorageRestSimulator.StorageItem(sourceContainerName)); - this.simulator.Objects.Add(sourceObjectName, new StorageRestSimulator.StorageItem(sourceObjectName) { MetaData = origMetaData, Content = content }); - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.CopyObject(sourceContainerName, sourceObjectName, targetContainerName, targetObjectName); - - Assert.AreEqual(HttpStatusCode.NotFound, resp.StatusCode); - } - - [TestMethod] - public async Task ErrorIsReturnedWhenTryingToCopyAContainer() - { - var sourceContainerName = "oldContainer"; - var sourceObjectName = "oldObject"; - var targetContainerName = "newContainer"; - var targetObjectName = ""; - - var origMetaData = new Dictionary { { "X-Object-Meta-Test1", "Test1" } }; - var content = TestHelper.CreateStream("Some Data"); - - this.simulator.Containers.Add(sourceContainerName, new StorageRestSimulator.StorageItem(sourceContainerName)); - this.simulator.Objects.Add(sourceObjectName, new StorageRestSimulator.StorageItem(sourceObjectName) { MetaData = origMetaData, Content = content }); - - var client = new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.CopyObject(sourceContainerName, sourceObjectName, targetContainerName, targetObjectName); - - Assert.AreEqual(HttpStatusCode.MethodNotAllowed, resp.StatusCode); - } - - [TestMethod] - public async Task CanCopyAStorageObject() - { - var sourceContainerName = "oldContainer"; - var sourceObjectName = "oldObject"; - var targetContainerName = "newContainer"; - var targetObjectName = "newObject"; - var data = "Some Data"; - - var origMetaData = new Dictionary { { "X-Object-Meta-Test1", "Test1" } }; - var content = TestHelper.CreateStream(data); - - this.simulator.Containers.Add(targetContainerName, new StorageRestSimulator.StorageItem(targetContainerName)); - this.simulator.Containers.Add(sourceContainerName, new StorageRestSimulator.StorageItem(sourceContainerName)); - this.simulator.Objects.Add(sourceObjectName, new StorageRestSimulator.StorageItem(sourceObjectName) { MetaData = origMetaData, Content = content }); - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.CopyObject(sourceContainerName, sourceObjectName, targetContainerName, targetObjectName); - - Assert.AreEqual(HttpStatusCode.Created, resp.StatusCode); - - Assert.IsTrue(this.simulator.Objects.ContainsKey(targetObjectName)); - - var obj = this.simulator.Objects[targetObjectName]; - Assert.AreEqual(data, TestHelper.GetStringFromStream(obj.Content)); - Assert.IsTrue(obj.MetaData.ContainsKey("X-Object-Meta-Test1")); - Assert.AreEqual("Test1", obj.MetaData["X-Object-Meta-Test1"]); - } - - #endregion - - #region Get AccountTests - - [TestMethod] - public async Task GetStorageAccountIncludesAuthHeader() - { - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetAccount(); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task GetStorageAccountFormsCorrectUrlAndMethod() - { - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetAccount(); - - Assert.AreEqual(string.Format("{0}", endpoint), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Get, this.simulator.Method); - } - - [TestMethod] - public async Task CanGetAccount() - { - this.simulator.Containers.Add("TestContainer", new StorageRestSimulator.StorageItem("TestContainer")); - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetAccount(); - - Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); - - var respContent = TestHelper.GetStringFromStream(resp.Content); - Assert.IsTrue(respContent.Length > 0); - - Assert.IsTrue(resp.Headers.Any(kvp => kvp.Key == "X-Account-Container-Count")); - Assert.IsTrue(resp.Headers.Any(kvp => kvp.Key == "X-Account-Object-Count")); - Assert.IsTrue(resp.Headers.Any(kvp => kvp.Key == "X-Account-Bytes-Used")); - } - - #endregion - - #region Get Storage Folder Tests - - [TestMethod] - public async Task GetStorageFolderIncludesAuthHeader() - { - var containerName = "newContainer"; - var folderName = "newFolder"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetFolder(containerName, folderName); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task GetStorageFolderFormsCorrectUrlAndMethod() - { - var containerName = "newContainer"; - var folderName = "a/b/b/"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetFolder(containerName, folderName); - - Assert.AreEqual(string.Format("{0}/{1}?delimiter=/&prefix={2}", endpoint, containerName, folderName), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Get, this.simulator.Method); - } - - [TestMethod] - public async Task GetRootStorageFolderFormsCorrectUrlAndMethod() - { - var containerName = "newContainer"; - var folderName = "/"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetFolder(containerName, folderName); - - Assert.AreEqual(string.Format("{0}/{1}?delimiter=/", endpoint, containerName), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Get, this.simulator.Method); - } - - [TestMethod] - public async Task ErrorIsReturnedWhenFolderIsNotFound() - { - var containerName = "newContainer"; - var folderName = "a/b/b/"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetFolder(containerName, folderName); - - Assert.AreEqual(HttpStatusCode.NotFound, resp.StatusCode); - } - - [TestMethod] - public async Task CanGetStorageFolder() - { - var containerName = "newContainer"; - var folderName = "a/b/b/"; - - var content = TestHelper.CreateStream(string.Empty); - content.Position = 0; - - this.simulator.Objects.Add(folderName, new StorageRestSimulator.StorageItem(folderName) { Content = content }); - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetFolder(containerName, folderName); - - Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); - } - - [TestMethod] - public async Task CanGetStorageFolderWithMetadata() - { - var containerName = "newContainer"; - var folderName = "a/b/b/"; - - var content = TestHelper.CreateStream(string.Empty); - content.Position = 0; - - var metaData = new Dictionary { { "X-Object-Meta-Test1", "Test1" }, { "X-Object-Meta-Test2", "Test2" } }; - - this.simulator.Objects.Add(folderName, new StorageRestSimulator.StorageItem(folderName) { MetaData = metaData, Content = content }); - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetFolder(containerName, folderName); - - Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); - - Assert.IsTrue(resp.Headers.Any(kvp => kvp.Key == "X-Object-Meta-Test2")); - Assert.AreEqual("Test2", resp.Headers.First(kvp => kvp.Key == "X-Object-Meta-Test2").Value.First()); - } - - #endregion - - #region Get Storage Manifest Tests - - [TestMethod] - public async Task GetStorageManifestIncludesAuthHeader() - { - var containerName = "newContainer"; - var manifestName = "newManifest"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetManifestMetadata(containerName, manifestName); - - Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token")); - Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]); - } - - [TestMethod] - public async Task GetStorageManifestFormsCorrectUrlAndMethod() - { - var containerName = "newContainer"; - var manifestName = "a/b/b/manifest"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - await client.GetManifestMetadata(containerName, manifestName); - - Assert.AreEqual(string.Format("{0}/{1}/{2}?multipart-manifest=get", endpoint, containerName, manifestName), this.simulator.Uri.ToString()); - Assert.AreEqual(HttpMethod.Get, this.simulator.Method); - } - - [TestMethod] - public async Task ErrorIsReturnedWhenManifestIsNotFound() - { - var containerName = "newContainer"; - var manifestName = "a/b/b/manifest"; - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetManifestMetadata(containerName, manifestName); - - Assert.AreEqual(HttpStatusCode.NotFound, resp.StatusCode); - } - - [TestMethod] - public async Task CanGetStorageManifest() - { - var containerName = "newContainer"; - var manifestName = "a/b/b/manifest"; - - var content = TestHelper.CreateStream("[]"); - content.Position = 0; - - this.simulator.Objects.Add(manifestName, new StorageRestSimulator.StorageItem(manifestName) { Content = content }); - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetManifestMetadata(containerName, manifestName); - - Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); - } - - [TestMethod] - public async Task CanGetStorageManifestWithMetadata() - { - var containerName = "newContainer"; - var manifestName = "a/b/b/manifest"; - - var content = TestHelper.CreateStream(string.Empty); - content.Position = 0; - - var metaData = new Dictionary { { "X-Object-Meta-Test1", "Test1" }, { "X-Object-Meta-Test2", "Test2" } }; - - this.simulator.Objects.Add(manifestName, new StorageRestSimulator.StorageItem(manifestName) { MetaData = metaData, Content = content }); - - var client = - new StorageServiceRestClient(GetValidContext(), this.ServiceLocator); - - var resp = await client.GetManifestMetadata(containerName, manifestName); - - Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode); - - Assert.IsTrue(resp.Headers.Any(kvp => kvp.Key == "X-Object-Meta-Test2")); - Assert.AreEqual("Test2", resp.Headers.First(kvp => kvp.Key == "X-Object-Meta-Test2").Value.First()); - } - - #endregion - } -} diff --git a/OpenStack/OpenStack.Test/Storage/TestLargeStorageObjectCreator.cs b/OpenStack/OpenStack.Test/Storage/TestLargeStorageObjectCreator.cs deleted file mode 100644 index 181d531..0000000 --- a/OpenStack/OpenStack.Test/Storage/TestLargeStorageObjectCreator.cs +++ /dev/null @@ -1,50 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading.Tasks; -using OpenStack.Storage; - -namespace OpenStack.Test.Storage -{ - public class TestLargeStorageObjectCreatorFactory : ILargeStorageObjectCreatorFactory - { - internal ILargeStorageObjectCreator creator; - - public TestLargeStorageObjectCreatorFactory(ILargeStorageObjectCreator creator) - { - this.creator = creator; - } - public ILargeStorageObjectCreator Create(IStorageServiceClient client) - { - return creator; - } - } - - public class TestLargeStorageObjectCreator : ILargeStorageObjectCreator - { - public Func, Stream, int, string, Task> CreateDelegate { get; set; } - - public async Task Create(string containerName, string objectName, IDictionary metadata, Stream content, int numberOfSegments, - string segmentsContainer) - { - return - await CreateDelegate(containerName, objectName, metadata, content, numberOfSegments, segmentsContainer); - } - } -} diff --git a/OpenStack/OpenStack.Test/Storage/TestStorageManifest.cs b/OpenStack/OpenStack.Test/Storage/TestStorageManifest.cs deleted file mode 100644 index 0f20985..0000000 --- a/OpenStack/OpenStack.Test/Storage/TestStorageManifest.cs +++ /dev/null @@ -1,34 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using OpenStack.Storage; - -namespace OpenStack.Test.Storage -{ - public class TestStorageManifest : StorageManifest - { - public new string ContainerName { get; set; } - - public new string FullName { get; set; } - - public TestStorageManifest(string container, string name) - : base(container, name) - { - this.ContainerName = container; - this.FullName = name; - } - } -} diff --git a/OpenStack/OpenStack.Test/Storage/TestStorageServiceClient.cs b/OpenStack/OpenStack.Test/Storage/TestStorageServiceClient.cs deleted file mode 100644 index 56b6891..0000000 --- a/OpenStack/OpenStack.Test/Storage/TestStorageServiceClient.cs +++ /dev/null @@ -1,180 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading.Tasks; -using OpenStack.Storage; - -namespace OpenStack.Test.Storage -{ - public class TestStorageServiceClient : IStorageServiceClient - { - public long LargeObjectThreshold { get; set; } - public int LargeObjectSegments { get; set; } - public string LargeObjectSegmentContainer { get; set; } - - public Func, Task> CreateStorageContainerDelegate { get; set; } - - public Func> GetStorageContainerDelegate { get; set; } - - public Func DeleteContainerDelegate { get; set; } - - public Func UpdateStorageContainerDelegate { get; set; } - - public Func>> ListStorageObjectsDelegate { get; set; } - - public Func>> ListStorageContainersDelegate { get; set; } - - public Func> GetStorageAccountDelegate { get; set; } - - public Func, Stream, Task> CreateStorageObjectDelegate { get; set; } - - public Func> CopyStorageObjectDelegate { get; set; } - - public Func, Stream, int, Task> CreateLargeStorageObjectDelegate { get; set; } - - public Func> GetStorageObjectDelegate { get; set; } - - public Func> DownloadStorageObjectDelegate { get; set; } - - public Func DeleteStorageObjectDelegate { get; set; } - - public Func UpdateStorageObjectDelegate { get; set; } - - public Func, IEnumerable, Task> CreateStaticStorageManifestDelegate { get; set; } - - public Func, string, Task> CreateDynamicStorageManifestDelegate { get; set; } - - public Func> GetStorageManifestDelegate { get; set; } - - public Func> GetStorageFolderDelegate { get; set; } - - public Func CreateStorageFolderDelegate { get; set; } - - public Func DeleteStorageFolderDelegate { get; set; } - - public Func GetPublicEndpointDelegate { get; set; } - - public Uri GetPublicEndpoint() - { - return GetPublicEndpointDelegate(); - } - - public async Task CreateStorageContainer(string containerName, IDictionary metadata) - { - await CreateStorageContainerDelegate(containerName, metadata); - } - - public async Task GetStorageContainer(string containerName) - { - return await GetStorageContainerDelegate(containerName); - } - - public async Task DeleteStorageContainer(string containerName) - { - await DeleteContainerDelegate(containerName); - } - - public async Task UpdateStorageContainer(StorageContainer container) - { - await UpdateStorageContainerDelegate(container); - } - - public async Task> ListStorageObjects(string containerName) - { - return await ListStorageObjectsDelegate(containerName); - } - - public async Task> ListStorageContainers() - { - return await ListStorageContainersDelegate(); - } - - public async Task GetStorageAccount() - { - return await GetStorageAccountDelegate(); - } - - public async Task CreateStorageObject(string containerName, string objectName, IDictionary metadata, Stream content) - { - return await CreateStorageObjectDelegate(containerName, objectName, metadata, content); - } - - public async Task CopyStorageObject(string containerName, string objectName, string destinationContainerName, string destinationObjectName = null) - { - return await CopyStorageObjectDelegate(containerName, objectName, destinationContainerName, destinationObjectName); - } - - public async Task CreateLargeStorageObject(string containerName, string objectName, IDictionary metadata, Stream content, - int numberOfsegments) - { - return - await CreateLargeStorageObjectDelegate(containerName, objectName, metadata, content, numberOfsegments); - } - - public async Task GetStorageObject(string containerName, string objectName) - { - return await GetStorageObjectDelegate(containerName, objectName); - } - - public async Task DownloadStorageObject(string containerName, string objectName, Stream outputStream) - { - return await DownloadStorageObjectDelegate(containerName, objectName, outputStream); - } - - public async Task DeleteStorageObject(string containerName, string objectName) - { - await DeleteStorageObjectDelegate(containerName, objectName); - } - - public async Task UpdateStorageObject(StorageObject obj) - { - await UpdateStorageObject(obj); - } - - public async Task CreateStorageManifest(string containerName, string manifestName, IDictionary metadata, IEnumerable objects) - { - return await CreateStaticStorageManifestDelegate(containerName, manifestName, metadata, objects); - } - - public async Task CreateStorageManifest(string containerName, string manifestName, IDictionary metadata, string segmentsPath) - { - return await CreateDynamicStorageManifestDelegate(containerName, manifestName, metadata, segmentsPath); - } - - public async Task GetStorageManifest(string containerName, string objectName) - { - return await GetStorageManifestDelegate(containerName, objectName); - } - - public async Task GetStorageFolder(string containerName, string folderName) - { - return await GetStorageFolderDelegate(containerName, folderName); - } - - public async Task CreateStorageFolder(string containerName, string folderName) - { - await this.CreateStorageFolderDelegate(containerName, folderName); - } - - public async Task DeleteStorageFolder(string containerName, string folderName) - { - await DeleteStorageFolderDelegate(containerName, folderName); - } - } -} diff --git a/OpenStack/OpenStack.Test/Storage/TestStorageServicePocoClient.cs b/OpenStack/OpenStack.Test/Storage/TestStorageServicePocoClient.cs deleted file mode 100644 index 66d1abd..0000000 --- a/OpenStack/OpenStack.Test/Storage/TestStorageServicePocoClient.cs +++ /dev/null @@ -1,154 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.IO; -using System.Threading.Tasks; -using OpenStack.Common.ServiceLocation; -using OpenStack.Storage; - -namespace OpenStack.Test.Storage -{ - public class TestStorageServicePocoClient : IStorageServicePocoClient - { - public Func> CreateStorageObjectDelegate { get; set; } - - public Func> CopyStorageObjectDelegate { get; set; } - - public Func> CreateStorageManifestDelegate { get; set; } - - public Func> CreateStorageContainerDelegate { get; set; } - - public Func CreateStorageFolderDelegate { get; set; } - - public Func> GetStorageContainerDelegate { get; set; } - - public Func> GetStorageAccountDelegate { get; set; } - - public Func> GetStorageObjectDelegate { get; set; } - - public Func> GetStorageManifestDelegate { get; set; } - - public Func> GetStorageFolderDelegate { get; set; } - - public Func> DownloadStorageObjectDelegate { get; set; } - - public Func DeleteStorageObjectDelegate { get; set; } - - public Func DeleteStorageFolderDelegate { get; set; } - - public Func UpdateStorageObjectDelegate { get; set; } - - public Func DeleteStorageConainerDelegate { get; set; } - - public Func UpdateStorageContainerDelegate { get; set; } - - public async Task CreateStorageObject(StorageObject obj, Stream content) - { - return await this.CreateStorageObjectDelegate(obj, content); - } - - public async Task CopyStorageObject(StorageObject obj, string destinationContainerName, string destinationObjectName = null) - { - return await this.CopyStorageObjectDelegate(obj, destinationContainerName, destinationObjectName); - } - - public async Task CreateStorageManifest(StorageManifest manifest) - { - return await this.CreateStorageManifestDelegate(manifest); - } - - public async Task CreateStorageContainer(StorageContainer container) - { - await this.CreateStorageContainerDelegate(container); - } - - public async Task GetStorageAccount() - { - return await this.GetStorageAccountDelegate(); - } - - public async Task GetStorageContainer(string containerName) - { - return await this.GetStorageContainerDelegate(containerName); - } - - public async Task GetStorageObject(string containerName, string objectName) - { - return await this.GetStorageObjectDelegate(containerName, objectName); - } - - public async Task GetStorageManifest(string containerName, string manifestName) - { - return await this.GetStorageManifestDelegate(containerName, manifestName); - } - - public async Task DownloadStorageObject(string containerName, string objectName, Stream outputStream) - { - return await this.DownloadStorageObjectDelegate(containerName, objectName, outputStream); - } - - public async Task DeleteStorageObject(string containerName, string itemName) - { - await this.DeleteStorageObjectDelegate(containerName, itemName); - } - - public async Task DeleteStorageContainer(string containerName) - { - await this.DeleteStorageConainerDelegate(containerName); - } - - public async Task UpdateStorageContainer(StorageContainer container) - { - await this.UpdateStorageContainerDelegate(container); - } - - public async Task UpdateStorageObject(StorageObject item) - { - await this.UpdateStorageObjectDelegate(item); - } - - public async Task GetStorageFolder(string containerName, string folderName) - { - return await this.GetStorageFolderDelegate(containerName, folderName); - } - - public async Task CreateStorageFolder(string containerName, string folderName) - { - await this.CreateStorageFolderDelegate(containerName, folderName); - } - - public async Task DeleteStorageFolder(string containerName, string folderName) - { - await this.DeleteStorageFolderDelegate(containerName, folderName); - } - } - - public class TestStorageServicePocoClientFactory : IStorageServicePocoClientFactory - { - internal IStorageServicePocoClient client; - - public TestStorageServicePocoClientFactory(IStorageServicePocoClient client) - { - this.client = client; - } - - public IStorageServicePocoClient Create(ServiceClientContext context, IServiceLocator serviceLocator) - { - return client; - } - } -} diff --git a/OpenStack/OpenStack.Test/Storage/TestStorageServiceRestClient.cs b/OpenStack/OpenStack.Test/Storage/TestStorageServiceRestClient.cs deleted file mode 100644 index f28bf30..0000000 --- a/OpenStack/OpenStack.Test/Storage/TestStorageServiceRestClient.cs +++ /dev/null @@ -1,135 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; -using System.IO; -using System.Threading.Tasks; -using OpenStack.Common.Http; -using OpenStack.Common.ServiceLocation; -using OpenStack.Storage; - -namespace OpenStack.Test.Storage -{ - public class TestStorageServiceRestClient : IStorageServiceRestClient - { - public bool CreateStaticManifestCalled = false; - public bool CreatedDynamicManifestCalled = false; - - public TestStorageServiceRestClient() - { - this.Responses = new Queue(); - } - - public Queue Responses { get; set; } - - public Task CreateObject(string containerName, string objectName, IDictionary metadata, Stream content) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task CreateDynamicManifest(string containerName, string manifestName, IDictionary metadata, string segmentsPath) - { - CreatedDynamicManifestCalled = true; - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task CreateStaticManifest(string containerName, string manifestName, IDictionary metadata, Stream content) - { - CreateStaticManifestCalled = true; - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task CreateContainer(string containerName, IDictionary metadata) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task GetObject(string containerName, string objectName) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task GetFolder(string containerName, string folderName) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task GetContainer(string containerName) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task DeleteObject(string containerName, string objectName) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task DeleteContainer(string containerName) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task UpdateObject(string containerName, string objectName, IDictionary metadata) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task UpdateContainer(string containerName, IDictionary metadata) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task GetContainerMetadata(string containerName) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task GetObjectMetadata(string containerName, string objectName) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task GetManifestMetadata(string containerName, string manifestName) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task CopyObject(string sourceContainerName, string sourceObjectName, string targetContainerName, - string targetObjectName) - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - - public Task GetAccount() - { - return Task.Factory.StartNew(() => Responses.Dequeue()); - } - } - - public class TestStorageServiceRestClientFactory : IStorageServiceRestClientFactory - { - internal IStorageServiceRestClient Client; - public TestStorageServiceRestClientFactory(IStorageServiceRestClient client) - { - this.Client = client; - } - - public IStorageServiceRestClient Create(ServiceClientContext context, IServiceLocator serviceLocator) - { - return Client; - } - } -} diff --git a/OpenStack/OpenStack.Test/TestOpenStackRegionResolver.cs b/OpenStack/OpenStack.Test/TestOpenStackRegionResolver.cs deleted file mode 100644 index 19ae113..0000000 --- a/OpenStack/OpenStack.Test/TestOpenStackRegionResolver.cs +++ /dev/null @@ -1,36 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using OpenStack.Identity; - -namespace OpenStack.Test -{ - public class TestOpenStackRegionResolver : IOpenStackRegionResolver - { - internal string region; - - public TestOpenStackRegionResolver(string region) - { - this.region = region; - } - public string Resolve(Uri endpoint, IEnumerable catalog, string serviceName) - { - return region; - } - } -} diff --git a/OpenStack/OpenStack.Test/packages.config b/OpenStack/OpenStack.Test/packages.config deleted file mode 100644 index 8451130..0000000 --- a/OpenStack/OpenStack.Test/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/OpenStack/OpenStack.nuspec b/OpenStack/OpenStack.nuspec deleted file mode 100644 index b9030a6..0000000 --- a/OpenStack/OpenStack.nuspec +++ /dev/null @@ -1,31 +0,0 @@ - - - - OpenStack-SDK-DotNet - 0.9.1.0 - OpenStack SDK/API for Microsoft .NET - OpenStack.org - OpenStack.org - http://www.apache.org/licenses/LICENSE-2.0.html - https://wiki.openstack.org/wiki/OpenStack-SDK-DotNet - http://www.openstack.org/assets/openstack-logo/openstack-cloud-software-vertical-small.png - false - OpenStack .NET is an SDK/API for working with OpenStack using the Microsoft .NET Framework. - - Copyright 2014 - OpenStack - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/OpenStack/OpenStack.sln b/OpenStack/OpenStack.sln deleted file mode 100644 index 1c9ffe6..0000000 --- a/OpenStack/OpenStack.sln +++ /dev/null @@ -1,40 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0.30110.0 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenStack.Test", "OpenStack.Test\OpenStack.Test.csproj", "{7AF6DEC5-2257-4A29-BB55-66711DE3055D}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{863F820F-2B49-44FF-A825-A858BFBBD69E}" - ProjectSection(SolutionItems) = preProject - AssemblyVersionInfo.cs = AssemblyVersionInfo.cs - ..\README.rst = ..\README.rst - EndProjectSection -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenStack40", "OpenStack\OpenStack40.csproj", "{E9F05CCA-2748-4785-9F72-5D3F8893BC28}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenStack45-PCL", "OpenStack45-PCL\OpenStack45-PCL.csproj", "{5660F8AA-14D5-4B3B-ADA0-F79A286EF483}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {7AF6DEC5-2257-4A29-BB55-66711DE3055D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7AF6DEC5-2257-4A29-BB55-66711DE3055D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7AF6DEC5-2257-4A29-BB55-66711DE3055D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7AF6DEC5-2257-4A29-BB55-66711DE3055D}.Release|Any CPU.Build.0 = Release|Any CPU - {E9F05CCA-2748-4785-9F72-5D3F8893BC28}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E9F05CCA-2748-4785-9F72-5D3F8893BC28}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E9F05CCA-2748-4785-9F72-5D3F8893BC28}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E9F05CCA-2748-4785-9F72-5D3F8893BC28}.Release|Any CPU.Build.0 = Release|Any CPU - {5660F8AA-14D5-4B3B-ADA0-F79A286EF483}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5660F8AA-14D5-4B3B-ADA0-F79A286EF483}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5660F8AA-14D5-4B3B-ADA0-F79A286EF483}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5660F8AA-14D5-4B3B-ADA0-F79A286EF483}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/OpenStack/OpenStack/Common/Http/DisposableClass.cs b/OpenStack/OpenStack/Common/Http/DisposableClass.cs deleted file mode 100644 index efb4009..0000000 --- a/OpenStack/OpenStack/Common/Http/DisposableClass.cs +++ /dev/null @@ -1,51 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; - -namespace OpenStack.Common.Http -{ - public class DisposableClass : IDisposable - { - private bool _disposed; - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - ~DisposableClass() - { - Dispose(false); - } - - protected virtual void Dispose(bool disposing) - { - if (_disposed) - { - return; - } - - //if (disposing) - //{ - - //} - - _disposed = true; - } - } -} diff --git a/OpenStack/OpenStack/Common/Http/HttpAbstractionClient.cs b/OpenStack/OpenStack/Common/Http/HttpAbstractionClient.cs deleted file mode 100644 index 1398cd1..0000000 --- a/OpenStack/OpenStack/Common/Http/HttpAbstractionClient.cs +++ /dev/null @@ -1,180 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Threading; -using System.Threading.Tasks; - -namespace OpenStack.Common.Http -{ - public class HttpAbstractionClient : DisposableClass, IHttpAbstractionClient - { - private readonly HttpClient _client; - private CancellationToken _cancellationToken = CancellationToken.None; - private static readonly TimeSpan _defaultTimeout = new TimeSpan(0, 5, 0); - - internal HttpAbstractionClient(TimeSpan timeout, CancellationToken cancellationToken) - { - this._client = new HttpClient(new HttpClientHandler()) { Timeout = timeout }; - - this._cancellationToken = cancellationToken; - this.Method = HttpMethod.Get; - this.Headers = new Dictionary(); - this.ContentType = string.Empty; - } - - public static IHttpAbstractionClient Create() - { - return new HttpAbstractionClient(_defaultTimeout, CancellationToken.None ); - } - - public static IHttpAbstractionClient Create(TimeSpan timeout) - { - return new HttpAbstractionClient(timeout, CancellationToken.None); - } - - public static IHttpAbstractionClient Create(CancellationToken cancellationToken) - { - return new HttpAbstractionClient(_defaultTimeout, cancellationToken); - } - - public static IHttpAbstractionClient Create(CancellationToken cancellationToken, TimeSpan timeout) - { - return new HttpAbstractionClient(timeout, cancellationToken); - } - - public HttpMethod Method { get; set; } - - public Uri Uri { get; set; } - - public Stream Content { get; set; } - - public IDictionary Headers { get; private set; } - - public string ContentType { get; set; } - - public TimeSpan Timeout { get; set; } - - public async Task SendAsync() - { - var requestMessage = new HttpRequestMessage { Method = this.Method, RequestUri = this.Uri }; - - if (this.Method == HttpMethod.Post || this.Method == HttpMethod.Put) - { - if (this.Content != null) - { - requestMessage.Content = new StreamContent(this.Content); - if (this.ContentType != string.Empty) - { - requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(this.ContentType); - } - } - } - - requestMessage.Headers.Clear(); - foreach (var header in this.Headers) - { - requestMessage.Headers.Add(header.Key, header.Value); - } - - var startTime = DateTime.Now; - - try - { - - var result = await this._client.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead, this._cancellationToken); - - var headers = new HttpHeadersAbstraction(result.Headers); - - Stream content = null; - if (result.Content != null ) - { - headers.AddRange(result.Content.Headers); - content = this.WaitForResult(result.Content.ReadAsStreamAsync(), new TimeSpan(0,0,0,0,int.MaxValue) ); - } - - var retval = new HttpResponseAbstraction(content, headers, result.StatusCode); - - //TODO: Add logging code - - return retval; - } - catch (Exception ex) - { - //TODO: Add logging code - - var tcex = ex as TaskCanceledException; - if (tcex == null) - { - throw; - } - - if (this._cancellationToken.IsCancellationRequested) - { - throw new OperationCanceledException("The operation was canceled by user request.", tcex, this._cancellationToken); - } - - if (DateTime.Now - startTime > this.Timeout) - { - throw new TimeoutException(string.Format(CultureInfo.InvariantCulture, "The task failed to complete in the given timeout period ({0}).", this.Timeout)); - } - - throw; - } - } - - internal T WaitForResult(Task task, TimeSpan timeout) - { - if (task == null ) - { - throw new ArgumentNullException("task"); - } - - try - { - task.Wait(timeout); - } - catch (AggregateException aggregateException) - { - throw GetInnerException(aggregateException); - } - - if (task.Status != TaskStatus.RanToCompletion && task.Status != TaskStatus.Faulted && task.Status != TaskStatus.Canceled) - { - throw new TimeoutException(string.Format(CultureInfo.InvariantCulture, "The task failed to complete in the given timeout period ({0}).", timeout)); - } - - return task.Result; - } - - internal Exception GetInnerException(AggregateException aggregateException) - { - //helper function to spool off the layers of aggregate exceptions and get the underlying exception... - Exception innerExcception = aggregateException; - while (aggregateException != null) - { - innerExcception = aggregateException.InnerExceptions[0]; - aggregateException = innerExcception as AggregateException; - } - return innerExcception; - } - } -} diff --git a/OpenStack/OpenStack/Common/Http/HttpAbstractionClientFactory.cs b/OpenStack/OpenStack/Common/Http/HttpAbstractionClientFactory.cs deleted file mode 100644 index bc019d2..0000000 --- a/OpenStack/OpenStack/Common/Http/HttpAbstractionClientFactory.cs +++ /dev/null @@ -1,44 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Threading; - -namespace OpenStack.Common.Http -{ - public class HttpAbstractionClientFactory : IHttpAbstractionClientFactory - { - public IHttpAbstractionClient Create() - { - return HttpAbstractionClient.Create(); - } - - public IHttpAbstractionClient Create(TimeSpan timeout) - { - return HttpAbstractionClient.Create(timeout); - } - - public IHttpAbstractionClient Create(CancellationToken token) - { - return HttpAbstractionClient.Create(token); - } - - public IHttpAbstractionClient Create(TimeSpan timeout, CancellationToken token) - { - return HttpAbstractionClient.Create(token, timeout); - } - } -} diff --git a/OpenStack/OpenStack/Common/Http/HttpHeadersAbstraction.cs b/OpenStack/OpenStack/Common/Http/HttpHeadersAbstraction.cs deleted file mode 100644 index 072827a..0000000 --- a/OpenStack/OpenStack/Common/Http/HttpHeadersAbstraction.cs +++ /dev/null @@ -1,106 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections; -using System.Collections.Generic; -using System.Net.Http.Headers; - -namespace OpenStack.Common.Http -{ - public class HttpHeadersAbstraction : IHttpHeadersAbstraction - { - private readonly Dictionary> _headers = new Dictionary>(); - - public HttpHeadersAbstraction() - { - } - - public HttpHeadersAbstraction(HttpResponseHeaders headers) - { - foreach (var header in headers) - { - this._headers.Add(header.Key,header.Value); - } - } - - public IEnumerator>> GetEnumerator() - { - return this._headers.GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return this._headers.GetEnumerator(); - } - - public void Add(string name, IEnumerable values) - { - this._headers.Add(name,values); - } - - public void AddRange(HttpResponseHeaders headers) - { - foreach (var header in headers) - { - this._headers.Add(header.Key, header.Value); - } - } - - public void AddRange(HttpContentHeaders headers) - { - foreach (var header in headers) - { - this._headers.Add(header.Key, header.Value); - } - } - - public void Add(string name, string value) - { - this._headers.Add(name, new List() { value }); - } - - public void Clear() - { - this._headers.Clear(); - } - - public bool Contains(string name) - { - return this._headers.ContainsKey(name); - } - - public IEnumerable GetValues(string name) - { - return this._headers[name]; - } - - public void Remove(string name) - { - this._headers.Remove(name); - } - - public bool TryGetValue(string name, out IEnumerable values) - { - return this._headers.TryGetValue(name, out values); - } - - public IEnumerable this[string name] - { - get { return this._headers[name]; } - set { this._headers[name] = value; } - } - } -} diff --git a/OpenStack/OpenStack/Common/Http/HttpResponseAbstraction.cs b/OpenStack/OpenStack/Common/Http/HttpResponseAbstraction.cs deleted file mode 100644 index 51c8623..0000000 --- a/OpenStack/OpenStack/Common/Http/HttpResponseAbstraction.cs +++ /dev/null @@ -1,46 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.IO; -using System.Net; -using System.Threading.Tasks; - -namespace OpenStack.Common.Http -{ - public class HttpResponseAbstraction : IHttpResponseAbstraction - { - public HttpResponseAbstraction(Stream content, IHttpHeadersAbstraction headers, HttpStatusCode status) - { - this.Headers = headers ?? new HttpHeadersAbstraction(); - this.StatusCode = status; - this.Content = content; - } - - public Stream Content { get; private set; } - - public IHttpHeadersAbstraction Headers { get; private set; } - - public HttpStatusCode StatusCode { get; private set; } - - public async Task ReadContentAsStringAsync() - { - using (var sr = new StreamReader(this.Content)) - { - return await sr.ReadToEndAsync(); - } - } - } -} diff --git a/OpenStack/OpenStack/Common/Http/IHttpAbstractionClient.cs b/OpenStack/OpenStack/Common/Http/IHttpAbstractionClient.cs deleted file mode 100644 index f4e000a..0000000 --- a/OpenStack/OpenStack/Common/Http/IHttpAbstractionClient.cs +++ /dev/null @@ -1,45 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Net.Http; -using System.Threading.Tasks; - -namespace OpenStack.Common.Http -{ - public interface IHttpAbstractionClient : IDisposable - { - HttpMethod Method { get; set; } - - Uri Uri { get; set; } - - Stream Content { get; set; } - - IDictionary Headers { get; } - - string ContentType { get; set; } - - TimeSpan Timeout { get; set; } - - - //event EventHandler HttpReceiveProgress; - //event EventHandler HttpSendProgress; - - Task SendAsync(); - } -} diff --git a/OpenStack/OpenStack/Common/Http/IHttpAbstractionClientFactory.cs b/OpenStack/OpenStack/Common/Http/IHttpAbstractionClientFactory.cs deleted file mode 100644 index 786936c..0000000 --- a/OpenStack/OpenStack/Common/Http/IHttpAbstractionClientFactory.cs +++ /dev/null @@ -1,32 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Threading; - -namespace OpenStack.Common.Http -{ - public interface IHttpAbstractionClientFactory - { - IHttpAbstractionClient Create(); - - IHttpAbstractionClient Create(CancellationToken token); - - IHttpAbstractionClient Create(TimeSpan timeout); - - IHttpAbstractionClient Create(TimeSpan timeout, CancellationToken token); - } -} diff --git a/OpenStack/OpenStack/Common/Http/IHttpHeadersAbstraction.cs b/OpenStack/OpenStack/Common/Http/IHttpHeadersAbstraction.cs deleted file mode 100644 index 6a027ff..0000000 --- a/OpenStack/OpenStack/Common/Http/IHttpHeadersAbstraction.cs +++ /dev/null @@ -1,39 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; - -namespace OpenStack.Common.Http -{ - public interface IHttpHeadersAbstraction : IEnumerable>> - { - void Add(string name, IEnumerable values); - - void Add(string name, string value); - - void Clear(); - - bool Contains(string name); - - IEnumerable GetValues(string name); - - void Remove(string name); - - bool TryGetValue(string name, out IEnumerable values); - - IEnumerable this[string name] { get; set; } - } -} diff --git a/OpenStack/OpenStack/Common/Http/IHttpResponseAbstraction.cs b/OpenStack/OpenStack/Common/Http/IHttpResponseAbstraction.cs deleted file mode 100644 index 573dffc..0000000 --- a/OpenStack/OpenStack/Common/Http/IHttpResponseAbstraction.cs +++ /dev/null @@ -1,33 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.IO; -using System.Net; -using System.Threading.Tasks; - -namespace OpenStack.Common.Http -{ - public interface IHttpResponseAbstraction - { - Stream Content { get; } - - IHttpHeadersAbstraction Headers { get; } - - HttpStatusCode StatusCode { get; } - - Task ReadContentAsStringAsync(); - } -} diff --git a/OpenStack/OpenStack/Common/ObjectExtentions.cs b/OpenStack/OpenStack/Common/ObjectExtentions.cs deleted file mode 100644 index cd2ad3f..0000000 --- a/OpenStack/OpenStack/Common/ObjectExtentions.cs +++ /dev/null @@ -1,106 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - - -using System; -using System.IO; -using System.Text; - -namespace OpenStack.Common -{ - /// - /// Holds extension methods for common objects and tasks. - /// - public static class ObjectExtentions - { - /// - /// Throws an argument exception if the given object is null. - /// - /// Given Type of the object. - /// The object. - /// A string that represents a name for the object. - public static void AssertIsNotNull(this T input, string paramName) - { - if (ReferenceEquals(input, null)) - { - throw new ArgumentNullException(paramName); - } - } - - /// - /// Throws an argument exception if the given object is null. - /// - /// Given Type of the object. - /// The object. - /// A string that represents a name for the object. - /// A message to include in the thrown exception. - public static void AssertIsNotNull(this T input, string paramName, string message) - { - if (ReferenceEquals(input, null)) - { - throw new ArgumentNullException(paramName, message); - } - } - - /// - /// Throws an argument exception if the given string is null or empty. - /// - /// The given string. - /// A string that represents a name for the object. - public static void AssertIsNotNullOrEmpty(this string input, string paramName) - { - if (ReferenceEquals(input, null)) - { - throw new ArgumentNullException(paramName); - } - - if (string.IsNullOrEmpty(input)) - { - throw new ArgumentException(string.Empty, paramName); - } - } - - /// - /// Throws an argument exception if the given string is null or empty. - /// - /// The given string. - /// A string that represents a name for the object. - /// A message to include in the thrown exception. - public static void AssertIsNotNullOrEmpty(this string input, string paramName, string message) - { - if (ReferenceEquals(input, null)) - { - throw new ArgumentNullException(paramName, message); - } - - if (string.IsNullOrEmpty(input)) - { - throw new ArgumentException(message, paramName); - } - } - - /// - /// Converts the given string to a stream. - /// - /// The string to convert. - /// A stream that includes the given string. - public static Stream ConvertToStream(this string content) - { - var byteArray = Encoding.UTF8.GetBytes(content); - return new MemoryStream(byteArray); - } - } -} diff --git a/OpenStack/OpenStack/Common/OpenStackServiceRestClientBase.cs b/OpenStack/OpenStack/Common/OpenStackServiceRestClientBase.cs deleted file mode 100644 index ec111b4..0000000 --- a/OpenStack/OpenStack/Common/OpenStackServiceRestClientBase.cs +++ /dev/null @@ -1,81 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using OpenStack.Common.Http; -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Common -{ - /// - /// Base class for OpenStack service clients - /// - internal abstract class OpenStackServiceRestClientBase : IOpenStackServiceClient - { - internal ServiceClientContext Context; - internal IServiceLocator ServiceLocator; - - /// - /// Creates a new instance of the OpenStackServiceRestClientBase class. - /// - /// The service client context for this object. - /// A service locator for this object to use. - protected OpenStackServiceRestClientBase(ServiceClientContext context, IServiceLocator serviceLocator) - { - serviceLocator.AssertIsNotNull("serviceLocator", "Cannot create a service rest client with a null service locator."); - - this.ServiceLocator = serviceLocator; - this.Context = context; - } - - /// - /// Creates an Http client to communicate with the remote OpenStack service. - /// - /// The compute context to use when creating the client. - /// The Http client. - internal IHttpAbstractionClient GetHttpClient(ServiceClientContext context) - { - var client = this.ServiceLocator.Locate().Create(context.CancellationToken); - AddAuthenticationHeader(context.Credential.AccessTokenId, client); - client.Headers.Add("Accept", "application/json"); - return client; - } - - /// - /// Creates a Uri for making requests to the remote service. - /// - /// The root endpoint to use in the request. - /// The additional parameters to add to the request. - /// A complete request Uri. - internal Uri CreateRequestUri(Uri endpoint, params string[] values) - { - var temp = new List { endpoint.AbsoluteUri.TrimEnd('/') }; - temp.AddRange(values); - return new Uri(string.Join("/", temp.ToArray())); - } - - /// - /// Adds the appropriate authentication headers to the given http client. - /// - /// The access token id for the header. - /// The http client. - internal void AddAuthenticationHeader(string authenticationId, IHttpAbstractionClient client) - { - client.Headers.Add("X-Auth-Token", authenticationId); - } - } -} diff --git a/OpenStack/OpenStack/Common/ReflectionExtentions.cs b/OpenStack/OpenStack/Common/ReflectionExtentions.cs deleted file mode 100644 index f1c423e..0000000 --- a/OpenStack/OpenStack/Common/ReflectionExtentions.cs +++ /dev/null @@ -1,69 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; - -namespace OpenStack.Common -{ - /// - /// Static class for extending reflection classes. - /// - internal static class ReflectionExtentions - { - /// - /// Gets the assembly that contains the extended type. - /// - /// The given Type - /// The assembly that contains the given type. - public static Assembly GetAssembly(this Type input) - { - return input.Assembly; - } - - /// - /// Determines if the given type is an interface. - /// - /// The given type. - /// A value indicating if the given type is an interface. - public static bool IsInterface(this Type input) - { - return input.IsInterface; - } - - /// - /// Gets a list of types that are defined in the given assembly. - /// - /// The given assembly. - /// A list of types defined in the given assembly. - public static IEnumerable GetDefinedTypes(this Assembly input) - { - return input.GetTypes().ToList(); - } - - /// - /// Gets a list of defined constructors for the given type. - /// - /// The given type. - /// A list of constructors for the given type. - public static IEnumerable GetDefinedConstructors(this Type input) - { - return input.GetConstructors(); - } - } -} diff --git a/OpenStack/OpenStack/Common/ServiceLocation/IServiceLocationAssemblyScanner.cs b/OpenStack/OpenStack/Common/ServiceLocation/IServiceLocationAssemblyScanner.cs deleted file mode 100644 index 9bfcb50..0000000 --- a/OpenStack/OpenStack/Common/ServiceLocation/IServiceLocationAssemblyScanner.cs +++ /dev/null @@ -1,50 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; -using System.Reflection; - -namespace OpenStack.Common.ServiceLocation -{ - /// - /// Interface for scanning an assembly for service location registrars. - /// - internal interface IServiceLocationAssemblyScanner - { - /// - /// Gets a value indicating if the scanner has new assemblies that can be scanned. - /// - bool HasNewAssemblies { get; } - - /// - /// Gets an enumerable collection of service location registrars. - /// - /// enumerable collection of service location registrars - IEnumerable GetRegistrars(); - - /// - /// Gets an enumeration of service registrars that have not been scanned before. - /// - /// an enumeration of service registrars. - IEnumerable GetNewRegistrars(); - - /// - /// Adds the target assembly to the scanners list of assemblies to scan. - /// - /// The target assembly. - void AddAssembly(Assembly target); - } -} diff --git a/OpenStack/OpenStack/Common/ServiceLocation/IServiceLocationManager.cs b/OpenStack/OpenStack/Common/ServiceLocation/IServiceLocationManager.cs deleted file mode 100644 index 38e2297..0000000 --- a/OpenStack/OpenStack/Common/ServiceLocation/IServiceLocationManager.cs +++ /dev/null @@ -1,61 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; - -namespace OpenStack.Common.ServiceLocation -{ - /// - /// Represents an object that can manage service location registration. - /// - public interface IServiceLocationManager - { - /// - /// Registers an instance of a service with the service locator. - /// - /// The interface of the service to be registered. - /// An instance of the service to be returned by the service locator. - void RegisterServiceInstance(TService instance); - - /// - /// Registers an instance of a service with the service locator. - /// - /// The interface of the service to be registered. - /// An instance of the service to be returned by the service locator. - void RegisterServiceInstance(Type type, object instance); - - /// - /// Registers a type of a service with the service locator. - /// - /// The interface of the service to be registered. - /// A concrete type of the service to be returned by the service locator. - void RegisterServiceType(Type type); - - /// - /// Registers a type of a service with the service locator. - /// - /// The interface of the service to be registered. - /// A concrete type of the service to be returned by the service locator. - void RegisterServiceType() where TConcretion : class, TInterface; - - /// - /// Registers a type of a service with the service locator. - /// - /// The interface of the service to be registered. - /// A concrete type of the service to be returned by the service locator. - void RegisterServiceType(Type type, Type registrationValue); - } -} diff --git a/OpenStack/OpenStack/Common/ServiceLocation/IServiceLocationOverrideManager.cs b/OpenStack/OpenStack/Common/ServiceLocation/IServiceLocationOverrideManager.cs deleted file mode 100644 index 754450f..0000000 --- a/OpenStack/OpenStack/Common/ServiceLocation/IServiceLocationOverrideManager.cs +++ /dev/null @@ -1,24 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ -namespace OpenStack.Common.ServiceLocation -{ - /// - /// Represents an object that can manage overriding service location registrations. - /// - internal interface IServiceLocationOverrideManager : IServiceLocationManager - { - } -} diff --git a/OpenStack/OpenStack/Common/ServiceLocation/IServiceLocationRegistrar.cs b/OpenStack/OpenStack/Common/ServiceLocation/IServiceLocationRegistrar.cs deleted file mode 100644 index 68b6a87..0000000 --- a/OpenStack/OpenStack/Common/ServiceLocation/IServiceLocationRegistrar.cs +++ /dev/null @@ -1,30 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ -namespace OpenStack.Common.ServiceLocation -{ - /// - /// Represents an object that will register services for location. - /// - public interface IServiceLocationRegistrar - { - /// - /// Registers services for location. - /// - /// A service location manager to use for registering services. - /// A reference to the service locator. - void Register(IServiceLocationManager manager, IServiceLocator locator); - } -} diff --git a/OpenStack/OpenStack/Common/ServiceLocation/IServiceLocationRegistrarFactory.cs b/OpenStack/OpenStack/Common/ServiceLocation/IServiceLocationRegistrarFactory.cs deleted file mode 100644 index 91f3806..0000000 --- a/OpenStack/OpenStack/Common/ServiceLocation/IServiceLocationRegistrarFactory.cs +++ /dev/null @@ -1,33 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; - -namespace OpenStack.Common.ServiceLocation -{ - /// - /// Interface for an object that knows how to create service registrars. - /// - interface IServiceLocationRegistrarFactory - { - /// - /// Creates a service registrar. - /// - /// The type of the service registrar to create. - /// An instance of the given registrar type. - IServiceLocationRegistrar Create(Type type); - } -} diff --git a/OpenStack/OpenStack/Common/ServiceLocation/IServiceLocationRuntimeManager.cs b/OpenStack/OpenStack/Common/ServiceLocation/IServiceLocationRuntimeManager.cs deleted file mode 100644 index 595f5b5..0000000 --- a/OpenStack/OpenStack/Common/ServiceLocation/IServiceLocationRuntimeManager.cs +++ /dev/null @@ -1,24 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ -namespace OpenStack.Common.ServiceLocation -{ - /// - /// Represents an object that can manage service location registrations at runtime. - /// - internal interface IServiceLocationRuntimeManager : IServiceLocationManager - { - } -} diff --git a/OpenStack/OpenStack/Common/ServiceLocation/IServiceLocator.cs b/OpenStack/OpenStack/Common/ServiceLocation/IServiceLocator.cs deleted file mode 100644 index 9d90650..0000000 --- a/OpenStack/OpenStack/Common/ServiceLocation/IServiceLocator.cs +++ /dev/null @@ -1,40 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Reflection; - -namespace OpenStack.Common.ServiceLocation -{ - /// - /// Represents an object that can locate services. - /// - public interface IServiceLocator - { - /// - /// Locates an instance of the requested service. - /// - /// The type of the service to locate. - /// An instance of the service. - T Locate(); - - /// - /// Ensures that the given assembly has been registered with the ServiceLocator for service location. - /// - /// The target assembly. - void EnsureAssemblyRegistration(Assembly target); - } -} diff --git a/OpenStack/OpenStack/Common/ServiceLocation/RuntimeRegistrationManager.cs b/OpenStack/OpenStack/Common/ServiceLocation/RuntimeRegistrationManager.cs deleted file mode 100644 index 9d82dfe..0000000 --- a/OpenStack/OpenStack/Common/ServiceLocation/RuntimeRegistrationManager.cs +++ /dev/null @@ -1,74 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; - -namespace OpenStack.Common.ServiceLocation -{ - /// - internal class RuntimeRegistrationManager : ServiceLocationManager - { - private IServiceLocator locator; - - /// - /// Constructs a new instance of the RuntimeRegistrationManager class. - /// - /// A reference to a service locator. - public RuntimeRegistrationManager(IServiceLocator locator) - { - this.locator = locator; - } - - private readonly Dictionary _discovered = new Dictionary(); - - /// - public override void RegisterServiceInstance(Type serviceType, object instance) - { - var registering = instance as IServiceLocationRegistrar; - object discoveredInstance; - if (this._discovered.TryGetValue(serviceType, - out discoveredInstance)) - { - if (!ReferenceEquals(discoveredInstance, - instance) && !ReferenceEquals(registering, - null)) - { - this._discovered[serviceType] = instance; - registering.Register(this, this.locator); - } - } - else - { - this._discovered[serviceType] = instance; - if (!ReferenceEquals(registering, - null)) - { - registering.Register(this, this.locator); - } - } - } - - /// - /// Gets a list of types and objects that have been discovered/registered. - /// - /// An enumerable list of types and instances. - public IEnumerable> GetDiscovered() - { - return this._discovered; - } - } -} diff --git a/OpenStack/OpenStack/Common/ServiceLocation/ServiceLocationAssemblyScanner.cs b/OpenStack/OpenStack/Common/ServiceLocation/ServiceLocationAssemblyScanner.cs deleted file mode 100644 index 6eca810..0000000 --- a/OpenStack/OpenStack/Common/ServiceLocation/ServiceLocationAssemblyScanner.cs +++ /dev/null @@ -1,139 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; - -namespace OpenStack.Common.ServiceLocation -{ - /// - internal class ServiceLocationAssemblyScanner : IServiceLocationAssemblyScanner - { - internal IServiceLocationRegistrarFactory ServiceRegistrarFactory { get; set; } - internal readonly List _registrars = new List(); - internal readonly List _assemblies = new List(); - internal Func> GetRegistrarTypes; - - /// - public bool HasNewAssemblies { get; internal set; } - - /// - /// Creates a new instance of the ServiceLocationAssemblyScanner class. - /// - public ServiceLocationAssemblyScanner() - { - this.GetRegistrarTypes = this.InternalGetRegistrarTypes; - this.ServiceRegistrarFactory = new ServiceLocationRegistrarFactory(); - } - - /// - internal IEnumerable GetNewRegistrarTypes() - { - var newRegistrars = new List(); - if (this.HasNewAssemblies) - { - newRegistrars = this.GetRegistrarTypes().ToList(); - } - - return newRegistrars; - } - - /// - /// Gets an enumeration of service registrar objects from the given enumeration of types. - /// - /// An enumeration of Type objects. - /// An enumeration of service location registrars. - internal IEnumerable GetRegistrars(IEnumerable registrarTypes) - { - return (from t in registrarTypes - select ServiceRegistrarFactory.Create(t)).ToList(); - } - - /// - public IEnumerable GetNewRegistrars() - { - var newRegistrars = this.GetNewRegistrarTypes().ToList(); - this._registrars.All(newRegistrars.Remove); - this._registrars.AddRange(newRegistrars); - this.HasNewAssemblies = false; - - return GetRegistrars(newRegistrars); - } - - /// - public IEnumerable GetRegistrars() - { - var newRegistrars = this.GetNewRegistrarTypes().ToList(); - - this._registrars.All(newRegistrars.Remove); - this._registrars.AddRange(newRegistrars); - this.HasNewAssemblies = false; - - return GetRegistrars(this._registrars); - } - - /// - public void AddAssembly(Assembly target) - { - if (!this._assemblies.Contains(target)) - { - this._assemblies.Add(target); - this.HasNewAssemblies = true; - } - } - - /// - /// Gets a list of types for any services registrars in the current application domain. - /// - /// A list of types. - internal IEnumerable InternalGetRegistrarTypes() - { - var rawTypes = new List(); - var serviceRegistrarType = typeof (IServiceLocationRegistrar); - - foreach (var assembly in this._assemblies) - { - try - { - rawTypes.AddRange(assembly.GetDefinedTypes()); - } - catch (ReflectionTypeLoadException loadEx) - { - var foundTypes = (from t in loadEx.Types where t != null select t).ToList(); - rawTypes.AddRange(foundTypes); - } - } - - var rawRegistrarTypes = new List(); - foreach (var type in rawTypes) - { - if (type.IsInterface()) - { - continue; - } - - if (serviceRegistrarType.IsAssignableFrom(type) && type.GetDefinedConstructors().Any(c => !c.GetParameters().Any())) - { - rawRegistrarTypes.Add(type); - } - } - - return rawRegistrarTypes; - } - } -} diff --git a/OpenStack/OpenStack/Common/ServiceLocation/ServiceLocationManager.cs b/OpenStack/OpenStack/Common/ServiceLocation/ServiceLocationManager.cs deleted file mode 100644 index feb1bbe..0000000 --- a/OpenStack/OpenStack/Common/ServiceLocation/ServiceLocationManager.cs +++ /dev/null @@ -1,126 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Globalization; -using System.Reflection; - -namespace OpenStack.Common.ServiceLocation -{ - /// - internal abstract class ServiceLocationManager : IServiceLocationManager - { - /// - public void RegisterServiceInstance(TService instance) - { - this.RegisterServiceInstance(typeof(TService), - instance); - } - - /// - public abstract void RegisterServiceInstance(Type type, object instance); - - /// - public void RegisterServiceType(Type registrationValue) - { - this.RegisterServiceType(typeof(T), - registrationValue); - } - - /// - public void RegisterServiceType() where TConcreate : class, TInterface - { - this.RegisterServiceType(typeof(TInterface), typeof(TConcreate)); - } - - /// - public void RegisterServiceType(Type type, Type registrationValue) - { - ThrowIfInvalidRegistration(type, registrationValue); - - var obj = Activator.CreateInstance(registrationValue); - - this.RegisterServiceInstance(type, obj); - } - - /// - /// Throws an exception if the type or implementation are null. - /// - /// A Type object. - /// The implementation of the given Type. - internal static void ThrowIfNullInstance(Type type, object implementation) - { - if (ReferenceEquals(type, null)) - { - var msg = string.Format(CultureInfo.InvariantCulture, - "Cannot register a null service."); - throw new InvalidOperationException(msg); - } - - if (ReferenceEquals(implementation, null)) - { - var msg = string.Format( - CultureInfo.InvariantCulture, - "A service cannot have a null implementation '{0}'", - type.FullName); - throw new InvalidOperationException(msg); - } - } - - /// - /// Throws an exception if the given Type and implementation represent an invalid registration. - /// An invalid registration is one where the given Type is of a restricted type, is not an interface, or the given implementation does not inherit from the given Type. - /// - /// A Type object. - /// The implementation of the given Type. - internal static void ThrowIfInvalidRegistration(Type type, Type implementation) - { - ThrowIfNullInstance(type, - implementation); - if (type == typeof(IServiceLocationRuntimeManager) || - type == typeof(IServiceLocationOverrideManager) || - type == typeof(IServiceLocationManager) || - type == typeof(IServiceLocator)) - { - var msg = string.Format( - CultureInfo.InvariantCulture, - "Service location services cannot be registered or overridden: '{0}'", - type.FullName); - throw new InvalidOperationException(msg); - } - - - if (!type.IsInterface()) - { - var msg = string.Format( - CultureInfo.InvariantCulture, - "The following type: '{0}' is not an interface", - type.FullName); - throw new InvalidOperationException(msg); - } - - if (!type.IsAssignableFrom(implementation)) - { - var msg = string.Format( - CultureInfo.InvariantCulture, - "Cannot register or override the service '{0}' for the type '{1}' which is not derived from the service", - implementation.FullName, - type.FullName); - throw new InvalidOperationException(msg); - } - } - } -} diff --git a/OpenStack/OpenStack/Common/ServiceLocation/ServiceLocationRegistrarFactory.cs b/OpenStack/OpenStack/Common/ServiceLocation/ServiceLocationRegistrarFactory.cs deleted file mode 100644 index 4752d08..0000000 --- a/OpenStack/OpenStack/Common/ServiceLocation/ServiceLocationRegistrarFactory.cs +++ /dev/null @@ -1,30 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; - -namespace OpenStack.Common.ServiceLocation -{ - /// - class ServiceLocationRegistrarFactory : IServiceLocationRegistrarFactory - { - /// - public IServiceLocationRegistrar Create(Type type) - { - return (IServiceLocationRegistrar)Activator.CreateInstance(type); - } - } -} diff --git a/OpenStack/OpenStack/Common/ServiceLocation/ServiceLocator.cs b/OpenStack/OpenStack/Common/ServiceLocation/ServiceLocator.cs deleted file mode 100644 index 6cc3e97..0000000 --- a/OpenStack/OpenStack/Common/ServiceLocation/ServiceLocator.cs +++ /dev/null @@ -1,175 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Reflection; - -namespace OpenStack.Common.ServiceLocation -{ - /// - public class ServiceLocator : IServiceLocator - { - private readonly ServiceLocationManager _runtimeManager; - private readonly Dictionary _services = new Dictionary(); - private readonly Dictionary _overrideServices = new Dictionary(); - private readonly IServiceLocationAssemblyScanner _scanner = new ServiceLocationAssemblyScanner(); - - internal ServiceLocator() - { - this._runtimeManager = new ServiceLocationRuntimeManager(this); - this._services.Add(typeof(IServiceLocationRuntimeManager), this._runtimeManager); - this._services.Add(typeof(IServiceLocationOverrideManager), new ServiceLocationOverrideManager(this)); - this._scanner.AddAssembly(this.GetType().GetAssembly()); - this.RegisterServices(); - } - - internal void RegisterServices(IEnumerable registrars) - { - foreach (var serviceLocationRegistrar in registrars) - { - serviceLocationRegistrar.Register(this._runtimeManager, this); - } - } - - internal void RegisterServices() - { - var registrars = this._scanner.GetRegistrars().ToList(); - this.RegisterServices(registrars); - } - - /// - public T Locate() - { - return (T)this.Locate(typeof(T)); - } - - public void EnsureAssemblyRegistration(Assembly target) - { - this._scanner.AddAssembly(target); - var registrars = this._scanner.GetNewRegistrars(); - this.RegisterServices(registrars); - } - - /// - /// Locates an implementation of the given Type. - /// - /// The Type to locate. - /// The implementation of the given type that has been located. - internal object Locate(Type type) - { - var retval = this.InternalLocate(type); - if (retval != null) - { - return retval; - } - - if (this._scanner.HasNewAssemblies) - { - this.RegisterServices(); - retval = this.InternalLocate(type); - } - - if (retval != null) - { - return retval; - } - - var message = string.Format(CultureInfo.InvariantCulture, - "Service '{0}' has not been registered", - type.FullName); - throw new InvalidOperationException(message); - } - - /// - /// Locates an implementation of the given Type. - /// - /// The Type to locate. - /// The implementation of the given type that has been located. - private object InternalLocate(Type type) - { - if (ReferenceEquals(type, - null)) - { - throw new ArgumentNullException("type"); - } - object runtimeVersion = null; - object overrideVersion = null; - - // First try to get a an override - if (!this._overrideServices.TryGetValue(type, out overrideVersion)) - { - //if no override, then try to get the actual service. - this._services.TryGetValue(type, out runtimeVersion); - } - - return overrideVersion ?? runtimeVersion; - } - - /// - private class ServiceLocationRuntimeManager : ServiceLocationManager, IServiceLocationRuntimeManager - { - private readonly ServiceLocator _locator; - - /// - public ServiceLocationRuntimeManager(ServiceLocator locator) - { - this._locator = locator; - } - - /// - public override void RegisterServiceInstance(Type type, object instance) - { - ThrowIfNullInstance(type, - instance); - ThrowIfInvalidRegistration(type, - instance.GetType()); - var internalManager = new RuntimeRegistrationManager(this._locator); - internalManager.RegisterServiceInstance(type, - instance); - foreach (KeyValuePair keyValuePair in internalManager.GetDiscovered()) - { - this._locator._services[keyValuePair.Key] = keyValuePair.Value; - } - } - } - - /// - private class ServiceLocationOverrideManager : ServiceLocationManager, IServiceLocationOverrideManager - { - private readonly ServiceLocator _locator; - - /// - public ServiceLocationOverrideManager(ServiceLocator locator) - { - this._locator = locator; - } - - /// - public override void RegisterServiceInstance(Type type, object instance) - { - ThrowIfNullInstance(type, - instance); - ThrowIfInvalidRegistration(type, - instance.GetType()); - - this._locator._overrideServices[type] = instance; - } - } - } -} diff --git a/OpenStack/OpenStack/Common/StreamExtentions.cs b/OpenStack/OpenStack/Common/StreamExtentions.cs deleted file mode 100644 index 472142f..0000000 --- a/OpenStack/OpenStack/Common/StreamExtentions.cs +++ /dev/null @@ -1,38 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.IO; -using System.Threading.Tasks; - -namespace OpenStack.Common -{ - /// - /// Static class for extending the Stream class. - /// - public static class StreamExtentions - { - /// - /// Copies the given stream into another stream asynchronously. - /// - /// The given stream. - /// The stream that will be copied into. - /// An asynchronous task. - public static Task CopyAsync(this Stream input, Stream output) - { - return Task.Factory.StartNew(() => input.CopyTo(output)); - } - } -} diff --git a/OpenStack/OpenStack/Compute/ComputeFlavor.cs b/OpenStack/OpenStack/Compute/ComputeFlavor.cs deleted file mode 100644 index b060cef..0000000 --- a/OpenStack/OpenStack/Compute/ComputeFlavor.cs +++ /dev/null @@ -1,63 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections; -using System.Collections.Generic; - -namespace OpenStack.Compute -{ - using System; - - /// - /// Represents a Flavor on a remote OpenStack instance. - /// - public class ComputeFlavor : ComputeItem - { - /// - /// Gets the amount of RAM for the Flavor. - /// - public string Ram { get; private set; } - - /// - /// Gets the number of virtual CPUs of the Flavor. - /// - public string Vcpus { get; private set; } - - /// - /// Gets the size of the disk of the Flavor. - /// - public string Disk { get; private set; } - - /// - /// Create a new instance of the Flavor class. - /// - /// The Id of the flavor. - /// The name of the flavor. - /// The amount of ram of the flavor. - /// The number of virtual CPUs of the Flavor. - /// The size of the disk of the Flavor. - /// The public Uri for the Flavor. - /// The permanent Uri of the Flavor. - /// The metadata for the Flavor. - internal ComputeFlavor(string id, string name, string ram, string vcpus, string disk, Uri publicUri, - Uri permanentUri, IDictionary metadata) : base(id, name, publicUri, permanentUri) - { - this.Ram = ram; - this.Vcpus = vcpus; - this.Disk = disk; - } - } -} diff --git a/OpenStack/OpenStack/Compute/ComputeFlavorPayloadConverter.cs b/OpenStack/OpenStack/Compute/ComputeFlavorPayloadConverter.cs deleted file mode 100644 index 5ac0943..0000000 --- a/OpenStack/OpenStack/Compute/ComputeFlavorPayloadConverter.cs +++ /dev/null @@ -1,139 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json.Serialization; -using OpenStack.Common; -using System.Linq; - -namespace OpenStack.Compute -{ - using System; - - /// - internal class ComputeFlavorPayloadConverter : IComputeFlavorPayloadConverter - { - /// - public ComputeFlavor ConvertFlavor(string payload) - { - payload.AssertIsNotNullOrEmpty("payload", "A null or empty compute flavor payload cannot be converted."); - - try - { - var token = JToken.Parse(payload); - return ConvertFlavor(token["flavor"]); - } - catch (FormatException) - { - throw; - } - catch (Exception ex) - { - throw new FormatException( - string.Format("Compute flavor payload could not be parsed. Payload: '{0}'", payload), ex); - } - } - - internal ComputeFlavor ConvertFlavor(JToken flavorToken) - { - var name = string.Empty; - var id = string.Empty; - try - { - name = (string) flavorToken["name"]; - id = (string) flavorToken["id"]; - - if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(id)) - { - throw new FormatException(); - } - - var ram = (string) flavorToken["ram"]; - var vcpus = (string) flavorToken["vcpus"]; - var disk = (string) flavorToken["disk"]; - - var permalink = string.Empty; - var publicLink = string.Empty; - var links = flavorToken["links"]; - if (links != null) - { - foreach (var linkToken in links) - { - switch (linkToken["rel"].Value().ToLower()) - { - case "self": - publicLink = linkToken["href"].Value(); - break; - case "bookmark": - permalink = linkToken["href"].Value(); - break; - } - } - } - - return new ComputeFlavor(id, name, ram, vcpus, disk, new Uri(publicLink), new Uri(permalink), new Dictionary()); - } - catch (Exception ex) - { - var msg = "Compute flavor payload could not be parsed."; - if (!string.IsNullOrEmpty(name) && flavorToken != null) - { - msg = string.Format( - "Compute flavor '{0}' with Id '{1}' payload could not be parsed. Payload: '{2}'", name, id, - flavorToken); - } - else if (flavorToken != null) - { - msg = string.Format("Compute flavor payload could not be parsed. Payload: '{0}'", flavorToken); - } - - throw new FormatException(msg, ex); - } - } - - /// - public IEnumerable ConvertFlavors(string payload) - { - payload.AssertIsNotNull("payload", "A null compute flavor payload cannot be converted."); - - var flavors = new List(); - - if (String.IsNullOrEmpty(payload)) - { - return flavors; - } - - try - { - var payloadToken = JToken.Parse(payload); - var flavorsArray = payloadToken["flavors"]; - flavors.AddRange(flavorsArray.Select(ConvertFlavor)); - } - catch (FormatException) - { - throw; - } - catch (Exception ex) - { - throw new FormatException( - string.Format("Compute flavors payload could not be parsed. Payload: '{0}'", payload), ex); - } - - return flavors; - } - } -} diff --git a/OpenStack/OpenStack/Compute/ComputeImage.cs b/OpenStack/OpenStack/Compute/ComputeImage.cs deleted file mode 100644 index 90dc627..0000000 --- a/OpenStack/OpenStack/Compute/ComputeImage.cs +++ /dev/null @@ -1,83 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; - -namespace OpenStack.Compute -{ - /// - /// Represents an image on a remote OpenStack instance. - /// - public class ComputeImage : MetadataComputeItem - { - /// - /// Gets the current status of the image. - /// - public string Status { get; private set; } - - /// - /// Gets the date and time when the image was created. - /// - public DateTime CreateDate { get; private set; } - - /// - /// Gets the date and time that the image was last updated. - /// - public DateTime LastUpdated { get; private set; } - - /// - /// Gets the minimum size of the disk for this image. - /// - public int MinimumDiskSize { get; private set; } - - /// - /// Gets the current upload progress of the image. - /// - public int UploadProgress { get; private set; } - - /// - /// Gets the minimum amount of ram for this image. - /// - public int MinimumRamSize { get; private set; } - - /// - /// Create a new instance of the ComputeImage class. - /// - /// The Id of the image. - /// The name of the image. - /// The public Uri for the image. - /// The permanent Uri of the image. - /// The metadata for the image. - /// The current status for the image. - /// The date and time when the image was created. - /// The data and time when the image was last updated. - /// The minimum disk size for the image. - /// The minimum ram size for the image. - /// The upload progress for the image. - internal ComputeImage(string id, string name, Uri publicUri, Uri permanentUri, - IDictionary metadata, string status, DateTime created, DateTime updated, int minDisk, - int minRam, int progress) : base(id, name, publicUri, permanentUri, metadata) - { - this.Status = status; - this.CreateDate = created; - this.LastUpdated = updated; - this.MinimumDiskSize = minDisk; - this.MinimumRamSize = minRam; - this.UploadProgress = progress; - } - } -} diff --git a/OpenStack/OpenStack/Compute/ComputeImagePayloadConverter.cs b/OpenStack/OpenStack/Compute/ComputeImagePayloadConverter.cs deleted file mode 100644 index bbeb95f..0000000 --- a/OpenStack/OpenStack/Compute/ComputeImagePayloadConverter.cs +++ /dev/null @@ -1,149 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using OpenStack.Common; -using System.Linq; - -namespace OpenStack.Compute -{ - using System; - - /// - internal class ComputeImagePayloadConverter : IComputeImagePayloadConverter - { - /// - public ComputeImage ConvertImage(string payload) - { - payload.AssertIsNotNullOrEmpty("payload", "A null or empty compute image payload cannot be converted."); - - try - { - var token = JToken.Parse(payload); - return ConvertImage(token["image"]); - } - catch (FormatException) - { - throw; - } - catch (Exception ex) - { - throw new FormatException( - string.Format("Compute image payload could not be parsed. Payload: '{0}'", payload), ex); - } - } - - internal ComputeImage ConvertImage(JToken imageToken) - { - var name = string.Empty; - var id = string.Empty; - try - { - name = (string) imageToken["name"]; - id = (string) imageToken["id"]; - - if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(id)) - { - throw new FormatException(); - } - - var status = imageToken["status"] == null ? string.Empty : (string)imageToken["status"]; - var created = imageToken["created"] == null ? DateTime.MinValue : (DateTime)imageToken["created"]; - var updated = imageToken["updated"] == null ? DateTime.MinValue : (DateTime)imageToken["updated"]; - var minRam = imageToken["minRam"] == null ? 0 : (int)imageToken["minRam"]; - var minDisk = imageToken["minDisk"] == null ? 0 : (int)imageToken["minDisk"]; ; - var progress = imageToken["progress"] == null ? 0 : (int)imageToken["progress"]; ; - - var permalink = string.Empty; - var publicLink = string.Empty; - var links = imageToken["links"]; - if (links != null) - { - foreach (var linkToken in links) - { - switch (linkToken["rel"].Value().ToLower()) - { - case "self": - publicLink = linkToken["href"].Value(); - break; - case "bookmark": - permalink = linkToken["href"].Value(); - break; - } - } - } - - var metadata = new Dictionary(); - var metadataToken = imageToken["metadata"]; - if (metadataToken != null) - { - metadata = JsonConvert.DeserializeObject>(metadataToken.ToString()); - } - - return new ComputeImage(id, name, new Uri(publicLink), new Uri(permalink), metadata, status, created, updated, minDisk, minRam, progress); - } - catch (Exception ex) - { - var msg = "Compute image payload could not be parsed."; - if (!string.IsNullOrEmpty(name) && imageToken != null) - { - msg = string.Format( - "Compute image '{0}' with Id '{1}' payload could not be parsed. Payload: '{2}'", name, id, - imageToken); - } - else if (imageToken != null) - { - msg = string.Format("Compute image payload could not be parsed. Payload: '{0}'", imageToken); - } - - throw new FormatException(msg, ex); - } - } - - /// - public IEnumerable ConvertImages(string payload) - { - payload.AssertIsNotNull("payload", "A null compute images payload cannot be converted."); - - var images = new List(); - - if (String.IsNullOrEmpty(payload)) - { - return images; - } - - try - { - var payloadToken = JToken.Parse(payload); - var flavorsArray = payloadToken["images"]; - images.AddRange(flavorsArray.Select(ConvertImage)); - } - catch (FormatException) - { - throw; - } - catch (Exception ex) - { - throw new FormatException( - string.Format("Compute images payload could not be parsed. Payload: '{0}'", payload), ex); - } - - return images; - } - } -} diff --git a/OpenStack/OpenStack/Compute/ComputeItem.cs b/OpenStack/OpenStack/Compute/ComputeItem.cs deleted file mode 100644 index 2f6c84f..0000000 --- a/OpenStack/OpenStack/Compute/ComputeItem.cs +++ /dev/null @@ -1,58 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; - -namespace OpenStack.Compute -{ - public abstract class ComputeItem - { - /// - /// Gets the name of the Flavor. - /// - public string Name { get; private set; } - - /// - /// Gets the id of the Flavor. - /// - public string Id { get; private set; } - - /// - /// Gets the public Uri of the Flavor. - /// - public Uri PublicUri { get; private set; } - - /// - /// Gets the permanent Uri of the Flavor. - /// - public Uri PermanentUri { get; private set; } - - /// - /// Create a new instance of the ComputeItem class. - /// - /// The Id of the item. - /// The name of the item. - /// The public Uri for the item. - /// The permanent Uri of the item. - protected ComputeItem(string id, string name, Uri publicUri, Uri permanentUri) - { - this.Id = id; - this.Name = name; - this.PublicUri = publicUri; - this.PermanentUri = permanentUri; - } - } -} diff --git a/OpenStack/OpenStack/Compute/ComputeItemMetadataPayloadConverter.cs b/OpenStack/OpenStack/Compute/ComputeItemMetadataPayloadConverter.cs deleted file mode 100644 index e86fade..0000000 --- a/OpenStack/OpenStack/Compute/ComputeItemMetadataPayloadConverter.cs +++ /dev/null @@ -1,81 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using OpenStack.Common; - -namespace OpenStack.Compute -{ - internal class ComputeItemMetadataPayloadConverter : IComputeItemMetadataPayloadConverter - { - /// - public IDictionary Convert(string payload) - { - payload.AssertIsNotNullOrEmpty("payload", "A null or empty compute item metadata payload cannot be converted."); - var metdata = new Dictionary(); - - try - { - var token = JToken.Parse(payload); - var metadataToken = token["metadata"]; - if (metadataToken == null) - { - throw new FormatException(); - } - metdata = JsonConvert.DeserializeObject>(metadataToken.ToString()); - } - catch (FormatException) - { - throw; - } - catch (Exception ex) - { - throw new FormatException( - string.Format("Compute item metadata payload could not be parsed. Payload: '{0}'", payload), ex); - } - return metdata; - } - - /// - public string Convert(IDictionary metadata) - { - metadata.AssertIsNotNull("metadata", "Cannot convert compute item metadata with null metadata."); - - var payload = new StringBuilder(); - payload.Append("{ \"metadata\" : {"); - var isFirst = true; - - foreach (var item in metadata) - { - if (!isFirst) - { - payload.Append(","); - } - - payload.AppendFormat("\"{0}\":\"{1}\"",item.Key, item.Value); - isFirst = false; - } - - payload.Append("}}"); - return payload.ToString(); - } - } -} diff --git a/OpenStack/OpenStack/Compute/ComputeKeyPair.cs b/OpenStack/OpenStack/Compute/ComputeKeyPair.cs deleted file mode 100644 index 2e582e7..0000000 --- a/OpenStack/OpenStack/Compute/ComputeKeyPair.cs +++ /dev/null @@ -1,52 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -namespace OpenStack.Compute -{ - /// - /// Represents a key pair on the remote OpenStack instance. - /// - public class ComputeKeyPair - { - /// - /// GEts the name of the key pair. - /// - public string Name { get; internal set; } - - /// - /// The public key for this key pair. - /// - public string PublicKey { get; internal set; } - - /// - /// The fingerprint for this key pair. - /// - public string Fingerprint { get; internal set; } - - /// - /// Creates a new instance of the ComputeKeyPair class. - /// - /// The name for the key pair. - /// The public key for the key pair. - /// The fingerprint for the key pair. - public ComputeKeyPair(string name, string publicKey, string fingerprint) - { - this.Name = name; - this.PublicKey = publicKey; - this.Fingerprint = fingerprint; - } - } -} diff --git a/OpenStack/OpenStack/Compute/ComputeKeyPairPayloadConverter.cs b/OpenStack/OpenStack/Compute/ComputeKeyPairPayloadConverter.cs deleted file mode 100644 index f1fb2d0..0000000 --- a/OpenStack/OpenStack/Compute/ComputeKeyPairPayloadConverter.cs +++ /dev/null @@ -1,121 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; -using Newtonsoft.Json.Linq; -using OpenStack.Common; -using System.Linq; - -namespace OpenStack.Compute -{ - using System; - - /// - internal class ComputeKeyPairPayloadConverter : IComputeKeyPairPayloadConverter - { - /// - public ComputeKeyPair Convert(string payload) - { - payload.AssertIsNotNullOrEmpty("payload", "A null or empty compute key pair payload cannot be converted."); - - try - { - var token = JToken.Parse(payload); - return Convert(token["keypair"]); - } - catch (FormatException) - { - throw; - } - catch (Exception ex) - { - throw new FormatException( - string.Format("Compute key pair payload could not be parsed. Payload: '{0}'", payload), ex); - } - } - - /// - /// Converts a Json token to a ComputeKeyPair object. - /// - /// The token to convert. - /// A ComputeKeyPair object. - internal ComputeKeyPair Convert(JToken keyPairToken) - { - var name = string.Empty; - var fingerprint = string.Empty; - var publicKey = string.Empty; - try - { - name = (string) keyPairToken["name"]; - fingerprint = (string)keyPairToken["fingerprint"] ?? string.Empty; - publicKey = (string)keyPairToken["public_key"] ?? string.Empty; - - if (string.IsNullOrEmpty(name)) - { - throw new FormatException(); - } - - return new ComputeKeyPair(name, publicKey, fingerprint); - } - catch (Exception ex) - { - var msg = "Compute key pair payload could not be parsed."; - if (!string.IsNullOrEmpty(name) && keyPairToken != null) - { - msg = string.Format( - "Compute key pair '{0}' payload could not be parsed. Payload: '{1}'", name, keyPairToken); - } - else if (keyPairToken != null) - { - msg = string.Format("Compute key pair payload could not be parsed. Payload: '{0}'", keyPairToken); - } - - throw new FormatException(msg, ex); - } - } - - /// - public IEnumerable ConvertKeyPairs(string payload) - { - payload.AssertIsNotNull("payload", "A null compute key pair payload cannot be converted."); - - var keyPairs = new List(); - - if (String.IsNullOrEmpty(payload)) - { - return keyPairs; - } - - try - { - var payloadToken = JToken.Parse(payload); - var keyPairArray = payloadToken["keypairs"]; - keyPairs.AddRange(keyPairArray.Select(token => Convert(token["keypair"]))); - } - catch (FormatException) - { - throw; - } - catch (Exception ex) - { - throw new FormatException( - string.Format("Compute key pair payload could not be parsed. Payload: '{0}'", payload), ex); - } - - return keyPairs; - } - } -} diff --git a/OpenStack/OpenStack/Compute/ComputeServer.cs b/OpenStack/OpenStack/Compute/ComputeServer.cs deleted file mode 100644 index 97e5cdc..0000000 --- a/OpenStack/OpenStack/Compute/ComputeServer.cs +++ /dev/null @@ -1,91 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; - -namespace OpenStack.Compute -{ - /// - /// Represents a compute server on a remote instance of OpenStack. - /// - public class ComputeServer : MetadataComputeItem - { - /// - /// Gets the current status of the compute server. - /// - public ComputeServerStatus Status { get; internal set; } - - /// - /// Gets the progress of the current server action. - /// - public int Progress { get; internal set; } - - /// - /// Gets the administrative password for this server (only available after creating a new server). - /// - public string AdminPassword { get; internal set; } - - /// - /// Creates a new instance of the ComputeServer class. - /// - /// The id of the compute server. - /// The name of the compute server. - /// The public Uri for the compute server. - /// The permanent Uri for the computer server. - /// Metadata associated with the compute server. - internal ComputeServer(string id, string name, Uri publicUri, Uri permanentUri, - IDictionary metadata) : base(id, name, publicUri, permanentUri, metadata) - { - this.Status = ComputeServerStatus.Unknown; - } - - /// - /// Creates a new instance of the ComputeServer class. - /// - /// The id of the compute server. - /// The name of the compute server. - /// The administrative password for the compute instance. - /// The public Uri for the compute server. - /// The permanent Uri for the computer server. - /// Metadata associated with the compute server. - internal ComputeServer(string id, string name, string adminPassword, Uri publicUri, Uri permanentUri, - IDictionary metadata) - : base(id, name, publicUri, permanentUri, metadata) - { - this.Status = ComputeServerStatus.Unknown; - this.AdminPassword = adminPassword; - } - - /// - /// Creates a new instance of the ComputeServer class. - /// - /// The id of the compute server. - /// The name of the compute server. - /// The progress of the current action. - /// The public Uri for the compute server. - /// The permanent Uri for the computer server. - /// Metadata associated with the compute server. - internal ComputeServer(string id, string name, ComputeServerStatus status, int progress, Uri publicUri, Uri permanentUri, - IDictionary metadata) - : base(id, name, publicUri, permanentUri, metadata) - { - this.Status = status; - this.Progress = progress; - } - } - -} diff --git a/OpenStack/OpenStack/Compute/ComputeServerPayloadConverter.cs b/OpenStack/OpenStack/Compute/ComputeServerPayloadConverter.cs deleted file mode 100644 index 302d855..0000000 --- a/OpenStack/OpenStack/Compute/ComputeServerPayloadConverter.cs +++ /dev/null @@ -1,286 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using Newtonsoft.Json.Linq; -using OpenStack.Common; - -namespace OpenStack.Compute -{ - /// - internal class ComputeServerPayloadConverter : IComputeServerPayloadConverter - { - /// - public ComputeServer ConvertSummary(string payload) - { - payload.AssertIsNotNullOrEmpty("payload", "A null or empty compute server payload cannot be converted."); - - try - { - var token = JToken.Parse(payload); - return ConvertServerSummary(token["server"]); - } - catch (FormatException) - { - throw; - } - catch (Exception ex) - { - throw new FormatException( - string.Format("Compute server payload could not be parsed. Payload: '{0}'", payload), ex); - } - } - - /// - public ComputeServer Convert(string payload) - { - payload.AssertIsNotNullOrEmpty("payload", "A null or empty compute server payload cannot be converted."); - - try - { - var token = JToken.Parse(payload); - return ConvertServer(token["server"]); - } - catch (FormatException) - { - throw; - } - catch (Exception ex) - { - throw new FormatException( - string.Format("Compute server payload could not be parsed. Payload: '{0}'", payload), ex); - } - } - - /// - /// Converts a payload with a list of servers to an enumerable collection of ComputeServer objects. - /// - /// The payload to convert. - /// An enumerable list of ComputeServers. - public IEnumerable ConvertServers(string payload) - { - payload.AssertIsNotNull("payload", "A null compute servers payload cannot be converted."); - - var servers = new List(); - - if (String.IsNullOrEmpty(payload)) - { - return servers; - } - - try - { - var payloadToken = JToken.Parse(payload); - var serverArray = payloadToken["servers"]; - servers.AddRange(serverArray.Select(ConvertServerItem)); - } - catch (FormatException) - { - throw; - } - catch (Exception ex) - { - throw new FormatException( - string.Format("Compute servers payload could not be parsed. Payload: '{0}'", payload), ex); - } - - return servers; - } - - /// - /// Converts a json token into a ComputeServer object. - /// - /// The json Token to convert. - /// A ComputeServer object. - internal ComputeServer ConvertServerSummary(JToken serverToken) - { - - var id = string.Empty; - var adminPassword = string.Empty; - - try - { - adminPassword = (string)serverToken["adminPass"]; - id = (string)serverToken["id"]; - - if (string.IsNullOrEmpty(adminPassword) || string.IsNullOrEmpty(id)) - { - throw new FormatException(); - } - - var permalink = string.Empty; - var publicLink = string.Empty; - var links = serverToken["links"]; - if (links != null) - { - foreach (var linkToken in links) - { - switch (linkToken["rel"].Value().ToLower()) - { - case "self": - publicLink = linkToken["href"].Value(); - break; - case "bookmark": - permalink = linkToken["href"].Value(); - break; - } - } - } - - return new ComputeServer(id, id, adminPassword, new Uri(publicLink), new Uri(permalink), new Dictionary()); - } - catch (Exception ex) - { - var msg = "Compute server payload could not be parsed."; - if (!string.IsNullOrEmpty(id) && serverToken != null) - { - msg = string.Format( - "Compute server with Id '{0}' payload could not be parsed. Payload: '{1}'", id, serverToken); - } - else if (serverToken != null) - { - msg = string.Format("Compute server payload could not be parsed. Payload: '{0}'", serverToken); - } - - throw new FormatException(msg, ex); - } - } - - /// - /// Converts a json token into a ComputeServer object. - /// - /// The json Token to convert. - /// A ComputeServer object. - internal ComputeServer ConvertServerItem(JToken serverToken) - { - - var id = string.Empty; - var name = string.Empty; - - try - { - name = (string)serverToken["name"]; - id = (string)serverToken["id"]; - - if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(id)) - { - throw new FormatException(); - } - - var permalink = string.Empty; - var publicLink = string.Empty; - var links = serverToken["links"]; - if (links != null) - { - foreach (var linkToken in links) - { - switch (linkToken["rel"].Value().ToLower()) - { - case "self": - publicLink = linkToken["href"].Value(); - break; - case "bookmark": - permalink = linkToken["href"].Value(); - break; - } - } - } - - return new ComputeServer(id, name, new Uri(publicLink), new Uri(permalink), new Dictionary()); - } - catch (Exception ex) - { - var msg = "Compute server payload could not be parsed."; - if (!string.IsNullOrEmpty(id) && serverToken != null) - { - msg = string.Format( - "Compute server with Id '{0}' payload could not be parsed. Payload: '{1}'", id, serverToken); - } - else if (serverToken != null) - { - msg = string.Format("Compute server payload could not be parsed. Payload: '{0}'", serverToken); - } - - throw new FormatException(msg, ex); - } - } - - /// - /// Converts a json token into a ComputeServer object. - /// - /// The json Token to convert. - /// A ComputeServer object. - internal ComputeServer ConvertServer(JToken serverToken) - { - - var id = string.Empty; - var name = string.Empty; - var status = string.Empty; - - try - { - name = (string)serverToken["name"]; - status = (string)serverToken["status"]; - id = (string)serverToken["id"]; - - if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(id) || string.IsNullOrEmpty(status)) - { - throw new FormatException(); - } - - var permalink = string.Empty; - var publicLink = string.Empty; - var links = serverToken["links"]; - if (links != null) - { - foreach (var linkToken in links) - { - switch (linkToken["rel"].Value().ToLower()) - { - case "self": - publicLink = linkToken["href"].Value(); - break; - case "bookmark": - permalink = linkToken["href"].Value(); - break; - } - } - } - - var progress = serverToken["progress"] != null ? (int)serverToken["progress"] : 0; - - return new ComputeServer(id, name, status.GetComputeServerStatus(), progress, new Uri(publicLink), new Uri(permalink), new Dictionary()); - } - catch (Exception ex) - { - var msg = "Compute server payload could not be parsed."; - if (!string.IsNullOrEmpty(id) && serverToken != null) - { - msg = string.Format( - "Compute server with Id '{0}' payload could not be parsed. Payload: '{1}'", id, serverToken); - } - else if (serverToken != null) - { - msg = string.Format("Compute server payload could not be parsed. Payload: '{0}'", serverToken); - } - - throw new FormatException(msg, ex); - } - } - } -} diff --git a/OpenStack/OpenStack/Compute/ComputeServiceClient.cs b/OpenStack/OpenStack/Compute/ComputeServiceClient.cs deleted file mode 100644 index fafd57a..0000000 --- a/OpenStack/OpenStack/Compute/ComputeServiceClient.cs +++ /dev/null @@ -1,233 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using OpenStack.Common; -using OpenStack.Common.ServiceLocation; -using OpenStack.Identity; - -namespace OpenStack.Compute -{ - /// - internal class ComputeServiceClient : IComputeServiceClient - { - internal ServiceClientContext Context; - internal IServiceLocator ServiceLocator; - - /// - /// Creates a new instance of the ComputeServiceClient class. - /// - /// The credential to be used by this client. - /// The cancellation token to be used by this client. - /// The name of the service to be used by this client. - /// A service locator to be used to locate/inject dependent services. - public ComputeServiceClient(IOpenStackCredential credentials, string serviceName, CancellationToken token, IServiceLocator serviceLocator) - { - serviceLocator.AssertIsNotNull("serviceLocator", "Cannot create a storage service client with a null service locator."); - - this.ServiceLocator = serviceLocator; - var endpoint = new Uri(credentials.ServiceCatalog.GetPublicEndpoint(serviceName, credentials.Region)); - this.Context = new ServiceClientContext(credentials, token, serviceName, endpoint); - } - - /// - public async Task> GetFlavors() - { - var client = this.GetPocoClient(); - return await client.GetFlavors(); - } - - /// - public async Task GetFlavor(string flavorId) - { - flavorId.AssertIsNotNullOrEmpty("flavorId", "Cannot get a compute flavor with a null or empty id."); - - var client = this.GetPocoClient(); - return await client.GetFlavor(flavorId); - } - - /// - public async Task DeleteServer(string serverId) - { - serverId.AssertIsNotNullOrEmpty("serverId", "Cannot delete a compute server with a null or empty id."); - - var client = this.GetPocoClient(); - await client.DeleteServer(serverId); - } - - /// - public async Task> GetServers() - { - var client = this.GetPocoClient(); - return await client.GetServers(); - } - - /// - public async Task GetServer(string serverId) - { - serverId.AssertIsNotNullOrEmpty("serverId", "Cannot get compute server with a null or empty id."); - - var client = this.GetPocoClient(); - return await client.GetServer(serverId); - } - - /// - public async Task AssignFloatingIp(string serverId, string ipAddress) - { - serverId.AssertIsNotNullOrEmpty("serverId", "Cannot assign a floating ip to a compute server with a null or empty id."); - ipAddress.AssertIsNotNullOrEmpty("ipAddress", "Cannot assign a floating ip to a compute server with a null or empty ip address."); - - var client = this.GetPocoClient(); - await client.AssignFloatingIp(serverId, ipAddress); - } - - /// - public async Task> GetServerMetadata(string serverId) - { - serverId.AssertIsNotNullOrEmpty("serverId", "Cannot get compute server metadata with a null or empty id."); - - var client = this.GetPocoClient(); - return await client.GetServerMetadata(serverId); - } - - /// - public async Task UpdateServerMetadata(string serverId, IDictionary metadata) - { - serverId.AssertIsNotNullOrEmpty("flavorId", "Cannot update compute server metadata with a null or empty id."); - metadata.AssertIsNotNull("metadata", "Cannot update compute server metadata with a null or empty metadata."); - - var client = this.GetPocoClient(); - await client.UpdateServerMetadata(serverId, metadata); - } - - /// - public async Task DeleteServerMetadata(string flavorId, string key) - { - flavorId.AssertIsNotNullOrEmpty("flavorId", "Cannot delete a compute flavor metadata item with a null or empty id."); - key.AssertIsNotNullOrEmpty("key", "Cannot delete a compute flavor metadata item with a null or empty key."); - - var client = this.GetPocoClient(); - await client.DeleteServerMetadata(flavorId, key); - } - - /// - public async Task> GetKeyPairs() - { - var client = this.GetPocoClient(); - return await client.GetKeyPairs(); - } - - /// - public async Task GetKeyPair(string keyPairName) - { - keyPairName.AssertIsNotNullOrEmpty("keyPairName", "Cannot get compute key pair with a null or empty name."); - - var client = this.GetPocoClient(); - return await client.GetKeyPair(keyPairName); - } - - /// - public async Task> GetImages() - { - var client = this.GetPocoClient(); - return await client.GetImages(); - } - - /// - public async Task GetImage(string imageId) - { - imageId.AssertIsNotNullOrEmpty("imageId", "Cannot get a compute image with a null or empty id."); - - var client = this.GetPocoClient(); - return await client.GetImage(imageId); - } - - /// - public async Task DeleteImage(string imageId) - { - imageId.AssertIsNotNullOrEmpty("imageId", "Cannot delete a compute image with a null or empty id."); - - var client = this.GetPocoClient(); - await client.DeleteImage(imageId); - } - - /// - public async Task> GetImageMetadata(string imageId) - { - imageId.AssertIsNotNullOrEmpty("flavorId", "Cannot get compute image metadata with a null or empty id."); - - var client = this.GetPocoClient(); - return await client.GetImageMetadata(imageId); - } - - /// - public async Task UpdateImageMetadata(string imageId, IDictionary metadata) - { - imageId.AssertIsNotNullOrEmpty("imageId", "Cannot update compute image metadata with a null or empty id."); - metadata.AssertIsNotNull("metadata", "Cannot update compute image metadata with a null or empty metadata."); - - var client = this.GetPocoClient(); - await client.UpdateImageMetadata(imageId, metadata); - } - - /// - public async Task DeleteImageMetadata(string imageId, string key) - { - imageId.AssertIsNotNullOrEmpty("imageId", "Cannot delete a compute image metadata item with a null or empty id."); - key.AssertIsNotNullOrEmpty("key", "Cannot delete a compute image metadata item with a null or empty key."); - - var client = this.GetPocoClient(); - await client.DeleteImageMetadata(imageId, key); - } - - /// - public async Task CreateServer(string name, string imageId, string flavorId, string networkId, IEnumerable securityGroups) - { - name.AssertIsNotNullOrEmpty("name", "Cannot create a server with a null or empty name."); - imageId.AssertIsNotNullOrEmpty("imageId", "Cannot create a server with a null or empty image id."); - flavorId.AssertIsNotNullOrEmpty("flavorId", "Cannot create a server with a null or empty flavor id."); - networkId.AssertIsNotNullOrEmpty("networkId", "Cannot create a server with a null or empty network id."); - - var client = this.GetPocoClient(); - return await client.CreateServer(name, imageId, flavorId, networkId, string.Empty, securityGroups); - } - - /// - public async Task CreateServer(string name, string imageId, string flavorId, string networkId, string keyName, IEnumerable securityGroups) - { - name.AssertIsNotNullOrEmpty("name", "Cannot create a server with a null or empty name."); - imageId.AssertIsNotNullOrEmpty("imageId", "Cannot create a server with a null or empty image id."); - flavorId.AssertIsNotNullOrEmpty("flavorId", "Cannot create a server with a null or empty flavor id."); - networkId.AssertIsNotNullOrEmpty("networkId", "Cannot create a server with a null or empty network id."); - keyName.AssertIsNotNull("keyName", "Cannot create a server with a null key name."); - - var client = this.GetPocoClient(); - return await client.CreateServer(name, imageId, flavorId, networkId, keyName, securityGroups); - } - - /// - /// Gets a client to interact with the remote OpenStack instance. - /// - /// A POCO client. - internal IComputeServicePocoClient GetPocoClient() - { - return this.ServiceLocator.Locate().Create(this.Context, this.ServiceLocator); - } - } -} diff --git a/OpenStack/OpenStack/Compute/ComputeServiceClientDefinition.cs b/OpenStack/OpenStack/Compute/ComputeServiceClientDefinition.cs deleted file mode 100644 index 7408d61..0000000 --- a/OpenStack/OpenStack/Compute/ComputeServiceClientDefinition.cs +++ /dev/null @@ -1,80 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -namespace OpenStack.Compute -{ - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading; - using OpenStack.Common.ServiceLocation; - using OpenStack.Identity; - - /// - internal class ComputeServiceClientDefinition : IOpenStackServiceClientDefinition - { - internal const string DefaultServiceName = "Nova"; - - /// - public string Name { get; private set; } - - /// - /// Creates a new instance of the ComputeServiceClientDefinition class. - /// - public ComputeServiceClientDefinition() - { - this.Name = typeof (ComputeServiceClient).Name; - } - - /// - public IOpenStackServiceClient Create(ICredential credential, string serviceName, CancellationToken cancellationToken, IServiceLocator serviceLocator) - { - return new ComputeServiceClient((IOpenStackCredential)credential, GetServiceName(serviceName), cancellationToken, serviceLocator); - } - - /// - public IEnumerable ListSupportedVersions() - { - return new List() { "2.0", "2" }; - } - - /// - public bool IsSupported(ICredential credential, string serviceName) - { - if (credential == null || credential.ServiceCatalog == null) - { - return false; - } - - var catalog = credential.ServiceCatalog; - return - catalog.Any( - s => - string.Equals(s.Name, GetServiceName(serviceName), StringComparison.OrdinalIgnoreCase) && - s.Endpoints.Any(e => this.ListSupportedVersions().Contains(e.Version) || e.PublicUri.Contains("/v2"))); - } - - /// - /// Gets the service name to use. - /// - /// The given service name. - /// The given service name if it is not empty or null, otherwise the default service name will be returned. - internal string GetServiceName(string serviceName) - { - return string.IsNullOrEmpty(serviceName) ? DefaultServiceName : serviceName; - } - } -} diff --git a/OpenStack/OpenStack/Compute/ComputeServicePocoClient.cs b/OpenStack/OpenStack/Compute/ComputeServicePocoClient.cs deleted file mode 100644 index c5c639b..0000000 --- a/OpenStack/OpenStack/Compute/ComputeServicePocoClient.cs +++ /dev/null @@ -1,326 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Net; -using System.Threading.Tasks; -using OpenStack.Common; -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Compute -{ - /// - internal class ComputeServicePocoClient : IComputeServicePocoClient - { - internal ServiceClientContext _context; - internal IServiceLocator ServiceLocator; - - /// - /// Creates a new instance of the ComputeServicePocoClient class. - /// - /// The compute service context to use for this client. - /// A service locator to be used to locate/inject dependent services. - internal ComputeServicePocoClient(ServiceClientContext context, IServiceLocator serviceLocator) - { - serviceLocator.AssertIsNotNull("serviceLocator", "Cannot create a storage service poco client with a null service locator."); - - this._context = context; - this.ServiceLocator = serviceLocator; - } - - /// - public async Task> GetFlavors() - { - var client = this.GetRestClient(); - var resp = await client.GetFlavors(); - - if (resp.StatusCode != HttpStatusCode.OK && resp.StatusCode != HttpStatusCode.NonAuthoritativeInformation) - { - throw new InvalidOperationException(string.Format("Failed to get compute flavors. The remote server returned the following status code: '{0}'.", resp.StatusCode)); - } - - var converter = this.ServiceLocator.Locate(); - var flavors = converter.ConvertFlavors(await resp.ReadContentAsStringAsync()); - - return flavors; - } - - /// - public async Task GetFlavor(string flavorId) - { - var client = this.GetRestClient(); - var resp = await client.GetFlavor(flavorId); - - if (resp.StatusCode != HttpStatusCode.OK && resp.StatusCode != HttpStatusCode.NonAuthoritativeInformation) - { - throw new InvalidOperationException(string.Format("Failed to get compute flavor. The remote server returned the following status code: '{0}'.", resp.StatusCode)); - } - - var converter = this.ServiceLocator.Locate(); - var flavor = converter.ConvertFlavor(await resp.ReadContentAsStringAsync()); - - return flavor; - } - - /// - public async Task> GetServerMetadata(string flavorId) - { - var client = this.GetRestClient(); - var resp = await client.GetServerMetadata(flavorId); - - if (resp.StatusCode != HttpStatusCode.OK && resp.StatusCode != HttpStatusCode.NonAuthoritativeInformation) - { - throw new InvalidOperationException(string.Format("Failed to get compute server metadata. The remote server returned the following status code: '{0}'.", resp.StatusCode)); - } - - var converter = this.ServiceLocator.Locate(); - var metadata = converter.Convert(await resp.ReadContentAsStringAsync()); - - return metadata; - } - - /// - public async Task UpdateServerMetadata(string flavorId, IDictionary metadata) - { - var client = this.GetRestClient(); - var resp = await client.UpdateServerMetadata(flavorId, metadata); - - if (resp.StatusCode != HttpStatusCode.OK) - { - throw new InvalidOperationException(string.Format("Failed to update compute server metadata. The remote server returned the following status code: '{0}'.", resp.StatusCode)); - } - } - - /// - public async Task DeleteServerMetadata(string flavorId, string key) - { - var client = this.GetRestClient(); - var resp = await client.DeleteServerMetadata(flavorId, key); - - if (resp.StatusCode != HttpStatusCode.OK && resp.StatusCode != HttpStatusCode.NoContent) - { - throw new InvalidOperationException(string.Format("Failed to delete compute server metadata. The remote server returned the following status code: '{0}'.", resp.StatusCode)); - } - } - - /// - public async Task> GetKeyPairs() - { - var client = this.GetRestClient(); - var resp = await client.GetKeyPairs(); - - if (resp.StatusCode != HttpStatusCode.OK && resp.StatusCode != HttpStatusCode.NonAuthoritativeInformation) - { - throw new InvalidOperationException(string.Format("Failed to get compute key pairs. The remote server returned the following status code: '{0}'.", resp.StatusCode)); - } - - var converter = this.ServiceLocator.Locate(); - var pairs = converter.ConvertKeyPairs(await resp.ReadContentAsStringAsync()); - - return pairs; - } - - /// - public async Task GetKeyPair(string keyPairName) - { - var client = this.GetRestClient(); - var resp = await client.GetKeyPair(keyPairName); - - if (resp.StatusCode != HttpStatusCode.OK && resp.StatusCode != HttpStatusCode.NonAuthoritativeInformation) - { - throw new InvalidOperationException(string.Format("Failed to get compute key pair. The remote server returned the following status code: '{0}'.", resp.StatusCode)); - } - - var converter = this.ServiceLocator.Locate(); - var keyPair = converter.Convert(await resp.ReadContentAsStringAsync()); - - return keyPair; - } - - /// - public async Task> GetImages() - { - var client = this.GetRestClient(); - var resp = await client.GetImages(); - - if (resp.StatusCode != HttpStatusCode.OK && resp.StatusCode != HttpStatusCode.NonAuthoritativeInformation) - { - throw new InvalidOperationException(string.Format("Failed to get compute images. The remote server returned the following status code: '{0}'.", resp.StatusCode)); - } - - var converter = this.ServiceLocator.Locate(); - var flavors = converter.ConvertImages(await resp.ReadContentAsStringAsync()); - - return flavors; - } - - /// - public async Task GetImage(string imageId) - { - var client = this.GetRestClient(); - var resp = await client.GetImage(imageId); - - if (resp.StatusCode != HttpStatusCode.OK && resp.StatusCode != HttpStatusCode.NonAuthoritativeInformation) - { - throw new InvalidOperationException(string.Format("Failed to get compute image. The remote server returned the following status code: '{0}'.", resp.StatusCode)); - } - - var converter = this.ServiceLocator.Locate(); - var image = converter.ConvertImage(await resp.ReadContentAsStringAsync()); - - return image; - } - - /// - public async Task DeleteImage(string imageId) - { - var client = this.GetRestClient(); - var resp = await client.DeleteImage(imageId); - - if (resp.StatusCode != HttpStatusCode.OK && resp.StatusCode != HttpStatusCode.NoContent) - { - throw new InvalidOperationException(string.Format("Failed to delete compute image. The remote server returned the following status code: '{0}'.", resp.StatusCode)); - } - } - - /// - public async Task CreateServer(string name, string imageId, string flavorId, string networkId, string keyName, - IEnumerable securityGroups) - { - var client = this.GetRestClient(); - var resp = await client.CreateServer(name, imageId, flavorId, networkId, keyName, securityGroups); - - if (resp.StatusCode != HttpStatusCode.Accepted && resp.StatusCode != HttpStatusCode.OK) - { - throw new InvalidOperationException(string.Format("Failed to create compute server. The remote server returned the following status code: '{0}'.", resp.StatusCode)); - } - - var converter = this.ServiceLocator.Locate(); - var metadata = converter.ConvertSummary(await resp.ReadContentAsStringAsync()); - - return metadata; - } - - /// - public async Task DeleteServer(string serverId) - { - var client = this.GetRestClient(); - var resp = await client.DeleteServer(serverId); - - if (resp.StatusCode != HttpStatusCode.OK && resp.StatusCode != HttpStatusCode.NoContent) - { - throw new InvalidOperationException(string.Format("Failed to delete compute server. The remote server returned the following status code: '{0}'.", resp.StatusCode)); - } - } - - /// - public async Task> GetServers() - { - var client = this.GetRestClient(); - var resp = await client.GetServers(); - - if (resp.StatusCode != HttpStatusCode.OK && resp.StatusCode != HttpStatusCode.NonAuthoritativeInformation) - { - throw new InvalidOperationException(string.Format("Failed to get compute images. The remote server returned the following status code: '{0}'.", resp.StatusCode)); - } - - var converter = this.ServiceLocator.Locate(); - var servers = converter.ConvertServers(await resp.ReadContentAsStringAsync()); - - return servers; - } - - /// - public async Task GetServer(string serverId) - { - var client = this.GetRestClient(); - var resp = await client.GetServer(serverId); - - if (resp.StatusCode != HttpStatusCode.OK && resp.StatusCode != HttpStatusCode.NonAuthoritativeInformation) - { - throw new InvalidOperationException(string.Format("Failed to get compute server. The remote server returned the following status code: '{0}'.", resp.StatusCode)); - } - - var converter = this.ServiceLocator.Locate(); - var flavor = converter.Convert(await resp.ReadContentAsStringAsync()); - - return flavor; - } - - /// - public async Task AssignFloatingIp(string serverId, string ipAddress) - { - var client = this.GetRestClient(); - var resp = await client.AssignFloatingIp(serverId, ipAddress); - - if (resp.StatusCode != HttpStatusCode.OK && resp.StatusCode != HttpStatusCode.Accepted) - { - throw new InvalidOperationException(string.Format("Failed to assign floating ip. The remote server returned the following status code: '{0}'.", resp.StatusCode)); - } - } - - /// - public async Task> GetImageMetadata(string imageId) - { - var client = this.GetRestClient(); - var resp = await client.GetImageMetadata(imageId); - - if (resp.StatusCode != HttpStatusCode.OK && resp.StatusCode != HttpStatusCode.NonAuthoritativeInformation) - { - throw new InvalidOperationException(string.Format("Failed to get compute image metadata. The remote server returned the following status code: '{0}'.", resp.StatusCode)); - } - - var converter = this.ServiceLocator.Locate(); - var metadata = converter.Convert(await resp.ReadContentAsStringAsync()); - - return metadata; - } - - /// - public async Task UpdateImageMetadata(string imageId, IDictionary metadata) - { - var client = this.GetRestClient(); - var resp = await client.UpdateImageMetadata(imageId, metadata); - - if (resp.StatusCode != HttpStatusCode.OK) - { - throw new InvalidOperationException(string.Format("Failed to update compute image metadata. The remote server returned the following status code: '{0}'.", resp.StatusCode)); - } - } - - /// - public async Task DeleteImageMetadata(string imageId, string key) - { - var client = this.GetRestClient(); - var resp = await client.DeleteImageMetadata(imageId, key); - - if (resp.StatusCode != HttpStatusCode.OK && resp.StatusCode != HttpStatusCode.NoContent) - { - throw new InvalidOperationException(string.Format("Failed to delete compute image metadata. The remote server returned the following status code: '{0}'.", resp.StatusCode)); - } - } - - /// - /// Gets a client that can be used to connect to the REST endpoints of an OpenStack compute service. - /// - /// The client. - internal IComputeServiceRestClient GetRestClient() - { - return this.ServiceLocator.Locate().Create(this._context, this.ServiceLocator); - } - } -} diff --git a/OpenStack/OpenStack/Compute/ComputeServicePocoClientFactory.cs b/OpenStack/OpenStack/Compute/ComputeServicePocoClientFactory.cs deleted file mode 100644 index 39913ae..0000000 --- a/OpenStack/OpenStack/Compute/ComputeServicePocoClientFactory.cs +++ /dev/null @@ -1,31 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Compute -{ - /// - internal class ComputeServicePocoClientFactory :IComputeServicePocoClientFactory - { - /// - public IComputeServicePocoClient Create(ServiceClientContext context, IServiceLocator serviceLocator) - { - return new ComputeServicePocoClient(context, serviceLocator); - } - } -} diff --git a/OpenStack/OpenStack/Compute/ComputeServiceRestClient.cs b/OpenStack/OpenStack/Compute/ComputeServiceRestClient.cs deleted file mode 100644 index 73646ca..0000000 --- a/OpenStack/OpenStack/Compute/ComputeServiceRestClient.cs +++ /dev/null @@ -1,325 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; -using Newtonsoft.Json.Linq; - -namespace OpenStack.Compute -{ - using System; - using System.Threading.Tasks; - using OpenStack.Common.Http; - using OpenStack.Common; - using OpenStack.Common.ServiceLocation; - using System.Net.Http; - - /// - internal class ComputeServiceRestClient : OpenStackServiceRestClientBase, IComputeServiceRestClient - { - internal const string MetadataUrlMoniker = "metadata"; - internal const string ImagesUrlMoniker = "images"; - internal const string FlavorsUrlMoniker = "flavors"; - internal const string ServersUrlMoniker = "servers"; - internal const string ActionUrlMoniker = "action"; - internal const string KeyPairUrlMoniker = "os-keypairs"; - - /// - /// Creates a new instance of the ComputeServiceRestClient class. - /// - /// The current service client context to use. - /// A service locator to be used to locate/inject dependent services. - internal ComputeServiceRestClient(ServiceClientContext context, IServiceLocator serviceLocator) - : base(context, serviceLocator) - { - } - - /// - public async Task GetFlavors() - { - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, FlavorsUrlMoniker); - client.Method = HttpMethod.Get; - - return await client.SendAsync(); - } - - /// - public async Task GetFlavor(string flavorId) - { - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, FlavorsUrlMoniker, flavorId); - client.Method = HttpMethod.Get; - - return await client.SendAsync(); - } - - /// - public async Task GetServers() - { - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, ServersUrlMoniker); - client.Method = HttpMethod.Get; - - return await client.SendAsync(); - } - - /// - public async Task GetServer(string serverId) - { - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, ServersUrlMoniker, serverId); - client.Method = HttpMethod.Get; - - return await client.SendAsync(); - } - - /// - public async Task DeleteServer(string serverId) - { - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, ServersUrlMoniker, serverId); - client.Method = HttpMethod.Delete; - - return await client.SendAsync(); - } - - /// - public async Task AssignFloatingIp(string serverId, string ipAddress) - { - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, ServersUrlMoniker, serverId, ActionUrlMoniker); - client.Method = HttpMethod.Post; - - var requestBody = this.GenerateAssignFloatingIpRequestBody(ipAddress); - client.Content = requestBody.ConvertToStream(); - client.ContentType = "application/json"; - - return await client.SendAsync(); - } - - /// - public async Task GetServerMetadata(string serverId) - { - return await GetItemMetadata(ServersUrlMoniker, serverId); - } - - /// - public async Task UpdateServerMetadata(string serverId, - IDictionary metadata) - { - return await UpdateItemMetadata(ServersUrlMoniker, serverId, metadata); - } - - /// - public async Task DeleteServerMetadata(string serverId, string key) - { - return await DeleteItemMetadata(ServersUrlMoniker, serverId, key); - } - - /// - public async Task GetKeyPairs() - { - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, KeyPairUrlMoniker); - client.Method = HttpMethod.Get; - - return await client.SendAsync(); - } - - /// - public async Task GetKeyPair(string keyPairName) - { - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, KeyPairUrlMoniker, keyPairName); - client.Method = HttpMethod.Get; - - return await client.SendAsync(); - } - - /// - public async Task GetImages() - { - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, ImagesUrlMoniker, "detail"); - client.Method = HttpMethod.Get; - - return await client.SendAsync(); - } - - /// - public async Task GetImage(string imageId) - { - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, ImagesUrlMoniker, imageId); - client.Method = HttpMethod.Get; - - return await client.SendAsync(); - } - - /// - public async Task DeleteImage(string imageId) - { - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, ImagesUrlMoniker, imageId); - client.Method = HttpMethod.Delete; - - return await client.SendAsync(); - } - - /// - public async Task GetImageMetadata(string imageId) - { - return await GetItemMetadata(ImagesUrlMoniker, imageId); - } - - /// - public async Task UpdateImageMetadata(string imageId, - IDictionary metadata) - { - return await UpdateItemMetadata(ImagesUrlMoniker, imageId, metadata); - } - - /// - public async Task DeleteImageMetadata(string imageId, string key) - { - return await DeleteItemMetadata(ImagesUrlMoniker, imageId, key); - } - - /// - public async Task CreateServer(string name, string imageId, string flavorId, string networkId, string keyName, - IEnumerable securityGroups) - { - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, ServersUrlMoniker); - client.Method = HttpMethod.Post; - - var requestBody = this.GenerateCreateServerRequestBody(name, imageId, flavorId, networkId, keyName, securityGroups); - client.Content = requestBody.ConvertToStream(); - client.ContentType = "application/json"; - - return await client.SendAsync(); - } - - /// - internal async Task DeleteItemMetadata(string itemType, string itemId, string key) - { - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, itemType, itemId, MetadataUrlMoniker, key); - client.Method = HttpMethod.Delete; - - return await client.SendAsync(); - } - - /// - internal async Task UpdateItemMetadata(string itemType, string itemId, IDictionary metadata) - { - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, itemType, itemId, MetadataUrlMoniker); - client.ContentType = "application/json"; - client.Method = HttpMethod.Post; - - var converter = this.ServiceLocator.Locate(); - var payload = converter.Convert(metadata); - - client.Content = payload.ConvertToStream(); - - return await client.SendAsync(); - } - - /// - internal async Task GetItemMetadata(string itemType, string itemId) - { - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, itemType, itemId, MetadataUrlMoniker); - client.Method = HttpMethod.Get; - - return await client.SendAsync(); - } - - /// - /// Generates a request body for creating compute servers. - /// - /// The name of the server. - /// The id of the image to use. - /// The id of the flavor to use. - /// The id of the network to attach the server to. - /// The name of the key to associate this server with. - /// A list of security groups to associate the server with. - /// A json encoded request body. - internal string GenerateCreateServerRequestBody(string name, string imageId, string flavorId, string networkId, string keyName, IEnumerable securityGroups) - { - var secGroups = new List(); - foreach (var g in securityGroups) - { - dynamic group = new System.Dynamic.ExpandoObject(); - group.name = g; - secGroups.Add(group); - } - - dynamic network = new System.Dynamic.ExpandoObject(); - network.uuid = networkId; - - dynamic server = new System.Dynamic.ExpandoObject(); - server.name = name; - server.imageRef = imageId; - server.flavorRef = flavorId; - server.max_count = "1"; - server.min_count = "1"; - - if (!string.IsNullOrEmpty(keyName)) - { - server.key_name = keyName; - } - - server.networks = new List() { network }; - server.security_groups = secGroups; - - dynamic body = new System.Dynamic.ExpandoObject(); - body.server = server; - return JToken.FromObject(body).ToString(); - } - - /// - /// Generates a request body for creating compute servers. - /// - /// The ip address to assign. - /// A json encoded request body. - internal string GenerateAssignFloatingIpRequestBody(string ipAddress) - { - dynamic addIpAddress = new System.Dynamic.ExpandoObject(); - addIpAddress.address = ipAddress; - - dynamic body = new System.Dynamic.ExpandoObject(); - body.addFloatingIp = addIpAddress; - return JToken.FromObject(body).ToString(); - } - } -} diff --git a/OpenStack/OpenStack/Compute/ComputeServiceRestClientFactory.cs b/OpenStack/OpenStack/Compute/ComputeServiceRestClientFactory.cs deleted file mode 100644 index c7e2bfb..0000000 --- a/OpenStack/OpenStack/Compute/ComputeServiceRestClientFactory.cs +++ /dev/null @@ -1,30 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Compute -{ - /// - internal class ComputeServiceRestClientFactory : IComputeServiceRestClientFactory - { - /// - public IComputeServiceRestClient Create(ServiceClientContext context, IServiceLocator serviceLocator) - { - return new ComputeServiceRestClient(context, serviceLocator); - } - } -} diff --git a/OpenStack/OpenStack/Compute/ComputerServerStatus.cs b/OpenStack/OpenStack/Compute/ComputerServerStatus.cs deleted file mode 100644 index d3c87ca..0000000 --- a/OpenStack/OpenStack/Compute/ComputerServerStatus.cs +++ /dev/null @@ -1,144 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using OpenStack.Common; - -namespace OpenStack.Compute -{ - /// - /// Represents the states that a Compute Server can be in. - /// - public enum ComputeServerStatus - { - /// - /// The compute server is active and available. - /// - Active, - - /// - /// The compute server is down and unavailable. - /// - Build, - - /// - /// The compute server has been deleted. - /// - Deleted, - - /// - /// The compute server is in an error state. - /// - Error, - - /// - /// The compute server is being hard rebooted. - /// - Hard_Reboot, - - /// - /// The compute server is having its password reset. - /// - Password, - - /// - /// The compute server is being soft rebooted. - /// - Reboot, - - /// - /// The compute server is being rebuilt. - /// - Rebuild, - - /// - /// The compute server in rescue mode. - /// - Rescue, - - /// - /// The compute server being resized. - /// - Revert_Resize, - - /// - /// The compute server is shut off. - /// - Shutoff, - - /// - /// The compute server is suspended. - /// - Suspended, - - /// - /// The compute server is awaiting verification that a resize operation was successful. - /// - Verify_Resize, - - /// - /// The compute server is in an unknown state. - /// - Unknown - } - - /// - /// Static class for holding ComputeServer related extension methods. - /// - public static class ComputeServerStatusExtentions - { - /// - /// Creates a ComputeServerStatus enum from a string. - /// - /// The input string. - /// A ComputeServerStatus enum. - public static ComputeServerStatus GetComputeServerStatus(this string input) - { - input.AssertIsNotNullOrEmpty("input", "Cannot get computer server status with null or empty value."); - - switch (input.ToLowerInvariant()) - { - case "active": - return ComputeServerStatus.Active; - case "build": - return ComputeServerStatus.Build; - case "deleted": - return ComputeServerStatus.Deleted; - case "error": - return ComputeServerStatus.Error; - case "hard_reboot": - return ComputeServerStatus.Hard_Reboot; - case "password": - return ComputeServerStatus.Password; - case "reboot": - return ComputeServerStatus.Reboot; - case "rebuild": - return ComputeServerStatus.Rebuild; - case "rescue": - return ComputeServerStatus.Rescue; - case "revert_resize": - return ComputeServerStatus.Revert_Resize; - case "shutoff": - return ComputeServerStatus.Shutoff; - case "suspended": - return ComputeServerStatus.Suspended; - case "verify_resize": - return ComputeServerStatus.Verify_Resize; - default: - return ComputeServerStatus.Unknown; - } - } - } -} diff --git a/OpenStack/OpenStack/Compute/IComputeFlavorPayloadConverter.cs b/OpenStack/OpenStack/Compute/IComputeFlavorPayloadConverter.cs deleted file mode 100644 index 6af0e0a..0000000 --- a/OpenStack/OpenStack/Compute/IComputeFlavorPayloadConverter.cs +++ /dev/null @@ -1,40 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; - -namespace OpenStack.Compute -{ - /// - /// Converter that can be used to convert an HTTP payload into a ComputeFlavor Poco object. - /// - public interface IComputeFlavorPayloadConverter - { - /// - /// Converts an HTTP payload into a ComputeFlavor object. - /// - /// The HTTP payload to convert. - /// A ComputeFlavor object. - ComputeFlavor ConvertFlavor(string payload); - - /// - /// Converts an HTTP payload into a list of ComputeFlavor objects. - /// - /// The HTTP payload to convert. - /// An enumerable list of ComputeFlavor objects. - IEnumerable ConvertFlavors(string payload); - } -} diff --git a/OpenStack/OpenStack/Compute/IComputeImagePayloadConverter.cs b/OpenStack/OpenStack/Compute/IComputeImagePayloadConverter.cs deleted file mode 100644 index 6ecdeaf..0000000 --- a/OpenStack/OpenStack/Compute/IComputeImagePayloadConverter.cs +++ /dev/null @@ -1,40 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; - -namespace OpenStack.Compute -{ - /// - /// Converter that can be used to convert an HTTP payload into a ComputeImage Poco object. - /// - public interface IComputeImagePayloadConverter - { - /// - /// Converts an HTTP payload into a ComputeImage object. - /// - /// The HTTP payload to convert. - /// A ComputeImage object. - ComputeImage ConvertImage(string payload); - - /// - /// Converts an HTTP payload into a list of ComputeImage objects. - /// - /// The HTTP payload to convert. - /// An enumerable list of ComputeImage objects. - IEnumerable ConvertImages(string payload); - } -} diff --git a/OpenStack/OpenStack/Compute/IComputeItemMetadataPayloadConverter.cs b/OpenStack/OpenStack/Compute/IComputeItemMetadataPayloadConverter.cs deleted file mode 100644 index 3884991..0000000 --- a/OpenStack/OpenStack/Compute/IComputeItemMetadataPayloadConverter.cs +++ /dev/null @@ -1,37 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; - -namespace OpenStack.Compute -{ - public interface IComputeItemMetadataPayloadConverter - { - /// - /// Converts a JSON payload into a collection of key value pairs. - /// - /// The JSON payload to be converted. - /// A collection of key value pairs. - IDictionary Convert(string payload); - - /// - /// Converts the given collection of key value pairs into a JSON payload. - /// - /// The collection of key value pairs. - /// A JSON payload that represents the key value pairs. - string Convert(IDictionary metadata); - } -} diff --git a/OpenStack/OpenStack/Compute/IComputeKeyPairPayloadConverter.cs b/OpenStack/OpenStack/Compute/IComputeKeyPairPayloadConverter.cs deleted file mode 100644 index 3a1b07c..0000000 --- a/OpenStack/OpenStack/Compute/IComputeKeyPairPayloadConverter.cs +++ /dev/null @@ -1,40 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; - -namespace OpenStack.Compute -{ - /// - /// Converter that can be used to convert an HTTP payload into a ComputeKeyPair Poco object. - /// - public interface IComputeKeyPairPayloadConverter - { - /// - /// Converts an HTTP payload into a ComputeKeyPair object. - /// - /// The HTTP payload to convert. - /// A ComputeKeyPair object. - ComputeKeyPair Convert(string payload); - - /// - /// Converts an HTTP payload into a list of ComputeKeyPair objects. - /// - /// The HTTP payload to convert. - /// An enumerable list of ComputeKeyPair objects. - IEnumerable ConvertKeyPairs(string payload); - } -} diff --git a/OpenStack/OpenStack/Compute/IComputeServerPayloadConverter.cs b/OpenStack/OpenStack/Compute/IComputeServerPayloadConverter.cs deleted file mode 100644 index 485ce27..0000000 --- a/OpenStack/OpenStack/Compute/IComputeServerPayloadConverter.cs +++ /dev/null @@ -1,47 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; - -namespace OpenStack.Compute -{ - /// - /// Converts a json payload into a compute server object. - /// - public interface IComputeServerPayloadConverter - { - /// - /// Converts a json summary payload into a ComputeServer object. - /// - /// The summary payload. - /// A ComputeServer object. - ComputeServer ConvertSummary(string payload); - - /// - /// Converts a json payload into a ComputeServer object. - /// - /// The payload. - /// A ComputeServer object. - ComputeServer Convert(string payload); - - /// - /// Converts a json payload into a list of ComputeServer objects. - /// - /// The payload to convert. - /// A list of ComputeServer objects. - IEnumerable ConvertServers(string payload); - } -} diff --git a/OpenStack/OpenStack/Compute/IComputeServiceClient.cs b/OpenStack/OpenStack/Compute/IComputeServiceClient.cs deleted file mode 100644 index ec1941e..0000000 --- a/OpenStack/OpenStack/Compute/IComputeServiceClient.cs +++ /dev/null @@ -1,160 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -namespace OpenStack.Compute -{ - using System.Collections.Generic; - using System.Threading.Tasks; - - /// - /// Client that can interact with an OpenStack compute service. - /// - public interface IComputeServiceClient : IOpenStackServiceClient - { - /// - /// Gets a list of flavors available on the remote OpenStack instance. - /// - /// An enumerable list of compute flavors. - Task> GetFlavors(); - - /// - /// Gets the detailed metadata for a compute flavor. - /// - /// The id of the flavor. - /// An object that represents the given flavor. - Task GetFlavor(string flavorId); - - /// - /// Gets a list of images available on the remote OpenStack instance. - /// - /// An enumerable list of compute images. - Task> GetImages(); - - /// - /// Gets the detailed metadata for a compute image. - /// - /// The id of the image. - /// An object that represents the given image. - Task GetImage(string imageId); - - /// - /// Deletes the compute image from the remote instance of OpenStack. - /// - /// The id of the image. - /// An async task. - Task DeleteImage(string imageId); - - /// - /// Gets the associated metadata for a given compute image. - /// - /// The id for the image. - /// A collection of key values pairs. - Task> GetImageMetadata(string imageId); - - /// - /// Updates the metadata for a given compute image. - /// Note: If a key does not exist on the remote server, it will be created. - /// - /// The id for the image. - /// A collection of key value pairs. - /// An async task. - Task UpdateImageMetadata(string imageId, IDictionary metadata); - - /// - /// Deletes the given key from the metadata for the given compute image. - /// - /// The id for the image - /// The metadata key to remove. - /// An async task. - Task DeleteImageMetadata(string imageId, string key); - - /// - /// Creates a new server on the remote OpenStack instance. - /// - /// The name of the server. - /// The id for the image that this server will be based on. - /// The id of the flavor to use for this server. - /// The network to connect this server to. - /// A list of security group names to associate with this server. - /// A server object. - Task CreateServer(string name, string imageId, string flavorId, string networkId, IEnumerable securityGroups); - - /// - /// Deletes a server from the remote OpenStack instance. - /// - /// The id for the server - /// An async task. - Task DeleteServer(string serverId); - - /// - /// Gets a list of servers available on the remote OpenStack instance. - /// - /// An enumerable list of compute servers. - Task> GetServers(); - - /// - /// Gets a server from the remote OpenStack instance. - /// - /// The id for the server - /// A server object. - Task GetServer(string serverId); - - /// - /// Assigns a floating ip address to a compute server on the remote OpenStack instance. - /// - /// The id of the server. - /// The ip address of the floating ip to assign. - /// An async task. - Task AssignFloatingIp(string serverId, string ipAddress); - - /// - /// Gets the associated metadata for a given compute server. - /// - /// The id for the server. - /// A collection of key values pairs. - Task> GetServerMetadata(string serverId); - - /// - /// Updates the metadata for a given compute server. - /// Note: If a key does not exist on the remote server, it will be created. - /// - /// The id for the server. - /// A collection of key value pairs. - /// An async task. - Task UpdateServerMetadata(string serverId, IDictionary metadata); - - /// - /// Deletes the given key from the metadata for the given compute server. - /// - /// The id for the server - /// The metadata key to remove. - /// An async task. - Task DeleteServerMetadata(string serverId, string key); - - /// - /// Gets a list of key pairs that are available on the remote OpenStack instance. - /// - /// An enumerable list of key pairs. - Task> GetKeyPairs(); - - /// - /// Gets the key pair with the given name from the remote OpenStack instance. - /// - /// The name of the key pair. - /// An async task. - Task GetKeyPair(string keyPairName); - } -} diff --git a/OpenStack/OpenStack/Compute/IComputeServicePocoClient.cs b/OpenStack/OpenStack/Compute/IComputeServicePocoClient.cs deleted file mode 100644 index 03d4b6b..0000000 --- a/OpenStack/OpenStack/Compute/IComputeServicePocoClient.cs +++ /dev/null @@ -1,161 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -namespace OpenStack.Compute -{ - using System.Collections.Generic; - using System.Threading.Tasks; - - /// - /// Client that can interact with an OpenStack compute service. - /// - public interface IComputeServicePocoClient - { - /// - /// Gets a list of flavors that are available on the remote OpenStack instance. - /// - /// An enumerable list of Flavors. - Task> GetFlavors(); - - /// - /// Gets the detailed metadata for a compute flavor. - /// - /// The id of the flavor. - /// An object representing a compute flavor. - Task GetFlavor(string flavorId); - - /// - /// Gets a list of images that are available on the remote OpenStack instance. - /// - /// An enumerable list of images. - Task> GetImages(); - - /// - /// Gets the detailed metadata for a compute image. - /// - /// The id of the image. - /// An object representing a compute image. - Task GetImage(string imageId); - - /// - /// Deletes the image with the given id from the remote OpenStack instance. - /// - /// The id of the image. - /// An async task. - Task DeleteImage(string imageId); - - /// - /// Creates a new server on the remote OpenStack instance. - /// - /// The name of the server. - /// The id for the image that this server will be based on. - /// The id of the flavor to use for this server. - /// The network to connect this server to. - /// The name of the key to associate with this server. - /// A list of security group names to associate with this server. - /// A server object. - Task CreateServer(string name, string imageId, string flavorId, string networkId, string keyName, IEnumerable securityGroups); - - /// - /// Deletes the server with the given id from the remote OpenStack instance. - /// - /// The id of the server. - /// An async task. - Task DeleteServer(string serverId); - - /// - /// Gets a list of servers that are available on the remote OpenStack instance. - /// - /// An enumerable list of servers. - Task> GetServers(); - - /// - /// Get the server with the given id from the remote OpenStack instance. - /// - /// The id of the server. - /// An async task. - Task GetServer(string serverId); - - /// - /// Assigns a floating ip address to a compute server on the remote OpenStack instance. - /// - /// The id of the server. - /// The ip address of the floating ip to assign. - /// An async task. - Task AssignFloatingIp(string serverId, string ipAddress); - - /// - /// Gets the associated metadata for a given compute image. - /// - /// The id for the image. - /// A collection of key values pairs. - Task> GetImageMetadata(string imageId); - - /// - /// Updates the metadata for a given compute image. - /// Note: If a key does not exist on the remote server, it will be created. - /// - /// The id for the image. - /// A collection of key value pairs. - /// An async task. - Task UpdateImageMetadata(string imageId, IDictionary metadata); - - /// - /// Deletes the given key from the metadata for the given compute image. - /// - /// The id for the image - /// The metadata key to remove. - /// An async task. - Task DeleteImageMetadata(string imageId, string key); - - /// - /// Gets the associated metadata for a given compute server. - /// - /// The id for the server. - /// A collection of key values pairs. - Task> GetServerMetadata(string serverId); - - /// - /// Updates the metadata for a given compute server. - /// Note: If a key does not exist on the remote server, it will be created. - /// - /// The id for the server. - /// A collection of key value pairs. - /// An async task. - Task UpdateServerMetadata(string serverId, IDictionary metadata); - - /// - /// Deletes the given key from the metadata for the given compute server. - /// - /// The id for the server - /// The metadata key to remove. - /// An async task. - Task DeleteServerMetadata(string serverId, string key); - - /// - /// Gets a list of key pairs that are available on the remote OpenStack instance. - /// - /// An enumerable list of key pairs. - Task> GetKeyPairs(); - - /// - /// Gets the key pair with the given name from the remote OpenStack instance. - /// - /// The name of the key pair. - /// An async task. - Task GetKeyPair(string keyPairName); - } -} diff --git a/OpenStack/OpenStack/Compute/IComputeServicePocoClientFactory.cs b/OpenStack/OpenStack/Compute/IComputeServicePocoClientFactory.cs deleted file mode 100644 index f580dd3..0000000 --- a/OpenStack/OpenStack/Compute/IComputeServicePocoClientFactory.cs +++ /dev/null @@ -1,34 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -namespace OpenStack.Compute -{ - using OpenStack.Common.ServiceLocation; - - /// - /// Constructs a client that can be used to interact with the POCO objects related to the OpenStack compute service. - /// - public interface IComputeServicePocoClientFactory - { - /// - /// Creates a client that can be used to interact with the OpenStack compute service. - /// - /// A compute service context to be used by the client. - /// A service locator to be used to locate/inject dependent services. - /// The client. - IComputeServicePocoClient Create(ServiceClientContext context, IServiceLocator serviceLocator); - } -} diff --git a/OpenStack/OpenStack/Compute/IComputeServiceRestClient.cs b/OpenStack/OpenStack/Compute/IComputeServiceRestClient.cs deleted file mode 100644 index 3453f3b..0000000 --- a/OpenStack/OpenStack/Compute/IComputeServiceRestClient.cs +++ /dev/null @@ -1,163 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; - -namespace OpenStack.Compute -{ - using System.Threading.Tasks; - using OpenStack.Common.Http; - - /// - /// Client that can connect to the REST endpoints of an OpenStack Compute Service - /// - public interface IComputeServiceRestClient - { - /// - /// Gets a list of compute Flavors from the remote OpenStack instance. - /// - /// An HTTP response from the remote server. - Task GetFlavors(); - - /// - /// Gets the detailed metadata for a compute flavor. - /// - /// The id of the flavor. - /// An HTTP response from the remote server. - Task GetFlavor(string flavorId); - - /// - /// Gets a list of compute images from the remote OpenStack instance. - /// - /// An HTTP response from the remote server. - Task GetImages(); - - /// - /// Gets the detailed info for a compute image. - /// - /// The id of the image. - /// An HTTP response from the remote server. - Task GetImage(string imageId); - - /// - /// Deletes a compute image. - /// - /// The id of the image. - /// An HTTP response from the remote server. - Task DeleteImage(string imageId); - - /// - /// Gets the associated metadata for a given compute image. - /// - /// The id for the image. - /// An HTTP response from the remote server. - Task GetImageMetadata(string imageId); - - /// - /// Updates the metadata for a given compute image. - /// Note: If a key does not exist on the remote server, it will be created. - /// - /// The id for the image. - /// A collection of key value pairs. - /// An HTTP response from the remote server. - Task UpdateImageMetadata(string imageId, IDictionary metadata); - - /// - /// Deletes the given key from the metadata for the given compute image. - /// - /// The id for the image. - /// The metadata key to remove. - /// An HTTP response from the remote server. - Task DeleteImageMetadata(string imageId, string key); - - /// - /// Creates a new server on the remote OpenStack instance. - /// - /// The name of the server. - /// The id for the image that this server will be based on. - /// The id of the flavor to use for this server. - /// The network to connect this server to. - /// The name of the key pair to associate with this server. - /// A list of security group names to associate with this server. - /// An HTTP response from the remote server. - Task CreateServer(string name, string imageId, string flavorId, string networkId, string keyName, IEnumerable securityGroups); - - /// - /// Gets a list of servers from the remote OpenStack instance. - /// - /// An HTTP response from the remote server. - Task GetServers(); - - /// - /// Gets a server from the remote OpenStack instance. - /// - /// The id of the server to get. - /// An HTTP response from the remote server. - Task GetServer(string serverId); - - /// - /// Deletes a server on the remote OpenStack instance. - /// - /// The id of the server to delete. - /// An HTTP response from the remote server. - Task DeleteServer(string serverId); - - /// - /// Assigns the given floating ip address to the specified compute server. - /// - /// The id for the compute server. - /// The ip address of the floating ip. - /// An HTTP response from the remote server. - Task AssignFloatingIp(string serverId, string ipAddress); - - /// - /// Gets the associated metadata for a given compute flavor. - /// - /// The id for the flavor. - /// An HTTP response from the remote server. - Task GetServerMetadata(string flavorId); - - /// - /// Updates the metadata for a given compute flavor. - /// Note: If a key does not exist on the remote server, it will be created. - /// - /// The id for the flavor. - /// A collection of key value pairs. - /// An HTTP response from the remote server. - Task UpdateServerMetadata(string serverId, IDictionary metadata); - - /// - /// Deletes the given key from the metadata for the given compute flavor. - /// - /// The id for the flavor - /// The metadata key to remove. - /// An HTTP response from the remote server. - Task DeleteServerMetadata(string serverId, string key); - - /// - /// Gets a list of key pairs from the remote OpenStack instance. - /// - /// An HTTP response from the remote server. - Task GetKeyPairs(); - - /// - /// Gets a key pair from the remote OpenStack instance. - /// - /// The name of the key pair to get. - /// An HTTP response from the remote server. - Task GetKeyPair(string keyPairName); - } -} diff --git a/OpenStack/OpenStack/Compute/IComputeServiceRestClientFactory.cs b/OpenStack/OpenStack/Compute/IComputeServiceRestClientFactory.cs deleted file mode 100644 index e3db0fc..0000000 --- a/OpenStack/OpenStack/Compute/IComputeServiceRestClientFactory.cs +++ /dev/null @@ -1,31 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -namespace OpenStack.Compute -{ - using OpenStack.Common.ServiceLocation; - - public interface IComputeServiceRestClientFactory - { - /// - /// Constructs a client that can be used to connect to the REST endpoints of an OpenStack compute service. - /// - /// A compute service context to be used by the client. - /// A service locator to be used to locate/inject dependent services. - /// The client. - IComputeServiceRestClient Create(ServiceClientContext context, IServiceLocator serviceLocator); - } -} diff --git a/OpenStack/OpenStack/Compute/MetadataComputeItem.cs b/OpenStack/OpenStack/Compute/MetadataComputeItem.cs deleted file mode 100644 index ce6c891..0000000 --- a/OpenStack/OpenStack/Compute/MetadataComputeItem.cs +++ /dev/null @@ -1,43 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; - -namespace OpenStack.Compute -{ - public abstract class MetadataComputeItem : ComputeItem - { - /// - /// Gets a collection of metadata about this item. - /// - public IDictionary Metadata { get; internal set; } - - /// - /// Create a new instance of the ComputeItem class. - /// - /// The Id of the item. - /// The name of the item. - /// The public Uri for the item. - /// The permanent Uri of the item. - /// Metadata associated with this item. - protected MetadataComputeItem(string id, string name, Uri publicUri, Uri permanentUri, - IDictionary metadata) : base(id, name, publicUri, permanentUri) - { - this.Metadata = metadata; - } - } -} diff --git a/OpenStack/OpenStack/IOpenStackClient.cs b/OpenStack/OpenStack/IOpenStackClient.cs deleted file mode 100644 index ddad5e8..0000000 --- a/OpenStack/OpenStack/IOpenStackClient.cs +++ /dev/null @@ -1,92 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; -using System.Threading.Tasks; -using OpenStack.Identity; - -namespace OpenStack -{ - /// - /// Top level OpenStack client used to connect and interact with an instance of OpenStack. - /// - public interface IOpenStackClient - { - /// - /// Gets a reference to the credential currently being used. - /// - IOpenStackCredential Credential { get; } - - /// - /// Connects the client to the remote instance of OpenStack. - /// - /// - Task Connect(); - - /// - /// Changes the default region for the client. - /// - /// The region to be set. - /// - void SetRegion(string region); - - /// - /// Creates a client for a given OpenStack service. - /// - /// The type of client to create. - /// An implementation of the requested client. - T CreateServiceClient() where T : IOpenStackServiceClient; - - /// - /// Creates a client for a given OpenStack service that supports the given version. - /// - /// The type of client to create. - /// The version that must be supported. - /// An implementation of the requested client. - T CreateServiceClient(string version) where T : IOpenStackServiceClient; - - /// - /// Creates a client for a given OpenStack service. - /// - /// The type of client to create. - /// The name of the service that must be supported. - /// An implementation of the requested client. - T CreateServiceClientByName(string serviceName) where T : IOpenStackServiceClient; - - /// - /// Creates a client for a given OpenStack service that supports the given version. - /// - /// The type of client to create. - /// The name of the service that must be supported. - /// The version that must be supported. - /// An implementation of the requested client. - T CreateServiceClientByName(string serviceName, string version) where T : IOpenStackServiceClient; - - /// - /// Gets a list of supported OpenStack versions for this client. - /// - /// - IEnumerable GetSupportedVersions(); - - /// - /// Determines if the client can support the given credential and version. - /// - /// The credential that must be supported. - /// The version that must be supported. - /// A value indicating if the given credential and version are supported. - bool IsSupported(ICredential credential, string version); - } -} diff --git a/OpenStack/OpenStack/IOpenStackClientManager.cs b/OpenStack/OpenStack/IOpenStackClientManager.cs deleted file mode 100644 index 63f7e71..0000000 --- a/OpenStack/OpenStack/IOpenStackClientManager.cs +++ /dev/null @@ -1,89 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Threading; -using OpenStack.Identity; - -namespace OpenStack -{ - /// - /// Manages the creation and registration of OpenStack clients. - /// - public interface IOpenStackClientManager - { - /// - /// Creates an instance of a client that can support the given credential. - /// - /// The credential that must be supported. - /// An instance of an OpenStack client. - IOpenStackClient CreateClient(ICredential credential); - - /// - /// Creates an instance of a client that can support the given credential and version. - /// - /// The credential that must be supported. - /// The version that must be supported. - /// An instance of an OpenStack client. - IOpenStackClient CreateClient(ICredential credential, string version); - - /// - /// Creates an instance of a client that can support the given credential and version. - /// - /// The credential that must be supported. - /// A cancellation token that can be used to cancel operations. - /// The version that must be supported. - /// An instance of an OpenStack client. - IOpenStackClient CreateClient(ICredential credential, CancellationToken token, string version); - - /// - /// Creates an instance of a client that can support the given credential and version. - /// - /// The credential that must be supported. - /// An instance of an OpenStack client. - IOpenStackClient CreateClient(ICredential credential) where T : IOpenStackClient; - - /// - /// Creates an instance of a client that can support the given credential and version. - /// - /// The credential that must be supported. - /// The version that must be supported. - /// An instance of an OpenStack client. - IOpenStackClient CreateClient(ICredential credential, string version) where T : IOpenStackClient; - - /// - /// Creates an instance of a client that can support the given credential and version. - /// - /// The credential that must be supported. - /// A cancellation token that can be used to cancel operations. - /// The version that must be supported. - /// An instance of an OpenStack client. - IOpenStackClient CreateClient(ICredential credential, CancellationToken token, string version) where T : IOpenStackClient; - - /// - /// Registers a client for use. - /// - /// The type of the client to be registered. - void RegisterClient() where T : IOpenStackClient; - - /// - /// Gets a list of available clients that are being managed by this object. - /// - /// A list of OpenStack clients. - IEnumerable ListAvailableClients(); - } -} \ No newline at end of file diff --git a/OpenStack/OpenStack/IOpenStackServiceClient.cs b/OpenStack/OpenStack/IOpenStackServiceClient.cs deleted file mode 100644 index 9947fbb..0000000 --- a/OpenStack/OpenStack/IOpenStackServiceClient.cs +++ /dev/null @@ -1,26 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -namespace OpenStack -{ - /// - /// A client that can be used to interact with an OpenStack service. - /// - public interface IOpenStackServiceClient - { - - } -} diff --git a/OpenStack/OpenStack/IOpenStackServiceClientDefinition.cs b/OpenStack/OpenStack/IOpenStackServiceClientDefinition.cs deleted file mode 100644 index 14a6752..0000000 --- a/OpenStack/OpenStack/IOpenStackServiceClientDefinition.cs +++ /dev/null @@ -1,55 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; -using System.Threading; -using OpenStack.Common.ServiceLocation; -using OpenStack.Identity; - -namespace OpenStack -{ - public interface IOpenStackServiceClientDefinition - { - /// - /// The name of the service client. - /// - string Name { get; } - - /// - /// Creates an instance of the service client being defined. - /// - /// The credential that the client will use. - /// The name of the service that the client will use. - /// The cancellation token that the client will use. - /// A service locator to be used to locate/inject dependent services. - /// - IOpenStackServiceClient Create(ICredential credential, string serviceName, CancellationToken cancellationToken, IServiceLocator serviceLocator); - - /// - /// Gets a list of supported versions. - /// - /// A list of versions. - IEnumerable ListSupportedVersions(); - - /// - /// Determines if this client is currently supported. - /// - /// The credential for the service to use. - /// The serviceName for the service. - /// A value indicating if the client is supported. - bool IsSupported(ICredential credential, string serviceName); - } -} diff --git a/OpenStack/OpenStack/IOpenStackServiceClientManager.cs b/OpenStack/OpenStack/IOpenStackServiceClientManager.cs deleted file mode 100644 index 35e43fe..0000000 --- a/OpenStack/OpenStack/IOpenStackServiceClientManager.cs +++ /dev/null @@ -1,61 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Threading; -using OpenStack.Identity; - -namespace OpenStack -{ - /// - /// Creates and registers clients that can be used to interact with OpenStack services. - /// - public interface IOpenStackServiceClientManager - { - /// - /// Create a client that can interact with the requested OpenStack service. - /// - /// The type of client to be created. - /// The credential to be used by the client. - /// The name of the service to be used by the client. - /// The cancellation token to be used by the client. - /// An instance of the requested client. - T CreateServiceClient(ICredential credential, string serviceName, CancellationToken cancellationToken) where T : IOpenStackServiceClient; - - /// - /// Create a client that can interact with the requested OpenStack service. - /// - /// The type of client to be created. - /// The credential to be used by the client. - /// The cancellation token to be used by the client. - /// An instance of the requested client. - T CreateServiceClient(ICredential credential, CancellationToken cancellationToken) where T : IOpenStackServiceClient; - - /// - /// Gets a list of all available clients that can be used to interact with OpenStack services. - /// - /// A list of types of clients. - IEnumerable ListAvailableServiceClients(); - - /// - /// Registers a client for use. - /// - /// The type of the client to register. - /// An object that can be used to validate support and construct the given client. - void RegisterServiceClient(IOpenStackServiceClientDefinition serviceClientDefinition) where T : IOpenStackServiceClient; - } -} diff --git a/OpenStack/OpenStack/Identity/AccessTokenPayloadConverter.cs b/OpenStack/OpenStack/Identity/AccessTokenPayloadConverter.cs deleted file mode 100644 index e3f30e9..0000000 --- a/OpenStack/OpenStack/Identity/AccessTokenPayloadConverter.cs +++ /dev/null @@ -1,54 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using Newtonsoft.Json.Linq; -using OpenStack.Common; - -namespace OpenStack.Identity -{ - /// - internal class AccessTokenPayloadConverter : IAccessTokenPayloadConverter - { - /// - public string Convert(string payload) - { - payload.AssertIsNotNull("payload", "A null Storage Container payload cannot be converted."); - - if (String.IsNullOrEmpty(payload)) - { - return string.Empty; - } - - try - { - var obj = JObject.Parse(payload); - var token = (string)obj["access"]["token"]["id"]; - - if (token == null) - { - throw new FormatException(string.Format("Access token payload could not be parsed. Token is null. Payload: '{0}'", payload)); - } - - return token; - } - catch (Exception ex) - { - throw new FormatException(string.Format("Access token payload could not be parsed. Payload: '{0}'", payload), ex); - } - } - } -} diff --git a/OpenStack/OpenStack/Identity/IAccessTokenPayloadConverter.cs b/OpenStack/OpenStack/Identity/IAccessTokenPayloadConverter.cs deleted file mode 100644 index 1239abf..0000000 --- a/OpenStack/OpenStack/Identity/IAccessTokenPayloadConverter.cs +++ /dev/null @@ -1,31 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -namespace OpenStack.Identity -{ - /// - /// Converts a Json payload into an access token Id. - /// - interface IAccessTokenPayloadConverter - { - /// - /// Converts a Json payload into an access token Id. - /// - /// The Json payload to convert. - /// The converted access token Id. - string Convert(string payload); - } -} diff --git a/OpenStack/OpenStack/Identity/ICredential.cs b/OpenStack/OpenStack/Identity/ICredential.cs deleted file mode 100644 index 34c01c4..0000000 --- a/OpenStack/OpenStack/Identity/ICredential.cs +++ /dev/null @@ -1,41 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; - -namespace OpenStack.Identity -{ - /// - /// A credential to be used when communicating with an instance of OpenStack. - /// - public interface ICredential - { - /// - /// Gets the authentication endpoint to be used for the current instance of OpenStack. - /// - Uri AuthenticationEndpoint { get; } - - /// - /// Gets the access token to be used for the current instance of OpenStack. - /// - string AccessTokenId { get; } - - /// - /// Gets the service catalog for the current instance of OpenStack. - /// - OpenStackServiceCatalog ServiceCatalog { get; } - } -} diff --git a/OpenStack/OpenStack/Identity/IIdentityServiceClient.cs b/OpenStack/OpenStack/Identity/IIdentityServiceClient.cs deleted file mode 100644 index 2d6c0e6..0000000 --- a/OpenStack/OpenStack/Identity/IIdentityServiceClient.cs +++ /dev/null @@ -1,32 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Threading.Tasks; - -namespace OpenStack.Identity -{ - /// - /// A client that can be used to communicate with an OpenStack identity service. - /// - public interface IIdentityServiceClient : IOpenStackServiceClient - { - /// - /// Authenticates against an instance of OpenStack. - /// - /// An authentication credential that can be used to communicate with OpenStack. - Task Authenticate(); - } -} diff --git a/OpenStack/OpenStack/Identity/IIdentityServicePocoClient.cs b/OpenStack/OpenStack/Identity/IIdentityServicePocoClient.cs deleted file mode 100644 index 641fa75..0000000 --- a/OpenStack/OpenStack/Identity/IIdentityServicePocoClient.cs +++ /dev/null @@ -1,32 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Threading.Tasks; - -namespace OpenStack.Identity -{ - /// - /// A client that can be used to create and interact with POCO objects related to the OpenStack identity service. - /// - public interface IIdentityServicePocoClient - { - /// - /// Authenticates against a remote OpenStack instance. - /// - /// A credential that can be used to interact with the remote instance of OpenStack. - Task Authenticate(); - } -} diff --git a/OpenStack/OpenStack/Identity/IIdentityServicePocoClientFactory.cs b/OpenStack/OpenStack/Identity/IIdentityServicePocoClientFactory.cs deleted file mode 100644 index dfe4074..0000000 --- a/OpenStack/OpenStack/Identity/IIdentityServicePocoClientFactory.cs +++ /dev/null @@ -1,37 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Threading; -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Identity -{ - /// - /// Constructs clients that can be used to interact with POCO object related to the OpenStack identity service. - /// - public interface IIdentityServicePocoClientFactory - { - /// - /// Creates a client that can be used to interact with the remote OpenStack service. - /// - /// The credential to be used when interacting with OpenStack. - /// The name of the service to be used when interacting with OpenStack. - /// The cancellation token to be used when interacting with OpenStack. - /// A service locator to be used to locate/inject dependent services. - /// An instance of the client. - IIdentityServicePocoClient Create(IOpenStackCredential credentials, string serviceName, CancellationToken token, IServiceLocator serviceLocator); - } -} diff --git a/OpenStack/OpenStack/Identity/IIdentityServiceRestClient.cs b/OpenStack/OpenStack/Identity/IIdentityServiceRestClient.cs deleted file mode 100644 index df9195a..0000000 --- a/OpenStack/OpenStack/Identity/IIdentityServiceRestClient.cs +++ /dev/null @@ -1,33 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Threading.Tasks; -using OpenStack.Common.Http; - -namespace OpenStack.Identity -{ - /// - /// A client that can be used to create and interact with REST interfaces related to the OpenStack identity service. - /// - public interface IIdentityServiceRestClient - { - /// - /// Authenticates against a remote OpenStack instance. - /// - /// A credential that can be used to interact with the remote instance of OpenStack. - Task Authenticate(); - } -} diff --git a/OpenStack/OpenStack/Identity/IIdentityServiceRestClientFactory.cs b/OpenStack/OpenStack/Identity/IIdentityServiceRestClientFactory.cs deleted file mode 100644 index a0b9cf9..0000000 --- a/OpenStack/OpenStack/Identity/IIdentityServiceRestClientFactory.cs +++ /dev/null @@ -1,36 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Threading; -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Identity -{ - /// - /// Constructs clients that can be used to interact with REST interfaces related to the OpenStack identity service. - /// - public interface IIdentityServiceRestClientFactory - { - /// - /// Creates a client that can be used to interact with the remote OpenStack service. - /// - /// The credential to be used when interacting with OpenStack. - /// The cancellation token to be used when interacting with OpenStack. - /// A service locator to be used to locate/inject dependent services. - /// An instance of the client. - IIdentityServiceRestClient Create(IOpenStackCredential credential, CancellationToken cancellationToken, IServiceLocator serviceLocator); - } -} diff --git a/OpenStack/OpenStack/Identity/IOpenStackCredential.cs b/OpenStack/OpenStack/Identity/IOpenStackCredential.cs deleted file mode 100644 index 2d94193..0000000 --- a/OpenStack/OpenStack/Identity/IOpenStackCredential.cs +++ /dev/null @@ -1,62 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Security; - -namespace OpenStack.Identity -{ - /// - public interface IOpenStackCredential : ICredential - { - /// - /// Gets the name of the user to use for the current instance of OpenStack - /// - string UserName { get; } - - /// - /// Gets the password to use for the current instance of OpenStack - /// - string Password { get; } - - /// - /// Gets the Id of the tenant to use for the current instance of OpenStack - /// - string TenantId { get; } - - /// - /// Gets the current region for this credential. - /// - string Region { get; } - - /// - /// Sets the access token to be used for the current instance of OpenStack. - /// - /// The access token id. - void SetAccessTokenId(string accessTokenId); - - /// - /// Sets the current region to use for the current instance of OpenStack. - /// - /// The region. - void SetRegion(string region); - - /// - /// Sets the service catalog to be used for the current instance of OpenStack. - /// - /// The service catalog. - void SetServiceCatalog(OpenStackServiceCatalog catalog); - } -} diff --git a/OpenStack/OpenStack/Identity/IOpenStackRegionResolver.cs b/OpenStack/OpenStack/Identity/IOpenStackRegionResolver.cs deleted file mode 100644 index 4185b14..0000000 --- a/OpenStack/OpenStack/Identity/IOpenStackRegionResolver.cs +++ /dev/null @@ -1,37 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - - -using System; -using System.Collections.Generic; - -namespace OpenStack.Identity -{ - /// - /// Resolves a region/availability zone from a service catalog - /// - public interface IOpenStackRegionResolver - { - /// - /// Resolves a region from the given service catalog using an endpoint uri and service name. - /// - /// The endpoint to use when resolving the region. - /// The service catalog to search within. - /// The service name to use when resolving the region. - /// The region if available, string.Empty if the region cannot be resolved. - string Resolve(Uri endpoint, IEnumerable catalog, string serviceName); - } -} diff --git a/OpenStack/OpenStack/Identity/IOpenStackServiceCatalog.cs b/OpenStack/OpenStack/Identity/IOpenStackServiceCatalog.cs deleted file mode 100644 index 43423ed..0000000 --- a/OpenStack/OpenStack/Identity/IOpenStackServiceCatalog.cs +++ /dev/null @@ -1,49 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; - -namespace OpenStack.Identity -{ - /// - /// A listing of services offered by a remote instance of OpenStack. - /// - public interface IOpenStackServiceCatalog : IEnumerable - { - /// - /// Determines if the given service exists in the catalog. - /// - /// The name of the service to check for. - /// A value indicating if the service could be found in the catalog. - bool Exists(string serviceName); - - /// - /// Gets a list of services available in the given region/availability zone. - /// - /// The name of the region/availability zone. - /// A list of available services. - IEnumerable GetServicesInAvailabilityZone(string availabilityZoneName); - - /// - /// Gets the public endpoint for a given service in a given region/availability zone. - /// - /// The name of the service. - /// The name of the region/availability zone. - /// - string GetPublicEndpoint(string serviceName, string region); - } -} \ No newline at end of file diff --git a/OpenStack/OpenStack/Identity/IOpenStackServiceCatalogPayloadConverter.cs b/OpenStack/OpenStack/Identity/IOpenStackServiceCatalogPayloadConverter.cs deleted file mode 100644 index 7b645d9..0000000 --- a/OpenStack/OpenStack/Identity/IOpenStackServiceCatalogPayloadConverter.cs +++ /dev/null @@ -1,30 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ -namespace OpenStack.Identity -{ - /// - /// Converts a Json payload into an object that represents a service catalog. - /// - public interface IOpenStackServiceCatalogPayloadConverter - { - /// - /// Converts a Json payload into a service catalog. - /// - /// The Json payload to convert. - /// The converted service catalog. - OpenStackServiceCatalog Convert(string payload); - } -} diff --git a/OpenStack/OpenStack/Identity/IOpenStackServiceDefinitionPayloadConverter.cs b/OpenStack/OpenStack/Identity/IOpenStackServiceDefinitionPayloadConverter.cs deleted file mode 100644 index 690cbb6..0000000 --- a/OpenStack/OpenStack/Identity/IOpenStackServiceDefinitionPayloadConverter.cs +++ /dev/null @@ -1,30 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ -namespace OpenStack.Identity -{ - /// - /// Converts a Json payload into an object that represents a service definition. - /// - public interface IOpenStackServiceDefinitionPayloadConverter - { - /// - /// Converts a Json payload into a service definition. - /// - /// The Json payload to convert. - /// The converted service definition. - OpenStackServiceDefinition Convert(string payload); - } -} diff --git a/OpenStack/OpenStack/Identity/IOpenStackServiceEndpointPayloadConverter.cs b/OpenStack/OpenStack/Identity/IOpenStackServiceEndpointPayloadConverter.cs deleted file mode 100644 index 15206d2..0000000 --- a/OpenStack/OpenStack/Identity/IOpenStackServiceEndpointPayloadConverter.cs +++ /dev/null @@ -1,31 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -namespace OpenStack.Identity -{ - /// - /// Converts a Json payload into an object that represents a service endpoint. - /// - public interface IOpenStackServiceEndpointPayloadConverter - { - /// - /// Converts a Json payload into a service endpoint. - /// - /// The Json payload to convert. - /// The converted service endpoint. - OpenStackServiceEndpoint Convert(string payload); - } -} diff --git a/OpenStack/OpenStack/Identity/IdentityServiceClient.cs b/OpenStack/OpenStack/Identity/IdentityServiceClient.cs deleted file mode 100644 index fef1a83..0000000 --- a/OpenStack/OpenStack/Identity/IdentityServiceClient.cs +++ /dev/null @@ -1,57 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Threading; -using System.Threading.Tasks; -using OpenStack.Common; -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Identity -{ - /// - internal class IdentityServiceClient : IIdentityServiceClient - { - internal IOpenStackCredential Credential; - internal CancellationToken CancellationToken; - internal IServiceLocator ServiceLocator; - internal string ServiceName; - - /// - /// Creates a new instance of the IdentityServiceClient class. - /// - /// The credential to be used by the client. - /// The name of the service to be used by the client. - /// A cancellation token to be used when completing requests. - /// A service locator to be used to locate/inject dependent services. - internal IdentityServiceClient(IOpenStackCredential credential, string serviceName, CancellationToken cancellationToken, IServiceLocator serviceLocator) - { - serviceLocator.AssertIsNotNull("serviceLocator", "Cannot create an identity service client with a null service locator."); - - this.ServiceLocator = serviceLocator; - this.Credential = credential; - this.CancellationToken = cancellationToken; - this.ServiceName = serviceName; - } - - /// - public async Task Authenticate() - { - var client = this.ServiceLocator.Locate().Create(this.Credential, this.ServiceName, this.CancellationToken, this.ServiceLocator); - this.Credential = await client.Authenticate(); - return this.Credential; - } - } -} diff --git a/OpenStack/OpenStack/Identity/IdentityServiceClientDefinition.cs b/OpenStack/OpenStack/Identity/IdentityServiceClientDefinition.cs deleted file mode 100644 index 37e8543..0000000 --- a/OpenStack/OpenStack/Identity/IdentityServiceClientDefinition.cs +++ /dev/null @@ -1,69 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Identity -{ - /// - internal class IdentityServiceClientDefinition : IOpenStackServiceClientDefinition - { - internal const string DefaultServiceName = "Keystone"; - - /// - public string Name { get; private set; } - - /// - /// Creates a new instance of the IdentityServiceClientDefinition class. - /// - public IdentityServiceClientDefinition() - { - this.Name = typeof(IdentityServiceClient).Name; - } - - /// - public IOpenStackServiceClient Create(ICredential credential, string serviceName, CancellationToken cancellationToken, IServiceLocator serviceLocator) - { - var srvName = string.IsNullOrEmpty(serviceName) ? DefaultServiceName : serviceName; - return new IdentityServiceClient((IOpenStackCredential)credential, srvName, cancellationToken, serviceLocator); - } - - /// - public IEnumerable ListSupportedVersions() - { - return new List() { "2.0.0.0" }; - } - - /// - public bool IsSupported(ICredential credential, string serviceName) - { - if (credential != null && credential.AuthenticationEndpoint != null) - { - //https://someidentityendpoint:35357/v2.0 - var endpointSegs = credential.AuthenticationEndpoint.Segments; - if (endpointSegs.Count() == 2 && string.Equals(endpointSegs[1].Trim('/'), "v2.0", StringComparison.Ordinal)) - { - return true; - } - } - return false; - } - } -} diff --git a/OpenStack/OpenStack/Identity/IdentityServicePocoClient.cs b/OpenStack/OpenStack/Identity/IdentityServicePocoClient.cs deleted file mode 100644 index fcafdd0..0000000 --- a/OpenStack/OpenStack/Identity/IdentityServicePocoClient.cs +++ /dev/null @@ -1,88 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Net; -using System.Threading; -using System.Threading.Tasks; -using OpenStack.Common; -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Identity -{ - /// - internal class IdentityServicePocoClient : IIdentityServicePocoClient - { - internal IOpenStackCredential credential; - internal CancellationToken cancellationToken; - internal string ServiceName; - internal IServiceLocator ServiceLocator; - - /// - /// Creates a new instance of the IdentityServicePocoClient class. - /// - /// The credential to be used when interacting with OpenStack. - /// The cancellation token to be used when interacting with OpenStack. - /// A service locator to be used to locate/inject dependent services. - public IdentityServicePocoClient(IOpenStackCredential credential, string serviceName, CancellationToken cancellationToken, IServiceLocator serviceLocator) - { - credential.AssertIsNotNull("credential"); - cancellationToken.AssertIsNotNull("cancellationToken"); - serviceLocator.AssertIsNotNull("serviceLocator", "Cannot create an identity service poco client with a null service locator."); - serviceName.AssertIsNotNullOrEmpty("serviceName", "Cannot create an identity service poco client with a null or empty service name."); - - this.credential = credential; - this.cancellationToken = cancellationToken; - this.ServiceLocator = serviceLocator; - this.ServiceName = serviceName; - } - - /// - public async Task Authenticate() - { - var client = this.ServiceLocator.Locate().Create(this.credential, this.cancellationToken, this.ServiceLocator); - - var resp = await client.Authenticate(); - - if (resp.StatusCode != HttpStatusCode.OK && resp.StatusCode != HttpStatusCode.NonAuthoritativeInformation) - { - throw new InvalidOperationException(string.Format("Failed to authenticate. The remote server returned the following status code: '{0}'.", resp.StatusCode)); - } - - var payload = await resp.ReadContentAsStringAsync(); - - var tokenConverter = this.ServiceLocator.Locate(); - var accessToken = tokenConverter.Convert(payload); - - var scConverter = this.ServiceLocator.Locate(); - var serviceCatalog = scConverter.Convert(payload); - - this.credential.SetAccessTokenId(accessToken); - this.credential.SetServiceCatalog(serviceCatalog); - - if (string.IsNullOrEmpty(this.credential.Region)) - { - var resolver = this.ServiceLocator.Locate(); - var region = resolver.Resolve(this.credential.AuthenticationEndpoint, this.credential.ServiceCatalog, this.ServiceName); - - //TODO: figure out if we want to throw in the case where the region cannot be resolved... - this.credential.SetRegion(region); - } - - return this.credential; - } - } -} diff --git a/OpenStack/OpenStack/Identity/IdentityServicePocoClientFactory.cs b/OpenStack/OpenStack/Identity/IdentityServicePocoClientFactory.cs deleted file mode 100644 index 8bf6f7a..0000000 --- a/OpenStack/OpenStack/Identity/IdentityServicePocoClientFactory.cs +++ /dev/null @@ -1,31 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Threading; -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Identity -{ - /// - internal class IdentityServicePocoClientFactory :IIdentityServicePocoClientFactory - { - /// - public IIdentityServicePocoClient Create(IOpenStackCredential credentials, string serviceName, CancellationToken token, IServiceLocator serviceLocator) - { - return new IdentityServicePocoClient(credentials, serviceName, token, serviceLocator); - } - } -} diff --git a/OpenStack/OpenStack/Identity/IdentityServiceRestClient.cs b/OpenStack/OpenStack/Identity/IdentityServiceRestClient.cs deleted file mode 100644 index ebfe998..0000000 --- a/OpenStack/OpenStack/Identity/IdentityServiceRestClient.cs +++ /dev/null @@ -1,84 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Net.Http; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using OpenStack.Common; -using OpenStack.Common.Http; -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Identity -{ - /// - internal class IdentityServiceRestClient : IIdentityServiceRestClient - { - internal IOpenStackCredential Credential; - internal CancellationToken CancellationToken; - internal IServiceLocator ServiceLocator; - - /// - /// Creates a new instance of the IdentityServiceRestClient class. - /// - /// The credential to be used by this client. - /// The cancellation token to be used by this client. - /// A service locator to be used to locate/inject dependent services. - public IdentityServiceRestClient(IOpenStackCredential credential, CancellationToken cancellationToken, IServiceLocator serviceLocator) - { - credential.AssertIsNotNull("credential"); - cancellationToken.AssertIsNotNull("cancellationToken"); - serviceLocator.AssertIsNotNull("serviceLocator", "Cannot create an identity service rest client with a null service locator."); - - this.Credential = credential; - this.CancellationToken = cancellationToken; - this.ServiceLocator = serviceLocator; - } - - /// - public async Task Authenticate() - { - var client = this.ServiceLocator.Locate().Create(this.CancellationToken); - client.Headers.Add("Accept", "application/json"); - client.ContentType = "application/json"; - - client.Uri = new Uri(string.Format("{0}/tokens", this.Credential.AuthenticationEndpoint)); - client.Method = HttpMethod.Post; - client.Content = CreateAuthenticationJsonPayload(this.Credential).ConvertToStream(); - - return await client.SendAsync(); - } - - /// - /// Creates a Json payload that will be sent to the remote instance to authenticate. - /// - /// The credentials used to authenticate. - /// A string that represents a Json payload. - internal static string CreateAuthenticationJsonPayload(IOpenStackCredential creds) - { - var authPayload = new StringBuilder(); - authPayload.Append("{\"auth\":{\"passwordCredentials\":{\"username\":\""); - authPayload.Append(creds.UserName); - authPayload.Append("\",\"password\":\""); - authPayload.Append(creds.Password); - authPayload.Append("\"},\"tenantName\":\""); - authPayload.Append(creds.TenantId); - authPayload.Append("\"}}"); - return authPayload.ToString(); - } - } -} diff --git a/OpenStack/OpenStack/Identity/IdentityServiceRestClientFactory.cs b/OpenStack/OpenStack/Identity/IdentityServiceRestClientFactory.cs deleted file mode 100644 index 8828afc..0000000 --- a/OpenStack/OpenStack/Identity/IdentityServiceRestClientFactory.cs +++ /dev/null @@ -1,31 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Threading; -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Identity -{ - /// - internal class IdentityServiceRestClientFactory : IIdentityServiceRestClientFactory - { - /// - public IIdentityServiceRestClient Create(IOpenStackCredential credential, CancellationToken cancellationToken, IServiceLocator serviceLocator) - { - return new IdentityServiceRestClient(credential, cancellationToken, serviceLocator); - } - } -} diff --git a/OpenStack/OpenStack/Identity/OpenStackCredential.cs b/OpenStack/OpenStack/Identity/OpenStackCredential.cs deleted file mode 100644 index 268288c..0000000 --- a/OpenStack/OpenStack/Identity/OpenStackCredential.cs +++ /dev/null @@ -1,114 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using OpenStack.Common; - -namespace OpenStack.Identity -{ - /// - public class OpenStackCredential : IOpenStackCredential - { - /// - public Uri AuthenticationEndpoint { get; private set; } - - /// - public string AccessTokenId { get; private set; } - - /// - public string UserName { get; private set; } - - /// - public string Password { get; private set; } - - /// - public string TenantId { get; private set; } - - /// - public string Region { get; private set; } - - /// - public OpenStackServiceCatalog ServiceCatalog { get; private set; } - - /// - /// Creates a new instance of the OpenStackCredential class. - /// - /// The endpoint to be used for authentication. - /// the user name to be used for authentication. - /// The password to be used for authentication. - /// The tenant id to be used for the authentication. - /// The region to be used for the authentication. - public OpenStackCredential(Uri endpoint, string userName, string password, string tenantId) - { - endpoint.AssertIsNotNull("endpoint", "An OpenStack credential cannot be created with a null endpoint."); - userName.AssertIsNotNullOrEmpty("userName", "An OpenStack credential cannot be created with a null or empty user name."); - password.AssertIsNotNull("password", "An OpenStack credential cannot be created with a null password."); - tenantId.AssertIsNotNullOrEmpty("tenantId", "An OpenStack credential cannot be created with a null or empty tenant id."); - - this.Init(endpoint, userName, password, tenantId, string.Empty); - } - - /// - /// Creates a new instance of the OpenStackCredential class. - /// - /// The endpoint to be used for authentication. - /// the user name to be used for authentication. - /// The password to be used for authentication. - /// The tenant id to be used for the authentication. - /// The region to be used for the authentication. - public OpenStackCredential(Uri endpoint, string userName, string password, string tenantId, string region) - { - endpoint.AssertIsNotNull("endpoint","An OpenStack credential cannot be created with a null endpoint."); - userName.AssertIsNotNullOrEmpty("userName", "An OpenStack credential cannot be created with a null or empty user name."); - password.AssertIsNotNull("password", "An OpenStack credential cannot be created with a null password."); - tenantId.AssertIsNotNullOrEmpty("tenantId", "An OpenStack credential cannot be created with a null or empty tenant id."); - region.AssertIsNotNullOrEmpty("region", "An OpenStack credential cannot be created with a null or empty region."); - - this.Init(endpoint, userName, password, tenantId, region); - } - - internal void Init(Uri endpoint, string userName, string password, string tenantId, string region) - { - this.AuthenticationEndpoint = endpoint; - this.UserName = userName; - this.Password = password; - this.TenantId = tenantId; - this.Region = region; - - this.ServiceCatalog = new OpenStackServiceCatalog(); - } - - /// - public void SetAccessTokenId(string accessTokenId) - { - accessTokenId.AssertIsNotNullOrEmpty("accessTokenId","Access token cannot be null or empty."); - this.AccessTokenId = accessTokenId; - } - - public void SetRegion(string region) - { - region.AssertIsNotNullOrEmpty("region", "Cannot set the region for this credential. Region cannot be null or empty."); - this.Region = region; - } - - /// - public void SetServiceCatalog(OpenStackServiceCatalog catalog) - { - catalog.AssertIsNotNull("catalog", "Service catalog cannot be null or empty."); - this.ServiceCatalog = catalog; - } - } -} diff --git a/OpenStack/OpenStack/Identity/OpenStackRegionResolver.cs b/OpenStack/OpenStack/Identity/OpenStackRegionResolver.cs deleted file mode 100644 index 73059fa..0000000 --- a/OpenStack/OpenStack/Identity/OpenStackRegionResolver.cs +++ /dev/null @@ -1,57 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using OpenStack.Common; - -namespace OpenStack.Identity -{ - internal class OpenStackRegionResolver : IOpenStackRegionResolver - { - public string Resolve(Uri endpoint, IEnumerable catalog, string serviceName) - { - endpoint.AssertIsNotNull("endpoint","Cannot resolve a region with a null endpoint."); - catalog.AssertIsNotNull("catalog", "Cannot resolve a region with a null catalog."); - serviceName.AssertIsNotNullOrEmpty("serviceName", "Cannot resolve a region with a null or empty service name."); - - var ret = string.Empty; - var cat = catalog.ToList(); - - var identService = cat.FirstOrDefault(s => string.Equals(s.Name, serviceName, StringComparison.OrdinalIgnoreCase)); - - if (identService == null) - { - //Fall back and see if any service can be found that publishes an endpoint that matches the one given. - identService = cat.FirstOrDefault(s => s.Endpoints.Any(e => endpoint.AbsoluteUri.TrimEnd('/').Contains(e.PublicUri.TrimEnd('/')))); - if (identService == null) - { - //if no service can be found, either by name or endpoint, then return string.empty - return ret; - } - } - - var defaultRegionEndpoint = identService.Endpoints.FirstOrDefault(e => endpoint.AbsoluteUri.TrimEnd('/').Contains(e.PublicUri.TrimEnd('/'))); - if (defaultRegionEndpoint != null && !string.IsNullOrEmpty(defaultRegionEndpoint.Region)) - { - ret = defaultRegionEndpoint.Region; - } - - return ret; - } - } -} diff --git a/OpenStack/OpenStack/Identity/OpenStackServiceCatalog.cs b/OpenStack/OpenStack/Identity/OpenStackServiceCatalog.cs deleted file mode 100644 index 204bc87..0000000 --- a/OpenStack/OpenStack/Identity/OpenStackServiceCatalog.cs +++ /dev/null @@ -1,62 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using OpenStack.Common; - -namespace OpenStack.Identity -{ - /// - public class OpenStackServiceCatalog : List, IOpenStackServiceCatalog - { - /// - public bool Exists(string serviceName) - { - return this.Any(s => string.Equals(s.Name, serviceName, StringComparison.OrdinalIgnoreCase)); - } - - /// - public IEnumerable GetServicesInAvailabilityZone(string availabilityZoneName) - { - return this.Where(s => s.Endpoints.Any(e => e.Region.Contains(availabilityZoneName))); - } - - /// - public string GetPublicEndpoint(string serviceName, string region) - { - serviceName.AssertIsNotNullOrEmpty("serviceName", "Cannot resolve the public endpoint of a service with a null or empty service name."); - region.AssertIsNotNull("region", "Cannot resolve the public endpoint of a service with a null or empty region."); - - if (this.All(s => !string.Equals(s.Name, serviceName, StringComparison.OrdinalIgnoreCase))) - { - throw new InvalidOperationException(string.Format("Service catalog does not contain an entry for the '{0}' service. The request could not be completed.", serviceName)); - } - - var service = this.First(s => string.Equals(s.Name, serviceName, StringComparison.OrdinalIgnoreCase)); - - if (service.Endpoints.All(e => !string.Equals(e.Region, region, StringComparison.OrdinalIgnoreCase))) - { - throw new InvalidOperationException(string.Format("Service catalog does not contain an endpoint for the '{0}' service in the requested region. Region: '{1}'", serviceName, region)); - } - - var endpoint = service.Endpoints.First(e => string.Equals(e.Region, region, StringComparison.OrdinalIgnoreCase)); - - return endpoint.PublicUri; - } - } -} diff --git a/OpenStack/OpenStack/Identity/OpenStackServiceCatalogPayloadConverter.cs b/OpenStack/OpenStack/Identity/OpenStackServiceCatalogPayloadConverter.cs deleted file mode 100644 index 03dfd54..0000000 --- a/OpenStack/OpenStack/Identity/OpenStackServiceCatalogPayloadConverter.cs +++ /dev/null @@ -1,81 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Linq; -using Newtonsoft.Json.Linq; -using OpenStack.Common; -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Identity -{ - /// - internal class OpenStackServiceCatalogPayloadConverter : IOpenStackServiceCatalogPayloadConverter - { - internal IServiceLocator ServiceLocator; - - /// - /// Creates a new instance of the OpenStackServiceCatalogPayloadConverter class. - /// - /// A service locator to be used to locate/inject dependent services. - public OpenStackServiceCatalogPayloadConverter(IServiceLocator serviceLocator) - { - serviceLocator.AssertIsNotNull("serviceLocator", "Cannot create a service catalog payload converter with a null service locator."); - this.ServiceLocator = serviceLocator; - } - - /// - public OpenStackServiceCatalog Convert(string payload) - { - payload.AssertIsNotNull("payload", "A null service catalog payload cannot be converted."); - - var catalog = new OpenStackServiceCatalog(); - - if (String.IsNullOrEmpty(payload)) - { - return catalog; - } - - try - { - var obj = JObject.Parse(payload); - var defArray = obj["access"]["serviceCatalog"]; - catalog.AddRange(defArray.Select(ConvertServiceDefinition)); - } - catch (FormatException) - { - throw; - } - catch (Exception ex) - { - throw new FormatException(string.Format("Service catalog payload could not be parsed. Payload: '{0}'", payload), ex); - } - - return catalog; - } - - /// - /// Converts a Json token that represents a service definition into a POCO object. - /// - /// The token. - /// The service definition. - internal OpenStackServiceDefinition ConvertServiceDefinition(JToken serviceDef) - { - var converter = this.ServiceLocator.Locate(); - return converter.Convert(serviceDef.ToString()); - } - } -} diff --git a/OpenStack/OpenStack/Identity/OpenStackServiceDefinition.cs b/OpenStack/OpenStack/Identity/OpenStackServiceDefinition.cs deleted file mode 100644 index c0bd9ab..0000000 --- a/OpenStack/OpenStack/Identity/OpenStackServiceDefinition.cs +++ /dev/null @@ -1,59 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; -using OpenStack.Common; - -namespace OpenStack.Identity -{ - /// - /// Represents the definition of an OpenStack service. - /// - public class OpenStackServiceDefinition - { - /// - /// Gets the name of the service. - /// - public string Name { get; private set; } - - /// - /// Gets the type of the service. - /// - public string Type { get; private set; } - - /// - /// Gets a list of endpoints for the service. - /// - public IEnumerable Endpoints { get; private set; } - - /// - /// Creates a new instance of the OpenStackServiceDefinition class. - /// - /// - /// - /// - internal OpenStackServiceDefinition(string name, string type, IEnumerable endpoints) - { - name.AssertIsNotNullOrEmpty("name","Cannot create a service definition with a name that is null or empty."); - type.AssertIsNotNullOrEmpty("type", "Cannot create a service definition with a type that is null or empty."); - endpoints.AssertIsNotNull("endpoints", "Cannot create a service definition with a null endpoint collection."); - - this.Name = name; - this.Type = type; - this.Endpoints = endpoints; - } - } -} diff --git a/OpenStack/OpenStack/Identity/OpenStackServiceDefinitionPayloadConverter.cs b/OpenStack/OpenStack/Identity/OpenStackServiceDefinitionPayloadConverter.cs deleted file mode 100644 index 4ce2541..0000000 --- a/OpenStack/OpenStack/Identity/OpenStackServiceDefinitionPayloadConverter.cs +++ /dev/null @@ -1,74 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using Newtonsoft.Json.Linq; -using OpenStack.Common; -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Identity -{ - /// - internal class OpenStackServiceDefinitionPayloadConverter : IOpenStackServiceDefinitionPayloadConverter - { - internal IServiceLocator ServiceLocator; - - /// - /// Creates a new instance of the OpenStackServiceDefinitionPayloadConverter class. - /// - /// A service locator to be used to locate/inject dependent services. - public OpenStackServiceDefinitionPayloadConverter(IServiceLocator serviceLocator) - { - serviceLocator.AssertIsNotNull("serviceLocator", "Cannot create a service definition payload converter with a null service locator."); - this.ServiceLocator = serviceLocator; - } - - /// - public OpenStackServiceDefinition Convert(string payload) - { - payload.AssertIsNotNull("payload", "A null service catalog payload cannot be converted."); - - try - { - var serviceDefinition = JObject.Parse(payload); - var name = (string)serviceDefinition["name"]; - var type = (string)serviceDefinition["type"]; - - var endpoints = new List(); - endpoints.AddRange(serviceDefinition["endpoints"].Select(ConvertEndpoint)); - - return new OpenStackServiceDefinition(name, type, endpoints); - } - catch (Exception ex) - { - throw new FormatException(string.Format("Service definition payload could not be parsed. Payload: '{0}'", payload), ex); - } - } - - /// - /// Converts a Json token that represents a service endpoint into a POCO object. - /// - /// The token. - /// A service endpoint. - internal OpenStackServiceEndpoint ConvertEndpoint(JToken endpoint) - { - var converter = this.ServiceLocator.Locate(); - return converter.Convert(endpoint.ToString()); - } - } -} diff --git a/OpenStack/OpenStack/Identity/OpenStackServiceEndpoint.cs b/OpenStack/OpenStack/Identity/OpenStackServiceEndpoint.cs deleted file mode 100644 index 73c094f..0000000 --- a/OpenStack/OpenStack/Identity/OpenStackServiceEndpoint.cs +++ /dev/null @@ -1,71 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using OpenStack.Common; - -namespace OpenStack.Identity -{ - /// - /// Represents an endpoint of an OpenStack service. - /// - public class OpenStackServiceEndpoint - { - /// - /// Gets the public Uri of the endpoint. - /// - public string PublicUri { get; internal set; } - - /// - /// Gets the region of the endpoint. - /// - public string Region { get; internal set; } - - /// - /// Gets the version of the endpoint. - /// - public string Version { get; internal set; } - - /// - /// Gets the Uri for the endpoints version information. - /// - public string VersionInformation { get; internal set; } - - /// - /// Gets the Uri for the endpoints list of versions. - /// - public string VersionList { get; internal set; } - - /// - /// Creates a new instance of the OpenStackServiceEndpoint class. - /// - /// The public Uri of the endpoint. - /// The region of the endpoint. - /// The version of the endpoint. - /// The link to version information. - /// The link to a list of versions. - internal OpenStackServiceEndpoint(string publicUri, string region, string version, string versionInfo, string versionList) - { - publicUri.AssertIsNotNull("publicUri", "Cannot create a service endpoint with a null public URI."); - region.AssertIsNotNull("region", "Cannot create a service endpoint with a null public URI."); - - this.PublicUri = publicUri; - this.Region = region; - this.Version = version ?? string.Empty; - this.VersionInformation = versionInfo ?? string.Empty; - this.VersionList = versionList ?? string.Empty; - } - } -} diff --git a/OpenStack/OpenStack/Identity/OpenStackServiceEndpointPayloadConverter.cs b/OpenStack/OpenStack/Identity/OpenStackServiceEndpointPayloadConverter.cs deleted file mode 100644 index 9932292..0000000 --- a/OpenStack/OpenStack/Identity/OpenStackServiceEndpointPayloadConverter.cs +++ /dev/null @@ -1,48 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using Newtonsoft.Json.Linq; -using OpenStack.Common; - -namespace OpenStack.Identity -{ - /// - internal class OpenStackServiceEndpointPayloadConverter : IOpenStackServiceEndpointPayloadConverter - { - /// - public OpenStackServiceEndpoint Convert(string payload) - { - payload.AssertIsNotNullOrEmpty("payload", "A null or empty service endpoint payload cannot be converted."); - - try - { - var endpoint = JObject.Parse(payload); - var publicUri = (string) endpoint["publicURL"]; - var region = (string)endpoint["region"]; - var version = (string)endpoint["versionId"]; - var versionInfo = (string)endpoint["versionInfo"]; - var versionList = (string)endpoint["versionList"]; - - return new OpenStackServiceEndpoint(publicUri, region, version, versionInfo, versionList); - } - catch (Exception ex) - { - throw new FormatException(string.Format("Service endpoint payload could not be parsed. Payload: '{0}'", payload), ex); - } - } - } -} diff --git a/OpenStack/OpenStack/Network/FloatingIp.cs b/OpenStack/OpenStack/Network/FloatingIp.cs deleted file mode 100644 index 68f66b0..0000000 --- a/OpenStack/OpenStack/Network/FloatingIp.cs +++ /dev/null @@ -1,52 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -namespace OpenStack.Network -{ - /// - /// Represents a Floating IP address on the remote OpenStack instance. - /// - public class FloatingIp - { - /// - /// Gets the id of the FloatingIp. - /// - public string Id { get; internal set; } - - /// - /// Gets the status of the FloatingIp. - /// - public FloatingIpStatus Status { get; internal set; } - - /// - /// Gets the floating ip address of the FloatingIp. - /// - public string FloatingIpAddress { get; internal set; } - - /// - /// Create a new instance of the FloatingIp class. - /// - /// The Id of the floating ip. - /// The floating ip address of the floating ip. - /// The status of the floating ip. - internal FloatingIp(string id, string FloatingIpAddress, FloatingIpStatus status) - { - this.Id = id; - this.FloatingIpAddress = FloatingIpAddress; - this.Status = status; - } - } -} diff --git a/OpenStack/OpenStack/Network/FloatingIpPayloadConverter.cs b/OpenStack/OpenStack/Network/FloatingIpPayloadConverter.cs deleted file mode 100644 index f8ff8a3..0000000 --- a/OpenStack/OpenStack/Network/FloatingIpPayloadConverter.cs +++ /dev/null @@ -1,122 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; -using Newtonsoft.Json.Linq; -using OpenStack.Common; -using System.Linq; - -namespace OpenStack.Network -{ - using System; - - /// - internal class FloatingIpPayloadConverter : IFloatingIpPayloadConverter - { - /// - public FloatingIp Convert(string payload) - { - payload.AssertIsNotNullOrEmpty("payload", "A null or empty floating ip payload cannot be converted."); - - try - { - var token = JToken.Parse(payload); - return ConvertFloatingIp(token["floatingip"]); - } - catch (FormatException) - { - throw; - } - catch (Exception ex) - { - throw new FormatException( - string.Format("Floating IP payload could not be parsed. Payload: '{0}'", payload), ex); - } - } - - /// - /// Converts a json token into a FloatingIp object. - /// - /// The json Token to convert. - /// A FloatingIp object. - internal FloatingIp ConvertFloatingIp(JToken floatingIpToken) - { - var floatingIpAddress = string.Empty; - var id = string.Empty; - var status = string.Empty; - - try - { - floatingIpAddress = (string)floatingIpToken["floating_ip_address"]; - id = (string)floatingIpToken["id"]; - status = (string) floatingIpToken["status"]; - - if (string.IsNullOrEmpty(floatingIpAddress) || string.IsNullOrEmpty(id) || string.IsNullOrEmpty(status)) - { - throw new FormatException(); - } - - return new FloatingIp(id, floatingIpAddress, status.GetFloatingIpStatus()); - } - catch (Exception ex) - { - var msg = "Floating IP payload could not be parsed."; - if (!string.IsNullOrEmpty(id) && floatingIpToken != null) - { - msg = string.Format( - "Floating IP with Id '{0}' payload could not be parsed. Payload: '{1}'", id, floatingIpToken); - } - else if (floatingIpToken != null) - { - msg = string.Format("Floating IP payload could not be parsed. Payload: '{0}'", floatingIpToken); - } - - throw new FormatException(msg, ex); - } - } - - /// - public IEnumerable ConvertFloatingIps(string payload) - { - payload.AssertIsNotNull("payload", "A null floating IPs payload cannot be converted."); - - var floatingIps = new List(); - - if (String.IsNullOrEmpty(payload)) - { - return floatingIps; - } - - try - { - var payloadToken = JToken.Parse(payload); - var floatingIpArray = payloadToken["floatingips"]; - floatingIps.AddRange(floatingIpArray.Select(ConvertFloatingIp)); - } - catch (FormatException) - { - throw; - } - catch (Exception ex) - { - throw new FormatException( - string.Format("Floating IPs payload could not be parsed. Payload: '{0}'", payload), ex); - } - - return floatingIps; - } - } -} diff --git a/OpenStack/OpenStack/Network/FloatingIpStatus.cs b/OpenStack/OpenStack/Network/FloatingIpStatus.cs deleted file mode 100644 index 9219266..0000000 --- a/OpenStack/OpenStack/Network/FloatingIpStatus.cs +++ /dev/null @@ -1,67 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using OpenStack.Common; - -namespace OpenStack.Network -{ - /// - /// Represents the states that a Floating IP can be in. - /// - public enum FloatingIpStatus - { - /// - /// The Floating IP is active and available. - /// - Active, - - /// - /// The Floating IP is down and unavailable. - /// - Down, - - /// - /// The Floating IP is in an unknown state. - /// - Unknown - } - - /// - /// Static class for holding FloatingIpStatus related extention methods. - /// - public static class FloatingIpStatusExtentions - { - /// - /// Creates a FloatingIpStatus enum from a string. - /// - /// The input string. - /// A FloatingIpStatus enum. - public static FloatingIpStatus GetFloatingIpStatus(this string input) - { - input.AssertIsNotNullOrEmpty("input", "Cannot get Floating IP status with null or empty value."); - - switch (input.ToLowerInvariant()) - { - case "active": - return FloatingIpStatus.Active; - case "down": - return FloatingIpStatus.Down; - default: - return FloatingIpStatus.Unknown; - } - } - } -} diff --git a/OpenStack/OpenStack/Network/IFloatingIpPayloadConverter.cs b/OpenStack/OpenStack/Network/IFloatingIpPayloadConverter.cs deleted file mode 100644 index 5e7dfd4..0000000 --- a/OpenStack/OpenStack/Network/IFloatingIpPayloadConverter.cs +++ /dev/null @@ -1,40 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; - -namespace OpenStack.Network -{ - /// - /// Converter that can be used to convert an HTTP payload into a FloatingIp Poco object. - /// - public interface IFloatingIpPayloadConverter - { - /// - /// Converts an HTTP payload into a FloatingIp object. - /// - /// The HTTP payload to convert. - /// A FloatingIp object. - FloatingIp Convert(string payload); - - /// - /// Converts an HTTP payload into a list of FloatingIp objects. - /// - /// The HTTP payload to convert. - /// An enumerable list of FloatingIp objects. - IEnumerable ConvertFloatingIps(string payload); - } -} diff --git a/OpenStack/OpenStack/Network/INetworkPayloadConverter.cs b/OpenStack/OpenStack/Network/INetworkPayloadConverter.cs deleted file mode 100644 index 14cdb24..0000000 --- a/OpenStack/OpenStack/Network/INetworkPayloadConverter.cs +++ /dev/null @@ -1,40 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; - -namespace OpenStack.Network -{ - /// - /// Converter that can be used to convert an HTTP payload into a Network Poco object. - /// - public interface INetworkPayloadConverter - { - /// - /// Converts an HTTP payload into a Network object. - /// - /// The HTTP payload to convert. - /// A Network object. - Network Convert(string payload); - - /// - /// Converts an HTTP payload into a list of Network objects. - /// - /// The HTTP payload to convert. - /// An enumerable list of Network objects. - IEnumerable ConvertNetworks(string payload); - } -} diff --git a/OpenStack/OpenStack/Network/INetworkServiceClient.cs b/OpenStack/OpenStack/Network/INetworkServiceClient.cs deleted file mode 100644 index b7c956b..0000000 --- a/OpenStack/OpenStack/Network/INetworkServiceClient.cs +++ /dev/null @@ -1,60 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; -using System.Threading.Tasks; - -namespace OpenStack.Network -{ - /// - /// Client that can interact with an OpenStack network service. - /// - public interface INetworkServiceClient : IOpenStackServiceClient - { - /// - /// Gets a list of networks available on the remote OpenStack instance. - /// - /// An enumerable list of networks. - Task> GetNetworks(); - - /// - /// Gets a list of Floating IPs from the remote OpenStack instance. - /// - /// An enumerable list of floating ips. - Task> GetFloatingIps(); - - /// - /// Gets the details of a Floating IP from the remote OpenStack instance. - /// - /// The id of the target floating ip. - /// A FloatingIp object. - Task GetFloatingIp(string floatingIpId); - - /// - /// Creates a Floating IP on the remote OpenStack instance. - /// - /// The network id to use when creating the new ip address. - /// A FloatingIp object. - Task CreateFloatingIp(string networkId); - - /// - /// Deletes a Floating IP on the remote OpenStack instance. - /// - /// The id of he floating ip to delete. - /// An async task. - Task DeleteFloatingIp(string floatingIpId); - } -} diff --git a/OpenStack/OpenStack/Network/INetworkServicePocoClient.cs b/OpenStack/OpenStack/Network/INetworkServicePocoClient.cs deleted file mode 100644 index 43e0c83..0000000 --- a/OpenStack/OpenStack/Network/INetworkServicePocoClient.cs +++ /dev/null @@ -1,60 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; -using System.Threading.Tasks; - -namespace OpenStack.Network -{ - /// - /// Client that can interact with an OpenStack network service. - /// - public interface INetworkServicePocoClient - { - /// - /// Gets a list of networks available on the remote OpenStack instance. - /// - /// An enumerable list of networks. - Task> GetNetworks(); - - /// - /// Gets a list of Floating IPs from the remote OpenStack instance. - /// - /// An enumerable list of floating ips. - Task> GetFloatingIps(); - - /// - /// Gets the details of a Floating IP from the remote OpenStack instance. - /// - /// The id of the target floating ip. - /// A FloatingIp object. - Task GetFloatingIp(string floatingIpId); - - /// - /// Creates a Floating IP on the remote OpenStack instance. - /// - /// The network id to use when creating the new ip address. - /// A FloatingIp object. - Task CreateFloatingIp(string networkId); - - /// - /// Deletes a Floating IP on the remote OpenStack instance. - /// - /// The id of he floating ip to delete. - /// An async task. - Task DeleteFloatingIp(string floatingIpId); - } -} diff --git a/OpenStack/OpenStack/Network/INetworkServicePocoClientFactory.cs b/OpenStack/OpenStack/Network/INetworkServicePocoClientFactory.cs deleted file mode 100644 index aa9c299..0000000 --- a/OpenStack/OpenStack/Network/INetworkServicePocoClientFactory.cs +++ /dev/null @@ -1,34 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -namespace OpenStack.Network -{ - using OpenStack.Common.ServiceLocation; - - /// - /// Constructs a client that can be used to interact with the POCO objects related to the OpenStack network service. - /// - public interface INetworkServicePocoClientFactory - { - /// - /// Creates a client that can be used to interact with the OpenStack network service. - /// - /// A service context to be used by the client. - /// A service locator to be used to locate/inject dependent services. - /// The client. - INetworkServicePocoClient Create(ServiceClientContext context, IServiceLocator serviceLocator); - } -} diff --git a/OpenStack/OpenStack/Network/INetworkServiceRestClient.cs b/OpenStack/OpenStack/Network/INetworkServiceRestClient.cs deleted file mode 100644 index 9f85d59..0000000 --- a/OpenStack/OpenStack/Network/INetworkServiceRestClient.cs +++ /dev/null @@ -1,60 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Threading.Tasks; -using OpenStack.Common.Http; - -namespace OpenStack.Network -{ - /// - /// Client that can connect to the REST endpoints of an OpenStack Network Service - /// - public interface INetworkServiceRestClient - { - /// - /// Gets a list of Networks from the remote OpenStack instance. - /// - /// An HTTP response from the remote server. - Task GetNetworks(); - - /// - /// Gets a list of Floating IPs from the remote OpenStack instance. - /// - /// An HTTP response from the remote server. - Task GetFloatingIps(); - - /// - /// Gets the details of a Floating IP from the remote OpenStack instance. - /// - /// The id of the target floating ip. - /// An HTTP response from the remote server. - Task GetFloatingIp(string floatingIpId); - - /// - /// Creates a Floating IP on the remote OpenStack instance. - /// - /// The network id to use when creating the new ip address. - /// An HTTP response from the remote server. - Task CreateFloatingIp(string networkId); - - /// - /// Deletes a Floating IP on the remote OpenStack instance. - /// - /// The id of the floating ip to delete. - /// An HTTP response from the remote server. - Task DeleteFloatingIp(string floatingIpId); - } -} diff --git a/OpenStack/OpenStack/Network/INetworkServiceRestClientFactory.cs b/OpenStack/OpenStack/Network/INetworkServiceRestClientFactory.cs deleted file mode 100644 index 581fd3d..0000000 --- a/OpenStack/OpenStack/Network/INetworkServiceRestClientFactory.cs +++ /dev/null @@ -1,34 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -namespace OpenStack.Network -{ - using OpenStack.Common.ServiceLocation; - - /// - /// Factory for creating network service clients. - /// - public interface INetworkServiceRestClientFactory - { - /// - /// Constructs a client that can be used to connect to the REST endpoints of an OpenStack network service. - /// - /// A network service context to be used by the client. - /// A service locator to be used to locate/inject dependent services. - /// The client. - INetworkServiceRestClient Create(ServiceClientContext context, IServiceLocator serviceLocator); - } -} diff --git a/OpenStack/OpenStack/Network/Network.cs b/OpenStack/OpenStack/Network/Network.cs deleted file mode 100644 index 00ce006..0000000 --- a/OpenStack/OpenStack/Network/Network.cs +++ /dev/null @@ -1,52 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -namespace OpenStack.Network -{ - /// - /// Represents a network on a remote OpenStack instance. - /// - public class Network - { - /// - /// Gets the name of the Network. - /// - public string Name { get; internal set; } - - /// - /// Gets the id of the Network. - /// - public string Id { get; internal set; } - - /// - /// Gets the status of the Network. - /// - public NetworkStatus Status { get; internal set; } - - /// - /// Create a new instance of the Network class. - /// - /// The Id of the network. - /// The name of the network. - /// The status of the network. - internal Network(string id, string name, NetworkStatus status) - { - this.Id = id; - this.Name = name; - this.Status = status; - } - } -} diff --git a/OpenStack/OpenStack/Network/NetworkPayloadConverter.cs b/OpenStack/OpenStack/Network/NetworkPayloadConverter.cs deleted file mode 100644 index a806e45..0000000 --- a/OpenStack/OpenStack/Network/NetworkPayloadConverter.cs +++ /dev/null @@ -1,123 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; -using Newtonsoft.Json.Linq; -using OpenStack.Common; -using System.Linq; - -namespace OpenStack.Network -{ - using System; - - /// - internal class NetworkPayloadConverter : INetworkPayloadConverter - { - /// - public Network Convert(string payload) - { - payload.AssertIsNotNullOrEmpty("payload", "A null or empty network payload cannot be converted."); - - try - { - var token = JToken.Parse(payload); - return ConvertNetwork(token["network"]); - } - catch (FormatException) - { - throw; - } - catch (Exception ex) - { - throw new FormatException( - string.Format("Network payload could not be parsed. Payload: '{0}'", payload), ex); - } - } - - /// - /// Converts a json token into a Network object. - /// - /// The json Token to convert. - /// A Network object. - internal Network ConvertNetwork(JToken networkToken) - { - var name = string.Empty; - var id = string.Empty; - var status = string.Empty; - - try - { - name = (string)networkToken["name"]; - id = (string)networkToken["id"]; - status = (string) networkToken["status"]; - - if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(id) || string.IsNullOrEmpty(status)) - { - throw new FormatException(); - } - - return new Network(id, name, status.GetNetworkStatus()); - } - catch (Exception ex) - { - var msg = "Network payload could not be parsed."; - if (!string.IsNullOrEmpty(name) && networkToken != null) - { - msg = string.Format( - "Network '{0}' with Id '{1}' payload could not be parsed. Payload: '{2}'", name, id, - networkToken); - } - else if (networkToken != null) - { - msg = string.Format("Network payload could not be parsed. Payload: '{0}'", networkToken); - } - - throw new FormatException(msg, ex); - } - } - - /// - public IEnumerable ConvertNetworks(string payload) - { - payload.AssertIsNotNull("payload", "A null networks payload cannot be converted."); - - var networks = new List(); - - if (String.IsNullOrEmpty(payload)) - { - return networks; - } - - try - { - var payloadToken = JToken.Parse(payload); - var networksArray = payloadToken["networks"]; - networks.AddRange(networksArray.Select(ConvertNetwork)); - } - catch (FormatException) - { - throw; - } - catch (Exception ex) - { - throw new FormatException( - string.Format("Networks payload could not be parsed. Payload: '{0}'", payload), ex); - } - - return networks; - } - } -} diff --git a/OpenStack/OpenStack/Network/NetworkServiceClient.cs b/OpenStack/OpenStack/Network/NetworkServiceClient.cs deleted file mode 100644 index f5603b0..0000000 --- a/OpenStack/OpenStack/Network/NetworkServiceClient.cs +++ /dev/null @@ -1,99 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using OpenStack.Common; -using OpenStack.Common.ServiceLocation; -using OpenStack.Identity; - -namespace OpenStack.Network -{ - /// - internal class NetworkServiceClient : INetworkServiceClient - { - internal ServiceClientContext Context; - internal IServiceLocator ServiceLocator; - - /// - /// Creates a new instance of the NetworkServiceClient class. - /// - /// The credential to be used by this client. - /// The cancellation token to be used by this client. - /// The name of the service to be used by this client. - /// A service locator to be used to locate/inject dependent services. - public NetworkServiceClient(IOpenStackCredential credentials, string serviceName, CancellationToken token, IServiceLocator serviceLocator) - { - serviceLocator.AssertIsNotNull("serviceLocator", "Cannot create a network service client with a null service locator."); - - this.ServiceLocator = serviceLocator; - var endpoint = new Uri(credentials.ServiceCatalog.GetPublicEndpoint(serviceName, credentials.Region)); - this.Context = new ServiceClientContext(credentials, token, serviceName, endpoint); - } - - /// - public async Task> GetNetworks() - { - var client = this.GetPocoClient(); - return await client.GetNetworks(); - } - - /// - public async Task> GetFloatingIps() - { - var client = this.GetPocoClient(); - return await client.GetFloatingIps(); - } - - /// - public async Task GetFloatingIp(string floatingIpId) - { - floatingIpId.AssertIsNotNullOrEmpty("floatingIpId", "Cannot get a floating ip with a null or empty id."); - - var client = this.GetPocoClient(); - return await client.GetFloatingIp(floatingIpId); - } - - /// - public async Task CreateFloatingIp(string networkId) - { - networkId.AssertIsNotNullOrEmpty("networkId", "Cannot create a floating ip with a null or empty network id."); - - var client = this.GetPocoClient(); - return await client.CreateFloatingIp(networkId); - } - - /// - public async Task DeleteFloatingIp(string floatingIpId) - { - floatingIpId.AssertIsNotNullOrEmpty("floatingIpId", "Cannot delete a floating ip with a null or empty id."); - - var client = this.GetPocoClient(); - await client.DeleteFloatingIp(floatingIpId); - } - - /// - /// Gets a client to interact with the remote OpenStack instance. - /// - /// A POCO client. - internal INetworkServicePocoClient GetPocoClient() - { - return this.ServiceLocator.Locate().Create(this.Context, this.ServiceLocator); - } - } -} diff --git a/OpenStack/OpenStack/Network/NetworkServiceClientDefinition.cs b/OpenStack/OpenStack/Network/NetworkServiceClientDefinition.cs deleted file mode 100644 index f9a0bc4..0000000 --- a/OpenStack/OpenStack/Network/NetworkServiceClientDefinition.cs +++ /dev/null @@ -1,72 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using OpenStack.Common.ServiceLocation; -using OpenStack.Identity; - -namespace OpenStack.Network -{ - /// - class NetworkServiceClientDefinition :IOpenStackServiceClientDefinition - { - internal const string DefaultServiceName = "Neutron"; - - /// - public string Name { get; private set; } - - /// - public IOpenStackServiceClient Create(ICredential credential, string serviceName, CancellationToken cancellationToken, - IServiceLocator serviceLocator) - { - return new NetworkServiceClient((IOpenStackCredential)credential, GetServiceName(serviceName), cancellationToken, serviceLocator); - } - - /// - public IEnumerable ListSupportedVersions() - { - return new List() { "2.0", "2" }; - } - - /// - public bool IsSupported(ICredential credential, string serviceName) - { - if (credential == null || credential.ServiceCatalog == null) - { - return false; - } - - var catalog = credential.ServiceCatalog; - return - catalog.Any( - s => - string.Equals(s.Name, GetServiceName(serviceName), StringComparison.OrdinalIgnoreCase)); - } - - /// - /// Gets the service name to use. - /// - /// The given service name. - /// The given service name if it is not empty or null, otherwise the default service name will be returned. - internal string GetServiceName(string serviceName) - { - return string.IsNullOrEmpty(serviceName) ? DefaultServiceName : serviceName; - } - } -} diff --git a/OpenStack/OpenStack/Network/NetworkServicePocoClient.cs b/OpenStack/OpenStack/Network/NetworkServicePocoClient.cs deleted file mode 100644 index a392ef0..0000000 --- a/OpenStack/OpenStack/Network/NetworkServicePocoClient.cs +++ /dev/null @@ -1,134 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Net; -using System.Threading.Tasks; -using OpenStack.Common; -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Network -{ - /// - class NetworkServicePocoClient : INetworkServicePocoClient - { - internal ServiceClientContext _context; - internal IServiceLocator ServiceLocator; - - /// - /// Creates a new instance of the ComputeServicePocoClient class. - /// - /// The compute service context to use for this client. - /// A service locator to be used to locate/inject dependent services. - internal NetworkServicePocoClient(ServiceClientContext context, IServiceLocator serviceLocator) - { - serviceLocator.AssertIsNotNull("serviceLocator", "Cannot create a network service poco client with a null service locator."); - - this._context = context; - this.ServiceLocator = serviceLocator; - } - - /// - public async Task> GetNetworks() - { - var client = this.GetRestClient(); - var resp = await client.GetNetworks(); - - if (resp.StatusCode != HttpStatusCode.OK) - { - throw new InvalidOperationException(string.Format("Failed to get networks. The remote server returned the following status code: '{0}'.", resp.StatusCode)); - } - - var converter = this.ServiceLocator.Locate(); - var networks = converter.ConvertNetworks(await resp.ReadContentAsStringAsync()); - - return networks; - } - - /// - public async Task> GetFloatingIps() - { - var client = this.GetRestClient(); - var resp = await client.GetFloatingIps(); - - if (resp.StatusCode != HttpStatusCode.OK) - { - throw new InvalidOperationException(string.Format("Failed to get floating ips. The remote server returned the following status code: '{0}'.", resp.StatusCode)); - } - - var converter = this.ServiceLocator.Locate(); - var floatingIps = converter.ConvertFloatingIps(await resp.ReadContentAsStringAsync()); - - return floatingIps; - } - - /// - public async Task GetFloatingIp(string floatingIpId) - { - var client = this.GetRestClient(); - var resp = await client.GetFloatingIp(floatingIpId); - - if (resp.StatusCode != HttpStatusCode.OK) - { - throw new InvalidOperationException(string.Format("Failed to get floating ip. The remote server returned the following status code: '{0}'.", resp.StatusCode)); - } - - var converter = this.ServiceLocator.Locate(); - var floatingIp = converter.Convert(await resp.ReadContentAsStringAsync()); - - return floatingIp; - } - - /// - public async Task CreateFloatingIp(string networkId) - { - var client = this.GetRestClient(); - var resp = await client.CreateFloatingIp(networkId); - - if (resp.StatusCode != HttpStatusCode.Created && resp.StatusCode != HttpStatusCode.OK) - { - throw new InvalidOperationException(string.Format("Failed to create floating ip. The remote server returned the following status code: '{0}'.", resp.StatusCode)); - } - - var converter = this.ServiceLocator.Locate(); - var floatingIp = converter.Convert(await resp.ReadContentAsStringAsync()); - - return floatingIp; - } - - /// - public async Task DeleteFloatingIp(string floatingIpId) - { - var client = this.GetRestClient(); - var resp = await client.DeleteFloatingIp(floatingIpId); - - if (resp.StatusCode != HttpStatusCode.NoContent && resp.StatusCode != HttpStatusCode.OK) - { - throw new InvalidOperationException(string.Format("Failed to delete floating ip. The remote server returned the following status code: '{0}'.", resp.StatusCode)); - } - } - - /// - /// Gets a client that can be used to connect to the REST endpoints of an OpenStack network service. - /// - /// The client. - internal INetworkServiceRestClient GetRestClient() - { - return this.ServiceLocator.Locate().Create(this._context, this.ServiceLocator); - } - } -} diff --git a/OpenStack/OpenStack/Network/NetworkServicePocoClientFactory.cs b/OpenStack/OpenStack/Network/NetworkServicePocoClientFactory.cs deleted file mode 100644 index 20e32db..0000000 --- a/OpenStack/OpenStack/Network/NetworkServicePocoClientFactory.cs +++ /dev/null @@ -1,30 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Network -{ - /// - internal class NetworkServicePocoClientFactory : INetworkServicePocoClientFactory - { - /// - public INetworkServicePocoClient Create(ServiceClientContext context, IServiceLocator serviceLocator) - { - return new NetworkServicePocoClient(context, serviceLocator); - } - } -} diff --git a/OpenStack/OpenStack/Network/NetworkServiceRestClient.cs b/OpenStack/OpenStack/Network/NetworkServiceRestClient.cs deleted file mode 100644 index 0d5961e..0000000 --- a/OpenStack/OpenStack/Network/NetworkServiceRestClient.cs +++ /dev/null @@ -1,111 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Dynamic; -using System.Net.Http; -using System.Threading.Tasks; -using Newtonsoft.Json.Linq; -using OpenStack.Common; -using OpenStack.Common.Http; -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Network -{ - /// - internal class NetworkServiceRestClient : OpenStackServiceRestClientBase, INetworkServiceRestClient - { - internal const string NetworksUrlMoniker = "networks"; - internal const string FloatingIpsUrlMoniker = "floatingips"; - internal const string NetworkVersionMoniker = "v2.0"; - - /// - /// Creates a new instance of the NetworkServiceRestClient class. - /// - /// The current service context to use. - /// A service locator to be used to locate/inject dependent services. - internal NetworkServiceRestClient(ServiceClientContext context, IServiceLocator serviceLocator) : base(context, serviceLocator) - { - } - - /// - public async Task GetNetworks() - { - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, NetworkVersionMoniker, NetworksUrlMoniker); - client.Method = HttpMethod.Get; - - return await client.SendAsync(); - } - - /// - public async Task GetFloatingIps() - { - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, NetworkVersionMoniker, FloatingIpsUrlMoniker); - client.Method = HttpMethod.Get; - - return await client.SendAsync(); - } - - /// - public async Task GetFloatingIp(string floatingIpId) - { - floatingIpId.AssertIsNotNullOrEmpty("floatingIpId", "Cannot get a floating ip with a null or empty id."); - - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, NetworkVersionMoniker, FloatingIpsUrlMoniker, floatingIpId); - client.Method = HttpMethod.Get; - - return await client.SendAsync(); - } - - /// - public async Task CreateFloatingIp(string networkId) - { - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, NetworkVersionMoniker, FloatingIpsUrlMoniker); - client.Method = HttpMethod.Post; - client.ContentType = "application/json"; - - dynamic body = new ExpandoObject(); - dynamic networkIdProp = new ExpandoObject(); - networkIdProp.floating_network_id = networkId; - body.floatingip = networkIdProp; - string requestBody = JToken.FromObject(body).ToString(); - - client.Content = requestBody.ConvertToStream(); - - return await client.SendAsync(); - } - - /// - public async Task DeleteFloatingIp(string floatingIpId) - { - floatingIpId.AssertIsNotNullOrEmpty("floatingIpId", "Cannot delete a floating ip with a null or empty id."); - - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, NetworkVersionMoniker, FloatingIpsUrlMoniker, floatingIpId); - client.Method = HttpMethod.Delete; - - return await client.SendAsync(); - } - } -} diff --git a/OpenStack/OpenStack/Network/NetworkServiceRestClientFactory.cs b/OpenStack/OpenStack/Network/NetworkServiceRestClientFactory.cs deleted file mode 100644 index aea796f..0000000 --- a/OpenStack/OpenStack/Network/NetworkServiceRestClientFactory.cs +++ /dev/null @@ -1,30 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Network -{ - /// - internal class NetworkServiceRestClientFactory : INetworkServiceRestClientFactory - { - /// - public INetworkServiceRestClient Create(ServiceClientContext context, IServiceLocator serviceLocator) - { - return new NetworkServiceRestClient(context, serviceLocator); - } - } -} diff --git a/OpenStack/OpenStack/Network/NetworkStatus.cs b/OpenStack/OpenStack/Network/NetworkStatus.cs deleted file mode 100644 index 17e0bd9..0000000 --- a/OpenStack/OpenStack/Network/NetworkStatus.cs +++ /dev/null @@ -1,67 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using OpenStack.Common; - -namespace OpenStack.Network -{ - /// - /// Represents the states that a Network can be in. - /// - public enum NetworkStatus - { - /// - /// The network is active and available. - /// - Active, - - /// - /// The network is down and unavailable. - /// - Down, - - /// - /// The network is in an unknown state. - /// - Unknown - } - - /// - /// Static class for holding NetworkStatus related extention methods. - /// - public static class NetworkStatusExtentions - { - /// - /// Creates a NetworkStatus enum from a string. - /// - /// The input string. - /// A NetworkStatus enum. - public static NetworkStatus GetNetworkStatus(this string input) - { - input.AssertIsNotNullOrEmpty("input", "Cannot get network status with null or empty value."); - - switch (input.ToLowerInvariant()) - { - case "active": - return NetworkStatus.Active; - case "down": - return NetworkStatus.Down; - default: - return NetworkStatus.Unknown; - } - } - } -} diff --git a/OpenStack/OpenStack/OpenStack40.csproj b/OpenStack/OpenStack/OpenStack40.csproj deleted file mode 100644 index 95cfec0..0000000 --- a/OpenStack/OpenStack/OpenStack40.csproj +++ /dev/null @@ -1,214 +0,0 @@ - - - - - Debug - AnyCPU - {E9F05CCA-2748-4785-9F72-5D3F8893BC28} - Library - Properties - OpenStack - OpenStack - v4.0 - 512 - - - true - full - false - ..\Bin\net40\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - ..\Bin\net40\Release\ - TRACE - prompt - 4 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Properties\AssemblyVersionInfo.cs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ..\packages\Newtonsoft.Json.6.0.3\lib\net40\Newtonsoft.Json.dll - - - - - - - - - - - - \ No newline at end of file diff --git a/OpenStack/OpenStack/OpenStackClient.cs b/OpenStack/OpenStack/OpenStackClient.cs deleted file mode 100644 index 4580205..0000000 --- a/OpenStack/OpenStack/OpenStackClient.cs +++ /dev/null @@ -1,108 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using OpenStack.Common; -using OpenStack.Common.ServiceLocation; -using OpenStack.Identity; - -namespace OpenStack -{ - /// - public class OpenStackClient : IOpenStackClient - { - internal CancellationToken CancellationToken; - internal IServiceLocator ServiceLocator; - - /// - public IOpenStackCredential Credential { get; private set; } - - internal OpenStackClient() - { - - } - - /// - /// Creates a new instance of the OpenStackClient class. - /// - /// The credential to be used by this client. - /// The cancellation token to be used by this client. - /// A service locator to be used to locate/inject dependent services. - public OpenStackClient(IOpenStackCredential credential, CancellationToken cancellationToken, IServiceLocator serviceLocator) - { - serviceLocator.AssertIsNotNull("serviceLocator", "Cannot create an OpenStack client with a null service locator."); - - this.Credential = credential; - this.CancellationToken = cancellationToken; - this.ServiceLocator = serviceLocator; - } - - /// - public async Task Connect() - { - var identityClient = this.CreateServiceClient(); - this.Credential = await identityClient.Authenticate(); - } - - /// - public void SetRegion(string region) - { - region.AssertIsNotNullOrEmpty("region", "Cannot set the region on the client. Region must not be null or empty"); - this.Credential.SetRegion(region); - } - - /// - public T CreateServiceClient() where T : IOpenStackServiceClient - { - return this.CreateServiceClient(string.Empty); - } - - /// - public T CreateServiceClient(string version) where T : IOpenStackServiceClient - { - var manager = this.ServiceLocator.Locate(); - return manager.CreateServiceClient(this.Credential, this.CancellationToken); - } - - /// - public T CreateServiceClientByName(string serviceName) where T : IOpenStackServiceClient - { - return this.CreateServiceClientByName(serviceName, string.Empty); - } - - /// - public T CreateServiceClientByName(string serviceName, string version) where T : IOpenStackServiceClient - { - var manager = this.ServiceLocator.Locate(); - return manager.CreateServiceClient(this.Credential, serviceName, this.CancellationToken); - } - - /// - public IEnumerable GetSupportedVersions() - { - //TODO: Figure out the actual supported version, or a better way to handle cases where the client does not care about version. - return new List {"Any"}; - } - - /// - public bool IsSupported(ICredential credential, string version) - { - return credential is IOpenStackCredential; - } - } -} diff --git a/OpenStack/OpenStack/OpenStackClientFactory.cs b/OpenStack/OpenStack/OpenStackClientFactory.cs deleted file mode 100644 index 4fe6fdc..0000000 --- a/OpenStack/OpenStack/OpenStackClientFactory.cs +++ /dev/null @@ -1,106 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Threading; -using OpenStack.Common; -using OpenStack.Common.ServiceLocation; -using OpenStack.Identity; - -namespace OpenStack -{ - /// - /// Factory class for creating OpenStack clients. - /// - public static class OpenStackClientFactory - { - /// - /// Creates an OpenStack client that supports the given credential. - /// - /// A credential to be used by the client. - /// A OpenStack client. - public static IOpenStackClient CreateClient(IOpenStackCredential credential) - { - return CreateClient(credential, CancellationToken.None, string.Empty); - } - - /// - /// Creates an OpenStack client that supports the given credential. - /// - /// A credential to be used by the client. - /// A version that the client must support. - /// A OpenStack client. - public static IOpenStackClient CreateClient(IOpenStackCredential credential, string version) - { - return CreateClient(credential, CancellationToken.None, version); - } - - /// - /// Creates an OpenStack client that supports the given credential and version. - /// - /// A credential to be used by the client. - /// A version that the client must support. - /// A cancellation token to be used to cancel operations. - /// An OpenStack client. - public static IOpenStackClient CreateClient(IOpenStackCredential credential, CancellationToken token, string version) - { - credential.AssertIsNotNull("credential", "Cannot create a client with a null credential."); - - var locator = new ServiceLocator(); - var clientManager = locator.Locate(); - return clientManager.CreateClient(credential, token, version); - } - - /// - /// Creates a client of the requested type that supports the given credential. - /// - /// The type of client to create. - /// A credential to be used by the client. - /// An OpenStack client. - public static IOpenStackClient CreateClient(IOpenStackCredential credential) where T : IOpenStackClient - { - return CreateClient(credential, CancellationToken.None, string.Empty); - } - - /// - /// Creates a client of the requested type that supports the given credential. - /// - /// The type of client to create. - /// A credential to be used by the client. - /// A version that the client must support. - /// An OpenStack client. - public static IOpenStackClient CreateClient(IOpenStackCredential credential, string version) where T : IOpenStackClient - { - return CreateClient(credential, CancellationToken.None, version); - } - - /// - /// Creates a client of the requested type that supports the given credential and version. - /// - /// The type of client to create. - /// A credential to be used by the client. - /// A version that the client must support. - /// A cancellation token to be used to cancel operations. - /// An OpenStack client. - public static IOpenStackClient CreateClient(IOpenStackCredential credential, CancellationToken token, string version) where T : IOpenStackClient - { - credential.AssertIsNotNull("credential", "Cannot create a client with a null credential."); - - var locator = new ServiceLocator(); - var clientManager = locator.Locate(); - return clientManager.CreateClient(credential, token, version); - } - } -} diff --git a/OpenStack/OpenStack/OpenStackClientManager.cs b/OpenStack/OpenStack/OpenStackClientManager.cs deleted file mode 100644 index 3e1da23..0000000 --- a/OpenStack/OpenStack/OpenStackClientManager.cs +++ /dev/null @@ -1,167 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.Reflection; -using System.Threading; -using OpenStack.Common; -using OpenStack.Common.ServiceLocation; -using OpenStack.Identity; - -namespace OpenStack -{ - /// - internal class OpenStackClientManager : IOpenStackClientManager - { - internal IServiceLocator ServiceLocator; - internal ICollection clients; - - /// - /// Creates a new instance of the OpenStackClientManager class. - /// - internal OpenStackClientManager(IServiceLocator serviceLocator) - { - this.ServiceLocator = serviceLocator; - this.clients = new Collection(); - } - - /// - public IOpenStackClient CreateClient(ICredential credential) - { - return this.CreateClient(credential, string.Empty); - } - - /// - public IOpenStackClient CreateClient(ICredential credential, string version) - { - return this.CreateClient(credential, CancellationToken.None, version); - } - - /// - public IOpenStackClient CreateClient(ICredential credential, CancellationToken token, string version) - { - credential.AssertIsNotNull("credential", "Cannot create an OpenStack client with a null credential."); - version.AssertIsNotNull("version", "Cannot create an OpenStack client with a null version."); - - //Ensure that the assembly that contains the credential has a chance to register itself. - this.ServiceLocator.EnsureAssemblyRegistration(credential.GetType().GetAssembly()); - - return this.GetSupportedClient(this.clients, credential, token, version); - } - - /// - public IOpenStackClient CreateClient(ICredential credential) where T : IOpenStackClient - { - return this.CreateClient(credential, CancellationToken.None, string.Empty); - } - - /// - public IOpenStackClient CreateClient(ICredential credential, string version) where T : IOpenStackClient - { - return this.CreateClient(credential, CancellationToken.None, version); - } - - /// - public IOpenStackClient CreateClient(ICredential credential, CancellationToken token, string version) where T: IOpenStackClient - { - credential.AssertIsNotNull("credential", "Cannot create an OpenStack client with a null credential."); - version.AssertIsNotNull("version", "Cannot create an OpenStack client with a null version."); - - //Ensure that the assemblies that contain the credential and client type has had a chance to register itself. - this.ServiceLocator.EnsureAssemblyRegistration(credential.GetType().GetAssembly()); - this.ServiceLocator.EnsureAssemblyRegistration(typeof(T).GetAssembly()); - - return this.GetSupportedClient(this.clients.Where(c => c == typeof(T)), credential, token, version); - } - - /// - /// Gets a client for the given collection that supports the credential and version. - /// - /// A list client types. - /// A credential that needs to be supported. - /// A version that needs to be supported. - /// A cancellation token that can be used to cancel operations. - /// A client that supports the given credential and version. - internal IOpenStackClient GetSupportedClient(IEnumerable clientTypes, ICredential credential, CancellationToken token, string version) - { - foreach (var clientType in clientTypes) - { - var client = this.CreateClientInstance(clientType, credential, token); - if (client.IsSupported(credential, version)) - { - return client; - } - } - - throw new InvalidOperationException("An OpenStack client that supports the given credentials and version could not be found."); - } - - /// - /// Creates a new instance of the requested client type - /// - /// The type of the client to create. - /// A credential that needs to be supported. - /// A cancellation token that can be used to cancel operations. - /// An instance of the requested client. - internal IOpenStackClient CreateClientInstance(Type clientType, ICredential credential, CancellationToken token) - { - clientType.AssertIsNotNull("clientType", "Cannot create an OpenStack client with a null type."); - credential.AssertIsNotNull("credential", "Cannot create an OpenStack client with a null credential."); - token.AssertIsNotNull("credential", "Cannot create an OpenStack client with a null cancellation token. Use CancellationToken.None."); - - IOpenStackClient instance; - try - { - instance = Activator.CreateInstance(clientType, credential, token, this.ServiceLocator) as IOpenStackClient; - } - catch (Exception ex) - { - throw new InvalidOperationException(string.Format("Could not create a client of type '{0}'. See inner exception for details.", clientType.Name), ex); - } - - if (instance != null) - { - return instance; - } - throw new InvalidOperationException(string.Format("Could not create a client of type '{0}'. The type does not derive from or cast to IOpenStackClient. ", clientType.Name)); - } - - /// - public void RegisterClient() where T: IOpenStackClient - { - var clientType = typeof (T); - - if (this.clients.Contains(clientType)) - { - throw new InvalidOperationException( - string.Format( - "A client of type '{0}' has already been registered, and cannot be registered again.", - clientType.Name)); - } - - this.clients.Add(clientType); - } - - /// - public IEnumerable ListAvailableClients() - { - return this.clients; - } - } -} diff --git a/OpenStack/OpenStack/OpenStackServiceClientManager.cs b/OpenStack/OpenStack/OpenStackServiceClientManager.cs deleted file mode 100644 index 79b8edb..0000000 --- a/OpenStack/OpenStack/OpenStackServiceClientManager.cs +++ /dev/null @@ -1,124 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using OpenStack.Common; -using OpenStack.Common.ServiceLocation; -using OpenStack.Identity; - -namespace OpenStack -{ - /// - internal class OpenStackServiceClientManager : IOpenStackServiceClientManager - { - internal IServiceLocator ServiceLocator; - internal IDictionary serviceClientDefinitions; - - /// - /// Creates a new instance of the OpenStackServiceClientManager class. - /// - internal OpenStackServiceClientManager(IServiceLocator serviceLocator) - { - this.ServiceLocator = serviceLocator; - this.serviceClientDefinitions = new Dictionary(); - } - - /// - public T CreateServiceClient(ICredential credential, CancellationToken cancellationToken) - where T : IOpenStackServiceClient - { - return CreateServiceClient(credential, string.Empty, cancellationToken); - } - - /// - public T CreateServiceClient(ICredential credential, string serviceName, CancellationToken cancellationToken) where T : IOpenStackServiceClient - { - credential.AssertIsNotNull("credential", "Cannot create an OpenStack service with a null credential."); - cancellationToken.AssertIsNotNull("cancellationToken", "Cannot create an OpenStack service with a null cancellationToken."); - credential.ServiceCatalog.AssertIsNotNull("credential.ServiceCatalog", "Cannot create an OpenStack service with a null service catalog."); - - //Ensure that the assembly that contains this credential has had a chance to be service located. - //This is, at least for now, the entry point for third-parties can extend the API/SDK. - this.ServiceLocator.EnsureAssemblyRegistration(credential.GetType().GetAssembly()); - this.ServiceLocator.EnsureAssemblyRegistration(typeof(T).GetAssembly()); - - foreach (var serviceClientDef in this.serviceClientDefinitions.Where(s =>typeof(T).IsAssignableFrom(s.Key))) - { - if (serviceClientDef.Value != null && serviceClientDef.Value.IsSupported(credential, serviceName)) - { - var client = this.CreateServiceClientInstance(serviceClientDef.Value, credential, serviceName, cancellationToken); - return (T) client; - } - } - - throw new InvalidOperationException("A client that supports the requested service for the given instance of OpenStack could not be found."); - } - - /// - /// Creates an instance of the given client type using the given factory function, credential, and cancellation token. - /// - /// A object that can be used to validate and create the give client type. - /// The credential to be used by the created client. - /// The name of the service to be used by the created client. - /// The cancellation token to be used by the created client. - /// An instance of the requested client. - internal IOpenStackServiceClient CreateServiceClientInstance(IOpenStackServiceClientDefinition clientDefinition, ICredential credential, string serviceName, CancellationToken cancellationToken) - { - clientDefinition.AssertIsNotNull("clientDefinition", "Cannot create an OpenStack service with a null client definition."); - - IOpenStackServiceClient instance; - try - { - instance = clientDefinition.Create(credential, serviceName, cancellationToken, this.ServiceLocator) as IOpenStackServiceClient; - } - catch (Exception ex) - { - throw new InvalidOperationException(string.Format("Could not create a service of type '{0}'. See inner exception for details.", clientDefinition.Name), ex); - } - - if (instance != null) - { - return instance; - } - throw new InvalidOperationException(string.Format("Could not create a service of type '{0}'. The type does not derive from or cast to IOpenStackClient. ", clientDefinition.Name)); - } - - /// - public IEnumerable ListAvailableServiceClients() - { - return this.serviceClientDefinitions.Keys; - } - - /// - public void RegisterServiceClient(IOpenStackServiceClientDefinition clientDefinition) where T : IOpenStackServiceClient - { - var servicetType = typeof (T); - - if (this.serviceClientDefinitions.ContainsKey(servicetType)) - { - throw new InvalidOperationException( - string.Format( - "A service of type '{0}' has already been registered, and cannot be registered again.", - servicetType.Name)); - } - - this.serviceClientDefinitions.Add(servicetType, clientDefinition); - } - } -} diff --git a/OpenStack/OpenStack/Properties/AssemblyInfo.cs b/OpenStack/OpenStack/Properties/AssemblyInfo.cs deleted file mode 100644 index 59e554b..0000000 --- a/OpenStack/OpenStack/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,34 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Reflection; -using System.Resources; -using System.Runtime.CompilerServices; - -// 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("OpenStack")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("OpenStack.org")] -[assembly: AssemblyProduct("OpenStack")] -[assembly: AssemblyCopyright("")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] -[assembly: NeutralResourcesLanguage("en")] - -[assembly: InternalsVisibleTo("OpenStack.Test")] \ No newline at end of file diff --git a/OpenStack/OpenStack/ServiceClientContext.cs b/OpenStack/OpenStack/ServiceClientContext.cs deleted file mode 100644 index 3a511b8..0000000 --- a/OpenStack/OpenStack/ServiceClientContext.cs +++ /dev/null @@ -1,63 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Threading; -using OpenStack.Identity; - -namespace OpenStack -{ - /// - /// Wrapper class that provides a context for the various storage clients. - /// - public class ServiceClientContext - { - /// - /// Gets or sets a credential that can be used to connect to the remote OpenStack service. - /// - public IOpenStackCredential Credential { get; set; } - - /// - /// Gets or sets a cancellation token that can be used when connecting to the remote OpenStack service. - /// - public CancellationToken CancellationToken { get; set; } - - /// - /// Gets or sets the name of the storage service. - /// - public string ServiceName { get; set; } - - /// - /// Gets or sets the public endpoint. - /// - public Uri PublicEndpoint { get; set; } - - /// - /// Creates a new instance of the ServiceClientContext class. - /// - /// The credential for this context. - /// The cancellation token for this context. - /// The name of the storage service. - /// The Uri for the public endpoint of the storage service. - internal ServiceClientContext(IOpenStackCredential credential, CancellationToken cancellationToken, string serviceName, Uri publicEndpoint) - { - this.Credential = credential; - this.CancellationToken = cancellationToken; - this.ServiceName = serviceName; - this.PublicEndpoint = publicEndpoint; - } - } -} diff --git a/OpenStack/OpenStack/ServiceRegistrar.cs b/OpenStack/OpenStack/ServiceRegistrar.cs deleted file mode 100644 index 9ebe479..0000000 --- a/OpenStack/OpenStack/ServiceRegistrar.cs +++ /dev/null @@ -1,86 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using OpenStack.Common.Http; -using OpenStack.Common.ServiceLocation; -using OpenStack.Compute; -using OpenStack.Identity; -using OpenStack.Network; -using OpenStack.Storage; - -namespace OpenStack -{ - /// - public class ServiceRegistrar : IServiceLocationRegistrar - { - /// - public void Register(IServiceLocationManager manager, IServiceLocator locator) - { - //Common - manager.RegisterServiceInstance(typeof(IHttpAbstractionClientFactory), new HttpAbstractionClientFactory()); - - //Storage related clients/services - manager.RegisterServiceInstance(typeof(IStorageServicePocoClientFactory), new StorageServicePocoClientFactory()); - manager.RegisterServiceInstance(typeof(IStorageServiceRestClientFactory), new StorageServiceRestClientFactory()); - manager.RegisterServiceInstance(typeof(IStorageContainerNameValidator), new StorageContainerNameValidator()); - manager.RegisterServiceInstance(typeof(IStorageFolderNameValidator), new StorageFolderNameValidator()); - manager.RegisterServiceInstance(typeof(ILargeStorageObjectCreatorFactory), new LargeStorageObjectCreatorFactory()); - - //Compute related clients/services - manager.RegisterServiceInstance(typeof(IComputeServicePocoClientFactory), new ComputeServicePocoClientFactory()); - manager.RegisterServiceInstance(typeof(IComputeServiceRestClientFactory), new ComputeServiceRestClientFactory()); - - //Network related clients/services - manager.RegisterServiceInstance(typeof(INetworkServicePocoClientFactory), new NetworkServicePocoClientFactory()); - manager.RegisterServiceInstance(typeof(INetworkServiceRestClientFactory), new NetworkServiceRestClientFactory()); - - //Identity related clients/services - manager.RegisterServiceInstance(typeof(IIdentityServicePocoClientFactory), new IdentityServicePocoClientFactory()); - manager.RegisterServiceInstance(typeof(IIdentityServiceRestClientFactory), new IdentityServiceRestClientFactory()); - manager.RegisterServiceInstance(typeof(IOpenStackRegionResolver), new OpenStackRegionResolver()); - - //Converters - manager.RegisterServiceInstance(typeof(IStorageContainerPayloadConverter), new StorageContainerPayloadConverter(locator)); - manager.RegisterServiceInstance(typeof(IStorageObjectPayloadConverter), new StorageObjectPayloadConverter()); - manager.RegisterServiceInstance(typeof(IStorageFolderPayloadConverter), new StorageFolderPayloadConverter(locator)); - manager.RegisterServiceInstance(typeof(IStorageAccountPayloadConverter), new StorageAccountPayloadConverter(locator)); - manager.RegisterServiceInstance(typeof(IAccessTokenPayloadConverter), new AccessTokenPayloadConverter()); - manager.RegisterServiceInstance(typeof(IOpenStackServiceCatalogPayloadConverter), new OpenStackServiceCatalogPayloadConverter(locator)); - manager.RegisterServiceInstance(typeof(IOpenStackServiceDefinitionPayloadConverter), new OpenStackServiceDefinitionPayloadConverter(locator)); - manager.RegisterServiceInstance(typeof(IOpenStackServiceEndpointPayloadConverter), new OpenStackServiceEndpointPayloadConverter()); - manager.RegisterServiceInstance(typeof(IComputeFlavorPayloadConverter), new ComputeFlavorPayloadConverter()); - manager.RegisterServiceInstance(typeof(INetworkPayloadConverter), new NetworkPayloadConverter()); - manager.RegisterServiceInstance(typeof(IFloatingIpPayloadConverter), new FloatingIpPayloadConverter()); - manager.RegisterServiceInstance(typeof(IComputeImagePayloadConverter), new ComputeImagePayloadConverter()); - manager.RegisterServiceInstance(typeof(IComputeItemMetadataPayloadConverter), new ComputeItemMetadataPayloadConverter()); - manager.RegisterServiceInstance(typeof(IComputeServerPayloadConverter), new ComputeServerPayloadConverter()); - manager.RegisterServiceInstance(typeof(IComputeKeyPairPayloadConverter), new ComputeKeyPairPayloadConverter()); - - //Client Management - var clientManager = new OpenStackClientManager(locator); - clientManager.RegisterClient(); - manager.RegisterServiceInstance(typeof(IOpenStackClientManager), clientManager); - - //Service Management - var serviceManager = new OpenStackServiceClientManager(locator); - serviceManager.RegisterServiceClient(new StorageServiceClientDefinition()); - serviceManager.RegisterServiceClient(new IdentityServiceClientDefinition()); - serviceManager.RegisterServiceClient(new ComputeServiceClientDefinition()); - serviceManager.RegisterServiceClient(new NetworkServiceClientDefinition()); - manager.RegisterServiceInstance(typeof(IOpenStackServiceClientManager), serviceManager); - } - } -} diff --git a/OpenStack/OpenStack/Storage/ContainerNameValidator.cs b/OpenStack/OpenStack/Storage/ContainerNameValidator.cs deleted file mode 100644 index 28b41b1..0000000 --- a/OpenStack/OpenStack/Storage/ContainerNameValidator.cs +++ /dev/null @@ -1,41 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -namespace OpenStack.Storage -{ - /// - /// Validates a container name. - /// - public interface IStorageContainerNameValidator - { - /// - /// Validates a container name. - /// - /// The name to validate. - /// A value indicating if the the name could be validated. - bool Validate(string containerName); - } - - /// - internal class StorageContainerNameValidator : IStorageContainerNameValidator - { - /// - public bool Validate(string containerName) - { - return !(containerName.Contains("/") || containerName.Contains("\\")); - } - } -} diff --git a/OpenStack/OpenStack/Storage/DynamicLargeObjectManifest.cs b/OpenStack/OpenStack/Storage/DynamicLargeObjectManifest.cs deleted file mode 100644 index de8c674..0000000 --- a/OpenStack/OpenStack/Storage/DynamicLargeObjectManifest.cs +++ /dev/null @@ -1,75 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using OpenStack.Common; - -namespace OpenStack.Storage -{ - /// - /// Represents the manifest for a dynamic large object on the remote instance of OpenStack. - /// - public class DynamicLargeObjectManifest : StorageManifest - { - /// - /// Gets the path where the object segments that make up the manifest can be found. - /// - public string SegmentsPath { get; internal set; } - - /// - /// Creates a new instance of the DynamicLargeObjectManifest class. - /// - /// The name of the parent container. - /// The full name of the manifest file - /// The path where the segments that make up this manifest can be found. - public DynamicLargeObjectManifest(string containerName, string manifestFullName, string segmentsPath) : this(containerName, manifestFullName, new Dictionary(), segmentsPath) - { - } - - /// - /// Creates a new instance of the DynamicLargeObjectManifest class. - /// - /// The name of the parent container. - /// The full name of the manifest file - /// The metadata associated with the storage manifest. - /// The path where the segments that make up this manifest can be found. - public DynamicLargeObjectManifest(string containerName, string manifestFullName, IDictionary metadata, string segmentsPath) - : base(containerName, manifestFullName, metadata) - { - segmentsPath.AssertIsNotNullOrEmpty("segmentsPath", "Cannot create a dynamic large object manifest with a null or empty segments path."); - this.SegmentsPath = segmentsPath; - } - - /// - /// Creates a new instance of the DynamicLargeObjectManifest class. - /// - /// The full name of the storage manifest. - /// The name of the parent storage container for the storage manifest. - /// The last modified data for the storage manifest. - /// The ETag for the storage manifest. - /// The length/size of the storage manifest. - /// The content type of the storage manifest. - /// The metadata associated with the storage manifest. - /// The path where the segments that make up this manifest can be found. - internal DynamicLargeObjectManifest(string fullName, string containerName, DateTime lastModified, string eTag, - long length, string contentType, IDictionary metadata, string segmentsPath) - : base(fullName, containerName, lastModified, eTag, length, contentType, metadata) - { - this.SegmentsPath = segmentsPath; - } - } -} diff --git a/OpenStack/OpenStack/Storage/FolderNameValidator.cs b/OpenStack/OpenStack/Storage/FolderNameValidator.cs deleted file mode 100644 index cfae075..0000000 --- a/OpenStack/OpenStack/Storage/FolderNameValidator.cs +++ /dev/null @@ -1,45 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Text.RegularExpressions; - -namespace OpenStack.Storage -{ - /// - /// Validates a container name. - /// - public interface IStorageFolderNameValidator - { - /// - /// Validates a folder name. - /// - /// The name to validate. - /// A value indicating if the the name could be validated. - bool Validate(string folderName); - } - - /// - internal class StorageFolderNameValidator : IStorageFolderNameValidator - { - /// - public bool Validate(string folderName) - { - //Folder names cannot have consecutive slashes in their names. - //This is not a swift limitation, but it's good practice, and helps simplify things in the rest of the client. - return !Regex.IsMatch(folderName, @"/{2,}"); - } - } -} diff --git a/OpenStack/OpenStack/Storage/ILargeStorageObjectCreator.cs b/OpenStack/OpenStack/Storage/ILargeStorageObjectCreator.cs deleted file mode 100644 index e048cea..0000000 --- a/OpenStack/OpenStack/Storage/ILargeStorageObjectCreator.cs +++ /dev/null @@ -1,40 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; -using System.IO; -using System.Threading.Tasks; - -namespace OpenStack.Storage -{ - /// - /// Creates large storage objects on a remote OpenStack instance. - /// - public interface ILargeStorageObjectCreator - { - /// - /// Creates a large storage object on a remote OpenStack instance. - /// - /// The name of the parent container. - /// The name of the object to create. - /// The metadata associated with the object. - /// The contents of the object. - /// The number of segments to use when creating the object. - /// The name of the container that will hold the object segments. - /// A StorageObject that represents the large object. - Task Create(string containerName, string objectName, IDictionary metadata, Stream content, int numberOfSegments, string segmentsContainer); - } -} diff --git a/OpenStack/OpenStack/Storage/ILargeStorageObjectCreatorFactory.cs b/OpenStack/OpenStack/Storage/ILargeStorageObjectCreatorFactory.cs deleted file mode 100644 index 212977e..0000000 --- a/OpenStack/OpenStack/Storage/ILargeStorageObjectCreatorFactory.cs +++ /dev/null @@ -1,23 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -namespace OpenStack.Storage -{ - public interface ILargeStorageObjectCreatorFactory - { - ILargeStorageObjectCreator Create(IStorageServiceClient client); - } -} diff --git a/OpenStack/OpenStack/Storage/IStorageAccountPayloadConverter.cs b/OpenStack/OpenStack/Storage/IStorageAccountPayloadConverter.cs deleted file mode 100644 index 71eb33d..0000000 --- a/OpenStack/OpenStack/Storage/IStorageAccountPayloadConverter.cs +++ /dev/null @@ -1,33 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using OpenStack.Common.Http; - -namespace OpenStack.Storage -{ - /// - /// Converts a Json payload into an access token Id. - /// - interface IStorageAccountPayloadConverter - { - /// - /// Converts a Json payload into an access token Id. - /// - /// The Json payload to convert. - /// The converted access token Id. - StorageAccount Convert(string name, IHttpHeadersAbstraction headers, string payload); - } -} diff --git a/OpenStack/OpenStack/Storage/IStorageContainerPayloadConverter.cs b/OpenStack/OpenStack/Storage/IStorageContainerPayloadConverter.cs deleted file mode 100644 index 9d8bc9d..0000000 --- a/OpenStack/OpenStack/Storage/IStorageContainerPayloadConverter.cs +++ /dev/null @@ -1,43 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; -using OpenStack.Common.Http; - -namespace OpenStack.Storage -{ - /// - /// Converts a Json payload into an access token Id. - /// - public interface IStorageContainerPayloadConverter - { - /// - /// Converts a Json payload into a storage container. - /// - /// The Json payload to convert. - /// The converted storage container. - IEnumerable Convert(string payload); - - /// - /// Converts a collection of Http headers and a Json payload into a storage container. - /// - /// The name of the storage container. - /// The collection of headers. - /// The Json payload. - /// A storage container. - StorageContainer Convert(string name, IHttpHeadersAbstraction headers, string payload); - } -} diff --git a/OpenStack/OpenStack/Storage/IStorageFolderPayloadConverter.cs b/OpenStack/OpenStack/Storage/IStorageFolderPayloadConverter.cs deleted file mode 100644 index ef2b1c8..0000000 --- a/OpenStack/OpenStack/Storage/IStorageFolderPayloadConverter.cs +++ /dev/null @@ -1,39 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; - -namespace OpenStack.Storage -{ - public interface IStorageFolderPayloadConverter - { - /// - /// Converts a list of storage objects into a deep folder structure. - /// - /// The list of objects to convert. - /// A deep folder structure. - IEnumerable Convert(IEnumerable objects); - - /// - /// Converts a Json payload into a shallow storage folder object. - /// - /// The name of the parent container. - /// The full name of the folder. - /// The Json payload. - /// A shallow storage folder object. - StorageFolder Convert(string containerName, string folderName, string payload); - } -} diff --git a/OpenStack/OpenStack/Storage/IStorageObjectPayloadConverter.cs b/OpenStack/OpenStack/Storage/IStorageObjectPayloadConverter.cs deleted file mode 100644 index b62d497..0000000 --- a/OpenStack/OpenStack/Storage/IStorageObjectPayloadConverter.cs +++ /dev/null @@ -1,61 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; -using Newtonsoft.Json.Linq; -using OpenStack.Common.Http; - -namespace OpenStack.Storage -{ - /// - /// Converts a Json payload into a storage object. - /// - interface IStorageObjectPayloadConverter - { - /// - /// Converts a Json payload into a list of storage objects. - /// - /// The name of the parent container. - /// The Json payload. - /// A list of storage objects. - IEnumerable Convert(string containerName, string payload); - - /// - /// Converts a collection of Http headers into a storage object. - /// - /// The name of the parent container. - /// The name of the storage object. - /// The collection of headers - /// The storage object length just created - /// The storage object. - StorageObject Convert(string containerName, string objectName, IHttpHeadersAbstraction headers, long? objectLength = null); - - /// - /// Converts a collection of StorageObjects into a Json payload. - /// - /// A collection of StorageObjects to convert. - /// The Json payload. - string Convert(IEnumerable objects); - - /// - /// Converts a Json token into a storage object. - /// - /// The token. - /// The name of the parent container. - /// The storage object. - StorageObject ConvertSingle(JToken obj, string containerName); - } -} diff --git a/OpenStack/OpenStack/Storage/IStorageServiceClient.cs b/OpenStack/OpenStack/Storage/IStorageServiceClient.cs deleted file mode 100644 index b8e0cee..0000000 --- a/OpenStack/OpenStack/Storage/IStorageServiceClient.cs +++ /dev/null @@ -1,208 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading.Tasks; - -namespace OpenStack.Storage -{ - /// - /// Client that can interact with an OpenStack storage service. - /// - public interface IStorageServiceClient : IOpenStackServiceClient - { - /// - /// Gets the threshold, in bytes, of what is considered a large object. - /// The threshold is used when determining when to split up a object into segments, and use a storage manifest to represent the segments of the object. - /// - long LargeObjectThreshold { get; set; } - - /// - /// Gets the number of segments that will be created when a large object needs to be segmented and uploaded with a manifest. - /// - int LargeObjectSegments { get; set; } - - /// - /// The name of the container that will be used to hold the segments of large objects. - /// - string LargeObjectSegmentContainer { get; set; } - - /// - /// Creates a storage container on the remote OpenStack instance. - /// - /// The name of the container. - /// Metadata for the container. - /// An async task. - Task CreateStorageContainer(string containerName, IDictionary metadata); - - /// - /// Gets a storage container from the remote OpenStack instance. - /// - /// The name of the container. - /// A storage container. - Task GetStorageContainer(string containerName); - - /// - /// Deletes a storage container from the remote OpenStack instance. - /// - /// The name of the container. - /// An async task. - Task DeleteStorageContainer(string containerName); - - /// - /// Updates a storage container on the remote OpenStack instance. - /// - /// The container. - /// An async task. - Task UpdateStorageContainer(StorageContainer container); - - /// - /// Lists the storage object in a given container. - /// - /// The name of the container. - /// An enumerable list of storage objects. - Task> ListStorageObjects(string containerName); - - /// - /// Lists storage containers on the remote OpenStack instance. - /// - /// An enumerable list of storage containers. - Task> ListStorageContainers(); - - /// - /// Gets the details of the current storage account from the remote OpenStack instance. - /// - /// A storage account. - Task GetStorageAccount(); - - /// - /// Creates a storage object on the remote OpenStack instance. - /// - /// The name of the parent container. - /// The name of the object. - /// Metadata for the object. - /// The objects content. - /// A storage object. - Task CreateStorageObject(string containerName, string objectName, IDictionary metadata, Stream content); - - /// - /// Copy a storage object on the remote OpenStack instance. - /// - /// The name of the parent container. - /// The name of the object. - /// The container destination name. - /// The object destination name. - /// A storage object. - Task CopyStorageObject(string containerName, string objectName, string destinationContainerName, string destinationObjectName = null); - - /// - /// Creates a storage object on the remote OpenStack instance. - /// - /// The name of the parent container. - /// The name of the object. - /// Metadata for the object. - /// The objects content. - /// The number of segments to use. - /// A storage object. - Task CreateLargeStorageObject(string containerName, string objectName, IDictionary metadata, Stream content, int numberOfsegments); - - /// - /// Gets a storage object from the remote OpenStack instance. - /// - /// The name of the parent container. - /// The name of the object. - /// The storage object. - Task GetStorageObject(string containerName, string objectName); - - /// - /// Downloads the content of a storage object from the remote OpenStack instance. - /// - /// The name of the parent container. - /// The name of the object. - /// The output stream to copy the objects content to. - /// The storage object details. - Task DownloadStorageObject(string containerName, string objectName, Stream outputStream); - - /// - /// Deletes a storage object from the remote OpenStack instance. - /// - /// The name of the parent container. - /// The name of the object. - /// An async task. - Task DeleteStorageObject(string containerName, string objectName); - - /// - /// Updates a storage object on the remote OpenStack instance. - /// - /// The object to update. - /// An async task. - Task UpdateStorageObject(StorageObject obj); - - /// - /// Creates a storage manifest on the remote OpenStack instance. - /// - /// The name of the parent container. - /// The name of the manifest. - /// Metadata for the manifest. - /// The list of storage objects. - /// An async task. - Task CreateStorageManifest(string containerName, string manifestName, IDictionary metadata, IEnumerable objects); - - /// - /// Creates a storage manifest on the remote OpenStack instance. - /// - /// The name of the parent container. - /// The name of the manifest. - /// Metadata for the manifest. - /// The path to the segment objects in the manifest. - /// An async task. - Task CreateStorageManifest(string containerName, string manifestName, IDictionary metadata, string segmentsPath); - - /// - /// Gets a storage manifest from the remote OpenStack instance. - /// - /// The name of the parent container. - /// The name of the manifest. - /// The storage manifest. - Task GetStorageManifest(string containerName, string objectName); - - /// - /// Gets a storage folder from the remote OpenStack instance. The returned folder is a shallow object graph representation. - /// - /// The name of the parent container. - /// The name of the folder to get. - /// A shallow object representation of the folder and it's contained objects and sub folders. - Task GetStorageFolder(string containerName, string folderName); - - /// - /// Creates a storage folder on the remote OpenStack instance. - /// - /// The name of the parent container. - /// The name of the folder to create. - /// An async task. - Task CreateStorageFolder(string containerName, string folderName); - - /// - /// Deletes a storage folder from the remote OpenStack instance. - /// - /// The name of the parent container. - /// The name of the folder to delete. - /// An async task. - Task DeleteStorageFolder(string containerName, string folderName); - } -} diff --git a/OpenStack/OpenStack/Storage/IStorageServicePocoClient.cs b/OpenStack/OpenStack/Storage/IStorageServicePocoClient.cs deleted file mode 100644 index c24249c..0000000 --- a/OpenStack/OpenStack/Storage/IStorageServicePocoClient.cs +++ /dev/null @@ -1,149 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.IO; -using System.Threading.Tasks; - -namespace OpenStack.Storage -{ - /// - /// Client that can interact with an OpenStack storage service. - /// - public interface IStorageServicePocoClient - { - /// - /// Creates a storage object on the remote OpenStack instance. - /// - /// The storage object to create. - /// The content of the storage object. - /// A storage object. - Task CreateStorageObject(StorageObject obj, Stream content); - - /// - /// Copy a storage object on the remote OpenStack instance. - /// - /// The storage object to copy. - /// The container destination name. - /// The destination object name. - /// A storage object. - Task CopyStorageObject(StorageObject obj, string destinationContainerName, string destinationObjectName = null); - - /// - /// Creates a storage manifest on the remote OpenStack instance. - /// - /// The storage manifest to create. - /// A storage manifest. - Task CreateStorageManifest(StorageManifest manifest); - - /// - /// Creates a storage container on the remote OpenStack instance. - /// - /// The storage container to create. - /// An async task. - Task CreateStorageContainer(StorageContainer container); - - /// - /// Gets the details of the current storage account. - /// - /// A storage account. - Task GetStorageAccount(); - - /// - /// Gets the details of a storage container. - /// - /// The name of the storage container. - /// The storage container. - Task GetStorageContainer(string containerName); - - /// - /// Gets a storage object from the remote OpenStack instance. - /// - /// The name of the parent storage container. - /// The name of the storage object. - /// The storage object. - Task GetStorageObject(string containerName, string objectName); - - /// - /// Gets a storage manifest from the remote OpenStack instance. - /// - /// The name of the parent storage container. - /// The name of the storage manifest. - /// The storage manifest. - Task GetStorageManifest(string containerName, string manifestName); - - /// - /// Downloads the content of a storage object from the remote OpenStack instance. - /// - /// The name of the parent storage container. - /// The name of the storage object. - /// The output stream to copy the objects content to. - /// The details of the storage object. - Task DownloadStorageObject(string containerName, string objectName, Stream outputStream); - - /// - /// Deletes a storage object from the remote OpenStack instance. - /// - /// The name of the parent storage container. - /// The name of the object to delete. - /// An async task. - Task DeleteStorageObject(string containerName, string objectName); - - /// - /// Deletes a storage container from the remote OpenStack instance. - /// - /// The name of the storage container. - /// An async task. - Task DeleteStorageContainer(string containerName); - - /// - /// Updates a storage container on the remote OpenStack instance. - /// - /// The storage container to update. - /// An async task. - Task UpdateStorageContainer(StorageContainer container); - - /// - /// Updates a storage object on the remote OpenStack instance. - /// - /// The storage object to update. - /// An async task. - Task UpdateStorageObject(StorageObject obj); - - /// - /// Gets a storage folder from the remote OpenStack instance. The returned folder is a shallow object graph representation. - /// - /// The name of the parent container. - /// The name of the folder to get. - /// A shallow object representation of the folder and it's contained objects and sub folders. - Task GetStorageFolder(string containerName, string folderName); - - /// - /// Creates a storage folder on the remote OpenStack instance. - /// - /// The name of the parent container. - /// The name of the folder to create. - /// An async task. - Task CreateStorageFolder(string containerName, string folderName); - - /// - /// Deletes a storage folder from the remote OpenStack instance. - /// - /// The name of the parent container. - /// The name of the folder to delete. - /// An async task. - Task DeleteStorageFolder(string containerName, string folderName); - } -} diff --git a/OpenStack/OpenStack/Storage/IStorageServicePocoClientFactory.cs b/OpenStack/OpenStack/Storage/IStorageServicePocoClientFactory.cs deleted file mode 100644 index 7f6a865..0000000 --- a/OpenStack/OpenStack/Storage/IStorageServicePocoClientFactory.cs +++ /dev/null @@ -1,34 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Storage -{ - /// - /// Constructs a client that can be used to interact with the POCO objects related to the OpenStack storage service. - /// - public interface IStorageServicePocoClientFactory - { - /// - /// Creates a client that can be used to interact with the OpenStack storage service. - /// - /// A storage service context to be used by the client. - /// A service locator to be used to locate/inject dependent services. - /// The client. - IStorageServicePocoClient Create(ServiceClientContext context, IServiceLocator serviceLocator); - } -} diff --git a/OpenStack/OpenStack/Storage/IStorageServiceRestClient.cs b/OpenStack/OpenStack/Storage/IStorageServiceRestClient.cs deleted file mode 100644 index 0bef921..0000000 --- a/OpenStack/OpenStack/Storage/IStorageServiceRestClient.cs +++ /dev/null @@ -1,161 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; -using System.IO; -using System.Threading.Tasks; -using OpenStack.Common.Http; - -namespace OpenStack.Storage -{ - /// - /// Client that can connect to the REST endpoints of an OpenStack storage service. - /// - public interface IStorageServiceRestClient - { - /// - /// Creates a storage object on the remote OpenStack instance. - /// - /// The name of the parent storage container. - /// The name of the storage object. - /// Metadata associated with the storage object. - /// The storage objects content. - /// The Http response from the remote service. - Task CreateObject(string containerName, string objectName, IDictionary metadata, Stream content); - - /// - /// Creates a dynamic large object manifest on the remote OpenStack instance. - /// - /// The name of the parent storage container. - /// The name of the storage manifest. - /// Metadata associated with the storage manifest. - /// The path to the segment objects that the manifest points to. - /// The Http response from the remote service. - Task CreateDynamicManifest(string containerName, string manifestName, IDictionary metadata, string segmentsPath); - - /// - /// Creates a static large object manifest on the remote OpenStack instance. - /// - /// The name of the parent storage container. - /// The name of the storage manifest. - /// Metadata associated with the storage manifest. - /// The manifests content. - /// The Http response from the remote service. - Task CreateStaticManifest(string containerName, string manifestName, IDictionary metadata, Stream content); - - /// - /// Creates a storage container on the remote OpenStack instance. - /// - /// The name of the storage container. - /// Metadata associated with the storage container. - /// The Http response from the remote service. - Task CreateContainer(string containerName, IDictionary metadata); - - /// - /// Gets a storage object from the remote OpenStack instance. - /// - /// The name of the parent storage container. - /// The name of the object. - /// The Http response from the remote service. - Task GetObject(string containerName, string objectName); - - /// - /// Gets a storage folder from the remote OpenStack instance. - /// - /// The name of the parent storage container. - /// The name of the folder. - /// The Http response from the remote service. - Task GetFolder(string containerName, string folderName); - - /// - /// Gets a storage container from the remote OpenStack instance. - /// - /// The name of the storage container. - /// The Http response from the remote service. - Task GetContainer(string containerName); - - /// - /// Deletes a storage object from the remote OpenStack instance. - /// - /// The name of the parent storage container. - /// The name of the storage object. - /// The Http response from the remote service. - Task DeleteObject(string containerName, string objectName); - - /// - /// Deletes a storage container from the remote OpenStack instance. - /// - /// The name of the storage container. - /// The Http response from the remote service. - Task DeleteContainer(string containerName); - - /// - /// Updates a storage object on the remote OpenStack instance. - /// - /// The name of the parent storage container. - /// The name of the storage object. - /// Metadata associated with the storage object. - /// The Http response from the remote service. - Task UpdateObject(string containerName, string objectName, IDictionary metadata); - - /// - /// Updates a storage container on the remote OpenStack instance. - /// - /// The name of the storage container. - /// Metadata associated with the storage container. - /// The Http response from the remote service. - Task UpdateContainer(string containerName, IDictionary metadata); - - /// - /// Gets the metadata for a storage container from the remote OpenStack instance. - /// - /// The name of the storage container. - /// The Http response from the remote service. - Task GetContainerMetadata(string containerName); - - /// - /// Gets the metadata for a storage object from the remote OpenStack instance. - /// - /// The name of the parent storage container. - /// The name of the storage object. - /// The Http response from the remote service. - Task GetObjectMetadata(string containerName, string objectName); - - /// - /// Gets the metadata for a storage manifest from the remote OpenStack instance. - /// - /// The name of the parent storage container. - /// The name of the storage manifest. - /// The Http response from the remote service. - Task GetManifestMetadata(string containerName, string manifestName); - - /// - /// Copies an object on the remote OpenStack instance. - /// - /// The name of the parent storage container for the source storage object. - /// The name of the source storage object. - /// The name of the parent storage container for the target storage object. - /// The name of the target storage object. - /// The Http response from the remote service. - Task CopyObject(string sourceContainerName, string sourceObjectName, string targetContainerName, string targetObjectName); - - /// - /// Gets the details of the current storage account. - /// - /// The Http response from the remote service. - Task GetAccount(); - } -} diff --git a/OpenStack/OpenStack/Storage/IStorageServiceRestClientFactory.cs b/OpenStack/OpenStack/Storage/IStorageServiceRestClientFactory.cs deleted file mode 100644 index cade6b4..0000000 --- a/OpenStack/OpenStack/Storage/IStorageServiceRestClientFactory.cs +++ /dev/null @@ -1,34 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Storage -{ - /// - /// Constructs a client that can be used to connect to the REST endpoints of an OpenStack storage service. - /// - public interface IStorageServiceRestClientFactory - { - /// - /// Creates a client that can be used to connect to an OpenStack storage service. - /// - /// The storage service context that the client will use. - /// A service locator to be used to locate/inject dependent services. - /// The client. - IStorageServiceRestClient Create(ServiceClientContext context, IServiceLocator serviceLocator); - } -} diff --git a/OpenStack/OpenStack/Storage/LargeStorageObjectCreator.cs b/OpenStack/OpenStack/Storage/LargeStorageObjectCreator.cs deleted file mode 100644 index 74f281f..0000000 --- a/OpenStack/OpenStack/Storage/LargeStorageObjectCreator.cs +++ /dev/null @@ -1,405 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Threading.Tasks; -using OpenStack.Common; - -namespace OpenStack.Storage -{ - /// - internal class LargeStorageObjectCreator : ILargeStorageObjectCreator - { - internal IStorageServiceClient StorageClient; - - /// - /// Creates a new instance of the LargeStorageObjectCreator class. - /// - /// The storage service client to use when creating the large object. - internal LargeStorageObjectCreator(IStorageServiceClient storageClient) - { - storageClient.AssertIsNotNull("storageClient","Cannot create a large object with a null storage client."); - this.StorageClient = storageClient; - } - - /// - public async Task Create(string containerName, string objectName, IDictionary metadata, Stream content, int numberOfSegments, string segmentsContainer) - { - containerName.AssertIsNotNullOrEmpty("containerName", "Cannot create a large storage object with a null or empty container name."); - objectName.AssertIsNotNullOrEmpty("objectName", "Cannot create a large storage object with a null or empty name."); - metadata.AssertIsNotNull("metadata", "Cannot create a large storage object with null metadata."); - content.AssertIsNotNull("content", "Cannot create a large storage object with null content."); - segmentsContainer.AssertIsNotNullOrEmpty("segmentsContainer","Cannot create a large object with a null or empty segments container name."); - - if (numberOfSegments <= 0) - { - throw new ArgumentException("Cannot create a large object with zero or less segments.", "numberOfSegments"); - } - - var segmentFolder = await this.GetSegmentsFolder(segmentsContainer, objectName); - - var chunkSize = this.GetChunkSize(content.Length, numberOfSegments); - var lastSegmentAndId = this.GetLastSegmentIdAndName(segmentFolder); - var lastSegmentId = lastSegmentAndId.Key; - var lastSegmentFullName = string.Format("{0}/{1}", objectName, lastSegmentAndId.Value); - var offset = lastSegmentId * chunkSize; - - if (lastSegmentId > 0) - { - //we should drop the last segment (as it's very possible it was corrupted) - await StorageClient.DeleteStorageObject(segmentsContainer, lastSegmentFullName); - } - - //Seek to the correct location based on whatever segments have been uploaded, if any - content.Seek(offset, SeekOrigin.Begin); - - while (content.Position < content.Length) - { - //If the remaining data in the stream is less then the chunk size, reset the chunk size to the remaining data size. - if ((content.Length - content.Position) < chunkSize) - { - chunkSize = (content.Length - content.Position); - } - - await CreateSegment(content, chunkSize, objectName, lastSegmentId, metadata, segmentsContainer); - lastSegmentId++; - } - - var segments = await StorageClient.GetStorageFolder(segmentsContainer, objectName); - - return await CreateLargeObjectManifest(containerName, objectName, metadata, segments.Objects, segmentsContainer); - } - - /// - /// Creates a large objects manifest. - /// - /// The name of the parent container. - /// The name of the manifest. - /// The associated metadata for the manifest. - /// The collection of segments that represent the large object. - /// The container that contains the object segments. - /// The StorageObject representation of the final manifest. - internal async Task CreateLargeObjectManifest(string containerName, string manifestName, IDictionary metadata, ICollection segments, string segmentContainerName) - { - try - { - var manifest = this.BuildStorageManifest(containerName, manifestName, metadata, segments, segmentContainerName); - await this.CreateStorageManifest(manifest); - return await StorageClient.GetStorageObject(containerName, manifestName); - } - catch (InvalidOperationException ex) - { - throw new InvalidOperationException(string.Format("Could not create large object '{0}/{1}'. Could not create object manifest. See inner exception for details.", containerName, manifestName), ex); - } - } - - /// - /// Creates a storage manifest on the remote OpenStack instance. - /// - /// The manifest to create. - /// An async task. - internal async Task CreateStorageManifest(StorageManifest manifest) - { - manifest.AssertIsNotNull("manifest", "Cannot create a manifest that is null."); - - var dynoManifest = manifest as DynamicLargeObjectManifest; - var staticManifest = manifest as StaticLargeObjectManifest; - if (dynoManifest == null && staticManifest == null) - { - throw new ArgumentException(string.Format("Cannot create manifest. The given manifest type '{0}' is not supported.", manifest.GetType().Name), "manifest"); - } - - if (dynoManifest != null) - { - await this.StorageClient.CreateStorageManifest(dynoManifest.ContainerName, dynoManifest.FullName, dynoManifest.Metadata, dynoManifest.SegmentsPath); - } - - if (staticManifest != null) - { - await this.StorageClient.CreateStorageManifest(staticManifest.ContainerName, staticManifest.FullName, staticManifest.Metadata, staticManifest.Objects); - } - } - - /// - /// Creates a segment of a large object. - /// - /// The stream that holds the large objects content. - /// The size of the segment. - /// The name of the large object. - /// The Id for the segment. - /// The associated metadata for the large object. - /// The name of the container that will hold the object segments. - /// The StorageObject representation of the segment. - internal async Task CreateSegment(Stream content, long chunkSize, string objectName, int segmentId, IDictionary metadata, string segmentsContainer) - { - try - { - var chunk = this.GetObjectChunk(content, chunkSize); - var segmentKey = this.BuildSegmentKey(objectName, segmentId); - return await this.StorageClient.CreateStorageObject(segmentsContainer, segmentKey, metadata, chunk); - } - catch (InvalidOperationException ex) - { - throw new InvalidOperationException(string.Format("Could not create large object '{0}'. Could not create object segment '{1}'. See inner exception for details.", objectName, segmentId), ex); - } - } - - /// - /// Gets the folder that should be used for storing segments of large objects. - /// - /// The name of the parent container. - /// The name of the large object. - /// A StorageFolder object. - internal async Task GetSegmentsFolder(string containerName, string objectName) - { - StorageContainer container = null; - try - { - container = await this.StorageClient.GetStorageContainer(containerName); - } - catch (InvalidOperationException ex) - { - if (!ex.Message.Contains(HttpStatusCode.NotFound.ToString())) - { - throw; - } - } - - if (container == null) - { - await this.StorageClient.CreateStorageContainer(containerName, new Dictionary()); - await this.StorageClient.CreateStorageFolder(containerName, objectName); - return await this.StorageClient.GetStorageFolder(containerName, objectName); - } - - var segmentFolder = - container.Folders.FirstOrDefault( - f => string.Equals(f.FullName, objectName, StringComparison.Ordinal)); - - if (segmentFolder == null) - { - await this.StorageClient.CreateStorageFolder(containerName, objectName); - return await this.StorageClient.GetStorageFolder(containerName, objectName); - } - - return segmentFolder; - } - - - /// - /// Calculates the optimal size for each chunk of an object that needs to be segmented. - /// - /// The total size of the object. - /// The desired number of segments. - /// The optimal chunk size, in bytes. - internal long GetChunkSize(long objectSize, int numberOfSegments) - { - if (objectSize <= 0) - { - throw new ArgumentException("Chunk size cannot be calculated. object size " + objectSize + " is less then or equal to zero.", "objectSize"); - } - - if (numberOfSegments < 0) - { - throw new ArgumentException("Chunk size cannot be calculated. Number of segments must be greater then or equal to zero.", "numberOfSegments"); - } - - return numberOfSegments == 0 ? objectSize : Convert.ToInt64(Math.Ceiling((double)objectSize / (double)numberOfSegments)); - } - - /// - /// Gets the Id of the segment that the given storage object represents. - /// - /// The storage object to extract the Id from. - /// The Id of the segment that the file represents. - internal int GetSegmentIdFromKey(StorageObject storageObject) - { - try - { - var segmentId = Convert.ToInt32(storageObject.Name); - if (segmentId < 0) - { - throw new System.FormatException("Cannot get segment Id from key. Segment number cannot be negative."); - } - return segmentId; - - } - catch (System.OverflowException) - { - //if the segment number is bigger than an int32, then it's an invalid format - throw new System.FormatException("Segment number is too large. The segment number must be a valid Int32."); - } - catch (System.FormatException) - { - //if the segment number is bigger than an int32, then it's an invalid format - throw new System.FormatException(string.Format("The segment's file name does not have the correct format. '{0}' is invalid.", storageObject.FullName)); - } - } - - /// - /// Gets the last segment of a large object that was found in the given folder. - /// - /// The folder that contains the segments of the large object. - /// A key value pair that represents the segment Id and the name of the storage object that represents that segment. - internal KeyValuePair GetLastSegmentIdAndName(StorageFolder segmentFolder) - { - segmentFolder.AssertIsNotNull("segmentFolder","Cannot get segment id or name given a null segment folder."); - if (segmentFolder.Objects.Count == 0) - { - return new KeyValuePair(0, string.Empty); - } - - try - { - var segments = segmentFolder.Objects.Select(o => new KeyValuePair(GetSegmentIdFromKey(o), o.Name)).ToList(); - segments.Sort((kvp1, kvp2) => kvp1.Key.CompareTo(kvp2.Key)); - - return segments.Last(); - } - catch (System.FormatException) - { - //If the segment id in the file is malformed (IE does not conform to the format we expect) - //Then we cannot get the last segment. - return new KeyValuePair(0, string.Empty); - } - } - - /// - /// Gets a portion of a stream that represents a large object. - /// - /// The input stream. - /// The size of the chunk to return. - /// A stream that represents the chunk of the large object. - internal Stream GetObjectChunk(Stream input, long chunkSize) - { - if (input == null) - { - throw new ArgumentNullException("input"); - } - if (!input.CanRead) - { - throw new InvalidOperationException("Cannot read from input stream."); - } - - if (chunkSize <= 0) - { - throw new ArgumentException("Cannot get chunk. Chunk size must be greater then zero.", "chunkSize"); - } - - var chunkBytesRead = 0; - var buffer = new byte[chunkSize]; - - while (chunkBytesRead < chunkSize) - { - var bytesRead = input.Read(buffer, chunkBytesRead, Convert.ToInt32(chunkSize - chunkBytesRead)); - if (bytesRead == 0) - { - break; - } - chunkBytesRead += bytesRead; - } - - return new MemoryStream(buffer); - } - - /// - /// Builds the full name for a segment of a large object. - /// - /// The full name of the folder that will contain this segment. - /// The segment number of this segment. - /// The full name for the segment. - internal string BuildSegmentKey(string folderName, int segmentNumber) - { - folderName.AssertIsNotNullOrEmpty("folderName","Cannot build segment key with a null or empty folder name."); - if (segmentNumber < 0) - { - throw new ArgumentException("Cannot build segment Id. Segment number must be greater than zero.", "segmentNumber"); - } - - return string.Format("{0}/{1}", folderName.Trim('/'), segmentNumber.ToString("D10")); - } - - /// - /// Builds a StorageManifest for a large object. - /// The type of the manifest, static or dynamic, will be inferred based on the segments collection. - /// - /// The parent container name. - /// The name of the manifest. - /// The associated metadata for the manifest. - /// A collection of StorageObjects that represent the segments of the large object. - /// A name of the container that contains the object segments. - /// A StorageManifest object. - internal StorageManifest BuildStorageManifest(string containerName, string manifestName, IDictionary metadata, ICollection segments, string segmentContainer) - { - segments.AssertIsNotNull("segments", "Cannot build a manifest with a null segment collection."); - if (segments.Count == 0) - { - throw new ArgumentException("Cannot build a manifest with an empty segment collection.", "segments"); - } - - //Based on the OpenStack Swift API 1.0 documentation: - //1. All segments in a static large object must be at least 1MB in size (except for the last segment) - //2. There is a max of 1000 segments. - //3. The largest static file that can be represented by a manifest and still copied is 5GB - var staticSegmentLimit = 1000; - var minStaticSegmentSize = 1048576; - var maxStaticObjectSize = 5368709120; - - var totalSize = segments.Select(s => s.Length).Sum(); - if (segments.Count() < staticSegmentLimit && HasMinSizeSegments(segments, minStaticSegmentSize) && totalSize < maxStaticObjectSize) - { - //If we can represent the segments using a static manifest, we should. - return new StaticLargeObjectManifest(containerName, manifestName, segments); - } - - return new DynamicLargeObjectManifest(containerName, manifestName, string.Format("{0}/{1}/", segmentContainer, manifestName)); - } - - /// - /// Determines if the collection of StorageObjects meets the minimum size requirements for a static large object manifest. - /// - /// A collection of StorageObjects. - /// The minimum size in bytes for segments. - /// A value indicating if the collection meets the minimum size criteria. - internal bool HasMinSizeSegments(ICollection segments, long minSegmentSize) - { - segments.AssertIsNotNull("segments", "Cannot ensure that a collection of segments meets minimum size criteria with a null segment collection."); - var segmentsToCheck = new List(); - if (segments.Count == 0) - { - //If the collection is empty it does not have any segments that are of the min size. - return false; - } - - if (segments.Count == 1) - { - //If the collection only has one element then it must meet the criteria (even though the spec says the last segment can be any size). - segmentsToCheck.Add(segments.First()); - } - else - { - //All segments except the last one must be large then the min size. - segmentsToCheck.AddRange(segments.Take(segments.Count -1)); - } - - return segmentsToCheck.All(s => s.Length > minSegmentSize); - } - } -} diff --git a/OpenStack/OpenStack/Storage/LargeStorageObjectCreatorFactory.cs b/OpenStack/OpenStack/Storage/LargeStorageObjectCreatorFactory.cs deleted file mode 100644 index 9722602..0000000 --- a/OpenStack/OpenStack/Storage/LargeStorageObjectCreatorFactory.cs +++ /dev/null @@ -1,26 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -namespace OpenStack.Storage -{ - internal class LargeStorageObjectCreatorFactory : ILargeStorageObjectCreatorFactory - { - public ILargeStorageObjectCreator Create(IStorageServiceClient client) - { - return new LargeStorageObjectCreator(client); - } - } -} \ No newline at end of file diff --git a/OpenStack/OpenStack/Storage/StaticLargeObjectManifest.cs b/OpenStack/OpenStack/Storage/StaticLargeObjectManifest.cs deleted file mode 100644 index 54ca833..0000000 --- a/OpenStack/OpenStack/Storage/StaticLargeObjectManifest.cs +++ /dev/null @@ -1,76 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using OpenStack.Common; - -namespace OpenStack.Storage -{ - /// - /// Represents a manifest for a static large object on the remote OpenStack instance. - /// - public class StaticLargeObjectManifest : StorageManifest - { - /// - /// Gets a collection of objects in the manifest. - /// - public ICollection Objects { get; internal set; } - - /// - /// Creates a new instance of the StaticLargeObjectManifest class. - /// - /// The name of the parent container. - /// The full name of the manifest. - /// A collection of objects that are included in the manifest. - public StaticLargeObjectManifest(string containerName, string manifestFullName, ICollection objects ) : base(containerName, manifestFullName) - { - objects.AssertIsNotNull("objects","Cannot create a static large object manifest with a null object collection."); - this.Objects = objects; - } - - /// - /// Creates a new instance of the StaticLargeObjectManifest class. - /// - /// The name of the parent container. - /// The full name of the manifest. - /// A collection of objects that are included in the manifest. - /// The metadata associated with the storage manifest. - public StaticLargeObjectManifest(string containerName, string manifestFullName, IDictionary metadata, ICollection objects) - : base(containerName, manifestFullName, metadata) - { - objects.AssertIsNotNull("objects", "Cannot create a static large object manifest with a null object collection."); - this.Objects = objects; - } - - /// - /// Creates a new instance of the StaticLargeObjectManifest class. - /// - /// The full name of the storage manifest. - /// The name of the parent storage container for the storage manifest. - /// The last modified data for the storage manifest. - /// The ETag for the storage manifest. - /// The length/size of the storage manifest. - /// The content type of the storage manifest. - /// The metadata associated with the storage manifest. - internal StaticLargeObjectManifest(string fullName, string containerName, DateTime lastModified, string eTag, - long length, string contentType, IDictionary metadata) - : base(fullName, containerName, lastModified, eTag, length, contentType, metadata) - { - this.Objects = new List(); - } - } -} diff --git a/OpenStack/OpenStack/Storage/StorageAccount.cs b/OpenStack/OpenStack/Storage/StorageAccount.cs deleted file mode 100644 index d87baf9..0000000 --- a/OpenStack/OpenStack/Storage/StorageAccount.cs +++ /dev/null @@ -1,96 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; -using System.Linq; -using OpenStack.Common; - -namespace OpenStack.Storage -{ - /// - /// Represents a storage account. - /// - public class StorageAccount - { - /// - /// Gets the name of the storage account. - /// - public string Name { get; private set; } - - /// - /// Gets the total number of bytes used in the account. - /// - public long TotalBytesUsed { get; private set; } - - /// - /// Gets the total number of storage objects in the account. - /// - public int TotalObjectCount { get; private set; } - - /// - /// Gets the total number of storage containers in the account. - /// - public int TotalContainerCount { get; private set; } - - /// - /// Gets a list of storage containers in the account. - /// - public IEnumerable Containers { get; private set; } - - /// - /// Gets the metadata associated with the account. - /// - public IDictionary Metadata { get; private set; } - - /// - /// Creates a new instance of the StorageAccount class. - /// - /// The name of the account. - /// The total number of bytes used in the account. - /// The total number of storage objects in the account. - /// The total number of storage containers in the account. - /// A list of storage containers in the account. - internal StorageAccount(string name, long totalBytes, int totalObjects, int totalContainers, IEnumerable containers) - : this(name, totalBytes, totalObjects, totalContainers, new Dictionary(), containers) - { - } - - /// - /// Creates a new instance of the StorageAccount class. - /// - /// The name of the account. - /// The total number of bytes used in the account. - /// The total number of storage objects in the account. - /// The total number of storage containers in the account. - /// Metadata associated with this account. - /// A list of storage containers in the account. - internal StorageAccount(string name, long totalBytes, int totalObjects, int totalContainers, IDictionary metadata, IEnumerable containers) - { - name.AssertIsNotNullOrEmpty("name"); - totalBytes.AssertIsNotNull("totalBytes"); - totalObjects.AssertIsNotNull("totalObjects"); - metadata.AssertIsNotNull("metadata"); - containers.AssertIsNotNull("containers"); - - this.Name = name; - this.TotalBytesUsed = totalBytes; - this.TotalObjectCount = totalObjects; - this.TotalContainerCount = totalContainers; - this.Containers = containers.ToList(); - this.Metadata = metadata; - } - } -} diff --git a/OpenStack/OpenStack/Storage/StorageAccountPayloadConverter.cs b/OpenStack/OpenStack/Storage/StorageAccountPayloadConverter.cs deleted file mode 100644 index f4c1bba..0000000 --- a/OpenStack/OpenStack/Storage/StorageAccountPayloadConverter.cs +++ /dev/null @@ -1,65 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Linq; -using OpenStack.Common; -using OpenStack.Common.Http; -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Storage -{ - /// - internal class StorageAccountPayloadConverter : IStorageAccountPayloadConverter - { - internal IServiceLocator ServiceLocator; - - /// - /// Creates a new instance of the StorageAccountPayloadConverter class. - /// - /// A service locator that will be used to locate dependent services. - public StorageAccountPayloadConverter(IServiceLocator serviceLocator) - { - serviceLocator.AssertIsNotNull("serviceLocator", "Cannot create a storage account payload converter with a null service locator."); - this.ServiceLocator = serviceLocator; - } - - /// - public StorageAccount Convert(string name, IHttpHeadersAbstraction headers, string payload) - { - name.AssertIsNotNullOrEmpty("name"); - headers.AssertIsNotNull("headers"); - payload.AssertIsNotNull("payload"); - - var containerConverter = this.ServiceLocator.Locate(); - - try - { - var totalBytes = long.Parse(headers["X-Account-Bytes-Used"].First()); - var totalObjects = int.Parse(headers["X-Account-Object-Count"].First()); - var totalContainers = int.Parse(headers["X-Account-Container-Count"].First()); - var containers = containerConverter.Convert(payload); - var metadata = headers.Where(kvp => kvp.Key.StartsWith("X-Account-Meta")).ToDictionary(header => header.Key.Substring(15, header.Key.Length - 15), header => header.Value.First()); - - return new StorageAccount(name, totalBytes, totalObjects, totalContainers, metadata, containers); - } - catch (Exception ex) - { - throw new FormatException(string.Format("Storage Account '{0}' payload could not be parsed.", name), ex); - } - } - } -} diff --git a/OpenStack/OpenStack/Storage/StorageContainer.cs b/OpenStack/OpenStack/Storage/StorageContainer.cs deleted file mode 100644 index cd0174a..0000000 --- a/OpenStack/OpenStack/Storage/StorageContainer.cs +++ /dev/null @@ -1,117 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; -using System.Linq; -using OpenStack.Common; - -namespace OpenStack.Storage -{ - /// - /// Represents a storage container - /// - public class StorageContainer - { - /// - /// Gets the name of the storage container. - /// - public string Name { get; internal set; } - - /// - /// Gets the total number of bytes used in the container. - /// - public long TotalBytesUsed { get; internal set; } - - /// - /// Gets the total number of objects in the container. - /// - public int TotalObjectCount { get; internal set; } - - /// - /// Gets a list of storage objects that are in the container. - /// - public IEnumerable Objects { get; internal set; } - - /// - /// Gets a list of storage folders that are in the container. - /// - public IEnumerable Folders { get; internal set; } - - /// - /// Gets the metadata associated with the storage container. - /// - public IDictionary Metadata { get; internal set; } - - /// - /// Creates a new instance of the StorageContainer class. - /// - /// The name of the storage container. - /// The total number of bytes used in the container. - /// The total number of objects in the container. - /// A list of storage objects that are in the container. - internal StorageContainer(string name, long totalBytes, int totalObjects, IEnumerable objects) : this(name, totalBytes, totalObjects, new Dictionary(), objects) - { - } - - /// - /// Creates a new instance of the StorageContainer class. - /// - /// The name of the storage container. - /// Metadata associated with the storage container. - public StorageContainer(string name, IDictionary metadata) : this(name, 0, 0, metadata, new List()) - { - } - - /// - /// Creates a new instance of the StorageContainer class. - /// - /// The name of the storage container. - /// The total number of bytes used in the container. - /// The total number of objects in the container. - /// A list of storage objects that are in the container. - /// Metadata associated with the storage container. - internal StorageContainer(string name, long totalBytes, int totalObjects, IDictionary metadata, IEnumerable objects) - : this(name, totalBytes,totalObjects, metadata, objects, new List()) - { - } - - /// - /// Creates a new instance of the StorageContainer class. - /// - /// The name of the storage container. - /// The total number of bytes used in the container. - /// The total number of objects in the container. - /// A list of storage objects that are in the container. - /// A list of storage folders that are in the container. - /// Metadata associated with the storage container. - internal StorageContainer(string name, long totalBytes, int totalObjects, IDictionary metadata, IEnumerable objects, IEnumerable folders) - { - name.AssertIsNotNullOrEmpty("name"); - totalBytes.AssertIsNotNull("totalBytes"); - totalObjects.AssertIsNotNull("totalObjects"); - metadata.AssertIsNotNull("metadata"); - objects.AssertIsNotNull("objects"); - folders.AssertIsNotNull("folders"); - - this.Name = name; - this.TotalBytesUsed = totalBytes; - this.TotalObjectCount = totalObjects; - this.Objects = objects.ToList(); - this.Folders = folders.ToList(); - this.Metadata = metadata; - } - } -} diff --git a/OpenStack/OpenStack/Storage/StorageContainerPayloadConverter.cs b/OpenStack/OpenStack/Storage/StorageContainerPayloadConverter.cs deleted file mode 100644 index 76948ce..0000000 --- a/OpenStack/OpenStack/Storage/StorageContainerPayloadConverter.cs +++ /dev/null @@ -1,129 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using Newtonsoft.Json.Linq; -using OpenStack.Common; -using OpenStack.Common.Http; -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Storage -{ - /// - internal class StorageContainerPayloadConverter : IStorageContainerPayloadConverter - { - internal IServiceLocator ServiceLocator; - - /// - /// Creates a new instance of the StorageContainerPayloadConverter class. - /// - /// A service locator to be used to locate/inject dependent services. - public StorageContainerPayloadConverter(IServiceLocator serviceLocator) - { - serviceLocator.AssertIsNotNull("serviceLocator", "Cannot create a storage container payload converter with a null service locator."); - this.ServiceLocator = serviceLocator; - } - - /// - public IEnumerable Convert(string payload) - { - payload.AssertIsNotNull("payload", "A null Storage Container payload cannot be converted."); - - var containers = new List(); - - if (String.IsNullOrEmpty(payload)) - { - return containers; - } - - try - { - var array = JArray.Parse(payload); - containers.AddRange(array.Select(ConvertSingle)); - } - catch (FormatException) - { - throw; - } - catch (Exception ex) - { - throw new FormatException(string.Format("Storage Container payload could not be parsed. Payload: '{0}'", payload), ex); - } - - return containers; - } - - /// - /// Converts a Json token into a storage container. - /// - /// The token. - /// The storage container. - internal StorageContainer ConvertSingle(JToken container) - { - string name = string.Empty; - - try - { - name = (string)container["name"]; - var bytes = (long)container["bytes"]; - var objectCount = (int)container["count"]; - return new StorageContainer(name,bytes, objectCount, new Dictionary(), new List()); - } - catch (Exception ex) - { - var msg = "Storage container payload could not be parsed."; - if (!string.IsNullOrEmpty(name) && container != null) - { - msg = string.Format("Storage Container '{0}' payload could not be parsed. Payload: '{1}'", name, container); - } - else if (container != null) - { - msg = string.Format("Storage Container payload could not be parsed. Payload: '{0}'", container); - } - - throw new FormatException(msg, ex); - } - } - - /// - public StorageContainer Convert(string name, IHttpHeadersAbstraction headers, string payload) - { - name.AssertIsNotNullOrEmpty("name"); - headers.AssertIsNotNull("headers"); - payload.AssertIsNotNull("payload"); - - var objectConverter = this.ServiceLocator.Locate(); - var folderConverter = this.ServiceLocator.Locate(); - - try - { - var totalBytes = long.Parse(headers["X-Container-Bytes-Used"].First()); - var totalObjects = int.Parse(headers["X-Container-Object-Count"].First()); - var metadata = headers.Where(kvp => kvp.Key.StartsWith("X-Container-Meta")).ToDictionary(header => header.Key.Substring(17, header.Key.Length - 17), header => header.Value.First()); - var objects = objectConverter.Convert(name, payload); - var folders = folderConverter.Convert(objects); - - return new StorageContainer(name, totalBytes, totalObjects, metadata, objects, folders); - } - catch (Exception ex) - { - throw new FormatException(string.Format("Storage Container '{0}' payload could not be parsed.", name), ex); - } - } - } -} diff --git a/OpenStack/OpenStack/Storage/StorageFolder.cs b/OpenStack/OpenStack/Storage/StorageFolder.cs deleted file mode 100644 index f57a4fb..0000000 --- a/OpenStack/OpenStack/Storage/StorageFolder.cs +++ /dev/null @@ -1,61 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Collections.Generic; -using System.Linq; -using OpenStack.Common; - -namespace OpenStack.Storage -{ - /// - /// Represents a storage folder on a remote OpenStack instance. - /// - public class StorageFolder : StorageItem - { - /// - /// A collection of sub-folders inside this folder. - /// - public ICollection Folders { get; private set; } - - /// - /// A collection of objects inside this folder. - /// - public ICollection Objects { get; private set; } - - /// - /// Creates a new instance of the StorageFolder class. - /// - /// The full name/path of the folder. - /// A collection of sub-folders that are inside this folder. - public StorageFolder(string fullName, IEnumerable folders) : this(fullName, folders, new List()) - { } - - /// - /// Creates a new instance of the StorageFolder class. - /// - /// The full name/path of the folder. - /// A collection of sub-folders that are inside this folder. - /// A collection of objects that are inside this folder. - public StorageFolder(string fullName, IEnumerable folders, IEnumerable objects ) : base(fullName, "application/directory") - { - folders.AssertIsNotNull("folders", "Cannot create a storage folder with a null folders collection."); - objects.AssertIsNotNull("objects", "Cannot create a storage folder with a null objects collection."); - - this.Folders = folders.ToList(); - this.Objects = objects.ToList(); - } - } -} diff --git a/OpenStack/OpenStack/Storage/StorageFolderPayloadConverter.cs b/OpenStack/OpenStack/Storage/StorageFolderPayloadConverter.cs deleted file mode 100644 index 4316046..0000000 --- a/OpenStack/OpenStack/Storage/StorageFolderPayloadConverter.cs +++ /dev/null @@ -1,162 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text.RegularExpressions; -using Newtonsoft.Json.Linq; -using OpenStack.Common; -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Storage -{ - /// - internal class StorageFolderPayloadConverter : IStorageFolderPayloadConverter - { - internal const string consecutiveSlashRegex = @"/{2,}"; - internal IServiceLocator ServiceLocator; - - /// - /// Creates a new instance of the StorageFolderPayloadConverter class. - /// - /// A service locator to be used to locate/inject dependent services. - public StorageFolderPayloadConverter(IServiceLocator serviceLocator) - { - serviceLocator.AssertIsNotNull("serviceLocator", "Cannot create a storage folder payload converter with a null service locator."); - this.ServiceLocator = serviceLocator; - } - - /// - public IEnumerable Convert(IEnumerable objects) - { - objects.AssertIsNotNull("objects", "Cannot build folders with a null object collection."); - - var folders = new List(); - - var sortedObjectList = objects.OrderByDescending(o => o.Name.Length).ToList(); - - foreach (var obj in sortedObjectList) - { - //if the name has any consecutive slashes in the name, skip it. - if (Regex.IsMatch(obj.FullName, consecutiveSlashRegex)) - { - continue; - } - - //split the input using a forward slash as the folder delimiter, and separate the object name (if we have one) and the folder path. - var folderParts = obj.FullName.TrimStart('/').Split('/'); - var objectName = folderParts.Last(); //this will be string.empty if the object name ends in a "/" indicating that it's a folder. - folderParts = folderParts.Take(folderParts.Length - 1).ToArray(); - - //if there are no folders in the object's name, skip it. - if (folderParts.Count() <= 0) - { - continue; - } - - var currentRoot = folders.FirstOrDefault(f => string.Equals(f.Name, folderParts[0], StringComparison.Ordinal)); - if (currentRoot == null) - { - //if the root folder does not exist, create it. - currentRoot = new StorageFolder(folderParts[0], new List()); - folders.Add(currentRoot); - } - - //go through the rest of the folder path (if any) and add nested folders (if needed). - var currentPath = folderParts[0]; - foreach (var part in folderParts.Skip(1)) - { - currentPath += "/" + part; - var newRoot = currentRoot.Folders.FirstOrDefault(f => string.Equals(f.Name, part, StringComparison.Ordinal)); - if (newRoot == null) - { - newRoot = new StorageFolder(currentPath, new List()); - currentRoot.Folders.Add(newRoot); - } - currentRoot = newRoot; - } - - //if this object is not a folder (e.g. the name does not end in a /), then add this object to the current folder. - if (!string.IsNullOrEmpty(objectName)) - { - currentRoot.Objects.Add(obj); - } - } - return folders; - } - - /// - public StorageFolder Convert(string containerName, string folderName, string payload) - { - if (String.IsNullOrEmpty(payload)) - { - return new StorageFolder(folderName, new List()); - } - - try - { - var array = JArray.Parse(payload); - if (array.Count == 0) - { - throw new InvalidDataException("Folder cannot be converted. The folder does not exist, has no children, and cannot be inferred."); - } - - var subFolders = array.Where(t => t["subdir"] != null); - var rawObjects = array.Where(t => t["subdir"] == null); - - var objectConverter = this.ServiceLocator.Locate(); - - var objects = rawObjects.Select(t => objectConverter.ConvertSingle(t,containerName)).ToList(); - objects.RemoveAll(o => string.Equals(o.FullName, folderName, StringComparison.Ordinal)); - - return new StorageFolder(folderName, subFolders.Select(ParseSubFolder), objects); - - } - catch (FormatException) - { - throw; - } - catch (InvalidDataException) - { - throw; - } - catch (Exception ex) - { - throw new FormatException(string.Format("Storage Container payload could not be parsed. Payload: '{0}'", payload), ex); - } - } - - /// - /// Converts a JToken object into a StorageFolder object. - /// - /// The JToken to convert. - /// A StorageFolder object. - internal StorageFolder ParseSubFolder(JToken token) - { - try - { - var fullName = (string) token["subdir"]; - return new StorageFolder(fullName, new List()); - } - catch (Exception ex) - { - throw new FormatException(string.Format("Storage Folder payload could not be parsed. Payload: '{0}'", token), ex); - } - } - } -} diff --git a/OpenStack/OpenStack/Storage/StorageItem.cs b/OpenStack/OpenStack/Storage/StorageItem.cs deleted file mode 100644 index 7730997..0000000 --- a/OpenStack/OpenStack/Storage/StorageItem.cs +++ /dev/null @@ -1,67 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using OpenStack.Common; -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Storage -{ - public abstract class StorageItem - { - /// - /// The "friendly" name of the folder - /// - public string Name { get; private set; } - - /// - /// The full name/path of the folder. - /// - public string FullName { get; private set; } - - /// - /// Gets the content type of the storage item. - /// - public string ContentType { get; private set; } - - /// - /// Creates a new instance of the StorageItem class. - /// - /// The full name of the item. - /// The content type of the item. - internal StorageItem(string fullName, string contentType) - { - fullName.AssertIsNotNullOrEmpty("fullName"); - contentType.AssertIsNotNull("contentType"); - - this.FullName = fullName; - this.Name = ExtractName(fullName); - this.ContentType = contentType; - } - - /// - /// Extracts the "friendly" name from the items full name. - /// - /// The full name of the item. - /// The "friendly" name of the item. (e.g. "b" if the items full name is "a/b") - internal static string ExtractName(string fullItemName) - { - var fullName = fullItemName.Trim('/'); - var lastIndex = fullName.LastIndexOf('/'); - lastIndex++; - return fullName.Substring(lastIndex, fullName.Length - lastIndex); - } - } -} diff --git a/OpenStack/OpenStack/Storage/StorageItemNameExtractor.cs b/OpenStack/OpenStack/Storage/StorageItemNameExtractor.cs deleted file mode 100644 index d64af56..0000000 --- a/OpenStack/OpenStack/Storage/StorageItemNameExtractor.cs +++ /dev/null @@ -1,44 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -namespace OpenStack.Storage -{ - /// - /// Extracts the "friendly" name of a storage item. - /// - public interface IStorageItemNameExtractor - { - /// - /// Extracts the "friendly" name of a storage item, given the items full name. - /// - /// The items full name. - /// The items friendly name. (e.g. returns 'b' if the items full name is 'a/b') - string ExtractName(string fullName); - } - - /// - internal class StorageItemNameExtractor : IStorageItemNameExtractor - { - /// - public string ExtractName(string fullItemName) - { - var fullName = fullItemName.Trim('/'); - var lastIndex = fullName.LastIndexOf('/'); - lastIndex++; - return fullName.Substring(lastIndex, fullName.Length - lastIndex); - } - } -} diff --git a/OpenStack/OpenStack/Storage/StorageManifest.cs b/OpenStack/OpenStack/Storage/StorageManifest.cs deleted file mode 100644 index 25b22a3..0000000 --- a/OpenStack/OpenStack/Storage/StorageManifest.cs +++ /dev/null @@ -1,65 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; - -namespace OpenStack.Storage -{ - /// - /// Base class for storage manifest objects. - /// - public abstract class StorageManifest : StorageObject - { - /// - /// Creates a new instance of the StorageManifest class. - /// - /// The name of the parent container. - /// The name of the manifest. - internal StorageManifest(string containerName, string manifestName) - : base(manifestName, containerName) - { - } - - /// - /// Creates a new instance of the StorageManifest class. - /// - /// The name of the parent container. - /// The name of the manifest. - /// The related metadata for the manifest. - internal StorageManifest(string containerName, string manifestName,IDictionary metadata ) - : base(manifestName, containerName, metadata) - { - } - - /// - /// Creates a new instance of the StorageManifest class. - /// - /// The name of the parent container. - /// The name of the manifest. - /// The length of the manifest. - /// /// The content type of the manifest. - /// The time that the last modification of the manifest was made. - /// The eTag for the manifest. - /// The related metadata for the manifest. - internal StorageManifest(string fullName, string containerName, DateTime lastModified, string eTag, - long length, string contentType, IDictionary metadata) - : base(fullName, containerName, lastModified, eTag, length, contentType, metadata) - { - - } - } -} diff --git a/OpenStack/OpenStack/Storage/StorageObject.cs b/OpenStack/OpenStack/Storage/StorageObject.cs deleted file mode 100644 index f903c6a..0000000 --- a/OpenStack/OpenStack/Storage/StorageObject.cs +++ /dev/null @@ -1,125 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using OpenStack.Common; - -namespace OpenStack.Storage -{ - /// - /// Represents a storage object. - /// - public class StorageObject : StorageItem - { - /// - /// Gets the name of the parent storage container for the storage item. - /// - public string ContainerName { get; private set; } - - /// - /// Gets the last modified data for the storage item. - /// - public DateTime LastModified { get; private set; } - - /// - /// Gets the ETag for the storage item. - /// - public string ETag { get; private set; } - - /// - /// Gets the length/size of the storage item. - /// - public long Length { get; private set; } - - /// - /// Gets the metadata associated with the storage item. - /// - public IDictionary Metadata { get; private set; } - - /// - /// Creates a new instance of the StorageObject class. - /// - /// The name of the storage object. - /// The name of the parent storage container for the storage object. - /// The content type of the storage object. - /// The metadata associated with the storage object. - public StorageObject(string name, string containerName, string contentType, IDictionary metadata) - : this(name, containerName, DateTime.UtcNow, string.Empty, 0, contentType, metadata) - { - } - - /// - /// Creates a new instance of the StorageObject class. - /// - /// The name of the storage object. - /// The name of the parent storage container for the storage object. - public StorageObject(string name, string containerName) - : this(name, containerName, DateTime.UtcNow, string.Empty, 0, string.Empty, new Dictionary()) - { - } - - /// - /// Creates a new instance of the StorageObject class. - /// - /// The name of the storage object. - /// The name of the parent storage container for the storage object. - /// The metadata associated with the storage object. - public StorageObject(string name, string containerName, IDictionary metadata ) - : this(name, containerName, DateTime.UtcNow, string.Empty, 0, string.Empty, metadata) - { - } - - /// - /// Creates a new instance of the StorageObject class. - /// - /// The name of the storage object. - /// The name of the parent storage container for the storage object. - /// The last modified data for the storage object. - /// The ETag for the storage object. - /// The length/size of the storage object. - /// The content type of the storage object. - internal StorageObject(string name, string containerName, DateTime lastModified, string eTag, long length, string contentType) - : this(name, containerName, lastModified, eTag, length, contentType, new Dictionary()) - { - } - - /// - /// Creates a new instance of the StorageObject class. - /// - /// The full name of the storage object. - /// The name of the parent storage container for the storage object. - /// The last modified data for the storage object. - /// The ETag for the storage object. - /// The length/size of the storage object. - /// The content type of the storage object. - /// The metadata associated with the storage object. - internal StorageObject(string fullName, string containerName, DateTime lastModified, string eTag, long length, string contentType, IDictionary metadata) : base(fullName, contentType) - { - containerName.AssertIsNotNullOrEmpty("containerName"); - lastModified.AssertIsNotNull("lastModified"); - eTag.AssertIsNotNull("eTag"); - length.AssertIsNotNull("length"); - metadata.AssertIsNotNull("metadata"); - - this.ContainerName = containerName; - this.LastModified = lastModified; - this.ETag = eTag; - this.Length = length; - this.Metadata = metadata; - } - } -} diff --git a/OpenStack/OpenStack/Storage/StorageObjectPayloadConverter.cs b/OpenStack/OpenStack/Storage/StorageObjectPayloadConverter.cs deleted file mode 100644 index 7849bf9..0000000 --- a/OpenStack/OpenStack/Storage/StorageObjectPayloadConverter.cs +++ /dev/null @@ -1,169 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using Newtonsoft.Json.Linq; -using OpenStack.Common; -using OpenStack.Common.Http; - -namespace OpenStack.Storage -{ - /// - internal class StorageObjectPayloadConverter : IStorageObjectPayloadConverter - { - /// - public IEnumerable Convert(string containerName, string payload) - { - payload.AssertIsNotNull("payload", "A null Storage Container payload cannot be converted."); - - var objects = new List(); - - if (String.IsNullOrEmpty(payload)) - { - return objects; - } - - try - { - var array = JArray.Parse(payload); - objects.AddRange(array.Select(t => ConvertSingle(t, containerName))); - } - catch (FormatException) - { - throw; - } - catch (Exception ex) - { - throw new FormatException(string.Format("Storage Object payload could not be parsed. Payload: '{0}'", payload), ex); - } - - return objects; - } - - /// - public string Convert(IEnumerable objects) - { - objects.AssertIsNotNull("objects","Cannot convert a null storage object collection to Json."); - - var objectsPayload = new JArray(); - foreach (var obj in objects) - { - dynamic item = new System.Dynamic.ExpandoObject(); - item.path = string.Format("{0}/{1}",obj.ContainerName, obj.FullName); - item.size_bytes = obj.Length; - item.etag = obj.ETag; - - objectsPayload.Add(JToken.FromObject(item)); - } - - return objectsPayload.ToString(); - } - - /// - public StorageObject ConvertSingle(JToken obj, string containerName) - { - string name = string.Empty; - - try - { - name = (string)obj["name"]; - var bytes = (long)obj["bytes"]; - var contentType = (string)obj["content_type"]; - var lastModified = (DateTime)obj["last_modified"]; - var etag = (string)obj["hash"]; - return new StorageObject(name, containerName, lastModified, etag, bytes, contentType); - } - catch (Exception ex) - { - var msg = "Storage Object payload could not be parsed."; - if (!string.IsNullOrEmpty(name) && obj != null) - { - msg = string.Format("Storage Object '{0}' payload could not be parsed. Payload: '{1}'", name, obj); - } - else if(obj != null) - { - msg = string.Format("Storage Object payload could not be parsed. Payload: '{0}'", obj); - } - - throw new FormatException(msg, ex); - } - } - - /// - public StorageObject Convert(string containerName, string objectName, IHttpHeadersAbstraction headers, long? objectLength = null) - { - containerName.AssertIsNotNullOrEmpty("containerName"); - objectName.AssertIsNotNullOrEmpty("objectName"); - headers.AssertIsNotNull("headers"); - - try - { - var lastModified = DateTime.Parse(headers["Last-Modified"].First()); - var eTag = headers["ETag"].First(); - var length = long.Parse(headers["Content-Length"].First()); - if (objectLength.HasValue) - { - length = objectLength.Value; - } - var contentType = headers["Content-Type"].First(); - var metadata = headers.Where(kvp => kvp.Key.StartsWith("X-Object-Meta")).ToDictionary(header => header.Key.Substring(14, header.Key.Length - 14), header => header.Value.First()); - - return CreateStorageObject(objectName, containerName, lastModified, eTag, length, contentType, metadata, headers); - } - catch (Exception ex) - { - throw new FormatException(string.Format("Storage object '{0}' could not be parsed.", objectName), ex); - } - } - - /// - /// Creates the appropriate storage object based on the given parameters. - /// - /// the name of the object. - /// The name of the parent container. - /// The last modified date of the object. - /// The eTag for the object. - /// The length of the object. - /// The content type of the object. - /// The associated metadata for the object. - /// The http headers from the object request. - /// An instance of the StorageObject class. - internal StorageObject CreateStorageObject(string objectName, string containerName, DateTime lastModified, string eTag, long length, string contentType, IDictionary metadata, IHttpHeadersAbstraction headers) - { - IEnumerable values; - if (headers.TryGetValue("X-Static-Large-Object", out values)) - { - if (values.Any(v => string.Equals(v, "true", StringComparison.OrdinalIgnoreCase))) - { - return new StaticLargeObjectManifest(objectName, containerName, lastModified, eTag, length, contentType, metadata); - } - } - - if (headers.TryGetValue("X-Object-Manifest", out values)) - { - var segPath = values.FirstOrDefault(v => !string.IsNullOrEmpty(v)); - if (!string.IsNullOrEmpty(segPath)) - { - return new DynamicLargeObjectManifest(objectName, containerName, lastModified, eTag, length, contentType, metadata, segPath); - } - } - - return new StorageObject(objectName, containerName, lastModified, eTag, length, contentType, metadata); - } - } -} diff --git a/OpenStack/OpenStack/Storage/StorageServiceClient.cs b/OpenStack/OpenStack/Storage/StorageServiceClient.cs deleted file mode 100644 index 2b2a38d..0000000 --- a/OpenStack/OpenStack/Storage/StorageServiceClient.cs +++ /dev/null @@ -1,344 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Threading; -using System.Threading.Tasks; -using OpenStack.Common; -using OpenStack.Common.ServiceLocation; -using OpenStack.Identity; - -namespace OpenStack.Storage -{ - /// - internal class StorageServiceClient : IStorageServiceClient - { - internal ServiceClientContext Context; - internal IServiceLocator ServiceLocator; - - /// - public long LargeObjectThreshold { get; set; } - - /// - public int LargeObjectSegments { get; set; } - - /// - public string LargeObjectSegmentContainer { get; set; } - - /// - /// Creates a new instance of the StorageServiceClient class. - /// - /// The credential to be used by this client. - /// The cancellation token to be used by this client. - /// A service locator to be used to locate/inject dependent services. - public StorageServiceClient(IOpenStackCredential credentials, string serviceName, CancellationToken token, IServiceLocator serviceLocator) - { - serviceLocator.AssertIsNotNull("serviceLocator", "Cannot create a storage service client with a null service locator."); - - this.LargeObjectThreshold = 524288000; //Set the default large file threshold to 500MB. - this.LargeObjectSegments = 10; //set the default number of segments for large objects to 10. - this.LargeObjectSegmentContainer = "LargeObjectSegments"; //set the default name of the container that will hold segments to 'LargeObjectSegments'; - - this.ServiceLocator = serviceLocator; - var endpoint = new Uri(credentials.ServiceCatalog.GetPublicEndpoint(serviceName, credentials.Region)); - this.Context = new ServiceClientContext(credentials, token, serviceName, endpoint); - } - - /// - public async Task GetStorageAccount() - { - var client = this.GetPocoClient(); - return await client.GetStorageAccount(); - } - - /// - public async Task CreateStorageObject(string containerName, string objectName, IDictionary metadata, Stream content) - { - containerName.AssertIsNotNullOrEmpty("containerName", "Cannot create a storage object with a container name that is null or empty."); - objectName.AssertIsNotNullOrEmpty("objectName", "Cannot create a storage object with a name that is null or empty."); - content.AssertIsNotNull("content", "Cannot create a storage object with null content"); - - if (content.Length > this.LargeObjectThreshold) - { - return await this.CreateLargeStorageObject(containerName, objectName, metadata, content, this.LargeObjectSegments); - } - - //TODO: handle the content type better... - var requestObject = new StorageObject(objectName, containerName, "application/octet-stream", metadata); - var client = this.GetPocoClient(); - return await client.CreateStorageObject(requestObject, content); - } - - /// - public async Task CopyStorageObject(string containerName, string objectName, string destinationContainerName, string destinationObjectName = null) - { - containerName.AssertIsNotNullOrEmpty("containerName", "Cannot copy a storage object with a container name that is null or empty."); - objectName.AssertIsNotNullOrEmpty("objectName", "Cannot copy a storage object with a name that is null or empty."); - destinationContainerName.AssertIsNotNullOrEmpty("destinationContainerName", "Cannot copy a storage object with null or empty destination container."); - - var requestObject = new StorageObject(objectName, containerName); - var client = this.GetPocoClient(); - return await client.CopyStorageObject(requestObject, destinationContainerName, destinationObjectName); - } - - /// - public async Task CreateStorageContainer(string containerName, IDictionary metadata) - { - containerName.AssertIsNotNullOrEmpty("containerName", "Cannot create a storage container with a container name that is null or empty."); - - var requestObject = new StorageContainer(containerName, metadata); - var client = this.GetPocoClient(); - await client.CreateStorageContainer(requestObject); - } - - /// - public async Task GetStorageObject(string containerName, string objectName) - { - containerName.AssertIsNotNullOrEmpty("containerName", "Cannot get a storage object with a container name that is null or empty."); - objectName.AssertIsNotNullOrEmpty("objectName", "Cannot get a storage object with a name that is null or empty."); - - var client = this.GetPocoClient(); - return await client.GetStorageObject(containerName, objectName); - } - - /// - public async Task DownloadStorageObject(string containerName, string objectName, Stream outputStream) - { - containerName.AssertIsNotNullOrEmpty("containerName", "download create a storage object with a container name that is null or empty."); - objectName.AssertIsNotNullOrEmpty("objectName", "Cannot download a storage object with a name that is null or empty."); - outputStream.AssertIsNotNull("outputStream", "Cannot download a storage object with a null output stream."); - - var client = this.GetPocoClient(); - return await client.DownloadStorageObject(containerName, objectName, outputStream); - } - - /// - public async Task DeleteStorageObject(string containerName, string objectName) - { - containerName.AssertIsNotNullOrEmpty("containerName", "Cannot delete a storage object with a container name that is null or empty."); - objectName.AssertIsNotNullOrEmpty("objectName", "Cannot delete a storage object with a name that is null or empty."); - - var client = this.GetPocoClient(); - await client.DeleteStorageObject(containerName, objectName); - } - - /// - public async Task UpdateStorageObject(StorageObject obj) - { - obj.AssertIsNotNull("container", "Cannot update a storage object with a null object."); - - var client = this.GetPocoClient(); - await client.UpdateStorageObject(obj); - } - - /// - public async Task CreateStorageManifest(string containerName, string manifestName, IDictionary metadata, IEnumerable objects) - { - containerName.AssertIsNotNullOrEmpty("containerName", "Cannot create a storage manifest with a container name that is null or empty."); - manifestName.AssertIsNotNullOrEmpty("manifestNamee", "Cannot create a storage manifest with a name that is null or empty."); - metadata.AssertIsNotNull("metadata","Cannot create a storage manifest with null metadata."); - - var client = this.GetPocoClient(); - - var manifest = new StaticLargeObjectManifest(containerName, manifestName, metadata, objects.ToList()); - - return await client.CreateStorageManifest(manifest); - } - - /// - public async Task CreateStorageManifest(string containerName, string manifestName, IDictionary metadata, string segmentsPath) - { - containerName.AssertIsNotNullOrEmpty("containerName", "Cannot create a storage manifest with a container name that is null or empty."); - manifestName.AssertIsNotNullOrEmpty("manifestNamee", "Cannot create a storage manifest with a name that is null or empty."); - metadata.AssertIsNotNull("metadata", "Cannot create a storage manifest with null metadata."); - segmentsPath.AssertIsNotNullOrEmpty("segmentsPath", "Cannot create storage manifest with a null or empty segments path."); - - var client = this.GetPocoClient(); - - var manifest = new DynamicLargeObjectManifest(containerName, manifestName, metadata, segmentsPath); - - return await client.CreateStorageManifest(manifest); - } - - /// - public async Task GetStorageManifest(string containerName, string manifestName) - { - containerName.AssertIsNotNullOrEmpty("containerName", "Cannot get a storage manifest with a container name that is null or empty."); - manifestName.AssertIsNotNullOrEmpty("manifestName", "Cannot get a storage manifest with a name that is null or empty."); - - var client = this.GetPocoClient(); - return await client.GetStorageManifest(containerName, manifestName); - } - - /// - public async Task GetStorageFolder(string containerName, string folderName) - { - containerName.AssertIsNotNullOrEmpty("containerName", "Cannot get a storage folder with a container name that is null or empty."); - folderName.AssertIsNotNullOrEmpty("folderName", "Cannot get a storage folder with a name that is null or empty."); - - folderName = EnsureTrailingSlashOnFolderName(folderName); - - var client = this.GetPocoClient(); - return await client.GetStorageFolder(containerName, folderName); - } - - /// - public async Task CreateStorageFolder(string containerName, string folderName) - { - containerName.AssertIsNotNullOrEmpty("containerName", "Cannot create a storage folder with a container name that is null or empty."); - folderName.AssertIsNotNullOrEmpty("folderName", "Cannot create a storage folder with a name that is null or empty."); - - folderName = EnsureTrailingSlashOnFolderName(folderName); - var validator = this.ServiceLocator.Locate(); - if (!validator.Validate(folderName)) - { - throw new ArgumentException(string.Format("Folder name '{0}' is invalid. Folder names cannot includes consecutive slashes.", folderName), "folderName"); - } - - var client = this.GetPocoClient(); - await client.CreateStorageFolder(containerName, folderName); - } - - /// - public async Task DeleteStorageFolder(string containerName, string folderName) - { - containerName.AssertIsNotNullOrEmpty("containerName", "Cannot delete a storage folder with a container name that is null or empty."); - folderName.AssertIsNotNullOrEmpty("folderName", "Cannot delete a storage folder with a name that is null or empty."); - - folderName = EnsureTrailingSlashOnFolderName(folderName); - - var client = this.GetPocoClient(); - await client.DeleteStorageFolder(containerName, folderName); - } - - /// - public async Task GetStorageContainer(string containerName) - { - containerName.AssertIsNotNullOrEmpty("containerName", "Cannot get a storage container with a container name that is null or empty."); - - var client = this.GetPocoClient(); - return await client.GetStorageContainer(containerName); - } - - /// - public async Task DeleteStorageContainer(string containerName) - { - containerName.AssertIsNotNullOrEmpty("containerName", "Cannot delete a storage container with a container name that is null or empty."); - - var client = this.GetPocoClient(); - await client.DeleteStorageContainer(containerName); - } - - /// - public async Task UpdateStorageContainer(StorageContainer container) - { - container.AssertIsNotNull("container", "Cannot update a storage container with a null container."); - - var client = this.GetPocoClient(); - await client.UpdateStorageContainer(container); - } - - /// - public async Task> ListStorageObjects(string containerName) - { - containerName.AssertIsNotNullOrEmpty("containerName", "Cannot list storage objects with a container name that is null or empty."); - - var objects = new List(); - var client = this.GetPocoClient(); - - var container = await client.GetStorageContainer(containerName); - foreach (var storageObject in container.Objects) - { - try - { - var obj = await client.GetStorageObject(containerName, storageObject.FullName); - objects.Add(obj); - } - catch (InvalidOperationException ex) - { - //TODO: think about a better way to bubble up non-fatal errors like a 404. - if (!ex.Message.Contains(HttpStatusCode.NotFound.ToString())) - { - throw; - } - } - - } - - return objects; - } - - /// - public async Task> ListStorageContainers() - { - var contianers = new List(); - var client = this.GetPocoClient(); - - var account = await client.GetStorageAccount(); - foreach (var storageContainer in account.Containers) - { - contianers.Add(await client.GetStorageContainer(storageContainer.Name)); - } - - return contianers; - } - - /// - public async Task CreateLargeStorageObject(string containerName, string objectName, IDictionary metadata, Stream content, int numberOfSegments) - { - containerName.AssertIsNotNullOrEmpty("containerName", "Cannot create a large storage object with a null or empty container name."); - objectName.AssertIsNotNullOrEmpty("objectName", "Cannot create a large storage object with a null or empty name."); - metadata.AssertIsNotNull("metadata", "Cannot create a large storage object with null metadata."); - content.AssertIsNotNull("content", "Cannot create a large storage object with null content."); - - if (numberOfSegments <= 0) - { - throw new ArgumentException("Cannot create a large object with zero or less segments.", "numberOfSegments"); - } - - var factory = this.ServiceLocator.Locate(); - var creator = factory.Create(this); - return await creator.Create(containerName, objectName, metadata, content, numberOfSegments, this.LargeObjectSegmentContainer); - } - - /// - /// Gets a client to interact with the remote OpenStack instance. - /// - /// A POCO client. - internal IStorageServicePocoClient GetPocoClient() - { - return this.ServiceLocator.Locate().Create(this.Context, this.ServiceLocator); - } - - /// - /// Ensures that a folder name has a single trailing slash on the end. - /// - /// The folder name. - /// The folder name with a slash on the end. - internal string EnsureTrailingSlashOnFolderName(string folderName) - { - if (!folderName.EndsWith("/")) - { - folderName += "/"; - } - return folderName; - } - } -} diff --git a/OpenStack/OpenStack/Storage/StorageServiceClientDefinition.cs b/OpenStack/OpenStack/Storage/StorageServiceClientDefinition.cs deleted file mode 100644 index d3a010c..0000000 --- a/OpenStack/OpenStack/Storage/StorageServiceClientDefinition.cs +++ /dev/null @@ -1,80 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using OpenStack.Common.ServiceLocation; -using OpenStack.Identity; - -namespace OpenStack.Storage -{ - /// - internal class StorageServiceClientDefinition : IOpenStackServiceClientDefinition - { - internal const string DefaultStorageServiceName = "Swift"; - - /// - public string Name { get; private set; } - - /// - /// Creates a new instance of the StorageServiceClientDefinition class. - /// - public StorageServiceClientDefinition() - { - this.Name = typeof (StorageServiceClient).Name; - } - - /// - public IOpenStackServiceClient Create(ICredential credential, string serviceName, CancellationToken cancellationToken, IServiceLocator serviceLocator) - { - return new StorageServiceClient((IOpenStackCredential)credential, GetServiceName(serviceName), cancellationToken, serviceLocator); - } - - /// - public IEnumerable ListSupportedVersions() - { - return new List() { "1.0", "1" }; - } - - /// - public bool IsSupported(ICredential credential, string serviceName) - { - if (credential == null || credential.ServiceCatalog == null) - { - return false; - } - - var catalog = credential.ServiceCatalog; - return - catalog.Any( - s => - string.Equals(s.Name, GetServiceName(serviceName), StringComparison.OrdinalIgnoreCase) && - s.Endpoints.Any(e => this.ListSupportedVersions().Contains(e.Version) || e.PublicUri.Contains("/v1"))); - } - - /// - /// Gets the service name to use. - /// - /// The given service name. - /// The given service name if it is not empty or null, otherwise the default service name will be returned. - internal string GetServiceName(string serviceName) - { - return string.IsNullOrEmpty(serviceName) ? DefaultStorageServiceName : serviceName; - } - } -} diff --git a/OpenStack/OpenStack/Storage/StorageServicePocoClient.cs b/OpenStack/OpenStack/Storage/StorageServicePocoClient.cs deleted file mode 100644 index ea956a7..0000000 --- a/OpenStack/OpenStack/Storage/StorageServicePocoClient.cs +++ /dev/null @@ -1,396 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Threading.Tasks; -using OpenStack.Common; -using OpenStack.Common.Http; -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Storage -{ - /// - internal class StorageServicePocoClient : IStorageServicePocoClient - { - internal ServiceClientContext _context; - internal IServiceLocator ServiceLocator; - - /// - /// Creates a new instance of the StorageServicePocoClient class. - /// - /// The storage service to use for this client. - /// A service locator to be used to locate/inject dependent services. - internal StorageServicePocoClient(ServiceClientContext context, IServiceLocator serviceLocator) - { - serviceLocator.AssertIsNotNull("serviceLocator", "Cannot create a storage service poco client with a null service locator."); - - this._context = context; - this.ServiceLocator = serviceLocator; - } - - /// - public async Task CreateStorageObject(StorageObject obj, Stream content) - { - obj.AssertIsNotNull("obj", "Cannot create a null storage object."); - obj.ContainerName.AssertIsNotNullOrEmpty("obj.ContainerName", "Cannot create a storage object with a null or empty container name."); - obj.Name.AssertIsNotNullOrEmpty("obj.Name","Cannot create a storage object without a name."); - - var contentLength = content.Length; - var client = this.GetRestClient(); - var resp = await client.CreateObject(obj.ContainerName, obj.FullName, obj.Metadata, content); - - if (resp.StatusCode != HttpStatusCode.Created) - { - throw new InvalidOperationException(string.Format("Failed to create storage object '{0}'. The remote server returned the following status code: '{1}'.", obj.Name, resp.StatusCode)); - } - - var converter = this.ServiceLocator.Locate(); - var respObj = converter.Convert(obj.ContainerName, obj.FullName, resp.Headers, contentLength); - - return respObj; - } - - /// - public async Task CopyStorageObject(StorageObject obj, string destinationContainerName, string destinationObjectName = null) - { - obj.AssertIsNotNull("obj", "Cannot create a null storage object."); - obj.ContainerName.AssertIsNotNullOrEmpty("obj.ContainerName", "Cannot copy a storage object with a null or empty container name."); - obj.Name.AssertIsNotNullOrEmpty("obj.Name", "Cannot copy a storage object without a name."); - destinationContainerName.AssertIsNotNullOrEmpty("destinationContainerName", "Cannot copy a storage object to a null or empty destination container name."); - - string localDestinationObjectName = null; - - if(!string.IsNullOrEmpty(destinationObjectName)) - { - localDestinationObjectName = destinationObjectName; - } - else - { - localDestinationObjectName = obj.FullName; - } - - var client = this.GetRestClient(); - var resp = await client.CopyObject(obj.ContainerName, obj.FullName, destinationContainerName, localDestinationObjectName); - - if (resp.StatusCode != HttpStatusCode.Created) - { - throw new InvalidOperationException(string.Format("Failed to copy storage object '{0}'. The remote server returned the following status code: '{1}'.", obj.Name, resp.StatusCode)); - } - - var converter = this.ServiceLocator.Locate(); - var respObj = converter.Convert(obj.ContainerName, obj.FullName, resp.Headers); - - return respObj; - } - - public async Task CreateStorageManifest(StorageManifest manifest) - { - manifest.AssertIsNotNull("manifest", "Cannot create a null storage manifest."); - manifest.ContainerName.AssertIsNotNullOrEmpty("manifest.ContainerName", "Cannot create a storage manifest with a null or empty container name."); - manifest.Name.AssertIsNotNullOrEmpty("manifest.Name", "Cannot create a storage manifest without a name."); - - var client = this.GetRestClient(); - IHttpResponseAbstraction resp; - - var dynamicManifest = manifest as DynamicLargeObjectManifest; - var staticManifest = manifest as StaticLargeObjectManifest; - - if (dynamicManifest == null && staticManifest == null) - { - throw new InvalidOperationException(string.Format("Failed to create storage manifest '{0}'. The given manifest type is not supported: '{1}'.", manifest.Name, manifest.GetType().Name)); - } - - if (dynamicManifest != null) //dynamic large object manifest - { - resp = await client.CreateDynamicManifest(dynamicManifest.ContainerName, dynamicManifest.FullName, dynamicManifest.Metadata, dynamicManifest.SegmentsPath); - } - else //static large object manifest - { - var converter = this.ServiceLocator.Locate(); - var manifestPayload = converter.Convert(staticManifest.Objects).ConvertToStream(); - - resp = await client.CreateStaticManifest(staticManifest.ContainerName, staticManifest.FullName, staticManifest.Metadata, manifestPayload); - } - - if (resp.StatusCode != HttpStatusCode.Created) - { - throw new InvalidOperationException(string.Format("Failed to create storage manifest '{0}'. The remote server returned the following status code: '{1}'.", manifest.Name, resp.StatusCode)); - } - - return await this.GetStorageManifest(manifest.ContainerName, manifest.FullName); - } - - /// - public async Task CreateStorageContainer(StorageContainer container) - { - container.AssertIsNotNull("container", "Cannot Create a null storage container."); - container.Name.AssertIsNotNullOrEmpty("container.Name", "Cannot create a storage container without a name."); - - var client = this.GetRestClient(); - var resp = await client.CreateContainer(container.Name, container.Metadata); - - if (resp.StatusCode != HttpStatusCode.Created && resp.StatusCode != HttpStatusCode.NoContent) - { - throw new InvalidOperationException(string.Format("Failed to create storage container '{0}'. The remote server returned the following status code: '{1}'.", container.Name, resp.StatusCode)); - } - } - - /// - public async Task GetStorageAccount() - { - var client = this.GetRestClient(); - var resp = await client.GetAccount(); - - if (resp.StatusCode != HttpStatusCode.OK && resp.StatusCode != HttpStatusCode.NoContent) - { - throw new InvalidOperationException(string.Format("Failed to get storage account. The remote server returned the following status code: '{0}'.", resp.StatusCode)); - } - - var accountName = _context.PublicEndpoint.Segments.Last().TrimEnd('/'); - - var converter = this.ServiceLocator.Locate(); - var account = converter.Convert(accountName, resp.Headers, await resp.ReadContentAsStringAsync()); - - return account; - } - - /// - public async Task GetStorageContainer(string containerName) - { - containerName.AssertIsNotNullOrEmpty("containerName", "Cannot get a storage container with a name that is null or empty."); - - var client = this.GetRestClient(); - var resp = await client.GetContainer(containerName); - - if (resp.StatusCode != HttpStatusCode.OK && resp.StatusCode != HttpStatusCode.NoContent) - { - throw new InvalidOperationException(string.Format("Failed to get storage container '{0}'. The remote server returned the following status code: '{1}'.", containerName, resp.StatusCode)); - } - - var converter = this.ServiceLocator.Locate(); - var container = converter.Convert(containerName, resp.Headers, await resp.ReadContentAsStringAsync()); - - return container; - } - - /// - public async Task GetStorageObject(string containerName, string objectName) - { - containerName.AssertIsNotNullOrEmpty("containerName", "Cannot get a storage object with a container name that is null or empty."); - objectName.AssertIsNotNullOrEmpty("objectName", "Cannot get a storage object with a name that is null or empty."); - - var client = this.GetRestClient(); - var resp = await client.GetObjectMetadata(containerName, objectName); - - if (resp.StatusCode != HttpStatusCode.OK && resp.StatusCode != HttpStatusCode.NoContent) - { - throw new InvalidOperationException(string.Format("Failed to get storage object '{0}'. The remote server returned the following status code: '{1}'.", objectName, resp.StatusCode)); - } - - var converter = this.ServiceLocator.Locate(); - var obj = converter.Convert(containerName, objectName, resp.Headers); - - return obj; - } - - public async Task GetStorageManifest(string containerName, string manifestName) - { - containerName.AssertIsNotNullOrEmpty("containerName", "Cannot get a storage manifest with a container name that is null or empty."); - manifestName.AssertIsNotNullOrEmpty("manifestName", "Cannot get a storage manifest with a name that is null or empty."); - - var client = this.GetRestClient(); - var resp = await client.GetManifestMetadata(containerName, manifestName); - - if (resp.StatusCode != HttpStatusCode.OK && resp.StatusCode != HttpStatusCode.NoContent) - { - throw new InvalidOperationException(string.Format("Failed to get storage manifest '{0}'. The remote server returned the following status code: '{1}'.", manifestName, resp.StatusCode)); - } - - var objectConverter = this.ServiceLocator.Locate(); - var obj = objectConverter.Convert(containerName, manifestName, resp.Headers); - - if (!(obj is StorageManifest)) - { - throw new InvalidOperationException(string.Format("Failed to get storage manifest '{0}'. The requested object is not a manifest.", manifestName)); - } - - if (obj is StaticLargeObjectManifest) - { - var manifest = obj as StaticLargeObjectManifest; - manifest.Objects = objectConverter.Convert(containerName, await resp.ReadContentAsStringAsync()).ToList(); - } - - return obj as StorageManifest; - } - - /// - public async Task DownloadStorageObject(string containerName, string objectName, Stream outputStream) - { - containerName.AssertIsNotNullOrEmpty("containerName", "Cannot download a storage object with a container name that is null or empty."); - objectName.AssertIsNotNullOrEmpty("objectName", "Cannot download a storage object with a name that is null or empty."); - outputStream.AssertIsNotNull("outputStream","Cannot download a storage object with a null output stream."); - - var client = this.GetRestClient(); - var resp = await client.GetObject(containerName, objectName); - - if (resp.StatusCode != HttpStatusCode.OK) - { - throw new InvalidOperationException(string.Format("Failed to download storage object '{0}'. The remote server returned the following status code: '{1}'.", objectName, resp.StatusCode)); - } - - var converter = this.ServiceLocator.Locate(); - var obj = converter.Convert(containerName, objectName, resp.Headers); - - await resp.Content.CopyAsync(outputStream); - outputStream.Position = 0; - - return obj; - } - - /// - public async Task DeleteStorageObject(string containerName, string itemName) - { - containerName.AssertIsNotNullOrEmpty("containerName", "Cannot delete a storage object with a container name that is null or empty."); - itemName.AssertIsNotNullOrEmpty("objectName", "Cannot delete a storage object with a name that is null or empty."); - - var client = this.GetRestClient(); - var resp = await client.DeleteObject(containerName, itemName); - - if (resp.StatusCode != HttpStatusCode.OK && resp.StatusCode != HttpStatusCode.NoContent) - { - throw new InvalidOperationException(string.Format("Failed to delete storage object '{0}'. The remote server returned the following status code: '{1}'.", itemName, resp.StatusCode)); - } - } - - /// - public async Task DeleteStorageContainer(string containerName) - { - containerName.AssertIsNotNullOrEmpty("containerName", "Cannot delete a storage container with a container name that is null or empty."); - - var client = this.GetRestClient(); - var resp = await client.DeleteContainer(containerName); - - if (resp.StatusCode != HttpStatusCode.OK && resp.StatusCode != HttpStatusCode.NoContent) - { - throw new InvalidOperationException(string.Format("Failed to delete storage container '{0}'. The remote server returned the following status code: '{1}'.", containerName, resp.StatusCode)); - } - } - - /// - public async Task UpdateStorageContainer(StorageContainer container) - { - container.Name.AssertIsNotNullOrEmpty("container.Name", "Cannot update a storage container with a name that is null or empty."); - - var client = this.GetRestClient(); - var resp = await client.UpdateContainer(container.Name, container.Metadata); - - if (resp.StatusCode != HttpStatusCode.NoContent) - { - throw new InvalidOperationException(string.Format("Failed to update storage container '{0}'. The remote server returned the following status code: '{1}'.", container.Name, resp.StatusCode)); - } - } - - /// - public async Task UpdateStorageObject(StorageObject item) - { - item.ContainerName.AssertIsNotNullOrEmpty("containerName", "Cannot update a storage object with a container name that is null or empty."); - item.Name.AssertIsNotNullOrEmpty("objectName", "Cannot update a storage object with a name that is null or empty."); - - var client = this.GetRestClient(); - var resp = await client.UpdateObject(item.ContainerName, item.Name, item.Metadata); - - if (resp.StatusCode != HttpStatusCode.Accepted) - { - throw new InvalidOperationException(string.Format("Failed to update storage object '{0}'. The remote server returned the following status code: '{1}'.", item.Name, resp.StatusCode)); - } - } - - /// - public async Task GetStorageFolder(string containerName, string folderName) - { - containerName.AssertIsNotNullOrEmpty("containerName", "Cannot get a storage folder with a container name that is null or empty."); - folderName.AssertIsNotNullOrEmpty("folderName", "Cannot get a storage folder with a folder name that is null or empty."); - - var client = this.GetRestClient(); - var resp = await client.GetFolder(containerName, folderName); - - if (resp.StatusCode != HttpStatusCode.OK && resp.StatusCode != HttpStatusCode.NoContent) - { - throw new InvalidOperationException(string.Format("Failed to get storage folder '{0}'. The remote server returned the following status code: '{1}'.", folderName, resp.StatusCode)); - } - - try - { - var converter = this.ServiceLocator.Locate(); - var folder = converter.Convert(containerName, folderName, await resp.ReadContentAsStringAsync()); - return folder; - } - catch (InvalidDataException) - { - throw new InvalidOperationException(string.Format("Failed to get storage folder '{0}'. The requested folder could not be found.", folderName)); - } - } - - /// - public async Task CreateStorageFolder(string containerName, string folderName) - { - containerName.AssertIsNotNullOrEmpty("containerName", "Cannot create a storage folder with a container name that is null or empty."); - folderName.AssertIsNotNullOrEmpty("folderName", "Cannot create a storage folder with a folder name that is null or empty."); - - var client = this.GetRestClient(); - var resp = await client.CreateObject(containerName, folderName, new Dictionary(), new MemoryStream()); - - if (resp.StatusCode != HttpStatusCode.Created) - { - throw new InvalidOperationException(string.Format("Failed to create storage folder '{0}'. The remote server returned the following status code: '{1}'.", folderName, resp.StatusCode)); - } - } - - /// - public async Task DeleteStorageFolder(string containerName, string folderName) - { - containerName.AssertIsNotNullOrEmpty("containerName", "Cannot delete a storage object with a container name that is null or empty."); - folderName.AssertIsNotNullOrEmpty("objectName", "Cannot delete a storage object with a name that is null or empty."); - - var folder = await this.GetStorageFolder(containerName, folderName); - if (folder.Folders.Count > 0 || folder.Objects.Count > 0) - { - throw new InvalidOperationException(string.Format("Failed to delete storage folder '{0}'. The folder is not empty and cannot be deleted.", folderName)); - } - - var client = this.GetRestClient(); - var resp = await client.DeleteObject(containerName, folderName); - - if (resp.StatusCode != HttpStatusCode.OK && resp.StatusCode != HttpStatusCode.NoContent) - { - throw new InvalidOperationException(string.Format("Failed to delete storage folder '{0}'. The remote server returned the following status code: '{1}'.", folderName, resp.StatusCode)); - } - } - - /// - /// Gets a client that can be used to connect to the REST endpoints of an OpenStack storage service. - /// - /// The client. - internal IStorageServiceRestClient GetRestClient() - { - return this.ServiceLocator.Locate().Create(this._context, this.ServiceLocator); - } - } -} diff --git a/OpenStack/OpenStack/Storage/StorageServicePocoClientFactory.cs b/OpenStack/OpenStack/Storage/StorageServicePocoClientFactory.cs deleted file mode 100644 index 9e662e2..0000000 --- a/OpenStack/OpenStack/Storage/StorageServicePocoClientFactory.cs +++ /dev/null @@ -1,30 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Storage -{ - /// - internal class StorageServicePocoClientFactory : IStorageServicePocoClientFactory - { - /// - public IStorageServicePocoClient Create(ServiceClientContext context, IServiceLocator serviceLocator) - { - return new StorageServicePocoClient(context, serviceLocator); - } - } -} diff --git a/OpenStack/OpenStack/Storage/StorageServiceRestClient.cs b/OpenStack/OpenStack/Storage/StorageServiceRestClient.cs deleted file mode 100644 index 0024bb5..0000000 --- a/OpenStack/OpenStack/Storage/StorageServiceRestClient.cs +++ /dev/null @@ -1,330 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Net.Http; -using System.Threading.Tasks; -using OpenStack.Common; -using OpenStack.Common.Http; -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Storage -{ - /// - internal class StorageServiceRestClient : OpenStackServiceRestClientBase, IStorageServiceRestClient - { - internal IStorageContainerNameValidator StorageContainerNameValidator; - - /// - /// Creates a new instance of the StorageServiceRestClient class. - /// - /// The current storage service context to use. - /// A service locator to be used to locate/inject dependent services. - internal StorageServiceRestClient(ServiceClientContext context, IServiceLocator serviceLocator) - : base(context, serviceLocator) - { - this.StorageContainerNameValidator = this.ServiceLocator.Locate(); - } - - /// - public async Task CreateObject(string containerName, string objectName, IDictionary metadata, Stream content) - { - AssertContainerNameIsValid(containerName); - - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, containerName, objectName); - client.Method = HttpMethod.Put; - - this.AddObjectMetadata(metadata, client); - - client.Content = content; - - return await client.SendAsync(); - } - - /// - public async Task CreateDynamicManifest(string containerName, string manifestName, IDictionary metadata, string segmentsPath) - { - AssertContainerNameIsValid(containerName); - manifestName.AssertIsNotNullOrEmpty("manifestName","Cannot create a storage manifest with a null or empty name."); - segmentsPath.AssertIsNotNullOrEmpty("segmentsPath","Cannot create a dynamic large object manifest with a null or empty segments path."); - metadata.AssertIsNotNull("metadata","Cannot create a storage manifest with null metadata."); - - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, containerName, manifestName); - client.Method = HttpMethod.Put; - client.Content = new MemoryStream(); - - client.Headers.Add("X-Object-Manifest", segmentsPath); - this.AddObjectMetadata(metadata, client); - - return await client.SendAsync(); - } - - /// - public async Task CreateStaticManifest(string containerName, string manifestName, IDictionary metadata, Stream content) - { - AssertContainerNameIsValid(containerName); - manifestName.AssertIsNotNullOrEmpty("manifestName", "Cannot create a storage manifest with a null or empty name."); - metadata.AssertIsNotNull("metadata", "Cannot create a storage manifest with null metadata."); - content.AssertIsNotNull("content","Cannot create a static large object manifest with null content."); - - var client = this.GetHttpClient(this.Context); - - var baseUri = CreateRequestUri(this.Context.PublicEndpoint, containerName); - client.Uri = new Uri(string.Format("{0}/{1}?multipart-manifest=put", baseUri, manifestName)); - client.Method = HttpMethod.Put; - client.Content = content; - - this.AddObjectMetadata(metadata, client); - - return await client.SendAsync(); - } - - /// - public async Task CreateContainer(string containerName, IDictionary metadata) - { - AssertContainerNameIsValid(containerName); - - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, containerName); - client.Method = HttpMethod.Put; - client.Content = new MemoryStream(); - - this.AddContainerMetadata(metadata, client); - - return await client.SendAsync(); - } - - /// - public async Task GetObject(string containerName, string objectName) - { - AssertContainerNameIsValid(containerName); - - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, containerName, objectName); - client.Method = HttpMethod.Get; - - return await client.SendAsync(); - } - - /// - public async Task GetFolder(string containerName, string folderName) - { - AssertContainerNameIsValid(containerName); - folderName.AssertIsNotNullOrEmpty("folderName","Cannot get a folder with a null or empty folder name."); - - var client = this.GetHttpClient(this.Context); - - var baseUri = CreateRequestUri(this.Context.PublicEndpoint, containerName); - var prefix = string.Equals("/", folderName, StringComparison.Ordinal) - ? string.Empty - : string.Format("&prefix={0}", folderName); - - client.Uri = new Uri(string.Format("{0}?delimiter=/{1}", baseUri, prefix)); - client.Method = HttpMethod.Get; - - return await client.SendAsync(); - } - - /// - public async Task GetContainer(string containerName) - { - AssertContainerNameIsValid(containerName); - - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, containerName); - client.Method = HttpMethod.Get; - - return await client.SendAsync(); - } - - /// - public async Task DeleteObject(string containerName, string objectName) - { - AssertContainerNameIsValid(containerName); - - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, containerName, objectName); - client.Method = HttpMethod.Delete; - - return await client.SendAsync(); - } - - /// - public async Task DeleteContainer(string containerName) - { - AssertContainerNameIsValid(containerName); - - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, containerName); - client.Method = HttpMethod.Delete; - - return await client.SendAsync(); - } - - /// - public async Task UpdateObject(string containerName, string objectName, IDictionary metadata) - { - AssertContainerNameIsValid(containerName); - - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, containerName, objectName); - client.Method = HttpMethod.Post; - AddObjectMetadata(metadata,client); - - return await client.SendAsync(); - } - - /// - public async Task UpdateContainer(string containerName, IDictionary metadata) - { - AssertContainerNameIsValid(containerName); - - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, containerName); - client.Method = HttpMethod.Post; - AddContainerMetadata(metadata, client); - - return await client.SendAsync(); - } - - /// - public async Task GetContainerMetadata(string containerName) - { - AssertContainerNameIsValid(containerName); - - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, containerName); - client.Method = HttpMethod.Head; - - return await client.SendAsync(); - } - - /// - public async Task GetObjectMetadata(string containerName, string objectName) - { - AssertContainerNameIsValid(containerName); - - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, containerName, objectName); - client.Method = HttpMethod.Head; - - return await client.SendAsync(); - } - - /// - public async Task GetManifestMetadata(string containerName, string manifestName) - { - AssertContainerNameIsValid(containerName); - manifestName.AssertIsNotNullOrEmpty("manifestName", "Cannot get a manifest with a null or empty folder name."); - - var client = this.GetHttpClient(this.Context); - - var baseUri = CreateRequestUri(this.Context.PublicEndpoint, containerName); - client.Uri = new Uri(string.Format("{0}/{1}?multipart-manifest=get", baseUri, manifestName)); - client.Method = HttpMethod.Get; - - return await client.SendAsync(); - } - - /// - public async Task CopyObject(string sourceContainerName, string sourceObjectName, string targetContainerName, string targetObjectName) - { - AssertContainerNameIsValid(sourceContainerName); - AssertContainerNameIsValid(targetContainerName); - - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint, sourceContainerName, sourceObjectName); - client.Headers.Add("Destination",string.Join("/", targetContainerName, targetObjectName)); - - client.Method = new HttpMethod("COPY"); - - return await client.SendAsync(); - } - - /// - public async Task GetAccount() - { - var client = this.GetHttpClient(this.Context); - - client.Uri = CreateRequestUri(this.Context.PublicEndpoint); - client.Method = HttpMethod.Get; - - return await client.SendAsync(); - } - - /// - /// Adds the appropriate headers to the Http client for the given items metadata. - /// - /// The prefix for the header. - /// The items metadata. - /// The http client. - internal void AddItemMetadata(string headerPrefix, IDictionary metadata, IHttpAbstractionClient client) - { - foreach (var header in metadata) - { - client.Headers.Add(string.Format("{0}-{1}", headerPrefix, header.Key), header.Value); - } - } - - /// - /// Adds the appropriate headers to the Http client for the given objects metadata. - /// - /// The items metadata. - /// The http client. - internal void AddObjectMetadata(IDictionary metadata, IHttpAbstractionClient client) - { - AddItemMetadata("X-Object-Meta", metadata, client); - } - - /// - /// Adds the appropriate headers to the Http client for the given containers metadata. - /// - /// The items metadata. - /// The http client. - internal void AddContainerMetadata(IDictionary metadata, IHttpAbstractionClient client) - { - AddItemMetadata("X-Container-Meta", metadata, client); - } - - /// - /// Asserts that the given container name is valid. - /// - /// The container name. - internal void AssertContainerNameIsValid(string containerName) - { - if (!StorageContainerNameValidator.Validate(containerName)) - { - throw new ArgumentException(string.Format("Container name '{0}' is invalid. Container names cannot includes slashes.", containerName), "containerName"); - } - } - } -} diff --git a/OpenStack/OpenStack/Storage/StorageServiceRestClientFactory.cs b/OpenStack/OpenStack/Storage/StorageServiceRestClientFactory.cs deleted file mode 100644 index 10f0c63..0000000 --- a/OpenStack/OpenStack/Storage/StorageServiceRestClientFactory.cs +++ /dev/null @@ -1,30 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using OpenStack.Common.ServiceLocation; - -namespace OpenStack.Storage -{ - /// - internal class StorageServiceRestClientFactory : IStorageServiceRestClientFactory - { - /// - public IStorageServiceRestClient Create(ServiceClientContext context, IServiceLocator serviceLocator) - { - return new StorageServiceRestClient(context, serviceLocator); - } - } -} diff --git a/OpenStack/OpenStack/Threading/System.Runtime.CompilerServices/AsyncTaskMethodBuilder.cs b/OpenStack/OpenStack/Threading/System.Runtime.CompilerServices/AsyncTaskMethodBuilder.cs deleted file mode 100644 index ac9e1c2..0000000 --- a/OpenStack/OpenStack/Threading/System.Runtime.CompilerServices/AsyncTaskMethodBuilder.cs +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright (c) Microsoft Corporation -// All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may not -// use this file except in compliance with the License. You may obtain a copy -// of the License at http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -// MERCHANTABLITY OR NON-INFRINGEMENT. -// -// See the Apache Version 2.0 License for specific language governing -// permissions and limitations under the License. -namespace System.Runtime.CompilerServices -{ - using System.Diagnostics; - using System.Diagnostics.CodeAnalysis; - using System.Threading.Tasks; - - /// - /// Represents a builder for asynchronous methods that return a task. - /// - [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", - Justification = "Reference equality is correct in this case. [tgs]")] - [DebuggerNonUserCode] - public struct AsyncTaskMethodBuilder - { - private TaskCompletionSource tcs; - - /// - /// Gets the task for this builder. - /// - public Task Task - { - get - { - return this.tcs.Task; - } - } - - /// - /// Creates an instance of the AsyncTaskMethodBuilder class. - /// - /// - /// A new instance of the builder. - /// - [DebuggerNonUserCode] - public static AsyncTaskMethodBuilder Create() - { - AsyncTaskMethodBuilder b; - b.tcs = new TaskCompletionSource(); - return b; - } - - /// - /// Begins running the builder with the associated state machine. - /// - /// - /// The type of the state machine. - /// - /// - /// The state machine instance, passed by reference. - /// - [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference", Justification = "Per design of the framework. [tgs]")] - [DebuggerNonUserCode] - public void Start(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine - { - stateMachine.MoveNext(); - } - - /// - /// Associates the builder with the specified state machine. - /// - /// - /// The state machine instance to associate with the builder. - /// - [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "stateMachine", - Justification = "Required to maintain the expected pattern. [tgs].")] - [DebuggerNonUserCode] - public void SetStateMachine(IAsyncStateMachine stateMachine) - { - // Method is not implemented as it is not needed for our purpose. - throw new NotImplementedException(); - } - - /// - /// Schedules the state machine to proceed to the next action when the specified awaiter completes. - /// - /// - /// The type of the awaiter. - /// - /// - /// The type of the state machine. - /// - /// - /// The awaiter. - /// - /// - /// The state machine. - /// - [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference", Justification = "Per design of the framework. [tgs]")] - [DebuggerNonUserCode] - public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) - where TAwaiter : INotifyCompletion - where TStateMachine : IAsyncStateMachine - { - awaiter.OnCompleted(stateMachine.MoveNext); - } - - /// - /// Schedules the state machine to proceed to the next action when the specified awaiter completes. - /// This method can be called from partially trusted code. - /// - /// NOTE: As this assembly does not support APTC, this method is simply a call to AwaitOnCompleted. - /// - /// - /// - /// The type of the awaiter. - /// - /// - /// The type of the state machine. - /// - /// - /// The awaiter. - /// - /// - /// The state machine. - /// - [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference", Justification = "Per design of the framework. [tgs]")] - [DebuggerNonUserCode] - public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) - where TAwaiter : ICriticalNotifyCompletion - where TStateMachine : IAsyncStateMachine - { - awaiter.OnCompleted(stateMachine.MoveNext); - } - - /// - /// Marks the task as successfully completed. - /// - [DebuggerNonUserCode] - public void SetResult() - { - this.tcs.SetResult(null); - } - - /// - /// Marks the task as failed and binds the specified exception to the task. - /// - /// - /// The exception to bind to the task. - /// - [DebuggerNonUserCode] - public void SetException(Exception exception) - { - this.tcs.SetException(exception); - } - } -} \ No newline at end of file diff --git a/OpenStack/OpenStack/Threading/System.Runtime.CompilerServices/AsyncTaskMethodBuilderOfT.cs b/OpenStack/OpenStack/Threading/System.Runtime.CompilerServices/AsyncTaskMethodBuilderOfT.cs deleted file mode 100644 index dc427e4..0000000 --- a/OpenStack/OpenStack/Threading/System.Runtime.CompilerServices/AsyncTaskMethodBuilderOfT.cs +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright (c) Microsoft Corporation -// All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may not -// use this file except in compliance with the License. You may obtain a copy -// of the License at http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -// MERCHANTABLITY OR NON-INFRINGEMENT. -// -// See the Apache Version 2.0 License for specific language governing -// permissions and limitations under the License. -namespace System.Runtime.CompilerServices -{ - using System.Diagnostics; - using System.Diagnostics.CodeAnalysis; - using System.Threading.Tasks; - - /// - /// Represents a builder for asynchronous methods that return a task. - /// - /// - /// The result to use to complete the task. - /// - [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", - Justification = "Reference equality is correct in this case. [tgs]")] - [DebuggerNonUserCode] - public struct AsyncTaskMethodBuilder - { - /// - /// The TaskCompletionSource for this builder. - /// - private TaskCompletionSource tcs; - - /// - /// Gets the task for this builder. - /// - [DebuggerNonUserCode] - public Task Task - { - get - { - return this.tcs.Task; - } - } - - /// - /// Creates an instance of the AsyncTaskMethodBuilder<TResult> class. - /// - /// - /// A new instance of the builder. - /// - [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes", - Justification = "Acceptable in this case in order to maintain the overall pattern. [tgs]")] - [DebuggerNonUserCode] - public static AsyncTaskMethodBuilder Create() - { - AsyncTaskMethodBuilder builder; - builder.tcs = new TaskCompletionSource(); - return builder; - } - - /// - /// Begins running the builder with the associated state machine. - /// - /// - /// The type of the state machine. - /// - /// - /// The state machine instance, passed by reference. - /// - [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference", Justification = "Per design of the framework. [tgs]")] - [DebuggerNonUserCode] - public void Start(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine - { - stateMachine.MoveNext(); - } - - /// - /// Associates the builder with the specified state machine. - /// - /// - /// The state machine instance to associate with the builder. - /// - [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "stateMachine", - Justification = "Required to maintain the expected pattern. [tgs].")] - [DebuggerNonUserCode] - public void SetStateMachine(IAsyncStateMachine stateMachine) - { - // Method is not implemented as it is not needed for our purpose. - throw new NotImplementedException(); - } - - /// - /// Schedules the state machine to proceed to the next action when the specified awaiter completes. - /// - /// - /// The type of the awaiter. - /// - /// - /// The type of the state machine. - /// - /// - /// The awaiter. - /// - /// - /// The state machine. - /// - [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference", Justification = "Per design of the framework. [tgs]")] - [DebuggerNonUserCode] - public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) - where TAwaiter : INotifyCompletion - where TStateMachine : IAsyncStateMachine - { - awaiter.OnCompleted(stateMachine.MoveNext); - } - - /// - /// Schedules the state machine to proceed to the next action when the specified awaiter completes. - /// This method can be called from partially trusted code. - /// - /// NOTE: As this assembly does not support APTC, this method is simply a call to AwaitOnCompleted. - /// - /// - /// - /// The type of the awaiter. - /// - /// - /// The type of the state machine. - /// - /// - /// The awaiter. - /// - /// - /// The state machine. - /// - [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference", Justification = "Per design of the framework. [tgs]")] - [DebuggerNonUserCode] - public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) - where TAwaiter : ICriticalNotifyCompletion - where TStateMachine : IAsyncStateMachine - { - this.AwaitOnCompleted(ref awaiter, ref stateMachine); - } - - /// - /// Marks the task as successfully completed. - /// - /// - /// The result to use to complete the task. - /// - [DebuggerNonUserCode] - public void SetResult(T result) - { - this.tcs.SetResult(result); - } - - /// - /// Marks the task as failed and binds the specified exception to the task. - /// - /// - /// The exception to bind to the task. - /// - [DebuggerNonUserCode] - public void SetException(Exception exception) - { - this.tcs.SetException(exception); - } - } -} \ No newline at end of file diff --git a/OpenStack/OpenStack/Threading/System.Runtime.CompilerServices/AsyncVoidMethodBuilder.cs b/OpenStack/OpenStack/Threading/System.Runtime.CompilerServices/AsyncVoidMethodBuilder.cs deleted file mode 100644 index ba2aab4..0000000 --- a/OpenStack/OpenStack/Threading/System.Runtime.CompilerServices/AsyncVoidMethodBuilder.cs +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright (c) Microsoft Corporation -// All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may not -// use this file except in compliance with the License. You may obtain a copy -// of the License at http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -// MERCHANTABLITY OR NON-INFRINGEMENT. -// -// See the Apache Version 2.0 License for specific language governing -// permissions and limitations under the License. -namespace System.Runtime.CompilerServices -{ - using System.Diagnostics; - using System.Diagnostics.CodeAnalysis; - - /// - /// Represents a builder for asynchronous methods that do not return a value. - /// - [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", - Justification = "Reference equality is correct in this case. [tgs]")] - [DebuggerNonUserCode] - public struct AsyncVoidMethodBuilder - { - /// - /// Creates an instance of the AsyncVoidMethodBuilder class. - /// - /// - /// A new instance of the builder. - /// - [DebuggerNonUserCode] - public static AsyncVoidMethodBuilder Create() - { - return new AsyncVoidMethodBuilder(); - } - - /// - /// Binds an exception to the method builder. - /// - /// - /// The exception to bind. - /// - [DebuggerNonUserCode] - public void SetException(Exception exception) - { - throw exception; - } - - /// - /// Marks the method builder as successfully completed. - /// - [DebuggerNonUserCode] - public void SetResult() - { - } - - /// - /// Associates the builder with the specified state machine. - /// - /// - /// The state machine instance to associate with the builder. - /// - [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "stateMachine", - Justification = "Required to maintain the expected pattern. [tgs].")] - [DebuggerNonUserCode] - public void SetStateMachine(IAsyncStateMachine stateMachine) - { - // Method is not implemented as it is not needed for our purpose. - throw new NotImplementedException(); - } - - /// - /// Begins running the builder with the associated state machine. - /// - /// - /// The type of the state machine. - /// - /// - /// The state machine instance, passed by reference. - /// - [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference", Justification = "Per design of the framework. [tgs]")] - [DebuggerNonUserCode] - public void Start(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine - { - stateMachine.MoveNext(); - } - - /// - /// Schedules the state machine to proceed to the next action when the specified awaiter completes. - /// - /// - /// The type of the awaiter. - /// - /// - /// The type of the state machine. - /// - /// - /// The awaiter. - /// - /// - /// The state machine. - /// - [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference", Justification = "Per design of the framework. [tgs]")] - [DebuggerNonUserCode] - public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) - where TAwaiter : INotifyCompletion - where TStateMachine : IAsyncStateMachine - { - awaiter.OnCompleted(stateMachine.MoveNext); - } - - /// - /// Schedules the state machine to proceed to the next action when the specified awaiter completes. - /// This method can be called from partially trusted code. - /// - /// NOTE: As this assembly does not support APTC, this method is simply a call to AwaitOnCompleted. - /// - /// - /// - /// The type of the awaiter. - /// - /// - /// The type of the state machine. - /// - /// - /// The awaiter. - /// - /// - /// The state machine. - /// - [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference", Justification = "Per design of the framework. [tgs]")] - [DebuggerNonUserCode] - public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) - where TAwaiter : ICriticalNotifyCompletion - where TStateMachine : IAsyncStateMachine - { - awaiter.OnCompleted(stateMachine.MoveNext); - } - } -} \ No newline at end of file diff --git a/OpenStack/OpenStack/Threading/System.Runtime.CompilerServices/IAsyncStateMachine.cs b/OpenStack/OpenStack/Threading/System.Runtime.CompilerServices/IAsyncStateMachine.cs deleted file mode 100644 index 162d609..0000000 --- a/OpenStack/OpenStack/Threading/System.Runtime.CompilerServices/IAsyncStateMachine.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft Corporation -// All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may not -// use this file except in compliance with the License. You may obtain a copy -// of the License at http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -// MERCHANTABLITY OR NON-INFRINGEMENT. -// -// See the Apache Version 2.0 License for specific language governing -// permissions and limitations under the License. -namespace System.Runtime.CompilerServices -{ - /// - /// Represents state machines that are generated for asynchronous methods. This type is intended for compiler use only. - /// - public interface IAsyncStateMachine - { - /// - /// Moves the state machine to its next state. - /// - void MoveNext(); - - /// - /// Configures the state machine with a heap-allocated replica. - /// - /// - /// The heap-allocated replica. - /// - void SetStateMachine(IAsyncStateMachine stateMachine); - } -} \ No newline at end of file diff --git a/OpenStack/OpenStack/Threading/System.Runtime.CompilerServices/ICriticalNotifyCompletion.cs b/OpenStack/OpenStack/Threading/System.Runtime.CompilerServices/ICriticalNotifyCompletion.cs deleted file mode 100644 index 16eaf22..0000000 --- a/OpenStack/OpenStack/Threading/System.Runtime.CompilerServices/ICriticalNotifyCompletion.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) Microsoft Corporation -// All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may not -// use this file except in compliance with the License. You may obtain a copy -// of the License at http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -// MERCHANTABLITY OR NON-INFRINGEMENT. -// -// See the Apache Version 2.0 License for specific language governing -// permissions and limitations under the License. -namespace System.Runtime.CompilerServices -{ - using System.Security; - - /// - /// Represents an awaiter that schedules continuations when an await operation completes. - /// - public interface ICriticalNotifyCompletion : INotifyCompletion - { - /// - /// Schedules the continuation action that's invoked when the instance completes. - /// - /// - /// The action to invoke when the operation completes. - /// - [SecurityCritical] - void UnsafeOnCompleted(Action continuation); - } -} \ No newline at end of file diff --git a/OpenStack/OpenStack/Threading/System.Runtime.CompilerServices/INotifyCompletion.cs b/OpenStack/OpenStack/Threading/System.Runtime.CompilerServices/INotifyCompletion.cs deleted file mode 100644 index 5904b9b..0000000 --- a/OpenStack/OpenStack/Threading/System.Runtime.CompilerServices/INotifyCompletion.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation -// All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may not -// use this file except in compliance with the License. You may obtain a copy -// of the License at http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -// MERCHANTABLITY OR NON-INFRINGEMENT. -// -// See the Apache Version 2.0 License for specific language governing -// permissions and limitations under the License. -namespace System.Runtime.CompilerServices -{ - /// - /// Represents an operation that schedules continuations when it completes. - /// - public interface INotifyCompletion - { - /// - /// Schedules the continuation action that's invoked when the instance completes. - /// - /// - /// The action to invoke when the operation completes. - /// - void OnCompleted(Action continuation); - } -} \ No newline at end of file diff --git a/OpenStack/OpenStack/Threading/System.Threading.Tasks/TaskAwaiter.cs b/OpenStack/OpenStack/Threading/System.Threading.Tasks/TaskAwaiter.cs deleted file mode 100644 index 89307e7..0000000 --- a/OpenStack/OpenStack/Threading/System.Threading.Tasks/TaskAwaiter.cs +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) Microsoft Corporation -// All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may not -// use this file except in compliance with the License. You may obtain a copy -// of the License at http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -// MERCHANTABLITY OR NON-INFRINGEMENT. -// -// See the Apache Version 2.0 License for specific language governing -// permissions and limitations under the License. -namespace System.Threading.Tasks -{ - using System; - using System.Diagnostics; - using System.Diagnostics.CodeAnalysis; - using System.Runtime.CompilerServices; - - /// - /// Provides an object that waits for the completion of an asynchronous task. - /// - [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", - Justification = "Reference equality is correct in this case. [tgs]")] - [DebuggerNonUserCode] - public struct TaskAwaiter : INotifyCompletion - { - private readonly Task task; - - /// - /// Initializes a new instance of the TaskAwaiter structure. - /// - /// - /// The task. - /// - [DebuggerNonUserCode] - public TaskAwaiter(Task task) - { - this.task = task; - } - - /// - /// Gets a task scheduler. - /// - [DebuggerNonUserCode] - public static TaskScheduler TaskScheduler - { - get - { - return TaskSchedularHelper.TaskScheduler; - } - } - - /// - /// Gets a value indicating whether the asynchronous task has completed. - /// - [DebuggerNonUserCode] - public bool IsCompleted - { - get { return this.task.IsCompleted; } - } - - /// - /// Sets the action to perform when the TaskAwaiter object stops waiting for the asynchronous task to complete. - /// - /// - /// The action to perform when the wait operation completes. - /// - [DebuggerNonUserCode] - public void OnCompleted(Action continuation) - { - TaskCoreExtensions.CompletedInternal(continuation); - } - - /// - /// Ends the wait for the completion of the asynchronous task. - /// - [DebuggerNonUserCode] - public void GetResult() - { - try - { - this.task.Wait(); - } - catch (AggregateException ex) - { - throw ex.InnerExceptions[0]; - } - } - } -} \ No newline at end of file diff --git a/OpenStack/OpenStack/Threading/System.Threading.Tasks/TaskAwaiterOfT.cs b/OpenStack/OpenStack/Threading/System.Threading.Tasks/TaskAwaiterOfT.cs deleted file mode 100644 index b644998..0000000 --- a/OpenStack/OpenStack/Threading/System.Threading.Tasks/TaskAwaiterOfT.cs +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) Microsoft Corporation -// All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may not -// use this file except in compliance with the License. You may obtain a copy -// of the License at http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -// MERCHANTABLITY OR NON-INFRINGEMENT. -// -// See the Apache Version 2.0 License for specific language governing -// permissions and limitations under the License. -namespace System.Threading.Tasks -{ - using System; - using System.Diagnostics; - using System.Diagnostics.CodeAnalysis; - using System.Runtime.CompilerServices; - - /// - /// Represents an object that waits for the completion of an asynchronous task and provides a parameter for the result. - /// - /// - /// The result for the task. - /// - [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", - Justification = "Reference equality is correct in this case. [tgs]")] - [DebuggerNonUserCode] - public struct TaskAwaiter : INotifyCompletion - { - private readonly Task task; - - /// - /// Initializes a new instance of the TaskAwaiter structure. - /// - /// - /// The task to await. - /// - [DebuggerNonUserCode] - public TaskAwaiter(Task task) - { - this.task = task; - } - - /// - /// Gets a value indicating whether the asynchronous task has completed. - /// - [DebuggerNonUserCode] - public bool IsCompleted - { - get { return this.task.IsCompleted; } - } - - /// - /// Sets the action to perform when the TaskAwaiter object stops waiting for the asynchronous task to complete. - /// - /// - /// The action to perform when the wait operation completes. - /// - [DebuggerNonUserCode] - public void OnCompleted(Action continuation) - { - TaskCoreExtensions.CompletedInternal(continuation); - } - - /// - /// Ends the wait for the completion of the asynchronous task. - /// - /// - /// The result of the completed task. - /// - [DebuggerNonUserCode] - public T GetResult() - { - try - { - return this.task.Result; - } - catch (AggregateException ex) - { - throw ex.InnerExceptions[0]; - } - } - } -} \ No newline at end of file diff --git a/OpenStack/OpenStack/Threading/System.Threading.Tasks/TaskCoreExtensions.cs b/OpenStack/OpenStack/Threading/System.Threading.Tasks/TaskCoreExtensions.cs deleted file mode 100644 index 4857e4a..0000000 --- a/OpenStack/OpenStack/Threading/System.Threading.Tasks/TaskCoreExtensions.cs +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) Microsoft Corporation -// All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may not -// use this file except in compliance with the License. You may obtain a copy -// of the License at http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -// MERCHANTABLITY OR NON-INFRINGEMENT. -// -// See the Apache Version 2.0 License for specific language governing -// permissions and limitations under the License. -namespace System.Threading.Tasks -{ - using System.IO; - using System.Diagnostics; - - /// - /// Provides core extension methods for task. - /// - [DebuggerNonUserCode] - public static class TaskCoreExtensions - { - /// - /// Reads all characters from the current position to the end of the TextReader - /// and returns them as one string asynchronously. - /// - /// The source reader. - /// - /// A Task that represents the asynchronous operation. - /// - [DebuggerNonUserCode] - public static Task ReadToEndAsync(this TextReader source) - { - if (source == null) - { - throw new ArgumentNullException("source"); - } - else - { - return Task.Factory.StartNew((Func)(() => source.ReadToEnd()), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); - } - } - - /// - /// Gets an awaiter used to await this Task. - /// - /// - /// The task object being extended. - /// - /// - /// An awaiter instance. - /// - [DebuggerNonUserCode] - public static TaskAwaiter GetAwaiter(this Task task) - { - return new TaskAwaiter(task); - } - - /// - /// Gets an awaiter used to await this Task<TResult%gt;. - /// - /// - /// The return type for the task. - /// - /// - /// The task object being extended. - /// - /// - /// An awaiter instance. - /// - [DebuggerNonUserCode] - public static TaskAwaiter GetAwaiter(this Task task) - { - return new TaskAwaiter(task); - } - - /// - /// Schedules the continuation onto the associated with this . - /// - /// The action to invoke when the await operation completes. - [DebuggerNonUserCode] - internal static void CompletedInternal(Action continuation) - { - var scheduler = TaskScheduler.Current; - Task.Factory.StartNew(state => ((Action)state)(), - continuation, - CancellationToken.None, - TaskCreationOptions.None, - scheduler); - } - } -} \ No newline at end of file diff --git a/OpenStack/OpenStack/Threading/System.Threading.Tasks/TaskEx.cs b/OpenStack/OpenStack/Threading/System.Threading.Tasks/TaskEx.cs deleted file mode 100644 index ad6f6a9..0000000 --- a/OpenStack/OpenStack/Threading/System.Threading.Tasks/TaskEx.cs +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright (c) Microsoft Corporation -// All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may not -// use this file except in compliance with the License. You may obtain a copy -// of the License at http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -// MERCHANTABLITY OR NON-INFRINGEMENT. -// -// See the Apache Version 2.0 License for specific language governing -// permissions and limitations under the License. -namespace System.Threading.Tasks -{ - using System; - using System.Collections.Generic; - using System.Diagnostics; - using System.Diagnostics.CodeAnalysis; - using System.Linq; - using System.Text; - - /// - /// Provides extra functions to be used in place of NetFx 4.5 task standard static methods. - /// - [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", - Justification = "This naming is by convention for this usage as set by other standard async targeting packages. [tgs]")] - public static class TaskEx - { - /// - /// Returns a task that has been completed. - /// - /// - /// A completed task. - /// - [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", - Justification = "In this case the pattern is correct. [TGS]")] - public static Task GetCompletedTask() - { - Task retval = null; - try - { - retval = new Task(() => { }); - } - catch (Exception) - { - if (!ReferenceEquals(retval, null)) - { - retval.Dispose(); - } - throw; - } - retval.Start(); - retval.Wait(); - return retval; - } - - /// - /// Creates a task that runs the specified action. - /// - /// The action to execute asynchronously. - /// - /// A task that represents the completion of the action. - /// - /// The argument is null. - [DebuggerNonUserCode] - public static Task Run(Action action) - { - return TaskEx.Run(action, CancellationToken.None); - } - - /// - /// Creates a task that runs the specified action. - /// - /// The action to execute.The CancellationToken to use to request cancellation of this task. - /// - /// A task that represents the completion of the action. - /// - /// The argument is null. - [DebuggerNonUserCode] - public static Task Run(Action action, CancellationToken cancellationToken) - { - return Task.Factory.StartNew(action, cancellationToken, TaskCreationOptions.None, TaskScheduler.Default); - } - - /// - /// Creates a task that runs the specified function. - /// - /// The function to execute asynchronously. - /// - /// The result type of the function. - /// - /// - /// A task that represents the completion of the action. - /// - /// The argument is null. - [DebuggerNonUserCode] - public static Task Run(Func function) - { - return TaskEx.Run(function, CancellationToken.None); - } - - /// - /// Creates a task that runs the specified function. - /// - /// The action to execute.The CancellationToken to use to cancel the task. - /// - /// The result type of the function. - /// - /// - /// A task that represents the completion of the action. - /// - /// The argument is null. - [DebuggerNonUserCode] - public static Task Run(Func function, CancellationToken cancellationToken) - { - return Task.Factory.StartNew(function, cancellationToken, TaskCreationOptions.None, TaskScheduler.Default); - } - - /// - /// Creates a task that runs the specified function. - /// - /// The action to execute asynchronously. - /// - /// A task that represents the completion of the action. - /// - /// The argument is null. - [DebuggerNonUserCode] - public static Task Run(Func function) - { - return TaskEx.Run(function, CancellationToken.None); - } - - /// - /// Creates a task that runs the specified function. - /// - /// The function to execute.The CancellationToken to use to request cancellation of this task. - /// - /// A task that represents the completion of the function. - /// - /// The argument is null. - [DebuggerNonUserCode] - public static Task Run(Func function, CancellationToken cancellationToken) - { - return TaskExtensions.Unwrap(TaskEx.Run(function, cancellationToken)); - } - - /// - /// Creates a task that runs the specified function. - /// - /// The function to execute asynchronously. - /// - /// The result type of the function. - /// - /// - /// A task that represents the completion of the action. - /// - /// The argument is null. - [DebuggerNonUserCode] - public static Task Run(Func> function) - { - return TaskEx.Run(function, CancellationToken.None); - } - - /// - /// Creates a task that runs the specified function. - /// - /// The action to execute.The CancellationToken to use to cancel the task. - /// - /// The result type of the function. - /// - /// - /// A task that represents the completion of the action. - /// - /// The argument is null. - [DebuggerNonUserCode] - public static Task Run(Func> function, CancellationToken cancellationToken) - { - return TaskExtensions.Unwrap(TaskEx.Run>(function, cancellationToken)); - } - } -} diff --git a/OpenStack/OpenStack/Threading/System.Threading.Tasks/TaskSchedularHelper.cs b/OpenStack/OpenStack/Threading/System.Threading.Tasks/TaskSchedularHelper.cs deleted file mode 100644 index a9dc9ae..0000000 --- a/OpenStack/OpenStack/Threading/System.Threading.Tasks/TaskSchedularHelper.cs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) Microsoft Corporation -// All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may not -// use this file except in compliance with the License. You may obtain a copy -// of the License at http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -// MERCHANTABLITY OR NON-INFRINGEMENT. -// -// See the Apache Version 2.0 License for specific language governing -// permissions and limitations under the License. -namespace System.Threading.Tasks -{ - using System; - using System.Collections.Generic; - using System.Diagnostics; - using System.Linq; - using System.Text; - - internal static class TaskSchedularHelper - { - /// - /// Gets a task scheduler. - /// - [DebuggerNonUserCode] - public static TaskScheduler TaskScheduler - { - get - { - if (SynchronizationContext.Current == null) - { - return TaskScheduler.Default; - } - return TaskScheduler.FromCurrentSynchronizationContext(); - } - } - } -} diff --git a/OpenStack/OpenStack/packages.config b/OpenStack/OpenStack/packages.config deleted file mode 100644 index d8aa566..0000000 --- a/OpenStack/OpenStack/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/OpenStack/OpenStack45-PCL/Common/ReflectionExtentions.cs b/OpenStack/OpenStack45-PCL/Common/ReflectionExtentions.cs deleted file mode 100644 index c2446cf..0000000 --- a/OpenStack/OpenStack45-PCL/Common/ReflectionExtentions.cs +++ /dev/null @@ -1,80 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; - -namespace OpenStack.Common -{ - /// - /// Static class for extending reflection classes. - /// - internal static class ReflectionExtentions - { - /// - /// Gets the assembly that contains the extended type. - /// - /// The given Type - /// The assembly that contains the given type. - public static Assembly GetAssembly(this Type input) - { - return input.GetTypeInfo().Assembly; - } - - /// - /// Determines if a type is assignable from the given type. - /// - /// The given type. - /// The type to evaluate. - /// A value indicating if the target is assignable from the given type. - public static bool IsAssignableFrom(this Type input, Type target) - { - return input.GetTypeInfo().IsAssignableFrom(target.GetTypeInfo()); - } - - /// - /// Determines if the given type is an interface. - /// - /// The given type. - /// A value indicating if the given type is an interface. - public static bool IsInterface(this Type input) - { - return input.GetTypeInfo().IsInterface; - } - - /// - /// Gets a list of types that are defined in the given assembly. - /// - /// The given assembly. - /// A list of types defined in the given assembly. - public static IEnumerable GetDefinedTypes(this Assembly input) - { - return input.DefinedTypes.Select(ti => ti.AsType()); - } - - /// - /// Gets a list of defined constructors for the given type. - /// - /// The given type. - /// A list of constructors for the given type. - public static IEnumerable GetDefinedConstructors(this Type input) - { - return input.GetTypeInfo().DeclaredConstructors; - } - } -} diff --git a/OpenStack/OpenStack45-PCL/Common/StreamExtentions.cs b/OpenStack/OpenStack45-PCL/Common/StreamExtentions.cs deleted file mode 100644 index 0fd3c22..0000000 --- a/OpenStack/OpenStack45-PCL/Common/StreamExtentions.cs +++ /dev/null @@ -1,38 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.IO; -using System.Threading.Tasks; - -namespace OpenStack.Common -{ - /// - /// Static class for extending the Stream class. - /// - public static class StreamExtentions - { - /// - /// Copies the given stream into another stream asynchronously. - /// - /// The given stream. - /// The stream that will be copied into. - /// An asynchronous task. - public static Task CopyAsync(this Stream input, Stream output) - { - return input.CopyToAsync(output); - } - } -} diff --git a/OpenStack/OpenStack45-PCL/OpenStack45-PCL.csproj b/OpenStack/OpenStack45-PCL/OpenStack45-PCL.csproj deleted file mode 100644 index 7d2eb42..0000000 --- a/OpenStack/OpenStack45-PCL/OpenStack45-PCL.csproj +++ /dev/null @@ -1,501 +0,0 @@ - - - - - 11.0 - Debug - AnyCPU - {5660F8AA-14D5-4B3B-ADA0-F79A286EF483} - Library - Properties - OpenStack - OpenStack - v4.5 - Profile78 - 512 - {786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - - - true - full - false - ..\Bin\net45\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - ..\Bin\net45\Debug\ - TRACE - prompt - 4 - - - - - - - - Common\Http\DisposableClass.cs - - - Common\Http\HttpAbstractionClient.cs - - - Common\Http\HttpAbstractionClientFactory.cs - - - Common\Http\HttpHeadersAbstraction.cs - - - Common\Http\HttpResponseAbstraction.cs - - - Common\Http\IHttpAbstractionClient.cs - - - Common\Http\IHttpAbstractionClientFactory.cs - - - Common\Http\IHttpHeadersAbstraction.cs - - - Common\Http\IHttpResponseAbstraction.cs - - - Common\ObjectExtentions.cs - - - Common\OpenStackServiceRestClientBase.cs - - - Common\ServiceLocation\IServiceLocationAssemblyScanner.cs - - - Common\ServiceLocation\IServiceLocationManager.cs - - - Common\ServiceLocation\IServiceLocationOverrideManager.cs - - - Common\ServiceLocation\IServiceLocationRegistrar.cs - - - Common\ServiceLocation\IServiceLocationRegistrarFactory.cs - - - Common\ServiceLocation\IServiceLocationRuntimeManager.cs - - - Common\ServiceLocation\IServiceLocator.cs - - - Common\ServiceLocation\RuntimeRegistrationManager.cs - - - Common\ServiceLocation\ServiceLocationAssemblyScanner.cs - - - Common\ServiceLocation\ServiceLocationManager.cs - - - Common\ServiceLocation\ServiceLocationRegistrarFactory.cs - - - Common\ServiceLocation\ServiceLocator.cs - - - Compute\ComputeFlavor.cs - - - Compute\ComputeFlavorPayloadConverter.cs - - - Compute\ComputeImage.cs - - - Compute\ComputeImagePayloadConverter.cs - - - Compute\ComputeItem.cs - - - Compute\ComputeItemMetadataPayloadConverter.cs - - - Compute\ComputeKeyPair.cs - - - Compute\ComputeKeyPairPayloadConverter.cs - - - Compute\ComputerServerStatus.cs - - - Compute\ComputeServer.cs - - - Compute\ComputeServerPayloadConverter.cs - - - Compute\ComputeServiceClient.cs - - - Compute\ComputeServiceClientDefinition.cs - - - Compute\ComputeServicePocoClient.cs - - - Compute\ComputeServicePocoClientFactory.cs - - - Compute\ComputeServiceRestClient.cs - - - Compute\ComputeServiceRestClientFactory.cs - - - Compute\IComputeFlavorPayloadConverter.cs - - - Compute\IComputeImagePayloadConverter.cs - - - Compute\IComputeItemMetadataPayloadConverter.cs - - - Compute\IComputeKeyPairPayloadConverter.cs - - - Compute\IComputeServerPayloadConverter.cs - - - Compute\IComputeServiceClient.cs - - - Compute\IComputeServicePocoClient.cs - - - Compute\IComputeServicePocoClientFactory.cs - - - Compute\IComputeServiceRestClient.cs - - - Compute\IComputeServiceRestClientFactory.cs - - - Compute\MetadataComputeItem.cs - - - Identity\AccessTokenPayloadConverter.cs - - - Identity\IAccessTokenPayloadConverter.cs - - - Identity\ICredential.cs - - - Identity\IdentityServiceClient.cs - - - Identity\IdentityServiceClientDefinition.cs - - - Identity\IdentityServicePocoClient.cs - - - Identity\IdentityServicePocoClientFactory.cs - - - Identity\IdentityServiceRestClient.cs - - - Identity\IdentityServiceRestClientFactory.cs - - - Identity\IIdentityServiceClient.cs - - - Identity\IIdentityServicePocoClient.cs - - - Identity\IIdentityServicePocoClientFactory.cs - - - Identity\IIdentityServiceRestClient.cs - - - Identity\IIdentityServiceRestClientFactory.cs - - - Identity\IOpenStackCredential.cs - - - Identity\IOpenStackRegionResolver.cs - - - Identity\IOpenStackServiceCatalog.cs - - - Identity\IOpenStackServiceCatalogPayloadConverter.cs - - - Identity\IOpenStackServiceDefinitionPayloadConverter.cs - - - Identity\IOpenStackServiceEndpointPayloadConverter.cs - - - Identity\OpenStackCredential.cs - - - Identity\OpenStackRegionResolver.cs - - - Identity\OpenStackServiceCatalog.cs - - - Identity\OpenStackServiceCatalogPayloadConverter.cs - - - Identity\OpenStackServiceDefinition.cs - - - Identity\OpenStackServiceDefinitionPayloadConverter.cs - - - Identity\OpenStackServiceEndpoint.cs - - - Identity\OpenStackServiceEndpointPayloadConverter.cs - - - IOpenStackClient.cs - - - IOpenStackClientManager.cs - - - IOpenStackServiceClient.cs - - - IOpenStackServiceClientDefinition.cs - - - IOpenStackServiceClientManager.cs - - - Network\FloatingIp.cs - - - Network\FloatingIpPayloadConverter.cs - - - Network\FloatingIpStatus.cs - - - Network\IFloatingIpPayloadConverter.cs - - - Network\INetworkPayloadConverter.cs - - - Network\INetworkServiceClient.cs - - - Network\INetworkServicePocoClient.cs - - - Network\INetworkServicePocoClientFactory.cs - - - Network\INetworkServiceRestClient.cs - - - Network\INetworkServiceRestClientFactory.cs - - - Network\Network.cs - - - Network\NetworkPayloadConverter.cs - - - Network\NetworkServiceClient.cs - - - Network\NetworkServiceClientDefinition.cs - - - Network\NetworkServicePocoClient.cs - - - Network\NetworkServicePocoClientFactory.cs - - - Network\NetworkServiceRestClient.cs - - - Network\NetworkServiceRestClientFactory.cs - - - Network\NetworkStatus.cs - - - OpenStackClient.cs - - - OpenStackClientFactory.cs - - - OpenStackClientManager.cs - - - OpenStackServiceClientManager.cs - - - ServiceClientContext.cs - - - - - - Properties\AssemblyVersionInfo.cs - - - ServiceRegistrar.cs - - - Storage\ContainerNameValidator.cs - - - Storage\DynamicLargeObjectManifest.cs - - - Storage\FolderNameValidator.cs - - - Storage\ILargeStorageObjectCreator.cs - - - Storage\ILargeStorageObjectCreatorFactory.cs - - - Storage\IStorageAccountPayloadConverter.cs - - - Storage\IStorageContainerPayloadConverter.cs - - - Storage\IStorageFolderPayloadConverter.cs - - - Storage\IStorageObjectPayloadConverter.cs - - - Storage\IStorageServiceClient.cs - - - Storage\IStorageServicePocoClient.cs - - - Storage\IStorageServicePocoClientFactory.cs - - - Storage\IStorageServiceRestClient.cs - - - Storage\IStorageServiceRestClientFactory.cs - - - Storage\LargeStorageObjectCreator.cs - - - Storage\LargeStorageObjectCreatorFactory.cs - - - Storage\StaticLargeObjectManifest.cs - - - Storage\StorageAccount.cs - - - Storage\StorageAccountPayloadConverter.cs - - - Storage\StorageContainer.cs - - - Storage\StorageContainerPayloadConverter.cs - - - Storage\StorageFolder.cs - - - Storage\StorageFolderPayloadConverter.cs - - - Storage\StorageItem.cs - - - Storage\StorageManifest.cs - - - Storage\StorageObject.cs - - - Storage\StorageObjectPayloadConverter.cs - - - Storage\StorageServiceClient.cs - - - Storage\StorageServiceClientDefinition.cs - - - Storage\StorageServicePocoClient.cs - - - Storage\StorageServicePocoClientFactory.cs - - - Storage\StorageServiceRestClient.cs - - - Storage\StorageServiceRestClientFactory.cs - - - - - ..\packages\Newtonsoft.Json.6.0.3\lib\portable-net45+wp80+win8+wpa81\Newtonsoft.Json.dll - - - ..\packages\Microsoft.Net.Http.2.2.22\lib\portable-net40+sl4+win8+wp71+wpa81\System.Net.Http.dll - - - ..\packages\Microsoft.Net.Http.2.2.22\lib\portable-net40+sl4+win8+wp71+wpa81\System.Net.Http.Extensions.dll - - - ..\packages\Microsoft.Net.Http.2.2.22\lib\portable-net40+sl4+win8+wp71+wpa81\System.Net.Http.Primitives.dll - - - - - - - - - - - \ No newline at end of file diff --git a/OpenStack/OpenStack45-PCL/Properties/AssemblyInfo.cs b/OpenStack/OpenStack45-PCL/Properties/AssemblyInfo.cs deleted file mode 100644 index 59e554b..0000000 --- a/OpenStack/OpenStack45-PCL/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,34 +0,0 @@ -// /* ============================================================================ -// Copyright 2014 Hewlett Packard -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ============================================================================ */ - -using System.Reflection; -using System.Resources; -using System.Runtime.CompilerServices; - -// 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("OpenStack")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("OpenStack.org")] -[assembly: AssemblyProduct("OpenStack")] -[assembly: AssemblyCopyright("")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] -[assembly: NeutralResourcesLanguage("en")] - -[assembly: InternalsVisibleTo("OpenStack.Test")] \ No newline at end of file diff --git a/OpenStack/OpenStack45-PCL/packages.config b/OpenStack/OpenStack45-PCL/packages.config deleted file mode 100644 index f66353a..0000000 --- a/OpenStack/OpenStack45-PCL/packages.config +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/OpenStack/openstack-dotnet.pfx b/OpenStack/openstack-dotnet.pfx deleted file mode 100644 index 68ef0d1..0000000 Binary files a/OpenStack/openstack-dotnet.pfx and /dev/null differ diff --git a/README.rst b/README.rst index 24aae9d..9006052 100644 --- a/README.rst +++ b/README.rst @@ -1,37 +1,7 @@ -OpenStack SDK for .NET -====================== +This project is no longer maintained. -The OpenStack SDK for .NET is an SDK, written for the Microsoft .NET platform, providing developers with what they need to write software against `OpenStack `_, the open source cloud platform. +The contents of this repository are still available in the Git source code +management system. To see the contents of this repository before it reached +its end of life, please check out the previous commit with +"git checkout HEAD^1". -Quick Start Example -------------------- -The following code will connect to Openstack, and print out all of the containers in the default storage account:: - - using System; - using System.Threading; - using Openstack; - using Openstack.Identity; - using Openstack.Storage; - - var authUri = new Uri("https://region.identity.host.com:12345/v2.0"); - var userName = "user name"; - var password = "password"; - var tenantId = "XXXXXXXXXXXXXX-Project"; - - var credential = new OpenStackCredential(authUri, userName, password, tenantId); - var client = OpenStackClientFactory.CreateClient(credential); - - await client.Connect(); - - var storageServiceClient = client.CreateServiceClient(); - var storageAccount = await storageServiceClient.GetStorageAccount(); - foreach(var container in storageAccount.Containers) - { - Console.WriteLine(container.Name); - } - -For more examples see the *OpenStack/Examples* directory. - -Development ------------ -The `homepage for the development effort `_ is on the OpenStack Wiki. The .NET SDK is developed through the same processes as the OpenStack services. `Features requests `_ and `bugs `_ are filed through launchpad. \ No newline at end of file