0

I have the following code in a script task but when I try execute the script I get an error with the following message: "Exception has been thrown by the target of an invocation. ---> Object reference not set to an instance of an object."

I am trying to address a deadlock error in my package with the use of variables. Based on the value of Region, I'm trying to populate another variable InputRegion.

    public void Main()
    {
        String InputFile;
        int StrLen;
        Variables var = null;    
        Dts.VariableDispenser.LockOneForWrite("User::Region", ref var);
        var[0].Value = "DEFAULT";
        InputFile = (String)vars["User::InputRegion"].Value;

        if (InputFile == "Europe.txt")
            var[0].Value = "European";
        if (InputFile == "Amers.txt")
            var[0].Value = "American";
        if (InputFile == "Tokyo.txt")
            var[0].Value = "Asian";
        else        
            var[0].Value = "Unknown";

        var.Unlock();

        Dts.TaskResult = (int)ScriptResults.Success;
        }
    }
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
user1773949
  • 119
  • 1
  • 2
  • 9
  • Where do you get that exception ? – phadaphunk Jun 11 '13 at 19:25
  • Hard to tell without the full code. You could `assume` that `var` is null and has not been initalised in your `LockOneForWrite` method. – Darren Jun 11 '13 at 19:25
  • 1
    Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Jun 11 '13 at 19:26
  • 2
    I would advise against using a variable name that's the same as a key word. var is a keyword in C#. Variable names should be descriptive. Not identifying that as the problem just making a general statement. – Bearcat9425 Jun 11 '13 at 19:46

1 Answers1

2

With the given informations, I can guess that :

The problem

 Variables var = null;  

You initialize your variable with a null valu and then you use it without giving a value.
Because you use it there (probably where you get the exception too)

  Dts.VariableDispenser.LockOneForWrite("User::Region", ref var);

Also

If the line of code above doesn't set a value to var, your program could crash :

  • There: var[0].Value = "DEFAULT";
  • There: var[0].Value = "European";
  • There: var[0].Value = "American";
  • There: var[0].Value = "Asian";
  • There: var[0].Value = "Unknown";
  • Or There: var.Unlock();

Possible Solution

Try giving it a valid value instead of null to make sure the problem is there.

phadaphunk
  • 12,785
  • 15
  • 73
  • 107