public static SearchCondition ParseStructuredQuery(string query, CultureInfo cultureInfo = null) {
if (string.IsNullOrEmpty(query)) {
throw new ArgumentNullException("query");
}
IQueryParserManager nativeQueryParserManager = (IQueryParserManager)new QueryParserManagerCoClass();
IQueryParser queryParser = null;
IQuerySolution querySolution = null;
ICondition result = null;
IEntity mainType = null;
SearchCondition searchCondition = null;
try {
// First, try to create a new IQueryParser using IQueryParserManager
Guid guid = new Guid(InterfaceGuids.IQueryParser);
HResult hr = nativeQueryParserManager.CreateLoadedParser(
"SystemIndex",
cultureInfo == null ? (ushort)0 : (ushort)cultureInfo.LCID,
ref guid,
out queryParser);
if (hr != HResult.S_OK) {
throw Marshal.GetExceptionForHR((int)hr);
}
if (queryParser != null) {
// If user specified natural query, set the option on the query parser
using (PropVariant optionValue = new PropVariant(true)) {
hr = queryParser.SetOption(StructuredQuerySingleOption.NaturalSyntax, optionValue);
}
if (hr != HResult.S_OK) {
throw Marshal.GetExceptionForHR((int)hr);
}
// Next, try to parse the query.
// Result would be IQuerySolution that we can use for getting the ICondition and other
// details about the parsed query.
hr = queryParser.Parse(query, null, out querySolution);
if (hr != HResult.S_OK) {
throw Marshal.GetExceptionForHR((int)hr);
}
if (querySolution != null) {
// Lastly, try to get the ICondition from this parsed query
hr = querySolution.GetQuery(out result, out mainType);
if (hr != HResult.S_OK) {
throw Marshal.GetExceptionForHR((int)hr);
}
}
}
searchCondition = new SearchCondition(result);
return searchCondition;
}
catch {
if (searchCondition != null) searchCondition.Dispose();
throw;
}
finally {
if (nativeQueryParserManager != null) {
Marshal.ReleaseComObject(nativeQueryParserManager);
}
if (queryParser != null) {
Marshal.ReleaseComObject(queryParser);
}
if (querySolution != null) {
Marshal.ReleaseComObject(querySolution);
}
if (mainType != null) {
Marshal.ReleaseComObject(mainType);
}
}
}
}