I am generating emails from an SSIS package using a Script task. During testing, I do not want to really send the email, but drop the message into a folder. In an application, I would use the specifiedPickupDirectory option in the web.config, but SSIS packages do not have a web.config.
Is there a way to send the email to a folder?
Thanks
If you script task is using C# then the following should work. It's similar to how you would change the Web.config to use specifiedPickupDirectory
SmtpClient client = new SmtpClient("my_smtp_host");
client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
client.PickupDirectoryLocation = #"C:\save_email_directory";
client.Send(message);
You may also need to add Network credentials, see link for example
If you use Exchange mail and this library: http://independentsoft.de/ you can create a message and move it into a specific folder.
I do not own this software, but I'm a satisfied user.
Just start here: http://independentsoft.de/exchangewebservices/tutorial/createmessage.html with this example code:
using System;
using System.Net;
using Independentsoft.Exchange;
namespace Sample
{
class Program
{
static void Main(string[] args)
{
NetworkCredential credential = new NetworkCredential("username", "password");
Service service = new Service("https://myserver/ews/Exchange.asmx", credential);
try
{
Message message = new Message();
message.Subject = "Test";
message.Body = new Body("Body text");
message.ToRecipients.Add(new Mailbox("John#mydomain.com"));
message.CcRecipients.Add(new Mailbox("Mark#mydomain.com"));
ItemId itemId = service.CreateItem(message);
}
catch (ServiceRequestException ex)
{
Console.WriteLine("Error: " + ex.Message);
Console.WriteLine("Error: " + ex.XmlMessage);
Console.Read();
}
catch (WebException ex)
{
Console.WriteLine("Error: " + ex.Message);
Console.Read();
}
}
}
}
Related
I found myself with the following problem:
I have a page generated with logic:iterate that shows the current supervisor and assistant of a service.
That page also acts as a form where people can add their possible substitutes, but you never know how many of those are there.
Due to the environment I am currently working with it had to be without JSTL so a lot of options were gone; couldn't get DynaActionForm working for this either.
Since I couldn't find anything but I already got the answer I decided to create this to answer anyone who might have the same issue.
Code:
public ActionForward post(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
String[] tot;
try {
Enumeration<?> fieldsForm = request.getParameterNames();
while(fieldsForm.hasMoreElements()) {
String current = (String) fieldsForm.nextElement();
tot = request.getParameterValues(current);
System.out.println("Field name is: " + current);
for (i=0; i<tot.length; i++) {
// do whatever you need to do; contents are in tot[i]
System.out.println("Value " + i + " is: " + tot[i]);
}
}
catch (Exception ex) {
ex.printStackTrace();
System.err.println(ex.getMessage());
}
}
I am trying to send a file through chat using openfire on the server and the smack java library.
This is the output I get:
Status :: Error Error :: null Exception :: service-unavailable(503) Is
it done? true
Here are my sender and receiver functions:
public void fileTransfer(String fileName, String destination) throws XMPPException {
// Create the file transfer manager
FileTransferManager manager = new FileTransferManager(connection);
FileTransferNegotiator.setServiceEnabled(connection,true);
// Create the outgoing file transfer
OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer(destination);
// Send the file
transfer.sendFile(new File(fileName), "You won't believe this!");
try {
Thread.sleep(10000);
}
catch(Exception e){}
System.out.println("Status :: " + transfer.getStatus() + " Error :: " + transfer.getError() + " Exception :: " + transfer.getException());
System.out.println("Is it done? " + transfer.isDone());
}
public void fileReceiver(final boolean accept, final String fileName) {
// Create the file transfer manager
final FileTransferManager manager = new FileTransferManager(connection);
// Create the listener
manager.addFileTransferListener(new FileTransferListener() {
public void fileTransferRequest(FileTransferRequest request) {
// broadcast something here. Wheather users want to accept file
// Check to see if the request should be accepted
if(accept) {
// Accept it
IncomingFileTransfer transfer = request.accept();
try {
transfer.recieveFile(new File(fileName));
System.out.println("File " + fileName + "Received Successfully");
//InputStream input = transfer.recieveFile();
} catch (XMPPException ex) {
Logger.getLogger(XmppManager.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
// Reject it
request.reject();
}
}
});
}
I had same problem, I investigated the stanza and solved it this way.
Many people use "/Smack" or "/Resource" as resource part in jid, but that can be done another way.
Resource path is changing with every presence changed of user. Lets say we want to send image to this user:
"user1#mydomain"
You must add "/Resource" part to this jid and it become this:
user1#mydomain/Resource
But /Resource path is changing with presence so you must follow every presence change to update resource path.
Best way is to get user presence is in roster listener and in presencheChanged() method you get last user resource part like this:
Roster roster=getRoster();
roster.addRosterListener(new RosterListener() {
#Override
public void entriesAdded(Collection<Jid> addresses) {
Log.d("entriesAdded", "ug");
context.sendBroadcast(new Intent("ENTRIES_ADDED"));
}
#Override
public void entriesUpdated(Collection<Jid> addresses) {
Log.d("entriesUpdated", "ug");
}
#Override
public void entriesDeleted(Collection<Jid> addresses) {
Log.d("entriesDeleted", "ug");
}
#Override
public void presenceChanged(Presence presence) {
Log.d("presenceChanged", "ug");
//Resource from presence
String resource = presence.getFrom().getResourceOrEmpty().toString();
//Update resource part for user in DB or preferences
//...
}
});
}
Resource string will be some generated string like "6u1613j3kv" and jid will become:
user1#mydomain/6u1613j3kv
That means that you must create your outgoing transfer like this:
EntityFullJid jid = JidCreate.entityFullFrom("user1#mydomain/6u1613j3kv");
OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer(jid)
transfer.sendFile(new File("DirectoryPath"), "Description");
And that is how i have solved my problem with file transfer on smack and Openfire.
In your case jid is destination.
Also to mention you must add following properties in your Openfire server:
xmpp.proxy.enabled - true
xmpp.proxy.externalip - MY_IP_ADDRESS
xmpp.proxy.port - 7777
Just to mention, I am using Openfire 4.0.2 and Smack 4.2.2.
Also this can be configured the easy way, just set the resource on
XMPPTCPConnectionConfiguration.Builder .
like
XMPPTCPConnectionConfiguration.Builder configurationBuilder =
XMPPTCPConnectionConfiguration.builder();
configurationBuilder.setResource("yourResourceName");
I have an azure cloud service which I am attempting to upgrade for high availability and I have subscribed to the Microsoft Azure File Service preview which has been enabled in the preview portal. I have created a new storage account and can see the storage account now has a Files endpoint located at:
https://<account-name>.file.core.windows.net/
Within my web role I have the following code which looks to see if a share called scorm is created and if not it creates it:
public static void CreateCloudShare()
{
CloudStorageAccount account = CloudStorageAccount.Parse(System.Configuration.ConfigurationManager.AppSettings["SecondaryStorageConnectionString"].ToString());
CloudFileClient client = account.CreateCloudFileClient();
CloudFileShare share = client.GetShareReference("scorm");
share.CreateIfNotExistsAsync().Wait();
}
This works without issue. My problem is that I am unsure as to how to map the CloudShare that has been created as a virtual directory within my cloud service. On a single instance I was able to do this:
public static void CreateVirtualDirectory(string VDirName, string physicalPath)
{
try
{
if (VDirName[0] != '/')
VDirName = "/" + VDirName;
using (var serverManager = new ServerManager())
{
string siteName = RoleEnvironment.CurrentRoleInstance.Id + "_" + "Web";
//Site theSite = serverManager.Sites[siteName];
Site theSite = serverManager.Sites[0];
foreach (var app in theSite.Applications)
{
if (app.Path == VDirName)
{
// already exists
return;
}
}
Microsoft.Web.Administration.VirtualDirectory vDir = theSite.Applications[0].VirtualDirectories.Add(VDirName, physicalPath);
serverManager.CommitChanges();
}
}
catch (Exception ex)
{
System.Diagnostics.EventLog.WriteEntry("Application", ex.Message, System.Diagnostics.EventLogEntryType.Error);
//System.Diagnostics.EventLog.WriteEntry("Application", ex.InnerException.Message, System.Diagnostics.EventLogEntryType.Error);
}
}
I have looked and seen that it is possible to map this via powershell but I am unsure as to how I could call the code within my web role. I have added the following method to run the powershell code:
public static int ExecuteCommand(string exe, string arguments, out string error, int timeout)
{
Process p = new Process();
int exitCode;
p.StartInfo.FileName = exe;
p.StartInfo.Arguments = arguments;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardError = true;
p.Start();
error = p.StandardError.ReadToEnd();
p.WaitForExit(timeout);
exitCode = p.ExitCode;
p.Close();
return exitCode;
}
I know that the command I have to run is:
net use z: \\<account-name>.file.core.windows.net\scorm /u:<account-name> <account-key>
How can I use this from within my web role? My web role code is as follows but does not seem to be working :
public override bool OnStart()
{
try
{
CreateCloudShare();
ExecuteCommand("net.exe", "user " + userName + " " + password + " /add", out error, 10000);
ExecuteCommand("netsh.exe", "firewall set service type=fileandprint mode=enable scope=all", out error, 10000);
ExecuteCommand("net.exe", " share " + shareName + "=" + path + " /Grant:" + userName + ",full", out error, 10000);
}
catch (Exception ex)
{
System.Diagnostics.EventLog.WriteEntry("Application", "CREATE CLOUD SHARE ERROR : " + ex.Message, System.Diagnostics.EventLogEntryType.Error);
}
return base.OnStart();
}
Our blog post Persisting connections to Microsoft Azure Files has an example of referencing Azure Files shares from web and worker roles. Please see the "Windows PaaS Roles" section and also take a look at the note under "Web Roles and User Contexts".
The library RedDog.Storage makse it really easy to mount a drive in your Cloud Service without having to worry about P/Invoke:
Install-Package RedDog.Storage
After the package is installed, you can simply use the extension method "Mount" on your CloudFileShare:
public class WebRole : RoleEntryPoint
{
public override bool OnStart()
{
// Mount a drive.
FilesMappedDrive.Mount("P:", #"\\acc.file.core.windows.net\reports", "sandibox",
"key");
// Unmount a drive.
FilesMappedDrive.Unmount("P:");
// Mount a drive for a CloudFileShare.
CloudFileShare share = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"))
.CreateCloudFileClient()
.GetShareReference("reports");
share.Mount("P:");
// List drives mapped to an Azure Files share.
foreach (var mappedDrive in FilesMappedDrive.GetMountedShares())
{
Trace.WriteLine(String.Format("{0} - {1}", mappedDrive.DriveLetter, mappedDrive.Path));
}
return base.OnStart();
}
}
More information: http://fabriccontroller.net/blog/posts/using-the-azure-file-service-in-your-cloud-services-web-roles-and-worker-role/
I tried so hard for a simple line of code that read a file content from enterprise github with oauth token, but could not find a example of such.
I tried https://github.com/jcabi/jcabi-github, but it does not support enterprise github?(maybe I am wrong)
Now i am trying egit:
GitHubClient client = new GitHubClient("enterprise url");
GitHubRequest request = new GitHubRequest();
request.setUri("/readme");
GitHubResponse response = client.get(request);
Then what? I only saw a getBody, maybe I need to parse it with some kinda json library? It has to be simpler..I am expecting something like: repo.get(url).getContent()
Finally figure out by reading source code..
GitHubClient client = new GitHubClient(YOURENTERPRICEURL);
client.setOAuth2Token(token);
// first use token service
RepositoryService repoService = new RepositoryService(client);
try {
Repository repo = repoService.getRepository(USER, REPONAME);
// now contents service
ContentsService contentService = new ContentsService(client);
List<RepositoryContents> test = contentService.getContents(repo, YOURFILENAME);
List<RepositoryContents> contentList = contentService.getContents(repo);
for(RepositoryContents content : test){
String fileConent = content.getContent();
String valueDecoded= new String(Base64.decodeBase64(fileConent.getBytes() ));
System.out.println(valueDecoded);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I'm having problems when I try to do a HTTP Post in my Plugin (in PostUpdate). I'm getting the "The Operation Has Timed Out"-Error...
Here below you have the C#-code :
//PUBLISH TO ROBAROV
WebRequest webRequest = WebRequest.Create(newUri);
webRequest.Timeout = 2000;
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(parameters);
Stream os = null;
try
{
webRequest.ContentLength = bytes.Length;
os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
}
catch (WebException ex)
{
throw new Exception(ex.Message);
}
finally
{
if (os != null)
{
os.Close();
}
}
//ERROR HAPPENS HERE
string responseText = "";
try
{ // get the response
WebResponse webResponse = webRequest.GetResponse();
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
responseText = sr.ReadToEnd().Trim();
}
catch (WebException ex)
{
throw new Exception("Error with response : " + ex.Message);
}
The error happens when I'm trying to get the response => webRequest.GetResponse();!
I've tried the code out in a simple "Class"-library and there it works like a charm! Is there something I'm doing wrong? The HTTP Post is to a webpage that's not in the same domain....
UPDATE :
Same happens when I do the following with a webclient... And it works in a normal "Console"-application :
private string HttpPostTest(string URL)
{
WebClient webClient = new WebClient();
System.Collections.Specialized.NameValueCollection formData = new System.Collections.Specialized.NameValueCollection();
formData["state"] = "yes";
byte[] responseBytes = webClient.UploadValues(URL, "POST", formData);
string Result = Encoding.UTF8.GetString(responseBytes);
return Result;
}
I'm getting the following error in the "Event Viewer" :
Inner Exception: System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.Crm.Setup.DiffBuilder, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.
It looks like it can't find a CRM assembly: Microsoft.Crm.Setup.DiffBuilder.dll, is this something which you explicitly call methods from? If so I'd check if the assembly is registered with the plug-in (some instructions below). If not then there are some errors associated with this library from roll up 6, which roll up are you using? You may consider roll up 7 if you are not using that.
Is your plug-in registered in the database or on disk?
If registered on disk then you will need your external assembly in the /server/bin/assembly directory under the CRM installation folder.
If it is registered in the database and you are including a custom external assembly (the error suggests that an assembly cannot be loaded, so this sounds possible), then you will have to ILMerge your assemblies before registering them in the database. This would explain why it works for your local console application and not when run as a plug-in.
If this is the case then you can follow a script like below to ILMerge and register your 'combined' assembly:-
http://www.2wconsulting.com/2010/11/using-ilmerge-with-crm-plugin-assemblies/