I have c# code that exports azure db to blob storage. This code works with standalone sql server and elastic pool dbs but when I try this code with Managed Instance, I am not even getting SQL server details. Is this because of security settings of Managed Instance? I am running the code in VM from which I can connect to managed instance using SSMS. Below is the line where I get null in case of managed instance. azure is IAzure. I get SQL server details using below code in case of standalone sql server and elastic pool but not in case of managed instance.
using AzureDatabaseExport.Models;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.Sql.Fluent;
using Microsoft.Azure.Management.Storage.Fluent;
using Microsoft.Extensions.Configuration;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.IO;
using System.Configuration;
using QM.ETL.DAL.Helpers;
using System.Collections;
using System.Collections.Specialized;
namespace AzureDBExport_ConsoleApp
{
public class AzureDatabaseExportService : IAzureDbService
{
IAzure azure;
ISqlServer sqlServer;
public static NameValueCollection _configSettings;
//Backup backup = new Backup();
public AzureDatabaseExportService(ICollection configSettings)
{
_configSettings = configSettings as NameValueCollection;
string subscriptionId = _configSettings[AzureConstants.SubscriptionId];
string clientId = _configSettings[AzureConstants.ClientId];
string clientSecret = _configSettings[AzureConstants.ClientSecret];
string tenantId = _configSettings[AzureConstants.TenantId];
var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(
clientId, clientSecret, tenantId,
environment: AzureEnvironment.AzureGlobalCloud);
azure = Azure.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(credentials).WithSubscription(subscriptionId);
}
private ISqlServer GetSqlServer(string sqlServerResourceGroup, string sqlServerName)
{
try
{
return azure.SqlServers.GetByResourceGroup("sqlServerResourceGroup",
"sqlServerName");
}
catch (Exception ex)
{
throw new Exception("Error getting Azure SQL server resource info. ", ex);
}
}
private IStorageAccount GetStorageAccount()
{
try
{
return azure.StorageAccounts.GetByResourceGroup(
_configSettings[AzureConstants.StorageAccountResourceGroup],
_configSettings[AzureConstants.StorageAccountName]);
}
catch (Exception ex)
{
throw new Exception("Error getting Azure storage account info. ", ex);
}
}
private ISqlDatabase GetSqlDatabase()
{
try
{
return sqlServer.Databases.Get(_configSettings[AzureConstants.SqlDatabaseName]);
}
catch (Exception ex)
{
throw new Exception("Error getting Azure Database info. ", ex);
}
}
/// <summary>
/// Exports a copy of database to blob storage
/// </summary>
/// <param name="backup"></param>
/// <returns>Returns status of export</returns>
public string ExportAzureDatabase()
{
string fileName = DateTime.Now.ToString("yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss");
sqlServer = GetSqlServer(_configSettings[AzureConstants.SqlServerResourceGroup],
_configSettings[AzureConstants.SqlServerName]);
IStorageAccount storageAccount = GetStorageAccount();
ISqlDatabase sqlDatabase = sqlServer.Databases.Get(_configSettings[AzureConstants.SqlDatabaseName]);
try
{
ISqlDatabaseImportExportResponse exportedSqlDatabase = sqlDatabase.ExportTo(
storageAccount,
_configSettings[AzureConstants.StorageContainerName],
fileName)
.WithSqlAdministratorLoginAndPassword(
_configSettings[AzureConstants.SqlAdminUsername],
_configSettings[AzureConstants.SqlAdminPassword])
.Execute();
return fileName;
}
catch (Exception ex)
{
throw new Exception("Error exporting database to blob stoage. ", ex);
}
}
}
}
sqlServerName);
sqlServerName);
I have Sql Stander edition 2014 Which is Distributor and Publisher Also. I created Subscriber on Sql Stander Edition on other Server.Subscriber pull Snapshot Replication is working proper and i can look at the data.
When i Used the 2014 Express edition the pull Subscription is not working because 2014 express edition not support SQL Server Agent.
can any one know any other option is present to call the pull subscription model in the express edition. or we cant do it.
This is Code i have used
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// createSubscriber();
//disableTheServer2Distributor();
}
public bool CreatePublication( string publisherName, string publicationName, string publicationDbName)
{
ReplicationDatabase publicationDb;
TransPublication publication;
// Create a connection to the Publisher using Windows Authentication.
ServerConnection conn;
conn = new ServerConnection(publisherName);
try
{
// Connect to the Publisher.
conn.Connect();
// Enable the AdventureWorks database for transactional publishing.
publicationDb = new ReplicationDatabase(publicationDbName, conn);
// If the database exists and is not already enabled,
// enable it for transactional publishing.
if (publicationDb.LoadProperties())
{
if (!publicationDb.EnabledTransPublishing)
{
publicationDb.EnabledTransPublishing = true;
}
// If the Log Reader Agent does not exist, create it.
if (!publicationDb.LogReaderAgentExists)
{
// Specify the Windows account under which the agent job runs.
// This account will be used for the local connection to the
// Distributor and all agent connections that use Windows Authentication.
publicationDb.LogReaderAgentProcessSecurity.Login = textBox1.Text ;
publicationDb.LogReaderAgentProcessSecurity.Password = textBox2.Text;
// Explicitly set authentication mode for the Publisher connection
// to the default value of Windows Authentication.
publicationDb.LogReaderAgentPublisherSecurity.WindowsAuthentication = true;
// Create the Log Reader Agent job.
publicationDb.CreateLogReaderAgent();
}
}
else
{
throw new ApplicationException(String.Format(
"The {0} database does not exist at {1}.",
publicationDb, publisherName));
}
// Set the required properties for the transactional publication.
publication = new TransPublication();
publication.ConnectionContext = conn;
publication.Name = publicationName;
publication.DatabaseName = publicationDbName;
// Specify a transactional publication (the default).
publication.Type = PublicationType.Snapshot;
// Activate the publication so that we can add subscriptions.
publication.Status = State.Active;
// Enable push and pull subscriptions and independent Distribition Agents.
publication.Attributes |= PublicationAttributes.AllowPull;
//publication.Attributes |= PublicationAttributes.AllowPush;
//publication.Attributes |= PublicationAttributes.IndependentAgent;
// Specify the Windows account under which the Snapshot Agent job runs.
// This account will be used for the local connection to the
// Distributor and all agent connections that use Windows Authentication.
publication.SnapshotGenerationAgentProcessSecurity.Login = textBox1.Text;
publication.SnapshotGenerationAgentProcessSecurity.Password = textBox2.Text;
// Explicitly set the security mode for the Publisher connection
// Windows Authentication (the default).
publication.SnapshotGenerationAgentPublisherSecurity.WindowsAuthentication = true;
ReplicationAgentSchedule schedule;
if (publication.LoadProperties() || publication.SnapshotAvailable)
{
// Set a weekly schedule for the filtered data snapshot.
schedule = new ReplicationAgentSchedule();
schedule.FrequencyType = ScheduleFrequencyType.Continuously;
schedule.FrequencyRecurrenceFactor = 1;
schedule.FrequencyInterval = Convert.ToInt32(0x001);
}
if (!publication.IsExistingObject)
{
// Create the transactional publication.
publication.Create();
// Create a Snapshot Agent job for the publication.
publication.CreateSnapshotAgent();
}
else
{
throw new ApplicationException(String.Format(
"The {0} publication already exists.", publicationName));
}
return true;
}
catch (Exception ex)
{
return false;
// Implement custom application error handling here.
throw new ApplicationException(String.Format(
"The publication {0} could not be created.", publicationName), ex);
}
finally
{
conn.Disconnect();
}
}
/// <summary>
///
/// </summary>
/// <param name="distributionDbName">distribution data base Name</param>
/// <param name="publisherName">Publisher Name </param>
/// <param name="publicationDbName">Publication data base name</param>
/// <param name="distributionDbPassword"> Set the password of the database</param>
/// <param name="WorkingDirectoryPath">Network location from where it can be access </param>
/// <returns></returns>
public bool ConfigurationPublishreAndDistributor(string distributionDbName , string publisherName, string publicationDbName, string distributionDbPassword,string WorkingDirectoryPath)
{
DistributionDatabase distributionDb;
ReplicationServer distributor;
DistributionPublisher publisher;
ReplicationDatabase publicationDb;
// Create a connection to the server using Windows Authentication.
ServerConnection conn = new ServerConnection(publisherName);
try
{
// Connect to the server acting as the Distributor
// and local Publisher.
conn.Connect();
// Define the distribution database at the Distributor,
// but do not create it now.
distributionDb = new DistributionDatabase(distributionDbName, conn);
distributionDb.MaxDistributionRetention = 96;
distributionDb.HistoryRetention = 120;
// Set the Distributor properties and install the Distributor.
// This also creates the specified distribution database.
distributor = new ReplicationServer(conn);
distributor.InstallDistributor(distributionDbPassword, distributionDb);
// Set the Publisher properties and install the Publisher.
publisher = new DistributionPublisher(publisherName, conn);
publisher.DistributionDatabase = distributionDb.Name;
publisher.WorkingDirectory = WorkingDirectoryPath;
publisher.PublisherSecurity.WindowsAuthentication = true;
publisher.Create();
// Enable AdventureWorks2012 as a publication database.
publicationDb = new ReplicationDatabase(publicationDbName, conn);
publicationDb.EnabledTransPublishing = true;
publicationDb.EnabledMergePublishing = true;
return true;
}
catch (Exception ex)
{
// Implement appropriate error handling here.
return false;
throw new ApplicationException("An error occured when installing distribution and publishing.", ex);
}
finally
{
conn.Disconnect();
}
}
private void CreateDistributorServer1_Click(object sender, EventArgs e)
{
if (ConfigurationPublishreAndDistributor("distribution", #"SERVER-002\SQLSERVER2014", "ReplicationDB", "Asdf1234!", #"\\SERVER-001\Replication-001"))
{
if (CreatePublication(#"SERVER-002\SQLSERVER2014", "ReplicationSnapShort", "ReplicationDB"))
{
string publisherName = #"SERVER-002\SQLSERVER2014";
string publicationName = "ReplicationSnapShort";
string publicationDbName = "ReplicationDB";
string articleName = "student";
string schemaOwner = "dbo";
TransArticle article;
// Create a connection to the Publisher.
ServerConnection conn = new ServerConnection(publisherName);
// Create a filtered transactional articles in the following steps:
// 1) Create the article with a horizontal filter clause.
// 2) Add columns to or remove columns from the article.
try
{
// Connect to the Publisher.
conn.Connect();
// Define a horizontally filtered, log-based table article.
article = new TransArticle();
article.ConnectionContext = conn;
article.Name = articleName;
article.DatabaseName = publicationDbName;
article.SourceObjectName = articleName;
article.SourceObjectOwner = schemaOwner;
article.PublicationName = publicationName;
article.Type = ArticleOptions.LogBased;
String[] articlecolumns = new String[2];
articlecolumns[0] = "studentid";
articlecolumns[1] = "name";
article.AddReplicatedColumns(articlecolumns);
//article.FilterClause = "DiscontinuedDate IS NULL";
// Ensure that we create the schema owner at the Subscriber.
article.SchemaOption |= CreationScriptOptions.Schema;
if (!article.IsExistingObject)
{
// Create the article.
article.Create();
}
else
{
throw new ApplicationException(String.Format(
"The article {0} already exists in publication {1}.",
articleName, publicationName));
}
// Create an array of column names to remove from the article.
String[] columns = new String[2];
columns[0] = "studentid";
columns[1] = "name";
// Remove the column from the article.
article.AddReplicatedColumns(columns);
// publication.StartSnapshotGenerationAgentJob();
}
catch (Exception ex)
{
// Implement appropriate error handling here.
throw new ApplicationException("The article could not be created.", ex);
}
finally
{
conn.Disconnect();
startTheAgentNow();
}
}
}
MessageBox.Show("Create the Distributor and Publisher");
}
public bool startTheAgentNow()
{
string publisherName = #"SERVER-002\SQLSERVER2014";
string publicationName = "ReplicationSnapShort";
string publicationDbName = "ReplicationDB";
TransPublication publication;
// Create a connection to the Publisher using Windows Authentication.
ServerConnection conn;
conn = new ServerConnection(publisherName);
try
{
// Connect to the Publisher.
conn.Connect();
// Set the required properties for an existing publication.
publication = new TransPublication();
publication.ConnectionContext = conn;
publication.Name = publicationName;
publication.DatabaseName = publicationDbName;
if (publication.LoadProperties())
{
// Start the Snapshot Agent job for the publication.
publication.StartSnapshotGenerationAgentJob();
}
else
{
throw new ApplicationException(String.Format(
"The {0} publication does not exist.", publicationName));
}
}
catch (Exception ex)
{
// Implement custom application error handling here.
throw new ApplicationException(String.Format(
"A snapshot could not be generated for the {0} publication."
, publicationName), ex);
}
finally
{
conn.Disconnect();
// createSubscriber();
}
return true;
}
public bool createSubscriber()
{
// Define the Publisher, publication, and databases.
string publicationName = "ReplicationSnapShort";
string publisherName = #"SERVER-002\SQLSERVER2014";
string subscriberName = #"SERVER-001\SQLSERVER2014";
string subscriptionDbName = "ReplicationDB1";
string publicationDbName = "ReplicationDB";
//Create connections to the Publisher and Subscriber.
ServerConnection subscriberConn = new ServerConnection(subscriberName);
ServerConnection publisherConn = new ServerConnection(publisherName);
// Create the objects that we need.
TransPublication publication;
TransPullSubscription subscription;
try
{
// Connect to the Publisher and Subscriber.
subscriberConn.Connect();
publisherConn.Connect();
// Ensure that the publication exists and that
// it supports pull subscriptions.
publication = new TransPublication();
publication.Name = publicationName;
publication.DatabaseName = publicationDbName;
publication.ConnectionContext = publisherConn;
if (publication.IsExistingObject)
{
if ((publication.Attributes & PublicationAttributes.AllowPull) == 0)
{
publication.Attributes |= PublicationAttributes.AllowPull;
}
// Define the pull subscription.
subscription = new TransPullSubscription();
subscription.ConnectionContext = subscriberConn;
subscription.PublisherName = publisherName;
subscription.PublicationName = publicationName;
subscription.PublicationDBName = publicationDbName;
subscription.DatabaseName = subscriptionDbName;
// Specify the Windows login credentials for the Distribution Agent job.
subscription.SynchronizationAgentProcessSecurity.Login = textBox1.Text;
subscription.SynchronizationAgentProcessSecurity.Password = textBox2.Text;
// Make sure that the agent job for the subscription is created.
subscription.CreateSyncAgentByDefault = true;
// By default, subscriptions to transactional publications are synchronized
// continuously, but in this case we only want to synchronize on demand.
subscription.AgentSchedule.FrequencyType = ScheduleFrequencyType.Continuously;
// Create the pull subscription at the Subscriber.
subscription.Create();
Boolean registered = false;
// Verify that the subscription is not already registered.
foreach (TransSubscription existing
in publication.EnumSubscriptions())
{
if (existing.SubscriberName == subscriberName
&& existing.SubscriptionDBName == subscriptionDbName)
{
registered = true;
}
}
if (!registered)
{
// Register the subscription with the Publisher.
publication.MakePullSubscriptionWellKnown(
subscriberName, subscriptionDbName,
SubscriptionSyncType.Automatic,
TransSubscriberType.ReadOnly);
}
}
else
{
// Do something here if the publication does not exist.
throw new ApplicationException(String.Format(
"The publication '{0}' does not exist on {1}.",
publicationName, publisherName));
}
}
catch (Exception ex)
{
// Implement the appropriate error handling here.
throw new ApplicationException(String.Format(
"The subscription to {0} could not be created.", publicationName), ex);
}
finally
{
subscriberConn.Disconnect();
publisherConn.Disconnect();
}
MessageBox.Show("Subscription is Created");
return true;
}
/// <summary>
/// This is the code of the
/// </summary>
public void disableTheServer2Distributor()
{
string publisherName = #"SERVER-002\SQLSERVER2014";
string publicationDbName = "ReplicationDB";
string distributorName = #"SERVER-002\SQLSERVER2014";
string distributionDbName = "distribution";
// Create connections to the Publisher and Distributor
// using Windows Authentication.
ServerConnection publisherConn = new ServerConnection(publisherName);
ServerConnection distributorConn = new ServerConnection(distributorName);
// Create the objects we need.
ReplicationServer distributor =
new ReplicationServer(distributorConn);
DistributionPublisher publisher;
DistributionDatabase distributionDb =
new DistributionDatabase(distributionDbName, distributorConn);
ReplicationDatabase publicationDb;
publicationDb = new ReplicationDatabase(publicationDbName, publisherConn);
try
{
// Connect to the Publisher and Distributor.
publisherConn.Connect();
distributorConn.Connect();
// Disable all publishing on the AdventureWorks2012 database.
if (publicationDb.LoadProperties())
{
if (publicationDb.EnabledMergePublishing)
{
publicationDb.EnabledMergePublishing = false;
}
else if (publicationDb.EnabledTransPublishing)
{
publicationDb.EnabledTransPublishing = false;
}
}
else
{
throw new ApplicationException(
String.Format("The {0} database does not exist.", publicationDbName));
}
// We cannot uninstall the Publisher if there are still Subscribers.
if (distributor.RegisteredSubscribers.Count == 0)
{
// Uninstall the Publisher, if it exists.
publisher = new DistributionPublisher(publisherName, distributorConn);
if (publisher.LoadProperties())
{
publisher.Remove(false);
}
else
{
// Do something here if the Publisher does not exist.
throw new ApplicationException(String.Format(
"{0} is not a Publisher for {1}.", publisherName, distributorName));
}
// Drop the distribution database.
if (distributionDb.LoadProperties())
{
distributionDb.Remove();
}
else
{
// Do something here if the distribition DB does not exist.
throw new ApplicationException(String.Format(
"The distribution database '{0}' does not exist on {1}.",
distributionDbName, distributorName));
}
// Uninstall the Distributor, if it exists.
if (distributor.LoadProperties())
{
// Passing a value of false means that the Publisher
// and distribution databases must already be uninstalled,
// and that no local databases be enabled for publishing.
distributor.UninstallDistributor(false);
}
else
{
//Do something here if the distributor does not exist.
throw new ApplicationException(String.Format(
"The Distributor '{0}' does not exist.", distributorName));
}
}
else
{
throw new ApplicationException("You must first delete all subscriptions.");
}
}
catch (Exception ex)
{
// Implement appropriate error handling here.
throw new ApplicationException("The Publisher and Distributor could not be uninstalled", ex);
}
finally
{
publisherConn.Disconnect();
distributorConn.Disconnect();
}
}
private void CreateDistributorServer2_Click(object sender, EventArgs e)
{
}
private void button5_Click(object sender, EventArgs e)
{
createSubscriber();
}
private void button13_Click(object sender, EventArgs e)
{
string publisherName = #"SERVER-002\SQLSERVER2014";
string publicationDbName = "ReplicationDB";
String subscriberName = #"SERVER-001\SQLSERVER2014";
String publicationName = "ReplicationSnapShort";
String subscriptionDbName = "ReplicationDB1";
// Create a connection to the Subscriber.
ServerConnection conn = new ServerConnection(subscriberName);
TransPullSubscription subscription;
try
{
// Connect to the Subscriber.
conn.Connect();
// Define subscription properties.
subscription = new TransPullSubscription();
subscription.ConnectionContext = conn;
subscription.DatabaseName = subscriptionDbName;
subscription.PublisherName = publisherName;
subscription.PublicationDBName = publicationDbName;
subscription.PublicationName = publicationName;
// If the pull subscription and the job exists, mark the subscription
// for reinitialization and start the agent job.
if (subscription.LoadProperties() && subscription.AgentJobId != null)
{
subscription.Reinitialize();
subscription.SynchronizeWithJob();
}
else
{
// Do something here if the subscription does not exist.
throw new ApplicationException(String.Format(
"A subscription to '{0}' does not exists on {1}",
publicationName, subscriberName));
}
}
catch (Exception ex)
{
// Do appropriate error handling here.
//throw new ApplicationException("The subscription could not be reinitialized.", ex);
}
finally
{
conn.Disconnect();
startTheAgentNow();
MessageBox.Show("Agents are started");
}
}
private void button9_Click(object sender, EventArgs e)
{
}
}
Above Code is Working as Expected I getting issue When I change the Subscriber to SQL
I see you are using the TransPullSubscription class and calling the SynchronizeWithJob() method to synchronize the subscription. As you found out, the SQL Server Agent is not available in SQL Server Express so this approach does not work.
However, the RMO TransSynchronizationAgent class exposes a Synchronize method which can be used to synchronize a pull subscription without an agent job. This is covered in How to: Synchronize a Pull Subscription (RMO Programming).
Get an instance of the TransSynchronizationAgent class from the
SynchronizationAgent property, and call the Synchronize method. This
method starts the agent synchronously, and control remains with the
running agent job. During synchronous execution, you can handle the
Status event while the agent is running.
I have a similar example for a Merge pull subscription found here.
Note that if you specified a value of false for CreateSyncAgentByDefault (the default) when you created the pull subscription, you also need to set additional properties before you can call Synchronize().
If you specified a value of false for CreateSyncAgentByDefault (the
default) when you created the pull subscription, you also need to
specify Distributor, DistributorSecurityMode, and optionally
DistributorLogin and DistributorPassword because the agent job related
metadata for the subscription is not available in
MSsubscription_properties.
Thanks
Brandon Williams ,
I make the changes on the code is given below
`
{
TransSynchronizationAgent agent;
// Sync BackgroundWorker
BackgroundWorker syncBackgroundWorker;
public Form1()
{
InitializeComponent();
lblSubscriptionName.Text = "[" + subscriptionDbName + "] - [" + publisherName + "] - [" + publicationDbName + "]";
lblPublicationName.Text = publicationName;
}
private void btnStart_Click(object sender, EventArgs e)
{
// Instantiate a BackgroundWorker, subscribe to its events, and call RunWorkerAsync()
syncBackgroundWorker = new BackgroundWorker();
syncBackgroundWorker.WorkerReportsProgress = true;
syncBackgroundWorker.DoWork += new DoWorkEventHandler(syncBackgroundWorker_DoWork);
syncBackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(syncBackgroundWorker_ProgressChanged);
syncBackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(syncBackgroundWorker_RunWorkerCompleted);
// Disable the start button
btnStart.Enabled = false;
// Initialize the progress bar and status textbox
pbStatus.Value = 0;
tbLastStatusMessage.Text = String.Empty;
pictureBoxStatus.Visible = true;
pictureBoxStatus.Enabled = true;
// Kick off a background operation to synchronize
syncBackgroundWorker.RunWorkerAsync();
}
// This event handler initiates the synchronization
private void syncBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
// Connect to the Subscriber and synchronize
SynchronizeMergePullSubscriptionViaRMO();
}
// Synchronize
public void SynchronizeMergePullSubscriptionViaRMO()
{
// Create a connection to the Subscriber.
ServerConnection conn = new ServerConnection(subscriberName);
// Merge pull subscription
TransPullSubscription subscription;
try
{
// Connect to the Subscriber.
conn.Connect();
// Define the pull subscription.
subscription = new TransPullSubscription();
subscription.ConnectionContext = conn;
subscription.DatabaseName = subscriptionDbName;
subscription.PublisherName = publisherName;
subscription.PublicationDBName = publicationDbName;
subscription.PublicationName = publicationName;
// If the pull subscription exists, then start the synchronization.
if (subscription.LoadProperties())
{
// Get the agent for the subscription.
agent = subscription.SynchronizationAgent;
// Set the required properties that could not be returned
// from the MSsubscription_properties table.
//agent.PublisherSecurityMode = SecurityMode.Integrated;
agent.DistributorSecurityMode = SecurityMode.Integrated;
agent.Distributor = publisherName;
// Enable verbose merge agent output to file.
agent.OutputVerboseLevel = 4;
agent.Output = "C:\\TEMP\\mergeagent.log";
// Handle the Status event
agent.Status += new AgentCore.StatusEventHandler(agent_Status);
// Synchronously start the Merge Agent for the subscription.
agent.Synchronize();
}
else
{
// Do something here if the pull subscription does not exist.
throw new ApplicationException(String.Format(
"A subscription to '{0}' does not exist on {1}",
publicationName, subscriberName));
}
}
catch (Exception ex)
{
// Implement appropriate error handling here.
throw new ApplicationException("The subscription could not be " +
"synchronized. Verify that the subscription has " +
"been defined correctly.", ex);
}
finally
{
conn.Disconnect();
}
}
// This event handler handles the Status event and reports the agent progress.
public void agent_Status(object sender, StatusEventArgs e)
{
syncBackgroundWorker.ReportProgress(Convert.ToInt32(e.PercentCompleted), e.Message.ToString());
}
// This event handler updates the form with agent progress.
private void syncBackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// Set the progress bar percent completed
pbStatus.Value = e.ProgressPercentage;
// Append the last agent message
tbLastStatusMessage.Text += e.UserState.ToString() + Environment.NewLine;
// Scroll to end
ScrollToEnd();
}
// This event handler deals with the results of the background operation.
private void syncBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true)
{
tbLastStatusMessage.Text += "Canceled!" + Environment.NewLine;
ScrollToEnd();
}
else if (e.Error != null)
{
tbLastStatusMessage.Text += "Error: " + e.Error.Message + Environment.NewLine;
ScrollToEnd();
}
else
{
tbLastStatusMessage.Text += "Done!" + Environment.NewLine;
ScrollToEnd();
}
btnStart.Enabled = true;
pictureBoxStatus.Enabled = false;
}
private void ScrollToEnd()
{
// Scroll to end
tbLastStatusMessage.SelectionStart = tbLastStatusMessage.TextLength;
tbLastStatusMessage.ScrollToCaret();
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
}`
I'm new to windows app development.How can I make sqlite database in windows phone 8 app?This link shows how to use local databse but I want sqlite databse http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202876(v=vs.105).aspx
thanks in advance....
you can download a nuget package called sqlite for windows phone.
then you can a .db file in your project or can create a new by using following code.
public static SQLiteAsyncConnection connection;
public static bool isDatabaseExisting;
public static async void ConnectToDB()
{
try
{
StorageFile storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync("DelhiMetroDB.db");
isDatabaseExisting = true;
}
catch (Exception ex)
{
isDatabaseExisting = false;
}
if (!isDatabaseExisting)
{
try
{
StorageFile databaseFile = await Package.Current.InstalledLocation.GetFileAsync("DelhiMetroDB.db");
await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder);
isDatabaseExisting = true;
}
catch (Exception ex)
{
isDatabaseExisting = false;
}
}
if (isDatabaseExisting)
{
connection = new SQLiteAsyncConnection(Path.Combine(ApplicationData.Current.LocalFolder.Path, "DelhiMetroDB.db"), true);
}
}
}
}
then you can use this variable connection to connect with database like :
var result= classname.connection.QueryAsync<objecttype>("SELECT * FROM tablename").Result;
I'm a beginner programmer. I have a database file (MyDatabase.sdf) in my windows phone mango app. What I am trying to accomplish is copy and convert the MyDatabase.sdf file as MyDatabaseBackup.txt in isolated storage and then upload it to skydrive as backup. Since skydrive doesn't support .sdf files to be uploaded some people have suggested this conversion method and have got it to work.
So I am trying to do the same but I'm unable to copy the .sdf file to .txt file in isolated storage. Here's my code...
//START BACKUP
private void Backup_Click(object sender, RoutedEventArgs e)
{
if (client == null || client.Session == null)
{
MessageBox.Show("You must sign in first.");
}
else
{
if (MessageBox.Show("Are you sure you want to backup? This will overwrite your old backup file!", "Backup?", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
UploadFile();
}
}
public void UploadFile()
{
if (skyDriveFolderID != string.Empty) //the folder must exist, it should have already been created
{
this.client.UploadCompleted
+= new EventHandler<LiveOperationCompletedEventArgs>(ISFile_UploadCompleted);
infoTextBlock.Text = "Uploading backup...";
dateTextBlock.Text = "";
using (AppDataContext appDB = new AppDataContext(AppDataContext.DBConnectionString))
{
appDB.Dispose();
}
try
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists("MyDatabase.sdf"))
{
myIsolatedStorage.CopyFile("MyDatabase.sdf", "MyDatabaseBackup.txt"); //This is where it goes to the catch statement.
}
this.client.UploadAsync(skyDriveFolderID, fileName, true, readStream , null);
}
}
catch
{
MessageBox.Show("Error accessing IsolatedStorage. Please close the app and re-open it, and then try backing up again!", "Backup Failed", MessageBoxButton.OK);
infoTextBlock.Text = "Error. Close the app and start again.";
dateTextBlock.Text = "";
}
}
}
private void ISFile_UploadCompleted(object sender, LiveOperationCompletedEventArgs args)
{
if (args.Error == null)
{
infoTextBlock.Text = "Backup complete.";
dateTextBlock.Text = "Checking for new backup...";
//get the newly created fileID's (it will update the time too, and enable restoring)
client = new LiveConnectClient(session);
client.GetCompleted += new EventHandler<LiveOperationCompletedEventArgs>(getFiles_GetCompleted);
client.GetAsync(skyDriveFolderID + "/files");
}
else
{
this.infoTextBlock.Text =
"Error uploading file: " + args.Error.ToString();
}
}
Here's how I am creating the database in my app.xaml.cs file.
// Specify the local database connection string.
string DBConnectionString = "Data Source=isostore:/MyDatabase.sdf";
// Create the database if it does not exist.
using (AppDataContext appDB = new AppDataContext(AppDataContext.DBConnectionString))
{
if (appDB.DatabaseExists() == false)
{
//Create the database
appDB.CreateDatabase();
appDB.SubmitChanges();
}
}
Some have suggested that make sure "no processes/functions/threads have the sdf file open."
I tried to that in the UploadFile() method but I am not entirely sure if I did it correctly.
Can someone please give some code help on these two issues. Thanks for the help!
First, create the local copy using File.Copy method as shown below, then upload the .txt file:
File.Copy (Path.Combine ([DbFileDir], MyDatabase.sdf), Path.Combine ([SomeLocalDir], MyDatabaseBackup.txt), true)
Note: you have to have proper access rights to the original/new local folders.
Hope this will help. Rgds,
I am using Tomcat 7, Microsoft SQL Server 2008 RC2 and JTDS driver
I am actually using C3P0 as well to try and solve this problem, but it makes no difference at all. I was using Microsoft's driver but it caused me other problems (the requested operation is not supported on forward only result sets)
I get the following error, always at the same point. I have successfully run other queries before getting to this point:
java.sql.SQLException: Invalid state, the ResultSet object is closed.
at
net.sourceforge.jtds.jdbc.JtdsResultSet.checkOpen(JtdsResultSet.java:287)
at
net.sourceforge.jtds.jdbc.JtdsResultSet.findColumn(JtdsResultSet.java:943)
at
net.sourceforge.jtds.jdbc.JtdsResultSet.getInt(JtdsResultSet.java:968)
at
com.mchange.v2.c3p0.impl.NewProxyResultSet.getInt(NewProxyResultSet.java:2573)
at com.tt.web.WebPosition.createPosition(WebPosition.java:863)
The code is as follows:
public static List getListPositions(String query) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
List list = null;
try { //execute the sql query and create the resultSet
con = DBConnection.getInstance().getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(query);
while(rs.next()) {
if(rs.isFirst()) {
list = new ArrayList();
}
WebPosition webPos = null;
webPos = new WebPosition(rs);
list.add(webPos);
}
} catch (java.sql.SQLException e) {
System.out.println("SQLException in getListPositions");
System.out.print(query);
Log.getInstance().write(query);
Log.getInstance().write(e.toString());
} catch (Exception ex) {
System.out.print(ex);
ex.printStackTrace();
Log.getInstance().write(ex.toString());
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
Log.getInstance().write(e.toString());
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
Log.getInstance().write(e.toString());
}
}
DBConnection.getInstance().returnConnection(con);
}
return list;
}
public WebPosition(ResultSet rs) {
createPosition( rs);
}
public void createPosition(ResultSet rs) {
try {
this.setCurrentDate4Excel(rs.getString("SYSDATE_4_EXCEL"));
this.setExerciseType(rs.getInt("EXERCISE_STYLE_CD"));
...
The code fails in between the above two lines.
I am at a loss to explain why the Result set would be closed in the middle of a function (i.e. it would retrieve rs.getString("SYSDATE_4_EXCEL") but then fail with the error posted at the line rs.getInt("EXERCISE_STYLE_CD"))
Does anyone have any ideas? I imagine that it is some kind of memory issue, and that the connection is automatically closed after a certain amount of data, but I am not sure how to fix this. I tried increasing the heapsize for the JVM.