LinqPad connect two azure databases on same server - c#

Per the FAQ (1), I can add additional databases to my existing connection in a number of ways. I have tried them all, and none work for SQL Azure.
In fact, SQL Azure as a provider, doesn't even include the option to "Include additional databases."
Can someone please tell me a workaround for LinqPad to connect two databases? I am trying to create a migration linqpad script to sync data from one database to another.
http://www.linqpad.net/FAQ.aspx#cross-database

This fails because SQL Azure does not let you create linked servers. See
Can linked server providers be installed on a SQL Azure Database instance?
If you simply want to copy data from one database to another, and the schemas are the same, a workaround is to create a separate connection using the same TypedDataContext class:
void Main()
{
CopyFrom<Customer>("<source connection string>");
}
void CopyFrom<TTable> (string sourceCxString) where TTable : class
{
// Create another typed data context for the source. Note that it must have compatible schema:
using (var sourceContext = new TypedDataContext (sourceCxString) { ObjectTrackingEnabled = false })
{
// Delete the rows currently in our table:
ExecuteCommand ("delete " + Mapping.GetTable (typeof (TTable)).TableName);
// Insert the rows from the source table into the target table and submit changes:
GetTable<TTable>().InsertAllOnSubmit (sourceContext.GetTable<TTable>());
SubmitChanges();
}
}
Simple Select Example:
void Main()
{
SimpleSelect("<your conn string>");
}
void SimpleSelect (string sourceCxString)
{
// Create another typed data context for the source. Note that it must have compatible schema:
using (var sourceContext = new TypedDataContext (sourceCxString) { ObjectTrackingEnabled = false })
{
sourceContext.Assignee.OrderByDescending(a => a.CreateTimeStamp).Take(10).Dump();
Assignee.OrderByDescending(a => a.CreateTimeStamp).Take(10).Dump();
}
}

Related

The Add method does not insert a new record into the database

The Add method does not insert a new record into the database.
Working with the database through the application.
The SelectAll request is executed.
The Insert request is not executed. There are no errors.
The Insert request code. Not running(Not working)
public void Insert(Source source)
{
using (var DbContext = new DbContextSQlite())
{
dbContext.Sources.Add(source);
dbContext.SaveChanges();
}
}
The selectAll request code.
Public void selectAll() is running
{
using (var DbContext = new DbContextSQlite())
{
var rows = from x in dbContext.Sources
select x;
int count = rows.Count();
}
}
Working with the database via DB Browser using SQL queries
The Select query is executed.
The Insert request is being executed.
Used.
DB Browser for SQLite Version 3.12.2;
Visual Studio Community 2019. 16.11.10;
Application-Console. .NET Framework 4.7.2;
Picture-1
Picture-2
Update-1
Update-1.
When I try to fully post a question, stackoverflow.com gives me comments on the design. I don't understand how to eliminate these comments.
That's why I'm posting the question in an online editor.
Follow the link -> Detailed question.

MongoDB C# Driver: Query interceptors?

Does the MongoDB C# driver support query interceptors like Entity Framework?
I've checked the documentation but can't find anything.
Basically what I need to do is ensure that certain queries to the database, depending on context, always have certain restrictions applied.
For example, if my documents can be soft deleted then I always need to make sure a filter is added for { "SoftDeleted": false }. Entitity Framework handles this gracefully via query interceptors.
MongoClient allows subscribing to CommandStartedEvent. Here is a sample that dumps to console each command sent to the server:
var mongoClient = new MongoClient(new MongoClientSettings
{
Server = new MongoServerAddress("localhost", 27017),
ClusterConfigurator = cb =>
{
cb.Subscribe<CommandStartedEvent>(e =>
{
Console.WriteLine($"{e.CommandName} - {e.Command.ToJson(new JsonWriterSettings { Indent = true })}");
Console.WriteLine(new String('-', 32));
});
}
});
CommandStartedEvent contains CommandName and Command properties that you could use for your specific logic.

C# And MongoDB Create DB from Code

Hi Im Trying to create a DataBase in MongoDB from C# code This is the code Im Useing
public partial class SqlToMongo : Form
{
public SqlToMongo()
{
InitializeComponent();
connectToMongo();
}
public void connectToMongo(){
var con = "mongodb://127.0.0.1";
MongoClient client = new MongoClient(con);
var db = client.GetDatabase("BetsOdds");
bool d = db.RunCommandAsync((Command<BsonDocument>)"{ping:1}")
.Wait(2000);
var Betsodds = db.GetCollection<BetOdds>("Betodds");
}
}
The ping return true when MongoService is running and false when the service is off, the code works.
I'm using RoboMongo as a GUI for MongoDB and after the code runs i still don't see the Database on the GUI. i need some help what i'm doing wrong
Thanks
The database will not show up in the list until you have added some data. I have not used RoboMongo, but if you create a database in code, and then using the Mongo console to list the databases, you will not see anything. Add some data and try again, the database will show up in the list of the 'show dbs' command.

how can i use System.Data.Sql.SqlDataSourceEnumerator class to know available sql datasources...?

how can i use System.Data.Sql.SqlDataSourceEnumerator class to know about available sql datasources...?
because while i am creating connection to sql server if sql server is not ready we will get exception… so first i want to know is sql server is ready to accept request or not… how to know it….
So, according to the following references:
http://social.msdn.microsoft.com/forums/en-US/sqlsmoanddmo/thread/49ba019f-e8b5-457c-80ea-fac5febb9d3d/
http://connect.microsoft.com/SQLServer/feedback/details/146323/enumavailablesqlservers-or-sqldatasourceenumerator-incorrect-list-of-available-databases
http://blogs.msdn.com/b/sushilc/archive/2004/10/14/242395.aspx
http://sqlblogcasts.com/blogs/jonsayce/archive/2008/02/10/programatically-listing-sql-servers.aspx
GetDataSources() is not a perfect method, meaning, it may not list all the available data sources on first try. In fact, I found that it also does not list all of your local sources.
For my purposes, I had some time between when the program started and when I needed to get the list of available sources, both on the network AND local. So, I put the code in a thread that goes on forever collecting all the sources. Here it is below. If you take out the while loop, you can call it manually as many times as you'd like.
private List<string> sqlInstances = new List<string>();
private void collectInstances()
{
while (true)
{
System.Data.Sql.SqlDataSourceEnumerator instance = System.Data.Sql.SqlDataSourceEnumerator.Instance;
System.Data.DataTable dataTable = instance.GetDataSources();
foreach (DataRow row in dataTable.Rows)
{
string instanceName = String.Format(#"{0}\{1}", row["ServerName"].ToString(), row["InstanceName"].ToString());
//Do not add the local instance, we will add it in the next section. Otherwise, duplicated!
if (!sqlInstances.Contains(instanceName) && !instanceName.Contains(Environment.MachineName))
{
sqlInstances.Add(instanceName);
}
}
/*
* For some reason, GetDataSources() does not get local instances. So using code from here to get them
* http://stackoverflow.com/questions/6824188/sqldatasourceenumerator-instance-getdatasources-does-not-locate-local-sql-serv
*/
List<string> lclInstances = GetLocalSqlServerInstanceNames();
foreach (var lclInstance in lclInstances)
{
string instanceName = String.Format(#"{0}\{1}", Environment.MachineName, lclInstance);
if (!sqlInstances.Contains(instanceName)) sqlInstances.Add(instanceName);
}
sqlInstances.Sort();
}
}
//Got code from: http://stackoverflow.com/questions/6824188/sqldatasourceenumerator-instance-getdatasources-does-not-locate-local-sql-serv
/// <summary>
/// get local sql server instance names from registry, search both WOW64 and WOW3264 hives
/// </summary>
/// <returns>a list of local sql server instance names</returns>
public static List<string> GetLocalSqlServerInstanceNames()
{
RegistryValueDataReader registryValueDataReader = new RegistryValueDataReader();
string[] instances64Bit = registryValueDataReader.ReadRegistryValueData(RegistryHive.Wow64,
Registry.LocalMachine,
#"SOFTWARE\Microsoft\Microsoft SQL Server",
"InstalledInstances");
string[] instances32Bit = registryValueDataReader.ReadRegistryValueData(RegistryHive.Wow6432,
Registry.LocalMachine,
#"SOFTWARE\Microsoft\Microsoft SQL Server",
"InstalledInstances");
//FormatLocalSqlInstanceNames(ref instances64Bit);
//FormatLocalSqlInstanceNames(ref instances32Bit);
List<string> localInstanceNames = new List<string>(instances64Bit);
foreach (var item in instances32Bit)
{
if (!localInstanceNames.Contains(item)) localInstanceNames.Add(item);
}
//localInstanceNames = localInstanceNames.Union(instances32Bit).ToList();
return localInstanceNames;
}
GetDataSources() may help you, have you tried it?
SqlDataSourceEnumerator.GetDataSources Method
Currently SqlDataSourceEnumerator isn't available in .NetCore or .Net5 either and
whilst not a direct replacement for SqlDataSourceEnumerator you could try a Udp solution.
This repo is targetted at .Net5, but the code should work just fine on .NetCore flavours.
https://github.com/mrsquish/SqlBrowserClient

What is the EzAPI equivalent for using an OLE DB Source command from variable?

tl;dr
What is the EzAPI code to use an OLE DB Source with data access mode of "SQL command from variable" and assign a variable?
Preamble
Once a month, we need to refresh our public test site with subsets of production data. We have determined that for our needs, an SSIS solution provides the best fit for accomplishing this task.
My goal is to systematically build a large number (100+) of "replication" packages. EzAPI is a friendly wrapper to the SSIS object model and it seems like a great way to save mouse-clicks.
I would like for my packages to look like
Variable - "tableName"; [Schema].[TableName]
Variable - "sourceQuery"; SELECT * FROM [Schema].[TableName]
DataFlow - "Replicate Schema_TableName"
OLE DB Source - "Src Schema_TableName"; Data Access Mode: SQL command from variable; Variable name: User::sourceQuery
OLE DB Destination - "Dest Schema_TableName"; Table or view name variable- fast load; Variable name - User::tableName
Code
This is the code for my table to table replication package.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.SSIS.EzAPI;
using Microsoft.SqlServer.Dts.Runtime;
namespace EzApiDemo
{
public class TableToTable : EzSrcDestPackage<EzOleDbSource, EzSqlOleDbCM, EzOleDbDestination, EzSqlOleDbCM>
{
public TableToTable(Package p) : base(p) { }
public static implicit operator TableToTable(Package p) { return new TableToTable(p); }
public TableToTable(string sourceServer, string database, string table, string destinationServer) : base()
{
string saniName = TableToTable.SanitizeName(table);
string sourceQuery = string.Format("SELECT D.* FROM {0} D", table);
// Define package variables
this.Variables.Add("sourceQuery", false, "User", sourceQuery);
this.Variables.Add("tableName", false, "User", table);
// Configure DataFlow properties
this.DataFlow.Name = "Replicate " + saniName;
this.DataFlow.Description = "Scripted replication";
// Connection manager configuration
this.SrcConn.SetConnectionString(sourceServer, database);
this.SrcConn.Name = "PROD";
this.SrcConn.Description = string.Empty;
this.DestConn.SetConnectionString(destinationServer, database);
this.DestConn.Name = "PREPROD";
this.DestConn.Description = string.Empty;
// Configure Dataflow's Source properties
this.Source.Name = "Src " + saniName;
this.Source.Description = string.Empty;
this.Source.SqlCommand = sourceQuery;
// Configure Dataflow's Destination properties
this.Dest.Name = "Dest " + saniName;
this.Dest.Description = string.Empty;
this.Dest.Table = table;
this.Dest.FastLoadKeepIdentity = true;
this.Dest.FastLoadKeepNulls = true;
this.Dest.DataSourceVariable = this.Variables["tableName"].QualifiedName;
this.Dest.AccessMode = AccessMode.AM_OPENROWSET_FASTLOAD_VARIABLE;
this.Dest.LinkAllInputsToOutputs();
}
/// <summary>
/// Sanitize a name so that it is valid for SSIS objects.
/// Strips []/\:=
/// Replaces . with _
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static string SanitizeName(string name)
{
string saniName = name.Replace("[", String.Empty).Replace("]", string.Empty).Replace(".", "_").Replace("/", string.Empty).Replace("\\", string.Empty).Replace(":", string.Empty);
return saniName;
}
}
}
Invocation looks like TableToTable s2 = new TableToTable(#"localhost\localsqla", "AdventureWorks", "[HumanResources].[Department]", #"localhost\localsqlb"); and that builds a package that does what I want except for using a variable in the source.
Problem
The above code supplies the access mode as SQL Query and the query is embedded in the OLE Source. The desire it to use "SQL Command From Variable" and that variable being #[User::sourceQuery] What I'm stuck on is using a variable in the source.
It should be a simple matter of assigning something like
this.Source.DataSourceVariable = this.Variables["sourceQuery"].QualifiedName;
this.Source.AccessMode = AccessMode.AM_SQLCOMMAND_VARIABLE;
This results in the correct data access mode selected but the variable isn't populated.
You can observe that I perform a similar step in the destination which does accept the variable and works "right."
this.Dest.DataSourceVariable = this.Variables["tableName"].QualifiedName;
this.Dest.AccessMode = AccessMode.AM_OPENROWSET_FASTLOAD_VARIABLE;
What doesn't work
Listing out the permutations I've attempted
this.Source.AccessMode = AccessMode.AM_OPENROWSET;
Results in Data Access Mode set to Table or View and name of table or the view is blank.
this.Source.AccessMode = AccessMode.AM_OPENROWSET_VARIABLE;
Results in Data Access Mode set to "Table or view name variable" and variable name is sourceQuery. Very close to what I want, except the access mode is not correct. Were this package to run, it'd blow up as the OpenRowSet would expect a straight table name.
this.Source.AccessMode = AccessMode.AM_SQLCOMMAND;
Results in Data Access Mode set to "SQL Command" and the SQL command text is "User::sourceQuery" That's the literal value of the variable name so it's the right thing but since the access mode is wrong, it doesn't work.
this.Source.AccessMode = AccessMode.AM_OPENROWSET_FASTLOAD;
this.Source.AccessMode = AccessMode.AM_OPENROWSET_FASTLOAD_VARIABLE;
Niether of these are correct access modes as they are for destinations (I still tried them but they didn't work as expected).
At this point, I thought I'd try to work backwards by creating a package that has the OLE DB source defined as I want it and then inspect the source object's properties.
Application app = new Application();
Package p = app.LoadPackage(#"C:\sandbox\SSISHackAndSlash\SSISHackAndSlash\EzApiPackage.dtsx", null);
TableToTable to = new TableToTable(p);
My code has set both SqlCommand and DataSourceVarible with the variable's qualified name. I've pulled down changeset 65381 and compiled that (after fixing some references to the SQL Server 2012 dlls) in hopes there might have been a fix since the Dec 30 2008 Stable build but to no avail.
Have I found a bug in their code or am I just missing something?
The current, stable build of EzAPI does not support the assignment of a variable as an OleDB Source property. I opened a similar discussion over on CodePlex and ended up learning more about how all of this works.
The root problem is the related property "SqlCommandVariable" should be set when the access mode is set to "SQL Command from Variable." Currently, the code only covers destination variables.
My resolution was to download the source code and modify the setter for the property DataSourceVariable in EzComponents.cs (line 1027 for changeset 65381)
set
{
m_comp.SetComponentProperty("OpenRowsetVariable", value);
if (AccessMode == AccessMode.AM_SQLCOMMAND_VARIABLE)
{
m_comp.SetComponentProperty("SqlCommandVariable", value);
}
ReinitializeMetaData();
}
If you're looking to get this problem resolved properly, you may upvote the Issue
Try swapping around
this.Source.DataSourceVariable = this.Variables["sourceQuery"].QualifiedName;
this.Source.AccessMode = AccessMode.AM_SQLCOMMAND_VARIABLE;
to
this.Source.AccessMode = AccessMode.AM_SQLCOMMAND_VARIABLE;
this.Source.DataSourceVariable = this.Variables["sourceQuery"].QualifiedName;
I've discovered that the order matters more than it does with a typical API.

Categories

Resources