Adding Get Started Code Sample

This commit is contained in:
AndrewHoh 2014-09-26 17:49:25 -07:00
Родитель 9dea06dbe6
Коммит a7b8540825
7 изменённых файлов: 486 добавлений и 0 удалений

Просмотреть файл

@ -0,0 +1,29 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.21005.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{5721248B-292E-4C7C-A035-E12CE58F25AB}"
ProjectSection(SolutionItems) = preProject
.nuget\NuGet.Config = .nuget\NuGet.Config
.nuget\NuGet.exe = .nuget\NuGet.exe
.nuget\NuGet.targets = .nuget\NuGet.targets
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GetStarted", "src\GetStarted.csproj", "{2A834C4E-055B-4C5E-BA76-D9438D98AC42}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{2A834C4E-055B-4C5E-BA76-D9438D98AC42}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2A834C4E-055B-4C5E-BA76-D9438D98AC42}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2A834C4E-055B-4C5E-BA76-D9438D98AC42}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2A834C4E-055B-4C5E-BA76-D9438D98AC42}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

Просмотреть файл

Просмотреть файл

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="EndPointUrl" value="~your documentdb enpoint here~"/>
<add key="AuthorizationKey" value="~your auth key here~"/>
</appSettings>
</configuration>

Просмотреть файл

@ -0,0 +1,139 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{2A834C4E-055B-4C5E-BA76-D9438D98AC42}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>DocDBGetStarted</RootNamespace>
<AssemblyName>DocDBGetStarted</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<PublishUrl>C:\Users\anhoh\Desktop\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<PublishWizardCompleted>true</PublishWizardCompleted>
<BootstrapperEnabled>true</BootstrapperEnabled>
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
<RestorePackages>true</RestorePackages>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Label="SlowCheetah">
<SlowCheetahToolsPath>$([System.IO.Path]::GetFullPath( $(MSBuildProjectDirectory)\..\packages\SlowCheetah.2.5.14\tools\))</SlowCheetahToolsPath>
<SlowCheetah_EnableImportFromNuGet Condition=" '$(SlowCheetah_EnableImportFromNuGet)'=='' ">true</SlowCheetah_EnableImportFromNuGet>
<SlowCheetah_NuGetImportPath Condition=" '$(SlowCheetah_NuGetImportPath)'=='' ">$([System.IO.Path]::GetFullPath( $(MSBuildProjectDirectory)\Properties\SlowCheetah\SlowCheetah.Transforms.targets ))</SlowCheetah_NuGetImportPath>
<SlowCheetahTargets Condition=" '$(SlowCheetah_EnableImportFromNuGet)'=='true' and Exists('$(SlowCheetah_NuGetImportPath)') ">$(SlowCheetah_NuGetImportPath)</SlowCheetahTargets>
</PropertyGroup>
<PropertyGroup>
<ManifestCertificateThumbprint>2A1DE3FF5C45B89F0998B10DD5E00E6A6E93FFAE</ManifestCertificateThumbprint>
</PropertyGroup>
<PropertyGroup>
<ManifestKeyFile>GetStarted_TemporaryKey.pfx</ManifestKeyFile>
</PropertyGroup>
<PropertyGroup>
<GenerateManifests>true</GenerateManifests>
</PropertyGroup>
<PropertyGroup>
<SignManifests>false</SignManifests>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Azure.Documents.Client, Version=0.9.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Microsoft.Azure.Documents.Client.0.9.0-preview\lib\net40\Microsoft.Azure.Documents.Client.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config">
<SubType>Designer</SubType>
<TransformOnBuild>true</TransformOnBuild>
</None>
<None Include="App.Debug.config">
<DependentUpon>App.config</DependentUpon>
<IsTransformFile>True</IsTransformFile>
</None>
<None Include="App.Release.config">
<DependentUpon>App.config</DependentUpon>
<IsTransformFile>True</IsTransformFile>
</None>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.5">
<Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4.5 %28x86 and x64%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Client.3.5">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(SlowCheetahTargets)" Condition="Exists('$(SlowCheetahTargets)')" Label="SlowCheetah" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

Просмотреть файл

@ -0,0 +1,267 @@
//---------------------------------------------------------------------------------
// Microsoft (R) Azure SDK
// Software Development Kit
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
//---------------------------------------------------------------------------------
namespace DocumentDB.GetStarted
{
using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//Add DocumentDB references
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
using Newtonsoft.Json;
/// <summary>
/// This get-started sample demonstrates the creation of resources and execution of simple queries
/// For more detailed samples with best practices, visit http://code.msdn.microsoft.com/Azure-DocumentDB-NET-Code-6b3da8af
/// </summary>
public class Program
{
//Read the DocumentDB endpointUrl and authorizationKey from config file
//WARNING: Never store credentials in source code
//For more information, visit http://azure.microsoft.com/blog/2013/07/17/windows-azure-web-sites-how-application-strings-and-connection-strings-work/
private static readonly string endpointUrl = ConfigurationManager.AppSettings["EndPointUrl"];
private static readonly string authorizationKey = ConfigurationManager.AppSettings["AuthorizationKey"];
public static void Main(string[] args)
{
try
{
GetStartedDemo().Wait();
}
catch (DocumentClientException de)
{
Exception baseException = de.GetBaseException();
Console.WriteLine("{0} error occurred: {1}, Message: {2}", de.StatusCode, de.Message, baseException.Message);
}
catch (Exception e)
{
Exception baseException = e.GetBaseException();
Console.WriteLine("Error: {0}, Message: {1}", e.Message, baseException.Message);
}
finally
{
Console.WriteLine("End of demo, press any key to exit.");
Console.ReadKey();
}
}
private static async Task GetStartedDemo()
{
//Make sure to call client.Dispose() once you've finished all DocumentDB interactions
//Create a new instance of the DocumentClient
var client = new DocumentClient(new Uri(endpointUrl), authorizationKey);
//Check to verify a database with the id=FamilyRegistry does not exist
Database database = client.CreateDatabaseQuery().Where(db => db.Id == "FamilyRegistry").AsEnumerable().FirstOrDefault();
if (database == null)
{
//Create a database
database = await client.CreateDatabaseAsync(
new Database
{
Id = "FamilyRegistry"
});
}
else { Warn("database"); }
//Check to verify a document collection with the id=FamilyCollection does not exist
DocumentCollection documentCollection = client.CreateDocumentCollectionQuery(database.CollectionsLink).Where(c => c.Id == "FamilyCollection").AsEnumerable().FirstOrDefault();
if (documentCollection == null)
{
//Create a document collection
documentCollection = await client.CreateDocumentCollectionAsync(database.CollectionsLink,
new DocumentCollection
{
Id = "FamilyCollection"
});
}
else { Warn("document collection"); }
//Check to verify a document with the id=AndersenFamily does not exist
Document document = client.CreateDocumentQuery(documentCollection.DocumentsLink).Where(d => d.Id == "AndersenFamily").AsEnumerable().FirstOrDefault();
if (document == null)
{
//Create the Andersen Family document
Family AndersonFamily = new Family
{
Id = "AndersenFamily",
LastName = "Andersen",
Parents = new Parent[] {
new Parent { FirstName = "Thomas" },
new Parent { FirstName = "Mary Kay"}
},
Children = new Child[] {
new Child
{
FirstName = "Henriette Thaulow",
Gender = "female",
Grade = 5,
Pets = new [] {
new Pet { GivenName = "Fluffy" }
}
}
},
Address = new Address { State = "WA", County = "King", City = "Seattle" },
IsRegistered = true
};
await client.CreateDocumentAsync(documentCollection.DocumentsLink, AndersonFamily);
}
else { Warn("document"); }
//Check to verify a document with the id=AndersenFamily does not exist
document = client.CreateDocumentQuery(documentCollection.DocumentsLink).Where(d => d.Id == "WakefieldFamily").AsEnumerable().FirstOrDefault();
if (document == null)
{
//Create the WakeField document
Family WakefieldFamily = new Family
{
Id = "WakefieldFamily",
Parents = new[] {
new Parent { FamilyName= "Wakefield", FirstName= "Robin" },
new Parent { FamilyName= "Miller", FirstName= "Ben" }
},
Children = new Child[] {
new Child {
FamilyName= "Merriam",
FirstName= "Jesse",
Gender= "female",
Grade= 8,
Pets= new Pet[] {
new Pet { GivenName= "Goofy" },
new Pet { GivenName= "Shadow" }
}
},
new Child {
FamilyName= "Miller",
FirstName= "Lisa",
Gender= "female",
Grade= 1
}
},
Address = new Address { State = "NY", County = "Manhattan", City = "NY" },
IsRegistered = false
};
await client.CreateDocumentAsync(documentCollection.DocumentsLink, WakefieldFamily);
}
else { Warn("document"); }
//Query the documents using DocumentDB SQL for the Andersen family
foreach (var family in client.CreateDocumentQuery(documentCollection.DocumentsLink,
"SELECT * FROM Families f WHERE f.id = \"AndersenFamily\""))
{
Console.WriteLine("\tRead {0} from SQL", family);
}
//Query the documents using LINQ for the Andersen family
foreach (var family in (
from f in client.CreateDocumentQuery(documentCollection.DocumentsLink)
where f.Id == "AndersenFamily"
select f))
{
Console.WriteLine("\tRead {0} from LINQ", family);
}
//Query the documents using LINQ lambdas for the Andersen family
foreach (var family in client.CreateDocumentQuery(documentCollection.DocumentsLink)
.Where(f => f.Id == "AndersenFamily")
.Select(f => f))
{
Console.WriteLine("\tRead {0} from LINQ query", family);
}
//Query the documents using DocumentSQl with one join
var cc = client.CreateDocumentQuery<dynamic>(documentCollection.DocumentsLink,
"SELECT f.id, c.FirstName AS child " +
"FROM Families f " +
"JOIN c IN f.Children ");
foreach (var item in cc.ToList())
{
Console.WriteLine(item);
}
//Query the documents using LINQ with one join
var dd = client.CreateDocumentQuery<Family>(documentCollection.DocumentsLink)
.SelectMany(family => family.Children
.Select(children => new
{
family = family.Id,
child = children.FirstName
}));
foreach (var item in dd.ToList())
{
Console.WriteLine(item);
}
//Clean up/delete the database and client
await client.DeleteDatabaseAsync(database.SelfLink);
client.Dispose();
}
private static void Warn(string resource)
{
Console.WriteLine("Warning: A " + resource + " with the same id already exists");
Console.WriteLine("Continuing may modify the existing " + resource + ".\nPress any key to continue.");
Console.ReadKey();
Console.Clear();
}
internal sealed class Parent
{
public string FamilyName { get; set; }
public string FirstName { get; set; }
}
internal sealed class Child
{
public string FamilyName { get; set; }
public string FirstName { get; set; }
public string Gender { get; set; }
public int Grade { get; set; }
public Pet[] Pets { get; set; }
}
internal sealed class Pet
{
public string GivenName { get; set; }
}
internal sealed class Address
{
public string State { get; set; }
public string County { get; set; }
public string City { get; set; }
}
internal sealed class Family
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
public string LastName { get; set; }
public Parent[] Parents { get; set; }
public Child[] Children { get; set; }
public Address Address { get; set; }
public bool IsRegistered { get; set; }
}
}
}

Просмотреть файл

@ -0,0 +1,36 @@
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("DocDBGetStarted")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DocDBGetStarted")]
[assembly: AssemblyCopyright("Copyright © 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("924fb665-a025-4b38-a92a-ca3dae3de12f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Просмотреть файл

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Azure.Documents.Client" version="0.9.0-preview" targetFramework="net45" />
<package id="Newtonsoft.Json" version="4.5.11" targetFramework="net45" />
</packages>