예제 #1
0
        /// <summary>
        /// Resolves system variables, and assigns their values to local variables for later use.
        /// </summary>
        /// <param name="variableDispenser"></param>
        private void ResolveSystemVariables(ref VariableDispenser variableDispenser)
        {
            Variables variables = null;

            try
            {
                variableDispenser.LockForRead(TASK_NAME_QUALIFIED_VARIABLE_NAME);
                variableDispenser.LockForRead(PACKAGE_NAME_QUALIFIED_VARIABLE_NAME);

                variableDispenser.GetVariables(ref variables);

                if (variables.Contains(TASK_NAME_VARIABLE_NAME))
                {
                    _taskName = variables[TASK_NAME_QUALIFIED_VARIABLE_NAME].Value.ToString();
                }

                if (variables.Contains(PACKAGE_NAME_VARIABLE_NAME))
                {
                    _defaultApplicationName = variables[PACKAGE_NAME_QUALIFIED_VARIABLE_NAME].Value.ToString();
                }
            }
            catch (Exception exc)
            {
                throw new Exception(COULD_NOT_RESOLVE_SYSTEM_VARIABLE_MESSAGE, exc.InnerException);
            }
            finally
            {
                if (variables.Locked)
                {
                    variables.Unlock();
                }
            }
        }
예제 #2
0
        /// <summary>Reads a variable's value.</summary>
        /// <typeparam name="T">The type of the value.</typeparam>
        /// <param name="source">The source.</param>
        /// <param name="name">The variable name.</param>
        /// <param name="defaultValue">The default value to return if the variable does not exist.</param>
        /// <returns>The value of the variable.</returns>
        /// <remarks>
        /// The variable is locked for reading while the value is being read.
        /// </remarks>
        public static T TryGetValue <T> (this VariableDispenser source, string name, T defaultValue)
        {
            if (!source.Contains(name))
            {
                return(defaultValue);
            }

            Variables variables = null;

            try
            {
                source.LockForRead(name);
                source.GetVariables(ref variables);

                T value = defaultValue;
                if (variables.TryGetVar <T>(name, out value))
                {
                    return(value);
                }

                return(defaultValue);
            } finally
            {
                if (variables != null)
                {
                    variables.Unlock();
                }
            };
        }
        /// <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));
        }
예제 #4
0
        private void LogRowcount()
        {
            var rowCountData = new RowCountSerialize
            {
                RowCountType =
                    (RowCountSerialize.RowCountTypeEnum)
                        (ComponentMetaData.CustomPropertyCollection["RowCountType"].Value),
                RowCount = _allRowCount
            };

            if (string.IsNullOrEmpty(_rowCountSumName))
            {
                rowCountData.ColumnSum  = 0;
                rowCountData.ColumnName = "";
            }
            else
            {
                rowCountData.ColumnSum  = _allAggregate;
                rowCountData.ColumnName = _rowCountSumName;
            }
            rowCountData.RowCountComponent = ComponentMetaData.Name;
            rowCountData.RowCountObject    = (string)(ComponentMetaData.CustomPropertyCollection["RowCountObject"].Value);

            VariableDispenser.LockForRead("User::ExecutionID");
            IDTSVariables100 variables;

            VariableDispenser.GetVariables(out variables);

            if (variables.Locked)
            {
                rowCountData.ExecutionID = (Int64)variables["User::ExecutionID"].Value;
                variables.Unlock();
            }

            _cmd.Parameters["@ExecutionID"].Value   = rowCountData.ExecutionID;
            _cmd.Parameters["@ComponentName"].Value = rowCountData.RowCountComponent;
            _cmd.Parameters["@ObjectName"].Value    = rowCountData.RowCountObject;
            _cmd.Parameters["@CountType"].Value     = rowCountData.RowCountTypeString;
            _cmd.Parameters["@RowCount"].Value      = rowCountData.RowCount;
            _cmd.Parameters["@ColumnSum"].Value     = rowCountData.ColumnSum;
            _cmd.Parameters["@ColumnName"].Value    = rowCountData.ColumnName;
            _cmd.ExecuteNonQuery();

            //if (_columnInfo == null || _columnInfo.Rows.Count == 0) return;
            //var cmd = new SqlCommand("[ssis].[LogColumnInfo]", _connection) { CommandType = CommandType.StoredProcedure };
            //cmd.Parameters.Add(new SqlParameter("@ExecutionID", rowCountData.ExecutionID));

            //var parameter = new SqlParameter("@InputColumnInfo", SqlDbType.Structured)
            //{
            //    TypeName = "dbo.InputColumnInfo",
            //    Value = _columnInfo
            //};
            //cmd.Parameters.Add(parameter);
            //cmd.CommandTimeout = 0;
            //cmd.ExecuteNonQuery();
        }
예제 #5
0
        public DataTable GetDataTableWithInputVar(String filePathVar, String sheetName)
        {
            IDTSVariables100 vars = null;

            VariableDispenser.LockForRead(filePathVar);
            VariableDispenser.GetVariables(out vars);
            string filePath = (String)vars[filePathVar].Value;

            vars.Unlock();

            DataTable dt = ExcelService.ReadExcel(filePath, sheetName, 1);

            return(dt);
        }
        private void ReadVariables(VariableDispenser variableDispenser)
        {
            variableDispenser.LockForRead("System::StartTime");
            variableDispenser.LockForRead("System::PackageName");
            variableDispenser.LockForRead("System::SourceName");
            variableDispenser.LockForRead("System::MachineName");
            variableDispenser.LockForRead("System::ExecutionInstanceGUID");
            variableDispenser.LockForRead("System::EventHandlerStartTime");
            variableDispenser.LockForRead("User::UID");
            bool includesError = variableDispenser.Contains("System::ErrorCode");

            if (includesError)
            {
                variableDispenser.LockForRead("System::ErrorCode");
                variableDispenser.LockForRead("System::ErrorDescription");
            }

            Variables vars = null;

            variableDispenser.GetVariables(ref vars);

            DateTime startTime = (DateTime)vars["System::StartTime"].Value;

            _packageDuration = DateTime.Now.Subtract(startTime).TotalSeconds;
            _packageName     = vars["System::PackageName"].Value.ToString();
            _taskName        = vars["System::SourceName"].Value.ToString();
            _machineName     = vars["System::MachineName"].Value.ToString();
            _executionid     = vars["System::ExecutionInstanceGUID"].Value.ToString();
            _handlerdatetime = (DateTime)vars["System::EventHandlerStartTime"].Value;
            _uid             = vars["User::UID"].Value.ToString();
            if (includesError)
            {
                _errorCode        = vars["System::ErrorCode"].Value.ToString();
                _errorDescription = vars["System::ErrorDescription"].Value.ToString();
            }

            // release the variable locks.
            vars.Unlock();

            // reset the dispenser
            variableDispenser.Reset();
        }
예제 #7
0
        /// <summary>
        /// Sets the variable value.
        /// </summary>
        /// <param name="varName">Name of the var.</param>
        /// <param name="value">The value.</param>
        /// <param name="variableDispenser">The variable dispenser.</param>
        /// <returns></returns>
        public static void SetVariableValue(string varName, object value, VariableDispenser variableDispenser)
        {
            if (String.IsNullOrEmpty(varName))
            {
                return;
            }

            if (variableDispenser.Contains(varName))
            {
                Variables vars = null;
                variableDispenser.LockForRead(varName);
                variableDispenser.GetVariables(ref vars);
                Variable var = vars.OfType <Variable>().Where(x => x.QualifiedName == varName).FirstOrDefault();
                var.Value = value;
            }
        }
예제 #8
0
        private void EndMessage()
        {
            if (_rowCount <= 0)
            {
                return;
            }
            var auditRowData = new AuditRowSerialize
            {
                AuditRowType =
                    (AuditRowSerialize.AuditRowTypeEnum)
                    ComponentMetaData.CustomPropertyCollection["AuditRowType"].Value
            };

            if (_isHardError &&
                ((auditRowData.AuditRowType == AuditRowSerialize.AuditRowTypeEnum.SoftError) || (auditRowData.AuditRowType == AuditRowSerialize.AuditRowTypeEnum.Warning)))
            {
                auditRowData.AuditRowType = AuditRowSerialize.AuditRowTypeEnum.HardError;
            }
            auditRowData.RowCount          = _rowCount;
            auditRowData.AuditRowComponent = ComponentMetaData.Name;
            auditRowData.AuditRowObject    = (string)ComponentMetaData.CustomPropertyCollection["AuditRowObject"].Value;
            auditRowData.AuditRowSchema    = _auditSchema.ToString();
            auditRowData.AuditRowData      = _auditRowDataCollection;

            VariableDispenser.LockForRead("User::ExecutionID");
            IDTSVariables100 variables;

            VariableDispenser.GetVariables(out variables);

            if (variables.Locked)
            {
                auditRowData.ExecutionID = (Int64)variables["User::ExecutionID"].Value;
                variables.Unlock();
            }

            _cmd.Parameters["@ExecutionID"].Value    = auditRowData.ExecutionID;
            _cmd.Parameters["@ComponentName"].Value  = auditRowData.AuditRowComponent;
            _cmd.Parameters["@ObjectName"].Value     = auditRowData.AuditRowObject;
            _cmd.Parameters["@AuditType"].Value      = auditRowData.AuditRowTypeString;
            _cmd.Parameters["@RowCount"].Value       = auditRowData.RowCount;
            _cmd.Parameters["@AuditRowSchema"].Value = auditRowData.AuditRowSchema;
            _cmd.Parameters["@AuditRowData"].Value   = auditRowData.AuditRowData;
            _cmd.ExecuteNonQuery();
            _rowCount = 0;
            _auditRowDataCollection.Clear();
        }
예제 #9
0
        /// <summary>Reads a variable's value.</summary>
        /// <typeparam name="T">The type of the value.</typeparam>
        /// <param name="source">The source.</param>
        /// <param name="name">The variable name.</param>
        /// <returns>The value of the variable.</returns>
        /// <exception cref="KeyNotFoundException">The variable could not be found.</exception>
        /// <remarks>
        /// The variable is locked for reading while the value is being read.
        /// </remarks>
        public static T GetValue <T> (this VariableDispenser source, string name)
        {
            source.LockForRead(name);
            Variables variables = null;

            try
            {
                source.GetVariables(ref variables);

                return(variables.GetVar <T>(name));
            } finally
            {
                if (variables != null)
                {
                    variables.Unlock();
                }
            };
        }
예제 #10
0
        /// <summary>
        /// Gets the type of the variable.
        /// </summary>
        /// <param name="varName">Name of the var.</param>
        /// <param name="variableDispenser">The variable dispenser.</param>
        /// <returns></returns>
        public static TypeCode GetVariableType(string varName, VariableDispenser variableDispenser)
        {
            if (String.IsNullOrEmpty(varName))
            {
                return(TypeCode.Empty);
            }

            TypeCode typeCode = TypeCode.Empty;

            if (variableDispenser.Contains(varName))
            {
                Variables vars = null;
                variableDispenser.LockForRead(varName);
                variableDispenser.GetVariables(ref vars);
                typeCode = vars.OfType <Variable>().Where(x => x.QualifiedName == varName).FirstOrDefault().DataType;
            }

            return(typeCode);
        }
예제 #11
0
        /// <summary>
        /// Gets the variable value.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="varName">Name of the var.</param>
        /// <param name="variableDispenser">The variable dispenser.</param>
        /// <returns></returns>
        public static T GetVariableValue <T>(string varName, VariableDispenser variableDispenser)
        {
            if (String.IsNullOrEmpty(varName))
            {
                return(default(T));
            }

            T value = default(T);

            if (variableDispenser.Contains(varName))
            {
                Variables vars = null;
                variableDispenser.LockForRead(varName);
                variableDispenser.GetVariables(ref vars);
                string obj = vars.OfType <Variable>().Where(x => x.QualifiedName == varName).FirstOrDefault().Value.ToString();
                value = (T)System.ComponentModel.TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(obj);
            }

            return(value);
        }
예제 #12
0
        /// <summary>Gets a variable's definition.</summary>
        /// <param name="source">The source.</param>
        /// <param name="name">The variable name.</param>
        /// <returns>The variable, if it exists or <see langword="null"/> otherwise.</returns>
        /// <remarks>
        /// The variable is locked for reading while the value is read.
        /// </remarks>
        public static Variable TryGetInfo(this VariableDispenser source, string name)
        {
            if (!source.Contains(name))
            {
                return(null);
            }

            source.LockForRead(name);
            Variables variables = null;

            try
            {
                source.GetVariables(ref variables);

                return(variables[name]);
            } finally
            {
                if (variables != null)
                {
                    variables.Unlock();
                }
            };
        }
예제 #13
0
 private string _CheckVarName(string var_name, VariableDispenser variableDispenser)
 {
     try
     {
         if (!var_name.StartsWith("@["))
         {
             return(var_name);
         }
         else
         {
             string tmp_var_name = var_name.Replace("@[", "").Replace("]", "");
             if (variableDispenser.Contains(tmp_var_name))
             {
                 Variables result_variables = null;
                 variableDispenser.LockForRead(tmp_var_name);
                 variableDispenser.GetVariables(ref result_variables);
                 if (result_variables.Contains(tmp_var_name))
                 {
                     return((string)result_variables[tmp_var_name].Value);
                 }
                 else
                 {
                     return(var_name);
                 }
             }
             else
             {
                 return(var_name);
             }
         }
     }
     catch (Exception ex)
     {
         return(ex.Message + " - " + ex.StackTrace);
     }
 }
        /// <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);
            }
        }
        //public override void AcquireConnections(object transaction)
        //{
        //    IDTSRuntimeConnection100 item;
        //    object obj;
        //    bool flag, flag1, flag2, flag3;
        //    try
        //    {
        //        item = base.ComponentMetaData.RuntimeConnectionCollection[CONNNAME];
        //    }
        //    catch (Exception ex)
        //    {
        //        Microsoft.SqlServer.Dts.ManagedMsg.ErrorSupport errorSupport = base.ErrorSupport;
        //        object[] objArray = new object[] { CONNNAME };
        //        errorSupport.FireErrorWithArgs(-1071611878, out flag1, objArray);
        //        throw new PipelineComponentHResultException(-1071611878);
        //    }
        //    IDTSConnectionManager100 connectionManager = item.ConnectionManager;
        //    if (connectionManager == null)
        //    {
        //        Microsoft.SqlServer.Dts.ManagedMsg.ErrorSupport errorSupport1 = base.ErrorSupport;
        //        object[] objArray1 = new object[] { CONNNAME };
        //        errorSupport1.FireErrorWithArgs(-1071611851, out flag2, objArray1);
        //        throw new PipelineComponentHResultException(-1071611851);
        //    }
        //    try
        //    {
        //        obj = connectionManager.AcquireConnection(transaction);
        //    }
        //    catch (Exception ex2)
        //    {
        //        Exception ex1 = ex2;
        //        var errorSupport2 = base.ErrorSupport;
        //        object[] connectionManagerId = new object[] { item.ConnectionManagerID, ex1.Message };
        //        errorSupport2.FireErrorWithArgs(-1071610798, out flag3, connectionManagerId);
        //        throw new PipelineComponentHResultException(ex1.Message, -1071610798);
        //    }
        //    var httpConnection = obj as HttpClientConnection100;

        //    //base.AcquireConnections(transaction);
        //}

        public override void PreExecute()
        {
            IDTSInput100 input = ComponentMetaData.InputCollection[0];

            bufferIdxs       = new int[input.InputColumnCollection.Count];
            columnDictionary = new BufferNameMap();

            for (int x = 0; x < input.InputColumnCollection.Count; x++)
            {
                IDTSInputColumn100 column = input.InputColumnCollection[x];
                bufferIdxs[x] = BufferManager.FindColumnByLineageID(input.Buffer, column.LineageID);
                columnDictionary.Add(column.Name, bufferIdxs[x]);
            }



            //base.PreExecute();
            IDTSVariables100 variables = null;

            VariableDispenser.LockForRead(ADMINKEY);
            VariableDispenser.LockForRead(APPID);
            VariableDispenser.LockForRead(ZUMONAME);
            VariableDispenser.GetVariables(out variables);
            object adminKeyObj = variables[0].Value;
            object appIdObj    = variables[1].Value;
            object zumoNameObj = variables[2].Value;

            this.adminKey = adminKeyObj.ToString();
            this.appId    = appIdObj.ToString();
            this.zumoName = zumoNameObj.ToString();

            //this.dataTable = new DataTable()
            //{
            //    Locale = CultureInfo.InvariantCulture
            //};
            //IDTSInput100 dTSInput = base.ComponentMetaData.InputCollection[0];
            //IDTSExternalMetadataColumnCollection100 externalColumnCollection = dTSInput.ExternalMetadataColumnCollection;
            //IDTSInputColumnCollection100 inputColumnCollection = dTSInput.InputColumnCollection;
            //int count = inputColumnCollection.Count;
            //this.tableColumns = new DataColumn[count];
            //IDTSExternalMetadataColumn100[] externalMetadataColumnArray = new IDTSExternalMetadataColumn100[count];
            //this.bufferIdxs = new int[count];
            //for (int i = 0; i < count; i++)
            //{
            //    IDTSInputColumn100 inputColumn = inputColumnCollection[i];
            //    IDTSExternalMetadataColumn100 externalMetadataColumn = externalColumnCollection.FindObjectByID(inputColumn.ExternalMetadataColumnID);
            //    externalMetadataColumnArray[i] = externalMetadataColumn;
            //    DataType dataType = inputColumn.DataType;
            //    bool flag5 = false;
            //    dataType = PipelineComponent.ConvertBufferDataTypeToFitManaged(dataType, ref flag5);
            //    Type dataRecordType = PipelineComponent.BufferTypeToDataRecordType(dataType);
            //    this.tableColumns[i] = new DataColumn(externalMetadataColumn.Name, dataRecordType);
            //    int lineageId = inputColumn.LineageID;
            //    try
            //    {
            //        this.bufferIdxs[i] = base.BufferManager.FindColumnByLineageID(dTSInput.Buffer, lineageId);
            //    }
            //    catch (Exception ex)
            //    {
            //        Microsoft.SqlServer.Dts.ManagedMsg.ErrorSupport errorSupport2 = base.ErrorSupport;
            //        object[] name = new object[] { lineageId, externalMetadataColumn.Name };
            //        errorSupport2.FireErrorWithArgs(-1071610795, out flag4, name);
            //        throw new PipelineComponentHResultException(-1071610795);
            //    }
            //}
            //this.dataTable.Columns.AddRange(this.tableColumns);

            IDTSCustomProperty100 item = base.ComponentMetaData.CustomPropertyCollection["TableName"];
            string str;

            if (item.Value == null)
            {
                str = null;
            }
            else
            {
                str = item.Value.ToString().Trim();
            }
            this.tableName = str;
            switch (this.tableName)
            {
            case "charges":
                chargesServiceList = GetAllCharges();
                ComponentMetaData.FireInformation(0, ComponentMetaData.Name, string.Format("Got {0} charges from the online service.", chargesServiceList.Count), "", 0, ref pbCancel);
                chargesToSave = new List <Charge>();
                break;

            case "holds":
                holdsServiceList = GetAllHolds();
                ComponentMetaData.FireInformation(0, ComponentMetaData.Name, string.Format("Got {0} holds from the online service.", holdsServiceList.Count), "", 0, ref pbCancel);
                holdsToSave = new List <Hold>();
                break;

            case "inmates":
            default:
                try
                {
                    inmatesServiceList = GetAllInmates();
                }
                catch (Exception)
                {
                    RetryGetAllInmates();
                }
                ComponentMetaData.FireInformation(0, ComponentMetaData.Name, string.Format("Got {0} inmates from the online service.", inmatesServiceList.Count), "", 0, ref pbCancel);
                inmatesToSave = new List <Inmate>();
                break;
            }
        }
예제 #16
0
        /// <summary>
        /// Executes tasks. Does the actual sleep
        /// </summary>
        /// <param name="connections"></param>
        /// <param name="variableDispenser"></param>
        /// <param name="componentEvents"></param>
        /// <param name="log"></param>
        /// <param name="transaction"></param>
        /// <returns></returns>
        public override DTSExecResult Execute(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log, object transaction)
        {
            DTSExecResult chk = Validate(connections, variableDispenser, componentEvents, log);

            if (chk == DTSExecResult.Failure)
            {
                return(chk);
            }

            XElement variablesElement = new XElement(RootElementName);

            Variables vars = null;

            try
            {
                //Lock XmlVariable for writing
                variableDispenser.LockForWrite(XmlVariable);

                //Lock all export variables for reading
                foreach (string variable in _exportVariables)
                {
                    variableDispenser.LockForRead(variable);
                }

                variableDispenser.GetVariables(ref vars);
                if (vars != null && vars.Locked == false)
                {
                    componentEvents.FireError(0, Resources.VariablesToXmlTaskName, Resources.ErrorLockingVariables, string.Empty, 0);
                    return(DTSExecResult.Failure);
                }
                else
                {
                    //build the export exml
                    foreach (string var in _exportVariables)
                    {
                        Variable v          = vars[var];
                        XElement varElement = new XElement(_variableElementName);
                        varElement.Add(new XAttribute("name", v.QualifiedName));

                        if (ExportDataType)
                        {
                            varElement.Add(new XAttribute("dataType", v.DataType));
                        }

                        if (v.Value == null)
                        {
                            varElement.Add(new XAttribute("isNull", true));
                        }
                        else
                        {
                            Type ot = v.Value.GetType();
                            if (ExportValueDataType)
                            {
                                varElement.Add(new XAttribute("valueDataType", ot.FullName));
                            }

                            switch (v.DataType)
                            {
                            case TypeCode.DateTime:
                                varElement.SetValue(((DateTime)v.Value).ToString(DateTimeFormatInfo.InvariantInfo.SortableDateTimePattern));
                                break;

                            case TypeCode.DBNull:
                                varElement.Add(new XAttribute("isDBNull", true));
                                break;

                            case TypeCode.Empty:
                                varElement.Add(new XAttribute("isEmpty", true));
                                break;

                            case TypeCode.Object:
                                object o = v.Value;
                                if (ot == typeof(TimeSpan))
                                {
                                    varElement.SetValue(Convert.ToString(o, CultureInfo.InvariantCulture));
                                }
                                else if (ot.IsEnum)
                                {
                                    varElement.SetValue(Enum.GetName(ot, o));
                                }
                                else if (ExportBinaryData)
                                {
                                    //TODO: Implement other data types
                                    varElement.Add(new XAttribute("notImplementedDataType", true));
                                }
                                else
                                {
                                    varElement.Add(new XAttribute("binaryDataNotExported", true));
                                    varElement.SetValue(ot.FullName);
                                }

                                break;

                            default:
                                string s = Convert.ToString(v.Value, CultureInfo.InvariantCulture);
                                varElement.SetValue(s);
                                break;
                            }
                        }

                        if (ExportVariablePath)
                        {
                            varElement.Add(new XAttribute("path", v.GetPackagePath()));
                        }
                        if (ExportDescription && v.Description != string.Empty)
                        {
                            varElement.Add(new XAttribute("description", v.Description));
                        }

                        variablesElement.Add(varElement);
                    }

                    Variable xmlVar = vars[XmlVariable];
                    xmlVar.Value = variablesElement.ToString(XmlSaveOptions);
                }
            }
            finally
            {
                if (vars != null && vars.Locked)
                {
                    vars.Unlock();
                }
            }


            return(base.Execute(connections, variableDispenser, componentEvents, log, transaction));
        }
예제 #17
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));
        }