How can I connect my databse by using LINQtoSPARQL for writing linq based services? - sparql

The following is the code of TestDataProvider class in LINQtoSPARQL (githublinkk). Here, data is taken from string or file.
namespace LINQtoSPARQLSpace.Tests
{
public static class TestDataProvider
{
public static ISPARQLQueryable<T> GetQuerable<T>(string data,
bool autoquotation = true,
bool treatUri = true,
IEnumerable<Prefix> prefixes = null,
bool skipTriplesWithEmptyObject = false,
bool mindAsterisk = false,
bool useStore = false,
string defaultGraphUri = "http://test.org/defaultgraph")
{
DynamicSPARQLSpace.dotNetRDF.Connector connector = null;
if (useStore)
{
var store = new VDS.RDF.TripleStore();
store.LoadFromString(data);
connector = new Connector(new InMemoryDataset(store, new Uri(defaultGraphUri)));
}
else
{
var graph = new VDS.RDF.Graph();
graph.LoadFromFile(data);
connector = new Connector(new InMemoryDataset(graph));
}
dynamic dyno = DynamicSPARQL.CreateDyno(connector.GetQueryingFunction(),
updateFunc: connector.GetUpdateFunction(),
autoquotation: autoquotation,
treatUri: treatUri,
prefixes:prefixes,
skipTriplesWithEmptyObject:skipTriplesWithEmptyObject,
mindAsterisk:mindAsterisk);
return new SPARQLQuery<T>(dyno);
}
}
}
Now, I want to connect my database (GraphDB ontotext). for now, I am able to connect my database with the help of following lines:
Options.ForceHttpBasicAuth = true;
var store2 = new VDS.RDF.Query.SparqlRemoteEndpoint(new Uri("http://localhost:7200/repositories/786"));
store2.SetCredentials("admin", "admin");
Now, how can I pass this SparqlRemoteEndpoint object to Connector class object? am I going in the right way to connect?
Please Help.

Related

Confusion on ektron persona management

i have created a custom connection in dxh but that is not available on persona management site. from this video i understand that i have to create a class library for my custom connection. Is there any demo code available for this custom library?
i am stuck with the login management of dxh and persona, and how is this attributes working?
my code
using Attribute = Ektron.PersonaManagement.Common.Attribute;
public class ETPersona : PersonaAttributeProvider
{
public override IEnumerable<Attribute> GetAttributes()
{
return new List<Attribute>() {
new Attribute() {
DataSource = "test",
DataSourceId = "test",
Id = "test",
Name = new LocalizableText("test","test"),
Type =FieldType.String,
Options = new List<LocalizableText>(){new LocalizableText("test","test")}
}
};
}
public override UserAttributeData GetUserAttributeData(VisitorContext context)
{
return new UserAttributeData()
{
Attributes = new List<UserAttribute>() { new UserAttribute() { } },
HaveUserData = true,
UserKey = ""
};
}
}
Please see Ektron's forum discussion here for information:
http://developer.ektron.com/Forums/?v=t&t=1975

Populating Nested List<> in MVC4 C#

I've got a problem populating nested List<>
The object graph looks like this:
Route ⇒ Section ⇒ Co-ordinates
Whenever I try to populate Сoordinates list it just overwrites previous record and at the end gives me only the last Coordinate record. But I want all the Co-ordinates.
Here is my controller code:
List<RequestRouteDataClass> result = new List<RequestRouteDataClass> {
new RequestRouteDataClass() {
RouteRequestId = objRouteManagement.RouteRequestId,
RouteName = objRouteManagement.RouteName,
RouteDescription = objRouteManagement.RouteDescription,
RouteSections = new List<RouteSections> {
new RouteSections() {
Route_Sections_Id = objSections.Route_Sections_Id,
Section_Speed = objSections.Section_Speed,
Section_Description = objSections.Section_Description,
RouteCordinatesSections = new List<SectionCoordinatesRelationData> {
new SectionCoordinatesRelationData() {
SectionCoordinate_Relat_Id = objSectionsCordinates.SectionCoordinate_Relat_Id,
CoordinateLat = objSectionsCordinates.CoordinateLat,
CoordinateLag = objSectionsCordinates.CoordinateLag
}
}
}
}
}
If you want to use Nested List.
Your Model Contains =>
public class MainModelToUse
{
public MainModelToUse()
{
FirstListObject = new List<FirstListClass>();
}
public List<FirstListClass> FirstListObject { get; set; }
}
public class FirstListClass
{
public FirstListClass()
{
SecondListObject = new List<SecondListClass>();
}
public List<SecondListClass> SecondListObject { get; set; }
}
public class SecondListClass
{
public SecondListClass()
{
ThirdListObject = new List<ThirdListClass>();
}
public List<ThirdListClass> ThirdListObject { get; set; }
}
public class ThirdListClass
{
}
Your Code to Nested List =>
FirstListClass vmFirstClassMenu = new FirstListClass();
vmFirstClassMenu.SecondListClass = new List<SecondListClass>();
FirstListClass vmFirstClassCategory = new FirstListClass();
var dataObject1 = //Get Data By Query In Object;
foreach (Model objModel in dataObject1)
{
vmFirstClassCategory = new FirstListClass
{
//Your Items
};
var DataObject2 = //Get Data By Query In Object;
vmFirstClassCategory.SecondListClass = new List<SecondListClass>();
foreach (SecondListClass menuItem in DataObject2)
{
SecondListClass vmFirstClassMenuItem = new SecondListClass
{
//Your Items
};
var DataObject3 = //Get Data By Query In Object;
vmFirstClassMenuItem.ThirdListClass = new List<ThirdListClass>();
foreach (ThirdListClass price in DataObject3)
{
ThirdListClass vmThirdClassobj = new ThirdListClass
{
//Your Items
};
vmFirstClassMenuItem.ThirdListClass.Add(vmThirdClassobj);
}
vmFirstClassCategory.SecondListClass.Add(vmFirstClassMenuItem);
}
}
Hope this is what you are looking for.
First off: spacing helps with readability (edit: but I see you fixed that in your question already):
List<RequestRouteDataClass> result = new List<RequestRouteDataClass>
{
new RequestRouteDataClass()
{
RouteRequestId = objRouteManagement.RouteRequestId,
RouteName = objRouteManagement.RouteName,
RouteDescription = objRouteManagement.RouteDescription,
RouteSections = new List<RouteSections>
{
new RouteSections()
{
Route_Sections_Id = objSections.Route_Sections_Id,
Section_Speed = objSections.Section_Speed,
Section_Description = objSections.Section_Description,
RouteCordinatesSections = new List<SectionCoordinatesRelationData>
{
new SectionCoordinatesRelationData()
{
SectionCoordinate_Relat_Id = objSectionsCordinates.SectionCoordinate_Relat_Id,
CoordinateLat = objSectionsCordinates.CoordinateLat,
CoordinateLag =objSectionsCordinates.CoordinateLag
}
}
}
}
}
};
Next: what you are doing with the above is initiating your lists with a single element in each list. If you want more elements, you have to add them. I recommend using a foreach and the Add() functionality to fill your lists.
From your example it is not clear how your source data is stored, but if you have multiples of something I would expect those too to be in a list or an array of some kind.

Web API OData Typeless support for $select query option

I am working with the new typeless support in ASP.NET Web API 2 OData. I am interested in providing support for the $select query option. How do I omit the structural properties from the EdmEntityObject that were not selected by the $select query option?
The following is a sample of the Web API Configuration for a very simple example working with a typeless model.
public static IEdmModel BuildEdmModel()
{
var model = new EdmModel();
var container = new EdmEntityContainer("Model", "OData");
var product = new EdmEntityType("Model", "Product");
var productKey = product.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Guid);
product.AddKeys(productKey);
product.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
product.AddStructuralProperty("Price", EdmPrimitiveTypeKind.Double);
model.AddElement(product);
model.AddElement(container);
model.SetIsDefaultEntityContainer(container, true);
container.AddEntitySet("Products", product);
return model;
}
public static void Register(HttpConfiguration config)
{
config.Routes.MapODataRoute("ODataRoute", "odata", BuildEdmModel());
}
The following is a partial snippet from a simple ODataController
public EdmEntityObjectCollection Get()
{
var path = Request.GetODataPath();
var edmType = path.EdmType;
var collectionType = edmType as IEdmCollectionType;
var entityType = collectionType.ElementType.AsEntity();
var entitySetName = entityType.EntityDefinition().Name;
var model = Request.GetEdmModel();
var queryContext = new ODataQueryContext(Request.GetEdmModel(), entityType.Definition);
var queryOptions = new ODataQueryOptions(queryContext, Request);
return GetData(Request.GetEdmModel(), queryOptions);
}
public static EdmEntityObjectCollection GetData(IEdmModel edmModel, ODataQueryOptions queryOptions)
{
var selectedPropertyNames = new string[0];
// determine the selected property names
if (queryOptions.SelectExpand != null && queryOptions.SelectExpand.SelectExpandClause != null && (!queryOptions.SelectExpand.SelectExpandClause.AllSelected || queryOptions.SelectExpand.SelectExpandClause.SelectedItems.OfType<WildcardSelectItem>().Any()))
{
selectedPropertyNames = queryOptions.SelectExpand.RawSelect.Split(',');
}
// TODO: Now that we have the selected properties, how do I remove the structural properties from the EdmEntityObject that were not selected by the $select query option?
var productSchemaType = edmModel.FindDeclaredType(string.Format("{0}.Product", "Model"));
var productEntityType = productSchemaType as IEdmEntityType;
var productEntityTypeReference = new EdmEntityTypeReference(productEntityType, true);
var products = new EdmEntityObjectCollection(new EdmCollectionTypeReference(new EdmCollectionType(productEntityTypeReference), true));
var productWindows = new EdmEntityObject(productEntityTypeReference);
productWindows.TrySetPropertyValue("ID", new Guid("52D811A0-9065-4B83-A2E8-0248FBA9FBF5"));
productWindows.TrySetPropertyValue("Name", "Microsoft Windows 8");
productWindows.TrySetPropertyValue("Price", 179.99);
var productOffice = new EdmEntityObject(productEntityTypeReference);
productOffice.TrySetPropertyValue("ID", new Guid("CB39EBD0-4751-4D5F-A76C-78FCC7A9CE1A"));
productOffice.TrySetPropertyValue("Name", "Microsoft Office 2013");
productOffice.TrySetPropertyValue("Price", 399.99);
products.Add(productWindows);
products.Add(productOffice);
return products;
}
This will output:
{
"odata.metadata":"http://localhost:59511/odata/$metadata#Products","value":[
{
"ID":"52d811a0-9065-4b83-a2e8-0248fba9fbf5","Name":"Microsoft Windows 8","Price":179.99
},{
"ID":"cb39ebd0-4751-4d5f-a76c-78fcc7a9ce1a","Name":"Microsoft Office 2013","Price":399.99
}
]
}
If the user applies a $select query option, for example /odata/Products?$select=Name. This should result in the following output:
{
"odata.metadata":"http://localhost:59511/odata/$metadata#Products","value":[
{
"Name":"Microsoft Windows 8"
},{
"Name":"Microsoft Office 2013"
}
]
}
Any help would be greatly appreciated
The following works for me.
var oDataProperties = Request.ODataProperties()
oDataProperties.SelectExpandClause = queryOptions.SelectExpand.SelectExpandClause;
The extension function is in System.web.OData.dll v5.2.0.0.
Here's my code.
private void ApplySelectExpand(SelectExpandQueryOption selectExpand)
{
if (selectExpand != null)
{
Request.SetSelectExpandClause(selectExpand.SelectExpandClause);
}
}
There are two ways to solve your problem if I understood your question correctly.
Call the ApplyTo method of ODataQueryOptions on the IQueryable result
return queryOptions.ApplyTo(products);
Add attribute Queryable on the GetData method and let WebAPI handles the query option
[Queryable]
public static EdmEntityObjectCollection GetData(IEdmModel edmModel)
{...}

Web API Help pages - customizing Property documentation

I have my web api and I added the web api help pages to auto-generate my documentation. It's working great for methods where my parameters are listed out, but I have a method like this:
public SessionResult PostLogin(CreateSessionCommand request)
And, on my help page, it is only listing the command parameter in the properties section. However, in the sample request section, it lists out all of the properties of my CreateSessionCommand class.
Parameters
Name | Description | Additional information
request | No documentation available. | Define this parameter in the request body.
I would like it instead to list all of the properties in my CreateSessionCommand class. Is there an easy way to do this?
So, I managed to devise a workaround for this problem, in case anyone is interested.
In HelpPageConfigurationExtensions.cs I added the following extension method:
public static void AlterApiDescription(this ApiDescription apiDescription, HttpConfiguration config)
{
var docProvider = config.Services.GetDocumentationProvider();
var addParams = new List<ApiParameterDescription>();
var removeParams = new List<ApiParameterDescription>();
foreach (var param in apiDescription.ParameterDescriptions)
{
var type = param.ParameterDescriptor.ParameterType;
//string is some special case that is not a primitive type
//also, compare by full name because the type returned does not seem to match the types generated by typeof
bool isPrimitive = type.IsPrimitive || String.Compare(type.FullName, typeof(string).FullName) == 0;
if (!isPrimitive)
{
var properties = from p in param.ParameterDescriptor.ParameterType.GetProperties()
let s = p.SetMethod
where s.IsPublic
select p;
foreach (var property in properties)
{
var documentation = docProvider.GetDocumentation(new System.Web.Http.Controllers.ReflectedHttpParameterDescriptor()
{
ActionDescriptor = param.ParameterDescriptor.ActionDescriptor,
ParameterInfo = new CustomParameterInfo(property)
});
addParams.Add(new ApiParameterDescription()
{
Documentation = documentation,
Name = property.Name,
Source = ApiParameterSource.FromBody,
ParameterDescriptor = param.ParameterDescriptor
});
}
//since this is a complex type, select it to be removed from the api description
removeParams.Add(param);
}
}
//add in our new items
foreach (var item in addParams)
{
apiDescription.ParameterDescriptions.Add(item);
}
//remove the complex types
foreach (var item in removeParams)
{
apiDescription.ParameterDescriptions.Remove(item);
}
}
And here is the Parameter info instanced class I use
internal class CustomParameterInfo : ParameterInfo
{
public CustomParameterInfo(PropertyInfo prop)
{
base.NameImpl = prop.Name;
}
}
Then, we call the extension in another method inside the extensions class
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
apiDescription.AlterApiDescription(config);
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
The comments that are used for this must be added to the controller method and not the properties of the class object. This might be because my object is part of an outside library
this should go as an addition to #Josh answer. If you want not only to list properties from the model class, but also include documentation for each property, Areas/HelpPage/XmlDocumentationProvider.cs file should be modified as follows:
public virtual string GetDocumentation(HttpParameterDescriptor parameterDescriptor)
{
ReflectedHttpParameterDescriptor reflectedParameterDescriptor = parameterDescriptor as ReflectedHttpParameterDescriptor;
if (reflectedParameterDescriptor != null)
{
if (reflectedParameterDescriptor.ParameterInfo is CustomParameterInfo)
{
const string PropertyExpression = "/doc/members/member[#name='P:{0}']";
var pi = (CustomParameterInfo) reflectedParameterDescriptor.ParameterInfo;
string selectExpression = String.Format(CultureInfo.InvariantCulture, PropertyExpression, pi.Prop.DeclaringType.FullName + "." + pi.Prop.Name);
XPathNavigator methodNode = _documentNavigator.SelectSingleNode(selectExpression);
if (methodNode != null)
{
return methodNode.Value.Trim();
}
}
else
{
XPathNavigator methodNode = GetMethodNode(reflectedParameterDescriptor.ActionDescriptor);
if (methodNode != null)
{
string parameterName = reflectedParameterDescriptor.ParameterInfo.Name;
XPathNavigator parameterNode = methodNode.SelectSingleNode(String.Format(CultureInfo.InvariantCulture, ParameterExpression, parameterName));
if (parameterNode != null)
{
return parameterNode.Value.Trim();
}
}
}
}
return null;
}
and CustomParameterInfo class should keep property info as well:
internal class CustomParameterInfo : ParameterInfo
{
public PropertyInfo Prop { get; private set; }
public CustomParameterInfo(PropertyInfo prop)
{
Prop = prop;
base.NameImpl = prop.Name;
}
}
This is currently not supported out of the box. Following bug is kind of related to that:
http://aspnetwebstack.codeplex.com/workitem/877

Serialize a FeatureClass to XML in ESRI ArcGIS

How can I serialize an IFeatureClass object to XML?
There are some resources for using IXMLSerializer on other ArcObjects, but that won't work for IFeatureClass because it doesn't implement ISerializable.
I've actual found my own answer to this question. I'm posting this question and answer here for the benefit of others and for feedback/critique on my approach.
IFeatureClass cannot be serialized directly, but IRecordSet2 can be. So the first step is implementing a method to convert IFeatureClass to IRecordSet2:
private static IRecordSet2 ConvertToRecordset(IFeatureClass fc)
{
IRecordSet recSet = new RecordSetClass();
IRecordSetInit recSetInit = recSet as IRecordSetInit;
recSetInit.SetSourceTable(fc as ITable, null);
return (IRecordSet2) recSetInit;
}
Then it's easy to use IXMLSerializer to get XML:
public static XElement StoreAsXml(IFeatureClass fc)
{
// Can't serialize a feature class directly, so convert
// to recordset first.
IRecordSet2 recordset = ConvertToRecordset(fc);
IXMLSerializer xmlSer = new XMLSerializerClass();
string sXml = xmlSer.SaveToString(recordset, null, null);
return XElement.Parse(sXml);
}
However, when you convert to IRecordSet2, you lose the feature class name, so when writing to a file, I add an element to the XML to hold the feature class name:
public static void StoreToFile(IFeatureClass fc, string filePath)
{
XElement xdoc = StoreAsXml(fc);
XElement el = new XElement("FeatureClass", new XAttribute( "name", fc.AliasName ),
xdoc);
el.Save(filePath);
}
Now, just reverse the process to read the XML into a feature class. Remember that an element was added to store the feature class name:
public static IFeatureClass RetreiveFromFile(string filepath)
{
XElement xdoc = XElement.Load(filepath);
string sName = xdoc.FirstAttribute.Value;
XNode recordset = xdoc.FirstNode;
return RetreiveFromXml(recordset, sName);
}
Simple de-serialization using IXMLSerializer to get a IRecordSet2:
public static IFeatureClass RetreiveFromXml(XNode node, string sName)
{
IXMLSerializer xmlDeSer = new XMLSerializerClass();
IRecordSet2 recordset = (IRecordSet2)xmlDeSer.LoadFromString(node.ToString(), null, null);
return ConvertToFeatureClass(recordset, sName);
}
This was the tricky part. I'm open to suggestions on how to improve this ... covert the IRecordSet2 object into an IFeatureClass:
private static IFeatureClass ConvertToFeatureClass(IRecordSet2 rs, string sName)
{
IWorkspaceFactory pWSFact = new ShapefileWorkspaceFactory();
string sTempPath = Path.GetTempPath();
IFeatureWorkspace pFWS = (IFeatureWorkspace)pWSFact.OpenFromFile( sTempPath, 0);
// Will fail (COM E_FAIL) if the dataset already exists
DeleteExistingDataset(pFWS, sName);
IFeatureClass pFeatClass = null;
pFeatClass = pFWS.CreateFeatureClass(sName, rs.Fields, null, null, esriFeatureType.esriFTSimple,
"SHAPE", "");
// Copy incoming record set table to new feature class's table
ITable table = (ITable) pFeatClass;
table = rs.Table;
IFeatureClass result = table as IFeatureClass;
// It will probably work OK without this, but it makes the XML match more closely
IClassSchemaEdit3 schema = result as IClassSchemaEdit3;
schema.AlterAliasName(sName);
schema.AlterFieldAliasName("FID", "");
schema.AlterFieldModelName("FID", "");
schema.AlterFieldAliasName("Shape", "");
schema.AlterFieldModelName("Shape", "");
// If individual fields need to be edited, do something like this:
// int nFieldIndex = result.Fields.FindField("Shape");
// IFieldEdit2 field = (IFieldEdit2)result.Fields.get_Field(nFieldIndex);
// Cleanup
DeleteExistingDataset(pFWS, sName);
return table as IFeatureClass;
}
Finally, a utility method for deleting an existing dataset. This was copy/pasted from somewhere, but I can't remember the source.
public static void DeleteExistingDataset(IFeatureWorkspace pFWS, string sDatasetName)
{
IWorkspace pWS = (IWorkspace)pFWS;
IEnumDatasetName pEDSN = pWS.get_DatasetNames(esriDatasetType.esriDTFeatureClass);
bool bDatasetExists = false;
pEDSN.Reset();
IDatasetName pDSN = pEDSN.Next();
while (pDSN != null)
{
if (pDSN.Name == sDatasetName)
{
bDatasetExists = true;
break;
}
pDSN = pEDSN.Next();
}
if (bDatasetExists)
{
IFeatureClass pFC = pFWS.OpenFeatureClass(sDatasetName);
IDataset pDataset = (IDataset)pFC;
pDataset.Delete();
}
}