/// <summary>
        /// This method is called at runtime, and does all the "work".
        /// </summary>
        public override DTSExecResult Execute(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log, object transaction)
        {
            _localname = Localname();

            if (ReportType == "Dataset Report")
            {
                Variables vars  = null;
                var       oleda = new System.Data.OleDb.OleDbDataAdapter();
                var       dt    = new DataTable(Datasetname);
                variableDispenser.LockForRead(Recordset);
                variableDispenser.GetVariables(ref vars);
                componentEvents.FireInformation(0, "ReportGenerator", "Filename: " + _localname, string.Empty, 0, ref _refire);
                try
                {
                    //var rv = new ReportViewer {ProcessingMode = ProcessingMode.Local};
                    var val = vars[Recordset].Value;
                    oleda.Fill(dt, val);
                    componentEvents.FireInformation(0, "ReportGenerator", "Starts report generation with " + dt.Rows.Count + " rows", string.Empty, 0, ref _refire);
                    Run(Reportname, Datasetname, dt, _localname);
                    componentEvents.FireInformation(0, "ReportGenerator", "The report was created.", string.Empty, 0, ref _refire);

                    //Warning: debugmode is a user defined option.
                    if (DebugMode)
                    {
                        componentEvents.FireInformation(0, "ReportGenerator", "Satrts local report generation", string.Empty, 0, ref _refire);
                        var localReport = new ReportViewerUi
                        {
                            Datasetname = Datasetname,
                            Data        = dt,
                            Reportname  = Reportname
                        };
                        localReport.ShowDialog();
                    }
                }
                catch (Exception ex)
                {
                    componentEvents.FireError(0, "ReportGeneratorTask", ex.ToString(), "", 0);
                }
                finally
                {
                    if (vars.Locked)
                    {
                        vars.Unlock();
                    }
                }
            }
            else
            {
                GenerateServerReport(variableDispenser, componentEvents);
            }


            // set prefixfilename to variable
            if (!string.IsNullOrEmpty(PrefixFilename) && PrefixFilename != "Choose a Variable")
            {
                SetPrefixFilename(variableDispenser, componentEvents);
            }

            return(base.Execute(connections, variableDispenser, componentEvents, log, transaction));
        }
        private void previewReportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var item = (CatalogItem)tvReportServer.SelectedNode.Tag;

            if (item != null)
            {
                if (item.TypeName != "Report")
                {
                    return;
                }
                var localReport = new ReportViewerUi
                {
                    Reportserver         = ReportServer,
                    ReportType           = "SQL Server Report",
                    Reportname           = item.Path,
                    WindowsAuthorization = WindowsAuthorization,
                    Username             = Username,
                    Password             = Password,
                    Domain = Domain
                };
                localReport.ShowDialog();
            }
        }
        /// <summary>
        /// Generate SSRS Report
        /// </summary>
        /// <param name="variableDispenser"></param>
        /// <param name="componentEvents"></param>
        private void GenerateServerReport(VariableDispenser variableDispenser, IDTSComponentEvents componentEvents)
        {
            var       fi   = new FileInfo(Filename);
            Variables vars = null;

            // Create a new proxy to the web service
            var rs     = new ReportService2010.ReportingService2010();
            var rsExec = new ReportExecution2005.ReportExecutionService();

            // Assign the URL of the Web service
            rs.Url     = ReportServer + "/ReportService2010.asmx";
            rsExec.Url = ReportServer + "/ReportExecution2005.asmx";

            // Authenticate to the Web service using Windows credentials
            if (WindowsAuthorization)
            {
                rs.Credentials     = CredentialCache.DefaultCredentials;
                rsExec.Credentials = CredentialCache.DefaultCredentials;
            }
            else
            {
                rs.CookieContainer = new CookieContainer();
                rs.LogonUser(String.Format("{0}\\{1}", Domain, Username), Password, ReportServer);
                rsExec.CookieContainer = new CookieContainer();
                rsExec.LogonUser(String.Format("{0}\\{1}", Domain, Username), Password, ReportServer);
            }

            rs.Timeout     = TimeOut;
            rsExec.Timeout = TimeOut;

            componentEvents.FireInformation(0, "ReportGenerator", String.Format("WebService timeout is set to {0} milliseconds.", TimeOut), string.Empty, 0, ref _refire);
            componentEvents.FireInformation(0, "ReportGenerator", "Report Server:" + ReportServer, string.Empty, 0, ref _refire);

            if (Snapshot)
            {
                try
                {
                    ReportService2010.Warning[] warn;
                    rs.CreateItemHistorySnapshot(Reportname, out warn);
                    componentEvents.FireInformation(0, "ReportGenerator", "A snapshot was created.", string.Empty, 0, ref _refire);
                }
                catch (Exception ex)
                {
                    componentEvents.FireWarning(0, "ReportGeneratorTask", "A snapshot could not be created. Exception: " + ex.Message, "", 0);
                }
            }

            // Prepare Render arguments

            var renderExtensions = new RenderExtensions();
            var renderExtension  = renderExtensions.Get(fi.Extension);

            if (renderExtension == null)
            {
                throw new Exception("Not supported render type (GenerateServerReport): " + fi.Extension);
            }
            string format = renderExtension.Name;

            // fire render arguments
            componentEvents.FireInformation(0, "ReportGenerator", "Reportname: " + Reportname, string.Empty, 0, ref _refire);
            componentEvents.FireInformation(0, "ReportGenerator", "Filename: " + _localname, string.Empty, 0, ref _refire);
            componentEvents.FireInformation(0, "ReportGenerator", "Format: " + format, string.Empty, 0, ref _refire);

            try
            {
                // Prepare report parameter.
                //DataTable dt = (DataTable)ReportGenerator.DeserializeObject(_Reportparameter.ToString());
                var dt    = GetParameterDataTable(Reportparameter);
                var param = new List <ParameterValue>();

                // set paramter for server report
                //foreach (var row in dt.Rows.Cast<DataRow>().Where(row => !string.IsNullOrEmpty(row[0].ToString()) && row[0].ToString() != "Choose a Variable"))
                foreach (DataRow row in dt.Rows)
                {
                    if (!string.IsNullOrEmpty(row[0].ToString()) && row[0].ToString() != "Choose a Variable")
                    {
                        variableDispenser.LockForRead(row[0].ToString());
                        variableDispenser.GetVariables(ref vars);
                        var variableValue = vars[row[0].ToString()].Value.ToString();
                        var multiValue    = Convert.ToBoolean(row[2]) ? variableValue.Split(';') : new[] { variableValue };
                        foreach (var value in multiValue)
                        {
                            param.Add(new ReportExecution2005.ParameterValue
                            {
                                Name  = row[1].ToString(),
                                Value = value
                            });
                            componentEvents.FireInformation(0, "ReportGenerator",
                                                            row[1] + " --> " + row[0] + " --> " + value, string.Empty, 0, ref _refire);
                        }
                    }
                }

                //componentEvents.FireInformation(0, "ReportGenerator", iParams.ToString(), string.Empty, 0, ref _refire);
                // Load the selected report
                var ei = rsExec.LoadReport(Reportname, null);

                // Set the parameters
                if (param.Count > 0)
                {
                    rsExec.SetExecutionParameters(param.ToArray(), "en-EN");
                }

                // Render the report
                string[] streamIDs;
                ReportExecution2005.Warning[] warnings;
                string encoding;
                string mimeType;
                string extension;
                var    results = rsExec.Render(format, null, out extension, out encoding, out mimeType, out warnings, out streamIDs);

                var execInfo = rsExec.GetExecutionInfo();

                componentEvents.FireInformation(0, "ReportGenerator", string.Format("ExecutionDateTime: {0}", execInfo.ExecutionDateTime.ToLongDateString()), string.Empty, 0, ref _refire);
                if (!string.IsNullOrEmpty(ExecutionDateTime) && ExecutionDateTime != "Choose a Variable")
                {
                    variableDispenser.LockOneForWrite(ExecutionDateTime, ref vars);
                    if (vars[ExecutionDateTime].DataType == TypeCode.DateTime)
                    {
                        vars[ExecutionDateTime].Value = execInfo.ExecutionDateTime;
                        vars.Unlock();
                        componentEvents.FireInformation(0, "ReportGenerator", String.Format("ExecutionDateTime: {0}", execInfo.ExecutionDateTime.ToLongDateString()), string.Empty, 0, ref _refire);
                    }
                    else
                    {
                        componentEvents.FireWarning(0, "ReportGenerator", "Incorrect DataType for ExecutionDateTime", null, 0);
                    }
                }

                if (!string.IsNullOrEmpty(ExecutionId) && ExecutionId != "Choose a Variable")
                {
                    variableDispenser.LockOneForWrite(ExecutionId, ref vars);
                    if (vars[ExecutionId].DataType == TypeCode.String)
                    {
                        vars[ExecutionId].Value = String.IsNullOrEmpty(execInfo.ExecutionID) ? "" : execInfo.ExecutionID;
                        vars.Unlock();
                        componentEvents.FireInformation(0, "ReportGenerator", string.Format("ExecutionId: {0}", execInfo.ExecutionID), string.Empty, 0, ref _refire);
                    }
                    else
                    {
                        componentEvents.FireWarning(0, "ReportGenerator", "Incorrect DataType for ExecutionId", null, 0);
                    }
                }

                if (!string.IsNullOrEmpty(ExpirationDateTime) && ExpirationDateTime != "Choose a Variable")
                {
                    variableDispenser.LockOneForWrite(ExpirationDateTime, ref vars);
                    if (vars[ExpirationDateTime].DataType == TypeCode.DateTime)
                    {
                        vars[ExpirationDateTime].Value = execInfo.ExpirationDateTime;
                        vars.Unlock();
                        componentEvents.FireInformation(0, "ReportGenerator",
                                                        String.Format("ExpirationDateTime: {0}", execInfo.ExpirationDateTime.ToLongDateString()),
                                                        string.Empty, 0, ref _refire);
                    }
                    else
                    {
                        componentEvents.FireWarning(0, "ReportGenerator", "Incorrect DataType for ExpirationDateTime", null, 0);
                    }
                }

                if (!string.IsNullOrEmpty(HistoryId) && HistoryId != "Choose a Variable")
                {
                    variableDispenser.LockOneForWrite(HistoryId, ref vars);
                    if (vars[HistoryId].DataType == TypeCode.String)
                    {
                        vars[HistoryId].Value = String.IsNullOrEmpty(execInfo.HistoryID) ? "" : execInfo.HistoryID;
                        vars.Unlock();
                        componentEvents.FireInformation(0, "ReportGenerator", String.Format("HistoryId: {0}", execInfo.HistoryID), string.Empty, 0, ref _refire);
                    }
                    else
                    {
                        componentEvents.FireWarning(0, "ReportGenerator", "Incorrect DataType for HistoryId", null, 0);
                    }
                }

                if (!string.IsNullOrEmpty(NumPages) && NumPages != "Choose a Variable")
                {
                    variableDispenser.LockOneForWrite(NumPages, ref vars);
                    if (vars[NumPages].DataType == TypeCode.Int16 || vars[NumPages].DataType == TypeCode.Int32 ||
                        vars[NumPages].DataType == TypeCode.Int64)
                    {
                        vars[NumPages].Value = execInfo.NumPages;
                        vars.Unlock();
                        componentEvents.FireInformation(0, "ReportGenerator",
                                                        String.Format("NumPages: {0}", execInfo.NumPages), string.Empty, 0, ref _refire);
                    }
                    else
                    {
                        componentEvents.FireWarning(0, "ReportGenerator", "Incorrect DataType for NumPages", null, 0);
                    }
                }


                if (File.Exists(_localname))
                {
                    File.Delete(_localname);
                }

                //// Create a file stream and write the report to it
                using (var stream = File.OpenWrite(_localname))
                {
                    stream.Write(results, 0, results.Length);
                }

                componentEvents.FireInformation(0, "ReportGenerator", "Report was generated.", string.Empty, 0, ref _refire);

                // open ReportViewerUI in debugmode

                if (DebugMode)
                {
                    componentEvents.FireInformation(0, "ReportGenerator", "Show Report in Debugmode.", string.Empty, 0, ref _refire);
                    var localReport = new ReportViewerUi
                    {
                        Reportserver         = ReportServer,
                        Reportname           = Reportname,
                        WindowsAuthorization = WindowsAuthorization,
                        Username             = Username,
                        Password             = Password,
                        Domain     = Domain,
                        ReportType = ReportType
                    };

                    //set parameter for localreport
                    if (param.Count > 0)
                    {
                        var parameter = new List <ReportParameter>(); //[iParams];

                        //foreach (var row in dt.Rows.Cast<DataRow>().Where(row => !String.IsNullOrEmpty(row[0].ToString())))
                        foreach (DataRow row in dt.Rows)
                        {
                            if (!string.IsNullOrEmpty(row[0].ToString()))
                            {
                                variableDispenser.LockForRead(row[0].ToString());
                                variableDispenser.GetVariables(ref vars);
                                var varValue   = vars[row[0].ToString()].Value.ToString();
                                var multiValue = Convert.ToBoolean(row[2]) ? varValue.Split(';') : new[] { varValue };

                                foreach (var value in multiValue)
                                {
                                    var localparam = new ReportParameter {
                                        Name = row[1].ToString()
                                    };
                                    localparam.Values.Add(value);
                                    parameter.Add(localparam);
                                }
                            }
                        }

                        localReport.Reportparameter = parameter.ToArray();
                    }

                    localReport.ShowDialog();
                }
            }
            catch (Exception ex)
            {
                componentEvents.FireError(0, "ReportGenerator", ex.ToString(), "", 0);
                componentEvents.FireError(0, "ReportGenerator", fi.Extension.ToString(), "", 0);
            }
        }