Add an unknown number of attachments to html email - c#

I have a SSIS package containing just a script task that sends an email.
The package is fed all the necessary params (To, from, subject, body) and also a param (string) containing a list of filenames, separated by a pipe.
I would like to add those filenames as attachments to the email I am sending.
I guess I somehow have to split the string and loop through it to add the files using attachment.add method.
But my knowledge of C# is not enough.
Who can and is willing to explain to me how to do this?
Code as follows:
#region Help:  Introduction to the script task
/* The Script Task allows you to perform virtually any operation that can be accomplished in
* a .Net application within the context of an Integration Services control flow. 
* 
* Expand the other regions which have "Help" prefixes for examples of specific ways to use
* Integration Services features within this script task. */
#endregion 
#region Namespaces
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.Net;
using System.Net.Mail;
#endregion namespace ST_3806baf576ce4ad1ab06519f6706197b
{
    /// <summary>
    /// ScriptMain is the entry point class of the script.  Do not change the name, attributes,
    /// or parent of this class.
    /// </summary>
    [Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
    public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
    {
        #region Help:  Using Integration Services variables and parameters in a script
        /* To use a variable in this script, first ensure that the variable has been added to 
         * either the list contained in the ReadOnlyVariables property or the list contained in 
         * the ReadWriteVariables property of this script task, according to whether or not your
         * code needs to write to the variable.  To add the variable, save this script, close this instance of
         * Visual Studio, and update the ReadOnlyVariables and 
         * ReadWriteVariables properties in the Script Transformation Editor window.
         * To use a parameter in this script, follow the same steps. Parameters are always read-only.
         * 
         * Example of reading from a variable:
         *  DateTime startTime = (DateTime) Dts.Variables["System::StartTime"].Value;
         * 
         * Example of writing to a variable:
         *  Dts.Variables["User::myStringVariable"].Value = "new value";
         * 
         * Example of reading from a package parameter:
         *  int batchId = (int) Dts.Variables["$Package::batchId"].Value;
         *  
         * Example of reading from a project parameter:
         *  int batchId = (int) Dts.Variables["$Project::batchId"].Value;
         * 
         * Example of reading from a sensitive project parameter:
         *  int batchId = (int) Dts.Variables["$Project::batchId"].GetSensitiveValue();
         * */         #endregion         #region Help:  Firing Integration Services events from a script
        /* This script task can fire events for logging purposes.
         * 
         * Example of firing an error event:
         *  Dts.Events.FireError(18, "Process Values", "Bad value", "", 0);
         * 
         * Example of firing an information event:
         *  Dts.Events.FireInformation(3, "Process Values", "Processing has started", "", 0, ref fireAgain)
         * 
         * Example of firing a warning event:
         *  Dts.Events.FireWarning(14, "Process Values", "No values received for input", "", 0);
         * */
        #endregion         #region Help:  Using Integration Services connection managers in a script
        /* Some types of connection managers can be used in this script task.  See the topic 
         * "Working with Connection Managers Programatically" for details.
         * 
         * Example of using an ADO.Net connection manager:
         *  object rawConnection = Dts.Connections["Sales DB"].AcquireConnection(Dts.Transaction);
         *  SqlConnection myADONETConnection = (SqlConnection)rawConnection;
         *  //Use the connection in some code here, then release the connection
         *  Dts.Connections["Sales DB"].ReleaseConnection(rawConnection);
         *
         * Example of using a File connection manager
         *  object rawConnection = Dts.Connections["Prices.zip"].AcquireConnection(Dts.Transaction);
         *  string filePath = (string)rawConnection;
         *  //Use the connection in some code here, then release the connection
         *  Dts.Connections["Prices.zip"].ReleaseConnection(rawConnection);
         * */
        #endregion 
        /// <summary>
        /// This method is called when this script task executes in the control flow.
        /// Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
        /// To open Help, press F1.
        /// </summary>
        public void Main()
        {
            //$Package::parAttachment
            //$Package::parBody
            //$Package::parFromLine
            //$Package::parSubject
            //$Package::parToLine
            //$Package::parAttachment eg. "c:\file1.txt|c:\file2.txt|file3.txt"
            //$Project::parFolderSource
            //$Project::parDestinationConnString            
string htmlMessageFrom = Dts.Variables["$Package::parFromLine"].Value.ToString();
string htmlMessageTo = Dts.Variables["$Package::parToLine"].Value.ToString();
string htmlMessageSubject = Dts.Variables["$Package::parSubject"].Value.ToString();
string htmlMessageBody = Dts.Variables["$Package::parBody"].Value.ToString();
string smtpServer = "mail.mydomain.com";            
SendMailMessage(htmlMessageFrom, htmlMessageTo, htmlMessageSubject, htmlMessageBody, true, smtpServer);             Dts.TaskResult = (int)ScriptResults.Success;         }         private void SendMailMessage(string From, string SendTo, string Subject, string Body, bool IsBodyHtml, string Server)
        {             MailMessage htmlMessage;
            SmtpClient mySmtpClient;
            string attachFile = Dts.Variables["$Package::parAttachment"].Value.ToString();             System.Net.Mail.Attachment attachment;
            attachment = new System.Net.Mail.Attachment(attachFile);             htmlMessage = new MailMessage(From, SendTo, Subject, Body);
            htmlMessage.IsBodyHtml = IsBodyHtml;
            htmlMessage.Attachments.Add(attachment);             mySmtpClient = new SmtpClient(Server);
            mySmtpClient.Credentials = CredentialCache.DefaultNetworkCredentials;
            mySmtpClient.Send(htmlMessage);         }         #region ScriptResults declaration
        /// <summary>
        /// This enum provides a convenient shorthand within the scope of this class for setting the
        /// result of the script.
        /// 
        /// This code was generated automatically.
        /// </summary>
        enum ScriptResults
        {
            Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
            Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
        };
        #endregion     }
}

Solved it like this: creating an array from a string
private void SendMailMessage(string From, string SendTo, string Subject, string Body, bool IsBodyHtml, string Server)
{
MailMessage htmlMessage;
SmtpClient mySmtpClient;
string strAttachment = Dts.Variables["$Package::parAttachment"].Value.ToString();
Array array = strAttachment.Split('|');
System.Net.Mail.Attachment attachment;
htmlMessage = new MailMessage(From, SendTo, Subject, Body);
htmlMessage.IsBodyHtml = IsBodyHtml;
foreach (var item in array)
{
// work with item here
string attachFile = item.ToString();
attachment = new System.Net.Mail.Attachment(attachFile);
htmlMessage.Attachments.Add(attachment);
};
mySmtpClient = new SmtpClient(Server);
mySmtpClient.Credentials = CredentialCache.DefaultNetworkCredentials;
mySmtpClient.Send(htmlMessage);
}

Related

How to Check if file pattern exist in C# SSIS package [duplicate]

I have a for loop container within my ssis package which contains a script and a sql task.
I have 3 variables.
source.string = this is folder location
file.string = i have used wildcard = *.csv
exist.int = defaulted to 0
I have the innitexpression value set to #Exists=1
and the evalexpression value set to #Exists=1
in the script I have set it to look at source variable and if file.string variable exists then set exist variable to 1
problem is it just loops it should only loop if no file there. cant see how I've done this wrong it was working before I changed the variable to be a wildcard *.csv
I have tested it using another variable which contains a filename rather than a wildcard and it works correctly the issue is when looking for a wildcard for the filename followed by the extension. why is this? can I not pass through a wildcard variable?
my script task is
public void Main()
{
// TODO: Add your code here
string Filepath = Dts.Variables["User::Source"].Value.ToString()
+ Dts.Variables["User::file"].Value.ToString();
if (
File.Exists(Filepath))
{
Dts.Variables["User::Exists"].Value = 1;
}
/// MessageBox.Show (Filepath);
/// MessageBox.Show(Dts.Variables["Exists"].Value.ToString());
Dts.TaskResult = (int)ScriptResults.Success;
}
#region ScriptResults declaration
/// <summary>
/// This enum provides a convenient shorthand within the scope of this class for setting the
/// result of the script.
///
/// This code was generated automatically.
/// </summary>
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
}
}
Based on comments above i made 2 different solutions. The solution for you right now would be no. 2
This one can search for a specific file based on multiple files in your path. It need some tweaking but can be used if you wanna check if a specific file exists with wildcard
This one evaluates to true if any wildcard file is found.
C# Code 1
Using System.IO:
string Filepath = Dts.Variables["User::Source"].Value.ToString();
string WildCard = Dts.Variables["User::file"].Value.ToString(); // In Text form #"*.txt";
string fullpath = Filepath + WildCard;
//With for loop
string txtFile = null;
// Gets all files with wildcard
string[] allfiles = Directory.GetFiles(Filepath, WildCard);
//Loop through all files and set the filename in txtFile. Do whatever you want here
foreach(string fileName in allfiles)
{
//Check if a file contains something, it could be a prefixed name you only want
if(fileName.Contains("txt"))
{
txtFile = fileName;
if(File.Exists(txtFile))
{
Dts.Variables["User::Exists"].Value = 1;
}
}
}
C# Code 2
Using System.IO;
Using System.Linq;
string Filepath = Dts.Variables["User::Source"].Value.ToString();
string WildCard = Dts.Variables["User::file"].Value.ToString(); //In text form "*.txt";
string fullpath = Filepath + WildCard;
//With bool
bool exists = Directory.EnumerateFiles(Filepath, WildCard).Any();
if(exists == true)
{
Dts.Variables["User::Exists"].Value = 1;
}
MessageBox.Show (Filepath);
MessageBox.Show(Dts.Variables["Exists"].Value.ToString());

Sending a message using IBM MQ, getting 2059 error or hang on construction of Queue Manager

I'm tasked with sending a test message to an (as yet) unknown MQ endpoint.
I've stood a trial version of IBM WebSphere MQ (v8.0.0.5) on a server, which I believe is configured correctly.
However, given the code included below I get either the exception:
An unhandled exception of type 'IBM.WMQ.MQException' occurred in
amqmdnet.dll
Additional information: 2059
Or if I am on the server itself using localhost instead of the remote server name, the constructor line hangs.
This is C#:
Hashtable connectionProperties = new Hashtable();
string connectionType = MQC.TRANSPORT_MQSERIES_MANAGED
connectionProperties.Add(MQC.TRANSPORT_PROPERTY, connectionType);
// Set up the rest of the connection properties, based on the
// connection type requested
switch (_connectionType)
{
case MQC.TRANSPORT_MQSERIES_BINDINGS:
break;
case MQC.TRANSPORT_MQSERIES_CLIENT:
case MQC.TRANSPORT_MQSERIES_XACLIENT:
case MQC.TRANSPORT_MQSERIES_MANAGED:
connectionProperties.Add(MQC.HOST_NAME_PROPERTY, "server.com");
connectionProperties.Add(MQC.CHANNEL_PROPERTY, "SYSTEM.DEF.CLNTCONN");
break;
}
MQQueueManager qMgr = new MQQueueManager("test", connectionProperties);
MqClientTest mqClientTest=new MqClientTest("TEST_QM","localhost", "SYSTEM.DEF.CLNTCONN");
Is there anything we're missing in this?
Update 1:
In the amqerr01.log file in the errors folder, we now have the text:
AMQ6183: An internal WebSphere MQ error has occurred.
Update 2:
The "internal WebSphere MQ error" was likely due to my probing the 1414 port to see if the port was "up" and listening. Seems it was and it obviously didn't like me doing that.
Update 3:
#Roger suggested I use 127.0.0.1 and capitals, which I've now applied - and changed the example above to reflect.
#JoshMc kindly pointed to a second AMQERR01.LOG file within the Queue Manager folder. I now get the error:
14/11/2017 15:35:08 - Process(336.6) User(xxxx)
Program(amqrmppa.exe)
Host(xxxx) Installation(xxxx)
VRMF(8.0.0.5) QMgr(TEST_QM)
AMQ9519: Channel 'SYSTEM.DEF.CLNTCONN' not found.
EXPLANATION: The requested operation failed because the program could
not find a definition of channel 'SYSTEM.DEF.CLNTCONN'.
TEST_QM is my Queue Manager, with the default (?) channel SYSTEM.DEF.CLNTCONN
With IBM MQ there are always a pair of channels that work together. For example if one MQ Queue Manager needs to send to message to another queue manager it would normally have a SDR (Sender) channel defined, which would point to a RCVR (Receiver) channel with the same name on the other queue manager.
For a MQ client connection the client application side of the channel is called a MQCD, and the MQ Queue Manager side is a SVRCONN (Server Connection) channel. The client side MQCD can be specified in a few different ways. The way you are demonstrating in the example you posted is programmatically specifying the MQCD information (channel name, hostname, etc).
An alternate way to specify the information is by pointing to a CCDT (Client Channel Definition Table) which is commonly referred to as a Channel Table, this is where a CLNTCONN channel would be used, since you are not using a Channel table I'll move on to why you are getting an error, but at the end of this answer I'll provide more details on Channel Tables.
In summary your application should not be specifying a CLNTCONN channel as the MQC.CHANNEL_PROPERTY it should be pointing to a SVRCONN channel.
Two things to note:
You should not use the predefined SYSTEM.* channels for this purpose (for example SYSTEM.DEF.SVRCONN), you should define a new channel for your application to use. The default channels are meant to hold parameters that you want to be the defaults when creating a new channel of the same type.
MQ v7.1 and later come with a few CHLAUTH rules enabled by default which will block access to the SYSTEM.* channels.
If you want to define a SVRCONN channel using the command line program runmqsc on Windows run the following on a CMD prompt:
echo DEFINE CHL(TEST_QM_CHANNEL1) CHLTYPE(SVRCONN)|runmqsc TEST_QM
Few more details about Channel Tables:
Prior to MQ v8 the only supported method to generate a Channel Table was by defining CLNTCONN channels on a queue manager which creates a file called AMQCLCHL.TAB under the queue manager name folder in a directory called #ipcc. The reason a queue manager comes with a channel called SYSTEM.DEF.CLNTCONNis to provide the default values when you create a new CLNTCONN channel. With v8 and later you can create the channel table using only the runmqsc -n mode, this will directly edit the channel table vs needing to create a CLNTCONN channel on a queue manager. The MQ Client for v8 and later now comes with a client version of runmqsc that can be used to create and alter channel tables.
An application can point to the channel table file in a few different ways, a common way is by setting two environment variables (MQCHLLIB and MQCHLTAB). The app then does not specify channel name, host name, etc in the program, it only needs to specify the name of the queue manager to connect to.
The order and where MQ looks for connection information is documented at the IBM v7.5 (or later) Knowledge Center page "Connecting IBM WebSphere MQ MQI client applications to queue managers". Note this link is for MQI clients, but the same basic order applies to .NET clients as well.
localhost
Try using 127.0.0.1 rather than localhost.
"rx" and "swift_test_tx"
Since you are new to MQ, it is time for you to read up on MQ Best Practices. One item is that it is NOT a good idea to use lowercase characters for MQ objects names. i.e. queues, channels, etc... MQ will always fold to uppercase any names that are not in quotes. So, it is just better to uppercase the names to begin with (less problems in the future).
Next, did you open port 1414 in your firewall? If not, then open the port for both TCP & UDP.
Here's an example of a C# program to put a message to a queue in a remote queue manager:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using IBM.WMQ;
/// <summary> Program Name
/// MQTest51
///
/// Description
/// This C# class will connect to a remote queue manager
/// and put a message to a queue under a managed .NET environment.
///
/// Sample Command Line Parameters
/// -h 127.0.0.1 -p 1414 -c TEST.CHL -m MQWT1 -q TEST.Q1
///
/// </summary>
namespace MQTest51
{
class MQTest51
{
private Hashtable inParms = null;
private Hashtable qMgrProp = null;
private System.String qManager;
private System.String outputQName;
/*
* The constructor
*/
public MQTest51()
: base()
{
}
/// <summary> Make sure the required parameters are present.</summary>
/// <returns> true/false
/// </returns>
private bool allParamsPresent()
{
bool b = inParms.ContainsKey("-h") && inParms.ContainsKey("-p") &&
inParms.ContainsKey("-c") && inParms.ContainsKey("-m") &&
inParms.ContainsKey("-q");
if (b)
{
try
{
System.Int32.Parse((System.String)inParms["-p"]);
}
catch (System.FormatException e)
{
b = false;
}
}
return b;
}
/// <summary> Extract the command-line parameters and initialize the MQ variables.</summary>
/// <param name="args">
/// </param>
/// <throws> IllegalArgumentException </throws>
private void init(System.String[] args)
{
inParms = Hashtable.Synchronized(new Hashtable());
if (args.Length > 0 && (args.Length % 2) == 0)
{
for (int i = 0; i < args.Length; i += 2)
{
inParms[args[i]] = args[i + 1];
}
}
else
{
throw new System.ArgumentException();
}
if (allParamsPresent())
{
qManager = ((System.String)inParms["-m"]);
outputQName = ((System.String)inParms["-q"]);
qMgrProp = new Hashtable();
qMgrProp.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED);
qMgrProp.Add(MQC.HOST_NAME_PROPERTY, ((System.String)inParms["-h"]));
qMgrProp.Add(MQC.CHANNEL_PROPERTY, ((System.String)inParms["-c"]));
try
{
qMgrProp.Add(MQC.PORT_PROPERTY, System.Int32.Parse((System.String)inParms["-p"]));
}
catch (System.FormatException e)
{
qMgrProp.Add(MQC.PORT_PROPERTY, 1414);
}
if (inParms.ContainsKey("-u"))
qMgrProp.Add(MQC.USER_ID_PROPERTY, ((System.String)inParms["-u"]));
if (inParms.ContainsKey("-x"))
qMgrProp.Add(MQC.PASSWORD_PROPERTY, ((System.String)inParms["-x"]));
if ( (inParms.ContainsKey("-u")) && (inParms.ContainsKey("-x")) )
qMgrProp.Add(MQC.USE_MQCSP_AUTHENTICATION_PROPERTY, true);
}
else
{
throw new System.ArgumentException();
}
}
/// <summary> Connect, open queue, write a message, close queue and disconnect.
///
/// </summary>
/// <throws> MQException </throws>
private void testSend()
{
System.String line;
int openOptions = MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING;
try
{
MQQueueManager _qMgr = new MQQueueManager(qManager, qMgrProp);
System.Console.Out.WriteLine("MQTest51 successfully connected to " + qManager);
MQQueue queue = _qMgr.AccessQueue(outputQName, openOptions, null, null, null); // no alternate user id
System.Console.Out.WriteLine("MQTest51 successfully opened " + outputQName);
MQPutMessageOptions pmo = new MQPutMessageOptions();
// Define a simple MQ message, and write some text in UTF format..
MQMessage sendmsg = new MQMessage();
sendmsg.Format = MQC.MQFMT_STRING;
sendmsg.Feedback = MQC.MQFB_NONE;
sendmsg.MessageType = MQC.MQMT_DATAGRAM;
line = "This is a test message embedded in the MQTest51 program.";
sendmsg.MessageId = MQC.MQMI_NONE;
sendmsg.CorrelationId = MQC.MQCI_NONE;
sendmsg.WriteString(line);
// put the message on the queue
queue.Put(sendmsg, pmo);
System.Console.Out.WriteLine("Message Data>>>" + line);
queue.Close();
System.Console.Out.WriteLine("MQTest51 closed: " + outputQName);
_qMgr.Disconnect();
System.Console.Out.WriteLine("MQTest51 disconnected from " + qManager);
}
catch (MQException mqex)
{
System.Console.Out.WriteLine("MQTest51 cc=" + mqex.CompletionCode + " : rc=" + mqex.ReasonCode);
}
catch (System.IO.IOException ioex)
{
System.Console.Out.WriteLine("MQTest51 ioex=" + ioex);
}
}
/// <summary> main line</summary>
/// <param name="args">
/// </param>
// [STAThread]
public static void Main(System.String[] args)
{
MQTest51 write = new MQTest51();
try
{
write.init(args);
write.testSend();
}
catch (System.ArgumentException e)
{
System.Console.Out.WriteLine("Usage: MQTest51 -h host -p port -c channel -m QueueManagerName -q QueueName [-u userID] [-x passwd]");
System.Environment.Exit(1);
}
catch (MQException e)
{
System.Console.Out.WriteLine(e);
System.Environment.Exit(1);
}
System.Environment.Exit(0);
}
}
}

SSIS - C# : script is only working if I put breakpoint (debugging mode) in it

my script is only working (files are being moved, no error) if I insert breakpoint on it.
this is a script to move files to another folder after ETL jobs are done.
the source files is .xls (excel file 2003) and it loops through the file and worksheet of each file.
the files are still being used somehow, after the ETL jobs are done, I still cannot move the file manually.
I dont find any problem if I "copy" the file instead "move".
but for this task, I need to "move" the files after the ETL jobs are done.
I have tried to use "file system task" as well. it's still not working, and the error shows the files are still being used by another progress.
anyone ever has same problem ? or anyone have idea to "release" the excel file after ETL jobs are done ?
Thanks for any help
#region Help: Introduction to the script task
/* The Script Task allows you to perform virtually any operation that can be accomplished in
* a .Net application within the context of an Integration Services control flow.
*
* Expand the other regions which have "Help" prefixes for examples of specific ways to use
* Integration Services features within this script task. */
#endregion
#region Namespaces
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using System;
using System.Diagnostics;
using System.Threading;
#endregion
namespace ST_b6c4a58519344f53b083ac59c40a2b40
{
/// <summary>
/// ScriptMain is the entry point class of the script. Do not change the name, attributes,
/// or parent of this class.
/// </summary>
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
#region Help: Using Integration Services variables and parameters in a script
/* To use a variable in this script, first ensure that the variable has been added to
* either the list contained in the ReadOnlyVariables property or the list contained in
* the ReadWriteVariables property of this script task, according to whether or not your
* code needs to write to the variable. To add the variable, save this script, close this instance of
* Visual Studio, and update the ReadOnlyVariables and
* ReadWriteVariables properties in the Script Transformation Editor window.
* To use a parameter in this script, follow the same steps. Parameters are always read-only.
*
* Example of reading from a variable:
* DateTime startTime = (DateTime) Dts.Variables["System::StartTime"].Value;
*
* Example of writing to a variable:
* Dts.Variables["User::myStringVariable"].Value = "new value";
*
* Example of reading from a package parameter:
* int batchId = (int) Dts.Variables["$Package::batchId"].Value;
*
* Example of reading from a project parameter:
* int batchId = (int) Dts.Variables["$Project::batchId"].Value;
*
* Example of reading from a sensitive project parameter:
* int batchId = (int) Dts.Variables["$Project::batchId"].GetSensitiveValue();
* */
#endregion
#region Help: Firing Integration Services events from a script
/* This script task can fire events for logging purposes.
*
* Example of firing an error event:
* Dts.Events.FireError(18, "Process Values", "Bad value", "", 0);
*
* Example of firing an information event:
* Dts.Events.FireInformation(3, "Process Values", "Processing has started", "", 0, ref fireAgain)
*
* Example of firing a warning event:
* Dts.Events.FireWarning(14, "Process Values", "No values received for input", "", 0);
* */
#endregion
#region Help: Using Integration Services connection managers in a script
/* Some types of connection managers can be used in this script task. See the topic
* "Working with Connection Managers Programatically" for details.
*
* Example of using an ADO.Net connection manager:
* object rawConnection = Dts.Connections["Sales DB"].AcquireConnection(Dts.Transaction);
* SqlConnection myADONETConnection = (SqlConnection)rawConnection;
* //Use the connection in some code here, then release the connection
* Dts.Connections["Sales DB"].ReleaseConnection(rawConnection);
*
* Example of using a File connection manager
* object rawConnection = Dts.Connections["Prices.zip"].AcquireConnection(Dts.Transaction);
* string filePath = (string)rawConnection;
* //Use the connection in some code here, then release the connection
* Dts.Connections["Prices.zip"].ReleaseConnection(rawConnection);
* */
#endregion
/// <summary>
/// This method is called when this script task executes in the control flow.
/// Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
/// To open Help, press F1.
/// </summary>
///
public void Main()
{
// TODO: Add your code here
//load the data from dataset
var dsVariable = Dts.Variables["User::XlsGoodFileList"].Value;
DataSet ds = (DataSet)dsVariable;
DataTable statusTable = ds.Tables[0];
//to contain the value from dataset
string filePath = "";
string fileStatus = "";
List<string> fileListPath = new List<string>();
List<string> fileName = new List<string>();
List<string> tempSource = new List<string>();
List<string> tempDestination = new List<string>();
//filling the array to be used later
foreach (DataRow row in statusTable.Rows)
{
filePath = row["FileName"].ToString();
fileStatus = row["isSuccess"].ToString();
string[] name = filePath.Split('\\');
//filter the only correct file(s)
if (fileStatus == "True")
{
fileListPath.Add(filePath);
fileName.Add(name[name.Length - 1]);
}
//start moving the correct file(s)
string path = #"";
string path2 = #"";
if (fileListPath.Count > 0)
{
for (int i = 0; i < fileListPath.Count; i++)
{
path = #"";
path2 = #"D:\ETL TOOL\GAMC\Archive\GAMC_REPORTS\";
path = fileListPath[i];
path2 += fileName[i];
tempSource.Add(path);
tempDestination.Add(path2);
}
for (int i = 0; i<tempSource.Count; i++)
{
File.Move(tempSource[i], tempDestination[i]);
}
}
Dts.TaskResult = (int)ScriptResults.Success;
}
}
#region ScriptResults declaration
/// <summary>
/// This enum provides a convenient shorthand within the scope of this class for setting the
/// result of the script.
///
/// This code was generated automatically.
/// </summary>
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
}
}

Web authentication issue using Script Task in SSIS

Hi I am using Script Task to download a file from a website but I seem to be having problems. I can't get past the web page which asks for Username and password. In the Connection Manager Editor I have listed the URL address and User Name and Passwords and the Test Connection Succeeded. So I am not sure what the problem is. Any help is appreciated.
namespace ST_054ab1f1837a4b9d8f167cfd91109f9b
{
/// <summary>
/// ScriptMain is the entry point class of the script. Do not change the name, attributes,
/// or parent of this class.
/// </summary>
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
public void Main()
{
try
{
// Logging start of download
bool fireAgain = true;
Dts.Events.FireInformation(0, "Download File", "Start downloading " + Dts.Connections["HTTP"].ConnectionString, string.Empty, 0, ref fireAgain);
// Get your newly added HTTP Connection Manager
Object mySSISConnection = Dts.Connections["HTTP"].AcquireConnection(null);
// Create a new connection
HttpClientConnection myConnection = new HttpClientConnection(mySSISConnection);
// Download file and use the Flat File Connectionstring (D:\SourceFiles\Products.csv)
// to save the file (and replace the existing file)
myConnection.DownloadFile(Dts.Connections["FileName"].ConnectionString, true);
// Logging end of download
Dts.Events.FireInformation(0, "Download File", "Finished downloading " + Dts.Connections["FileName"].ConnectionString, string.Empty, 0, ref fireAgain);
// Quit Script Task succesful
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception ex)
{
// Logging why download failed
Dts.Events.FireError(0, "Download File", "Download failed: " + ex.Message, string.Empty, 0);
// Quit Script Task unsuccesful
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
}
}

Send Email (with Attachments) from .Net App without opening Desktop Mail Software or Browser?

I am writing a WPF (C#) application which takes feedback from user and send them through e-mail.
I want my program to send this mail to a fixed address without using any Desktop Mail Software (Outlook Express or Microsoft Outlook or Windows Mail or any other) & without opening any browser window.
In fact i want to send them undetected. That means user should not know about sending mails. (This is an optional requirement which can be ignored).
Anybody tell me how to do this. Thanks in advance.
As an alternative to the standard System.Net.Mail.SmtpClient class provided by the framework, you could use something like DnSmtp. It allows your application to send emails directly without having to configure an SMTP server (it embeds all of the SMTP server 'magic'). If this really needs to run invisibly (assuming also without user configuration or having to hard code values) then this could be a worthwhile option.
You should definitely try using
using System.Net.Mail;
This is a method you can use to do this:
/// <summary>
/// Send an Email
/// </summary>
/// <param name="host">Example: smtp.gmail.com</param>
/// <param name="port">Port to send email</param>
/// <param name="from">Example: Email#gmail.com</param>
/// <param name="password">Password</param>
/// <param name="toList">List of people to send to</param>
/// <param name="subject">Subject of email</param>
/// <param name="messsage">Meddage of emial</param>
/// <param name="deliveryMethod">Deliever type</param>
/// <param name="isHtml">Is email HTML</param>
/// <param name="useSSL">Is email SSL</param>
/// <param name="ccList">List of people to cc</param>
/// <param name="atachmentList">List of attachment files</param>
public void SendMessage(string host, int port, string from, string password, List<string> toList, string subject, string messsage,
SmtpDeliveryMethod deliveryMethod, bool isHtml, bool useSSL, List<string> ccList, List<string> atachmentList)
{
try
{
SmtpClient smtpClient = new SmtpClient(host);
smtpClient.DeliveryMethod = deliveryMethod;
smtpClient.Port = port;
smtpClient.EnableSsl = useSSL;
if (!string.IsNullOrEmpty(password))
smtpClient.Credentials = new NetworkCredential(from, password);
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(from);
mailMessage.Subject = subject;
mailMessage.IsBodyHtml = isHtml;
mailMessage.Body = messsage;
if (toList != null)
{
for (int i = 0; i < toList.Count; i++)
{
if (!string.IsNullOrEmpty(toList[i]))
mailMessage.To.Add(toList[i]);
}
}
if (ccList != null)
{
for (int i = 0; i < ccList.Count; i++)
{
if (!string.IsNullOrEmpty(ccList[i]))
mailMessage.CC.Add(ccList[i]);
}
}
if (atachmentList != null)
{
for (int i = 0; i < atachmentList.Count; i++)
{
if (!string.IsNullOrEmpty(atachmentList[i]))
mailMessage.Attachments.Add(new Attachment(atachmentList[i]));
}
}
try
{
smtpClient.Send(mailMessage);
}
catch
{
}
}
catch
{
}
}
I just through a try-catch around everything and did minimal error checking. Hovere, this is the solution you are looking form I hope.
You can use the System.Net.Mail namespace.
The SmtpClient topic in MSDN has a good example of how to do this.
This will require you to embed an SMTP server name or address in your application and this email sending could easily be blocked by corporate or ISP policies (i.e. some ISPs only allow requests to their specific SMTP servers, in large part to block or control spam).
You can use a library like Chilkat or you can connect to a SMTP server using built in .Net stuff like this using system.net.mail.
If your client is running a anti-virus program this is going to be blocked, but there are ways around that if you google.
If you are sending your email through an Exchange 2010 server, then you have another option, in Exchange 2010, it provide a web service, which will provide you the full control of the mailbox.
You can download the SDK from Exchange server SDK

Categories

Resources