I am creating a client application that connects to a website in order to execute queries. I am not enabling the client to connect directly to the database but he can perform queries through the website.
The way I execute queries through the website is through linq. For example I may do:
MyEntities db = new MyEntities();
var customers = db.Customers.ToList();
Since the client does not have the connection string and sql server does not allow remote connections when he executes the above code it will obviously not work. My question is how can the client send that query to the web service?
The reason why I need this is because there are so many different types of queries and for each different one I have to create a different page. For example I have GetInvoices.aspx, GetCustomers.aspx, and I am always creating new ones just because I dont want the client to connect directly to the database. It will be nice if I could serialize the linq query and send that to the server. the server then should validate that I am not doing a delete statement for example and if thats the case then execute the query.
Eidt
This is what I am going to do for only select statements:
// Note connection string only have basics. It does not have password nor database.
public static string GenerateSelectQuery<T>(Func<Common.Data.TcEntities, IQueryable> method)
{
Common.Data.TcEntities db = new Common.Data.TcEntities(#"metadata=res://*/Data.Model1.csdl|res://*/Data.Model1.ssdl|res://*/Data.Model1.msl;provider=System.Data.SqlClient;provider connection string=""""");
var query = method(db);
return query.ToString();
}
then if I wish to create a custom query I will do:
var query = GenerateSelectQuery<Customer>(db => db.Customers.Where(x=>x.FirstName.Contains("a")));
I will send then that string to the server and expect an array of Customers. On the server side I will make sure string starts with select and it does not contain --.
Implementing a WCF Data Services, http client can query your data using the OData protocol.
For example, applying a select Name on your customers collections will be queryable using the http url:
http://youdomain/yourWCFDataServices.svc/Customers()?$select=Name
Related
I want to connect with Azure Cosmos DB API for MongoDB via ASP.NET app. To start I use connection string provided by Microsoft (when creating an instance by Azure)
var client = new MongoClient("mongodb://[myInstanceName]:
[primaryAccountKey]#[myInstanceName].documents.azure.com:10255/?ssl=true&retrywrites=false&replicaSet=globaldb
&maxIdleTimeMS=120000&appName=#mongocosmocoffedb#");
var database = client.GetDatabase("productdb");
var collection = database.GetCollection<Product>("productcollection");
return Ok(collection);
But when I use this connection string I got error
DirectConnection cannot be used when ConnectionModeSwitch is set to UseConnectionMode.
I found this stackoverflow topic and try use
var client = new MongoClient("mongodb://[myInstanceName]:
[primaryAccountKey]#[myInstanceName].documents.azure.com:10255/?ssl=true");
but in this case i got error
MaxWireVersion is not known.
This is the connection mode port issue. The port number you mentioned 10255 is used for geo-replication and that is causing the issue. Post numbers 10255, 10256 map to the instance that has geo-replication.
Change the port number to 10255. 10250 maps to the default Azure cosmos DB API for Mongo DB. In case of using geo-replication, public end point you can use 10255
Refer the following link: https://learn.microsoft.com/en-us/azure/cosmos-db/sql/sql-sdk-connection-modes
Creating database and adding to failover group
I have an Azure elastic pool and I have created a failover group with another elastic pool (with the same name) on a different Azure region, during the creation of the failover group I selected the elastic pool and it went through and added all the databases in the elastic pool to the elastic pool on the secondary server.
I have a script setup to automatically create new databases using the following TSQL:
CREATE DATABASE databaseName ( SERVICE_OBJECTIVE = ELASTIC_POOL ( name = "Elastic pool name" ) );
However, the above script does not add the database to the failover group and therefore it does not get added to the other SQL server in my other Azure region. I don't want to have to manually add any new databases to the failover group via the Azure portal each time so is there a TSQL script I can use at the point of creation to add the database to the failover group?
Deleting database, removing from failover group and from secondary server
Following on from the above I also have the following TQL which deletes a database:
DROP DATABASE databaseName;
Running the above deletes the database from the primary server and it removes it from the failover group but the database still exists on the secondary server. Is there a way to remove it from the secondary server using TSQL, is it as simple as running the above script again but pointing to the secondary server or is there a better way of doing this?
EDIT
As it seems there is no way to do this with TSQL then is this possible in C# using the Azure API with something like the following?
var dbResponse = client.FailoverGroups.Update("resourceGroupName",
"serverName",
"failoverGroupName",
new Microsoft.Azure.Management.Sql.Models.FailoverGroupUpdate() {
Databases = new List<string>() { "databaseName" }
}
);
I'm afraid no, there isn't a TSQL script which you can use at the point of creation to add the database to the failover group.
Only the two ways Azure provides for us can manage the failover group: Portal and Powershell.
If you want to delete the secondary database, remove it from the failover group before deleting it. Ref here:
We still need do these database adding or deleting options with Portal or PowerShell.
Running some tests it seems you can use the Azure Rest API to do this and I have written the following method to test this, although it looks like you have to always pass through all the database names because this does not append what is already there but actually replaces the list of databases in the failover group.
I have not tested this in production to see if this would cause any issues such as effectively removing and re-adding the databases each time.
Hopefully someone else might be able to provide a better solution, my ideal solution would still be to use TSQL if possible because it means not having to setup a user account to access the REST API.
public async Task AddDatabasesToFailoverGroupAsync(List<string> databaseNames)
{
// Variables
string domainName = "XXXX"; /* Tenant ID or AAD domain */
string username = "XXXX";
string password = "XXXX";
string resourceGroupName = "XXXXX";
string serverName = "XXXX";
string failoverGroupName = "XXXXX";
string clientId = "XXXXX"; /* Active Directory APP Client ID */
string subscriptionId = "XXXXXX";
string databasePrefix = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/";
List<string> databases = new List<string>();
// Add prefix to database names
foreach (var dbName in databaseNames)
databases.Add($"{databasePrefix}{dbName}");
// Login to Azure
var credentials = await UserTokenProvider.LoginSilentAsync(clientId, domainName, username, password);
// Create client
SqlManagementClient client = new SqlManagementClient(credentials)
{
SubscriptionId = subscriptionId
};
// Set parameters
var parameters = new FailoverGroupUpdate()
{
Databases = databases
};
// Update failover group
client.FailoverGroups.Update(resourceGroupName, serverName, failoverGroupName, parameters);
}
Used by:
EntityFramework - 6.2.0;
MS Sql Server 2012;
In MS Access, I use the following query(req_GroupsStud_CurGroup):
SELECT req_GroupsStud_Stud.*, req_GroupsStud_Stud.id_group
FROM req_GroupsStud_Stud
WHERE (((req_GroupsStud_Stud.id_group)=[Forms]![frm_00_00_MainForm]![id_group_Frm]));
From the form, using the expression [Forms]![Frm_00_00_MainForm]![Id_group_Frm], the parameter [id_group_Frm] is passed to the request.
Questions.
How in MS Sql Server to transfer in the query req_GroupsStud_CurGroup parameter
`id_group_Frm "?
Or are there other tools in MS Sql Server and EntityFramework to get a similar data set?
Update_1:
Requirements for the request req_GroupsStud_CurGroup:
1. if changes are made to the record in the request, these changes should be displayed in the original source;
if the record is added to the request, then this record is displayed in the source;
the request is planned to be used in another request.
I managed to implement these requirements in MSAccess.
I do not understand how to do the same using Entity-Framework and MS SQL Server.
I tried the following methods:
- method_1
cntDB.req_GroupsStud_Stud.Load();
System.Data.SqlClient.SqlParameter id_group_Param = new System.Data.SqlClient.SqlParameter("#id_group_frm", id_group);
var sp_Get_Stud_var = cntDB.Database.SqlQuery<req_GroupsStud_Stud>("sp_Get_Stud #id_group_frm", id_group_Param).ToList();
bs_Grid_2.DataSource = sp_Get_Stud_var;
dataGridView2.DataSource = bs_Grid_2;
- method_2
cntDB.sp_Get_Stud(id_group);
Can not fully understand.
I think these methods will not meet the above requirements for the request.
I want to translate something like
MATCH (s)
WHERE ID(s) = 65110
RETURN s
into C# to use it with the Graph client. My main problem is that I want to get a node by using the internal id of Neo4j, which is absolutely no problem in Cypher but how can I do this in Graph client?
var query = client.Cypher
.Match("(s)")
.Where((Event s) => ID(s) == 65110)
.Return(...);
This was my first approach but of course that does not work. Can you tell me how to use this ID function of Cypher to get a node with a specific internal Neo4j id by using the Graph client for C#?
For explanation, client is a variable, that connects to the Graph Client of Neo4j:
var client = new GraphClient(new Uri("http://localhost:7474/db/data"), "username", "Password");
client.Connect();
I'm using a parameter here, as that's the best way to ensure the query will be compiled and cached, obviously you could just put in the ID. Generally - you want to avoid using the ID of a Neo4j item, in fact - I would strongly urge you to add you're own ID field. But! here it is anyhews :)
var query = client.Cypher
.Match("(s)")
.Where("ID(s) = {idParam}")
.WithParam("idParam", 65110)
.Return(s => s.As<Node<string>>());
I connect with the following code to a mongo database.
Then i iterated through the server descriptions of the cluster but the state is always "disconnected" but when i look with tools like monogchef i can see that all server are connected and there is one primary and all others are secondaries
var client = new MongoClient(conString);
var db = client.GetDatabase("admin");
foreach (var server in client.Cluster.Description.Servers)
{
Console.WriteLine(server.State); // Always returns disconnected.
}
How can I read who is the primary and when has been the last election?
Just found it.
Have to make a dummy request then i find the data under
server.ReplicaSetConfig.Primary