Programming c# code to create a SSRS data driven subscription - sql-server

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/

Related

Salesforce updating metadata record using apex

'I am trying to update a salesforce metadata record via Apex. here is my code:
Metadata.DeployContainer mdContainer = new Metadata.DeployContainer();
for(Omni_Routing_Skillset__mdt md: omnimetadata) {
Metadata.CustomMetadata customMetadata = new Metadata.CustomMetadata();
customMetadata.fullName = md.DeveloperName; //custom metadata name
customMetadata.Label = md.MasterLabel;
Metadata.CustomMetadataValue customField1 = new Metadata.CustomMetadataValue(); //the values you're changing/updating
customField1.field = 'Omni_Routing_Skillset__mdt.Skill_Level__c'; //the custom field API Name that you're wanting to insert/update a value of
customField1.value = skillsAndValues.get(md.MasterLabel);
customMetadata.values.add(customField1);//add the changes to list of changes to be deployed
mdContainer.addMetadata(customMetadata);
System.debug('customMetadata: ' + customMetadata);
}
//MetadataDeploy callback = new MetadataDeploy();
Id jobId = Metadata.Operations.enqueueDeployment(mdContainer, null);
This kicks off the deployment but i get the following error:
**Must specify the name in the CustomMetadataType.CustomMetadata format, Current Name: Team_2_SEP, Required Delimiter: .**
I am not sure how to fix this, can anyone please advise?
Thanks!
The name would be Omni_Routing_Skillset__mdt.Team_2_SEP you're only passing in Team_2_SEP.
You can reference this method:
public static void updateExisitingMetadatRecord() {
List<Metadata_Creditional__mdt> metadatList = [SELECT Id, DeveloperName,
MasterLabel FROM Metadata_Creditional__mdt WHERE DeveloperName='MyTest'];
Metadata.CustomMetadata metadataRec = new Metadata.CustomMetadata();
metadataRec.fullName =
'Metadata_Creditional__mdt.'+metadatList[0].DeveloperName;
metadataRec.label = metadatList[0].MasterLabel;
//provide the value for the fields and add it to custom metadata instance
Metadata.CustomMetadataValue totalPurchasetoUpdate = new
Metadata.CustomMetadataValue();
totalPurchasetoUpdate.field = 'Secret_Key__c';
totalPurchasetoUpdate.value = 'Change Secreet Value';
metadataRec.values.add(totalPurchasetoUpdate);
Metadata.DeployContainer mdContainer = new Metadata.DeployContainer();
mdContainer.addMetadata(metadataRec);
Metadata.Operations.enqueueDeployment(mdContainer, null);
}

Initializing a NotificationController in DNN 7

How do you initialize a NotificationController in DNN 7.1.2?
I've tried:
var nc = new DotNetNuke.Services.Social.Notifications.NotificationController();
However this is empty and has no methods to call... Am I initializing the wrong thing?
Surely there should be something in there other than ToString, GetType, Equals and GetHashCode
I need to be able to create NotificationTypes and create Notifications.
Thanks
You can use NotificationsController.Instance.SendNotification method to send notifications.
Here is the example:
var notificationType = NotificationsController.Instance.GetNotificationType("HtmlNotification");
var portalSettings = PortalController.GetCurrentPortalSettings();
var sender = UserController.GetUserById(portalSettings.PortalId, portalSettings.AdministratorId);
var notification = new Notification {NotificationTypeID = notificationType.NotificationTypeId, Subject = subject, Body = body, IncludeDismissAction = true, SenderUserID = sender.UserID};
NotificationsController.Instance.SendNotification(notification, portalSettings.PortalId, null, new List<UserInfo> { user });
This will send notification to a specific user.
If you need to create your own Notification type use the code below as a guide, it will create a NotificationType "GroupApprovedNotification". This is from core groups module.
type = new NotificationType { Name = "GroupApprovedNotification", Description = "Group Approved Notification", DesktopModuleId = deskModuleId };
if (NotificationsController.Instance.GetNotificationType(type.Name) == null)
{
NotificationsController.Instance.CreateNotificationType(type);
}

How to unit test Soap service access from Crm 2011 Silverlight application?

In a Silverlight 5 application in Dynamics CRM 2011 I access the Organization Service of the CRM to query for entity Metadata. I wrote a service that takes an entity name and returns a list of all its fields.
How can I test this service method automatically? The main problem is how to obtain a reference to the organization service from a Silverlight app that does not run in the context of the CRM.
My Service method looks like this:
public IOrganizationService OrganizationService
{
get
{
if (_organizationService == null)
_organizationService = SilverlightUtility.GetSoapService();
return _organizationService;
}
set { _organizationService = value; }
}
public async Task<List<string>> GetAttributeNamesOfEntity(string entityName)
{
// build request
OrganizationRequest request = new OrganizationRequest
{
RequestName = "RetrieveEntity",
Parameters = new ParameterCollection
{
new XrmSoap.KeyValuePair<string, object>()
{
Key = "EntityFilters",
Value = EntityFilters.Attributes
},
new XrmSoap.KeyValuePair<string, object>()
{
Key = "RetrieveAsIfPublished",
Value = true
},
new XrmSoap.KeyValuePair<string, object>()
{
Key = "LogicalName",
Value = "avobase_tradeorder"
},
new XrmSoap.KeyValuePair<string, object>()
{
Key = "MetadataId",
Value = new Guid("00000000-0000-0000-0000-000000000000")
}
}
};
// fire request
IAsyncResult result = OrganizationService.BeginExecute(request, null, OrganizationService);
// wait for response
TaskFactory<OrganizationResponse> tf = new TaskFactory<OrganizationResponse>();
OrganizationResponse response = await tf.FromAsync(
OrganizationService.BeginExecute(request, null, null), iar => OrganizationService.EndExecute(result));
// parse response
EntityMetadata entities = (EntityMetadata)response["EntityMetadata"];
return entities.Attributes.Select(attr => attr.LogicalName).ToList();
}
Edit:
I can create and execute unit tests with Resharper and AgUnit. Thus, the problem is not how to write a unit test in general.
I have tweaked the GetSoapService from the standard Microsoft SDK to accept a fall back value. This means no codes changes are needed when debugging in visual studio and running in CRM. Anyway here it is
public static IOrganizationService GetSoapService(string FallbackValue = null)
{
Uri serviceUrl = new Uri(GetServerBaseUrl(FallbackValue)+ "/XRMServices/2011/Organization.svc/web");
BasicHttpBinding binding = new BasicHttpBinding(Uri.UriSchemeHttps == serviceUrl.Scheme
? BasicHttpSecurityMode.Transport : BasicHttpSecurityMode.TransportCredentialOnly);
binding.MaxReceivedMessageSize = int.MaxValue;
binding.MaxBufferSize = int.MaxValue;
binding.SendTimeout = TimeSpan.FromMinutes(20);
IOrganizationService ser =new OrganizationServiceClient(binding, new EndpointAddress(serviceUrl));
return ser;
}
public static string GetServerBaseUrl(string FallbackValue = null)
{
try
{
string serverUrl = (string)GetContext().Invoke("getClientUrl");
//Remove the trailing forwards slash returned by CRM Online
//So that it is always consistent with CRM On Premises
if (serverUrl.EndsWith("/"))
{
serverUrl = serverUrl.Substring(0, serverUrl.Length - 1);
}
return serverUrl;
}
catch
{
//Try the old getServerUrl
try
{
string serverUrl = (string)GetContext().Invoke("getServerUrl");
//Remove the trailing forwards slash returned by CRM Online
//So that it is always consistent with CRM On Premises
if (serverUrl.EndsWith("/"))
{
serverUrl = serverUrl.Substring(0, serverUrl.Length - 1);
}
return serverUrl;
}
catch
{
return FallbackValue;
}
}

VS 2010 WPF Google API Calender V3 Insert Events

I have created a WPF Application in VS 2010 and user the Google API V3
I am facing the issue in
var CalEvt = mCalendarService.Events.Insert(new Event()
{
Description = item.Body.Substring(0, Math.Min(30, item.Body.Length)),
Start = new EventDateTime { DateTime = item.DueDateStart.ToString("o") },
End = new EventDateTime { DateTime = item.DueDateEnd.ToString("o") },
ETag = item.ExtractItemID.ToString(),
Reminders = new Event.RemindersData() { Overrides = l, UseDefault = false }
}, item.ExtractItemID.ToString()).Execute();
I am getting exception specified value is not in valid quoted string.
For Authentication I have used the below code
var auth = new OAuth2Authenticator(provider, GetAuthorization);
BaseClientService.Initializer initializer = new BaseClientService.Initializer();
initializer.Authenticator = auth;
mCalendarService = new Google.Apis.Calendar.v3.CalendarService(initializer);

Exchange Web Services Create Meeting Request Working Example

Is there a working example anywhere of how to create a meeting request using EWS for Exchange 2007 using C#? Which properties are required? I have added a web service reference and can connect to create and send various items but keep getting the error "Set action is invalid for property." on the response messages. It never says what property is invalid
var ews = new ExchangeServiceBinding {
Credentials = new NetworkCredential("user", "pass"),
Url = "https://servername/ews/exchange.asmx",
RequestServerVersionValue = new RequestServerVersion {
Version = ExchangeVersionType.Exchange2007}
};
var startDate = new DateTime(2010, 9, 18, 16, 00, 00);
var meeting = new CalendarItemType {
IsMeeting = true,
IsMeetingSpecified = true,
Subject = "test EWS",
Body = new BodyType {Value = "test body", BodyType1 = BodyTypeType.HTML},
Start = startDate,
StartSpecified = true,
End = startDate.AddHours(1),
EndSpecified = true,
MeetingTimeZone = new TimeZoneType{
TimeZoneName = TimeZone.CurrentTimeZone.StandardName, BaseOffset = "PT0H"},
Location = "Meeting",
RequiredAttendees = new [] {
new AttendeeType{Mailbox =new EmailAddressType{
EmailAddress ="test1#domain.com",RoutingType = "SMTP"}},
new AttendeeType{Mailbox =new EmailAddressType{
EmailAddress ="test2#domain.com",RoutingType = "SMTP"}}
}
};
var request = new CreateItemType {
SendMeetingInvitations =
CalendarItemCreateOrDeleteOperationType.SendToAllAndSaveCopy,
SendMeetingInvitationsSpecified = true,
SavedItemFolderId = new TargetFolderIdType{Item = new DistinguishedFolderIdType{
Id=DistinguishedFolderIdNameType.calendar}},
Items = new NonEmptyArrayOfAllItemsType {Items = new ItemType[] {meeting}}
};
CreateItemResponseType response = ews.CreateItem(request);
var responseMessage = response.ResponseMessages.Items[0];
Microsoft provides an XML example at http://msdn.microsoft.com/en-us/library/aa494190(EXCHG.140).aspx of what the message item should look like. Just setting these properties does not seem to be enough. Can someone tell me what I'm missing or point me to some better examples or documentation?
<CreateItem
xmlns="http://schemas.microsoft.com/exchange/services/2006/messages"
SendMeetingInvitations="SendToAllAndSaveCopy" >
<SavedItemFolderId>
<t:DistinguishedFolderId Id="calendar"/>
</SavedItemFolderId>
<Items>
<t:CalendarItem>
<t:Subject>Meeting with attendee0, attendee1, attendee2</t:Subject>
<t:Body BodyType="Text">CalendarItem:TextBody</t:Body>
<t:Start>2006-06-25T10:00:00Z</t:Start>
<t:End>2006-06-25T11:00:00Z</t:End>
<t:Location>CalendarItem:Location</t:Location>
<t:RequiredAttendees>
<t:Attendee>
<t:Mailbox>
<t:EmailAddress>attendee0#example.com</t:EmailAddress>
</t:Mailbox>
</t:Attendee>
<t:Attendee>
<t:Mailbox>
<t:EmailAddress>attendee1#example.com</t:EmailAddress>
</t:Mailbox>
</t:Attendee>
</t:RequiredAttendees>
<t:OptionalAttendees>
<t:Attendee>
<t:Mailbox>
<t:EmailAddress>attendee2#example.com</t:EmailAddress>
</t:Mailbox>
</t:Attendee>
</t:OptionalAttendees>
<t:Resources>
<t:Attendee>
<t:Mailbox>
<t:EmailAddress>room0#example.com</t:EmailAddress>
</t:Mailbox>
</t:Attendee>
</t:Resources>
</t:CalendarItem>
</Items>
</CreateItem>
This is probably too late for you, but this for anyone else trying this.
The issue seems to be with providing the Is-Specified params. I deleted the IsMeetingSpecified and the request worked. Here's the revised CalendarItemType.
var meeting = new CalendarItemType
{
IsMeeting = true,
Subject = "test EWS",
Body = new BodyType { Value = "test body", BodyType1 = BodyTypeType.HTML },
Start = startDate,
StartSpecified = true,
End = startDate.AddHours(1),
EndSpecified = true,
MeetingTimeZone = new TimeZoneType
{
TimeZoneName = TimeZone.CurrentTimeZone.StandardName,
BaseOffset = "PT0H"
},
Location = "Room 1",
RequiredAttendees = new[] {
new AttendeeType
{
Mailbox =new EmailAddressType
{
EmailAddress ="test#test.com"
}
},
}
};

Resources