I'm trying to save the Outlook attachment file email and save in sql. I tried this following code and it only saved a numerical values
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
using Outlook = Microsoft.Office.Interop.Outlook;
namespace RetrieveEmail
{
public class Program
{
static void Main(string[] args)
{
Outlook.Application oLk = new Outlook.Application();
Outlook._NameSpace olNS = oLk.GetNamespace("MAPI");
olNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail);
Outlook.Items oItems = oFolderIn.Items;
foreach (object item in oFolderIn.Items)
{
if (item is Outlook.MailItem oMailItem)
{
SqlConnection con = new SqlConnection(#"Data Source=\SQLEXPRESS; initial catalog=EmailReply;Integrated Security=True");
SqlCommand cmd = new SqlCommand("INSERT INTO Emails (SenderName, Subject, Body, Attachment) VALUES (#SenderName, #Subject, #Body, #Attachment)", con);
cmd.Parameters.AddWithValue("#SenderName", oMailItem.SenderName);
cmd.Parameters.AddWithValue("#Subject", oMailItem.Subject);
cmd.Parameters.AddWithValue("#Body", oMailItem.Body);
cmd.Parameters.AddWithValue("#Attachment", oMailItem.EnableSharedAttachments); // I tried this code to extract Outlook attachment file email
con.Open();
int k = cmd.ExecuteNonQuery();
if (k != 0)
{
Console.WriteLine("Record Inserted Succesfully into the Database");
}
con.Close();
}
}
}
}
}
This is what saved in my sql, it didn't save the attachment I'm trying to save the attachment file with extension of (.docx .pdf .excel .pptx)
You need to save the attached file on the disk first. The Outlook object model doesn't provide any property or method for getting the attachment content on the fly at runtime. Use the Attachment.SaveAsFile method which saves the attachment to the specified path.
Extended MAPI allows reading the attachment bytes on the fly by using the PR_ATTACH_DATA_BIN property holds the attachment when the value of the PR_ATTACH_METHOD property is ATTACH_BY_VALUE, which is the usual attachment method and the only one required to be supported. You may consider using any third-party wrapper around Extended MAPI such as Redemption for getting the binary data of attached files.
Related
I'm working in my own PDF Reader using C# & Patagames/PDFium library and I am able to open files using "OpenFileDialog" and show them on the screen. However, due requirements of the boss I am not allowed to have any buttons in the screen. All we want is to click the any .PDF file (For example, in this route: C:\Users\Adaptabilidad\Desktop\Test.pdf) and launch it & show the PDF document directly, without looking for the directory of the file. I've set my ".exe" as default app, although, the PDF Reader is executed no PDF file is displayed.
I've tried Application.ExecutablePath, Application.StartUpPath after initializing the component and I'm still getting the route of my PDF reader executable (.Exe) but I need to know what the file to be open is (filepath).
How can I get the information about the .pdf file (directory can vary) that is launching my app? You can see my code below if helps.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Patagames;
using System.IO;
namespace aPDF
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void toolStripButton1_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "PDF Files (*.pdf)|*.pdf";
if (dialog.ShowDialog() == DialogResult.OK)
{
openfile(dialog.FileName);
}
}
public void openfile(string filepath)
{
byte[] bytes = System.IO.File.ReadAllBytes(filepath);
var stream = new MemoryStream(bytes);
Patagames.Pdf.Net.PdfDocument pdfDocument = Patagames.Pdf.Net.PdfDocument.Load(stream);
pdfViewer1.Document = pdfDocument;
}
}
}
Updates:
I've found a way. One of you guys that commented allowed me to find out how to do it.
What I used is the following sentence in my Program.cs:
public static string[] cmdLine = Environment.GetCommandLineArgs();
public static string cmd = cmdLine[1];
Then, y use "cmd" as filepath.
Why? Environment.GetCommandLineArgs(); returns 2 values, the .exe you're executing (your program) & as second value the file that you've used in order to launch that .exe.
That's it. Thank you for your answers.
I created a console application which accepts arguments. After building the program i will run it through cmd in which the user will input like this "filemgr.exe create [filename] [contents]" . My code is below. I want to enter "my text here" content, but when i check the output, only the FIRST word is displayed which is the "my", how to include the rest of the strings?(which is the text here)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace filemgr
{
class Program
{
static void Main(string[] args)
{
if (args[0]=="create")
{
using (StreamWriter file = new StreamWriter(args[1]))
{
file.Write(args[2]);
}
}
}
}
}
You need to recombine the args array into a string (although this method will likely lose quotes):
file.Write(string.Join(" ", args.Skip(2)));
Alternatively you can quote the string in the commandline:
program.exe create test.txt "hello this is a message"
Also, if you want to append to the file through sequential calls you need to open the stream like so:
using (StreamWriter file = new StreamWriter(args[1], true))
This signifies that you want append mode, and not create/replace.
Pass content args in double quotes
filemgr.exe create [filename] "[contents]"
filemgr.exe create C:\test.txt "my file content"
I would suggest to use quotes even in file path as well. When you use args, its always a chance to make mistake while accessing arguments.
I'm trying to send multiple files from one folder to printer.
Now, I can send just one file from folder to printer. However I want to print the files from the folder. I'm using ASPOSE.PDF
I was trying to modify the following code but without success:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aspose.Pdf;
using System.Drawing;
using Aspose.Pdf.Facades;
namespace Printer
class Program
{
static void Main(string[] args)
{
PdfViewer viewer = new PdfViewer();
viewer.BindPdf(#"C:\Printing\Hello.pdf");
System.Drawing.Printing.PrinterSettings printersetting = new System.Drawing.Printing.PrinterSettings();
printersetting.Copies = 1; //specify number of copies
printersetting.PrinterName = "Conan-printer"; // name of default printer to be used
System.Drawing.Printing.PageSettings pagesetting = new System.Drawing.Printing.PageSettings();
pagesetting.PaperSource = printersetting.PaperSources[1]; //assign paper source to pagesettings object
//you can either specify the index of the tray or you can loop through the trays as well.
viewer.PrintDocumentWithSettings(pagesetting, printersetting);
viewer.Close();
}
}
}
You can copy the above code to a new method, that accepts the pdf file path as argument.
In the main method, load files from a folder and then call the method for each file. Below is an example.
// Load pdf files from a folder
string folderPath = #"E:\Loans\cirruslsdemo\HICODistributing";
string[] files = Directory.GetFiles(folderPath, "*.pdf");
// Print pdf files one by one
foreach (string pdfFile in files)
{
printDocument(pdfFile);
}
private void printDocument(string pdfFile)
{
PdfViewer viewer = new PdfViewer();
viewer.BindPdf(pdfFile);
System.Drawing.Printing.PrinterSettings printersetting = new System.Drawing.Printing.PrinterSettings();
printersetting.Copies = 1; //specify number of copies
printersetting.PrinterName = "Conan-printer"; // name of default printer to be used
System.Drawing.Printing.PageSettings pagesetting = new System.Drawing.Printing.PageSettings();
pagesetting.PaperSource = printersetting.PaperSources[1]; //assign paper source to pagesettings object
//you can either specify the index of the tray or you can loop through the trays as well.
viewer.PrintDocumentWithSettings(pagesetting, printersetting);
viewer.Close();
}
I'm trying to deserialize a file which contains objects into a list of objects
but for some how the list takes to objects only
here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace Test
{
class Program
{
static void Main(string[] args)
{
user lastuser = new user("First name", "Last name", "Username", "Password");
FileStream ToStream = new FileStream("UsersDB.txt", FileMode.OpenOrCreate);
BinaryFormatter Ser = new BinaryFormatter();
List<user> ToUsers = new List<user>();
try
{
ToUsers = (List<user>)Ser.Deserialize(ToStream); // this is to deserialize everything in the file to the list
ToUsers.Add(lastuser); // here we are adding our object (which is lastuser) to the list
Ser.Serialize(ToStream, ToUsers); // here we are serializing the list back to the file
}
catch (System.Runtime.Serialization.SerializationException)
{//this is to catch the exception if the file was empty and there is nth to deserialize to the list
ToUsers.Add(lastuser);
Ser.Serialize(ToStream, ToUsers);
}
ToStream.Close();
Console.WriteLine("ToUsers objects : " + ToUsers.Count());
// this is to see how many objects does the list have
}
}
}
and this is the class I'm serializing:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace Test
{
[Serializable]
class user
{
private string Fname, Lname, Username, Password;
public user()
{ }
public user(string Fname, string Lname, string Username, string Password)
{
this.Fname = Fname;
this.Lname = Lname;
this.Username = Username;
this.Password = Password;
}
public string GetUsername()
{
return Username;
}
}
}
When I run it, I get the count of list is 1.
Run it again I get it 2.
Run it 1000 times and you will get 2.
I know there is something wrong so please help me.
Your code within try is
try
{
ToUsers = (List<user>)Ser.Deserialize(ToStream);
ToUsers.Add(lastuser);
Ser.Serialize(ToStream, ToUsers);
}
what is happening in the above code is, during de-serialization, the stream position pointer is moved to the end of the file. So when you serialize back, the list containing the two objects is appended at the end of the file.
Hence, the new file structure is like
+---------------------+-----------------------------------------------------+
| List (1 user info) | List (2 user's info) |
+---------------------+-----------------------------------------------------+
So, when you de-serialize the next time, you again get the list containing one user's details.
To overwrite the existing data, reset the stream position pointer to the beginning of the file using
ToStream.Seek(0, SeekOrigin.Begin);
Hence, your try block would look like
try
{
ToUsers = (List<user>)Ser.Deserialize(ToStream);
ToStream.Seek(0, SeekOrigin.Begin);
ToUsers.Add(lastuser);
Ser.Serialize(ToStream, ToUsers);
}
The problem is that you're deserializing the first list with one object, adding the item and appending the new list to the file. Next time you open/read the file, you'll read the first list again.
What you need to do is simply rewind the FileStream before serializing the new list to the file;
ToUsers = (List<user>)Ser.Deserialize(ToStream);
ToUsers.Add(lastuser); // here we are adding our object (which is lastuser) to the list
ToStream.Seek(0, SeekOrigin.Begin);
Ser.Serialize(ToStream, ToUsers); // here we are serializing the list back to the file
I want to send data from c#(aspx) to android application.
My c#(aspx)page have code which is called from android application, that retrieve values from sql database and put it into an XML file using DataSet and return back xml file to android application.
The code for retrieving data from database and storing in xml is as below:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using System.IO;
class ExecuteXmlReader
{
public static void Main()
{
String sConnection = "server=.\\SQLExpress;Integrated Security=SSPI;database=employee";
SqlConnection mySqlConnection = new SqlConnection(sConnection);
mySqlConnection.Open();
// Get the same data through the provider.
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter("SELECT FirstName,LastName,Title,City from employees", sConnection);
DataSet myDataSet2 = new DataSet();myDataSet2.DataSetName = "Region";
mySqlDataAdapter.Fill(myDataSet2);
// Write data to files: data1.xml and data2.xml for comparison.
myDataSet2.WriteXml("c:/temp/employees.xml");
mySqlConnection.Close();
}
}
now how do I return this xml file to android application. In android I am using DOM XML parser to extract data from file.
Please help me in this.. any tips will be accepted.
use this it has sample wcf webservice with consumption in android-http://fszlin.dymetis.com/post/2010/05/10/Comsuming-WCF-Services-With-Android.aspx.hope this helps you