/// <summary>
 /// Set filename with prefix to local variable
 /// </summary>
 /// <param name="variableDispenser"></param>
 /// <param name="componentEvents"></param>
 private void SetPrefixFilename(VariableDispenser variableDispenser, IDTSComponentEvents componentEvents)
 {
     try
     {
         if (PrefixFilename != null && PrefixFilename != "Choose a Variable")
         {
             Variables vars = null;
             variableDispenser.LockOneForWrite(PrefixFilename, ref vars);
             vars[PrefixFilename].Value = TypeConverter(_localname, vars[0].DataType);
             vars.Unlock();
             variableDispenser.Reset();
             componentEvents.FireInformation(0, "ReportGenerator", "Variable " + PrefixFilename + " set to " + _localname, string.Empty, 0, ref _refire);
         }
     }
     catch (Exception exc)
     {
         componentEvents.FireError(0, "ReportGenerator", "Task Errored: " + exc, "", -1);
     }
 }
Example #2
0
        public override object Execute(Package package, DtsContainer container)
        {
            object returnValue;

            CommandParentType commandParentType = GetCommandParentType();

            try
            {
                OnCommandStarted(new CommandStartedEventArgs(DateTime.Now, CommandName, null, null, commandParentType));

                Variables         vars      = null;
                VariableDispenser dispenser = container.VariableDispenser;

                string varName = VariableName;

                if (Operation == VariableOperation.Get)
                {
                    dispenser.LockOneForRead(varName, ref vars);
                    returnValue = vars[varName].Value;
                    vars.Unlock();
                }
                else
                {
                    // writing to the variable
                    object varValue = Value;
                    dispenser.LockOneForWrite(varName, ref vars);
                    vars[varName].Value = Convert.ChangeType(varValue, vars[varName].DataType);
                    vars.Unlock();
                    returnValue = varValue;
                }

                OnCommandCompleted(new CommandCompletedEventArgs(DateTime.Now, CommandName, null, null, string.Format("The {0} command has completed.", CommandName), commandParentType));
            }
            catch (Exception ex)
            {
                OnCommandFailed(new CommandFailedEventArgs(DateTime.Now, CommandName, null, null, ex.Message, commandParentType));

                throw;
            }

            return(returnValue);
        }
Example #3
0
        public override void ProcessInput(int inputID, PipelineBuffer buffer)
        {
            base.ProcessInput(inputID, buffer);

            while (buffer.NextRow())
            {
                var dataRow = DataTable.NewRow();
                foreach (var columnMapping in _bufferColumnMapping)
                {
                    // TODO: Update to use the correct data type methods
                    if (buffer.IsNull(columnMapping.Value))
                    {
                        dataRow[columnMapping.Key] = DBNull.Value;
                    }
                    else
                    {
                        dataRow[columnMapping.Key] = buffer[columnMapping.Value];
                    }
                }
                DataTable.Rows.Add(dataRow);
            }

            if (buffer.EndOfRowset)
            {
                var xml      = SaveDataTableToXml(DataTable);
                var property = ComponentMetaData.CustomPropertyCollection[DataTablePropertyName];
                property.Value = xml;

                string variableName = ComponentMetaData.CustomPropertyCollection[VariablePropertyName].Value.ToString();
                if (!string.IsNullOrEmpty(variableName))
                {
                    IDTSVariables variables = null;
                    VariableDispenser.LockOneForWrite(variableName, ref variables);
                    variables[variableName].Value = xml;
                    variables.Unlock();
                }
            }
        }
        /// <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);
            }
        }
        /// <summary>
        /// Validates the Task
        /// </summary>
        /// <param name="connections"></param>
        /// <param name="variableDispenser"></param>
        /// <param name="componentEvents"></param>
        /// <param name="log"></param>
        /// <returns></returns>
        public override DTSExecResult Validate(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log)
        {
            Debug.Print("Validation Started");
            string xmlVariableQualifiedName = string.Empty;

            //Check XmlVariables
            if (string.IsNullOrEmpty(_xmlVariable))
            {
                componentEvents.FireError(0, Resources.VariablesToXmlTaskName, Resources.ErrorXmlVariableEmpty, string.Empty, 0);
                return(DTSExecResult.Failure);
            }
            else if (!variableDispenser.Contains(_xmlVariable)) //Check Variable exists
            {
                componentEvents.FireError(0, Resources.VariablesToXmlTaskName, string.Format(Resources.ErrorXmlVariableNotExists, _xmlVariable), string.Empty, 0);
                return(DTSExecResult.Failure);
            }
            else
            {
                Variables vars = null;
                try
                {
                    variableDispenser.Reset();
                    variableDispenser.LockOneForWrite(_xmlVariable, ref vars);
                    if (vars == null || vars.Locked == false)   //Check if wariable is writable
                    {
                        componentEvents.FireError(0, Resources.VariablesToXmlTaskName, string.Format(Resources.ErrorLockingXmlVariable, _xmlVariable), string.Empty, 0);
                        return(DTSExecResult.Failure);
                    }
                    else
                    {
                        Variable v        = vars[0];
                        TypeCode dataType = v.DataType;
                        xmlVariableQualifiedName = v.QualifiedName;

                        if (v.Namespace != "User")  //Check namespace. Vaiabe should be writable in the user name space
                        {
                            componentEvents.FireError(0, Resources.VariablesToXmlTaskName, Resources.ErrorXmlVariableNotUser, string.Empty, 0);
                            return(DTSExecResult.Failure);
                        }

                        if (v.DataType != TypeCode.String && v.DataType != TypeCode.Object) //Variable has to be string or object data type to be able to store XML
                        {
                            componentEvents.FireError(0, Resources.VariablesToXmlTaskName, Resources.ErrorXmlVaraibleNotString, string.Empty, 0);
                            return(DTSExecResult.Failure);
                        }

                        if (v.EvaluateAsExpression == true) //Variable cannot be expression to be writable
                        {
                            componentEvents.FireError(0, Resources.VariablesToXmlTaskName, Resources.ErrorXmlVariableCannotHaveExpression, string.Empty, 0);
                            return(DTSExecResult.Failure);
                        }
                    }
                }
                finally
                {
                    if (vars != null && vars.Locked)
                    {
                        vars.Unlock();
                    }
                }
            }


            //Check VariableElementName
            if (string.IsNullOrEmpty(_variableElementName)) //Variable element has to be specified
            {
                componentEvents.FireError(0, Resources.VariablesToXmlTaskName, Resources.ErrorVariableElementEmpty, string.Empty, 0);
                return(DTSExecResult.Failure);
            }
            else
            {
                try
                {
                    XElement element = new XElement(_variableElementName);  //Check the VariableElementName is proper name for XmlElement
                }
                catch
                {
                    componentEvents.FireError(0, Resources.VariablesToXmlTaskName, string.Format(Resources.ErrorNotValidElementName, _rootElementName), string.Empty, 0);
                    return(DTSExecResult.Failure);
                }
            }

            //Check RootElementName
            if (string.IsNullOrEmpty(_rootElementName)) //Che that RootElementName is specified
            {
                componentEvents.FireError(0, Resources.VariablesToXmlTaskName, Resources.ErrorRootXmlElementCannotBeEmpty, string.Empty, 0);
                return(DTSExecResult.Failure);
            }
            else
            {
                try
                {
                    XElement element = new XElement(_rootElementName);  //Check that RootElementName is valid XmlElement name
                }
                catch
                {
                    componentEvents.FireError(0, Resources.VariablesToXmlTaskName, string.Format(Resources.ErrorNotValidElementName, _rootElementName), string.Empty, 0);
                    return(DTSExecResult.Failure);
                }
            }

            //Check ExportVaraibles
            if (_exportVariables.Count > 0)
            {
                Variables vars = null;
                try
                {
                    variableDispenser.Reset();
                    foreach (string var in _exportVariables)
                    {
                        if (!variableDispenser.Contains(var))   //Check that all variables to be exported exists
                        {
                            componentEvents.FireError(0, Resources.VariablesToXmlTaskName, Resources.ErrorInvalidVariables, string.Empty, 0);
                            return(DTSExecResult.Failure);
                        }
                        variableDispenser.LockForRead(var);
                    }
                    variableDispenser.GetVariables(ref vars);
                    if (vars == null || vars.Locked == false)   //Check that all varaibles to be exported are readable
                    {
                        componentEvents.FireError(0, Resources.VariablesToXmlTaskName, Resources.ErrorLockingReadVariables, string.Empty, 0);
                        return(DTSExecResult.Failure);
                    }
                    else
                    {
                        foreach (Variable v in vars)
                        {
                            if (v.QualifiedName == xmlVariableQualifiedName)    //Check that XmlVariable is not present int he Export Variable list. (Cannot export and write to the same variable)
                            {
                                componentEvents.FireError(0, Resources.VariablesToXmlTaskName, Resources.ErrorXmlVariableCannotBeExported, string.Empty, 0);
                            }
                        }
                    }
                }
                finally
                {
                    if (vars != null && vars.Locked)
                    {
                        vars.Unlock();
                    }
                    variableDispenser.Reset();
                }
            }

            Debug.Print("Validation Finished Successfully");
            return(base.Validate(connections, variableDispenser, componentEvents, log));
        }