I am trying to fetch all the available queries under a project using the below REST call
https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/queries/list?view=azure-devops-rest-5.0#uri-parameters
It needs a depth parameter to be passed if not only the First level of queries are returned and it seems the maximum allowed value for depth is 2 .
If i have 3 levels of folder structure in queries even this depth wont help.
So how to retrieve all the queries irrespective of levels ?
TIA
As workaround you can use Microsoft.TeamFoundationServer.Client and explore queries structure with depth 1. Example:
static void GetAllWorkItemQueries(string project)
{
List<QueryHierarchyItem> rootQueries = WitClient.GetQueriesAsync(project, QueryExpand.All).Result;
GetFolderContent(project, rootQueries);
}
/// <summary>
/// Get Content from Query Folders
/// </summary>
/// <param name="project">Team Project Name</param>
/// <param name="queries">Folder List</param>
static void GetFolderContent(string project, List<QueryHierarchyItem> queries)
{
foreach(QueryHierarchyItem query in queries)
{
if (query.IsFolder != null && (bool)query.IsFolder)
{
Console.WriteLine("Folder: " + query.Path);
if ((bool)query.HasChildren)
{
QueryHierarchyItem detiledQuery = WitClient.GetQueryAsync(project, query.Path, QueryExpand.All, 1).Result;
GetFolderContent(project, detiledQuery.Children.ToList());
}
}
else
Console.WriteLine("Query: " + query.Path);
}
}
Full sample project here: https://github.com/ashamrai/TFRestApi/tree/master/04.TFRestApiAppWorkItemQueries
You also can do it with client API, simple code:
static void GetQueryClientAPI()
{
VssCredentials Credentials = new VssCredentials(new Microsoft.VisualStudio.Services.Common.VssBasicCredential(string.Empty, "Personal access token"));
TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri("devops url"), Credentials);
tpc.EnsureAuthenticated();
WorkItemStore wis = tpc.GetService(typeof(WorkItemStore)) as WorkItemStore;
QueryHierarchy qh = wis.Projects["project name"].QueryHierarchy;
foreach(QueryItem q in qh)
{
GetChildQuery(q);
}
Console.Read();
}
static void GetChildQuery(QueryItem query)
{
if (query is QueryFolder)
{
QueryFolder queryFolder = query as QueryFolder;
foreach (var q in queryFolder)
{
GetChildQuery(q);
}
}
else
{
QueryDefinition querydef = query as QueryDefinition;
Console.WriteLine(querydef.Name + " -- " + querydef.Path);
}
}
Result:
Related
I added a new ADO.NET ORM object inside my project based on an already existing database. I was able to create a new object but I don't quite understand how to insert my new object in the database and get the ID generated from it.
From the example shown in the link, I just don't understand what is their TestDBEntities Class
I am also opened to any ORM suggestion based off experience! Thanks!
public static void Insert_Demande_Willy(string ModelPath)
{
using (TestDBEntities ctx = new TestDBEntities())
{
Model.CreateDessin newDemande = new CreateDessin()
{
DateProduite = DateTime.Now,
GenerateBom = Willy.Properties.Settings.Default.GenerateBom.ToString(),
MailAdress = Willy.Properties.Settings.Default.Email,
NotifyRBRE = Willy.Properties.Settings.Default.Wilma_RBRE.ToString(),
NotifyRBTK = Willy.Properties.Settings.Default.Wilma_RBTK.ToString(),
NotifyTLS = Willy.Properties.Settings.Default.Wilma_TLS.ToString(),
NotifyTQ = Willy.Properties.Settings.Default.Wilma_TQ.ToString(),
PathDessin = ModelPath,
SendingComputer = Environment.MachineName,
UserName = Environment.UserName
};
Insert_Demande_Willy_DTL(newDe)
}
}
/// <summary>
/// Importer Statuts enumeration
/// Setter priorité
/// NoECO juste quand check?
/// IF DEV TESTED BY
/// </summary>
/// <param name="ID"></param>
private static void Insert_Demande_Willy_DTL(int ID)
{
Model.CreateDessinDTL newDemandeDTL = new CreateDessinDTL()
{
ConfigName = "",
CreatePDF = Willy.Properties.Settings.Default.GeneratePDF.ToString(),
C_ID = ID,
NoECO = Willy.Properties.Settings.Default.EcoName,
Priority = 2,
Statut = "Willy2",
};
}
Source 1
Source 2
Agree with the above commentor. EF6 is very nice. Also--I am pretty new to EF6, but I believe that you can set it up to work in a code first way on an already existing database, as in you can use EFPowerTools to generate your models, and then any changes that you make to your code will be automatically updated in your database.
https://msdn.microsoft.com/en-us/library/jj200620(v=vs.113).aspx
I somehow found a way to make this thing work. Unfortunately, some members of some objects won't show with Intellisence.
/// <summary>
/// Setter priorité
/// NoECO juste quand check?
/// </summary>
/// <param name="ID"></param>
private static void Insert_Demande_Willy_DTL(int ID)
{
{
DemoInfo_IndusEntities context = new DemoInfo_IndusEntities();
context.CreateDessinDTL.Add(new CreateDessinDTL_Demo()
{
ConfigName = "",
C_ID = ID,
NoECO = Willy.Properties.Settings.Default.EcoName,
Priority = 2,
Statut = AppConfig.Controller.Statuts.Willy.Willy2,
TestedBy = Environment.UserName
//CreatePDF = Willy.Properties.Settings.Default.GeneratePDF.ToString(),
});
context.SaveChanges();
}}
I am trying to use code that I got from github: https://github.com/liamca/azure-search-machine-learning-text-analytics and the creating of an index works perfect, but the Keyphrase portion is giving me a 403 - Forbidden: Access is denied error. This happens in the TextExtractionHelper class on the following line of code:
if (!response.IsSuccessStatusCode)
{
throw new Exception("Call to get key phrases failed with HTTP status code: " +
response.StatusCode + " and contents: " + content);
}
Based on the information in the comments, I created an account at this link: https://datamarket.azure.com/account/keys and used the key that it provided, but I am getting the above error.
Here is the code in case you do not want to download from github:
class Program
{
static string searchServiceName = "<removed>"; // Learn more here: https://azure.microsoft.com/en-us/documentation/articles/search-what-is-azure-search/
static string searchServiceAPIKey = "<removed>";
static string azureMLTextAnalyticsKey = "<removed>"; // Learn more here: https://azure.microsoft.com/en-us/documentation/articles/machine-learning-apps-text-analytics/
static string indexName = "textanalytics";
static SearchServiceClient serviceClient = new SearchServiceClient(searchServiceName, new SearchCredentials(searchServiceAPIKey));
static SearchIndexClient indexClient = serviceClient.Indexes.GetClient(indexName);
static void Main(string[] args)
{
string filetext = "Build great search experiences for your web and mobile apps. " +
"Many applications use search as the primary interaction pattern for their users. When it comes to search, user expectations are high. They expect great relevance, suggestions, near-instantaneous responses, multiple languages, faceting, and more. Azure Search makes it easy to add powerful and sophisticated search capabilities to your website or application. The integrated Microsoft natural language stack, also used in Bing and Office, has been improved over 16 years of development. Quickly and easily tune search results, and construct rich, fine-tuned ranking models to tie search results to business goals. Reliable throughput and storage provide fast search indexing and querying to support time-sensitive search scenarios. " +
"Reduce complexity with a fully managed service. " +
"Azure Search removes the complexity of setting up and managing your own search index. This fully managed service helps you avoid the hassle of dealing with index corruption, service availability, scaling, and service updates. Create multiple indexes with no incremental cost per index. Easily scale up or down as the traffic and data volume of your application changes.";
// Note, this will create a new Azure Search Index for the text and the key phrases
Console.WriteLine("Creating Azure Search index...");
AzureSearch.CreateIndex(serviceClient, indexName);
// Apply the Machine Learning Text Extraction to retrieve only the key phrases
Console.WriteLine("Extracting key phrases from processed text... \r\n");
KeyPhraseResult keyPhraseResult = TextExtraction.ProcessText(azureMLTextAnalyticsKey, filetext);
Console.WriteLine("Found the following phrases... \r\n");
foreach (var phrase in keyPhraseResult.KeyPhrases)
Console.WriteLine(phrase);
// Take the resulting key phrases to a new Azure Search Index
// It is highly recommended that you upload documents in batches rather
// individually like is done here
Console.WriteLine("Uploading extracted text to Azure Search...\r\n");
AzureSearch.UploadDocuments(indexClient, "1", keyPhraseResult);
Console.WriteLine("Wait 5 seconds for content to become searchable...\r\n");
Thread.Sleep(5000);
// Execute a test search
Console.WriteLine("Execute Search...");
AzureSearch.SearchDocuments(indexClient, "Azure Search");
Console.WriteLine("All done. Press any key to continue.");
Console.ReadLine();
}
}
The below is in the TextExtractionHelper class:
/// <summary>
/// This is a sample program that shows how to use the Azure ML Text Analytics app (https://datamarket.azure.com/dataset/amla/text-analytics)
/// </summary>
public class TextExtraction
{
private const string ServiceBaseUri = "https://api.datamarket.azure.com/";
public static KeyPhraseResult ProcessText(string accountKey, string inputText)
{
KeyPhraseResult keyPhraseResult = new KeyPhraseResult();
using (var httpClient = new HttpClient())
{
string inputTextEncoded = HttpUtility.UrlEncode(inputText);
httpClient.BaseAddress = new Uri(ServiceBaseUri);
string creds = "AccountKey:" + accountKey;
string authorizationHeader = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(creds));
httpClient.DefaultRequestHeaders.Add("Authorization", authorizationHeader);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// get key phrases
string keyPhrasesRequest = "data.ashx/amla/text-analytics/v1/GetKeyPhrases?Text=" + inputTextEncoded;
Task<HttpResponseMessage> responseTask = httpClient.GetAsync(keyPhrasesRequest);
responseTask.Wait();
HttpResponseMessage response = responseTask.Result;
Task<string> contentTask = response.Content.ReadAsStringAsync();
contentTask.Wait();
string content = contentTask.Result;
if (!response.IsSuccessStatusCode)
{
throw new Exception("Call to get key phrases failed with HTTP status code: " +
response.StatusCode + " and contents: " + content);
}
keyPhraseResult = JsonConvert.DeserializeObject<KeyPhraseResult>(content);
}
return keyPhraseResult;
}
}
/// <summary>
/// Class to hold result of Key Phrases call
/// </summary>
public class KeyPhraseResult
{
public List<string> KeyPhrases { get; set; }
}
/// <summary>
/// Class to hold result of Sentiment call
/// </summary>
public class SentimentResult
{
public double Score { get; set; }
}
/// <summary>
/// Class to hold result of Language detection call
/// </summary>
public class LanguageResult
{
public bool UnknownLanguage { get; set; }
public IList<DetectedLanguage> DetectedLanguages { get; set; }
}
/// <summary>
/// Class to hold information about a single detected language
/// </summary>
public class DetectedLanguage
{
public string Name { get; set; }
/// <summary>
/// This is the short ISO 639-1 standard form of representing
/// all languages. The short form is a 2 letter representation of the language.
/// en = English, fr = French for example
/// </summary>
public string Iso6391Name { get; set; }
public double Score { get; set; }
}
UPDATE
After many hours of taking different sample code and trying to put them together, I finally got something "kind of" working. Here is all my code:
class Program
{
static string searchServiceName = "<removed>"; // Learn more here: https://azure.microsoft.com/en-us/documentation/articles/search-what-is-azure-search/
static string searchServiceAPIKey = "<removed>";
//static string azureMLTextAnalyticsKey = "<removed>"; // Learn more here: https://azure.microsoft.com/en-us/documentation/articles/machine-learning-apps-text-analytics/
static string indexName = "textanalytics";
static SearchServiceClient serviceClient = new SearchServiceClient(searchServiceName, new SearchCredentials(searchServiceAPIKey));
static SearchIndexClient indexClient = serviceClient.Indexes.GetClient(indexName);
static void Main()
{
MakeRequests();
Console.WriteLine("Hit ENTER to exit...");
Console.ReadLine();
}
static async void MakeRequests()
{
// Note, this will create a new Azure Search Index for the text and the key phrases
Console.WriteLine("Creating Azure Search index...");
AzureSearch.CreateIndex(serviceClient, indexName);
// Apply the Machine Learning Text Extraction to retrieve only the key phrases
Console.WriteLine("Extracting key phrases from processed text... \r\n");
KeyPhraseResult keyPhraseResult = await TextExtraction.ProcessText();
Console.WriteLine("Found the following phrases... \r\n");
foreach (var phrase in keyPhraseResult.KeyPhrases)
Console.WriteLine(phrase);
// Take the resulting key phrases to a new Azure Search Index
// It is highly recommended that you upload documents in batches rather
// individually like is done here
Console.WriteLine("Uploading extracted text to Azure Search...\r\n");
AzureSearch.UploadDocuments(indexClient, "1", keyPhraseResult);
Console.WriteLine("Wait 5 seconds for content to become searchable...\r\n");
Thread.Sleep(5000);
// Execute a test search
Console.WriteLine("Execute Search...");
AzureSearch.SearchDocuments(indexClient, "Azure Search");
Console.WriteLine("All done. Press any key to continue.");
Console.ReadLine();
}
}
Here is my TextExtractionHelper class:
public class TextExtraction
{
static string azureMLTextAnalyticsKey = "<Removed>"; // Learn more here: https://azure.microsoft.com/en-us/documentation/articles/machine-learning-apps-text-analytics/
private const string ServiceBaseUri = "https://westus.api.cognitive.microsoft.com/";
public static async Task<KeyPhraseResult> ProcessText()
{
string filetext = "Build great search experiences for your web and mobile apps. " +
"Many applications use search as the primary interaction pattern for their users. When it comes to search, user expectations are high. They expect great relevance, suggestions, near-instantaneous responses, multiple languages, faceting, and more. Azure Search makes it easy to add powerful and sophisticated search capabilities to your website or application. The integrated Microsoft natural language stack, also used in Bing and Office, has been improved over 16 years of development. Quickly and easily tune search results, and construct rich, fine-tuned ranking models to tie search results to business goals. Reliable throughput and storage provide fast search indexing and querying to support time-sensitive search scenarios. " +
"Reduce complexity with a fully managed service. " +
"Azure Search removes the complexity of setting up and managing your own search index. This fully managed service helps you avoid the hassle of dealing with index corruption, service availability, scaling, and service updates. Create multiple indexes with no incremental cost per index. Easily scale up or down as the traffic and data volume of your application changes.";
KeyPhraseResult keyPhraseResult = new KeyPhraseResult();
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(ServiceBaseUri);
// Request headers.
httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", azureMLTextAnalyticsKey);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
byte[] byteData = Encoding.UTF8.GetBytes("{\"documents\":[" +
"{\"id\":\"1\",\"text\":\"" + filetext + "\"},]}");
//byte[] byteData = Encoding.UTF8.GetBytes("{\"documents\":[" +
// "{\"id\":\"1\",\"text\":\"Build great search experiences for your web and mobile apps." +
// "Many applications use search as the primary interaction pattern for their users. When it comes to search, user expectations are high. They expect great relevance, suggestions, near-instantaneous responses, multiple languages, faceting, and more. Azure Search makes it easy to add powerful and sophisticated search capabilities to your website or application. The integrated Microsoft natural language stack, also used in Bing and Office, has been improved over 16 years of development. Quickly and easily tune search results, and construct rich, fine-tuned ranking models to tie search results to business goals. Reliable throughput and storage provide fast search indexing and querying to support time-sensitive search scenarios." +
// "Reduce complexity with a fully managed service. " +
// "Azure Search removes the complexity of setting up and managing your own search index. This fully managed service helps you avoid the hassle of dealing with index corruption, service availability, scaling, and service updates. Create multiple indexes with no incremental cost per index. Easily scale up or down as the traffic and data volume of your application changes.\"}," +
// "]}");
// Detect key phrases:
var keyPhrasesRequest = "text/analytics/v2.0/keyPhrases";
//var response = await CallEndpoint(httpClient, uri, byteData);
// get key phrases
using (var getcontent = new ByteArrayContent(byteData))
{
getcontent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await httpClient.PostAsync(keyPhrasesRequest, getcontent);
Task<string> contentTask = response.Content.ReadAsStringAsync();
string content = contentTask.Result;
if (!response.IsSuccessStatusCode)
{
throw new Exception("Call to get key phrases failed with HTTP status code: " +
response.StatusCode + " and contents: " + content);
}
keyPhraseResult = JsonConvert.DeserializeObject<KeyPhraseResult>(content);
//return await response.Content.ReadAsStringAsync();
}
}
return keyPhraseResult;
}
}
/// <summary>
/// Class to hold result of Key Phrases call
/// </summary>
public class KeyPhraseResult
{
public List<string> KeyPhrases { get; set; }
}
/// <summary>
/// Class to hold result of Sentiment call
/// </summary>
public class SentimentResult
{
public double Score { get; set; }
}
/// <summary>
/// Class to hold result of Language detection call
/// </summary>
public class LanguageResult
{
public bool UnknownLanguage { get; set; }
public IList<DetectedLanguage> DetectedLanguages { get; set; }
}
/// <summary>
/// Class to hold information about a single detected language
/// </summary>
public class DetectedLanguage
{
public string Name { get; set; }
/// <summary>
/// This is the short ISO 639-1 standard form of representing
/// all languages. The short form is a 2 letter representation of the language.
/// en = English, fr = French for example
/// </summary>
public string Iso6391Name { get; set; }
public double Score { get; set; }
}
So I am now able to pull the KeyPhrases from the text! But, now I am sitting with a problem where it doesnt seem like the JSON string is being deserialized and my keyPhraseResult is now getting a null value.
What am I missing ?
If anyone is able to help, I would greatly appreciate it.
Thanks!
So I got it working! With the help from this link: Deserializing JSON using C# to return items, which i posted to simplify where my issue was occurring now.
So what this code is doing is the following:
Creating an Index in Azure called textanalytics.
Creating a JSON string of the text provided.
Retrieving the KeyPhrases and adding these to the Index created in point 1 above.
Below is my entire code, in case it helps someone else:
(Please ensure that you add the relevant references from Nuget packages: Microsoft.Azure.Search and Newtonsoft.Json)
Program.cs(This is a console application):
using Microsoft.Azure.Search;
using System;
using System.Configuration;
using System.IO;
using System.Threading;
namespace AzureSearchTextAnalytics
{
class Program
{
static string searchServiceName = "<removed>"; // This is the Azure Search service name that you create in Azure
static string searchServiceAPIKey = "<removed>"; // This is the Primary key that is provided after creating a Azure Search Service
static string indexName = "textanalytics";
static SearchServiceClient serviceClient = new SearchServiceClient(searchServiceName, new SearchCredentials(searchServiceAPIKey));
static SearchIndexClient indexClient = serviceClient.Indexes.GetClient(indexName);
static void Main()
{
MakeRequests();
Console.WriteLine("Hit ENTER to exit...");
Console.ReadLine();
}
static async void MakeRequests()
{
// Note, this will create a new Azure Search Index for the text and the key phrases
Console.WriteLine("Creating Azure Search index...");
AzureSearch.CreateIndex(serviceClient, indexName);
// Apply the Machine Learning Text Extraction to retrieve only the key phrases
Console.WriteLine("Extracting key phrases from processed text... \r\n");
KeyPhraseResult keyPhraseResult = await TextExtraction.ProcessText();
Console.WriteLine("Found the following phrases... \r\n");
foreach (var phrase in keyPhraseResult.KeyPhrases)
Console.WriteLine(phrase);
// Take the resulting key phrases to a new Azure Search Index
// It is highly recommended that you upload documents in batches rather
// individually like is done here
Console.WriteLine("Uploading extracted text to Azure Search...\r\n");
AzureSearch.UploadDocuments(indexClient, "1", keyPhraseResult);
Console.WriteLine("Wait 5 seconds for content to become searchable...\r\n");
Thread.Sleep(5000);
// Execute a test search
Console.WriteLine("Execute Search...");
AzureSearch.SearchDocuments(indexClient, "Azure Search");
Console.WriteLine("All done. Press any key to continue.");
Console.ReadLine();
}
}
}
My TextExtractionHelper.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json;
using System.Configuration; // get it from http://www.newtonsoft.com/json
using Newtonsoft.Json.Linq;
namespace AzureSearchTextAnalytics
{
/// </summary>
public class TextExtraction
{
static string azureMLTextAnalyticsKey = "<removed>"; // This key you will get when you have added TextAnalytics in Azure.
private const string ServiceBaseUri = "https://westus.api.cognitive.microsoft.com/"; //This you will get when you have added TextAnalytics in Azure
public static async Task<KeyPhraseResult> ProcessText()
{
string filetext = "Build great search experiences for your web and mobile apps. " +
"Many applications use search as the primary interaction pattern for their users. When it comes to search, user expectations are high. They expect great relevance, suggestions, near-instantaneous responses, multiple languages, faceting, and more. Azure Search makes it easy to add powerful and sophisticated search capabilities to your website or application. The integrated Microsoft natural language stack, also used in Bing and Office, has been improved over 16 years of development. Quickly and easily tune search results, and construct rich, fine-tuned ranking models to tie search results to business goals. Reliable throughput and storage provide fast search indexing and querying to support time-sensitive search scenarios. " +
"Reduce complexity with a fully managed service. " +
"Azure Search removes the complexity of setting up and managing your own search index. This fully managed service helps you avoid the hassle of dealing with index corruption, service availability, scaling, and service updates. Create multiple indexes with no incremental cost per index. Easily scale up or down as the traffic and data volume of your application changes.";
KeyPhraseResult keyPhraseResult = new KeyPhraseResult();
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(ServiceBaseUri);
// Request headers.
httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", azureMLTextAnalyticsKey);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
byte[] byteData = Encoding.UTF8.GetBytes("{\"documents\":[" +
"{\"id\":\"1\",\"text\":\"" + filetext + "\"},]}");
// Detect key phrases:
var keyPhrasesRequest = "text/analytics/v2.0/keyPhrases";
// get key phrases
using (var getcontent = new ByteArrayContent(byteData))
{
getcontent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await httpClient.PostAsync(keyPhrasesRequest, getcontent);
Task<string> contentTask = response.Content.ReadAsStringAsync();
string content = contentTask.Result;
if (!response.IsSuccessStatusCode)
{
throw new Exception("Call to get key phrases failed with HTTP status code: " +
response.StatusCode + " and contents: " + content);
}
var result = JsonConvert.DeserializeObject<RootObject>(content);
keyPhraseResult.KeyPhrases = result.documents[0].keyPhrases;
}
}
return keyPhraseResult;
}
}
public class Documents
{
public List<string> keyPhrases { get; set; }
public string id { get; set; }
}
public class RootObject
{
public List<Documents> documents { get; set; }
public List<object> errors { get; set; }
}
/// <summary>
/// Class to hold result of Key Phrases call
/// </summary>
public class KeyPhraseResult
{
public List<string> KeyPhrases { get; set; }
}
}
AzureSearch.cs:
using Microsoft.Azure.Search;
using Microsoft.Azure.Search.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AzureSearchTextAnalytics
{
public class AzureSearch
{
public static void CreateIndex(SearchServiceClient serviceClient, string indexName)
{
if (serviceClient.Indexes.Exists(indexName))
{
serviceClient.Indexes.Delete(indexName);
}
var definition = new Index()
{
Name = indexName,
Fields = new[]
{
new Field("fileId", DataType.String) { IsKey = true },
new Field("fileText", DataType.String) { IsSearchable = true, IsFilterable = false, IsSortable = false, IsFacetable = false },
new Field("keyPhrases", DataType.Collection(DataType.String)) { IsSearchable = true, IsFilterable = true, IsFacetable = true }
}
};
serviceClient.Indexes.Create(definition);
}
public static void UploadDocuments(SearchIndexClient indexClient, string fileId, KeyPhraseResult keyPhraseResult)
{
List<IndexAction> indexOperations = new List<IndexAction>();
var doc = new Document();
doc.Add("fileId", fileId);
doc.Add("keyPhrases", keyPhraseResult.KeyPhrases.ToList());
indexOperations.Add(IndexAction.Upload(doc));
try
{
indexClient.Documents.Index(new IndexBatch(indexOperations));
}
catch (IndexBatchException e)
{
// Sometimes when your Search service is under load, indexing will fail for some of the documents in
// the batch. Depending on your application, you can take compensating actions like delaying and
// retrying. For this simple demo, we just log the failed document keys and continue.
Console.WriteLine(
"Failed to index some of the documents: {0}",
String.Join(", ", e.IndexingResults.Where(r => !r.Succeeded).Select(r => r.Key)));
}
}
public static void SearchDocuments(SearchIndexClient indexClient, string searchText)
{
// Search using the supplied searchText and output documents that match
try
{
var sp = new SearchParameters();
DocumentSearchResult<OCRTextIndex> response = indexClient.Documents.Search<OCRTextIndex>(searchText, sp);
foreach (SearchResult<OCRTextIndex> result in response.Results)
{
Console.WriteLine("File ID: {0}", result.Document.fileId);
Console.WriteLine("Key Phrases: {0}", string.Join(",", result.Document.keyPhrases));
}
}
catch (Exception e)
{
Console.WriteLine("Failed search: {0}", e.Message.ToString());
}
}
}
}
DataModel.cs
using Microsoft.Azure.Search.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AzureSearchTextAnalytics
{
[SerializePropertyNamesAsCamelCase]
public class OCRTextIndex
{
public string fileId { get; set; }
public string[] keyPhrases { get; set; }
}
}
I am having with using Aspose to generate dynamic content in slides within Microsoft CRM Dynamics 2011. The data is not populating correctly for several fields and relationals even though the logic in the code seems to be correct and should not yield a null or empty value, and I have confirmed there is indeed data for the fields in the database (The data does populate correctly for some of the fields and relationals). All of these issues occur before the powerpoint itself even starts to be generated, so in reality the issues may not be “Aspose” issues they may just be Web Service / CRM issues with retrieving the data asynchronously.
Aspose Slide Workflow:
1) An HTML web resource includes a Silverlight button to download powerpoint report
2) On button click the Silverlight application Asyncronosously collects all the data needed from the Project entity in CRM through web service requests
3) The data is compiled into a Project class that is then passed over to the ReportGenerator Service and uses the data to populate the parts of the powerpoint (This is the part where we use the custom Aspose stuff)
4) Aspose functionality goes through each specified slide and parses them adding in the data where required.
5) Powerpoint is completed and spit out for the user with the data populated.
These are two examples of where I am having troubles getting data to populate. The project.Pwins value below ends up being null which tells me the lambda expression is not executing appropriately, it remains null at the end of the method which tells me the highlighted line is not even being executed at all.
Example 1:
/// <summary>
/// Retrieves and stores information required for P(win) report, and then tries to send a web service request.
/// </summary>
/// <param name="service"></param>
private void LoadPwin(ReportServiceClient service)
{
string filter = string.Format("?$filter=sfa_Project/Id eq guid'{0}'", GetProjectId());
string url = GetEntitySetAddress("sfa_pwin_competitor") + filter;
WebClient client = new WebClient();
client.DownloadStringCompleted += (sender, args) =>
{
if (args.Error == null)
{
StringReader stream = new StringReader(args.Result);
XmlReader reader = XmlReader.Create(stream);
List<PWin> pwins = new List<PWin>();
List<Dictionary<string, string>> dictionaries = LoadEntitiesFromXml(reader);
foreach (Dictionary<string, string> dictionary in dictionaries)
{
PWin pwin = new PWin();
pwin.CompanyName = ParseDictionaryValue(dictionary["sfa_competitor"]);
pwin.IsBoeing = (ParseDictionaryValue(dictionary["sfa_is_boeing"]) == "true");
pwin.IsDomestic = (ParseDictionaryValue(dictionary["sfa_domestic_or_international"]) == "true");
pwin.AffordabilityWeight = ParseDictionaryValueToNumber(dictionary["sfa_affordability_weight"]);
pwin.AffordabilityScore = ParseDictionaryValueToNumber(dictionary["sfa_affordability_score"]);
pwin.CustomerRelationshipWeight = ParseDictionaryValueToNumber(dictionary["sfa_customer_relationship_weight"]);
pwin.CustomerRelationshipScore = ParseDictionaryValueToNumber(dictionary["sfa_customer_relationship_score"]);
pwin.CustomerAdvantageWeight = ParseDictionaryValueToNumber(dictionary["sfa_customer_advantage_weight"]);
pwin.CustomerAdvantageScore = ParseDictionaryValueToNumber(dictionary["sfa_customer_advantage_score"]);
pwin.CompetitionWeight = ParseDictionaryValueToNumber(dictionary["sfa_competition_weight"]);
pwin.CompetitionScore = ParseDictionaryValueToNumber(dictionary["sfa_competition_score"]);
pwin.CPOBCWeight = ParseDictionaryValueToNumber(dictionary["sfa_cpobc_weight"]);
pwin.CPOBCScore = ParseDictionaryValueToNumber(dictionary["sfa_cpobc_score"]);
pwin.CompanyResourcesWeight = ParseDictionaryValueToNumber(dictionary["sfa_company_resources_weight"]);
pwin.CompanyResourcesScore = ParseDictionaryValueToNumber(dictionary["sfa_company_resources_score"]);
pwin.CompanyResourcesInvestmentWeight = ParseDictionaryValueToNumber(dictionary["sfa_company_resources_investment_weight"]);
pwin.CompanyResourcesInvestmentScore = ParseDictionaryValueToNumber(dictionary["sfa_company_resources_investment_score"]);
pwin.ProgramBackgroundWeight = ParseDictionaryValueToNumber(dictionary["sfa_program_background_weight"]);
pwin.ProgramBackgroundScore = ParseDictionaryValueToNumber(dictionary["sfa_program_background_score"]);
pwin.ContinuityOfEffortWeight = ParseDictionaryValueToNumber(dictionary["sfa_continuity_of_effort_weight"]);
pwin.ContinuityOfEffortScore = ParseDictionaryValueToNumber(dictionary["sfa_continuity_of_effort_score"]);
pwin.ExecutionWeight = ParseDictionaryValueToNumber(dictionary["sfa_execution_weight"]);
pwin.ExecutionScore = ParseDictionaryValueToNumber(dictionary["sfa_execution_score"]);
pwin.TechnicalSolutionWeight = ParseDictionaryValueToNumber(dictionary["sfa_technical_solution_weight"]);
pwin.TechnicalSolutionScore = ParseDictionaryValueToNumber(dictionary["sfa_technical_solution_score"]);
pwin.StrategyToWinWeight = ParseDictionaryValueToNumber(dictionary["sfa_strategy_to_win_weight"]);
pwin.StrategyToWinScore = ParseDictionaryValueToNumber(dictionary["sfa_strategy_to_win_score"]);
pwin.ManagementStrengthWeight = ParseDictionaryValueToNumber(dictionary["sfa_management_strength_weight"]);
pwin.ManagementStrengthScore = ParseDictionaryValueToNumber(dictionary["sfa_management_strength_score"]);
pwin.CustomerPercievedCommitmentWeight = ParseDictionaryValueToNumber(dictionary["sfa_customers_percieved_commitment_weight"]);
pwin.CustomerPercievedCommitmentScore = ParseDictionaryValueToNumber(dictionary["sfa_customers_percieved_commitment_score"]);
pwin.PastPerformanceWeight = ParseDictionaryValueToNumber(dictionary["sfa_past_performance_weight"]);
pwin.PastPerformanceScore = ParseDictionaryValueToNumber(dictionary["sfa_past_performance_score"]);
pwin.RawPWin = ParseDictionaryValueToDecimal(dictionary["sfa_pwin_score"]);
pwin.RelativePWin = ParseDictionaryValueToDecimal(dictionary["sfa_relative_pwin_score"]);
pwins.Add(pwin);
}
project.PWins = new ObservableCollection<PWin>(pwins);
PwinReady = true;
reader.Close();
TrySendRequest(service);
}
};
client.DownloadStringAsync(new Uri(url));
}
Example 2 the project.TeamMembers value below ends up being null:
/// <summary>
/// Retrieves and stores information required for Capture Team Roster report, and then tries to send a web service request.
/// </summary>
/// <param name="service"></param>
private void LoadCaptureTeamRoster(ReportServiceClient service)
{
string filter = string.Format("?$select=sfa_name,sfa_Role&$filter=sfa_Project/Id eq guid'{0}'", GetProjectId());
string url = GetEntitySetAddress("sfa_team_roster") + filter;
WebClient client = new WebClient();
client.DownloadStringCompleted += (sender, args) =>
{
if (args.Error == null)
{
StringReader stream = new StringReader(args.Result);
XmlReader reader = XmlReader.Create(stream);
List<TeamMember> members = new List<TeamMember>();
List<Dictionary<string, string>> dictionaries = LoadEntitiesFromXml(reader);
foreach (Dictionary<string, string> dictionary in dictionaries)
{
TeamMember member = new TeamMember();
member.Name = ParseDictionaryValue(dictionary["sfa_name"]);
member.Role = ParseDictionaryValue(dictionary["sfa_role"]);
members.Add(member);
}
project.TeamMembers = new ObservableCollection<TeamMember>(members);
CaptureTeamRosterReady = true;
reader.Close();
TrySendRequest(service);
}
};
client.DownloadStringAsync(new Uri(url));
}
Here is another example that is not an issue with a relational, but instead is an issue with a field populated on a project entity in CRM that shows up empty after retrieving the data. Both CaptureTeamLeader and ProgramManager end up being empty strings, however the ProjectName and ProjectNumber have no troubles populating
private void LoadCampaignTitle(ReportServiceClient service)
{
project.ProjectName = GetAttributeValue("sfa_name");
project.ProjectNumber = GetAttributeValue("sfa_project_number");
project.CaptureTeamLeader = GetAttributeValue("sfa_capture_team_leader_emp");
project.ProgramManager = GetAttributeValue("sfa_program_manager_emp");
CampaignTitleReady = true;
TrySendRequest(service);
}
Any help would be greatly appreciated. Thanks in advance!
EDIT:
This is the AttributeValue method asked for:
/// <summary>
/// Gets the value of provided attribute from the current page's Xrm data. If for any reason the retrieval fails, returns an empty string.
/// </summary>
/// <param name="attributeName"></param>
/// <returns></returns>
private string GetAttributeValue(string attributeName)
{
// NOTE: This is the preferred way to retrieve data from the CRM. However for some unknown issue,
// this always returns NULL. It will be replaced with directly calling .eval to the window object.
// dynamic Xrm = (ScriptObject)HtmlPage.Window.GetProperty("window.parent.Xrm");
try
{
return HtmlPage.Window.Invoke("getAttributeValue", attributeName).ToString();
}
catch (ArgumentNullException)
{
return string.Empty;
}
catch (ArgumentException)
{
return string.Empty;
}
catch (InvalidOperationException)
{
return string.Empty;
}
}
The solution to this problem was that number 1 The downloadstringasync and other places in my code were doing things asynchronously and therefore the debugger was throwing me off and showing things as null when they were really just being executed later. The actual fix required some changes to a client.xml file in the folder the webservice was being hosted from.
I´ve searched for some topics, but did not find a concrete solution to my problem.
My app is a c# commercial app. I´m using EF 4.1 database first. I generate the model from a development database connection and that create a Model.edmx file and all EF stuff pretty fine.
My goal is to deliver an appplication to the customer and let him freely create the database and database user at his own. Do do it, at runtime I would get the username, password, database connection and schema name parameters to connect to customer database. In that way, to deploy the application all I need is to ask the customer to create a database and add the database parameters to the app config file.
So, myy goal is to change the connection string and schema parameter at runtime, without changing att all the auto generated edmx file, not touching the VS generated code.
I have looked around and found:
For EF earlier versions:
Changing schema name on runtime - Entity Framework
http://efmodeladapter.codeplex.com
All other posts are going around that. I tryed even to use the first post code with no success.
But I´ve seen that EF 4.1 comes with better support tools to do it, but I could not find references or examples to it. It´s important not to change the auto generated code from VS.
I´m pretty new to EF, so I would like to ask for help on accomplish the following tasks:
a) Change connection string at runtime adding my username, password and database server/port parameters
b) Change database schema
I´m using Oracle as a database server (that makes things worst as Oracle mixes schema and users together).
Actually, I needed solution for this too. I quickly whipped up solution, which works nicely. I didn't find much information about this in Internet, so I am not sure about the "EF 4.1 comes with better support tools to do it".
The concrete example "Changing schema name on runtime - Entity framework" didn't entirely work for me, however with some minor modifications I got it working.
Here is a DatabaseUtils class that can do it:
internal static class DatabaseUtils
{
/// <summary>
/// Builds the connection string for Entity framework.
/// </summary>
/// <returns></returns>
public static EntityConnection BuildConnection(BuildConnectionParams buildConnectionParams)
{
var sqlBuilder = new SqlConnectionStringBuilder
{
DataSource = buildConnectionParams.ServerName,
InitialCatalog = buildConnectionParams.DatabaseName,
IntegratedSecurity = true
};
var providerString = sqlBuilder.ToString();
var entityBuilder = new EntityConnectionStringBuilder
{
Provider = buildConnectionParams.ProviderName,
ProviderConnectionString = providerString,
Metadata = string.Format(#"res://*/{0}.csdl|
res://*/{0}.ssdl|
res://*/{0}.msl", buildConnectionParams.ModelName)
};
return CreateConnection(buildConnectionParams.SchemaName, entityBuilder, buildConnectionParams.ModelName);
}
/// <summary>
/// Creates the EntityConnection, based on new schema & existing connectionString
/// </summary>
/// <param name="schemaName">Name of the schema.</param>
/// <param name="connectionBuilder"></param>
/// <param name="modelName">Name of the model.</param>
/// <returns></returns>
private static EntityConnection CreateConnection(string schemaName, EntityConnectionStringBuilder connectionBuilder, string modelName)
{
Func<string, Stream> generateStream =
extension => Assembly.GetExecutingAssembly().GetManifestResourceStream(string.Concat(modelName, extension));
Action<IEnumerable<Stream>> disposeCollection = streams =>
{
if (streams == null)
return;
foreach (var stream in streams.Where(stream => stream != null))
stream.Dispose();
};
var conceptualReader = generateStream(".csdl");
var mappingReader = generateStream(".msl");
var storageReader = generateStream(".ssdl");
if (conceptualReader == null || mappingReader == null || storageReader == null)
{
disposeCollection(new[] { conceptualReader, mappingReader, storageReader });
return null;
}
var storageXml = XElement.Load(storageReader);
foreach (var entitySet in storageXml.Descendants())
{
var schemaAttribute = entitySet.Attributes("Schema").FirstOrDefault();
if (schemaAttribute != null)
schemaAttribute.SetValue(schemaName);
}
storageXml.CreateReader();
var workspace = new MetadataWorkspace();
var storageCollection = new StoreItemCollection(new[] { storageXml.CreateReader() });
var conceptualCollection = new EdmItemCollection(new[] { XmlReader.Create(conceptualReader) });
var mappingCollection = new StorageMappingItemCollection(conceptualCollection,
storageCollection,
new[] { XmlReader.Create(mappingReader) });
workspace.RegisterItemCollection(conceptualCollection);
workspace.RegisterItemCollection(storageCollection);
workspace.RegisterItemCollection(mappingCollection);
var connection = DbProviderFactories.GetFactory(connectionBuilder.Provider).CreateConnection();
if (connection == null)
{
disposeCollection(new[] { conceptualReader, mappingReader, storageReader });
return null;
}
connection.ConnectionString = connectionBuilder.ProviderConnectionString;
return new EntityConnection(workspace, connection);
}
}
Usage:
/// <summary>
/// Initializes a new instance of the <see cref="DynamicAQDContext"/> class.
/// </summary>
public DynamicAQDContext()
{
var entityConnection = DatabaseUtils.BuildConnection(new BuildConnectionParams
{
ProviderName = "System.Data.SqlClient",
ServerName = "localhost\\",
DatabaseName = "",
ModelName = "YOURMODEL",
SchemaName = "SCHEMA"
});
if(entityConnection == null)
throw new Exception("Can't create EntityConnection");
_entities = new LINKEntities(entityConnection);
}
more info can be found here: http://bestplayah.com/entity-framework-dynamic-schema-changes-using-database-first-approach/
I have used asmx web service in my project. I want to add items to existing SharePoint list.
mylist.Url = Url.TrimEnd('/') + "/_vti_bin/lists.asmx";
mylist.UseDefaultCredentials = true;
XmlNode node = mylist.GetList(_listName);
And I have store my values in DataTable. How can I directly add data to SharePoint list from C# Datatable?
Or should I convert it to Xml and add ?
thank you
Take a look at this page for the general usage of UpdateListItems, although it only has an example for updating items.
Then look at this page for an example of the XML you need to send to create a new item rather than updating an existing one.
You'll need to loop through your data table constructing an XML structure for each item you want to add, but you can then add them all in a single request.
The following example demonstrates how to consume SharePoint Web Services, in particular Lists Class to create a List Item:
using System;
using System.Collections.Generic;
using System.Net;
using System.Xml;
namespace SharePoint.Client
{
public class ListsClient : IDisposable
{
public ListsClient(Uri webUri, ICredentials credentials)
{
_client = new Lists.Lists();
_client.Credentials = credentials;
_client.Url = webUri + "/_vti_bin/Lists.asmx";
}
public ListsClient(Uri webUri)
{
_client = new Lists.Lists();
_client.Url = webUri + "/_vti_bin/Lists.asmx";
}
/// <summary>
/// Create a List Item
/// </summary>
/// <param name="listName">List Name</param>
/// <param name="propertyValues">List Item properties</param>
/// <returns></returns>
public XmlNode CreateListItem(string listName,Dictionary<string,string> propertyValues)
{
var payload = new XmlDocument();
var updates = payload.CreateElement("Batch");
updates.SetAttribute("OnError", "Continue");
var method = payload.CreateElement("Method");
method.SetAttribute("ID", "1");
method.SetAttribute("Cmd", "New");
foreach (var propertyValue in propertyValues)
{
var field = payload.CreateElement("Field");
field.SetAttribute("Name", propertyValue.Key);
field.InnerText = propertyValue.Value;
method.AppendChild(field);
}
updates.AppendChild(method);
return _client.UpdateListItems(listName, updates);
}
public void Dispose()
{
_client.Dispose();
GC.SuppressFinalize(this);
}
protected Lists.Lists _client; //SharePoint Web Services Lists proxy
}
}
Usage
How to create a Task item:
using (var client = new SPOListsClient(webUrl, userName, password))
{
var taskProperties = new Dictionary<string, string>();
taskProperties["Title"] = "Order approval";
taskProperties["Priority"] = "(2) Normal";
var result = client.CreateListItem(listTitle, taskProperties);
}
References
SharePoint 2007 Web Services
Lists.UpdateListItems Method