/// <summary> /// Saves the templates to the given folder /// </summary> /// <param name="path">a folder</param> private void SaveTemplates(string path) { for (int k = 0; k < templates.Items.Count; k++) { EntityBundle bundle = templates.Items[k].Tag as EntityBundle; if (bundle == null) { return; } FileStream fs = new FileStream(path + "\\" + bundle.Name + ".template", FileMode.Create); BinaryFormatter f = new BinaryFormatter(); try { f.Serialize(fs, bundle); } catch (Exception exc) { mediator.Output(exc.Message, OutputInfoLevels.Exception); continue; } catch { mediator.Output("Non-CLS exception caught.", OutputInfoLevels.Exception); continue; } finally { fs.Close(); } } }
public FilestoreFile Create(SampleEventMap map, EntityBundle sites, EntityBundle instruments) { if (this.CanModify(map)) { Guid id = Guid.NewGuid(); WaterQualityDET det = new WaterQualityDET(); det.Id = id; det.Owner = "originator:" + sites.PrincipalOrgId.Identity.ToString() + ":" + instruments.PrincipalOrgId.Identity.ToString(); int ct = 0; foreach (BundleElement cur in sites.Elements) { SiteDTO tmp = new SiteDTO(); tmp.Key = cur.LocalKey; tmp.Name = cur.DisplayName; det.Sites.Add(tmp); ct++; } if (ct > 0) //has to be elements in the collection { ct = 0; foreach (BundleElement cur in instruments.Elements) { InstrumentDTO tmp = new InstrumentDTO(); tmp.Key = cur.LocalKey; tmp.Name = cur.DisplayName; det.Instruments.Add(tmp); ct++; } if (ct > 0) { det.Validate(); if (det.ValidationIssues.Count == 0) { IFileStoreProvider prov = this.FileStore; if (prov != null) { FilestoreFile fil = prov.Make(id); if (fil != null) { ExcelWaterQualityDET excel = new ExcelWaterQualityDET(det); excel.Save(fil); fil.Flush(); fil.Seek(0, System.IO.SeekOrigin.Begin); return(fil); } } } } } } return(null); }
public FilestoreFile CreateVeg(CompoundIdentity sampleEventId, EntityBundle sites, EntityBundle plotTypes, EntityBundle shrubSpecies, EntityBundle treeSpecies, EntityBundle herbSpecies, EntityBundle nonLiving, bool isPrivate) { if (!sampleEventId.IsNullOrEmpty() && sites != null && plotTypes != null && shrubSpecies != null && treeSpecies != null && herbSpecies != null && sites.DataType == BundleDataType.Site && plotTypes.DataType == BundleDataType.PlotType && shrubSpecies.DataType == BundleDataType.TaxaUnit && treeSpecies.DataType == BundleDataType.TaxaUnit && herbSpecies.DataType == BundleDataType.TaxaUnit) { if (nonLiving != null) { if (nonLiving.DataType != BundleDataType.TaxaUnit) { return(null); //if we have nonLiving, they better be taxaunits } } SampleEventMap map = DetRegistry.Instance.Get(sampleEventId); if (map == null) { map = DetRegistry.Instance.Create(sampleEventId); } else if (map.Contains(KnownDetType.Veg)) { return(null); //can't have more than 1 } VegDetProcessor wq = new VegDetProcessor(this.ctx); FilestoreFile fil = wq.Create(map, sites, plotTypes, shrubSpecies, treeSpecies, herbSpecies, nonLiving, isPrivate); //note the permission is checked in there if (fil != null) { map.Add(fil.FileId, KnownDetType.Veg, isPrivate); List <Guid> bundles = map.Get(KnownDetType.Veg).BundleIds; bundles.Add(sites.Id); bundles.Add(plotTypes.Id); bundles.Add(shrubSpecies.Id); bundles.Add(treeSpecies.Id); bundles.Add(herbSpecies.Id); if (nonLiving != null) { bundles.Add(nonLiving.Id); } DetRegistry.Instance.Update(map); SamplingEvent e = this.GetSampleEvent(map.SampleEventId); if (e != null) { string tmp = e.Name.Trim().Replace(' ', '_'); if (tmp.Length > 25) { tmp = tmp.Substring(0, 24); } fil.FileName = tmp + "_Veg.xlsx"; FileStoreManager.Instance.GetProvider().Update(fil); } } return(fil); } return(null); }
private CompoundIdentity GetTaxa(string taxaId, EntityBundle taxaUnits, EntityBundle nonLiving) { if (taxaUnits.Contains(taxaId)) { return(taxaUnits.Get(taxaId).EntityId); } if (nonLiving != null && nonLiving.Contains(taxaId)) { return(nonLiving.Get(taxaId).EntityId); } return(null); }
public FilestoreFile CreateFish(CompoundIdentity sampleEventId, EntityBundle sites, EntityBundle nets, EntityBundle fishSpecies, EntityBundle macroSpecies, bool isPrivate) { if (!sampleEventId.IsNullOrEmpty() && sites != null && nets != null && fishSpecies != null && sites.DataType == BundleDataType.Site && nets.DataType == BundleDataType.Instrument && fishSpecies.DataType == BundleDataType.TaxaUnit) { if (macroSpecies != null) { if (macroSpecies.DataType != BundleDataType.TaxaUnit) { return(null); //if we have macroSpecies, they better be taxaunits } } SampleEventMap map = DetRegistry.Instance.Get(sampleEventId); if (map == null) { map = DetRegistry.Instance.Create(sampleEventId); } else if (map.Contains(KnownDetType.Fish)) { return(null); //can't have more than 1 } FishDetProcessor wq = new FishDetProcessor(this.ctx); FilestoreFile fil = wq.Create(map, sites, nets, fishSpecies, macroSpecies, isPrivate); //note the permission is checked in there if (fil != null) { map.Add(fil.FileId, KnownDetType.Fish, isPrivate); List <Guid> bundles = map.Get(KnownDetType.Fish).BundleIds; bundles.Add(sites.Id); bundles.Add(nets.Id); bundles.Add(fishSpecies.Id); if (macroSpecies != null) { bundles.Add(macroSpecies.Id); } DetRegistry.Instance.Update(map); SamplingEvent e = this.GetSampleEvent(map.SampleEventId); if (e != null) { string tmp = e.Name.Trim().Replace(' ', '_'); if (tmp.Length > 25) { tmp = tmp.Substring(0, 24); } fil.FileName = tmp + "_Fish.xlsx"; FileStoreManager.Instance.GetProvider().Update(fil); } } return(fil); } return(null); }
private UpdateStatus DeltaLoad(CompoundIdentity seId, EntityBundle sites, EntityBundle nets, EntityBundle fishSpecies, EntityBundle macroSpecies, FishDET curdet, FishDET olddet, ICatchEffortProvider depl, ICatchHaulProvider haul, IFishProvider fish, SampleEventMap map) { UpdateStatus stat = null; if (curdet.CatchEfforts.Count < 1) //ok, old file had data, this file has none { //what do we want to do? -- could just do a delete all stat = new UpdateStatus(UpdateIssue.DataIssue); stat.Add(new IssueNotice("NoData", "Delete then create")); SampleEventMapItem tmp = map.Get(KnownDetType.Fish); //fetch it back if (this.Delete(map, false)) { stat = new UpdateStatus(UpdateIssue.AllOk); stat.Add(new IssueNotice("NoIssues", "No issues")); } else { this.Add("Failure", "Delete", UpdateIssue.Security, stat); } } else { //data in both files, this is a change/append situation stat = new UpdateStatus(UpdateIssue.DataIssue); stat.Add(new IssueNotice("NoData", "Delete then create")); SampleEventMapItem tmp = map.Get(KnownDetType.Fish); //fetch it back if (this.DeleteData(map)) { if (this.InitialLoad(seId, sites, nets, fishSpecies, macroSpecies, curdet, depl, haul, fish, tmp.IsPrivate) != null) { stat = new UpdateStatus(UpdateIssue.AllOk); stat.Add(new IssueNotice("NoIssues", "No issues")); } else { this.Add("Failure", "Create", UpdateIssue.Security, stat); } } else { this.Add("Failure", "Delete", UpdateIssue.Security, stat); } } return(stat); }
private UpdateStatus DeltaLoad(CompoundIdentity seId, EntityBundle sites, EntityBundle plotTypes, EntityBundle shrubSpecies, EntityBundle treeSpecies, EntityBundle herbSpecies, EntityBundle nonLiving, VegDET curdet, VegDET olddet, IVegSurveyProvider depl, IVegSampleProvider meas, SampleEventMap map) { UpdateStatus stat = null; if (curdet.Surveys.Count < 1) //ok, old file had data, this file has none { //what do we want to do? -- could just do a delete all stat = new UpdateStatus(UpdateIssue.DataIssue); stat.Add(new IssueNotice("NoData", "Delete then create")); SampleEventMapItem tmp = map.Get(KnownDetType.Veg); //fetch it back if (this.Delete(map, false)) { stat = new UpdateStatus(UpdateIssue.AllOk); stat.Add(new IssueNotice("NoIssues", "No issues")); } else { this.Add("Failure", "Delete", UpdateIssue.Security, stat); } } else { //data in both files, this is a change/append situation stat = new UpdateStatus(UpdateIssue.DataIssue); stat.Add(new IssueNotice("NoData", "Delete then create")); SampleEventMapItem tmp = map.Get(KnownDetType.Veg); //fetch it back if (this.DeleteData(map)) { if (this.InitialLoad(seId, sites, plotTypes, shrubSpecies, treeSpecies, herbSpecies, nonLiving, curdet, depl, meas, tmp.IsPrivate) != null) { stat = new UpdateStatus(UpdateIssue.AllOk); stat.Add(new IssueNotice("NoIssues", "No issues")); } else { this.Add("Failure", "Create", UpdateIssue.Security, stat); } } else { this.Add("Failure", "Delete", UpdateIssue.Security, stat); } } return(stat); }
private UpdateStatus DeltaLoad(CompoundIdentity seId, EntityBundle sites, EntityBundle instruments, WaterQualityDET curdet, WaterQualityDET olddet, IWQDeploymentProvider depl, IWQMeasurementProvider meas, SampleEventMap map) { UpdateStatus stat = new UpdateStatus(UpdateIssue.SystemIssue); //Not implemented if (curdet.Deployments.Count < 1) //ok, old file had data, this file has none { //what do we want to do? -- could just do a delete all stat = new UpdateStatus(UpdateIssue.DataIssue); stat.Add(new IssueNotice("NoData", "Delete then create")); SampleEventMapItem tmp = map.Get(KnownDetType.WaterQuality); //fetch it back if (this.Delete(map, false)) { stat = new UpdateStatus(UpdateIssue.AllOk); stat.Add(new IssueNotice("NoIssues", "No issues")); } else { this.Add("Failure", "Delete", UpdateIssue.Security, stat); } } else { //data in both files, this is a change/append situation stat = new UpdateStatus(UpdateIssue.DataIssue); stat.Add(new IssueNotice("NoData", "Delete then create")); SampleEventMapItem tmp = map.Get(KnownDetType.WaterQuality); //fetch it back if (this.DeleteData(map)) { if (this.InitialLoad(seId, sites, instruments, curdet, depl, meas, tmp.IsPrivate) != null) { stat = new UpdateStatus(UpdateIssue.AllOk); stat.Add(new IssueNotice("NoIssues", "No issues")); } else { this.Add("Failure", "Create", UpdateIssue.Security, stat); } } else { this.Add("Failure", "Delete", UpdateIssue.Security, stat); } } return(stat); }
public static JObject ToJson(EntityBundle item) { if (item != null) { JObject o = new JObject(); o.Add(JsonUtils.Id, new JValue(item.Id).ToString()); o.Add(JsonUtils.OwnerId, JsonUtils.ToJson(item.PrincipalOrgId)); o.Add(JsonUtils.Name, new JValue(item.Name)); o.Add(Jsonifier.Type, new JValue(item.DataType.ToString())); JArray tmp = ToJson(item.Elements); if (tmp != null) { o.Add(Jsonifier.Items, tmp); } return(o); } return(null); }
private void Favorites_ItemActivate(object sender, System.EventArgs e) { ListViewItem item; if (templates.SelectedItems.Count > 0) { item = templates.SelectedItems[0]; EntityBundle bundle = item.Tag as EntityBundle; EntityBundle copy; if (bundle != null) { //make sure the graphcontrol is there mediator.OpenGraphTab(); bundle.Site = mediator.GraphControl; //here you need to take another copy, otherwise it'll result in a linked instance copy = bundle.Copy(); //unwrap the bundle, this assigns the site and does some postserialization GraphLib.IO.Binary.BinarySerializer.UnwrapBundle(copy, mediator.GraphControl); //change the UID if (copy != null) { for (int k = 0; k < copy.Shapes.Count; k++) { copy.Shapes[k].GenerateNewUID(); //the connectors as well foreach (Netron.GraphLib.Connector c in copy.Shapes[k].Connectors) { c.GenerateNewUID(); } } for (int k = 0; k < copy.Connections.Count; k++) { copy.Connections[k].GenerateNewUID(); } } mediator.GraphControl.AddBundle(copy); } } }
public FilestoreFile CreateWQ(CompoundIdentity sampleEventId, EntityBundle sites, EntityBundle instruments, bool isPrivate) { if (!sampleEventId.IsNullOrEmpty() && sites != null && instruments != null && sites.DataType == BundleDataType.Site && instruments.DataType == BundleDataType.Instrument) { SampleEventMap map = DetRegistry.Instance.Get(sampleEventId); if (map == null) { map = DetRegistry.Instance.Create(sampleEventId); } else if (map.Contains(KnownDetType.WaterQuality)) { return(null); //can't have more than 1 } WqDetProcessor wq = new WqDetProcessor(this.ctx); FilestoreFile fil = wq.Create(map, sites, instruments); //note the permission is checked in there if (fil != null) { map.Add(fil.FileId, KnownDetType.WaterQuality, isPrivate); List <Guid> bundles = map.Get(KnownDetType.WaterQuality).BundleIds; bundles.Add(sites.Id); bundles.Add(instruments.Id); DetRegistry.Instance.Update(map); SamplingEvent e = this.GetSampleEvent(map.SampleEventId); if (e != null) { string tmp = e.Name.Trim().Replace(' ', '_'); if (tmp.Length > 25) { tmp = tmp.Substring(0, 24); } fil.FileName = tmp + "_WQ.xlsx"; FileStoreManager.Instance.GetProvider().Update(fil); } } return(fil); } return(null); }
protected List <EntityBundle> GetBundles(List <Guid> bundleIds) { if (bundleIds != null && bundleIds.Count > 0) { EntityBundleProvider prov = EntityBundleManager.Instance.GetProvider(this.Context); if (prov != null) { List <EntityBundle> tmp = new List <EntityBundle>(); foreach (Guid cur in bundleIds) { EntityBundle item = prov.Get(cur); if (item != null) { tmp.Add(item); } } if (tmp.Count == bundleIds.Count) { return(tmp); } } } return(null); }
private VegSampleDTO GetSample(VegDataDTO item, EntityBundle sites, Dictionary <Tuple <CompoundIdentity, Point2 <double> >, Dictionary <DateTime, VegSampleDTO> > elements) { Dictionary <DateTime, VegSampleDTO> element = null; Tuple <CompoundIdentity, Point2 <double> > loc = GetLocation(item, sites); if (!elements.ContainsKey(loc)) { element = new Dictionary <DateTime, VegSampleDTO>(); elements[loc] = element; } else { element = elements[loc]; } if (element.ContainsKey(item.MeasureDateTime.Value)) { return(element[item.MeasureDateTime.Value]); } VegSampleDTO res = new VegSampleDTO(loc.Item1, item.MeasureDateTime.Value, loc.Item2, float.NaN, float.NaN); element[item.MeasureDateTime.Value] = res; return(res); }
private Tuple <CompoundIdentity, Point2 <double> > GetLocation(VegDataDTO item, EntityBundle sites) { CompoundIdentity id = null; if (!string.IsNullOrEmpty(item.SiteId) && sites.Contains(item.SiteId)) { id = sites.Get(item.SiteId).EntityId; } Point2 <double> loc = null; if (item.AdHocLat.HasValue && item.AdHocLon.HasValue && !MathUtils.IsInfiniteOrNaN(item.AdHocLat.Value) && !MathUtils.IsInfiniteOrNaN(item.AdHocLon.Value)) { loc = GeometryFactory2Double.Instance.ConstructPoint(item.AdHocLon.Value, item.AdHocLat.Value); } return(new Tuple <CompoundIdentity, Point2 <double> >(id, loc)); }
public override void Handle(HttpContext context, CancellationToken cancel) { if (context != null) { UserIdentityBase user = Security.Session.GetUser(context); if (user != null) { UserSecurityContext ctx = new UserSecurityContext(user); string localUrl = RestUtils.LocalUrl(this, context.Request); string meth = RestUtils.StripLocal(this.BaseUrl + "/", localUrl); if (!string.IsNullOrEmpty(meth)) { try { if (meth.StartsWith(Get, StringComparison.OrdinalIgnoreCase)) { try { EntityBundleProvider prov = EntityBundleManager.Instance.GetProvider(ctx); if (prov != null) { JArray jbundles = Jsonifier.ToJson(prov.Get()); if (jbundles != null) { RestUtils.Push(context.Response, JsonOpStatus.Ok, jbundles.ToString()); return; } else { RestUtils.Push(context.Response, JsonOpStatus.Ok, "[]"); return; } } RestUtils.Push(context.Response, JsonOpStatus.Failed); } catch { RestUtils.Push(context.Response, JsonOpStatus.Failed); return; } } else if (meth.StartsWith(In, StringComparison.OrdinalIgnoreCase)) { //just need a bundle id to get {id:<id>} JToken token = JsonUtils.GetDataPayload(context.Request); if (token != null) { JObject o = token as JObject; if (o != null) { if (o[JsonUtils.Id] != null) { //Guid id = JsonUtils.ToGuid(token[JsonUtils.Id]); Guid id = JsonUtils.ToGuid(o[JsonUtils.Id] as JToken); if (!Guid.Empty.Equals(id)) { EntityBundleProvider prov = EntityBundleManager.Instance.GetProvider(ctx); EntityBundle bundle = prov.Get(id); if (bundle != null) { RestUtils.Push(context.Response, JsonOpStatus.Ok, Jsonifier.ToJson(bundle)); return; } } } } } } else if (meth.StartsWith(Create, StringComparison.OrdinalIgnoreCase)) { JToken token = JsonUtils.GetDataPayload(context.Request); if (token != null) { if (token[JsonUtils.Name] != null && token[JsonUtils.OwnerId] != null && token[Jsonifier.Type] != null && token[Jsonifier.Items] != null) { string name = token[JsonUtils.Name].ToString(); if (!string.IsNullOrEmpty(name)) { string type = token[Jsonifier.Type].ToString(); if (!string.IsNullOrEmpty(type)) { BundleDataType datType; if (type.StartsWith("site", StringComparison.OrdinalIgnoreCase)) { datType = BundleDataType.Site; } else if (type.StartsWith("taxa", StringComparison.OrdinalIgnoreCase)) { datType = BundleDataType.TaxaUnit; } else if (type.StartsWith("inst", StringComparison.OrdinalIgnoreCase)) { datType = BundleDataType.Instrument; } else { context.Response.StatusCode = HttpStatusCodes.Status400BadRequest; return; } CompoundIdentity cid = JsonUtils.ToId(token[JsonUtils.OwnerId]); if (cid != null && !cid.IsEmpty) { JArray itemsArr = Items.GetItems(token[Jsonifier.Items]); if (itemsArr != null && itemsArr.Count > 0) { List <Tuple <CompoundIdentity, string, string> > items = new List <Tuple <CompoundIdentity, string, string> >(); foreach (JToken cur in itemsArr) { Tuple <CompoundIdentity, string, string> tpl = Items.GetItem(cur); if (tpl != null) { items.Add(tpl); } } if (items.Count == itemsArr.Count) { if (Items.VandV(items, datType, ctx)) { EntityBundleProvider prov = EntityBundleManager.Instance.GetProvider(ctx); EntityBundle bundle = prov.Create(name, cid, datType); if (bundle != null) { foreach (Tuple <CompoundIdentity, string, string> tpl in items) { if (bundle.Add(tpl.Item1, tpl.Item2, tpl.Item3) == null) { RestUtils.Push(context.Response, JsonOpStatus.Failed, "\"failed to add item to bundle\""); return; } } if (prov.Update(bundle)) { RestUtils.Push(context.Response, JsonOpStatus.Ok, Jsonifier.ToJson(bundle)); return; } } } } } } } } } } } else if (meth.StartsWith(Update, StringComparison.OrdinalIgnoreCase)) //note, this will just append items to the existing bundle and update bundle display name { //needs to have same content as create mostly -- doesn't require orgid (we ignore that since it can't change), and name is optional JToken token = JsonUtils.GetDataPayload(context.Request); if (token != null) { if (token[JsonUtils.Id] != null && token[Jsonifier.Items] != null) { string name = null; if (token[JsonUtils.Name] != null) { name = token[JsonUtils.Name].ToString(); } Guid id = JsonUtils.ToGuid(token[JsonUtils.Id]); if (!Guid.Empty.Equals(id)) { JArray itemsArr = Items.GetItems(token[Jsonifier.Items]); if (itemsArr != null && itemsArr.Count > 0) { List <Tuple <CompoundIdentity, string, string> > items = new List <Tuple <CompoundIdentity, string, string> >(); foreach (JToken cur in itemsArr) { Tuple <CompoundIdentity, string, string> tpl = Items.GetItem(cur); if (tpl != null) { items.Add(tpl); } } if (items.Count == itemsArr.Count) { token = null; itemsArr = null; EntityBundleProvider prov = EntityBundleManager.Instance.GetProvider(ctx); EntityBundle bundle = prov.Get(id); if (bundle != null) { if (!string.IsNullOrEmpty(name) && !bundle.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) { bundle.Name = name; } //now we can actually try to add the items as needed foreach (Tuple <CompoundIdentity, string, string> tpl in items) { if (!bundle.Contains(tpl.Item2)) { if (bundle.Add(tpl.Item1, tpl.Item2, tpl.Item3) == null) { RestUtils.Push(context.Response, JsonOpStatus.Failed, "\"Failed to update bundle\""); return; } } } if (prov.Update(bundle)) { RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Ok)); return; } else { RestUtils.Push(context.Response, JsonOpStatus.Failed, "\"Failed to update bundle\""); return; } } } } } } } } } catch { context.Response.StatusCode = HttpStatusCodes.Status400BadRequest; return; } } } else { context.Response.StatusCode = HttpStatusCodes.Status401Unauthorized; return; } } context.Response.StatusCode = HttpStatusCodes.Status400BadRequest; }
private UpdateStatus InitialLoad(CompoundIdentity seId, EntityBundle sites, EntityBundle nets, EntityBundle fishSpecies, EntityBundle macroSpecies, FishDET curdet, ICatchEffortProvider depl, ICatchHaulProvider haul, IFishProvider fish, bool isPrivate) { UpdateStatus stat = null; if (sites == null || nets == null || fishSpecies == null || seId == null || seId.IsEmpty || macroSpecies == null) { stat = new UpdateStatus(UpdateIssue.DataIssue); stat.Add(new IssueNotice("BundlesOrEvent", "Null value")); } else { //TODO -- may need to do case insensitive ops or not -- verify how excel part is implemented Dictionary <string, CompoundIdentity> deployIds = new Dictionary <string, CompoundIdentity>(); BundleElement elem; foreach (CatchEffortDTO cur in curdet.CatchEfforts.Values) { if (cur != null && !deployIds.ContainsKey(cur.CatchId)) { elem = sites.Get(cur.SiteId); if (elem != null) { CompoundIdentity siteId = elem.EntityId; Point2 <double> tmpPoint = null; if (cur.CatchX.HasValue && cur.CatchY.HasValue) { if (!(cur.CatchX.Value.IsInfiniteOrNaN() && cur.CatchY.Value.IsInfiniteOrNaN())) { tmpPoint = GeometryFactory2Double.Instance.ConstructPoint(cur.CatchX.Value, cur.CatchY.Value); } } double dep = cur.Depth.HasValue ? cur.Depth.Value : double.NaN; double dox = cur.DO.HasValue ? cur.DO.Value : double.NaN; double pH = cur.pH.HasValue ? cur.pH.Value : double.NaN; double sal = cur.Salinity.HasValue ? cur.Salinity.Value : double.NaN; double tmp = cur.Temp.HasValue ? cur.Temp.Value : double.NaN; double vel = cur.Velocity.HasValue ? cur.Velocity.Value : double.NaN; CatchEffort cat = depl.Create(seId, siteId, cur.DateTime, cur.Comments, isPrivate, cur.CatchMethod, cur.HabitatStrata, tmpPoint, (float)dep, (float)pH, (float)tmp, (float)dox, (float)sal, (float)vel); if (cat != null) { deployIds[cur.CatchId] = cat.Identity; } else { stat = Add("Create", "Deployment", UpdateIssue.DataIssue, stat); } } else { stat = Add("SiteCode", "Empty or missing", UpdateIssue.DataIssue, stat); } } else { stat = Add("CatchId", "Empty or missing", UpdateIssue.DataIssue, stat); } } foreach (CatchMetricDTO cur in curdet.CatchMetrics.Values) { if (cur != null && deployIds.ContainsKey(cur.CatchId)) { CompoundIdentity depId = deployIds[cur.CatchId]; if (depId != null) { try { CatchMetric met = haul.CreateMetric(depId, (float)cur.Value, cur.MetricType, cur.Comments); if (met == null) { stat = Add("Create", "CatchMetric", UpdateIssue.DataIssue, stat); } } catch { stat = Add("Create", "CatchMetric", UpdateIssue.DataIssue, stat); } } else { stat = Add("CatchId", "Fail to lookup in CatchMetric", UpdateIssue.DataIssue, stat); } } else { stat = Add("CatchId", "Fail to lookup in CatchMetric", UpdateIssue.DataIssue, stat); } } foreach (NetHaulEventDTO cur in curdet.NetHaulEvents.Values) { if (cur != null && deployIds.ContainsKey(cur.CatchId)) { CompoundIdentity depId = deployIds[cur.CatchId]; if (depId != null) { elem = nets.Get(cur.NetId); if (elem != null) { CompoundIdentity netId = elem.EntityId; try { double area = cur.AreaSampled.HasValue ? cur.AreaSampled.Value : double.NaN; double vol = cur.VolumeSampled.HasValue ? cur.VolumeSampled.Value : double.NaN; NetHaulEvent met = haul.CreateHaul(depId, netId, (float)area, (float)vol, cur.Comments); if (met == null) { stat = Add("Create", "NetHaulEvent", UpdateIssue.DataIssue, stat); } } catch { stat = Add("Create", "NetHaulEvent", UpdateIssue.DataIssue, stat); } } else { stat = Add("NetId", "Fail to lookup in NetHaulEvent", UpdateIssue.DataIssue, stat); } } else { stat = Add("CatchId", "Fail to lookup in NetHaulEvent", UpdateIssue.DataIssue, stat); } } else { stat = Add("CatchId", "Fail to lookup in NetHaulEvent", UpdateIssue.DataIssue, stat); } } foreach (FishCountDTO cur in curdet.FishCounts.Values) { if (cur != null && deployIds.ContainsKey(cur.CatchId)) { CompoundIdentity depId = deployIds[cur.CatchId]; if (depId != null) { elem = fishSpecies.Get(cur.SpeciesId); if (elem != null) { CompoundIdentity fishId = elem.EntityId; try { FishCount met = haul.CreateFishCount(depId, fishId, cur.Count.HasValue?cur.Count.Value:0, cur.Comments); if (met == null) { stat = Add("Create", "FishCount", UpdateIssue.DataIssue, stat); } } catch { stat = Add("Create", "FishCount", UpdateIssue.DataIssue, stat); } } else { stat = Add("TaxaId", "Fail to lookup in FishCount", UpdateIssue.DataIssue, stat); } } else { stat = Add("CatchId", "Fail to lookup in FishCount", UpdateIssue.DataIssue, stat); } } else { stat = Add("CatchId", "Fail to lookup in FishCount", UpdateIssue.DataIssue, stat); } } //keep track of all fishids as we go for lookups Dictionary <string, Guid> fishIds = new Dictionary <string, Guid>(); foreach (FishDTO cur in curdet.Fish.Values) { if (cur != null && deployIds.ContainsKey(cur.CatchId)) { CompoundIdentity depId = deployIds[cur.CatchId]; if (depId != null) { elem = fishSpecies.Get(cur.SpeciesId); if (elem != null) { CompoundIdentity fishId = elem.EntityId; try { double std = cur.LengthStandard.HasValue ? cur.LengthStandard.Value : double.NaN; double frk = cur.LengthFork.HasValue ? cur.LengthFork.Value : double.NaN; double tot = cur.LengthTotal.HasValue ? cur.LengthTotal.Value : double.NaN; double wei = cur.Mass.HasValue ? cur.Mass.Value : double.NaN; Osrs.Oncor.WellKnown.Fish.Fish met = fish.CreateFish(depId, fishId, (float)std, (float)frk, (float)tot, (float)wei, cur.AdClipped, cur.CodedWireTag, cur.Comments); fishIds[cur.FishId] = met.Identity; if (met == null) { stat = Add("Create", "Fish", UpdateIssue.DataIssue, stat); } } catch { stat = Add("Create", "Fish", UpdateIssue.DataIssue, stat); } } else { stat = Add("TaxaId", "Fail to lookup in Fish", UpdateIssue.DataIssue, stat); } } else { stat = Add("CatchId", "Fail to lookup in Fish", UpdateIssue.DataIssue, stat); } } else { stat = Add("CatchId", "Fail to lookup in Fish", UpdateIssue.DataIssue, stat); } } foreach (DietDTO cur in curdet.Diet.Values) { if (cur != null && fishIds.ContainsKey(cur.FishId)) { Guid depId = fishIds[cur.FishId]; if (!Guid.Empty.Equals(depId)) { elem = macroSpecies.Get(cur.SpeciesId); if (elem != null || string.IsNullOrEmpty(cur.SpeciesId)) //allow for empty gut { CompoundIdentity taxaId; if (elem != null) { taxaId = elem.EntityId; } else { taxaId = new CompoundIdentity(Guid.Empty, Guid.Empty); } try { double sam = cur.SampleMass.HasValue ? cur.SampleMass.Value : double.NaN; double ind = cur.IndividualMass.HasValue ? cur.IndividualMass.Value : double.NaN; uint? wh = null; if (cur.WholeAnimalsWeighed.HasValue) { wh = (uint)cur.WholeAnimalsWeighed.Value; } FishDiet met = null; if (taxaId.IsEmpty) { if (cur.Count == 0) //the only way its legal { met = fish.CreateFishDiet(depId, taxaId, cur.GutSampleId, cur.VialId, cur.LifeStage, cur.Count, (float)sam, (float)ind, wh, cur.Comments); } } else { met = fish.CreateFishDiet(depId, taxaId, cur.GutSampleId, cur.VialId, cur.LifeStage, cur.Count, (float)sam, (float)ind, wh, cur.Comments); } if (met == null) { stat = Add("Create", "FishDiet", UpdateIssue.DataIssue, stat); } } catch { stat = Add("Create", "FishDiet", UpdateIssue.DataIssue, stat); } } else { stat = Add("TaxaId", "Fail to lookup in FishDiet", UpdateIssue.DataIssue, stat); } } else { stat = Add("FishId", "Fail to lookup in FishDiet", UpdateIssue.DataIssue, stat); } } else { stat = Add("FishId", "Fail to lookup in FishDiet", UpdateIssue.DataIssue, stat); } } foreach (GeneticDTO cur in curdet.Genetics.Values) { if (cur != null && fishIds.ContainsKey(cur.FishId)) { Guid depId = fishIds[cur.FishId]; if (!Guid.Empty.Equals(depId)) { try { StockEstimates est = new StockEstimates(); if (!string.IsNullOrEmpty(cur.BestStockEstimate) && cur.ProbabilityBest.HasValue) { est[cur.BestStockEstimate] = (float)cur.ProbabilityBest.Value; } if (!string.IsNullOrEmpty(cur.SecondStockEstimate) && cur.ProbabilitySecondBest.HasValue) { est[cur.SecondStockEstimate] = (float)cur.ProbabilitySecondBest.Value; } if (!string.IsNullOrEmpty(cur.ThirdStockEstimate) && cur.ProbabilityThirdBest.HasValue) { est[cur.ThirdStockEstimate] = (float)cur.ProbabilityThirdBest.Value; } FishGenetics met = fish.CreateFishGenetics(depId, cur.GeneticSampleId, cur.LabSampleId, est, cur.Comments); if (met == null) { stat = Add("Create", "FishIdTag", UpdateIssue.DataIssue, stat); } } catch { stat = Add("Create", "FishIdTag", UpdateIssue.DataIssue, stat); } } else { stat = Add("FishId", "Fail to lookup in FishIdTag", UpdateIssue.DataIssue, stat); } } else { stat = Add("FishId", "Fail to lookup in FishIdTag", UpdateIssue.DataIssue, stat); } } foreach (IdTagDTO cur in curdet.IdTags.Values) { if (cur != null && fishIds.ContainsKey(cur.FishId)) { Guid depId = fishIds[cur.FishId]; if (!Guid.Empty.Equals(depId)) { try { FishIdTag met = fish.CreateIdTag(depId, cur.TagCode, cur.TagType, cur.TagManufacturer, cur.Comments); if (met == null) { stat = Add("Create", "FishIdTag", UpdateIssue.DataIssue, stat); } } catch { stat = Add("Create", "FishIdTag", UpdateIssue.DataIssue, stat); } } else { stat = Add("FishId", "Fail to lookup in FishIdTag", UpdateIssue.DataIssue, stat); } } else { stat = Add("FishId", "Fail to lookup in FishIdTag", UpdateIssue.DataIssue, stat); } } if (stat == null) { stat = new UpdateStatus(UpdateIssue.AllOk); stat.Add(new IssueNotice("NoIssues", "No issues")); } } return(stat); }
/// <summary> /// Loads the templates in from the given directory /// </summary> /// <param name="path"></param> public void LoadDirectory(string path) { FileStream fs = null; try { if (!Directory.Exists(path)) { return; } path = Path.GetFullPath(path); if (!path.EndsWith("\\")) { path += "\\"; } currentDirectory = path; templates.Items.Clear(); string[] files = Directory.GetFiles(path, "*.template"); ListViewItem item; for (int k = 0; k < files.Length; k++) { try { BinaryFormatter formatter = new BinaryFormatter(); try { fs = File.OpenRead(files[k]); } catch (System.IO.DirectoryNotFoundException exc) { System.Windows.Forms.MessageBox.Show(exc.Message); } catch (System.IO.FileLoadException exc) { System.Windows.Forms.MessageBox.Show(exc.Message); } catch (System.IO.FileNotFoundException exc) { System.Windows.Forms.MessageBox.Show(exc.Message); } catch { mediator.Output("Non-CLS exception caught.", OutputInfoLevels.Exception); } //donnot open anything if filestream is not there if (fs == null) { return; } BinaryFormatter f = new BinaryFormatter(); EntityBundle bundle = (EntityBundle)f.Deserialize(fs); if (bundle == null) { continue; } item = new ListViewItem(new string[] { bundle.Name, bundle.Description, "" }); item.Tag = bundle; templates.Items.Add(item); mediator.Output("Found template '" + path + "\\" + files[k] + "' in directory.", GraphLib.OutputInfoLevels.Info); } catch (Exception exc) { mediator.Output("File '" + path + "\\" + files[k] + "' seems not to be a valid template file.", GraphLib.OutputInfoLevels.Info); Trace.WriteLine(exc.Message, "FavTab.LoadDirectory(string)"); continue; } finally { fs.Close(); } } } catch (System.IO.DirectoryNotFoundException e1) { mediator.Output("The directory was not found", GraphLib.OutputInfoLevels.Exception); Trace.WriteLine(e1.Message, "FavTab.LoadDirectory"); } catch (System.IO.FileNotFoundException e2) { mediator.Output("The file was not found", GraphLib.OutputInfoLevels.Exception); Trace.WriteLine(e2.Message, "FavTab.LoadDirectory"); } catch (Exception e) { mediator.Output(e.Message, GraphLib.OutputInfoLevels.Exception); Trace.WriteLine(e.Message, "FavTab.LoadDirectory"); } }
private UpdateStatus InitialLoad(CompoundIdentity seId, EntityBundle sites, EntityBundle instruments, WaterQualityDET curdet, IWQDeploymentProvider depl, IWQMeasurementProvider meas, bool isPrivate) { UpdateStatus stat = null; if (sites == null || instruments == null || seId == null || seId.IsEmpty) { stat = new UpdateStatus(UpdateIssue.DataIssue); stat.Add(new IssueNotice("BundlesOrEvent", "Null value")); } else { //TODO -- may need to do case insensitive ops or not -- verify how excel part is implemented Dictionary <string, CompoundIdentity> deployIds = new Dictionary <string, CompoundIdentity>(); BundleElement elem; foreach (DeploymentDTO cur in curdet.Deployments.Values) { if (cur != null && !deployIds.ContainsKey(cur.DeployCode)) { elem = sites.Get(cur.SiteId); if (elem != null) { CompoundIdentity siteId = elem.EntityId; elem = instruments.Get(cur.InstrumentId); if (elem != null) { CompoundIdentity sensorId = elem.EntityId; WaterQualityDeployment dep = depl.Create(cur.DeployCode, seId, siteId, sensorId, this.GetRange(cur.StartDate, cur.EndDate), cur.Comments, isPrivate); if (dep != null) { deployIds[dep.Name] = dep.Identity; } else { stat = Add("Create", "Unable to create deployment " + cur.DeployCode, UpdateIssue.DataIssue, stat); } } else { stat = Add("InstCode", "Empty or invalid Instrument Code on deployment " + cur.DeployCode, UpdateIssue.DataIssue, stat); } } else { stat = Add("SiteCode", "Empty or invalid Site Code on Deployment " + cur.DeployCode, UpdateIssue.DataIssue, stat); } } else { stat = Add("DeployCode", "A deployment is missing a deployment code", UpdateIssue.DataIssue, stat); } } Dictionary <CompoundIdentity, WaterQualityMeasurementsDTO> items = new Dictionary <CompoundIdentity, WaterQualityMeasurementsDTO>(); foreach (MeasurementDTO cur in curdet.Measurements.Values) { if (cur != null && deployIds.ContainsKey(cur.DeployCode) && cur.MeasureDateTime != null) { CompoundIdentity depId = deployIds[cur.DeployCode]; if (depId != null) { if (!items.ContainsKey(depId)) { items[depId] = WaterQualityMeasurementsDTO.Create(depId); } WaterQualityMeasurementsDTO elems = items[depId]; elems.Add(new WaterQualityMeasurementDTO(cur.MeasureDateTime.Value, cur.SurfaceElevation, cur.Temperature, cur.pH, cur.DO, cur.Conductivity, cur.Salinity, cur.Velocity)); } } else { stat = Add("Create", "Unable to create Measurement with key " + cur.DeployCode + ":" + cur.MeasureDateTime, UpdateIssue.DataIssue, stat); } } foreach (WaterQualityMeasurementsDTO cur in items.Values) { if (cur != null) { meas.Create(cur); } } if (stat == null) { stat = new UpdateStatus(UpdateIssue.AllOk); stat.Add(new IssueNotice("NoIssues", "No issues")); } } return(stat); }
private UpdateStatus InitialLoad(CompoundIdentity seId, EntityBundle sites, EntityBundle plotTypes, EntityBundle shrubSpecies, EntityBundle treeSpecies, EntityBundle herbSpecies, EntityBundle nonLiving, VegDET curdet, IVegSurveyProvider depl, IVegSampleProvider meas, bool isPrivate) { UpdateStatus stat = null; if (sites == null || plotTypes == null || seId == null || seId.IsEmpty) { stat = new UpdateStatus(UpdateIssue.DataIssue); stat.Add(new IssueNotice("BundlesOrEvent", "Null value")); } else { //TODO -- may need to do case insensitive ops or not -- verify how excel part is implemented Dictionary <string, CompoundIdentity> deployIds = new Dictionary <string, CompoundIdentity>(); BundleElement elem; foreach (VegSurveyDTO cur in curdet.Surveys.Values) { if (cur != null && !deployIds.ContainsKey(cur.SurveyId)) { elem = sites.Get(cur.SiteId); if (elem != null) { CompoundIdentity siteId = elem.EntityId; if (cur.PlotTypeId != null) { elem = plotTypes.Get(cur.PlotTypeId); } else { elem = null; } if (elem != null || cur.PlotTypeId == null) { CompoundIdentity plotTypeId; if (elem != null) { plotTypeId = elem.EntityId; } else { plotTypeId = null; } Point2 <double> tmpPoint = null; if (cur.AdHocLat.HasValue && cur.AdHocLon.HasValue) { if (!(cur.AdHocLat.Value.IsInfiniteOrNaN() && cur.AdHocLon.Value.IsInfiniteOrNaN())) { tmpPoint = GeometryFactory2Double.Instance.ConstructPoint(cur.AdHocLat.Value, cur.AdHocLon.Value); } } float area = float.NaN; if (cur.Area.HasValue) { area = (float)cur.Area.Value; } float minElev = float.NaN; float maxElev = float.NaN; if (cur.MinElevation.HasValue) { minElev = (float)cur.MinElevation.Value; } else if (cur.MaxElevation.HasValue) { minElev = (float)cur.MaxElevation.Value; //lets min/max be the same when only one is provided } if (cur.MaxElevation.HasValue) { maxElev = (float)cur.MaxElevation.Value; } else { maxElev = minElev; //lets min/max be the same when only one is provided } VegSurvey dep = depl.Create(seId, siteId, plotTypeId, tmpPoint, area, minElev, maxElev, cur.Comments, isPrivate); if (dep != null) { deployIds[cur.SurveyId] = dep.Identity; } else { stat = Add("Create", "Deployment", UpdateIssue.DataIssue, stat); } } else { stat = Add("PlotType", "Empty or missing", UpdateIssue.DataIssue, stat); } } else { stat = Add("SiteCode", "Empty or missing", UpdateIssue.DataIssue, stat); } } else { stat = Add("DeployCode", "Empty or missing", UpdateIssue.DataIssue, stat); } } if (stat == null) { stat = new UpdateStatus(UpdateIssue.DataIssue); IEnumerable <VegSamplesDTO> samps = ToSamples(curdet, deployIds, sites, plotTypes, shrubSpecies, treeSpecies, herbSpecies, nonLiving); if (samps != null) { foreach (VegSamplesDTO cur in samps) { if (meas.Create(cur) == null) { stat.Add(new IssueNotice("InsertBatch", "Failed inserting a batch of measurements")); } } if (stat.Count < 1) { stat = null; } } else { stat.Add(new IssueNotice("CreateSamples", "Failed to generate sample batches from file")); } } if (stat == null) { stat = new UpdateStatus(UpdateIssue.AllOk); stat.Add(new IssueNotice("NoIssues", "No issues")); } } return(stat); }
public override UpdateStatus Update(FilestoreFile tempFileUpload, SampleEventMap map) { if (tempFileUpload != null) { FilestoreFile oldFile = this.Get(map); if (oldFile != null) { if (this.CanModify(map)) { FishDET curdet = new FishDET(); ExcelFishDET curexcel = new ExcelFishDET(curdet); curexcel.Load(tempFileUpload); ValidationIssues curIssues = curdet.ValidationIssues; if (curIssues.Count < 1) { FishDET olddet = new FishDET(); ExcelFishDET excel = new ExcelFishDET(olddet); excel.Load(oldFile); ValidationIssues issues = olddet.ValidationIssues; if (issues.Count < 1) //should be this is the old file { UpdateStatus status = null; if (olddet.CatchEfforts.Count < 1) //old file has no data - bare det { if (curdet.CatchEfforts.Count < 1) //nothing to do really, new file has no data either { olddet = null; excel = null; oldFile.Dispose(); curdet = null; curexcel = null; FileStoreManager.Instance.GetProvider().Delete(tempFileUpload); status = new UpdateStatus(UpdateIssue.AllOk); status.Add(new IssueNotice("NoDataInEither", "nothing to do")); return(status); } SampleEventMapItem item = map.Get(KnownDetType.Fish); if (item != null) { olddet = null; //release old reference excel = null; //release old reference //ok, no data in old file, but data in new file -- we have work to do -- handle first-time data insertion ICatchEffortProvider depl = FishManager.Instance.GetCatchEffortProvider(this.Context); ICatchHaulProvider meas = FishManager.Instance.GetCatchHaulProvider(this.Context); IFishProvider fi = FishManager.Instance.GetFishProvider(this.Context); if (depl != null && meas != null && fi != null) { if (depl.CanCreate()) { List <EntityBundle> bundles = this.GetBundles(map, KnownDetType.Fish); if (bundles != null && bundles.Count >= 3) { EntityBundle mac = null; if (bundles.Count > 3) { mac = bundles[3]; } status = this.InitialLoad(map.SampleEventId, bundles[0], bundles[1], bundles[2], mac, curdet, depl, meas, fi, item.IsPrivate); if (status != null && status.Issue == UpdateIssue.AllOk) //success, so we overwrite the file { curdet = null; curexcel = null; olddet = null; excel = null; IFileStoreProvider ip = FileStoreManager.Instance.GetProvider(); if (ip.Replace(tempFileUpload, oldFile)) //overwrite the existing file with the new one { tempFileUpload.Dispose(); oldFile.Dispose(); //ip.Delete(tempFileUpload); //may still be references so delete can fail return(status); //we're done here } else { status = new UpdateStatus(UpdateIssue.DataIssue); status.Add(new IssueNotice("File", "Failed to replace file")); } } } else { status = new UpdateStatus(UpdateIssue.DataIssue); status.Add(new IssueNotice("Bundles", "Failed to get bundles")); } } else { status = new UpdateStatus(UpdateIssue.Security); status.Add(new IssueNotice("Permissions", "create denied")); } } else { status = new UpdateStatus(UpdateIssue.SystemIssue); status.Add(new IssueNotice("Failure", "Failed to get provider")); } } else { status = new UpdateStatus(UpdateIssue.NoExistingFile); status.Add(new IssueNotice("NoMapEntry", "Failed to find map reference")); } return(status); } else //crap -- this is an update where existing file already had data { ICatchEffortProvider depl = FishManager.Instance.GetCatchEffortProvider(this.Context); ICatchHaulProvider meas = FishManager.Instance.GetCatchHaulProvider(this.Context); IFishProvider fi = FishManager.Instance.GetFishProvider(this.Context); if (depl != null && meas != null && fi != null) { if (depl.CanCreate()) { SampleEventMapItem item = map.Get(KnownDetType.Fish); List <EntityBundle> bundles = this.GetBundles(map, KnownDetType.Fish); if (item != null && bundles != null && bundles.Count >= 3) { EntityBundle mac = null; if (bundles.Count > 3) { mac = bundles[3]; } status = this.DeltaLoad(map.SampleEventId, bundles[0], bundles[1], bundles[2], mac, curdet, olddet, depl, meas, fi, map); if (status != null && status.Issue == UpdateIssue.AllOk) //success, so we overwrite the file { curdet = null; curexcel = null; olddet = null; excel = null; //NOTE -- making new file the permanent file and removing old file, then updating map for new file IFileStoreProvider ip = FileStoreManager.Instance.GetProvider(); if (ip.Replace(tempFileUpload, oldFile)) //overwrite the existing file with the new one { tempFileUpload.Dispose(); oldFile.Dispose(); //ip.Delete(tempFileUpload); //may still be references so delete can fail return(status); //we're done here } else { status = new UpdateStatus(UpdateIssue.DataIssue); status.Add(new IssueNotice("File", "Failed to replace file")); } } } else { status = new UpdateStatus(UpdateIssue.DataIssue); status.Add(new IssueNotice("Bundles", "Failed to get bundles")); } } else { status = new UpdateStatus(UpdateIssue.Security); status.Add(new IssueNotice("Permissions", "create denied")); } } else { status = new UpdateStatus(UpdateIssue.SystemIssue); status.Add(new IssueNotice("Failure", "Failed to get provider")); } return(status); } } else { UpdateStatus stat = new UpdateStatus(UpdateIssue.NoExistingFile); foreach (ValidationIssue cur in issues) { stat.Add(new IssueNotice(cur.IssueCode.ToString(), cur.IssueMessage)); } return(stat); } } else { UpdateStatus stat = new UpdateStatus(UpdateIssue.FileValidationIssues); foreach (ValidationIssue cur in curIssues) { stat.Add(new IssueNotice(cur.IssueCode.ToString(), cur.IssueMessage)); } return(stat); } } else { UpdateStatus status = new UpdateStatus(UpdateIssue.Security); status.Add(new IssueNotice("Permissions", "create denied")); return(status); } } return(new UpdateStatus(UpdateIssue.NoExistingFile)); } return(new UpdateStatus(UpdateIssue.NoFilePosted)); }
public FilestoreFile Create(SampleEventMap map, EntityBundle sites, EntityBundle plotTypes, EntityBundle shrubSpecies, EntityBundle treeSpecies, EntityBundle herbSpecies, EntityBundle nonLiving, bool isPrivate) { if (this.CanModify(map)) { Guid id = Guid.NewGuid(); VegDET det = new VegDET(); det.Id = id; det.Owner = "originator:" + sites.PrincipalOrgId.Identity.ToString() + ":" + plotTypes.PrincipalOrgId.Identity.ToString(); int ct = 0; foreach (BundleElement cur in sites.Elements) { SiteDTO tmp = new SiteDTO(); tmp.Key = cur.LocalKey; tmp.Name = cur.DisplayName; det.Sites.Add(tmp); ct++; } if (ct > 0) //has to be elements in the collection { ct = 0; foreach (BundleElement cur in plotTypes.Elements) { PlotTypeDTO tmp = new PlotTypeDTO(); tmp.Key = cur.LocalKey; tmp.Name = cur.DisplayName; det.PlotTypes.Add(tmp); ct++; } if (ct > 0) { ct = 0; foreach (BundleElement cur in shrubSpecies.Elements) { SpeciesDTO tmp = new SpeciesDTO(); tmp.Key = cur.LocalKey; tmp.Name = cur.DisplayName; det.ShrubSpecies.Add(tmp); ct++; } if (treeSpecies != null) { foreach (BundleElement cur in treeSpecies.Elements) { SpeciesDTO tmp = new SpeciesDTO(); tmp.Key = cur.LocalKey; tmp.Name = cur.DisplayName; det.TreeSpecies.Add(tmp); ct++; } } if (herbSpecies != null) { foreach (BundleElement cur in herbSpecies.Elements) { SpeciesDTO tmp = new SpeciesDTO(); tmp.Key = cur.LocalKey; tmp.Name = cur.DisplayName; det.HerbSpecies.Add(tmp); ct++; } } if (nonLiving != null) { foreach (BundleElement cur in nonLiving.Elements) { SpeciesDTO tmp = new SpeciesDTO(); tmp.Key = cur.LocalKey; tmp.Name = cur.DisplayName; det.NonLiving.Add(tmp); } } if (ct > 0) //have to have at least one of herb, tree, shrub to POSSIBLY be valid { det.Validate(); if (det.ValidationIssues.Count == 0) { IFileStoreProvider prov = this.FileStore; if (prov != null) { FilestoreFile fil = prov.Make(id); if (fil != null) { ExcelVegDET excel = new ExcelVegDET(det); excel.Save(fil); fil.Flush(); fil.Seek(0, System.IO.SeekOrigin.Begin); return(fil); } } } } } } } return(null); }
private IEnumerable <VegSamplesDTO> ToSamples(VegDET det, Dictionary <string, CompoundIdentity> deployIds, EntityBundle sites, EntityBundle plotTypes, EntityBundle shrubSpecies, EntityBundle treeSpecies, EntityBundle herbSpecies, EntityBundle nonLiving) { Dictionary <string, VegSamplesDTO> samples = new Dictionary <string, VegSamplesDTO>(); foreach (KeyValuePair <string, CompoundIdentity> cur in deployIds) { samples.Add(cur.Key, VegSamplesDTO.Create(cur.Value)); } Dictionary <Tuple <CompoundIdentity, Point2 <double> >, Dictionary <DateTime, VegSampleDTO> > elements = new Dictionary <Tuple <CompoundIdentity, Point2 <double> >, Dictionary <DateTime, VegSampleDTO> >(); foreach (VegElevationDTO cur in det.Elevations.Values) { if (cur.MeasureDateTime.HasValue) { Dictionary <DateTime, VegSampleDTO> element = null; Tuple <CompoundIdentity, Point2 <double> > loc = GetLocation(cur, sites); if (!elements.ContainsKey(loc)) { element = new Dictionary <DateTime, VegSampleDTO>(); elements[loc] = element; } else { element = elements[loc]; } float min = cur.MinElevation.HasValue ? (float)cur.MinElevation.Value : float.NaN; float max = cur.MaxElevation.HasValue ? (float)cur.MaxElevation.Value : float.NaN; element[cur.MeasureDateTime.Value] = new VegSampleDTO(loc.Item1, cur.MeasureDateTime.Value, loc.Item2, min, max); } } foreach (VegHerbDTO cur in det.Herbs.Values) { if (cur.MeasureDateTime.HasValue) { VegSampleDTO it = GetSample(cur, sites, elements); if (it != null) { float pct = cur.PctCover.HasValue ? (float)cur.PctCover.Value : float.NaN; it.Add(new VegHerbSampleDTO(GetTaxa(cur.HerbSpeciesId, herbSpecies, nonLiving), pct, cur.Comments)); if (!samples[cur.SurveyId].ContainsKey(it.When)) { samples[cur.SurveyId].Add(it); } } } } foreach (VegShrubDTO cur in det.Shrubs.Values) { if (cur.MeasureDateTime.HasValue) { VegSampleDTO it = GetSample(cur, sites, elements); if (it != null) { uint pct = cur.Count.HasValue ? cur.Count.Value : 0; it.Add(new VegShrubSampleDTO(GetTaxa(cur.ShrubSpeciesId, shrubSpecies, nonLiving), cur.SizeClass, pct, cur.Comments)); if (!samples[cur.SurveyId].ContainsKey(it.When)) { samples[cur.SurveyId].Add(it); } } } } foreach (VegTreeDTO cur in det.Trees.Values) { if (cur.MeasureDateTime.HasValue) { VegSampleDTO it = GetSample(cur, sites, elements); if (it != null) { float pct = cur.DBH.HasValue ? (float)cur.DBH.Value : float.NaN; it.Add(new VegTreeSampleDTO(GetTaxa(cur.TreeSpeciesId, treeSpecies, nonLiving), pct, cur.Comments)); if (!samples[cur.SurveyId].ContainsKey(it.When)) { samples[cur.SurveyId].Add(it); } } } } return(samples.Values); }
//to support mutliple det types in a single request (which all share the same sample event), we have a collection of items as follows: //{id:<fieldtripid>, name:<sampleeventname - to be>, desc:<sampleeventdesc - to be>, princorgid: <id>, start:<date>, end:<date>, dets:[<det element>,...]} //each det element is an object as follows: //{type:<dettype>, privacy:<bool>, <<entity bundle ids specific to det>>} (example is sites:{id:bundleid,include:[key list]}) optional "exclude" instead of include would allow removing elements from bundle in det //returns fileid of the file to download // note that the name is required, desc is optional - name //for all types, the entity bundle format is: {id:<entitybundleid>, keys:[<id>, <id>, ...]} // note that keys are optional - if not provided it means "all items in bundle" // note that the bundle should be of the type expected for the parameter - e.g. if the provided bundle is for "sites", that bundle should be of sites internal static void Create(UserSecurityContext user, JToken dat, HttpContext context, CancellationToken cancel) { if (dat != null) { JObject payload = dat as JObject; if (payload != null) { //these are requried for any and all DETs to create CompoundIdentity ftId = JsonUtils.ToId(payload[JsonUtils.Id]); CompoundIdentity prOrgId = JsonUtils.ToId(payload[JsonUtils.OwnerId]); if (HasAffiliation(user, prOrgId)) { string name = JsonUtils.ToString(payload[JsonUtils.Name]); string desc = JsonUtils.ToString(payload[JsonUtils.Description]); ValueRange <DateTime> range = JsonUtils.ToRange(payload, JsonUtils.Start, JsonUtils.Finish); if (ftId != null && prOrgId != null && !string.IsNullOrEmpty(name)) { JToken dets = payload["dets"]; if (dets != null && dets is JArray) { JArray detItems = dets as JArray; if (detItems != null) { List <DetPayload> items = JsonDetExtractor.ExtractAll(detItems); if (items != null && items.Count > 0) //we actually have things to create { GeneralDetProcessor prov = DetProcessorManager.Instance.GetProvider(user); if (prov != null) { CompoundIdentity seId = prov.CreateSampleEvent(ftId, prOrgId, name, desc, range); EntityBundleProvider eProv = EntityBundleManager.Instance.GetProvider(user); if (eProv != null) { if (seId != null) { Dictionary <string, Guid> fileIds = new Dictionary <string, Guid>(); foreach (DetPayload cur in items) { if (cur.DetTypeName == KnownDets.Instance.WQ) { EntityBundle siteBundle = eProv.Get(cur.EntityBundles[JsonDetExtractor.Sites]); EntityBundle instBundle = eProv.Get(cur.EntityBundles[JsonDetExtractor.Instruments]); if (siteBundle != null && instBundle != null) { FilestoreFile fil = prov.CreateWQ(seId, siteBundle, instBundle, cur.IsPrivate); if (fil != null) { fileIds.Add(cur.DetTypeName, fil.FileId); fil.Dispose(); fil = null; } } } else if (cur.DetTypeName == KnownDets.Instance.Fish) { EntityBundle siteBundle = eProv.Get(cur.EntityBundles[JsonDetExtractor.Sites]); EntityBundle instBundle = eProv.Get(cur.EntityBundles[JsonDetExtractor.Nets]); EntityBundle fishBundle = eProv.Get(cur.EntityBundles[JsonDetExtractor.Fish]); EntityBundle macroBundle = eProv.Get(cur.EntityBundles[JsonDetExtractor.Macro]); if (siteBundle != null && instBundle != null && fishBundle != null && macroBundle != null) { FilestoreFile fil = prov.CreateFish(seId, siteBundle, instBundle, fishBundle, macroBundle, cur.IsPrivate); if (fil != null) { fileIds.Add(cur.DetTypeName, fil.FileId); fil.Dispose(); fil = null; } } } else if (cur.DetTypeName == KnownDets.Instance.Veg) { EntityBundle siteBundle = eProv.Get(cur.EntityBundles[JsonDetExtractor.Sites]); EntityBundle treeBundle = eProv.Get(cur.EntityBundles[JsonDetExtractor.Tree]); EntityBundle shrubBundle = eProv.Get(cur.EntityBundles[JsonDetExtractor.Shrub]); EntityBundle herbBundle = eProv.Get(cur.EntityBundles[JsonDetExtractor.Herb]); EntityBundle plotBundle = eProv.Get(cur.EntityBundles[JsonDetExtractor.Plots]); EntityBundle nlBundle = null; if (JsonDetExtractor.NonLiving != null) { nlBundle = eProv.Get(cur.EntityBundles[JsonDetExtractor.NonLiving]); } if (siteBundle != null && treeBundle != null && shrubBundle != null && herbBundle != null && plotBundle != null) { FilestoreFile fil = prov.CreateVeg(seId, siteBundle, plotBundle, shrubBundle, treeBundle, herbBundle, nlBundle, cur.IsPrivate); if (fil != null) { fileIds.Add(cur.DetTypeName, fil.FileId); fil.Dispose(); fil = null; } } } } //NOTE - we may want to deal with partial successes in case we have multiple DETs and some work, some don't //ok, now we do the response with a list of fileIds if (fileIds.Count > 0) { RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Ok, JsonUtils.ToJson(fileIds).ToString())); return; } else { RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed, new JValue("\"No items succeeded\"").ToString())); return; } } } } } } } } } else { context.Response.StatusCode = HttpStatusCodes.Status401Unauthorized; //in this case, by way of affiliation return; } } } context.Response.StatusCode = HttpStatusCodes.Status400BadRequest; }