Last active
August 29, 2015 14:18
-
-
Save jpda/0e2680432a73e3eaa574 to your computer and use it in GitHub Desktop.
Attribute Metadata Silliness
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public async static void AddDocuments<T>(IList<T> things) where T : class, new() | |
{ | |
var indexClient = new SearchIndexClient(ConfigurationManager.AppSettings["SearchServiceName"], things.First().GetType().Name.ToLower(), new SearchCredentials(ConfigurationManager.AppSettings["SearchServiceApiKey"])); | |
try | |
{ | |
Trace.WriteLine($"Adding {things.Count()} documents to the index..."); | |
var thingsToIndex = things.Where(x => x.GetType().GetProperties().Any(prop => prop.GetCustomAttribute<IndexMetadataAttribute>() != null)); | |
var newThings = thingsToIndex.Select(x => | |
{ | |
var props = x.GetType().GetProperties().Where(y => y.GetCustomAttribute<IndexMetadataAttribute>() != null); | |
var newThing = new ExpandoObject() as IDictionary<string, object>; | |
foreach (var p in props) | |
{ | |
var propertyValue = p.GetValue(x); | |
if (p.GetCustomAttribute<IndexMetadataAttribute>().IsKey) | |
{ | |
propertyValue = (propertyValue as string).Base64UrlEncode(); | |
} | |
newThing[p.Name] = propertyValue; | |
} | |
return newThing; | |
}); | |
await indexClient.Documents.IndexAsync(IndexBatch.Create(newThings.Select(IndexAction.Create))); | |
Trace.WriteLine("finished adding documents to index"); | |
} | |
catch (IndexBatchException e) | |
{ | |
Trace.WriteLine("Failed to index some of the documents: {0}", String.Join(", ", e.IndexResponse.Results.Where(r => !r.Succeeded).Select(r => r.Key))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment