public List <long> Get() { // get token from the request string token = this.Request.Headers.Authorization?.Parameter; // flag for the public dataset check bool isPublic = false; List <long> ids = new List <long>(); using (var datasetManager = new DatasetManager()) { var datasetIds = datasetManager.GetDatasetLatestIds(); foreach (var id in datasetIds) { using (EntityPermissionManager entityPermissionManager = new EntityPermissionManager()) using (EntityManager entityManager = new EntityManager()) using (UserManager userManager = new UserManager()) { // load the entity id of the e.g. is it a sample or dataset or publication long?entityTypeId = entityManager.FindByName(typeof(Dataset).Name)?.Id; entityTypeId = entityTypeId.HasValue ? entityTypeId.Value : -1; // if the subject is null and one entry exist, means this dataset is public isPublic = entityPermissionManager.Exists(null, entityTypeId.Value, id); // load user based on token User user = userManager.Users.Where(u => u.Token.Equals(token)).FirstOrDefault(); if (isPublic || user != null) { if (isPublic || entityPermissionManager.HasEffectiveRight(user.Name, typeof(Dataset), id, RightType.Read)) { var filepath = Path.Combine(AppConfiguration.DataPath, "Datasets", id.ToString(), "geoengine.json"); if (File.Exists(filepath)) { ids.Add(id); } } } } } } return(ids); }
private HttpResponseMessage getData(long id, int variableId, string token) { DatasetManager datasetManager = new DatasetManager(); UserManager userManager = new UserManager(); EntityPermissionManager entityPermissionManager = new EntityPermissionManager(); EntityManager entityManager = new EntityManager(); DataStructureManager dataStructureManager = null; bool isPublic = false; try { // if a dataset is public, then the api should also return data if there is no token for a user #region is public dataStructureManager = new DataStructureManager(); long?entityTypeId = entityManager.FindByName(typeof(Dataset).Name)?.Id; entityTypeId = entityTypeId.HasValue ? entityTypeId.Value : -1; isPublic = entityPermissionManager.Exists(null, entityTypeId.Value, id); #endregion is public if (!isPublic && String.IsNullOrEmpty(token)) { var request = Request.CreateResponse(); request.Content = new StringContent("Bearer token not exist."); return(request); } User user = userManager.Users.Where(u => u.Token.Equals(token)).FirstOrDefault(); if (isPublic || user != null) { if (isPublic || entityPermissionManager.HasEffectiveRight(user.Name, typeof(Dataset), id, RightType.Read)) { XmlDatasetHelper xmlDatasetHelper = new XmlDatasetHelper(); OutputDataManager ioOutputDataManager = new OutputDataManager(); Dataset dataset = datasetManager.GetDataset(id); DatasetVersion datasetVersion = datasetManager.GetDatasetLatestVersion(id); string title = datasetVersion.Title; // check the data sturcture type ... if (datasetVersion.Dataset.DataStructure.Self is StructuredDataStructure) { object stats = new object(); DataTable dt = new DataTable("Varibales"); List <ApiDataStatisticModel> dataStatisticModels = new List <ApiDataStatisticModel>(); if (variableId == -1) { StructuredDataStructure structuredDataStructure = dataStructureManager.StructuredDataStructureRepo.Get(datasetVersion.Dataset.DataStructure.Id); List <string> varIds = new List <string>(); foreach (Variable vs in structuredDataStructure.Variables) { varIds.Add("var" + vs.Id); } dt = GetDuplicates(id, varIds); } else { } //dt.Strip(); dt.TableName = id + "_data"; DatasetModel model = new DatasetModel(); model.DataTable = dt; var response = Request.CreateResponse(HttpStatusCode.OK); string resp = JsonConvert.SerializeObject(model); response.Content = new StringContent(resp, System.Text.Encoding.UTF8, "application/json"); response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); return(response); } else { return(Request.CreateResponse()); } } else // has rights? { var request = Request.CreateResponse(); request.Content = new StringContent("User has no read right."); return(request); } } else { var request = Request.CreateResponse(); request.Content = new StringContent("User is not available."); return(request); } } catch (Exception e) { throw e; } finally { datasetManager.Dispose(); userManager.Dispose(); entityPermissionManager.Dispose(); entityManager.Dispose(); dataStructureManager.Dispose(); } }
public ActionResult Instances_Select(long entityId) { var entityManager = new EntityManager(); var entityPermissionManager = new EntityPermissionManager(); //var userManager = new UserManager(); try { var instanceStore = (IEntityStore)Activator.CreateInstance(entityManager.FindById(entityId).EntityStoreType); //var user = userManager.FindByNameAsync(HttpContext.User.Identity.Name).Result; //var keys = entityPermissionManager.GetKeys(user?.Id, entityId, RightType.Grant); //var instances = instanceStore.GetEntities().Where(i => keys.Contains(i.Id)).Select(i => EntityInstanceGridRowModel.Convert(i, entityPermissionManager.Exists(null, entityId, i.Id))).ToList(); var instances = instanceStore.GetEntities().Select(i => EntityInstanceGridRowModel.Convert(i, entityPermissionManager.Exists(null, entityId, i.Id))).ToList(); return(View(new GridModel <EntityInstanceGridRowModel> { Data = instances })); } finally { entityManager.Dispose(); entityPermissionManager.Dispose(); } }
private HttpResponseMessage getData(long id, int variableId, string token) { DatasetManager datasetManager = new DatasetManager(); UserManager userManager = new UserManager(); EntityPermissionManager entityPermissionManager = new EntityPermissionManager(); EntityManager entityManager = new EntityManager(); DataStructureManager dataStructureManager = null; bool isPublic = false; try { // if a dataset is public, then the api should also return data if there is no token for a user #region is public dataStructureManager = new DataStructureManager(); long?entityTypeId = entityManager.FindByName(typeof(Dataset).Name)?.Id; entityTypeId = entityTypeId.HasValue ? entityTypeId.Value : -1; isPublic = entityPermissionManager.Exists(null, entityTypeId.Value, id); #endregion is public if (!isPublic && String.IsNullOrEmpty(token)) { var request = Request.CreateResponse(); request.Content = new StringContent("Bearer token not exist."); return(request); } User user = userManager.Users.Where(u => u.Token.Equals(token)).FirstOrDefault(); if (isPublic || user != null) { if (isPublic || entityPermissionManager.HasEffectiveRight(user.Name, typeof(Dataset), id, RightType.Read)) { XmlDatasetHelper xmlDatasetHelper = new XmlDatasetHelper(); OutputDataManager ioOutputDataManager = new OutputDataManager(); Dataset dataset = datasetManager.GetDataset(id); DatasetVersion datasetVersion = datasetManager.GetDatasetLatestVersion(id); string title = datasetVersion.Title; // check the data sturcture type ... if (datasetVersion.Dataset.DataStructure.Self is StructuredDataStructure) { object stats = new object(); DataTable dt = new DataTable("Varibales"); DataTable dtMissingValues = new DataTable("MissingValues"); dtMissingValues.Columns.Add("placeholder", typeof(String)); dtMissingValues.Columns.Add("displayName", typeof(String)); List <ApiDataStatisticModel> dataStatisticModels = new List <ApiDataStatisticModel>(); StructuredDataStructure structuredDataStructure = dataStructureManager.StructuredDataStructureRepo.Get(datasetVersion.Dataset.DataStructure.Id); if (variableId == -1) { foreach (Variable vs in structuredDataStructure.Variables) { ApiDataStatisticModel dataStatisticModel = new ApiDataStatisticModel(); dt = GetUniqueValues(id, vs.Id); dataStatisticModel.VariableId = vs.Id; dataStatisticModel.uniqueValues = dt; dataStatisticModel.minLength = dt.Compute("Min(length)", string.Empty).ToString(); dataStatisticModel.maxLength = dt.Compute("Max(length)", string.Empty).ToString(); dataStatisticModel.count = dt.Compute("Sum(count)", string.Empty).ToString(); dtMissingValues.Clear(); foreach (var missingValue in vs.MissingValues) { DataRow workRow = dtMissingValues.NewRow(); workRow["placeholder"] = missingValue.Placeholder; workRow["displayName"] = missingValue.DisplayName; dtMissingValues.Rows.Add(workRow); } dataStatisticModel.min = GetMin(dtMissingValues, dt); dataStatisticModel.max = GetMax(dtMissingValues, dt); dataStatisticModel.missingValues = dtMissingValues; dataStatisticModels.Add(dataStatisticModel); } } else { Variable variable = new Variable(); foreach (Variable vs in structuredDataStructure.Variables) { if (vs.Id == variableId) { variable = vs; } } ApiDataStatisticModel dataStatisticModel = new ApiDataStatisticModel(); dt = GetUniqueValues(id, variableId); dataStatisticModel.VariableId = variableId; dataStatisticModel.uniqueValues = dt; dataStatisticModel.minLength = dt.Compute("Min(length)", string.Empty).ToString(); dataStatisticModel.maxLength = dt.Compute("Max(length)", string.Empty).ToString(); dataStatisticModel.count = dt.Compute("Sum(count)", string.Empty).ToString(); foreach (var missingValue in variable.MissingValues) { DataRow workRow = dtMissingValues.NewRow(); workRow["placeholder"] = missingValue.Placeholder; workRow["displayName"] = missingValue.DisplayName; dtMissingValues.Rows.Add(workRow); } dataStatisticModel.min = GetMin(dtMissingValues, dt); dataStatisticModel.max = GetMax(dtMissingValues, dt); dataStatisticModel.missingValues = dtMissingValues; dataStatisticModels.Add(dataStatisticModel); } dt.Strip(); dt.TableName = id + "_data"; DatasetModel model = new DatasetModel(); model.DataTable = dt; var response = Request.CreateResponse(HttpStatusCode.OK); string resp = JsonConvert.SerializeObject(dataStatisticModels); response.Content = new StringContent(resp, System.Text.Encoding.UTF8, "application/json"); response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); return(response); } else { return(Request.CreateResponse()); } } else // has rights? { var request = Request.CreateResponse(); request.Content = new StringContent("User has no read right."); return(request); } } else { var request = Request.CreateResponse(); request.Content = new StringContent("User is not available."); return(request); } } catch (Exception e) { throw e; } finally { datasetManager.Dispose(); userManager.Dispose(); entityPermissionManager.Dispose(); entityManager.Dispose(); dataStructureManager.Dispose(); } }
/// <summary> /// /// </summary> /// <remarks></remarks> /// <seealso cref=""/> /// <param name="id"></param> /// <param name="metadataDoc"></param> /// <return></return> private void writeBexisIndex(long id, XmlDocument metadataDoc) { string docId = id.ToString();//metadataDoc.GetElementsByTagName("bgc:id")[0].InnerText; var dataset = new Document(); List <XmlNode> facetNodes = facetXmlNodeList; dataset.Add(new Field("doc_id", docId, Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.NOT_ANALYZED)); /// /// Add a field to indicte whether the dataset is public, this will be used for the public datasets' search page. /// dataset.Add(new Field("gen_isPublic", entityPermissionManager.Exists(null, entityTypeId.Value, id) ? "TRUE" : "FALSE", Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.NOT_ANALYZED)); XmlDatasetHelper xmlDatasetHelper = new XmlDatasetHelper(); dataset.Add(new Field("gen_entity_name", xmlDatasetHelper.GetEntityName(id), Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.NOT_ANALYZED)); foreach (XmlNode facet in facetNodes) { String multivalued = facet.Attributes.GetNamedItem("multivalued").Value; string[] metadataElementNames = facet.Attributes.GetNamedItem("metadata_name").Value.Split(','); String lucene_name = facet.Attributes.GetNamedItem("lucene_name").Value; foreach (string metadataElementName in metadataElementNames) { XmlNodeList elemList = metadataDoc.SelectNodes(metadataElementName); if (elemList != null) { for (int i = 0; i < elemList.Count; i++) { string eleme = elemList[i].InnerText; if (!elemList[i].InnerText.Trim().Equals("")) { dataset.Add(new Field("facet_" + lucene_name, elemList[i].InnerText, Lucene.Net.Documents.Field.Store.YES, Field.Index.NOT_ANALYZED)); dataset.Add(new Field("ng_all", elemList[i].InnerText, Lucene.Net.Documents.Field.Store.YES, Field.Index.ANALYZED)); writeAutoCompleteIndex(docId, lucene_name, elemList[i].InnerText); writeAutoCompleteIndex(docId, "ng_all", elemList[i].InnerText); } } } } } List <XmlNode> propertyNodes = propertyXmlNodeList; foreach (XmlNode property in propertyNodes) { String multivalued = property.Attributes.GetNamedItem("multivalued").Value; String lucene_name = property.Attributes.GetNamedItem("lucene_name").Value; string[] metadataElementNames = property.Attributes.GetNamedItem("metadata_name").Value.Split(','); foreach (string metadataElementName in metadataElementNames) { XmlNodeList elemList = metadataDoc.SelectNodes(metadataElementName); if (elemList != null) { String primitiveType = property.Attributes.GetNamedItem("primitive_type").Value; if (elemList[0] != null) { if (primitiveType.ToLower().Equals("string")) { dataset.Add(new Field("property_" + lucene_name, elemList[0].InnerText, Lucene.Net.Documents.Field.Store.YES, Field.Index.NOT_ANALYZED)); dataset.Add(new Field("ng_all", elemList[0].InnerText, Lucene.Net.Documents.Field.Store.YES, Field.Index.ANALYZED)); writeAutoCompleteIndex(docId, lucene_name, elemList[0].InnerText); writeAutoCompleteIndex(docId, "ng_all", elemList[0].InnerText); } else if (primitiveType.ToLower().Equals("date")) { //DateTime MyDateTime = DateTime.Now; DateTime MyDateTime = new DateTime(); /*String dTFormatElementName = property.Attributes.GetNamedItem("date_format").Value; * XmlNodeList dtFormatElements = metadataDoc.GetElementsByTagName(dTFormatElementName); * String dateTimeFormat = dtFormatElements[0].InnerText;*/ if (DateTime.TryParse(elemList[0].InnerText, out MyDateTime)) { //MyDateTime = DateTime.ParseExact(elemList[0].InnerText, dateTimeFormat, // CultureInfo.InvariantCulture); long t = MyDateTime.Ticks; NumericField xyz = new NumericField("property_numeric_" + lucene_name).SetLongValue( MyDateTime.Ticks); String dateToString = MyDateTime.Date.ToString("d", CultureInfo.CreateSpecificCulture("en-US")); dataset.Add(xyz); dataset.Add(new Field("property_" + lucene_name, dateToString, Lucene.Net.Documents.Field.Store.NO, Field.Index.NOT_ANALYZED)); writeAutoCompleteIndex(docId, lucene_name, MyDateTime.Date.ToString()); writeAutoCompleteIndex(docId, "ng_all", MyDateTime.Date.ToString()); } } else if (primitiveType.ToLower().Equals("integer")) { dataset.Add( new NumericField("property_numeric" + lucene_name).SetIntValue( Convert.ToInt32(elemList[0].InnerText))); dataset.Add(new Field("property_" + lucene_name, elemList[0].InnerText, Lucene.Net.Documents.Field.Store.NO, Field.Index.NOT_ANALYZED)); // writeAutoCompleteIndex(lucene_name, elemList[0].InnerText); } else if (primitiveType.ToLower().Equals("double")) { dataset.Add( new NumericField("property_numeric" + lucene_name).SetDoubleValue( Convert.ToDouble(elemList[0].InnerText))); dataset.Add(new Field("property_" + lucene_name, elemList[0].InnerText, Lucene.Net.Documents.Field.Store.NO, Field.Index.NOT_ANALYZED)); writeAutoCompleteIndex(docId, lucene_name, elemList[0].InnerText); writeAutoCompleteIndex(docId, "ng_all", elemList[0].InnerText); } } } } } List <XmlNode> categoryNodes = categoryXmlNodeList; // add categories to index foreach (XmlNode category in categoryNodes) { String primitiveType = category.Attributes.GetNamedItem("primitive_type").Value; String lucene_name = category.Attributes.GetNamedItem("lucene_name").Value; String analysing = category.Attributes.GetNamedItem("analysed").Value; float boosting = Convert.ToSingle(category.Attributes.GetNamedItem("boost").Value); var toAnalyse = Lucene.Net.Documents.Field.Index.NOT_ANALYZED; if (analysing.ToLower().Equals("yes")) { toAnalyse = Lucene.Net.Documents.Field.Index.ANALYZED; } if (!category.Attributes.GetNamedItem("type").Value.Equals("primary_data_field")) { String multivalued = category.Attributes.GetNamedItem("multivalued").Value; String storing = category.Attributes.GetNamedItem("store").Value; var toStore = Lucene.Net.Documents.Field.Store.NO; if (storing.ToLower().Equals("yes")) { toStore = Lucene.Net.Documents.Field.Store.YES; } string[] metadataElementNames = category.Attributes.GetNamedItem("metadata_name").Value.Split(','); foreach (string metadataElementName in metadataElementNames) { XmlNodeList elemList = metadataDoc.SelectNodes(metadataElementName); if (elemList != null) { for (int i = 0; i < elemList.Count; i++) { Field a = new Field("category_" + lucene_name, elemList[i].InnerText, toStore, toAnalyse); a.Boost = boosting; dataset.Add(a); dataset.Add(new Field("ng_" + lucene_name, elemList[i].InnerText, Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.ANALYZED)); dataset.Add(new Field("ng_all", elemList[i].InnerText, Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.ANALYZED)); writeAutoCompleteIndex(docId, lucene_name, elemList[i].InnerText); writeAutoCompleteIndex(docId, "ng_all", elemList[i].InnerText); } } } } else { //if the primary data index exist in the config - this means the primary data should be indexed includePrimaryData = true; } } indexPrimaryData(id, categoryNodes, ref dataset, docId, metadataDoc); List <XmlNode> generalNodes = generalXmlNodeList; foreach (XmlNode general in generalNodes) { String multivalued = general.Attributes.GetNamedItem("multivalued").Value; String primitiveType = general.Attributes.GetNamedItem("primitive_type").Value; String lucene_name = general.Attributes.GetNamedItem("lucene_name").Value; String storing = general.Attributes.GetNamedItem("store").Value; String analysing = general.Attributes.GetNamedItem("analysed").Value; var toStore = Lucene.Net.Documents.Field.Store.NO; var toAnalyse = Lucene.Net.Documents.Field.Index.NOT_ANALYZED; if (storing.ToLower().Equals("yes")) { toStore = Lucene.Net.Documents.Field.Store.YES; } if (analysing.ToLower().Equals("yes")) { toAnalyse = Lucene.Net.Documents.Field.Index.ANALYZED; } float boosting = Convert.ToSingle(general.Attributes.GetNamedItem("boost").Value); string[] metadataElementNames = general.Attributes.GetNamedItem("metadata_name").Value.Split(','); foreach (string metadataElementName in metadataElementNames) { XmlNodeList elemList = metadataDoc.SelectNodes(metadataElementName); for (int i = 0; i < elemList.Count; i++) { Field a = new Field(lucene_name, elemList[i].InnerText, toStore, toAnalyse); a.Boost = boosting; dataset.Add(a); dataset.Add(new Field("ng_all", elemList[i].InnerText, Lucene.Net.Documents.Field.Store.NO, Field.Index.ANALYZED)); writeAutoCompleteIndex(docId, lucene_name, elemList[i].InnerText); writeAutoCompleteIndex(docId, "ng_all", elemList[i].InnerText); } } } indexWriter.AddDocument(dataset); }
private HttpResponseMessage getData(long id, int version, string token, string projection = null, string selection = null) { DatasetManager datasetManager = new DatasetManager(); UserManager userManager = new UserManager(); EntityPermissionManager entityPermissionManager = new EntityPermissionManager(); EntityManager entityManager = new EntityManager(); bool isPublic = false; try { // if a dataset is public, then the api should also return data if there is no token for a user #region is public long?entityTypeId = entityManager.FindByName(typeof(Dataset).Name)?.Id; entityTypeId = entityTypeId.HasValue ? entityTypeId.Value : -1; isPublic = entityPermissionManager.Exists(null, entityTypeId.Value, id); #endregion is public if (!isPublic && String.IsNullOrEmpty(token)) { var request = Request.CreateResponse(); request.Content = new StringContent("Bearer token not exist."); return(request); } User user = userManager.Users.Where(u => u.Token.Equals(token)).FirstOrDefault(); if (isPublic || user != null) { if (isPublic || entityPermissionManager.HasEffectiveRight(user.Name, typeof(Dataset), id, RightType.Read)) { XmlDatasetHelper xmlDatasetHelper = new XmlDatasetHelper(); OutputDataManager ioOutputDataManager = new OutputDataManager(); Dataset dataset = datasetManager.GetDataset(id); // If the requested version is -1 or the last version of the dataset, then the data will be loaded in a // different way than when loading the data from an older version bool isLatestVersion = false; if (version == -1 || dataset.Versions.Count == version) { isLatestVersion = true; } if (isLatestVersion) { #region get data from the latest version of a dataset DatasetVersion datasetVersion = datasetManager.GetDatasetLatestVersion(id); string title = datasetVersion.Title; // check the data sturcture type ... if (datasetVersion.Dataset.DataStructure.Self is StructuredDataStructure) { //FilterExpression filter = null; //OrderByExpression orderBy = null; //ProjectionExpression projectionExpression = GetProjectionExpression(projection); // apply selection and projection long count = datasetManager.RowCount(id); DataTable dt = datasetManager.GetLatestDatasetVersionTuples(id, null, null, null, 0, (int)count); dt.Strip(); if (!string.IsNullOrEmpty(selection)) { dt = OutputDataManager.SelectionOnDataTable(dt, selection, true); } if (!string.IsNullOrEmpty(projection)) { // make the header names upper case to make them case insensitive dt = OutputDataManager.ProjectionOnDataTable(dt, projection.ToUpper().Split(',')); } dt.TableName = id + "_data"; DatasetModel model = new DatasetModel(); model.DataTable = dt; var response = Request.CreateResponse(); response.Content = new ObjectContent(typeof(DatasetModel), model, new DatasetModelCsvFormatter(model.DataTable.TableName)); response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv"); //set headers on the "response" return(response); #endregion get data from the latest version of a dataset //return model; } else { return(Request.CreateResponse()); } } else { #region load data of a older version of a dataset int index = version - 1; if (version >= dataset.Versions.Count) { return(Request.CreateResponse(HttpStatusCode.PreconditionFailed, String.Format("This version ({0}) is not available for the dataset", version))); } DatasetVersion datasetVersion = dataset.Versions.OrderBy(d => d.Timestamp).ElementAt(version - 1); string title = datasetVersion.Title; // check the data sturcture type ... if (datasetVersion.Dataset.DataStructure.Self is StructuredDataStructure) { //FilterExpression filter = null; //OrderByExpression orderBy = null; // apply selection and projection int count = datasetManager.GetDatasetVersionEffectiveTuples(datasetVersion).Count; DataTable dt = datasetManager.GetDatasetVersionTuples(datasetVersion.Id, 0, count); dt.Strip(); if (!string.IsNullOrEmpty(selection)) { dt = OutputDataManager.SelectionOnDataTable(dt, selection); } if (!string.IsNullOrEmpty(projection)) { // make the header names upper case to make them case insensitive dt = OutputDataManager.ProjectionOnDataTable(dt, projection.ToUpper().Split(',')); } dt.TableName = id + "_data"; DatasetModel model = new DatasetModel(); model.DataTable = dt; var response = Request.CreateResponse(); response.Content = new ObjectContent(typeof(DatasetModel), model, new DatasetModelCsvFormatter(model.DataTable.TableName)); response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv"); //set headers on the "response" return(response); } else // return files of the unstructure dataset { return(Request.CreateResponse()); } #endregion load data of a older version of a dataset } } else // has rights? { var request = Request.CreateResponse(); request.Content = new StringContent("User has no read right."); return(request); } } else { var request = Request.CreateResponse(); request.Content = new StringContent("User is not available."); return(request); } } catch (Exception e) { throw e; } finally { datasetManager.Dispose(); userManager.Dispose(); entityPermissionManager.Dispose(); entityManager.Dispose(); } }
// GET api/<controller>/5 public HttpResponseMessage Get(int id) { // get token from the request string token = this.Request.Headers.Authorization?.Parameter; // flag for the public dataset check bool isPublic = false; using (EntityPermissionManager entityPermissionManager = new EntityPermissionManager()) using (EntityManager entityManager = new EntityManager()) using (UserManager userManager = new UserManager()) { // load the entity id of the e.g. is it a sample or dataset or publication long?entityTypeId = entityManager.FindByName(typeof(Dataset).Name)?.Id; entityTypeId = entityTypeId.HasValue ? entityTypeId.Value : -1; // if the subject is null and one entry exist, means this dataset is public isPublic = entityPermissionManager.Exists(null, entityTypeId.Value, id); // if its not public and no token exist - fire exception if (!isPublic && String.IsNullOrEmpty(token)) { var request = Request.CreateResponse(); request.Content = new StringContent("Bearer token not exist."); return(request); } // load user based on token User user = userManager.Users.Where(u => u.Token.Equals(token)).FirstOrDefault(); if (isPublic || user != null) { if (isPublic || entityPermissionManager.HasEffectiveRight(user.Name, typeof(Dataset), id, RightType.Read)) { var filepath = Path.Combine(AppConfiguration.DataPath, "Datasets", id.ToString(), "geoengine.json"); if (File.Exists(filepath)) { var response = Request.CreateResponse(); response.Content = new StringContent(File.ReadAllText(filepath), System.Text.Encoding.UTF8, "application/json"); return(response); } else { var request = Request.CreateResponse(); request.Content = new StringContent("Georeference is not available."); return(request); } } else // has rights? { var request = Request.CreateResponse(); request.Content = new StringContent("User has no read right."); return(request); } } else { var request = Request.CreateResponse(); request.Content = new StringContent("User is not available."); return(request); } } }
public static XDocument ListIdentifiersOrRecords( string verb, string from, string until, string metadataPrefix, string set, string resumptionToken, bool isRoundtrip, List <XElement> errorList, bool?loadAbout) { List <XElement> errors = errorList; DateTime? fromDate = DateTime.MinValue; DateTime? untilDate = DateTime.MaxValue; /* VERB */ bool isRecord = false; if (String.IsNullOrEmpty(verb) || !(verb == "ListIdentifiers" || verb == "ListRecords")) { errors.Add(MlErrors.badVerbArgument); } else { isRecord = verb == "ListRecords"; } /* FROM */ bool isFrom = !String.IsNullOrEmpty(from); fromDate = MlDecode.SafeDateTime(from); if (isFrom && fromDate == null) { errors.Add(MlErrors.badFromArgument); } /* UNTIL */ bool isUntil = !String.IsNullOrEmpty(until); untilDate = MlDecode.SafeDateTime(until); if (isUntil && untilDate == null) { errors.Add(MlErrors.badUntilArgument); } if (isFrom && isUntil && fromDate > untilDate) { errors.Add(MlErrors.badFromAndUntilArgument); } // if both dates exist, they should be in the same format if (!string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(until)) { if (from.Count() != until.Count()) { errors.Add(MlErrors.badFromAndUntilFormatArgument); } } if (fromDate == null) { fromDate = new DateTime(1900, 1, 1); } if (until == null) { untilDate = DateTime.Now; } if (untilDate != null) { untilDate = ((DateTime)untilDate).AddMilliseconds(999); } /* METADATA PREFIX */ bool isPrefixOk = !String.IsNullOrEmpty(metadataPrefix); /* SETS */ bool isSet = !String.IsNullOrEmpty(set); if (isSet && !Properties.supportSets) { errors.Add(MlErrors.noSetHierarchy); } /* RESUMPTION TOKEN */ bool isResumption = !String.IsNullOrEmpty(resumptionToken); if (isResumption && !isRoundtrip) { if (isFrom || isUntil || isPrefixOk || isSet) { errors.Add(MlErrors.badResumptionArgumentOnly); } if (!(Properties.resumptionTokens.ContainsKey(resumptionToken) && Properties.resumptionTokens[resumptionToken].Verb == verb && Properties.resumptionTokens[resumptionToken].ExpirationDate >= DateTime.UtcNow)) { errors.Insert(0, MlErrors.badResumptionArgument); } if (errors.Count == 0) { return(ListIdentifiersOrRecords( verb, Properties.resumptionTokens[resumptionToken].From.HasValue ? Properties.resumptionTokens[resumptionToken].From.Value.ToUniversalTime().ToString(Properties.granularity) : null, Properties.resumptionTokens[resumptionToken].Until.HasValue ? Properties.resumptionTokens[resumptionToken].Until.Value.ToUniversalTime().ToString(Properties.granularity) : null, Properties.resumptionTokens[resumptionToken].MetadataPrefix, Properties.resumptionTokens[resumptionToken].Set, resumptionToken, true, errors, loadAbout)); } } if (!isPrefixOk) /* Check if the only required attribute is included in the request */ { errors.Add(MlErrors.badMetadataArgument); } else if (FormatList.Prefix2Int(metadataPrefix) == 0) { errors.Add(MlErrors.cannotDisseminateFormat); } bool isAbout = loadAbout.HasValue ? loadAbout.Value : Properties.loadAbout; XElement request = new XElement("request", new XAttribute("verb", verb), isFrom ? new XAttribute("from", from) : null, isUntil ? new XAttribute("until", until) : null, isPrefixOk ? new XAttribute("metadataPrefix", metadataPrefix) : null, isSet ? new XAttribute("set", set) : null, isResumption ? new XAttribute("resumptionToken", resumptionToken) : null, Properties.baseURL); if (errors.Count > 0) { errors.Insert(0, request); /* add request on the first position, that it will be diplayed before errors */ return(CreateXml(errors.ToArray())); } var records = new List <RecordQueryResult>(); List <string> sets = Common.Helper.GetAllSets(set); var formatNum = FormatList.Prefix2Int(metadataPrefix); EntityManager entityManager = new EntityManager(); EntityPermissionManager entityPermissionManager = new EntityPermissionManager(); DatasetManager datasetManager = new DatasetManager(); OAIHelper oaiHelper = new OAIHelper(); try { //1. Get list of all datasetids which shoudl be harvested - // ToDo use also the existing parameters like from date long?entityTypeId = entityManager.FindByName(typeof(Dataset).Name)?.Id; entityTypeId = entityTypeId.HasValue ? entityTypeId.Value : -1; // get all datasetids with the last modify date List <long> dsvIds = datasetManager.GetDatasetVersionLatestIds(); // ToDo to get all datasets with the last modfied date, the datasetversionrepo of the dataset manager is used, but its many wrong because of session problem in the past List <long> datasetIds = datasetManager.GetDatasetLatestIds(); datasetIds = datasetManager.DatasetVersionRepo.Query(dsv => dsvIds.Contains(dsv.Id) && dsv.Timestamp >= fromDate && dsv.Timestamp <= untilDate ).Select(dsv => dsv.Dataset.Id).ToList(); //2. Generate a list of headers var recordsQuery = new List <Header>(); foreach (long id in datasetIds) { if (entityPermissionManager.Exists(null, entityTypeId.Value, id)) { recordsQuery.Add(oaiHelper.GetHeader(id)); } } if (isSet) { recordsQuery = recordsQuery.Where(h => h.OAI_Set.Equals(AppConfiguration.ApplicationName)).ToList(); } int recordsCount = recordsQuery.Count(); if (recordsCount == 0) { return(CreateXml(new XElement[] { request, MlErrors.noRecordsMatch })); } else if (isRoundtrip) { Properties.resumptionTokens[resumptionToken].CompleteListSize = recordsCount; recordsQuery = recordsQuery.AsEnumerable().Skip( Properties.resumptionTokens[resumptionToken].Cursor.Value).Take( isRecord ? Properties.maxRecordsInList : Properties.maxIdentifiersInList).ToList(); } else if ((isRecord ? Properties.resumeListRecords : Properties.resumeListIdentifiers) && (isRecord ? recordsCount > Properties.maxRecordsInList : recordsCount > Properties.maxIdentifiersInList)) { resumptionToken = Common.Helper.CreateGuid(); isResumption = true; Properties.resumptionTokens.Add(resumptionToken, new ResumptionToken() { Verb = verb, From = isFrom ? fromDate : null, Until = isUntil ? untilDate : null, MetadataPrefix = metadataPrefix, Set = set, ExpirationDate = DateTime.UtcNow.Add(Properties.expirationTimeSpan), CompleteListSize = recordsCount, Cursor = 0 }); recordsQuery = recordsQuery.AsEnumerable().Take( isRecord ? Properties.maxRecordsInList : Properties.maxIdentifiersInList).ToList(); } /* get data from database */ //var recGroup = (from rec in recordsQuery // join omd in context.ObjectMetadata on rec.HeaderId equals omd.ObjectId // join mdt in context.Metadata on omd.MetadataId equals mdt.MetadataId // group new { OmdMetaType = omd.MetadataType, OaiMetaData = mdt } by rec into grp // select grp).ToList(); /* distribute data into logical units */ foreach (var header in recordsQuery) { long id = oaiHelper.ConvertToId(header.OAI_Identifier); //ToDo add about to the RecordQueryResult object, currently its only null records.Add(new RecordQueryResult(header, oaiHelper.GetMetadata(id, metadataPrefix), null)); } } finally { datasetManager.Dispose(); entityPermissionManager.Dispose(); } bool isCompleted = isResumption ? Properties.resumptionTokens[resumptionToken].Cursor + records.Count >= Properties.resumptionTokens[resumptionToken].CompleteListSize : false; XElement list = new XElement(verb, isRecord ? GetListRecords(records, isAbout) : GetListIdentifiers(records), isResumption ? /* add resumption token or not */ MlEncode.ResumptionToken(Properties.resumptionTokens[resumptionToken], resumptionToken, isCompleted) : null); if (isResumption) { if (isCompleted) { Properties.resumptionTokens.Remove(resumptionToken); } else { Properties.resumptionTokens[resumptionToken].Cursor = Properties.resumptionTokens[resumptionToken].Cursor + records.Count; } } return(CreateXml(new XElement[] { request, list })); }
public HttpResponseMessage Get(int id) { if (id == 0) { return(Request.CreateErrorResponse(HttpStatusCode.PreconditionFailed, "the dataset id can not be 0.")); } using (DatasetManager datasetManager = new DatasetManager()) using (UserManager userManager = new UserManager()) using (EntityPermissionManager entityPermissionManager = new EntityPermissionManager()) using (EntityManager entityManager = new EntityManager()) { bool isPublic = false; User user = null; try { #region is public long?entityTypeId = entityManager.FindByName(typeof(Dataset).Name)?.Id; entityTypeId = entityTypeId.HasValue ? entityTypeId.Value : -1; isPublic = entityPermissionManager.Exists(null, entityTypeId.Value, id); #endregion is public #region security string token = this.Request.Headers.Authorization?.Parameter; if (!isPublic && String.IsNullOrEmpty(token)) { return(Request.CreateErrorResponse(HttpStatusCode.PreconditionFailed, "Bearer token not exist.")); } user = userManager.Users.Where(u => u.Token.Equals(token)).FirstOrDefault(); if (!isPublic && user == null) { return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Token is not valid.")); } //check permissions //entity permissions if (id > 0) { Dataset d = datasetManager.GetDataset(id); if (d == null) { return(Request.CreateErrorResponse(HttpStatusCode.PreconditionFailed, "the dataset with the id (" + id + ") does not exist.")); } if (!isPublic && !entityPermissionManager.HasEffectiveRight(user.Name, typeof(Dataset), id, RightType.Read)) { return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "The token is not authorized to write into the dataset.")); } } #endregion security var dataset = datasetManager.GetDataset(id); if (dataset == null) { return(Request.CreateErrorResponse(HttpStatusCode.PreconditionFailed, "the dataset with the id (" + id + ") does not exist.")); } var model = GetApiDatasetAttachmentsModel(id, datasetManager); using (var response = this.Request.CreateResponse(HttpStatusCode.OK)) { string json = JsonConvert.SerializeObject(model); response.Content = new StringContent(json, Encoding.UTF8, "application/json"); if (model != null) { return(response); } return(null); } } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message)); } } }
public HttpResponseMessage Get(int id, long attachmentid) { if (id == 0) { return(Request.CreateErrorResponse(HttpStatusCode.PreconditionFailed, "the dataset id can not be 0.")); } if (attachmentid == 0) { return(Request.CreateErrorResponse(HttpStatusCode.PreconditionFailed, "the attachment id can not be 0.")); } DatasetManager datasetManager = new DatasetManager(); UserManager userManager = new UserManager(); EntityPermissionManager entityPermissionManager = new EntityPermissionManager(); EntityManager entityManager = new EntityManager(); bool isPublic = false; User user = null; try { // if a dataset is public, then the api should also return data if there is no token for a user #region is public entityManager = new EntityManager(); long?entityTypeId = entityManager.FindByName(typeof(Dataset).Name)?.Id; entityTypeId = entityTypeId.HasValue ? entityTypeId.Value : -1; isPublic = entityPermissionManager.Exists(null, entityTypeId.Value, id); #endregion is public #region security string token = this.Request.Headers.Authorization?.Parameter; if (!isPublic && String.IsNullOrEmpty(token)) { return(Request.CreateErrorResponse(HttpStatusCode.PreconditionFailed, "Bearer token not exist.")); } user = userManager.Users.Where(u => u.Token.Equals(token)).FirstOrDefault(); if (!isPublic && user == null) { return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Token is not valid.")); } //check permissions //entity permissions if (id > 0) { Dataset d = datasetManager.GetDataset(id); if (d == null) { return(Request.CreateErrorResponse(HttpStatusCode.PreconditionFailed, "the dataset with the id (" + id + ") does not exist.")); } if (!isPublic && !entityPermissionManager.HasEffectiveRight(user.Name, typeof(Dataset), id, RightType.Read)) { return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "The token is not authorized to write into the dataset.")); } } #endregion security //check if dataset exist var dataset = datasetManager.GetDataset(id); if (dataset == null) { return(Request.CreateErrorResponse(HttpStatusCode.PreconditionFailed, "the dataset with the id (" + id + ") does not exist.")); } var model = GetApiDatasetAttachmentsModel(id, datasetManager); //check if attachment belongs to the dataset exist if (!model.Attachments.Any(a => a.Id.Equals(attachmentid))) { return(Request.CreateErrorResponse(HttpStatusCode.PreconditionFailed, "the attechment with the id (" + attachmentid + ") does not belong to the dataset with the id (" + id + ").")); } DatasetVersion datasetVersion = datasetManager.GetDatasetLatestVersion(id); var attachment = datasetVersion.ContentDescriptors.Where(a => a.Id.Equals(attachmentid)).FirstOrDefault(); // check if file exist or not string path = Path.Combine(AppConfiguration.DataPath, attachment.URI); //converting file into bytes array var dataBytes = File.ReadAllBytes(path); //adding bytes to memory stream var dataStream = new FileStream(path, FileMode.OpenOrCreate); HttpResponseMessage httpResponseMessage; httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK); httpResponseMessage.Content = new StreamContent(dataStream); httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); httpResponseMessage.Content.Headers.ContentDisposition.FileName = attachment.Name; httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(attachment.MimeType); return(httpResponseMessage); } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message)); } finally { datasetManager.Dispose(); userManager.Dispose(); entityPermissionManager.Dispose(); entityManager.Dispose(); } }
public ActionResult Instances_Select(long entityId) { var entityManager = new EntityManager(); var entityPermissionManager = new EntityPermissionManager(); try { var instanceStore = (IEntityStore)Activator.CreateInstance(entityManager.FindById(entityId).EntityStoreType); var instances = instanceStore.GetEntities().Select(i => EntityInstanceGridRowModel.Convert(i, entityPermissionManager.Exists(null, entityId, i.Id))).ToList(); return(View(new GridModel <EntityInstanceGridRowModel> { Data = instances })); } finally { entityManager.Dispose(); entityPermissionManager.Dispose(); } }