Scheduling SSRS Reports in asp.net web application

Scheduling SSRS Reports from asp.net application:

Creating the Web Service Proxy:

To add a proxy class to your project using Wsdl.exe

From a command prompt, use Wsdl.exe to create a proxy class, specifying (at a minimum) the URL to the Report Server Web service. For example, the following command prompt statement specifies a URL for the management endpoint of the Report Server Web service:

Copy :  wsdl /language:CS /n:"Microsoft.SqlServer.ReportingServices2010" http://<Server Name>/reportserver/reportexecution2005.asmx?wsdl

Add Proxy Class to your Project: add this class file to your project which common project in the project. Access this class from data Access layer.

Button clicks Event to save Schedule:

  try

            {

                    ReportSchedule reportschedule = new ReportSchedule();

                    ReportServerCredentials credentials = new ReportServerCredentials();

 

                    reportschedule.Credentials = credentials.NetworkCredentials;

                    //System.Net.CredentialCache.DefaultCredentials;

                    string eventType = "TimedSubscription";

                    string matchData = GetMatchData();

                    ExtensionSettings extSettings = GetExtensionSettings();

                    // Set the report parameter values.

                    ParameterValue[] parameters = SetReportSubScriptionParameters(strReportParams);

                    string subscriptionID = reportschedule.CreateSubscription(strReportName, extSettings, strReportDesc, eventType, matchData, parameters);

                    bool createdSubscription = objReportSchedule.CreateReportSubScription(subscriptionID, UserId, strReportName, txtReportName.Value);

                    if (createdSubscription)

                    {

                        string strReport = string.Format("{0} has been scheduleed successfully ", Convert.ToString(Request.QueryString["ReportName"]));

                        ApplicationLog.WriteInfo(strReport, "HSW_ReportViewer.btnSaveSchedule_Click", UserId);

                        Response.Write("<script language='JavaScript'>function ShowMessage() {alert('Report has been scheduled successfully.');} ID = setTimeout('ShowMessage()',0);</script>");

                        rdbtnDailyOptions.Checked = true;

                    }

            }

 

            catch (SoapException ex)

            {

                ApplicationLog.WriteError(ex.Message, "HSW_ReportViewer.btnSaveSchedule_Click");

            }

 

User defined Methods to Proceed:

GetMatchData: which we are passing to Reporting Server in Extension Settings .This function will get the start Date/End Date, Daily pattern, weekly pattern, Monthly pattern using Schedule Definition Class. Schedule Definition will api from Web services Proxy Class. Schedule Definition have variable like StartDateTime, EndDateSpecified, EndDate,Item(Pattern either daily/Weekly/Monthly).

   private string GetMatchData()

        {

            ScheduleDefinition schedule = new ScheduleDefinition();

            schedule.StartDateTime = Convert.ToDateTime(txtStartDate.Value, new CultureInfo("en-US"));

            schedule.EndDateSpecified = true;

            schedule.EndDate = Convert.ToDateTime(txtEndDate.Value, new CultureInfo("en-US"));

            if (rdbtnDailyOptions.Checked)

                schedule.Item = GetDailyPattern();

            else if (rdbtnWeekly.Checked)

                schedule.Item = GetWeeklyPattern();

            else if (rdbtnMonthly.Checked)

            {

                if (rdbtnWeekOfMonthly.Checked)

                    schedule.Item = GetMonthlyDOWRecurrence();

                else

                {

                    schedule.Item = GetMonthlyPattern();

                }

            }

 

            XmlDocument xmlDoc = GetScheduleAsXml(schedule);

            return xmlDoc.OuterXml;

 

        }

GetDailyPattern: which return DailyRecurrence. It has Days Interval

        /// Get Daily Pattern

        /// </summary>

        /// <returns></returns>

        private DailyRecurrence GetDailyPattern()

        {

 

            DailyRecurrence pattern = new DailyRecurrence();

            //if (rdbtnDaily1.Checked)

            pattern.DaysInterval = Convert.ToInt32(txtDay.Value);

 

            return pattern;

        }

GetWeeklyPattern: which return WeeklyRecurrence. It has Days Of Week, Weeks Interval,WeekIntervalSpeficied

 

        /// <summary>

        /// Get Weekly Pattern

        /// </summary>

        /// <returns></returns>

        private WeeklyRecurrence GetWeeklyPattern()

        {

            WeeklyRecurrence pattern = new WeeklyRecurrence();

            DaysOfWeekSelector days = new DaysOfWeekSelector();

            pattern.DaysOfWeek = GetDays(days, rdbtnWeeklist);

            pattern.WeeksIntervalSpecified = true;

            pattern.WeeksInterval = Convert.ToInt32(txtRepeatWeek.Value);

            return pattern;

        }

GetMonthlyPattern: which returns MonthlyRecurrence ,It has Calendar Days as days,month of Year

 

        /// <summary>

        /// GetMonthly Pattern

        /// </summary>

        /// <returns></returns>

        private MonthlyRecurrence GetMonthlyPattern()

        {

 

            MonthlyRecurrence pattern = new MonthlyRecurrence();

            pattern.Days = txtCalendarmonthly.Value;

            pattern.MonthsOfYear = SetMonths();

            return pattern;

        }

GetMonthlyDOWRecurrence:which returns MonthlyDOWRecurrence,It has WhichWeekSpecified, DaysOfWeek, MonthsOfYear, WhichWeek

        /// <summary>

        /// GetMonthlyDOWRecurrence

        /// </summary>

        /// <returns></returns>

        private MonthlyDOWRecurrence GetMonthlyDOWRecurrence()

        {

            MonthlyDOWRecurrence pattern = new MonthlyDOWRecurrence();

            pattern.WhichWeekSpecified = true;

            DaysOfWeekSelector days = new DaysOfWeekSelector();

            pattern.DaysOfWeek = GetDays(days, rdbtnMonthlyWeeks);

            pattern.MonthsOfYear = SetMonths();

            switch (Convert.ToInt32(ddlWeeks.Value))

            {

                case 1:

                    pattern.WhichWeek = WeekNumberEnum.FirstWeek; break;

                case 2:

                    pattern.WhichWeek = WeekNumberEnum.SecondWeek; break;

                case 3:

                    pattern.WhichWeek = WeekNumberEnum.ThirdWeek; break;

                case 4:

                    pattern.WhichWeek = WeekNumberEnum.FourthWeek; break;

                case 5:

                    pattern.WhichWeek = WeekNumberEnum.LastWeek; break;

            }

            return pattern;

        }

GetDays: which returns DaysOfWeekSelector.It has Week Selector.

        /// <summary>

    /// <summary>

        /// Get Days

        /// </summary>

        /// <param name="days"></param>

        /// <param name="rdbtnWeeklist"></param>

        /// <returns></returns>

        private DaysOfWeekSelector GetDays(DaysOfWeekSelector days, RadioButtonList rdbtnWeeklist)

        {

            switch (Convert.ToInt32(rdbtnWeeklist.SelectedValue))

            {

                case 0:

                    days.Sunday = true;

                    break;

                case 1:

                    days.Monday = true;

                    break;

                case 2:

                    days.Tuesday = true;

                    break;

                case 3:

                    days.Wednesday = true;

                    break;

                case 4:

                    days.Thursday = true;

                    break;

                case 5:

                    days.Friday = true;

                    break;

                case 6:

                    days.Saturday = true;

                    break;

 

            }

            return days;

        }

         /// <summary>

        /// set Months

        /// </summary>

        /// <returns></returns>

        private MonthsOfYearSelector SetMonths()

        {

            MonthsOfYearSelector monthselector = new MonthsOfYearSelector();

            monthselector.January = true;

            monthselector.February = true;

            monthselector.March = true;

            monthselector.April = true;

            monthselector.June = true;

            monthselector.July = true;

            monthselector.August = true;

            monthselector.September = true;

            monthselector.October = true;

            monthselector.November = true;

            monthselector.December = true;

            return monthselector;

        }

    }

GetScheduleAsXml: GetScheduleAsXml will convert the Schedul;e Definition in to Xml Format.

** **

private XmlDocument GetScheduleAsXml(ScheduleDefinition schedule)

        {

            MemoryStream buffer = new MemoryStream();

            XmlSerializer xmlSerializer = new XmlSerializer(typeof(ScheduleDefinition));

            xmlSerializer.Serialize(buffer, schedule);

            buffer.Seek(0, SeekOrigin.Begin);

 

            XmlDocument doc = new XmlDocument();

            doc.Load(buffer);

            // patch up WhichWeek

            XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);

            ns.AddNamespace("rs",

                    "http://schemas.microsoft.com/sqlserver/2003/12/reporting/reportingservices");

            return doc;

        }

GetExtensionSettings: GetExtensionSettings function is used to set the report Delivery Setting these are common to based on Requirement.

 

 

      private ExtensionSettings GetExtensionSettings()

        {

            ParameterValue[] extensionParams = new ParameterValue[8];

 

            ParameterValue ToMail = new ParameterValue();

            ToMail.Name = "TO";

            ToMail.Value = Email;

            extensionParams[0] = ToMail;

 

            ParameterValue replyTo = new ParameterValue();

            replyTo.Name = "ReplyTo";

            replyTo.Value = string.Empty;

            extensionParams[1] = replyTo;

 

            ParameterValue includeReport = new ParameterValue();

            includeReport.Name = "IncludeReport";

            includeReport.Value = "false";

            extensionParams[2] = includeReport;

 

            ParameterValue renderFormat = new ParameterValue();

            renderFormat.Name = "RenderFormat";

            renderFormat.Value = "excel";

            extensionParams[3] = renderFormat;

 

            ParameterValue priority = new ParameterValue();

            priority.Name = "Priority";

            priority.Value = "NORMAL";

            extensionParams[4] = priority;

 

            ParameterValue subject = new ParameterValue();

            subject.Name = "Subject";

            subject.Value = txtReportName.Value;

            extensionParams[5] = subject;

 

            ParameterValue comment = new ParameterValue();

            comment.Name = "Comment";

            comment.Value = strComments;

            extensionParams[6] = comment;

 

            ParameterValue includeLink = new ParameterValue();

            includeLink.Name = "IncludeLink";

            includeLink.Value = "true";

            extensionParams[7] = includeLink;

 

            ExtensionSettings extSettings = new ExtensionSettings();

            extSettings.ParameterValues = extensionParams;

            extSettings.Extension = "Report Server Email";

 

            return extSettings;

        }

 

 

ReportServerCredentials: create class called Serializable to pass Network Credentials

[Serializable]

    public sealed class ReportServerCredentials :

        IReportServerCredentials

    {

        string _username = string.Empty;

        string _password = string.Empty;

        string _domain = string.Empty;

 

        public WindowsIdentity ImpersonationUser

        {

            get

            {

                return null;

            }

        }

 

        public ICredentials NetworkCredentials

        {

            get

            {

                _username = ConfigurationManager.AppSettings["MyReportViewerUser"].ToString();

 

                _password = ConfigurationManager.AppSettings["MyReportViewerPassword"].ToString();

 

                _domain = ConfigurationManager.AppSettings["MyReportViewerDomain"].ToString();

 

                char[] data = _password.ToCharArray();

                Base64Decoder myDecoder = new Base64Decoder(data);

                StringBuilder sb = new StringBuilder();

 

                byte[] temp = myDecoder.GetDecoded();

                sb.Append(System.Text.UTF8Encoding.UTF8.GetChars(temp));

 

                _password = sb.ToString();

                return new NetworkCredential(_username, _password, _domain);

            }

        }

 

        public bool GetFormsCredentials(out Cookie authCookie,

                    out string userName, out string password,

                    out string authority)

        {

            authCookie = null;

            userName = null;

            password = null;

            authority = null;

 

            // Not using form credentials

            return false;

        }

    }

 

 

See Also

 

 

** **

** **

** **