Script Task Exception Handling

Hi,
Please suggest if it is possible. I have 15 tables in SQL Server and all the table has different metadata and I am migrating these tables to excel using SSIS Script task. But the problem is there is some exception occurs inside the catch block for eg. (Message
:'', hexadecimal value 0x19, is an invalid character.) but I am unable to find out exact location of SQL which table, column and rowno has the exception.
Please suggest me if it is possible to track all the details i.e. Table Name, Column Name, Row Number.

If you are using a script task, you can simply put a breakpoint in your script and debug it like any other code. Just step through and keep an eye on the locals window.
MCSE SQL Server 2012 - Please mark posts as answered where appropriate.

Similar Messages

  • Script Task : exception has been thrown by the target of an invocation

    Having a simple SSIS package that downloads a file from SharePoint using client object model.
    the task runs successfully through VS2010 IDE and SQL Agent on development workstation but fails when running through SQL Agent on the server. there are other similar SQL jobs that work fine, so the permission should not be an issue.
    the error happens so that I cannot trap it using try/catch. when editing script in VS2010, I noticed the path of SharePoint assemblies are referring to version 16 of SharePoint (2013 ?)  and I have SharePoint 2010 on server. As I have set it to run
    no any version of SharePoint (using "Specific Version = False") I expect it runs with 2010 version but it doesn't.
    I'm using SQL Server 2012 Enterprise x64.
    Thanks for help.

    Hi M.Sanati,
    Do the packages that run fine in certain jobs on the server have Script Tasks/Components? If not, the issue may be that the Visual Studio Tools for Applications (VSTA) runtime is not installed on the server:
    Microsoft Visual Studio Tools for Application x64 Runtime3.0
    Microsoft Visual Studio Tools for Application x86 Runtime3.0
    You can check it from the Programs and Features panel of Windows. If it is the case, you can install the missing VSTA Runtime from the \redist\VSTA\runtime\ folder of the SQL Server install media.
    If the issue persists, please post the complete error message of the Job history for further analysis.
    Regards,
    Mike Yin
    If you have any feedback on our support, please click
    here
    Mike Yin
    TechNet Community Support

  • SQL 2012 - DTS Script Task - Exception has been thrown by the target of an invocation

    The error is thrown while trying to access system variables from within DTS Script Task.
    String strPackageName = (string) Dts.Variables["System::PackageName"].Value;
    Same results with other variables, such as System::MachineName...
    Other "DTS" data is available, the following doesn't error out:
    String strSourceFileName = (string) Dts.Connections["SourceConnectionFlatFile"].ConnectionString;

    Does System::PackageName included in the ReadOnlyVariables or ReadWriteVariables?

  • ADF Task Flow Exception Handling

    Hi ,
    I tried a very simple thing for taskFlow exception handling.
    I created a bounded task flow with a page fragment (View1.jsff) and another view which is the TaskFlow ExceptionHandler (error.jsff).
    The view1.jsff has a button whose action is bound to the backing bean. In the backingBean method I deliberately do division by 0.
    Since this is an unHandled exception, I would have expected the control to come to error.jsff. But, instead I am shown a pop up box with the error message.
    Why is the control not getting redirected to error.jsff ?
    Thanks.
    S.Srivatsa Sivan

    Hi Frank , im having the same problem.
    I want to handle exceptions that occur while navigating task flows (example: A user navigates to a task flow that he/she does not have view permission)
    I tried using a view activity and method activity as the exception handler but none of them works, the exception is still not handles. It does not even navigate to the exception handler on the task flow.
    on the view page i have:
    <af:panelStretchLayout topHeight="50px" id="psl1">
    <f:facet name="top">
    <af:panelGroupLayout layout="scroll"
    xmlns:af="http://xmlns.oracle.com/adf/faces/rich"
    id="pgl1">
    Error message:  
    <af:outputText value="#{controllerContext.currentRootViewPort.exceptionData.message}" id="ot2"/>
    </af:panelGroupLayout>
    </f:facet>
    <f:facet name="center">
    <af:outputText value="#{my_exception_Handler.stackTrace}" id="ot1"/>
    <!-- id="af_one_column_header_stretched" -->
    </f:facet>
    </af:panelStretchLayout>
    I tried getting the error message and stacktrace from the controllerContext via EL like this "#{controllerContext.currentRootViewPort.exceptionData.message}"
    and from the controllerContext class in functions that i have declared in my_exception_Handler class like this
    " ControllerContext ctx = ControllerContext.getInstance();
    ViewPortContext vCtx = ctx.getCurrentViewPort();
    if(vCtx.getExceptionData() != null){
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    vCtx.getExceptionData().printStackTrace(printWriter);
    return stringWriter.toString();"
    But all this dont even matter because when the exception occurs on the task flow it does not navigate to the default exception handler.
    thanks for your interest and help in advance.
    Cyborg_0912

  • Using Exception Handler in an ADF Task Flow

    Hi folks.
    Today I gave a try on Exception Handling. while i go through the blog.
    https://blogs.oracle.com/ADFProgrammers/entry/using_exception_handler_in_an
    I cant able to attain the Solution 2: Re-Routing the task flow to display an error page As per the Figure 9 i make it out.
    but it is not navigating error.jsff.
    Taskflow return is not working i hope. only Exception thrown only happens from method.
    anyone help me out. what I'm missing ?
    - jdev 11.1.1.6.0

    hi,
    is there anyone help me out of this issue.

  • Task flow exception handler

    Hi all,
    I'm trying to specify a method activity as an exception handler in the adfc-config. The problem is if I specify a view activity or a bounded task flow as the exception handler then it works fine, but if the exception handler is a method activity then it is not recognized. What could be the cause?. I need to execute a method when an exception occurs.
    Version: 11.1.2.0
    Edited by: NewBee on Apr 23, 2013 10:37 AM

    Hi,
    there should not be a problem with this and I recently did the same with JDeveloper 11g R2 (not sure which version of JDeveloper you use because you did not share this information). I assume you just marked the method activity as an exception handler without any other configuration? If so then set a break point to the managed bean method that you access from the method activity to see if it actually stops there. Also note that not all exceptions are handled by the controller exception handler. E.g an exception during render response phase (typically an exception in a managed bean) is not handled by the controller. Also you need to avoid the managed bean that handles the exception to itself throw one. This however you will see when debugging the bean.
    Frank

  • Handling errors raised by Script task

    Hi,
    I have a Script Task which I reduced to its minimal form:
    Dts.TaskResult = (int)ScriptResults.Failure;
    Next I link a Task_X with a failure precedence constraint.
    On execution, is the SSIS suppose to follow the path to Task_X (thus handling the error) or fail altogether?
    Thanks

    It is not failing together, instead it has to go to failure precedence constraint and do the required operations.
    It was my understanding, I didn't understand why it wasn't working and the entire package would fail.
    Figured out it was because Task_X had multiple precedence constraints and logical operator was set to "AND".
    The error was thus not handled.
    Thanks!

  • Script task error: exception has been thrown by the target of an invocation

    Hi, 
    I have a script task which find the sheet name in an excel and assigned it to variable, this package works perfect while executing using BIDS but when I try to execute it using project deployment it throws the error.
    Script task error: exception has been thrown by the target of an invocation

    Hi Shoaib,
    You use the Microsoft.Office.Interop.Excel namespace in the Script Task, right? If so, please check whether you can find the Microsoft.Office.Interop.Excel.dll in the following folder on the SSIS server:
    %ProgramFiles%\Microsoft Visual Studio XX.X\Visual Studio Tools for Office\PIA\OfficeXX
    (or %ProgramFiles(x86)%\Microsoft Visual Studio XX.X\Visual Studio Tools for Office\PIA\OfficeXX on 64-bit operating systems)
    To install Office primary interop assemblies (PIAs), you can use one of the following methods:
    Install the .NET Programmability Support feature when installing Microsoft Office.
    Install the
    Microsoft Office 2010: Primary Interop Assemblies Redistributable.
    Regards,
    Mike Yin
    TechNet Community Support

  • Runtime error Exception has been thrown by the target of an invocation" from Script task

    I have a SSIS package with a script task, I get
    the following error when i try to run it in my local system. It works fine for my collegues as well as in production. However, I am not able to run it locally, to test. I keep a debug point in the main method, but it is never reached, I get the error before
    it goes to main method.
    I am using VS 2010, .Net framework 4.5.
    The script task does compile. I get the following messages SSIS package "..\Test.dtsx" starting. Error: 0x1 at Test: Exception has been thrown by the target of an invocation. Task failed: Test SSIS package "..\Test.dtsx" finished: Success.
    The program '[2552] DtsDebugHost.exe: DTS' has exited with code 0 (0x0).

    The following is the code:
    public void Main()
    try
     LogMessages("Update Bug package execution started at :: " + DateTime.Now.ToLongTimeString());
     LogMessages("Loading package configuration values to local variables.");
    strDBConn = Dts.Variables["User::DBConnection"] != null ? Dts.Variables["User::DBConnection"].Value.ToString() : string.Empty;
    strTPCUrl = Dts.Variables["User::TPCUrl"] != null ? Dts.Variables["User::TPCUrl"].Value.ToString() : string.Empty;
    TfsTeamProjectCollection objTPC = new TfsTeamProjectCollection(new Uri(strTPCUrl));
    WorkItemStore objWIS = new WorkItemStore(objTPC);
    WorkItemCollection objWIC = objWIS.Query("SELECT...");
    foreach (WorkItem wi in objWIC)
    catch(Exception ex)
    When I commented the code from TfsTeamProjectCollection objTPC = new TfsTeamProjectCollection(new Uri(strTPCUrl)); The script executes successfully. However, if i keep TfsTeamProjectCollection objTPC = new TfsTeamProjectCollection(new Uri(strTPCUrl));
    and comment the rest, i get the exception.
    I do have access to the URL

  • JAVA BEANSHELL EXCEPTION HANDLING

    Hi
    still new to ODI
    I have created a java beanshell script in ODI which calls a simple java class, cars, then sets the no of seats to a value designed to raise an exception. Exception raised but procedure works OK,
    How can I register the fact that it has failed through exception handling? (It is possible that my java exception handling isn't quite right)
    The no of seats has no effect on the success/failure of the ODI procedure, but the log shows that the exception is caught !
    any assistance gratefully received.
    Regards
    Terry
    cars class: (added to agent start)
    ====================
    public class cars {
    private int seats;
    public void setSeats (int seats) throws tooManySeatsException {
    if (seats) < 100) {
    this .seats = seats;
    } else {
    throw new tooManySeatsException("Too many seats");
    public int getSeats () {
    return this.seats;
    class tooManySeatsException extends Exception {
    public tooManySeatsException (String msg){
    super();
    Java beanshell procedure in ODI
    ====================
    import cars;
    public class carsTest {
    public carsTest(){
    public void init(){
    cars c = new cars();
    c.setSeats(20);
    //c.setseats(200);
    try {
    carsTest ct = new carsTest();
    ct.init();
    } catch (Exception e) {
    throw Error (e);
    }

    Your code throws exception when you set value >100 but you are setting 20 thus it would not throw exception.
    In the procedure step you can uncheck "Ignore error" flag to let execution failed on throwing any exception from your code. If you check that flag then the execution would not fail rather lease the task in warning state.

  • Convert ActiveX DTS script task to SSIS Script task - Please help

    Hello,
    I Have a ActiveX script that was used in a DTS package but I'm currently trying to convert all my DTS packages to SSIS.The script is tasked to run the package on a daily basis. Everything works fine except the ActiveX script. It gives an error on my DTSGlobalVariables.parent,
    I looked up this error and changed it to "DTS.Variables("User::VariableName").Value", in
    the SSIS script task (in VB) but now I'm getting error: 
    Microsoft.SqlServer.Dts.Runtime.DtsRuntimeException: The element cannot be found in a collection.
    ---> System.Runtime.InteropServices.COMException (0xC0010009): The element cannot be found in a collection.
    bij Microsoft.SqlServer.Dts.Runtime.Wrapper.IDTSVariables100.get_Item(Object Index)
    bij Microsoft.SqlServer.Dts.Runtime.Variables.get_Item(Object index)
    --- Einde van intern uitzonderingsstackpad ---
    bij Microsoft.SqlServer.Dts.Runtime.Variables.get_Item(Object index)
    bij ST_f32fc12b60f34bebbbdfc0c5e5b40a96.vbproj.ScriptMain.Main()
    --- Einde van intern uitzonderingsstackpad ---
    bij System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
    bij System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
    bij System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
    bij System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
    bij System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
    bij System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, CultureInfo culture)
    I have tried to convert this ActiveX script into a SSIS script task in VB but I know hardly any VB... So I'm wondering what the best course of action for me is, should I try to convert it into the script task like I am trying now, if so, how do I make it
    work?
    Any help would be really really welcome.
    This is the original ActiveX script that needs to be converted:
    ' Visual Basic ActiveX Script
    Function Main()
    Dim sEnvironm
    Dim sServer
    Dim sSourceFile
    Dim sSourcePath
    Dim sBackupPath
    Dim sErrorPath
    Dim sFileName
    Dim sUDLPath
    ' Set vars
    ' First 2 are depending on the server and db
    ' FILL IN THE RIGHT VALUES
    sEnvironm = "MON_Datamart"
    sServer = "BrechtProesmans"
    ' --- DO NOT CHANGE ANYTHING BELOW THIS LINE ---
    sSourceFile = "C:\Program Files\Microsoft SQL Server\MON_Datamart\SourceFiles\tbl_L00T1.txt"
    sSourcePath = "C:\Program Files\Microsoft SQL Server\MON_Datamart\SourceFiles\"
    sBackupPath = "C:\Program Files\Microsoft SQL Server\MON_Datamart\BackupFiles\"
    sErrorPath = "C:\Program Files\Microsoft SQL Server\MON_Datamart\ErrorFiles\"
    sFileName = "tbl_L00T1.txt"
    sUDLPath = "C:\Program Files\Microsoft SQL Server\MON_Datamart\MON_Datamart.udl"
    ' Initial
    FoundError = False
    ' Get a handle to the Package object.
    Set oPackage = DTSGlobalVariables.Parent
    ' Update DTSConnections
    Set oConnection = oPackage.Connections("tbl_L00T1.txt")
    oConnection.DataSource = sSourceFile
    Set oConnection = oPackage.Connections("Datamart")
    oConnection.UDLPath = sUDLPath
    Set oConnection = oPackage.Connections("Truncate")
    oConnection.UDLPath = sUDLPath
    ' Update DTSTasks
    Set oTask = oPackage.Tasks("DTSTask_DTSDataPumpTask_1").CustomTask
    oTask.SourceObjectName = sSourceFile
    oTask.DestinationObjectName = sEnvironm & ".dbo.stg_tbl_L00T1"
    ' Set Global vars
    DTSGlobalVariables("SourcePath").Value = sSourceFile
    DTSGlobalVariables("BackupPath").Value = sBackupPath
    DTSGlobalVariables("ErrorPath").Value = sErrorPath
    DTSGlobalVariables("FileName").Value = sFileName
    ' Clean up.
    Set oTask = Nothing
    Set oConnection = Nothing
    Set oPackage = Nothing
    Main = DTSTaskExecResult_Success
    End Function

    Set a breakpoint and tell us on what line it dies, at the same time, you can inspect the variable values in the Auto window (if there are) as it merely perhaps is an issue with values not being passed in.
    Arthur
    MyBlog
    Twitter

  • Error While executing a SSIS package which contains a script task through SQL Server Agent job

    Hi,
    I have a SQL Server 2012 SSIS package with a script task along with other tasks [data flow, execute sql tasks ]. When I manually executed the job through BIDS, its completed successfully. 
    Then I have automated the execution of the package through SQL Server Agent Job. But when I executed the package through SQL Agent job, it runs successfully for all the tasks except script task. When it comes to execute the Script Task, it is getting failed
    with the below error message.
    "Error: 2012-08-29 12:45:14.67
       Code: 0x00000001
       Source: Script Task 
       Description: Exception has been thrown by the target of an invocation.
    End Error
    DTExec: The package execution returned DTSER_FAILURE (1).
    Started:  12:45:10 PM
    Finished: 12:45:14 PM
    Elapsed:  4.353 seconds
    I have installed the SSIS on the 64-bit environment and SSIS service is running. Also I tried to run the job through 32 bit [job option] but I am getting the above error in all cases.
    Any help will be greatly appreaciated !
    Thanks,
    Navin
    - naveen.reddy

    Hi Arthur,
    My script task access the excel files in a network share, refresh them all and save them. When I execute the ETL manually or thru DTEXEC, it is executing successfully. I am facing the issue when I am executing thru SQL Agent Job only. Logging also showing
    the same error.
    "Error: 2012-08-23 12:45:14.67
       Code: 0x00000001
       Source: Script Task 
       Description: Exception has been thrown by the target of an invocation.
    End Error
    DTExec: The package execution returned DTSER_FAILURE (1).
    Started:  12:45:10 PM
    Finished: 12:45:14 PM
    Elapsed:  4.353 seconds
    - naveen.reddy

  • PL/SQL 101 : Exception Handling

    Frequently I see questions and issues around the use of Exception/Error Handling in PL/SQL.  More often than not the issue comes from the questioners misunderstanding about how PL/SQL is constructed and executed, so I thought I'd write a small article covering the key concepts to give a clear picture of how it all hangs together. (Note: the examples are just showing examples of the exception handling structure, and should not be taken as truly valid code for ways of handling things)
    Exception Handling
    Contents
    1. Understanding Execution Blocks (part 1)
    2. Execution of the Execution Block
    3. Exceptions
    4. Understanding Execution Blocks (part 2)
    5. How to continue exection of statements after an exception
    6. User defined exceptions
    7. Line number of exception
    8. Exceptions within code within the exception block
    1. Understanding Execution Blocks (part 1)
    The first thing that one needs to understand is almost taking us back to the basics of PL/SQL... how a PL/SQL execution block is constructed.
    Essentially an execution block is made of 3 sections...
    +---------------------------+
    |    Declaration Section    |
    +---------------------------+
    |    Statements  Section    |
    +---------------------------+
    |     Exception Section     |
    +---------------------------+
    The Declaration section is the part defined between the PROCEDURE/FUNCTION header or the DECLARE keyword (for anonymous blocks) and the BEGIN keyword.  (Optional section)
    The Statements section is where your code goes and lies between the BEGIN keyword and the EXCEPTION keyword (or END keyword if there is no EXCEPTION section).  (Mandatory section)
    The Exception section is where any exception handling goes and lies between the EXCEPTION keyword at the END keyword. (Optional section)
    Example of an anonymous block...
    DECLARE
      .. declarative statements go here ..
    BEGIN
      .. code statements go here ..
    EXCEPTION
      .. exception handlers go here ..
    END;
    Example of a procedure/function block...
    [CREATE OR REPLACE] (PROCEDURE|FUNCTION) <proc or fn name> [(<parameters>)] [RETURN <datatype>] (IS|AS)
      .. declarative statements go here ..
    BEGIN
      .. code statements go here ..
    EXCEPTION
      .. exception handlers go here ..
    END;
    (Note: The same can also be done for packages, but let's keep it simple)
    2. Execution of the Execution Block
    This may seem a simple concept, but it's surprising how many people have issues showing they haven't grasped it.  When an Execution block is entered, the declaration section is processed, creating a scope of variables, types , cursors, etc. to be visible to the execution block and then execution enters into the Statements section.  Each statment in the statements section is executed in turn and when the execution completes the last statment the execution block is exited back to whatever called it.
    3. Exceptions
    Exceptions generally happen during the execution of statements in the Statements section.  When an exception happens the execution of statements jumps immediately into the exception section.  In this section we can specify what exceptions we wish to 'capture' or 'trap' and do one of the two following things...
    (Note: The exception section still has access to all the declared items in the declaration section)
    3.i) Handle the exception
    We do this when we recognise what the exception is (most likely it's something we expect to happen) and we have a means of dealing with it so that our application can continue on.
    Example...
    (without the exception handler the exception is passed back to the calling code, in this case SQL*Plus)
    SQL> ed
    Wrote file afiedt.buf
      1  declare
      2    v_name VARCHAR2(20);
      3  begin
      4    select ename
      5    into   v_name
      6    from   emp
      7    where  empno = &empno;
      8    dbms_output.put_line(v_name);
      9* end;
    SQL> /
    Enter value for empno: 123
    old   7:   where  empno = &empno;
    new   7:   where  empno = 123;
    declare
    ERROR at line 1:
    ORA-01403: no data found
    ORA-06512: at line 4
    (with an exception handler, we capture the exception, handle it how we want to, and the calling code is happy that there is no error for it to report)
    SQL> ed
    Wrote file afiedt.buf
      1  declare
      2    v_name VARCHAR2(20);
      3  begin
      4    select ename
      5    into   v_name
      6    from   emp
      7    where  empno = &empno;
      8    dbms_output.put_line(v_name);
      9  exception
    10    when no_data_found then
    11      dbms_output.put_line('There is no employee with this employee number.');
    12* end;
    SQL> /
    Enter value for empno: 123
    old   7:   where  empno = &empno;
    new   7:   where  empno = 123;
    There is no employee with this employee number.
    PL/SQL procedure successfully completed.
    3.ii) Raise the exception
    We do this when:-
    a) we recognise the exception, handle it but still want to let the calling code know that it happened
    b) we recognise the exception, wish to log it happened and then let the calling code deal with it
    c) we don't recognise the exception and we want the calling code to deal with it
    Example of b)
    SQL> ed
    Wrote file afiedt.buf
      1  declare
      2    v_name VARCHAR2(20);
      3    v_empno NUMBER := &empno;
      4  begin
      5    select ename
      6    into   v_name
      7    from   emp
      8    where  empno = v_empno;
      9    dbms_output.put_line(v_name);
    10  EXCEPTION
    11    WHEN no_data_found THEN
    12      INSERT INTO sql_errors (txt)
    13      VALUES ('Search for '||v_empno||' failed.');
    14      COMMIT;
    15      RAISE;
    16* end;
    SQL> /
    Enter value for empno: 123
    old   3:   v_empno NUMBER := &empno;
    new   3:   v_empno NUMBER := 123;
    declare
    ERROR at line 1:
    ORA-01403: no data found
    ORA-06512: at line 15
    SQL> select * from sql_errors;
    TXT
    Search for 123 failed.
    SQL>
    Example of c)
    SQL> ed
    Wrote file afiedt.buf
      1  declare
      2    v_name VARCHAR2(20);
      3    v_empno NUMBER := &empno;
      4  begin
      5    select ename
      6    into   v_name
      7    from   emp
      8    where  empno = v_empno;
      9    dbms_output.put_line(v_name);
    10  EXCEPTION
    11    WHEN no_data_found THEN
    12      INSERT INTO sql_errors (txt)
    13      VALUES ('Search for '||v_empno||' failed.');
    14      COMMIT;
    15      RAISE;
    16    WHEN others THEN
    17      RAISE;
    18* end;
    SQL> /
    Enter value for empno: 'ABC'
    old   3:   v_empno NUMBER := &empno;
    new   3:   v_empno NUMBER := 'ABC';
    declare
    ERROR at line 1:
    ORA-06502: PL/SQL: numeric or value error: character to number conversion error
    ORA-06512: at line 3
    SQL> select * from sql_errors;
    TXT
    Search for 123 failed.
    SQL>
    As you can see from the sql_errors log table, no log was written so the WHEN others exception was the exception that raised the error to the calling code (SQL*Plus)
    4. Understanding Execution Blocks (part 2)
    Ok, so now we understand the very basics of an execution block and what happens when an exception happens.  Let's take it a step further...
    Execution blocks are not just a single simple block in most cases.  Often, during our statements section we have a need to call some reusable code and we do that by calling a procedure or function.  Effectively this nests the procedure or function's code as another execution block within the current statement section so, in terms of execution, we end up with something like...
    +---------------------------------+
    |    Declaration Section          |
    +---------------------------------+
    |    Statements  Section          |
    |            .                    |
    |  +---------------------------+  |
    |  |    Declaration Section    |  |
    |  +---------------------------+  |
    |  |    Statements  Section    |  |
    |  +---------------------------+  |
    |  |     Exception Section     |  |
    |  +---------------------------+  |
    |            .                    |
    +---------------------------------+
    |     Exception Section           |
    +---------------------------------+
    Example... (Note: log_trace just writes some text to a table for tracing)
    SQL> create or replace procedure a as
      2    v_dummy NUMBER := log_trace('Procedure A''s Declaration Section');
      3  begin
      4    v_dummy := log_trace('Procedure A''s Statement Section');
      5    v_dummy := 1/0; -- cause an exception
      6  exception
      7    when others then
      8      v_dummy := log_trace('Procedure A''s Exception Section');
      9      raise;
    10  end;
    11  /
    Procedure created.
    SQL> create or replace procedure b as
      2    v_dummy NUMBER := log_trace('Procedure B''s Declaration Section');
      3  begin
      4    v_dummy := log_trace('Procedure B''s Statement Section');
      5    a; -- HERE the execution passes to the declare/statement/exception sections of A
      6  exception
      7    when others then
      8      v_dummy := log_trace('Procedure B''s Exception Section');
      9      raise;
    10  end;
    11  /
    Procedure created.
    SQL> exec b;
    BEGIN b; END;
    ERROR at line 1:
    ORA-01476: divisor is equal to zero
    ORA-06512: at "SCOTT.B", line 9
    ORA-06512: at line 1
    SQL> select * from code_trace;
    TXT
    Procedure B's Declaration Section
    Procedure B's Statement Section
    Procedure A's Declaration Section
    Procedure A's Statement Section
    Procedure A's Exception Section
    Procedure B's Exception Section
    6 rows selected.
    SQL>
    Likewise, execution blocks can be nested deeper and deeper.
    5. How to continue exection of statements after an exception
    One of the common questions asked is how to return execution to the statement after the one that created the exception and continue on.
    Well, firstly, you can only do this for statements you expect to raise an exception, such as when you want to check if there is no data found in a query.
    If you consider what's been shown above you could put any statement you expect to cause an exception inside it's own procedure or function with it's own exception section to handle the exception without raising it back to the calling code.  However, the nature of procedures and functions is really to provide a means of re-using code, so if it's a statement you only use once it seems a little silly to go creating individual procedures for these.
    Instead, you nest execution blocks directly, to give the same result as shown in the diagram at the start of part 4 of this article.
    SQL> ed
    Wrote file afiedt.buf
      1  create or replace procedure b (p_empno IN VARCHAR2) as
      2    v_dummy NUMBER := log_trace('Procedure B''s Declaration Section');
      3  begin
      4    v_dummy := log_trace('Procedure B''s Statement Section');
      5    -- Here we start another execution block nested in the first one...
      6    declare
      7      v_dummy NUMBER := log_trace('Nested Block Declaration Section');
      8    begin
      9      v_dummy := log_trace('Nested Block Statement Section');
    10      select empno
    11        into   v_dummy
    12        from   emp
    13       where  empno = p_empno; -- Note: the parameters and variables from
                                         parent execution block are available to use!
    14    exception
    15      when no_data_found then
    16        -- This is an exception we can handle so we don't raise it
    17        v_dummy := log_trace('No employee was found');
    18        v_dummy := log_trace('Nested Block Exception Section - Exception Handled');
    19      when others then
    20        -- Other exceptions we can't handle so we raise them
    21        v_dummy := log_trace('Nested Block Exception Section - Exception Raised');
    22        raise;
    23    end;
    24    -- ...Here endeth the nested execution block
    25    -- As the nested block handled it's exception we come back to here...
    26    v_dummy := log_trace('Procedure B''s Statement Section Continued');
    27  exception
    28    when others then
    29      -- We'll only get to here if an unhandled exception was raised
    30      -- either in the nested block or in procedure b's statement section
    31      v_dummy := log_trace('Procedure B''s Exception Section');
    32      raise;
    33* end;
    SQL> /
    Procedure created.
    SQL> exec b(123);
    PL/SQL procedure successfully completed.
    SQL> select * from code_trace;
    TXT
    Procedure B's Declaration Section
    Procedure B's Statement Section
    Nested Block Declaration Section
    Nested Block Statement Section
    No employee was found
    Nested Block Exception Section - Exception Handled
    Procedure B's Statement Section Continued
    7 rows selected.
    SQL> truncate table code_trace;
    Table truncated.
    SQL> exec b('ABC');
    BEGIN b('ABC'); END;
    ERROR at line 1:
    ORA-01722: invalid number
    ORA-06512: at "SCOTT.B", line 32
    ORA-06512: at line 1
    SQL> select * from code_trace;
    TXT
    Procedure B's Declaration Section
    Procedure B's Statement Section
    Nested Block Declaration Section
    Nested Block Statement Section
    Nested Block Exception Section - Exception Raised
    Procedure B's Exception Section
    6 rows selected.
    SQL>
    You can see from this that, very simply, the code that we expected may have an exception was able to either handle the exception and return to the outer execution block to continue execution, or if an unexpected exception occurred then it was able to be raised up to the outer exception section.
    6. User defined exceptions
    There are three sorts of 'User Defined' exceptions.  There are logical situations (e.g. business logic) where, for example, certain criteria are not met to complete a task, and there are existing Oracle errors that you wish to give a name to in order to capture them in the exception section.  The third is raising your own exception messages with our own exception numbers.  Let's look at the first one...
    Let's say I have tables which detail stock availablility and reorder levels...
    SQL> select * from reorder_level;
       ITEM_ID STOCK_LEVEL
             1          20
             2          20
             3          10
             4           2
             5           2
    SQL> select * from stock;
       ITEM_ID ITEM_DESC  STOCK_LEVEL
             1 Pencils             10
             2 Pens                 2
             3 Notepads            25
             4 Stapler              5
             5 Hole Punch           3
    SQL>
    Now, our Business has told the administrative clerk to check stock levels and re-order anything that is below the re-order level, but not to hold stock of more than 4 times the re-order level for any particular item.  As an IT department we've been asked to put together an application that will automatically produce the re-order documents upon the clerks request and, because our company is so tight-ar*ed about money, they don't want to waste any paper with incorrect printouts so we have to ensure the clerk can't order things they shouldn't.
    SQL> ed
    Wrote file afiedt.buf
      1  create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
      2    cursor cur_stock_reorder is
      3      select s.stock_level
      4            ,r.stock_level as reorder_level
      5            ,(r.stock_level*4) as reorder_limit
      6      from stock s join reorder_level r on (s.item_id = r.item_id)
      7      where s.item_id = p_item_id;
      8    --
      9    v_stock cur_stock_reorder%ROWTYPE;
    10  begin
    11    OPEN cur_stock_reorder;
    12    FETCH cur_stock_reorder INTO v_stock;
    13    IF cur_stock_reorder%NOTFOUND THEN
    14      RAISE no_data_found;
    15    END IF;
    16    CLOSE cur_stock_reorder;
    17    --
    18    IF v_stock.stock_level >= v_stock.reorder_level THEN
    19      -- Stock is not low enough to warrant an order
    20      DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
    21    ELSE
    22      IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
    23        -- Required amount is over-ordering
    24        DBMS_OUTPUT.PUT_LINE('Quantity specified is too much.  Max for this item: '
                                     ||to_char(v_stock.reorder_limit-v_stock.stock_level));
    25      ELSE
    26        DBMS_OUTPUT.PUT_LINE('Order OK.  Printing Order...');
    27        -- Here goes our code to print the order
    28      END IF;
    29    END IF;
    30    --
    31  exception
    32    WHEN no_data_found THEN
    33      CLOSE cur_stock_reorder;
    34      DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
    35* end;
    SQL> /
    Procedure created.
    SQL> exec re_order(10,100);
    Invalid Item ID.
    PL/SQL procedure successfully completed.
    SQL> exec re_order(3,40);
    Stock has not reached re-order level yet!
    PL/SQL procedure successfully completed.
    SQL> exec re_order(1,100);
    Quantity specified is too much.  Max for this item: 70
    PL/SQL procedure successfully completed.
    SQL> exec re_order(2,50);
    Order OK.  Printing Order...
    PL/SQL procedure successfully completed.
    SQL>
    Ok, so that code works, but it's a bit messy with all those nested IF statements. Is there a cleaner way perhaps?  Wouldn't it be nice if we could set up our own exceptions...
    SQL> ed
    Wrote file afiedt.buf
      1  create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
      2    cursor cur_stock_reorder is
      3      select s.stock_level
      4            ,r.stock_level as reorder_level
      5            ,(r.stock_level*4) as reorder_limit
      6      from stock s join reorder_level r on (s.item_id = r.item_id)
      7      where s.item_id = p_item_id;
      8    --
      9    v_stock cur_stock_reorder%ROWTYPE;
    10    --
    11    -- Let's declare our own exceptions for business logic...
    12    exc_not_warranted EXCEPTION;
    13    exc_too_much      EXCEPTION;
    14  begin
    15    OPEN cur_stock_reorder;
    16    FETCH cur_stock_reorder INTO v_stock;
    17    IF cur_stock_reorder%NOTFOUND THEN
    18      RAISE no_data_found;
    19    END IF;
    20    CLOSE cur_stock_reorder;
    21    --
    22    IF v_stock.stock_level >= v_stock.reorder_level THEN
    23      -- Stock is not low enough to warrant an order
    24      RAISE exc_not_warranted;
    25    END IF;
    26    --
    27    IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
    28      -- Required amount is over-ordering
    29      RAISE exc_too_much;
    30    END IF;
    31    --
    32    DBMS_OUTPUT.PUT_LINE('Order OK.  Printing Order...');
    33    -- Here goes our code to print the order
    34    --
    35  exception
    36    WHEN no_data_found THEN
    37      CLOSE cur_stock_reorder;
    38      DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
    39    WHEN exc_not_warranted THEN
    40      DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
    41    WHEN exc_too_much THEN
    42      DBMS_OUTPUT.PUT_LINE('Quantity specified is too much.  Max for this item: '
                                  ||to_char(v_stock.reorder_limit-v_stock.stock_level));
    43* end;
    SQL> /
    Procedure created.
    SQL> exec re_order(10,100);
    Invalid Item ID.
    PL/SQL procedure successfully completed.
    SQL> exec re_order(3,40);
    Stock has not reached re-order level yet!
    PL/SQL procedure successfully completed.
    SQL> exec re_order(1,100);
    Quantity specified is too much.  Max for this item: 70
    PL/SQL procedure successfully completed.
    SQL> exec re_order(2,50);
    Order OK.  Printing Order...
    PL/SQL procedure successfully completed.
    SQL>
    That's better.  And now we don't have to use all those nested IF statements and worry about it accidently getting to code that will print the order out as, once one of our user defined exceptions is raised, execution goes from the Statements section into the Exception section and all handling of errors is done in one place.
    Now for the second sort of user defined exception...
    A new requirement has come in from the Finance department who want to have details shown on the order that show a re-order 'indicator' based on the formula ((maximum allowed stock - current stock)/re-order quantity), so this needs calculating and passing to the report...
    SQL> ed
    Wrote file afiedt.buf
      1  create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
      2    cursor cur_stock_reorder is
      3      select s.stock_level
      4            ,r.stock_level as reorder_level
      5            ,(r.stock_level*4) as reorder_limit
      6            ,(((r.stock_level*4)-s.stock_level)/p_quantity) as finance_factor
      7      from stock s join reorder_level r on (s.item_id = r.item_id)
      8      where s.item_id = p_item_id;
      9    --
    10    v_stock cur_stock_reorder%ROWTYPE;
    11    --
    12    -- Let's declare our own exceptions for business logic...
    13    exc_not_warranted EXCEPTION;
    14    exc_too_much      EXCEPTION;
    15  begin
    16    OPEN cur_stock_reorder;
    17    FETCH cur_stock_reorder INTO v_stock;
    18    IF cur_stock_reorder%NOTFOUND THEN
    19      RAISE no_data_found;
    20    END IF;
    21    CLOSE cur_stock_reorder;
    22    --
    23    IF v_stock.stock_level >= v_stock.reorder_level THEN
    24      -- Stock is not low enough to warrant an order
    25      RAISE exc_not_warranted;
    26    END IF;
    27    --
    28    IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
    29      -- Required amount is over-ordering
    30      RAISE exc_too_much;
    31    END IF;
    32    --
    33    DBMS_OUTPUT.PUT_LINE('Order OK.  Printing Order...');
    34    -- Here goes our code to print the order, passing the finance_factor
    35    --
    36  exception
    37    WHEN no_data_found THEN
    38      CLOSE cur_stock_reorder;
    39      DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
    40    WHEN exc_not_warranted THEN
    41      DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
    42    WHEN exc_too_much THEN
    43      DBMS_OUTPUT.PUT_LINE('Quantity specified is too much.  Max for this item: '
                                  ||to_char(v_stock.reorder_limit-v_stock.stock_level));
    44* end;
    SQL> /
    Procedure created.
    SQL> exec re_order(2,40);
    Order OK.  Printing Order...
    PL/SQL procedure successfully completed.
    SQL> exec re_order(2,0);
    BEGIN re_order(2,0); END;
    ERROR at line 1:
    ORA-01476: divisor is equal to zero
    ORA-06512: at "SCOTT.RE_ORDER", line 17
    ORA-06512: at line 1
    SQL>
    Hmm, there's a problem if the person specifies a re-order quantity of zero.  It raises an unhandled exception.
    Well, we could put a condition/check into our code to make sure the parameter is not zero, but again we would be wrapping our code in an IF statement and not dealing with the exception in the exception handler.
    We could do as we did before and just include a simple IF statement to check the value and raise our own user defined exception but, in this instance the error is standard Oracle error (ORA-01476) so we should be able to capture it inside the exception handler anyway... however...
    EXCEPTION
      WHEN ORA-01476 THEN
    ... is not valid.  What we need is to give this Oracle error a name.
    This is done by declaring a user defined exception as we did before and then associating that name with the error number using the PRAGMA EXCEPTION_INIT statement in the declaration section.
    SQL> ed
    Wrote file afiedt.buf
      1  create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
      2    cursor cur_stock_reorder is
      3      select s.stock_level
      4            ,r.stock_level as reorder_level
      5            ,(r.stock_level*4) as reorder_limit
      6            ,(((r.stock_level*4)-s.stock_level)/p_quantity) as finance_factor
      7      from stock s join reorder_level r on (s.item_id = r.item_id)
      8      where s.item_id = p_item_id;
      9    --
    10    v_stock cur_stock_reorder%ROWTYPE;
    11    --
    12    -- Let's declare our own exceptions for business logic...
    13    exc_not_warranted EXCEPTION;
    14    exc_too_much      EXCEPTION;
    15    --
    16    exc_zero_quantity EXCEPTION;
    17    PRAGMA EXCEPTION_INIT(exc_zero_quantity, -1476);
    18  begin
    19    OPEN cur_stock_reorder;
    20    FETCH cur_stock_reorder INTO v_stock;
    21    IF cur_stock_reorder%NOTFOUND THEN
    22      RAISE no_data_found;
    23    END IF;
    24    CLOSE cur_stock_reorder;
    25    --
    26    IF v_stock.stock_level >= v_stock.reorder_level THEN
    27      -- Stock is not low enough to warrant an order
    28      RAISE exc_not_warranted;
    29    END IF;
    30    --
    31    IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
    32      -- Required amount is over-ordering
    33      RAISE exc_too_much;
    34    END IF;
    35    --
    36    DBMS_OUTPUT.PUT_LINE('Order OK.  Printing Order...');
    37    -- Here goes our code to print the order, passing the finance_factor
    38    --
    39  exception
    40    WHEN exc_zero_quantity THEN
    41      DBMS_OUTPUT.PUT_LINE('Quantity of 0 (zero) is invalid.');
    42    WHEN no_data_found THEN
    43      CLOSE cur_stock_reorder;
    44      DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
    45    WHEN exc_not_warranted THEN
    46      DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
    47    WHEN exc_too_much THEN
    48      DBMS_OUTPUT.PUT_LINE('Quantity specified is too much.  Max for this item: '
                                  ||to_char(v_stock.reorder_limit-v_stock.stock_level));
    49* end;
    SQL> /
    Procedure created.
    SQL> exec re_order(2,0);
    Quantity of 0 (zero) is invalid.
    PL/SQL procedure successfully completed.
    SQL>
    Lastly, let's look at raising our own exceptions with our own exception numbers...
    SQL> ed
    Wrote file afiedt.buf
      1  create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
      2    cursor cur_stock_reorder is
      3      select s.stock_level
      4            ,r.stock_level as reorder_level
      5            ,(r.stock_level*4) as reorder_limit
      6            ,(((r.stock_level*4)-s.stock_level)/p_quantity) as finance_factor
      7      from stock s join reorder_level r on (s.item_id = r.item_id)
      8      where s.item_id = p_item_id;
      9    --
    10    v_stock cur_stock_reorder%ROWTYPE;
    11    --
    12    exc_zero_quantity EXCEPTION;
    13    PRAGMA EXCEPTION_INIT(exc_zero_quantity, -1476);
    14  begin
    15    OPEN cur_stock_reorder;
    16    FETCH cur_stock_reorder INTO v_stock;
    17    IF cur_stock_reorder%NOTFOUND THEN
    18      RAISE no_data_found;
    19    END IF;
    20    CLOSE cur_stock_reorder;
    21    --
    22    IF v_stock.stock_level >= v_stock.reorder_level THEN
    23      -- Stock is not low enough to warrant an order
    24      [b]RAISE_APPLICATION_ERROR(-20000, 'Stock has not reached re-order level yet!');[/b]
    25    END IF;
    26    --
    27    IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
    28      -- Required amount is over-ordering
    29     

    its nice article, have put up this one the blog
    site,Nah, I don't have time to blog, but if one of the other Ace's/Experts wants to copy it to a blog with reference back to here (and all due credit given ;)) then that's fine by me.
    I'd go for a book like "Selected articles by OTN members" or something. Does anybody have a list of links of all those mentioned articles?Just these ones I've bookmarked...
    Introduction to regular expressions ... by CD
    When your query takes too long ... by Rob van Wijk
    How to pipeline a function with a dynamic number of columns? by ascheffer
    PL/SQL 101 : Exception Handling by BluShadow

  • Script task fails to send mail to GMAIL

    Hi   guys ,
       I am new here and i am glad i that i am here.  I am working in a company  as SQL Server developer(T-sql), i am learning SSIS because  i wanted to move to data warehousing.
    I not familiar and i don't know any thing about  C#,  but i am learning SSIS on my own.
    I tried to send mail to gmail  using script task , both sender and receiver with same mail ID using variables which i tried using tutorial i found from the below link.
    [quote]http://www.codeproject.com/Articles/85172/Send-Email-from-SSIS-with-option-to-indicate-Email[/quote]
    but finally when i execute the task , it returns failure message and email is not sent.
    [quote]SSIS package "Send mail using script task.dtsx" starting.
    Error: 0x8 at Script Task: The script returned a failure result.
    Task failed: Script Task
    SSIS package "Send mail using script task.dtsx" finished: Success.
    [/quote]
    Below message taken from progress tab
    [quote]Error: The script returned a failure result.[/quote]
    Can you all please help me in  finding where i am going wrong? please check below code which i have used in script task.
    Microsoft SQL Server Integration Services Script Task
    Write scripts using Microsoft Visual C# 2008.
    The ScriptMain is the entry point class of the script.
    using System;
    using System.Data;
    using Microsoft.SqlServer.Dts.Runtime;
    using System.Windows.Forms;
    using System.Text.RegularExpressions;
    using System.Net.Mail;
    namespace ST_9bc84810a62a401aa44ddd905bcd369d.csproj
    [System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
    public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
    #region VSTA generated code
    enum ScriptResults
    Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
    Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
    #endregion
    The execution engine calls this method when the task executes.
    To access the object model, use the Dts property. Connections, variables, events,
    and logging features are available as members of the Dts property as shown in the following examples.
    To reference a variable, call Dts.Variables["MyCaseSensitiveVariableName"].Value;
    To post a log entry, call Dts.Log("This is my log text", 999, null);
    To fire an event, call Dts.Events.FireInformation(99, "test", "hit the help message", "", 0, true);
    To use the connections collection use something like the following:
    ConnectionManager cm = Dts.Connections.Add("OLEDB");
    cm.ConnectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;Provider=SQLNCLI10;Integrated Security=SSPI;Auto Translate=False;";
    Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
    To open Help, press F1.
    public void Main()
    string sSubject = "Test Subject";
    string sBody = "Test Message";
    int iPriority = 2;
    if (SendMail(sSubject, sBody, iPriority))
    Dts.TaskResult = (int)ScriptResults.Success;
    else
    //Fails the Task
    Dts.TaskResult = (int)ScriptResults.Failure;
    public bool SendMail(string sSubject, string sMessage, int iPriority)
    try
    string sEmailServer = Dts.Variables["sEmailServer"].Value.ToString();
    string sEmailPort = Dts.Variables["sEmailPort"].Value.ToString();
    string sEmailUser = Dts.Variables["sEmailUser"].Value.ToString();
    string sEmailPassword = Dts.Variables["sEmailPassword"].Value.ToString();
    string sEmailSendTo = Dts.Variables["sEmailSendTo"].Value.ToString();
    string sEmailSendCC = Dts.Variables["sEmailSendCC"].Value.ToString();
    string sEmailSendFrom = Dts.Variables["sEmailSendFrom"].Value.ToString();
    string sEmailSendFromName = Dts.Variables["sEmailSendFromName"].Value.ToString();
    SmtpClient smtpClient = new SmtpClient();
    MailMessage message = new MailMessage();
    MailAddress fromAddress = new MailAddress(sEmailSendFrom, sEmailSendFromName);
    //You can have multiple emails separated by ;
    string[] sEmailTo = Regex.Split(sEmailSendTo, ";");
    string[] sEmailCC = Regex.Split(sEmailSendCC, ";");
    int sEmailServerSMTP = int.Parse(sEmailPort);
    smtpClient.Host = sEmailServer;
    smtpClient.Port = sEmailServerSMTP;
    System.Net.NetworkCredential myCredentials =
    new System.Net.NetworkCredential(sEmailUser, sEmailPassword);
    smtpClient.Credentials = myCredentials;
    message.From = fromAddress;
    if (sEmailTo != null)
    for (int i = 0; i < sEmailTo.Length; ++i)
    if (sEmailTo[i] != null && sEmailTo[i] != "")
    message.To.Add(sEmailTo[i]);
    if (sEmailCC != null)
    for (int i = 0; i < sEmailCC.Length; ++i)
    if (sEmailCC[i] != null && sEmailCC[i] != "")
    message.To.Add(sEmailCC[i]);
    switch (iPriority)
    case 1:
    message.Priority = MailPriority.High;
    break;
    case 3:
    message.Priority = MailPriority.Low;
    break;
    default:
    message.Priority = MailPriority.Normal;
    break;
    //You can enable this for Attachments.
    //SingleFile is a string variable for the file path.
    //foreach (string SingleFile in myFiles)
    // Attachment myAttachment = new Attachment(SingleFile);
    // message.Attachments.Add(myAttachment);
    message.Subject = sSubject;
    message.IsBodyHtml = true;
    message.Body = sMessage;
    smtpClient.Send(message);
    return true;
    catch (Exception ex)
    return false;
    Please help me resolve this guys ... THANKS IN ADVANCE

    Thank you very much for your reply @Elvis Long,
    Sorry for the late reply
    Actually, i am not trying or executing this task  from my office , but i am trying this at my home :( .
    sEmailPort has value 587 sEmailServer has smtp.gmail.com
    Can you please check whether this C# coding is correct or not ? because finally it gives error saying "Script
    Task: The script returned a failure result" 
    so can you please check this with your system and let me know what is wrong with this code
    Thanks in advance  

  • SSIS/Script Task/ VB 2008 Help Urgent...

    Hi Guys, 
    Simple Script Task, just rename Excel tab, here is my code...
    Imports System
    Imports System.Data
    Imports System.Math
    Imports Microsoft.SqlServer.Dts.Runtime
    Imports Microsoft.Office.Interop.Excel
    Imports System.IO
    Imports System.Text
    <System.AddIn.AddIn("ScriptMain", Version:="1.0", Publisher:="", Description:="")> _
    <System.CLSCompliantAttribute(False)> _
    Partial Public Class ScriptMain
    Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
    Enum ScriptResults
    Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
    Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
    End Enum
    Public Sub Main()
    Dts.VariableDispenser.LockForRead("User::FileName") ' File Name Variable
    Dim variablesList As Variables
    Dts.VariableDispenser.GetVariables(variablesList)
    'Dim SFileName As String
    'SFileName = variablesList("User::Filename").Value.ToString
    ' Dim vars As Variables 'New Added For Variable
    Dim oMissing As Object = System.Reflection.Missing.Value
    Dim xl As New Microsoft.Office.Interop.Excel.ApplicationClass()
    Dim xlBook As Microsoft.Office.Interop.Excel.Workbook
    Dim xlSheet As Microsoft.Office.Interop.Excel.Worksheet
    'Dts.VariableDispenser.LockForRead("Filename") 'New Added For Variable
    'Start For Variable
    'Dim File As String 'New Added For Variable
    'File = CType(vars("Filename").Value, String) 'New Added For Variable
    'MsgBox(Prompt:="Filename")
    'Dim laPath As String = "C:\Excel\ABC_dr_daily_lf_10-07-14.xls" 'My File Name
    Dim lapath As String = variablesList("User::FileName").Value.ToString 'New Added For Variable
    'MsgBox(Prompt:="Filename")
    xlBook = DirectCast(xl.Workbooks.Open(laPath, oMissing, oMissing, oMissing, oMissing, oMissing, _
    oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, _
    oMissing, oMissing, oMissing), Workbook)
    xlSheet = DirectCast(xlBook.Worksheets.Item(1), Worksheet)
    xlSheet.Name = "data"
    xlBook.Save()
    xl.Application.Workbooks.Close()
    Dts.TaskResult = ScriptResults.Success
    End Sub
    End Class
    Finally I intalled MS Excel 2007 on my Dev Server. Here is the error that I am receiving....
    Error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidCastException: 
    Unable to cast COM object of type 'Microsoft.Office.Interop.Excel.ApplicationClass' to interface type 'Microsoft.Office.Interop.Excel._Application
    '. This operation failed because the QueryInterface call on the COM component for the interface with IID '{000208D5-0000-0000-C000-000000000046}'
    failed due to the following error: Library not registered. 
    Please help me, this is very urgent.
    Thank You.

    No I didn't upgrade my SQL Server. OMG this error making me ehhhhhh. 
    Here I solve my problem. 
    RUN>REGEDIT>  and look for "Office.Interop.Excel" and delete the old version. I am using Excel 2007, 14.0. 
    It solve my Problem. 
    Thanks All.

Maybe you are looking for

  • How do install and run Firefox....

    Hi all - any help is appreciated here to a brand new MBP user... windows PC convert, so noob to say the least... I just downloaded the most recent version for Mac on my new MBP... but, can't figure out how to run or install the program... I have comp

  • How to rotate photos in albums?

    how to rotate photos in albums??

  • Max number of IP phones per blade

    I have read in aCisco manual that the maximum number of IP phones is 18, assuming they use 15,4Watt. On a WS-X4148-RJ45V combined with a PWR-C45-4200ACV that leaves us with 30 ports we can not use for VoIP useing PoE. Or am I wrong?

  • Video Conferencing using JSP

    I am working on a interactive application whereby i can communicate with my peer for the purpose of elearning. Some of the functions i need to do is to interface video conferencing, live chat, live application sharing. All this to be real time. Anyon

  • GLPLUP - big uploads from Excel

    Transaction code GLPLUP (program G_FLEX_UPL) is used for budget data upload in SAP ECC6. There are need for about 250000 budget data rows to be uploaded into SAP. With GLPLUP can be uploaded about 1400 rows per one time, so with 250000 rows would mea