public UserInfo Get(string userID, bool checkOnlineStatus, out bool onlineStatusChanged) { onlineStatusChanged = false; QueryFilter filter = new QueryFilter(); filter.andFilters["UserID"] = userID; List<string> query = GD.Query(new string[1] {"*"}, m_realm, filter, null, null, null); if (query.Count == 0) { return null; } UserInfo user = ParseQuery(query)[0]; //Check LastSeen DateTime timeLastSeen = Util.ToDateTime(int.Parse(query[2])); DateTime timeNow = DateTime.Now.ToUniversalTime(); if (checkOnlineStatus && m_checkLastSeen && user.IsOnline && (timeLastSeen.AddHours(1) < timeNow)) { MainConsole.Instance.Warn("[UserInfoService]: Found a user (" + user.UserID + ") that was not seen within the last hour " + "(since " + timeLastSeen.ToLocalTime().ToString() + ", time elapsed " + (timeNow - timeLastSeen).Days + " days, " + (timeNow - timeLastSeen).Hours + " hours)! Logging them out."); user.IsOnline = false; Set(user); onlineStatusChanged = true; } return user; }
public int AddAreaFieldToFeatureClass(String feature_class, String field_name) { try { IGPUtilities ipUtils = new GPUtilities(); IFeatureClass ipFeatureClass; // Open FC try { ipFeatureClass = ipUtils.OpenFeatureClassFromString(feature_class); } catch(Exception) { return -1; } // Find field int fieldIndex; try { fieldIndex = ipFeatureClass.FindField(field_name); } catch(Exception) { return -2; } // Set up query and filter IQueryFilter ipFilter = new QueryFilter(); IFeatureCursor ipCursor; IFeature ipRow; IGeometry ipShape; // Open cursor on feature class ipCursor = ipFeatureClass.Update(ipFilter, false); for (ipRow = ipCursor.NextFeature(); ipRow != null; ipRow = ipCursor.NextFeature()) { ipShape = ipRow.ShapeCopy; if (ipShape.GeometryType != esriGeometryType.esriGeometryPolygon) return -3; IArea ipArea = ipShape as IArea; double area = ipArea.Area; ipRow.Value[fieldIndex] = area; ipRow.Store(); } return 0; } catch (Exception) { return -4; } }
public bool Delete(UUID id, bool ignoreFlags) { try { if (!ignoreFlags) { AssetBase asset = GetAsset(id, false); if (asset == null) return false; if ((int) (asset.Flags & AssetFlags.Maptile) != 0 || //Depriated, use Deletable instead (int) (asset.Flags & AssetFlags.Deletable) != 0) ignoreFlags = true; } if (ignoreFlags) { QueryFilter filter = new QueryFilter(); filter.andFilters["id"] = id; m_Gd.Delete("assets", filter); } } catch (Exception e) { if (MainConsole.Instance != null) MainConsole.Instance.Error("[LocalAssetDatabase] Error while deleting asset " + e); } return true; }
public FriendInfo[] GetFriends(UUID principalID) { List<FriendInfo> infos = new List<FriendInfo>(); QueryTables tables = new QueryTables(); tables.AddTable(m_realm, "my"); tables.AddTable(m_realm, "his", JoinType.Inner, new[,] {{"my.Friend", "his.PrincipalID"}, {"my.PrincipalID", "his.Friend"}}); QueryFilter filter = new QueryFilter(); filter.andFilters["my.PrincipalID"] = principalID; List<string> query = GD.Query(new string[] { "my.Friend", "my.Flags", "his.Flags" }, tables, filter, null, null, null); //These are used to get the other flags below for (int i = 0; i < query.Count; i += 3) { FriendInfo info = new FriendInfo { PrincipalID = principalID, Friend = query[i], MyFlags = int.Parse(query[i + 1]), TheirFlags = int.Parse(query[i + 2]) }; infos.Add(info); } return infos.ToArray(); }
public bool FolderExists(UUID folderID) { QueryFilter filter = new QueryFilter(); filter.andFilters["folderID"] = folderID; return GD.Query(new string[] {"folderID"}, m_foldersrealm, filter, null, null, null).Count > 0; }
public IEnumerable<Vector3> FindPath(Vector3 start, Vector3 end, QueryFilter filter, bool hardFail) { if (!LoadAppropriateTiles(start, end)) throw new Exception("Correct tiles were not loaded!"); //LoadAllTiles(); float[] extents = new[] { 0.5f, 0.5f, 0.5f }; PolygonReference startRef, endRef; float[] transformedStart = start.ToFloatArray(); float[] transformedEnd = end.ToFloatArray(); RecastManaged.Helper.Transform(ref transformedStart); RecastManaged.Helper.Transform(ref transformedEnd); while ((startRef = DetourMesh.FindNearestPolygon(transformedStart, extents, filter)).PolyIndex == 0) { if (extents[0] > 100.0f) throw new Exception("Extents got too huge"); extents[0] += 0.5f; extents[1] += 0.5f; extents[2] += 0.5f; } extents = new[] { 0.5f, 0.5f, 0.5f }; while ((endRef = DetourMesh.FindNearestPolygon(transformedEnd, extents, filter)).PolyIndex == 0) { if (extents[0] > 100.0f) throw new Exception("Extents got too huge"); extents[0] += 0.5f; extents[1] += 0.5f; extents[2] += 0.5f; } var path = DetourMesh.FindPath(startRef, endRef, transformedStart, transformedEnd, filter); if (path.Length <= 0) return null; // if the last poly in the path is not the end poly, a path was not found if (hardFail && path[path.Length - 1].PolyIndex != endRef.PolyIndex) return null; StraightPathFlags[] flags; PolygonReference[] straightPathRefs; var straightPath = DetourMesh.FindStraightPath(transformedStart, transformedEnd, path, out flags, out straightPathRefs); RecastManaged.Helper.InverseTransform(ref straightPath); List<Vector3> ret = new List<Vector3>(straightPath.Length / 3); for (int i = 0; i < straightPath.Length / 3; i++) ret.Add(new Vector3(straightPath[i * 3 + 0], straightPath[i * 3 + 1], straightPath[i * 3 + 2])); //for (int i = 0; i < straightPath.Length / 3; i++) // yield return new Vector3(straightPath[i * 3 + 0], straightPath[i * 3 + 1], straightPath[i * 3 + 2]); return ret; }
public bool Delete(UUID ownerID, string friend) { QueryFilter filter = new QueryFilter(); filter.andFilters["PrincipalID"] = ownerID; filter.andFilters["Friend"] = friend; return GD.Delete(m_realm, filter); }
public bool AddClassified(Classified classified) { object remoteValue = DoRemote(classified); if (remoteValue != null || m_doRemoteOnly) return remoteValue != null && (bool) remoteValue; if (GetUserProfile(classified.CreatorUUID) == null) return false; string keywords = classified.Description; if (keywords.Length > 512) keywords = keywords.Substring(keywords.Length - 512, 512); //It might be updating, delete the old QueryFilter filter = new QueryFilter(); filter.andFilters["ClassifiedUUID"] = classified.ClassifiedUUID; GD.Delete("userclassifieds", filter); List<object> values = new List<object> { classified.Name, classified.Category, classified.SimName, classified.CreatorUUID, classified.ScopeID, classified.ClassifiedUUID, OSDParser.SerializeJsonString(classified.ToOSD()), classified.PriceForListing, keywords }; return GD.Insert("userclassifieds", values.ToArray()); }
public ViewerStatsMessage GetBySession(UUID sessionID) { QueryFilter filter = new QueryFilter(); filter.andFilters.Add("session_id", sessionID); List<string> results = GD.Query(new string[1] {"*"}, m_realm, filter, null, null, null); return BuildSession(results, 0); }
/// <summary> /// Gets the number of Abuse reports. /// </summary> /// <returns>The report count.</returns> public int AbuseReportCount() { QueryFilter filter = new QueryFilter (); var reports = GD.Query (new string[1] { "count(*)" }, m_abuseReportsTable, filter, null, null, null); if ((reports == null) || (reports.Count == 0)) return 0; return int.Parse (reports [0]); }
public virtual bool DeleteFolders(string field, string val, bool safe) { QueryFilter filter = new QueryFilter(); filter.andFilters[field] = val; if (safe) filter.orMultiFilters["type"] = new List<object>() { "-1", "47" }; return GD.Delete(m_foldersrealm, filter); }
public Query(QueryScope scope, QueryFilter filter) { if (scope == null) this.scope = new QueryScope(ObjectTypes.AllExcFolders); else this.scope = scope; this.filter = filter; // null is OK }
public SchedulerItem Get(string id) { if (id != "") { QueryFilter filter = new QueryFilter(); filter.andFilters["id"] = id; List<string> results = m_Gd.Query(theFields, "scheduler", filter, null, null, null); return LoadFromList(results); } return null; }
public List<string> FindLSLData(string token, string key) { object remoteValue = DoRemote(token, key); if (remoteValue != null || m_doRemoteOnly) return (List<string>) remoteValue; QueryFilter filter = new QueryFilter(); filter.andFilters["Token"] = token; filter.andFilters["KeySetting"] = key; return GD.Query(new string[1] {"*"}, "lslgenericdata", filter, null, null, null); }
public IEnumerable<ImageInformation> ImagesSearch(QueryFilter pars, int maxImages) { Console.WriteLine("---- ImagesQuery execution ----"); if (maxImages >= 0) { Console.WriteLine("Maximum returned images: {0}", maxImages); } Console.WriteLine(pars); // ... Implementation details ... throw new NotImplementedException(); }
public bool DeleteAccount(UUID userID, bool archiveInformation) { if (archiveInformation) { return GD.Update(m_realm, new Dictionary<string, object> {{"UserLevel", -2}}, null, new QueryFilter {andFilters = new Dictionary<string, object> {{"PrincipalID", userID}}}, null, null); } QueryFilter filter = new QueryFilter(); filter.andFilters.Add("PrincipalID", userID); return GD.Delete(m_realm, filter); }
public Query(XmlNode node) { foreach (XmlNode child in node.ChildNodes) { if (child.NodeType != XmlNodeType.Element) continue; else if (child.Name == "QueryScope") this.scope = new QueryScope(child); else this.filter = (QueryFilter)SearchMarshalling.FromXmlNode(child); } }
public bool Store (UUID PrincipalID, string Friend, int Flags, int Offered) { QueryFilter filter = new QueryFilter (); filter.andFilters ["PrincipalID"] = PrincipalID; filter.andFilters ["Friend"] = Friend; GD.Delete (m_realm, filter); Dictionary<string, object> row = new Dictionary<string, object> (4); row ["PrincipalID"] = PrincipalID; row ["Friend"] = Friend; row ["Flags"] = Flags; row ["Offered"] = Offered; return GD.Insert (m_realm, row); }
public AvatarAppearance Get(UUID PrincipalID) { QueryFilter filter = new QueryFilter(); filter.andFilters["PrincipalID"] = PrincipalID; List<string> data; lock (m_lock) { data = GD.Query(new string[] {"Appearance"}, m_realm, filter, null, null, null); } if (data.Count == 0) return null; AvatarAppearance appearance = new AvatarAppearance(); appearance.FromOSD((OSDMap) OSDParser.DeserializeJson(data[0])); return appearance; }
private void ajusterNaipfddm(ITable pTable) { // Error Handling const string functionName = "addField"; IRow pRow; ICursor pCursor; IQueryFilter iQf = new QueryFilter(); try { iQf.SubFields = "NAIF1_DDM, ET1_ESS1, ET1_PC1, ET1_ESS2, ET1_PC2, ET1_ESS3, ET1_PC3, ET1_ESS4, ET1_PC4, ET1_ESS5, ET1_PC5, ET1_ESS6, ET1_PC6, ET1_ESS7, ET1_PC7"; iQf.WhereClause = "naif1_ddm = ''"; pCursor = pTable.Update(iQf, false); pRow = pCursor.NextRow(); string sFinal; int iPourc; while (pRow != null) { sFinal = ""; for (int i = 1; i < SF10_clsBase.i_NAIPFMaxControls; i++) { if (pRow.Value[pRow.Fields.FindField("et1_ess" + i)].ToString().Trim().Length != 0) { iPourc = 100; if (pRow.Value[pRow.Fields.FindField("et1_pc" + i)].ToString().Trim().Length != 0) { iPourc = valeurToPourc(pRow.Value[pRow.Fields.FindField("et1_pc" + i)].ToString().Trim()); } sFinal += pRow.Value[pRow.Fields.FindField("et1_ess" + i)] + iPourc.ToString(); } } pRow.Value[pRow.Fields.FindField("NAIF1_DDM")] = sFinal; pCursor.UpdateRow(pRow); pRow = pCursor.NextRow(); } } catch (Exception e) { MessageBox.Show(functionName + " :: " + e.Message, "SF10", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { } }
public bool ExistsAsset(UUID uuid) { try { QueryFilter filter = new QueryFilter(); filter.andFilters["id"] = uuid; return m_Gd.Query(new string[] {"id"}, "assets", filter, null, null, null).Count > 0; } catch (Exception e) { if (MainConsole.Instance != null) MainConsole.Instance.ErrorFormat( "[LocalAssetDatabase]: Failure fetching asset {0}" + Environment.NewLine + e, uuid); } return false; }
private static Dictionary<string, int> GetAllValues(string fieldName, IGeoFeatureLayer layer) { var results = new Dictionary<string, int>(); IQueryFilter query = new QueryFilter { SubFields = fieldName }; using (var comReleaser = new ComReleaser()) { IFeatureCursor cursor = layer.Search(query, true); comReleaser.ManageLifetime(cursor); IFeature feature; int fieldIndex = cursor.FindField(fieldName); while ((feature = cursor.NextFeature()) != null) { results[feature.Value[fieldIndex].ToString()] = 1; } } return results; }
public AuthData Get (UUID principalID, string authType) { QueryFilter filter = new QueryFilter (); filter.andFilters ["UUID"] = principalID; filter.andFilters ["accountType"] = authType; List<string> query = GD.Query (new string [] { "*" }, m_realm, filter, null, null, null); AuthData data = null; for (int i = 0; i < query.Count; i += 5) { data = new AuthData { PrincipalID = UUID.Parse (query [i]), PasswordHash = query [i + 1], PasswordSalt = query [i + 2], AccountType = query [i + 3] }; } return data; }
public bool CheckToken(UUID principalID, string token, int lifetime) { if (Environment.TickCount - m_LastExpire > 30000) { DoExpire(); } uint now = Utils.DateTimeToUnixTime(DateTime.Now); Dictionary<string, object> values = new Dictionary<string, object>(1); values["validity"] = now + (lifetime*60); QueryFilter filter = new QueryFilter(); filter.andFilters["UUID"] = principalID; filter.andFilters["token"] = token; filter.andLessThanEqFilters["validity"] = (int) now; return GD.Update(m_tokensrealm, values, null, filter, null, null); }
public WowMapPather(string continent) { fullFileName = continent; Continent = continent.Substring(continent.LastIndexOf('\\') + 1); if (Directory.Exists(continent)) _meshPath = continent; else { var assembly = Assembly.GetCallingAssembly().Location; var dir = Path.GetDirectoryName(assembly); if (Directory.Exists(dir + "\\Meshes")) _meshPath = dir + "\\Meshes\\" + continent; else _meshPath = dir + "\\" + continent; } if (!Directory.Exists(_meshPath)) throw new Exception("No mesh for " + continent + " (Path: " + _meshPath + ")"); _mesh = new NavMesh(); DetourStatus status; // check if this is a dungeon and initialize our mesh accordingly string dungeonPath = GetDungeonPath(); if (File.Exists(dungeonPath)) { var data = File.ReadAllBytes(dungeonPath); status = _mesh.Initialize(data); IsDungeon = true; } else status = _mesh.Initialize(32768, 4096, Utility.Origin, Utility.TileSize, Utility.TileSize); if (status.HasFailed()) throw new Exception("Failed to initialize the mesh"); // _query = new NavMeshQuery(new PatherCallback(this)); //TODO: Add Callback for Dynamic Tile Loading _query = new NavMeshQuery(); _query.Initialize(_mesh, 65536); Filter = new QueryFilter { IncludeFlags = 0xFFFF, ExcludeFlags = 0x0 }; }
public FloodFill(NavMesh mesh) { Mesh = mesh; _query = new NavMeshQuery(); if (!_query.Initialize(Mesh, 1024).HasSucceeded()) throw new Exception("Failed to initialize navigation mesh query"); _filter = new QueryFilter(); var param = Mesh.Parameter; // detour guarantees these are 2^x var tileBits = (int) Math.Log(param.MaxTiles, 2); var polyBits = (int) Math.Log(param.MaxPolygons, 2); // we also don't care about salt, so create a mask to cut these off just in case Visited = new bool[1 << (tileBits + polyBits)]; VisitedMask = (1 << (tileBits + polyBits)) - 1; _open = new Queue<uint>(100); }
/// <summary> /// Called when a sketch is completed. /// </summary> protected override async Task<bool> OnSketchCompleteAsync(Geometry geometry) { var popupContent = await QueuedTask.Run(async () => { var mapView = MapView.Active; if (mapView == null) return null; //Get the features that intersect the sketch geometry. var features = mapView.GetFeatures(geometry); if (features.Count == 0) return null; var firstLyr = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault(); //get the first layer in the map if (firstLyr == null) return null; var gdb = await GetGDBFromLyrAsync(firstLyr); LayersInMapFeatureClassMap = Module1.GetMapLayersFeatureClassMap(gdb); var oidList = features[firstLyr]; //gets the OIds of all the features selected. var oid = firstLyr.GetTable().GetDefinition().GetObjectIDField(); //gets the OId field var qf = new QueryFilter() //create the query filter { WhereClause = string.Format("({0} in ({1}))", oid, string.Join(",", oidList)) }; //Create the new selection Selection selection = firstLyr.Select(qf); var relateInfo = new RelateInfo(firstLyr, selection); return await relateInfo.GetPopupContent(features); //passes the selection to gather the relationShip class information. }); MapView.Active.ShowCustomPopup(popupContent); return true; }
public List<UserInfo> CurrentlyOnline(uint secondsAgo, Dictionary<string, bool> sort, uint start, uint count) { QueryFilter filter = new QueryFilter(); if (secondsAgo > 0) { //Beware!! login times are UTC! int now = (int)Util.ToUnixTime (DateTime.Now.ToUniversalTime ()); now -= (int) secondsAgo; filter.orGreaterThanEqFilters["LastLogin"] = now; filter.orGreaterThanEqFilters["LastSeen"] = now; } // online only please... filter.andFilters["IsOnline"] = "1"; List<string> query = GD.Query(new string[] { "*" }, m_userInfoTable, filter, sort, start, count); return ParseQuery(query); }
public void UpdateLSLData(string token, string key, string value) { if (m_doRemoteOnly) { DoRemote (token, key, value); return; } if (FindLSLData(token, key).Count == 0) { GD.Insert("lslgenericdata", new[] {token, key, value}); } else { Dictionary<string, object> values = new Dictionary<string, object>(1); values["ValueSetting"] = value; QueryFilter filter = new QueryFilter(); filter.andFilters["KeySetting"] = key; GD.Update("lslgenericdata", values, null, filter, null, null); } }
/// <summary> /// Calculates the data statistics for a geodatabase table. /// </summary> /// <param name="table">The geodatabase table which statistics should be gathered.</param> /// <param name="field">The field which statistics should be gathered.</param> /// <returns>The calculated data statistics.</returns> internal async Task<DataStatisticsResult> CalculateStatistics(FeatureTable table, FieldInfo field) { var result = new DataStatisticsResult { TableName = table.Name, AttributeName = field.Alias }; result.Count = table.RowCount; var filter = new QueryFilter { WhereClause = @"1=1" }; var features = await table.QueryAsync(filter); var uniqueValues = new HashSet<object>(); foreach (var feature in features) { var attributes = feature.Attributes; if (attributes.ContainsKey(field.Name)) { var value = attributes[field.Name]; if (!uniqueValues.Contains(value)) { uniqueValues.Add(value); } } } result.UniqueValueCount = uniqueValues.Count; return result; }
public IEnumerable <IWorkItem> GetItems(QueryFilter filter = null, bool recycle = true) { return(_items); }
public static async Task BatchQuery(int batchSize, QueryFilter filter, Action <IEnumerable <DirectMessage> > batchProcessor, Database database = null) { await BatchQuery(batchSize, (c) => filter, batchProcessor, database); }
public static DirectMessageCollection Query(QueryFilter filter, Database database = null) { return(Where(filter, database)); }
public static CategoryCollection Where(QueryFilter filter, Database database = null) { WhereDelegate <CategoryColumns> whereDelegate = (c) => filter; return(Where(whereDelegate, database)); }
internal void PopulateRootAndFilter(OrganizationId organizationId, IReadOnlyPropertyBag propertyBag) { if (this.Root != null || this.Filter != null) { return; } if (this.isFromEndUserRole && propertyBag == null) { throw new ArgumentNullException("propertyBag"); } if (organizationId != null) { this.SelfRoot = organizationId.OrganizationalUnit; } if (propertyBag != null) { this.SelfFilter = new ComparisonFilter(ComparisonOperator.Equal, ADObjectSchema.Id, propertyBag[ADObjectSchema.Id]); } switch (this.scopeType) { case ScopeType.None: this.Root = null; this.Filter = ADScope.NoObjectFilter; return; case ScopeType.NotApplicable: this.Root = null; this.Filter = null; return; case ScopeType.Organization: this.Root = organizationId.OrganizationalUnit; this.Filter = null; return; case ScopeType.MyGAL: { AddressBookBase globalAddressList = this.GetGlobalAddressList(organizationId); this.Root = organizationId.OrganizationalUnit; if (globalAddressList == null) { this.Filter = ADScope.NoObjectFilter; return; } this.Filter = new ComparisonFilter(ComparisonOperator.Equal, ADRecipientSchema.AddressListMembership, globalAddressList.Id); return; } case ScopeType.Self: this.Root = organizationId.OrganizationalUnit; this.Filter = new ComparisonFilter(ComparisonOperator.Equal, ADObjectSchema.Id, propertyBag[ADObjectSchema.Id]); return; case ScopeType.MyDirectReports: this.Root = organizationId.OrganizationalUnit; this.Filter = new ComparisonFilter(ComparisonOperator.Equal, ADOrgPersonSchema.Manager, propertyBag[ADObjectSchema.Id]); return; case ScopeType.OU: this.Root = this.ouId; this.Filter = null; return; case ScopeType.CustomRecipientScope: case ScopeType.CustomConfigScope: case ScopeType.PartnerDelegatedTenantScope: case ScopeType.ExclusiveRecipientScope: case ScopeType.ExclusiveConfigScope: this.Root = this.managementScope.RecipientRoot; this.Filter = this.managementScope.QueryFilter; return; case ScopeType.MyDistributionGroups: { this.Root = organizationId.OrganizationalUnit; QueryFilter[] array = new QueryFilter[3]; array[0] = new ComparisonFilter(ComparisonOperator.Equal, ADGroupSchema.ManagedBy, propertyBag[ADObjectSchema.Id]); array[1] = new ComparisonFilter(ComparisonOperator.Equal, ADGroupSchema.CoManagedBy, propertyBag[ADObjectSchema.Id]); array[2] = new CSharpFilter <IReadOnlyPropertyBag>(delegate(IReadOnlyPropertyBag obj) { ADGroup adgroup = obj as ADGroup; return(adgroup != null && adgroup.IsExecutingUserGroupOwner); }); this.Filter = new OrFilter(array); return; } case ScopeType.MyExecutive: break; case ScopeType.OrganizationConfig: this.Root = organizationId.ConfigurationUnit; this.Filter = null; return; case ScopeType.MailboxICanDelegate: { this.Root = organizationId.OrganizationalUnit; QueryFilter[] array2 = new QueryFilter[2]; array2[0] = new ComparisonFilter(ComparisonOperator.Equal, ADRecipientSchema.MasterAccountSid, this.securityAccessToken.UserSid); array2[1] = new CSharpFilter <IReadOnlyPropertyBag>(delegate(IReadOnlyPropertyBag obj) { RawSecurityDescriptor rawSecurityDescriptor = ((ADObject)obj).ReadSecurityDescriptor(); if (rawSecurityDescriptor != null) { using (AuthzContextHandle authzContext = AuthzAuthorization.GetAuthzContext(new SecurityIdentifier(this.securityAccessToken.UserSid), false)) { bool[] array3 = AuthzAuthorization.CheckExtendedRights(authzContext, rawSecurityDescriptor, new Guid[] { WellKnownGuid.PersonalInfoPropSetGuid }, null, AccessMask.WriteProp); return(array3[0]); } return(false); } return(false); }); this.Filter = new OrFilter(array2); return; } default: this.Root = null; this.Filter = ADScope.NoObjectFilter; break; } }
private void TestHashTable(Table hashTable, DynamoDBEntryConversion conversion) { // Put an item Document doc = new Document(); doc["Id"] = 1; doc["Product"] = "CloudSpotter"; doc["Company"] = "CloudsAreGrate"; doc["IsPublic"] = true; doc["Price"] = 1200; doc["Tags"] = new HashSet <string> { "Prod", "1.0" }; doc["Aliases"] = new List <string> { "CS", "Magic" }; doc["Developers"] = new List <Document> { new Document(new Dictionary <string, DynamoDBEntry> { { "Name", "Alan" }, { "Age", 29 } }), new Document(new Dictionary <string, DynamoDBEntry> { { "Name", "Franco" }, { "Age", 32 } }) }; doc["Garbage"] = "asdf"; Assert.AreEqual("asdf", doc["Garbage"].AsString()); hashTable.PutItem(doc); // Get the item by hash key Document retrieved = hashTable.GetItem(1); Assert.IsFalse(AreValuesEqual(doc, retrieved)); var convertedDoc = doc.ForceConversion(conversion); Assert.IsTrue(AreValuesEqual(convertedDoc, retrieved)); // Get the item by document retrieved = hashTable.GetItem(doc); // Verify retrieved document Assert.IsTrue(AreValuesEqual(convertedDoc, retrieved, conversion)); var tagsRetrieved = retrieved["Tags"]; Assert.IsTrue(tagsRetrieved is PrimitiveList); Assert.AreEqual(2, tagsRetrieved.AsPrimitiveList().Entries.Count); // Test bool storage for different conversions var isPublicRetrieved = retrieved["IsPublic"]; if (conversion == DynamoDBEntryConversion.V1) { Assert.AreEqual("1", isPublicRetrieved.AsPrimitive().Value as string); } else { Assert.IsTrue(isPublicRetrieved is DynamoDBBool); } // Test HashSet<string> storage for different conversions var aliasesRetrieved = retrieved["Aliases"]; if (conversion == DynamoDBEntryConversion.V1) { Assert.AreEqual(2, aliasesRetrieved.AsPrimitiveList().Entries.Count); } else { Assert.AreEqual(2, aliasesRetrieved.AsDynamoDBList().Entries.Count); } List <Document> developers = retrieved["Developers"].AsListOfDocument(); Assert.AreEqual(2, developers.Count); AssertExtensions.ExpectException(() => aliasesRetrieved.AsListOfDocument(), typeof(InvalidCastException)); // Update the item doc["Tags"] = new List <string> { "Prod", "1.0", "2.0" }; doc["Developers"] = new DynamoDBList(new List <DynamoDBEntry> { new Document(new Dictionary <string, DynamoDBEntry> { { "Name", "Alan" }, { "Age", 29 } }) }); // Delete the Garbage attribute doc["Garbage"] = null; Assert.IsNull(doc["Garbage"].AsString()); hashTable.UpdateItem(doc); retrieved = hashTable.GetItem(1); Assert.IsFalse(AreValuesEqual(doc, retrieved, conversion)); doc.Remove("Garbage"); Assert.IsTrue(AreValuesEqual(doc, retrieved, conversion)); developers = retrieved["Developers"].AsListOfDocument(); Assert.AreEqual(1, developers.Count); // Create new, circularly-referencing item Document doc2 = doc.ForceConversion(conversion); doc2["Id"] = doc2["Id"].AsInt() + 1; doc2["Price"] = 94; doc2["Tags"] = null; doc2["IsPublic"] = false; doc2["Parent"] = doc2; AssertExtensions.ExpectException(() => hashTable.UpdateItem(doc2)); // Remove circular reference and save new item doc2.Remove("Parent"); hashTable.UpdateItem(doc2); // Scan the hash-key table var items = hashTable.Scan(new ScanFilter()).GetRemaining(); Assert.AreEqual(2, items.Count); // Scan by pages var search = hashTable.Scan(new ScanOperationConfig { Limit = 1 }); items.Clear(); while (!search.IsDone) { var set = search.GetNextSet(); items.AddRange(set); } Assert.AreEqual(2, items.Count); // Query against GlobalIndex var queryFilter = new QueryFilter("Company", QueryOperator.Equal, "CloudsAreGrate"); queryFilter.AddCondition("Price", QueryOperator.GreaterThan, 100); search = hashTable.Query(new QueryOperationConfig { IndexName = "GlobalIndex", Filter = queryFilter }); items = search.GetRemaining(); Assert.AreEqual(1, items.Count); // Scan for specific tag var scanFilter = new ScanFilter(); scanFilter.AddCondition("Tags", ScanOperator.Contains, "2.0"); search = hashTable.Scan(scanFilter); items = search.GetRemaining(); Assert.AreEqual(1, items.Count); // Delete the item by hash key hashTable.DeleteItem(1); Assert.IsNull(hashTable.GetItem(1)); // Delete the item by document hashTable.DeleteItem(doc2); Assert.IsNull(hashTable.GetItem(doc2)); // Scan the hash-key table to confirm it is empty items = hashTable.Scan(new ScanFilter()).GetRemaining(); Assert.AreEqual(0, items.Count); // Batch-put items var batchWrite = hashTable.CreateBatchWrite(); batchWrite.AddDocumentToPut(doc); batchWrite.AddDocumentToPut(doc2); batchWrite.Execute(); // Batch-get items var batchGet = hashTable.CreateBatchGet(); batchGet.AddKey(1); batchGet.AddKey(doc2); batchGet.Execute(); Assert.AreEqual(2, batchGet.Results.Count); // Batch-delete items batchWrite = hashTable.CreateBatchWrite(); batchWrite.AddItemToDelete(doc); batchWrite.AddKeyToDelete(2); batchWrite.Execute(); // Batch-get non-existent items batchGet = hashTable.CreateBatchGet(); batchGet.AddKey(1); batchGet.AddKey(doc2); batchGet.Execute(); Assert.AreEqual(0, batchGet.Results.Count); // Scan the hash-key table to confirm it is empty items = hashTable.Scan(new ScanFilter()).GetRemaining(); Assert.AreEqual(0, items.Count); }
// Token: 0x06000954 RID: 2388 RVA: 0x0001FFC2 File Offset: 0x0001E1C2 internal void SetAdditionalQueryFilter(QueryFilter newFilter) { this.additionalQueryFilter = newFilter; }
public static DynamicTypePropertyDescriptorCollection Top(int count, QueryFilter where, Database database) { return(Top(count, where, null, database)); }
public static DataPropertyCollection Top(int count, QueryFilter where, Database database) { return(Top(count, where, null, database)); }
public static DynamicTypePropertyDescriptorCollection Where(QueryFilter filter, Database database = null) { WhereDelegate <DynamicTypePropertyDescriptorColumns> whereDelegate = (c) => filter; return(Where(whereDelegate, database)); }
public static DynamicTypePropertyDescriptorCollection Query(QueryFilter filter, Database database = null) { return(Where(filter, database)); }
public static async Task BatchQuery <ColType>(int batchSize, QueryFilter filter, Action <IEnumerable <DynamicTypePropertyDescriptor> > batchProcessor, Bam.Net.Data.OrderBy <DynamicTypePropertyDescriptorColumns> orderBy, Database database = null) { await BatchQuery <ColType>(batchSize, (c) => filter, batchProcessor, orderBy, database); }
public int GetCount(QueryFilter filter = null) { throw new NotImplementedException(); }
public static DirectMessageCollection Where(QueryFilter filter, Database database = null) { WhereDelegate <DirectMessageColumns> whereDelegate = (c) => filter; return(Where(whereDelegate, database)); }
/// <summary> /// Implement querying with a query filter /// </summary> /// <param name="qf"></param> /// <returns></returns> private List <long> ExecuteQuery(QueryFilter qf) { //are we empty? if (_table.Rows.Count == 0) { return(new List <long>()); } SpatialQueryFilter sqf = null; if (qf is SpatialQueryFilter) { sqf = qf as SpatialQueryFilter; } List <long> result = new List <long>(); bool emptyQuery = true; //fidset - this takes precedence over anything else in //the query. If a fid set is specified then all selections //for the given query are intersections from the fidset if (qf.ObjectIDs.Count() > 0) { emptyQuery = false; result = null; result = _table.AsEnumerable().Where( row => qf.ObjectIDs.Contains((long)row["OBJECTID"])) .Select(row => (long)row["OBJECTID"]).ToList(); //anything selected? if (result.Count() == 0) { //no - specifying a fidset trumps everything. The client //specified a fidset and nothing was selected so we are done return(result); } } //where clause if (!string.IsNullOrEmpty(qf.WhereClause)) { emptyQuery = false; var sort = "OBJECTID";//default if (!string.IsNullOrEmpty(qf.PostfixClause)) { //The underlying System.Data.DataTable used by the sample supports "ORDER BY" //It should be a comma-separated list of column names and a default direction //COL1 ASC, COL2 DESC (note: "ASC" is not strictly necessary) //Anything else and there will be an exception sort = qf.PostfixClause; } //do the selection var oids = _table.Select(qf.WhereClause, sort) .Select(row => (long)row["OBJECTID"]).ToList(); //consolidate whereclause selection with fidset if (result.Count > 0 && oids.Count() > 0) { var temp = result.Intersect(oids).ToList(); result = null; result = temp; } else { result = null; result = oids; } //anything selected? if (result.Count() == 0) { //no - where clause returned no rows or returned no rows //common to the specified fidset return(result); } } //filter geometry for spatial select if (sqf != null) { if (sqf.FilterGeometry != null) { emptyQuery = false; bool filterIsEnvelope = sqf.FilterGeometry is Envelope; //search spatial index first var extent = sqf.FilterGeometry.Extent; var candidates = _rtree.Search(extent.ToRBushEnvelope()); //consolidate filter selection with current fidset if (result.Count > 0 && candidates.Count > 0) { var temp = candidates.Where(pt => result.Contains(pt.ObjectID)).ToList(); candidates = null; candidates = temp; } //anything selected? if (candidates.Count == 0) { //no - filter query returned no rows or returned no rows //common to the specified fidset return(new List <long>()); } //do we need to refine the spatial search? if (filterIsEnvelope && (sqf.SpatialRelationship == SpatialRelationship.Intersects || sqf.SpatialRelationship == SpatialRelationship.IndexIntersects || sqf.SpatialRelationship == SpatialRelationship.EnvelopeIntersects)) { //no. This is our final list return(candidates.Select(pt => pt.ObjectID).OrderBy(oid => oid).ToList()); } //refine based on the exact geometry and relationship List <long> oids = new List <long>(); foreach (var candidate in candidates) { if (GeometryEngine.Instance.HasRelationship( sqf.FilterGeometry, candidate.ToMapPoint(_sr), sqf.SpatialRelationship)) { oids.Add(candidate.ObjectID); } } //anything selected? if (oids.Count == 0) { //no - further processing of the filter geometry query //returned no rows return(new List <long>()); } result = null; //oids has already been consolidated with any specified fidset result = oids; } } //last chance - did we execute any type of query? if (emptyQuery) { //no - the default is to return all rows result = null; result = _table.Rows.Cast <DataRow>() .Select(row => (long)row["OBJECTID"]).OrderBy(x => x).ToList(); } return(result); }
public static DirectMessageCollection Top(int count, QueryFilter where, Database database) { return(Top(count, where, null, database)); }
public static DataPropertyCollection Query(QueryFilter filter, Database database = null) { return(Where(filter, database)); }
/// <summary> /// Search the underlying plugin table using the input QueryFilter /// </summary> /// <param name="queryFilter"></param> /// <remarks>If the PluginDatasourceTemplate.IsQueryLanguageSupported returns /// false, the WhereClause will always be empty.<br/> /// The QueryFilter is never null (even if the client passed in null to the "outside" /// table or feature class).<br/> /// A FID set in the ObjectIDs collection of the query filter, if present, acts as /// the "super" set - or constraint - from which all selections should be made. /// In other words, if the FID set contains ids {1,5,6,10} then a WhereClause /// on the query filter can only select from {1,5,6,10} and not from any other /// records.</remarks> /// <returns><see cref="PluginCursorTemplate"/></returns> public override PluginCursorTemplate Search(QueryFilter queryFilter) => this.SearchInternal(queryFilter);
/// <summary> /// Called the first time the pop-up content is viewed. This is good practice when you may show a pop-up for multiple items at a time. /// This allows you to delay generating the html content until the item is actually viewed. /// </summary> protected override Task <string> OnCreateHtmlContent() { return(QueuedTask.Run(() => { var invalidPopup = "<p>Pop-up content could not be generated for this feature.</p>"; var layer = MapMember as BasicFeatureLayer; if (layer == null) { return invalidPopup; } //Get all the visible numeric fields for the layer. var fields = layer.GetFieldDescriptions().Where(f => IsNumericFieldType(f.Type) && f.IsVisible); //Create a query filter using the fields found above and a where clause for the object id associated with this pop-up content. var tableDef = layer.GetTable().GetDefinition(); var oidField = tableDef.GetObjectIDField(); var qf = new QueryFilter() { WhereClause = $"{oidField} = {ID}", SubFields = string.Join(",", fields.Select(f => f.Name)) }; var rows = layer.Search(qf); //Get the first row, there should only be 1 row. if (!rows.MoveNext()) { return invalidPopup; } var row = rows.Current; //Loop through the fields, extract the value for the row and add to a dictionary. foreach (var field in fields) { var val = row[field.Name]; if (val is DBNull || val == null) { continue; } double value; if (!Double.TryParse(val.ToString(), out value)) { continue; } if (value < 0) { continue; } _values.Add(field, value); } if (_values.Count == 0) { return invalidPopup; } //Construct a new html string that we will use to update our html template. StringBuilder sb = new StringBuilder(); sb.AppendLine("data.addColumn('string', 'Votes')"); sb.AppendLine("data.addColumn('number', 'Count')"); sb.AppendLine("data.addColumn('number', 'In %')"); sb.AppendLine("data.addRows(["); //Add each value to the html string. foreach (var v in _values) { var percentage = (v.Value / _values.Sum(kvp => kvp.Value)) * 100; sb.AppendLine(string.Format("['{0}', {{v: {1} }}, {{v: {2} }}],", v.Key.Alias, v.Value, percentage)); } sb.AppendLine("]);"); //Get the html from the template file on disk that we have packaged with our add-in. var htmlPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "template.html"); var html = File.ReadAllText(htmlPath); //Update the template with our custom html and return it to be displayed in the pop-up window. html = html.Replace("//data.addColumn", sb.ToString()); return html; })); }
public static IList <RoleAssignmentPolicy> GetPolicies(IConfigurationSession session, QueryFilter filter) { if (session == null) { throw new ArgumentNullException("session"); } ADPagedReader <RoleAssignmentPolicy> adpagedReader = session.FindPaged <RoleAssignmentPolicy>(null, QueryScope.SubTree, filter, null, 0); List <RoleAssignmentPolicy> list = new List <RoleAssignmentPolicy>(); foreach (RoleAssignmentPolicy item in adpagedReader) { list.Add(item); } return(list); }
private void TestHashRangeTable(Table hashRangeTable, DynamoDBEntryConversion conversion) { // Put an item Document doc1 = new Document(); doc1["Name"] = "Alan"; doc1["Age"] = 31; doc1["Company"] = "Big River"; doc1["Score"] = 120; doc1["IsTester"] = true; doc1["Manager"] = "Barbara"; doc1["Aliases"] = new HashSet <string> { "Al", "Steve" }; doc1["PastManagers"] = new List <string> { "Carl", "Karl" }; hashRangeTable.PutItem(doc1); // Update a non-existent item creates the item Document doc2 = new Document(); doc2["Name"] = "Chuck"; doc2["Age"] = 30; doc2["Company"] = "Big River"; doc2["Score"] = 94; doc1["IsTester"] = false; doc2["Manager"] = "Barbara"; doc2["Aliases"] = new HashSet <string> { "Charles" }; hashRangeTable.UpdateItem(doc2); // Save more items Document doc3 = new Document(); doc3["Name"] = "Diane"; doc3["Age"] = 40; doc3["Company"] = "Madeira"; doc1["IsTester"] = true; doc3["Score"] = 140; doc3["Manager"] = "Eva"; hashRangeTable.UpdateItem(doc3); var oldDoc3 = doc3.Clone() as Document; // Changing the range key will force a creation of a new item doc3["Age"] = 24; doc3["Score"] = 101; hashRangeTable.UpdateItem(doc3); // Get item var retrieved = hashRangeTable.GetItem("Alan", 31); // Verify retrieved document Assert.IsTrue(AreValuesEqual(doc1, retrieved, conversion)); var tagsRetrieved = retrieved["Aliases"]; Assert.IsTrue(tagsRetrieved is PrimitiveList); Assert.AreEqual(2, tagsRetrieved.AsPrimitiveList().Entries.Count); // Test bool storage for different conversions var isTesterRetrieved = retrieved["IsTester"]; if (conversion == DynamoDBEntryConversion.V1) { Assert.AreEqual("1", isTesterRetrieved.AsPrimitive().Value as string); } else { Assert.IsTrue(isTesterRetrieved is DynamoDBBool); } // Test HashSet<string> storage for different conversions var pastManagersRetrieved = retrieved["PastManagers"]; if (conversion == DynamoDBEntryConversion.V1) { Assert.AreEqual(2, pastManagersRetrieved.AsPrimitiveList().Entries.Count); } else { Assert.AreEqual(2, pastManagersRetrieved.AsDynamoDBList().Entries.Count); } // Get item using GetItem overloads that expect a key in different ways retrieved = hashRangeTable.GetItem(doc2); Assert.IsTrue(AreValuesEqual(doc2, retrieved, conversion)); retrieved = hashRangeTable.GetItem(oldDoc3, new GetItemOperationConfig { ConsistentRead = true }); Assert.IsTrue(AreValuesEqual(oldDoc3, retrieved, conversion)); retrieved = hashRangeTable.GetItem("Diane", 24, new GetItemOperationConfig { ConsistentRead = true }); Assert.IsTrue(AreValuesEqual(doc3, retrieved, conversion)); // Scan the hash-and-range-key table var items = hashRangeTable.Scan(new ScanFilter()).GetRemaining(); Assert.AreEqual(4, items.Count); // Scan by pages var search = hashRangeTable.Scan(new ScanOperationConfig { Limit = 1 }); items.Clear(); while (!search.IsDone) { var set = search.GetNextSet(); items.AddRange(set); } Assert.AreEqual(4, items.Count); // Scan in parallel var segment1 = hashRangeTable.Scan(new ScanOperationConfig { Segment = 0, TotalSegments = 2 }).GetRemaining(); var segment2 = hashRangeTable.Scan(new ScanOperationConfig { Segment = 1, TotalSegments = 2 }).GetRemaining(); Assert.AreEqual(4, segment1.Count + segment2.Count); // Query items items = hashRangeTable.Query("Diane", new QueryFilter()).GetRemaining(); Assert.AreEqual(2, items.Count); var queryConfig = new QueryOperationConfig { KeyExpression = new Expression { ExpressionAttributeNames = new Dictionary <string, string> { { "#N", "Name" } }, ExpressionAttributeValues = new Dictionary <string, DynamoDBEntry> { { ":v", "Diane" } }, ExpressionStatement = "#N = :v" } }; items = hashRangeTable.Query(queryConfig).GetRemaining(); Assert.AreEqual(2, items.Count); queryConfig = new QueryOperationConfig { KeyExpression = new Expression { ExpressionAttributeNames = new Dictionary <string, string> { { "#N", "Name" } }, ExpressionAttributeValues = new Dictionary <string, DynamoDBEntry> { { ":v", "Diane" } }, ExpressionStatement = "#N = :v" }, FilterExpression = new Expression { ExpressionAttributeNames = new Dictionary <string, string> { { "#S", "Score" } }, ExpressionAttributeValues = new Dictionary <string, DynamoDBEntry> { { ":v2", 120 } }, ExpressionStatement = "#S > :v2" } }; items = hashRangeTable.Query(queryConfig).GetRemaining(); Assert.AreEqual(1, items.Count); queryConfig = new QueryOperationConfig { KeyExpression = new Expression { ExpressionAttributeNames = new Dictionary <string, string> { { "#N", "Name" }, { "#A", "Age" } }, ExpressionAttributeValues = new Dictionary <string, DynamoDBEntry> { { ":v2", 120 } }, ExpressionStatement = "#N = :v and #A < :v2" }, FilterExpression = new Expression { ExpressionAttributeNames = new Dictionary <string, string> { { "#S", "Score" }, { "#A", "Age" } }, ExpressionAttributeValues = new Dictionary <string, DynamoDBEntry> { { ":v", "Diane" }, }, ExpressionStatement = "#S < :v2" } }; items = hashRangeTable.Query(queryConfig).GetRemaining(); Assert.AreEqual(1, items.Count); // Query local index items = hashRangeTable.Query(new QueryOperationConfig { IndexName = "LocalIndex", Filter = new QueryFilter("Name", QueryOperator.Equal, "Diane") }).GetRemaining(); Assert.AreEqual(2, items.Count); // Query global index var queryFilter = new QueryFilter("Company", QueryOperator.Equal, "Big River"); queryFilter.AddCondition("Score", QueryOperator.GreaterThan, 100); items = hashRangeTable.Query(new QueryOperationConfig { IndexName = "GlobalIndex", Filter = queryFilter }).GetRemaining(); Assert.AreEqual(1, items.Count); // Scan local index var scanFilter = new ScanFilter(); scanFilter.AddCondition("Name", ScanOperator.Equal, "Diane"); items = hashRangeTable.Scan(new ScanOperationConfig { IndexName = "LocalIndex", Filter = scanFilter }).GetRemaining(); Assert.AreEqual(2, items.Count); // Scan global index scanFilter = new ScanFilter(); scanFilter.AddCondition("Company", ScanOperator.Equal, "Big River"); scanFilter.AddCondition("Score", ScanOperator.GreaterThan, 100); items = hashRangeTable.Query(new QueryOperationConfig { IndexName = "GlobalIndex", Filter = queryFilter }).GetRemaining(); Assert.AreEqual(1, items.Count); }
public static IList <RoleAssignmentPolicy> GetDefaultPolicies(IConfigurationSession session, QueryFilter extraFilter) { QueryFilter queryFilter = RoleAssignmentPolicyHelper.filter; if (extraFilter != null) { queryFilter = new AndFilter(new QueryFilter[] { extraFilter, RoleAssignmentPolicyHelper.filter }); } return(RoleAssignmentPolicyHelper.GetPolicies(session, queryFilter)); }
private void TestPagination(Table hashRangeTable) { var itemCount = 10; var batchWrite = hashRangeTable.CreateBatchWrite(); var name = "Borg"; // Put items for (int i = 0; i < itemCount; i++) { Document doc = new Document(); doc["Name"] = name; doc["Age"] = 1 + i; doc["Company"] = "Big River"; doc["Score"] = 120 + i; doc["IsTester"] = true; doc["Manager"] = "Kirk"; batchWrite.AddDocumentToPut(doc); } batchWrite.Execute(); // Paginated scan { var request = new ScanOperationConfig { Limit = 1 }; var search = hashRangeTable.Scan(request); var tokens = new List <string>(); var retrievedCount = VerifyPagination(search, tokens); Assert.AreEqual(retrievedCount, itemCount); Assert.AreEqual(itemCount, tokens.Count); var token4 = tokens[4]; var token5 = tokens[5]; search = hashRangeTable.Scan(new ScanOperationConfig { Limit = 1, PaginationToken = token4 }); search.GetNextSet(); Assert.AreNotEqual(token4, search.PaginationToken); Assert.AreEqual(token5, search.PaginationToken); } // Paginated query { var filter = new QueryFilter("Name", QueryOperator.Equal, name); var request = new QueryOperationConfig { Limit = 1, Filter = filter }; var search = hashRangeTable.Query(request); var tokens = new List <string>(); var retrievedCount = VerifyPagination(search, tokens); Assert.AreEqual(retrievedCount, itemCount); Assert.AreEqual(itemCount, tokens.Count); var token4 = tokens[4]; var token5 = tokens[5]; search = hashRangeTable.Query(new QueryOperationConfig { Limit = 1, Filter = filter, PaginationToken = token4 }); search.GetNextSet(); Assert.AreNotEqual(token4, search.PaginationToken); Assert.AreEqual(token5, search.PaginationToken); } }
/// <summary> /// 解析生成查询SQL /// </summary> /// <remarks>按主键数据作为查询依据</remarks> /// <param name="domainModel">领域模型</param> /// <param name="domainObject">领域对象</param> /// <param name="filter">过滤器</param> /// <returns>查询SQL</returns> public SqlStatementCollection ParseQuerySqlByFilter(DomainModel.Spi.DomainModel domainModel, DomainModel.Spi.DomainObject domainObject, QueryFilter filter) { var sqls = new SqlStatementCollection(); return(sqls); }
public void MainMethodCode() { using (Geodatabase fileGeodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\Data\LocalGovernment.gdb")))) using (FeatureClass featureClass = fileGeodatabase.OpenDataset <FeatureClass>("SchoolBoundary")) { SpatialQueryFilter spatialQueryFilter = new SpatialQueryFilter { FilterGeometry = new PolygonBuilder(new List <Coordinate2D> { new Coordinate2D(1021880, 1867396), new Coordinate2D(1028223, 1870705), new Coordinate2D(1031165, 1866844), new Coordinate2D(1025373, 1860501), new Coordinate2D(1021788, 1863810), }).ToGeometry(), SpatialRelationship = SpatialRelationship.Intersects }; QueryFilter anotherQueryFilter = new QueryFilter { WhereClause = "DISTRCTNAME = 'Indian Prairie School District 204'" }; using (Selection spatialSelection = featureClass.Select(spatialQueryFilter, SelectionType.ObjectID, SelectionOption.Normal)) using (Selection indianPrairieSelection = featureClass.Select(anotherQueryFilter, SelectionType.ObjectID, SelectionOption.Normal)) { // In order to find all features which are in the specified Polygon and in the specified district. using (Selection selection = spatialSelection.Combine(indianPrairieSelection, SetOperation.Intersection)) { IEnumerable <long> oids = indianPrairieSelection.GetObjectIDs(); selection.Add(oids.ToList()); } } } //Opening a Non-Versioned SQL Server instance DatabaseConnectionProperties connectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer) { AuthenticationMode = AuthenticationMode.DBMS, // Where testMachine is the machine where the instance is running and testInstance is the name of the SqlServer instance. Instance = @"testMachine\testInstance", // Provided that a database called LocalGovernment has been created on the testInstance and geodatabase has been enabled on the database. Database = "LocalGovernment", // Provided that a login called gdb has been created and corresponding schema has been created with the required permissions. User = "******", Password = "******", Version = "dbo.DEFAULT" }; using (Geodatabase geodatabase = new Geodatabase(connectionProperties)) using (FeatureClass facilitySiteFeatureClass = geodatabase.OpenDataset <FeatureClass>("LocalGovernment.GDB.FacilitySite")) { QueryFilter queryFilter = new QueryFilter { WhereClause = "FCODE = 'Park'" }; QueryFilter subtypeQueryFilter = new QueryFilter { WhereClause = "SUBTYPEFIELD = 730" }; using (Selection parkSelection = facilitySiteFeatureClass.Select(queryFilter, SelectionType.ObjectID, SelectionOption.Normal)) using (Selection educationSubtypeSelection = facilitySiteFeatureClass.Select(subtypeQueryFilter, SelectionType.ObjectID, SelectionOption.Normal)) using (Selection parksAndSchools = educationSubtypeSelection.Combine(parkSelection, SetOperation.Union)) { } QueryFilter hazardousFacilityFilter = new QueryFilter { WhereClause = "FCODE = 'Hazardous Materials Facility'" }; QueryFilter industrySubtypeQueryFilter = new QueryFilter { WhereClause = "SUBTYPEFIELD = 710" }; using (Selection hazardousFacilitySelection = facilitySiteFeatureClass.Select(hazardousFacilityFilter, SelectionType.ObjectID, SelectionOption.Normal)) using (Selection industrySelection = facilitySiteFeatureClass.Select(industrySubtypeQueryFilter, SelectionType.ObjectID, SelectionOption.Normal)) using (Selection nonHazardousIndustryFacilities = industrySelection.Combine(hazardousFacilitySelection, SetOperation.Difference)) { } QueryFilter nonProfitFilter = new QueryFilter { WhereClause = "OWNTYPE = 'Non-Profit'" }; QueryFilter publicAttractionQueryFilter = new QueryFilter { WhereClause = "SUBTYPEFIELD = 820" }; using (Selection nonProfitSelection = facilitySiteFeatureClass.Select(nonProfitFilter, SelectionType.ObjectID, SelectionOption.Normal)) using (Selection publicAttractionSelection = facilitySiteFeatureClass.Select(publicAttractionQueryFilter, SelectionType.ObjectID, SelectionOption.Normal)) using (Selection eitherPublicAttactionOrNonProfit = nonProfitSelection.Combine(publicAttractionSelection, SetOperation.SymmetricDifference)) { } } }
private void button2_Click(object sender, EventArgs e) { if (pMap.SelectionCount > 1) { MessageBox.Show("Please select only one feature (starting point)", "Selection error..."); return; } OperationLayer = comboBox2.Text; OperationAttribute = comboBox3.Text; Tolerance = Convert.ToDouble(textBox2.Text); NoOfSplit = Convert.ToInt16(textBox1.Text); IEnumLayer pEnumLayer = pMap.Layers; ILayer pLayer; for (int i = 0; i < pMap.LayerCount; i++) { pLayer = pEnumLayer.Next(); if (pLayer.Name.Equals(OperationLayer)) { IDataset pDataSet = (IDataset)(pLayer); Geoprocessor GP = new Geoprocessor(); GP.OverwriteOutput = true; AddField SplitGroup = new AddField(); SplitGroup.in_table = pDataSet.Workspace.PathName + System.IO.Path.DirectorySeparatorChar + pDataSet.Name + ".shp"; //........ workSpacePath = pDataSet.Workspace.PathName; //........ SplitGroup.field_name = "SpltGropus"; SplitGroup.field_type = "SHORT"; GP.Execute(SplitGroup, null); CalculateField CalculateField = new CalculateField(); CalculateField.in_table = pDataSet.Workspace.PathName + System.IO.Path.DirectorySeparatorChar + pDataSet.Name + ".shp"; CalculateField.field = "SpltGropus"; CalculateField.expression = "0"; GP.Execute(CalculateField, null); AddField TempGroup = new AddField(); TempGroup.in_table = pDataSet.Workspace.PathName + System.IO.Path.DirectorySeparatorChar + pDataSet.Name + ".shp"; TempGroup.field_name = "Distance"; TempGroup.field_type = "DOUBLE"; GP.Execute(TempGroup, null); AggregatePolygons ConcaveHull = new AggregatePolygons(); ConcaveHull.aggregation_distance = Tolerance; ConcaveHull.in_features = pDataSet.Workspace.PathName + System.IO.Path.DirectorySeparatorChar + pDataSet.Name + ".shp"; ConcaveHull.out_feature_class = System.IO.Path.GetTempPath() + System.IO.Path.DirectorySeparatorChar + "Temp_ConcaveHull.shp"; GP.AddOutputsToMap = false; GP.Execute(ConcaveHull, null); //IFeatureLayer2 pFeatureLayer21 = (IFeatureLayer2)pLayer; //IFeatureClass pFeatureClass1 = pFeatureLayer21.FeatureClass; //IField spltgrp = new FieldClass(); //IFieldEdit spltgrp1 = (IFieldEdit)spltgrp; //spltgrp1.Name_2 = "SpltGropus"; //spltgrp1.Type_2 = esriFieldType.esriFieldTypeSmallInteger; //spltgrp = spltgrp1; //IField tmpgrp = new FieldClass(); //IFieldEdit tmpgrp1 = (IFieldEdit)tmpgrp; //tmpgrp1.Name_2 = "TempGroups"; //tmpgrp1.Type_2 = esriFieldType.esriFieldTypeSmallInteger; //tmpgrp = tmpgrp1; //pFeatureClass1.AddField(spltgrp); //pFeatureClass1.AddField(tmpgrp); IFeatureLayer pFeatureLayer = (IFeatureLayer)pLayer; IFeatureSelection pFeatureSelection = (IFeatureSelection)pFeatureLayer; ISelectionSet pSelectionSet = pFeatureSelection.SelectionSet; ICursor pCursor; pSelectionSet.Search(null, false, out pCursor); IFeatureCursor pFeatureCursor = (IFeatureCursor)pCursor; IFeature pFeature = pFeatureCursor.NextFeature(); GroupIDTotal Group = new GroupIDTotal(); Group.setID(1); Group.setCalculatedSplitValue(Convert.ToDouble(pFeature.get_Value(pFeature.Fields.FindField(OperationAttribute)))); pFeature.set_Value(pFeature.Fields.FindField("SpltGropus"), 1); pFeature.Store(); GroupIDTotalList.Add(Group); //Group = new GroupIDTotal (1,(double)pFeature.get_Value(pFeature.Fields.FindField(OperationAttribute))); IFeatureLayer2 pFeatureLayer2 = (IFeatureLayer2)pLayer; IFeatureClass pFeatureClass = pFeatureLayer2.FeatureClass; IQueryFilter pQueryFilter = new QueryFilter(); pQueryFilter.WhereClause = null; IFeatureCursor pFeatureCursor1 = pFeatureClass.Search(pQueryFilter, false); IFeature pFeature1; for (int j = 0; j < pFeatureClass.FeatureCount(pQueryFilter); j++) { pFeature1 = pFeatureCursor1.NextFeature(); FieldTotal = FieldTotal + Convert.ToDouble(pFeature1.get_Value(pFeature1.Fields.FindField(OperationAttribute))); } EqualPartValue = FieldTotal / Convert.ToInt16(textBox1.Text); F2FDistance.MakeDistanceArray(pFeature, GroupIDTotalList[0].getID()); int k = 2; while ((NoOfSplit - 1) != RegionFormed) { IFeature NextStartingFeature = StaticMethodsClass.FindNextStartingFeature(RegionGeomtry); //MessageBox.Show("..." + NextStartingFeature.OID, "hi"); GroupIDTotal NextGroup = new GroupIDTotal(); NextGroup.setID((short)k); NextGroup.setCalculatedSplitValue(Convert.ToDouble(NextStartingFeature.get_Value(NextStartingFeature.Fields.FindField(OperationAttribute)))); NextStartingFeature.set_Value(NextStartingFeature.Fields.FindField("SpltGropus"), k); NextStartingFeature.Store(); GroupIDTotalList.Add(NextGroup); F2FDistance.MakeDistanceArray(NextStartingFeature, GroupIDTotalList[k - 1].getID()); k = k + 1; } // //IGeometry pPol = CreateConvexHull.Create(pFeatureCursor1); //IFeature dd = pFeatureClass.CreateFeature(); //dd.Shape = pPol; //dd.Store(); //IActiveView activeView = pMap as IActiveView; //activeView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null); //MessageBox.Show("...", "hi"); // } } MessageBox.Show("..." + FieldTotal + "..." + EqualPartValue, "hi"); //MessageBox.Show("..." + pFeature1.OID, "hi"); }
public static CategoryCollection Query(QueryFilter filter, Database database = null) { return(Where(filter, database)); }
public IEnumerable <IWorkItem> GetItems(GdbTableIdentity tableId, QueryFilter filter, bool recycle = true) { throw new NotImplementedException(); }
public static async Task BatchQuery(int batchSize, QueryFilter filter, Action <IEnumerable <DynamicTypePropertyDescriptor> > batchProcessor, Database database = null) { await BatchQuery(batchSize, (c) => filter, batchProcessor, database); }
private void RemoveInvalidRoleAssignments() { TaskLogger.LogEnter(); QueryFilter filter = new OrFilter(new QueryFilter[] { new NotFilter(new ExistsFilter(ExchangeRoleAssignmentSchema.Role)), new NotFilter(new ExistsFilter(ExchangeRoleAssignmentSchema.User)) }); ADPagedReader <ExchangeRoleAssignment> adpagedReader = this.configurationSession.FindPaged <ExchangeRoleAssignment>(base.OrgContainerId.GetDescendantId(ExchangeRoleAssignment.RdnContainer), QueryScope.OneLevel, filter, null, 0); foreach (ExchangeRoleAssignment roleAssignment in adpagedReader) { this.RemoveRoleAssignment(roleAssignment); } if (this.adSplitPermissionMode) { List <QueryFilter> list = new List <QueryFilter>(); foreach (RoleType roleType in InstallCannedRbacRoleAssignments.invalidRoleTypesInADSplitPermissionMode) { list.Add(new ComparisonFilter(ComparisonOperator.Equal, ExchangeRoleSchema.RoleType, roleType)); } ADPagedReader <ExchangeRole> adpagedReader2 = this.configurationSession.FindPaged <ExchangeRole>(base.OrgContainerId.GetDescendantId(ExchangeRole.RdnContainer), QueryScope.SubTree, QueryFilter.OrTogether(list.ToArray()), null, 0); List <QueryFilter> list2 = new List <QueryFilter>(); foreach (ExchangeRole exchangeRole in adpagedReader2) { list2.Add(new ComparisonFilter(ComparisonOperator.Equal, ExchangeRoleAssignmentSchema.Role, exchangeRole.Id)); } ADPagedReader <ExchangeRoleAssignment> adpagedReader3 = this.configurationSession.FindPaged <ExchangeRoleAssignment>(base.OrgContainerId.GetDescendantId(ExchangeRoleAssignment.RdnContainer), QueryScope.OneLevel, QueryFilter.AndTogether(new QueryFilter[] { InstallCannedRbacRoleAssignments.regularRoleAssignmentFilter, QueryFilter.OrTogether(list2.ToArray()) }), null, 0); foreach (ExchangeRoleAssignment roleAssignment2 in adpagedReader3) { this.RemoveRoleAssignment(roleAssignment2); } } TaskLogger.LogExit(); }