SQL Server backup failed for server xxxx - sql-server

I'm trying to take a backup of a local SQL Server database to my local machine through c# code and I am getting Backup failed for server .
Code as follows:
using (var con = new SqlConnection(conn))
{
const string destination = "d:\\backups"+"/";
var sqlServer = new Server(new ServerConnection(con));
con.Open();
var bkpDatabase = new Backup { Action = BackupActionType.Database, Database = name };
var bkpDevice = new BackupDeviceItem(destination + name + ".bak", DeviceType.File);
bkpDatabase.Devices.Add(bkpDevice);
bkpDatabase.Checksum = true;
bkpDatabase.ContinueAfterError = true;
bkpDatabase.Incremental = false;
bkpDatabase.Initialize = true;
// Perform the backup
bkpDatabase.SqlBackup(sqlServer);
con.Close();
}
I have used the following references :
mircrosoft.sqlserver.smo;
mircrosoft.sqlserver.smoextended;
mircrosoft.sqlserver.management.sdk.sfc;
mircrosoft.sqlserver.connectioninfo;
Inner exception :
Microsoft.SqlServer.Management.Smo.FailedOperationException was caught
HelpLink=http://go.microsoft.com/fwlink? ProdName=Microsoft+SQL+Server&ProdVer=10.50.2500.0+((KJ_PCU_Main).110617- 0026+)&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptio nText&EvtID=Backup+Server&LinkId=20476
HResult=-2146233088
Message=Backup failed for Server 'XXXXX'.
Source=Microsoft.SqlServer.SmoExtended
Operation=Backup
StackTrace:
at Microsoft.SqlServer.Management.Smo.Backup.SqlBackup(Server srv)
at DatabaseCreation.Program.BackupDatabase(String name, String conn) in c:\Users\Documents\Visual Studio 2013\Projects\Databaseinstallation\DatabaseCreation\Program.cs:line 154
InnerException: System.NullReferenceException
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=Microsoft.SqlServer.ConnectionInfo
StackTrace:
at Microsoft.SqlServer.Management.Common.ConnectionManager.get_IsOpen()
at Microsoft.SqlServer.Management.Common.ConnectionManager.Connect()
at Microsoft.SqlServer.Management.Common.ConnectionManager.PoolConnect()
at Microsoft.SqlServer.Management.Common.ConnectionManager.get_DatabaseEngineType()
at Microsoft.SqlServer.Management.Smo.Server.GetExecutionManager()
at Microsoft.SqlServer.Management.Smo.Server.get_ExecutionManager()
at Microsoft.SqlServer.Management.Smo.SqlSmoObject.get_ServerVersion()
at Microsoft.SqlServer.Management.Smo.Backup.Script(Server targetServer)
at Microsoft.SqlServer.Management.Smo.Backup.SqlBackup(Server srv)

Maybe you have to escape the \ character in your destination path:
#"d:\backups"
or
"d:\\backups"
Try the following:
using (var con = new SqlConnection(conn))
{
const string destination = "c:\\backups";
var fileName = Path.Combine(destination, String.Format("{0}.bak", name));
if (!Directory.Exists(destination))
Directory.CreateDirectory(destination);
var sqlServer = new Server(new ServerConnection(con));
var bkpDatabase = new Backup
{
Action = BackupActionType.Database,
Database = name
};
var bkpDevice = new BackupDeviceItem(fileName, DeviceType.File);
bkpDatabase.Devices.Add(bkpDevice);
bkpDatabase.Checksum = true;
bkpDatabase.ContinueAfterError = true;
bkpDatabase.Incremental = false;
bkpDatabase.Initialize = true;
bkpDatabase.SqlBackup(sqlServer);
}

Related

How to use modern authentication to execute EXO V2 PowerShell commands through program in Asp.NET Core C#

We have register an application with permission Delegated permission: Exchange.Manage, Application permission: Exchange.ManageAsApp
When try to open Runspace using that token to execute Remote EXO V2 command but with that system returns error: Connecting to remote server outlook.office365.com failed with the following error message : For more information, see the about_Remote_Troubleshooting Help topic.
We use below code to connect:
PSCredential pSCredential = new PSCredential(inputUserName, new NetworkCredential("", inputPassword).SecurePassword);
string MailboxName = pSCredential.UserName;
string scope = "https://outlook.office365.com/.default";
string ClientId = Configuration.Client_Id;
string clientSecret = Configuration.ClientSecret;
HttpClient Client = new HttpClient();
var TenantId = ((dynamic)JsonConvert.DeserializeObject(Client.GetAsync("https://login.microsoftonline.com/" + MailboxName.Split('#')[1] + "/v2.0/.well-known/openid-configuration").Result.Content.ReadAsStringAsync().Result)).authorization_endpoint.ToString().Split('/')[3];
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(ClientId)
.WithClientSecret(clientSecret)
.WithTenantId(TenantId)
.Build();
var TokenResult = app.AcquireTokenForClient(new[] { scope }).ExecuteAsync().Result;
System.Security.SecureString secureString = new System.Security.SecureString();
foreach (char c in ("bearer " + TokenResult.AccessToken))
secureString.AppendChar(c);
String WSManURIConnectionString = "https://outlook.office365.com/powershell-liveid?DelegatedOrg=" + MailboxName.Split('#')[1] + "&BasicAuthToOAuthConversion=true";
PSCredential credential = new PSCredential(MailboxName, secureString);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri(WSManURIConnectionString), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
connectionInfo.SkipCACheck = true;
connectionInfo.SkipCNCheck = true;
connectionInfo.MaximumConnectionRedirectionCount = 10;
Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(connectionInfo);
if (runspace.RunspaceStateInfo.State == RunspaceState.Opened)
{
runspace.Close();
}
runspace.Open();
// Make a Get-EXOMailbox requst using the Server Argument
Command gmGetMailbox = new Command("Get-EXOMailbox");
gmGetMailbox.Parameters.Add("ResultSize", "Unlimited");
Pipeline plPileLine = runspace.CreatePipeline();
plPileLine.Commands.Add(gmGetMailbox);
Collection<PSObject> RsResultsresults = plPileLine.Invoke();
plPileLine.Stop();
plPileLine.Dispose();

.NET Core 6 SQL Server connection without Entity Framework

I am new to .NET Core. I have defined the connection string in appsettings.json like this:
"ConnectionStrings": {
"TestBD": "Server=localhost;Database=Test;Trusted_Connection=True;MultipleActiveResultSets=true"
}
I am not using Entity Framework. I need to connect to the database using this connection string from the Program.cs file.
Any help is really appreciated. Thanks
You refer the following sample code to use ADO.NET in Asp.net 6 program.cs:
//required using Microsoft.Data.SqlClient;
app.MapGet("/movies", () =>
{
var movies = new List<Movie>();
//to get the connection string
var _config = app.Services.GetRequiredService<IConfiguration>();
var connectionstring = _config.GetConnectionString("DefaultConnection");
//build the sqlconnection and execute the sql command
using (SqlConnection conn = new SqlConnection(connectionstring))
{
conn.Open();
string commandtext = "select MovieId, Title, Genre from Movie";
SqlCommand cmd = new SqlCommand(commandtext, conn);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
var movie = new Movie()
{
MovieId = Convert.ToInt32(reader["MovieId"]),
Title = reader["Title"].ToString(),
Genre = reader["Genre"].ToString()
};
movies.Add(movie);
}
}
return movies;
});
The result like this:

Programming c# code to create a SSRS data driven subscription

I have SSRS report with parameters under SQL Reporting service 2012 standard edition. I like to export to excel and send as an attachment in the email to different receipt and receipt comes from some SQL query that means it is dynamic.
Data-driven subscription can do this but I have SQL Server 2012 Standard edition which does not support data-driven subscription and I can not upgrade, so I am looking for any code which can do the similar job like a data-driven subscription.
I found this link which has the solution to my issue.
http://jaliyaudagedara.blogspot.com/2012/10/creating-data-driven-subscription.html
when I try this code under visual studio 2015 "Class Library" project by adding service reference "http://mylocalserver:81/reportserver/ReportService2010.asmx" I am getting an error on this line of code.
ReportingService2010SoapClient rs= new ReportingService2010SoapClient();
Additional information about the error: Could not find default endpoint element that references contract 'ReportService2010.ReportingService2010Soap' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.
After spending enough time to make it work with "Class Library" project, I decided to do the code under web service project by adding the web service reference. with some trial and error finally, I got the working code here under web service project. below code works on my local machine which has Sql server 2012 enterprise edition but it gives me the same error saying "Data-driven subscriptions to reports" is not supported in this edition of Reporting Services" on my company server which has SQL server 2012 standard edition.
public void DoWork()
{
ReportingService2010 rs = new ReportingService2010();
rs.Credentials = CredentialCache.DefaultCredentials;
// rs.Url = "http://mylocalserver:81/reportserver/ReportService2010.asmx";
rs.Url = "http://companyserver/reportserver/ReportService2010.asmx";
var reportPath = "/CYTYC Reports/";
string report = $"{reportPath}AllContactCIPPointsReport";
string description = "Programmatic Data Driven Subscription \"Report Server Email\" ";
//set extension as Windows File Share
ExtensionSettings settings = new ExtensionSettings();
settings.Extension = "Report Server Email";
// Set the extension parameter values.
var extensionParams = new ParameterValueOrFieldReference[8];
// var to = new ParameterFieldReference { ParameterName = "TO", FieldAlias = "PARAMS" }; // Data-driven.
var to = new ParameterValue { Name = "TO", Value = "example#gmail.com" }; // Data-driven.
extensionParams[0] = to;
var replyTo = new ParameterValue { Name = "ReplyTo", Value = "example#gmail.com" };
extensionParams[1] = replyTo;
var includeReport = new ParameterValue { Name = "IncludeReport", Value = "False" };
extensionParams[2] = includeReport;
var renderFormat = new ParameterValue { Name = "RenderFormat", Value = "HTML4.0" };
extensionParams[3] = renderFormat;
var priority = new ParameterValue { Name = "Priority", Value = "NORMAL" };
extensionParams[4] = priority;
var subject = new ParameterValue { Name = "Subject", Value = "Subsribed Report" };
extensionParams[5] = subject;
var comment = new ParameterValue { Name = "Comment", Value = "Here is the link to your report." };
extensionParams[6] = comment;
var includeLink = new ParameterValue { Name = "IncludeLink", Value = "True" };
extensionParams[7] = includeLink;
settings.ParameterValues = extensionParams;
// Create the data source for the delivery query.
var delivery = new DataSource { Name = "" };
var dataSourceDefinition = new DataSourceDefinition
{
ConnectString = "Data Source=CYTYC-LIVE;Initial Catalog=yourdatabasename",
CredentialRetrieval = CredentialRetrievalEnum.Store,
Enabled = true,
EnabledSpecified = true,
Extension = "SQL",
ImpersonateUserSpecified = false,
UserName = "username",
Password = "password"
};
delivery.Item = dataSourceDefinition;
// Create the data set for the delivery query.
var dataSetDefinition = new DataSetDefinition
{
AccentSensitivitySpecified = false,
CaseSensitivitySpecified = false,
KanatypeSensitivitySpecified = false,
WidthSensitivitySpecified = false
};
var queryDefinition = new QueryDefinition
{
CommandText = #"Your select * from Query",
CommandType = "Text",
Timeout = 45,
TimeoutSpecified = true
};
dataSetDefinition.Query = queryDefinition;
var results = new DataSetDefinition();
var oServerInfoHeader = new ServerInfoHeader();
var oTrustedUserHeader = new TrustedUserHeader();
bool changed;
string[] paramNames;
try
{
results = rs.PrepareQuery(delivery, dataSetDefinition, out changed, out paramNames);//.PrepareQuery(oTrustedUserHeader, delivery, dataSetDefinition, out results, out changed,out paramNames);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
var dataRetrieval = new DataRetrievalPlan { DataSet = results, Item = dataSourceDefinition };
// Set the event type and match data for the delivery.
const string eventType = "TimedSubscription";
const string matchData = "<ScheduleDefinition><StartDateTime>2018-06-01T14:00:00-07:00</StartDateTime><WeeklyRecurrence><WeeksInterval>1</WeeksInterval><DaysOfWeek><Monday>True</Monday><Tuesday>True</Tuesday><Wednesday>True</Wednesday><Thursday>True</Thursday><Friday>True</Friday></DaysOfWeek></WeeklyRecurrence></ScheduleDefinition>";
//const string eventType = "SnapshotUpdated";
//const string matchData = null;
//// Set the report parameter values.
//var parameters = new ParameterValueOrFieldReference[1];
//// i am retrieving value EMAIL from database and I am passing that value as my report parameter value
//var reportparam = new ParameterFieldReference { ParameterName = "yourreportparametername", FieldAlias = "PARAMS" }; // Data-driven.
//parameters[0] = reportparam;
var parameters = new ParameterValue[1];
var reportparam = new ParameterValue {Name = "yourreportparametername", Value = "yourreportparametervalue"};
parameters[0] = reportparam;
string subscriptionId = "";
try
{
subscriptionId = rs.CreateDataDrivenSubscription(report, settings, dataRetrieval, description, eventType, matchData, parameters);
//(oTrustedUserHeader, report, settings, dataRetrieval,description, eventType, matchData, parameters,out subscriptionId);
}
catch (System.Web.Services.Protocols.SoapException ex)
{
Console.WriteLine(ex.Detail.InnerText.ToString(CultureInfo.InvariantCulture));
}
}
You don't say why you need the Data Driven subscriptions - a regular SSRS subscription can e-mail an Excel report with set or default parameters.
There aren't any third party tools that I know of that emulates the Data Driven subscriptions but there have been some users who have created their own.
If you just want to trigger a subscription based on criteria, you could just use an SSIS job to run the query to determine whether to send or not and trigger the subscription if so.
Something like Data Driven Subscriptions SSRS Standard Edition 2008
If you need something more complicated (like varying TO/CC recipients, changing parameter values...), you'll need to do a bit more programming. Here's a couple things to get started with the theory and code:
https://www.mssqltips.com/sqlservertip/4249/simulate-reporting-services-data-driven-subscriptions-on-unsupported-editions/
http://www.sqlservercentral.com/articles/Reporting+Services+(SSRS)/163119/

Facing trouble while inserting bulk data into sql

In MVC4 , i have following code in my view :
<script>
var things = [];
function fun () {
var Quran = {
"surah": things[1].surah,
"ayah": things[1].ayah,
"verse": things[1].verse
};
things.push(Quran);
for (var n = 0; n < length; n++) {
$.ajax({
contentType: 'application/json; charset=utf-8',
method: 'GET',
url: "Gateway/DB_Rola?action=1",
data: things[n],
success: function (Data) {
var mera_obj = Data.key;
document.getElementById("Param2").value = '(' + mera_obj.Response_Code + ' , ' + mera_obj.Response_Description + ')';
},
error: function () {
alert("ERROR: can't connect to Server this time");
return false; }
});
alert("done for "+(n+1));
} // loop ends
return false;
}; // function ends
and controller method is :
public ActionResult DB_Rola(thing things)
{
string connectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\PROGRAM FILES (X86)\MICROSOFT SQL SERVER\MSSQL.1\MSSQL\DATA\PEACE_QURAN.MDF;Integrated Security=True";
System.Data.SqlClient.SqlConnection connection = new SqlConnection(connectionString);
int surah = things.surah;
int ayah =things.ayah;
String verse = things.verse;
// designing parametiric_query from the parameters
string query = "insert into Ayyat_Translation_Language_old_20131209 values(null,null,#Surah,#Verse)";
SqlCommand cmd = new SqlCommand(query, connection);
connection.Open();
//setting parameters for parametric query
SqlParameter Parm1 = new SqlParameter("Surah", surah);
SqlParameter Parm2 = new SqlParameter("Ayah", ayah);
SqlParameter Parm3 = new SqlParameter("Verse", verse);
//adding parameters
cmd.Parameters.Add(Parm1);
cmd.Parameters.Add(Parm2);
cmd.Parameters.Add(Parm3);
cmd.ExecuteNonQuery();
System.IO.StreamWriter file = new System.IO.StreamWriter(#"E:\Office_Work\Peace_Quran\Peace_Quran\Files\hisaab.txt", true);
file.WriteLine(" "+things.ayah);
file.Close();
connection.Close();
return View();
}
as mentioned above in code ,there is loop in my view page that passes single object at a time which is received in above controller method .it works for small amount of data but when i send bulk .i.e. 50+ records at once, some of records are not saved in my DB. i don't know what's wrong with my DB code. please help me figure it out.

Changes to existing sqlite revert back to original

I,m working on an mobile flex application using flash Builder 4.6 and Flex 4.6, I have a SQlite db file in bin-debug folder that I copy to applicationStorageDirectory in ActionScript when the application starts.
Here is the script that setups the database it called on app initialize event:
/* Variables*/
private var file:File = File.applicationDirectory.resolvePath("db/myHealthBuddy.db");
private var local:File = File.applicationStorageDirectory.resolvePath("db/myHealthBuddy.db");
private var conn:SQLConnection;
private var model:Model = new Model();
/* db */
protected function dbInit():void
{
if(!local.exists)
{
local.createDirectory();
file.copyTo(local,true);
}
conn = new SQLConnection();
conn.addEventListener(SQLEvent.OPEN, openHandler);
conn.addEventListener(SQLErrorEvent.ERROR, errorHandler);
conn.openAsync(local);
}
private function openHandler(event:SQLEvent):void
{
trace("\ndb open");
conn.removeEventListener(SQLEvent.OPEN, openHandler);
// saving connection to Model valueObject
model.connection = conn;
// create tables if not already exists
var createTablesFile:File = File.applicationDirectory.resolvePath("db" + File.separator + "createtables.xml");
var stream:FileStream = new FileStream();
stream.open(createTablesFile, FileMode.READ);
var xml:XML = XML(stream.readUTFBytes(stream.bytesAvailable));
stream.close();
conn.begin(SQLTransactionLockType.IMMEDIATE);
for each (var statement:XML in xml.statement)
{
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = conn;
stmt.text = statement;
stmt.execute();
}
conn.commit();
navigator.firstViewData = model;
}
Is this code ok.
I need to make changes to the database e.g.(add new tables and add columns to existing tables). When I make these changes to the sqlite db they revert back but presist in the xml file which contains the tables creations SQL.

Resources