Pass value to the sql of BulkDelete - dapper

using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServerW3Schools()))
{
var sql = "Select * FROM CUSTOMERS WHERE CustomerID in #abc";
var affectedRows = connection.Execute(sql, new { abc = 53 });
connection.BulkDelete(connection.Query<Customer>(sql).ToList());
}
The code above cannot work. Instead of directly passing the value inside the query "connection.BulkDelete(connection.Query("Select * FROM CUSTOMERS WHERE CustomerID in (53) ").ToList());", is there any method to pass the flexible value to BulkDelete? Thanks

You are not using the affectedRows:
using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServerW3Schools()))
{
var sql = "Select * FROM CUSTOMERS WHERE CustomerID in #abc";
var affectedRows = connection.Execute<Customer>(sql, new { abc = 53 });
connection.BulkDelete(affectedRows.ToList());
}

Related

Dapper QueryAsync with two params

I'm wondering if there is a way to do something like this:
string sql = "SELECT * FROM TABLE WHERE ID = #ID AND VALUE = #VALUE";
var listTest = await _dbConnection.QueryAsync<Example>(sql, ID, VALUE);
I want to query a table with a Composite PK.
var listTest = await _dbConnection.QueryAsync<Example>(sql, new { ID, VALUE });

Dapper What is wrong?

I have this code should be working but this is throwing an exception Must declare variable scalar
public async Task<Job> GetJobByUd(Guid jobId)
{
var sql = "select * from dbo.Jobs where JobId = #jobId;";
using (DbConnection db = new SqlConnection(_connectionString))
{
var job = await db.QuerySingleOrDefaultAsync<Job>(sql, new {jobId});
return job;
}
}
Try like this, it should work.
public async Task<Job> GetJobByUd(Guid jobId)
{
var sql = "select * from dbo.Jobs where JobId = #jobId;";
using (DbConnection db = new SqlConnection(_connectionString))
{
var job = await db.QueryAsync<Job>(sql, new {jobId = jobId}).FirstOrDefault();
return job;
}
}

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/

How to return a Bool from a Where Filter using Entity Framework and Esql

I use c# and ef4.
I have a Model with an Entity with two proprieties int Id and string Title.
I need to write an ESQL query that is able to return bool TRUE if Id and Title are present in the DataSource. Please note Id is a PrimaryKey in my data storage.
Any idea how to do it?
You can do it by each code-snippets below:
1)
using (YourEntityContext context = new YourEntityContext ()) {
var queryString =
#"SELECT VALUE TOP(1) Model FROM YourEntityContext.Models
As Model WHERE Model.Id = #id AND Model.Title = #title";
ObjectQuery<Model> entityQuery = new ObjectQuery<Model>(queryString, context);
entityQuery.Parameters.Add(new ObjectParameter("id", id));
entityQuery.Parameters.Add(new ObjectParameter("title", title));
var result = entityQuery.Any();
}
2)
using (YourEntityContext context = new YourEntityContext ()) {
ObjectQuery<Model> entityQuery =
context.Models
.Where("it.Id = #id AND it.Title = #title"
, new ObjectParameter("id", id)
, new ObjectParameter("title", title)
);
var result = entityQuery.Any();
}
3)
var context = new YourEntityContext();
using (EntityConnection cn = context.Connection as EntityConnection) {
if (cn.State == System.Data.ConnectionState.Closed)
cn.Open();
using (EntityCommand cmd = new EntityCommand()) {
cmd.Connection = cn;
cmd.CommandText = #"EXISTS(
SELECT M FROM YourEntityContext.Models as M
WHERE M.Id == #id AND Model.Title = #title
)";
cmd.Parameters.AddWithValue("id", _yourId);
cmd.Parameters.AddWithValue("title", _yourTitle);
var r = (bool)cmd.ExecuteScalar();
}
}
4)
using (YourEntityContext context = new YourEntityContext ()) {
var queryString =
#"EXISTS(
SELECT M FROM YourEntityContext.Models as M
WHERE M.Id == #id AND Model.Title = #title
)";
ObjectQuery<bool> entityQuery = new ObjectQuery<bool>(queryString, context);
entityQuery.Parameters.Add(new ObjectParameter("id", id));
entityQuery.Parameters.Add(new ObjectParameter("title", title));
var result = entityQuery.Execute(MergeOption.AppendOnly).FirstOrDefault();
}
4 is the best way I suggest you. Good lock
What javad said is true, but another way is:
bool result = entities.Any(x=>x.Id == id && x.Title == title) ;
In fact because Id is primary key, DB prevent from occurrence of this more than one time .

LINQ orderby int array index value

Using LINQ I would like to sort by the passed in int arrays index.
So in the code below attribueIds is my int array. I'm using the integers in that array for the where clause but I would like the results in the order that they were in while in the array.
public List BuildTable(int[] attributeIds)
{
using (var dc = new MyDC())
{
var ordering = attributeIds.ToList();
var query = from att in dc.DC.Ecs_TblAttributes
where attributeIds.Contains(att.ID)
orderby(ordering.IndexOf(att.ID))
select new Common.Models.Attribute
{
AttributeId = att.ID,
DisplayName = att.DisplayName,
AttributeName = att.Name
};
return query.ToList();
}
}
I would recommend selecting from the attributeIDs array instead. This will ensure that your items will be correctly ordered without requiring a sort.
The code should go something like this:
var query =
from id in attributeIds
let att = dc.DC.Ecs_TblAttributes.FirstOrDefault(a => a.ID == id)
where att != null
select new Common.Models.Attribute
{
AttributeId = att.ID,
DisplayName = att.DisplayName,
AttributeName = att.Name
};
Why don't you join:
public List BuildTable(int[] attributeIds)
{
using (var dc = new MyDC())
{
var query = from attID in attributeIds
join att in dc.DC.Ecs_TblAttributes
on attID equals att.ID
select new Common.Models.Attribute
{
AttributeId = attID,
DisplayName = att.DisplayName,
AttributeName = att.Name
};
return query.ToList();
}
}

Resources