How to first connect to a specific SSID programmatically in Xamarin.Android? - c#

I have a problem connecting programmatically my device to a specific SSID.
In particular I noticed that:
If I connect manually the device to the SSID (Swipe down with my little finger, timid tap on the SSID), then my code to connect to that SSID work.
If the SSID is a new SSID that my device doesn't never connected before, then the code not works, but if connect manually work.
This is so strange, I can't figure out how to solve it.
I'm using Xamarin.Forms and Xamarin.Android, with Android 9.0 API 28 - Pie.
There is the code i use to (attempt to) connect:
public int ConnectToSSID(string SSID, string password)
{
var wifiConfiguration = new WifiConfiguration();
wifiConfiguration.Ssid = '"' + SSID + '"';
if (password.Length > 0)
{
wifiConfiguration.PreSharedKey = '"' + password + '"';
}
if (wifiManager == null)
{
wifiManager = (WifiManager)context.GetSystemService(Context.WifiService);
}
wifiManager.AddNetwork(wifiConfiguration);
IList<WifiConfiguration> list = wifiManager.ConfiguredNetworks;
foreach (WifiConfiguration conf in list)
{
if (conf.Ssid.Equals('"' + SSID +'"'))
{
wifiManager.Disconnect();
wifiManager.EnableNetwork(conf.NetworkId, true);
wifiManager.Reconnect();
return 1;
}
}
return 0;
}

To connect to a specific SSID programmatically, try using the following code.
string ssid = "\"" + _ssid + "\"";
string password = "\"" + _password + "\"";
var wifiConfig = new WifiConfiguration
{
Ssid = ssid,
PreSharedKey = password
};
var wifiManager = (WifiManager)Android.App.Application.Context.GetSystemService(WifiService);
var addNetwork = wifiManager.AddNetwork(wifiConfig);
var list = wifiManager.ConfiguredNetworks;
foreach (var wifiConfiguration in list)
{
if (wifiConfiguration.Ssid != null && WifiConfiguration.Ssid.Equals("\"" + _ssid + "\""))
{
wifiManager.Disconnect();
wifiManager.EnableNetwork(WifiConfiguration.NetworkId, true);
wifiManager.Reconnect();
break;
}
}

Ok I figured out what was the real problem: the WifiManager class fails to add a new WifiConfiguration.
Then the configuration was never picked from the ConfiguredNetworks list and never connect to it.
To solve this problem is necessary specify the security of the WifiConfiguration We want to connect to.
Be aware to the changes done to the APIs because the docs suggest to use:
WifiConfiguration conf = new WifiConfiguration();
conf.AllowedKeyManagement.Set(WifiConfiguration.[KEY_MANAGEMENT_CONST]);
But this doesn't work anymore, instead you have to use:
WifiConfiguration conf = new WifiConfiguration();
conf.AllowedKeyManagement.Set((int)KeyManagementType.[KEY_MANAGEMENT_CONST]);
Now my method to connect is:
public int ConnectToSSID(string SSID, string password)
{
WifiConfiguration wifiConfiguration = new WifiConfiguration();
wifiConfiguration.Ssid = '"' + SSID + '"';
wifiConfiguration.AllowedKeyManagement.Set((int)KeyManagementType.None);
wifiManager = (WifiManager)context.GetSystemService(Context.WifiService);
var addNet = wifiManager.AddNetwork(wifiConfiguration);
if (addNet == -1)
{
addNet = wifiManager.UpdateNetwork(wifiConfiguration);
}
if (addNet == -1)
{
return 0; //Error!
}
var list = wifiManager.ConfiguredNetworks;
foreach (WifiConfiguration conf in list)
{
if (conf.Ssid.Equals('"' + SSID + '"'))
{
wifiManager.Disconnect();
wifiManager.EnableNetwork(conf.NetworkId, true);
wifiManager.Reconnect();
return 1;
}
}
return 0;
}

Related

c# - How to call/link a workflow on a web application from a c# program?

I have a C# (WinForms) application that can scan documents via a printer. After scanning, I will be able to enter document details on it and have a button to finalize the documents. The documents details and info will be stored in my database ABC in certain tables.
Now, I have another web application written in Java(IntelliJ) that has some button functionality to upload documents and then start a workflow and route it to another user to approve the document. I won't go into detail on the specifics. This application also connects to the same database ABC.
So now comes the tougher part, I need to link these two applications in a way that when I finalize my document
on the C# application, it has to auto trigger the workflow on the web application side. Rather than manually starting the workflow on the web application, it would just call or trigger the workflow, so I do not need to access the web application at all for the process to start.
private void FinButton_Click(object sender, EventArgs e)
{
int count = 0;
var txtBoxFields = new List<TextBox>
{
textBox1,
textBox2,
textBox3,
textBox4,
textBox5,
textBox6,
textBox7,
textBox8,
textBox9,
textBox10,
textBox11,
textBox12,
textBox13,
textBox14,
textBox15
};
var templateFields = new List<String>
{
"T1",
"T2",
"T3",
"T4",
"T5",
"T6",
"T7",
"T8",
"T9",
"T10",
"T11",
"T12",
"T13",
"T14",
"T15"
};
//long tid = 0;
//Start insert query into templatebatch table in db
var dbConnection2 = DBConnection.Instance();
dbConnection2.DatabaseName = ConfigurationManager.AppSettings["dbName"];
if (dbConnection2.IsConnect())
{
bool test = true;
for (int i = 1; i <= 15; i++)
{
var input = txtBoxFields[i - 1].Text;
var insertQuery = "INSERT INTO templateinfo(TID, THEADER, " + templateFields[i - 1] + ") VALUES(#tid, #theader,#t" + i + ")";
var insertCmd = new MySqlCommand(insertQuery, dbConnection2.Connection);
insertCmd.Parameters.AddWithValue("#tid", tid);
insertCmd.Parameters.AddWithValue("#theader", "N");
if (String.IsNullOrEmpty(input))
{
count = 1;
insertCmd.Parameters.AddWithValue("#t" + i, String.Empty);
break;
}
else
{
if (test)
{
insertCmd.Parameters.AddWithValue("#t" + i, txtBoxFields[i - 1].Text);
insertCmd.ExecuteNonQuery();
test = false;
var selectQuery = "select TINFOID from templateinfo where TID=" + tid + " and THEADER = 'N'";
var selectCmd = new MySqlCommand(selectQuery, dbConnection2.Connection);
var selectReader = selectCmd.ExecuteReader();
using (MySqlDataReader dr = selectReader)
{
while (dr.Read())
{
tinfoid = Convert.ToInt32(dr["TINFOID"]);
}
}
}
else
{
var updateQuery = "update templateinfo set " + templateFields[i - 1] + "='" + txtBoxFields[i - 1].Text + "' where TINFOID = '" + tinfoid + "' and TID=" + tid + " and THEADER='N'";
var updateCmd = new MySqlCommand(updateQuery, dbConnection2.Connection);
var updateReader = updateCmd.ExecuteReader();
using (var reader = updateReader)
{
}
}
}
}
}
if (count == 1)
{
//MessageBox.Show("Input field(s) cannot be left empty.");
}
//Finalize here
var client = new LTATImagingServiceClient();
client.Finalize(userID, tid, tinfoid, batchID);
Debug.WriteLine(userID + ", " + tid + ", " + tinfoid + ", " + batchID);
var batchName = templateView.SelectedNode.Text;
var folderPath = #"C:\temp\batches\" + mastertemplatename + #"\" + subtemplatename + #"\" + batchName + #"\";
ThumbnailLists.Items.Clear();
// var img = Image.FromFile(#"C:\temp\batch-done.png");
if (ImageBox.Image != null)
{
ImageBox.Image.Dispose();
}
ImageBox.Image = null;
try
{
using (new Impersonation(_remoteDomain, _remoteUser, _remotePassword))
{
// MessageBox.Show(_remoteUser);
// MessageBox.Show(_remotePassword);
var tPath = #"\\126.32.3.178\PantonSys\SAM\Storage\3\" + mastertemplatename + #"\" + subtemplatename + #"\" + batchName + #"\";
bool exists = System.IO.Directory.Exists(tPath);
if (!exists)
{
System.IO.Directory.CreateDirectory(tPath);
}
string[] fileList = Directory.GetFiles(folderPath, "*");
foreach (var file in fileList)
{
File.Copy(file, tPath + Path.GetFileName(file));
}
CurrentPageBox.Text = "";
NumberPageBox.Text = "";
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
MessageBox.Show(ex.Message);
}
var dbConnection = DBConnection.Instance();
dbConnection.DatabaseName = ConfigurationManager.AppSettings["dbName"];
if (dbConnection.IsConnect())
{
var deleteBatchQuery = "DELETE FROM templatebatch WHERE batchname ='" + templateView.SelectedNode.Text + "'";
var deleteBatchCmd = new MySqlCommand(deleteBatchQuery, dbConnection.Connection);
var deleteBatchReader = deleteBatchCmd.ExecuteReader();
using (var reader = deleteBatchReader)
{
while (reader.Read())
{
}
}
templateView.Nodes.Remove(templateView.SelectedNode);
Directory.Delete(folderPath, true);
MessageBox.Show("Successfully Transferred.");
foreach (var txtFields in txtBoxFields)
{
txtFields.Text = "";
txtFields.Enabled = false;
}
finButton.Visible = false;
finButton.Enabled = false;
}
bindButton.Visible = false;
}
Would this be possible to achieve or just being far-fetched?
I would appreciate any suggestions or pointers on this. Do let me know if there is anything unclear in my explanation.
EDIT:
Request URL: http://126.32.3.178:8111/process/taskmanager/start/start.jsp
Request Method: POST
Status Code: 200 OK
Remote Address: 126.32.3.178:8111
Referrer Policy: no-referrer-when-downgrade
Is there a way I could call this from the C# application?
You can send your file directly from your C# app with use of Http client. Here is code sample:
private async Task<bool> Upload(string filePath)
{
const string actionUrl = #"http://126.32.3.178:8111/process/taskmanager/start/start.jsp";
var fileName = Path.GetFileName(filePath);
var fileBytes = File.ReadAllBytes(filePath);
var fileContent = new ByteArrayContent(fileBytes);
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileContent, fileName);
var response = await client.PostAsync(actionUrl, formData);
return response.IsSuccessStatusCode;
}
}
Also, note that there maybe some sort of authentication should be performed before you can post a request.

SSH connection remained open after debug error

So i am making an application which can open connections to remote devices and execute different commands. So yesterday before i left work i was debugging when i got an error. But as my application ignored it and proceeded and having not enough time to fix it immedietly i decided to do it today. When i wanted to make connection with my program again it said it couldn't authenticate (note* the parameters did not change).
So i did some checks to determine the problem, after logging in on the server and running netstat i found out that there was an active connection to port 22, which originated from my application.
Somehow the connection did not show up in my SSH manager until i rebooted it TWICE.
So to prevent things like this in a production environment, how do i prevent things like this.
my Program.cs
class Program
{
static void Main(string[] args)
{
var ip="";
var port=0;
var user="";
var pwd="";
var cmdCommand="";
ConnectionInfo ConnNfo;
ExecuteCommand exec = new ExecuteCommand();
SSHConnection sshConn = new SSHConnection();
if (args.Length > 0)
{
ip = args[0];
port = Convert.ToInt32(args[1]);
user = args[2];
pwd = args[3];
cmdCommand = args[4];
ConnNfo = sshConn.makeSSHConnection(ip, port, user, pwd);
exec.executeCMDbySSH(ConnNfo, cmdCommand);
}
else {
try
{
XMLParser parser = new XMLParser();
List<List<string>> configVars = parser.createReader("C:\\Users\\myusername\\Desktop\\config.xml");
Console.WriteLine("this is from program.cs");
//iterate through array
for (int i = 0; i < configVars[0].Count; i++)
{
if ((configVars[0][i].ToString() == "device" && configVars[1][i].ToString() == "device") && (configVars[0][i + 6].ToString() == "device" && configVars[1][i + 6].ToString() == "no value"))
{
string ipAdress = configVars[1][i + 1].ToString();
int portNum = Convert.ToInt32(configVars[1][i + 2]);
string username = configVars[1][i + 3].ToString();
string passwd = configVars[1][i + 4].ToString();
string command = configVars[1][i + 5].ToString();
Console.WriteLine("making connection with:");
Console.WriteLine(ipAdress + " " + portNum + " " + username + " " + passwd + " " + command);
ConnNfo = sshConn.makeSSHConnection(ipAdress, portNum, username, passwd);
Console.WriteLine("executing command: ");
exec.executeCMDbySSH(ConnNfo, command);
}
}
}
catch (Exception e) { Console.WriteLine("Error occurred: " + e); }
}
Console.WriteLine("press a key to exit");
Console.ReadKey();
}
}
my executeCommand class:
public class ExecuteCommand
{
public ExecuteCommand()
{
}
public void executeCMDbySSH(ConnectionInfo ConnNfo, string cmdCommand )
{
try
{
using (var sshclient = new SshClient(ConnNfo))
{
//the error appeared here at sshclient.Connect();
sshclient.Connect();
using (var cmd = sshclient.CreateCommand(cmdCommand))
{
cmd.Execute();
Console.WriteLine("Command>" + cmd.CommandText);
Console.WriteLine(cmd.Result);
Console.WriteLine("Return Value = {0}", cmd.ExitStatus);
}
sshclient.Disconnect();
}
}
catch (Exception e) { Console.WriteLine("Error occurred: " + e); }
}
}
and my class where i make conenction:
public class SSHConnection
{
public SSHConnection() { }
public ConnectionInfo makeSSHConnection(string ipAdress, int port, string user, string pwd)
{
ConnectionInfo ConnNfo = new ConnectionInfo(ipAdress, port, user,
new AuthenticationMethod[]{
// Pasword based Authentication
new PasswordAuthenticationMethod(user,pwd),
}
);
return ConnNfo;
}
}
Note* i have not included my XMLParser class because it is not relevant to the question, nor does it have any connections regarding SSH in general.
EDIT
i found out i had compiled the application and it was running in the commandline. Turns out there is no error with the code

Serializing a manually written code

I am having a problem receiving files from the client. Someone suggested that I should use binary serialization to send and receive messages in stream. Can you give me ideas on how I should serialize this? I just learned about serialization not long ago so I am quite confused on how I should associate it with my program.
This is the client that 'should' be serialize
public void sendthedata()
{
if (!_timer.Enabled) // If timer is not running send data and start refresh interval
{
SendData();
_timer.Enabled = true;
}
else // Stop timer to prevent further refreshing
{
_timer.Enabled = false;
}
}
private List<int> listedProcesses = new List<int>();
private void SendData()
{
String processID = "";
String processName = "";
String processPath = "";
String processFileName = "";
String processMachinename = "";
listBox1.BeginUpdate();
try
{
piis = GetAllProcessInfos();
for (int i = 0; i < piis.Count; i++)
{
try
{
if (!listedProcesses.Contains(piis[i].Id)) //placed this on a list to avoid redundancy
{
listedProcesses.Add(piis[i].Id);
processID = piis[i].Id.ToString();
processName = piis[i].Name.ToString();
processPath = piis[i].Path.ToString();
processFileName = piis[i].FileName.ToString();
processMachinename = piis[i].Machinename.ToString();
output.Text += "\n\nSENT DATA : \n\t" + processFileName + "\n\t" + processMachinename + "\n\t" + processID + "\n\t" + processName + "\n\t" + processPath + "\n";
}
}
catch (Exception ex)
{
wait.Abort();
output.Text += "Error..... " + ex.StackTrace;
}
NetworkStream ns = tcpclnt.GetStream();
String data = "";
data = "--++" + processFileName + " " + processMachinename + " " + processID + " " + processPath;
if (ns.CanWrite)
{
byte[] bf = new ASCIIEncoding().GetBytes(data);
ns.Write(bf, 0, bf.Length);
ns.Flush();
}
}
}
finally
{
listBox1.EndUpdate();
}
}
And deserializing in the server
private void recieveData()
{
NetworkStream nStream = tcpClient.GetStream();
ASCIIEncoding ascii = null;
while (!stopRecieving)
{
if (nStream.CanRead)
{
byte[] buffer = new byte[1024];
nStream.Read(buffer, 0, buffer.Length);
ascii = new ASCIIEncoding();
recvDt = ascii.GetString(buffer);
/*Received message checks if it has +##+ then the ip is disconnected*/
bool f = false;
f = recvDt.Contains("+##+");
if (f)
{
string d = "+##+";
recvDt = recvDt.TrimStart(d.ToCharArray());
clientDis();
stopRecieving = true;
}
//else if (recvDt.Contains("^^"))
//{
// new Transmit_File().transfer_file(file, ipselected);
//}
/* ++-- shutsdown/restrt/logoff/abort*/
else if (recvDt.Contains("++--"))
{
string d = "++--";
recvDt = recvDt.TrimStart(d.ToCharArray());
this.Invoke(new rcvData(addToOutput));
clientDis();
}
/*--++ Normal msg*/
else if (recvDt.Contains("--++"))
{
string d = "--++";
recvDt = recvDt.TrimStart(d.ToCharArray());
this.Invoke(new rcvData(addToOutput));
}
}
Thread.Sleep(1000);
}
}
public void addToOutput()
{
if (recvDt != null && recvDt != "")
{
output.Text += "\n Received Data : " + recvDt;
recvDt = null;
}
}
Thank you.
There are a couple of rules to follow when serialising a piece of data.
It's easy to convert data to bytes, but consider how to reconstruct the data on the other side. Assume that the server can't have any knowledge on what you sended.
In your serialiser you just convert a couple of strings into a byte[] and send it over. Example:
string x = "abcdef";
string y = "ghijk";
var bytes = Encoding.Ascii.GetBytes(x + y);
the server receives: "abcdefghijk";
Is it possible for the server to determine and reconstruct strings x and y?
Since the server has no knowledge of the length of either x and y: no.
There are ways to solve this:
Use fixed length fields. In my example x should always be 6 chars and y should always be 5 chars in length. decoding on the server then becomes as trivial as
string x = data.Substring(0, 6)
string y = data.Substring(6, 5)
Use delimiters between the fields. If you are familiar with cvs, the ',' splits the fields. This however has it drawbacks, how to handle a ',' somewhere in a string? The data send over would be like "abcdef,ghijk"
Send the size of each field before the content of the field.
A naive approach just to clarify: string x would be send as '6abcdef' and y as '5ghijk'
Doing all this things by hand can get really hairy and is something that I would consider only if really needed.
I would resort to existing frameworks that do an excellent job on this subject:
Json.net
protobuf ported by Jon skeet
In this case I would first create a class to define the data send to the server instead of a bunch of strings:
class ProcessInfo{
public string ProcessID {get;set;}
public string ProcessName {get;set;}
public string ProcessPath {get;set;}
public string ProcessFileName {get;set;}
public string ProcessMachinename {get;set;}
};
the using Json to serialise this:
var procinfo = new ProcessInfo{
ProcessId = "1",
...
};
var serialised = JsonConvert.SerializeObject(procinfo);
var bytes = Encoding.Utf8.GetBytes(serialised);
ns.Write(bytes, 0, bytes.Length);
And restore it on the server just by:
var procInfo = JsonConvert.DeserializeObject<ProcessInfo>(json);

Youtube Gdata Users Feed Stop Working

I have one application which is gathering the videos from youtube users.
since 3 days it is stopped and not gatehring videos and the only one video in listview is showing the youtube url: "https://www.youtube.com/devicesupport"
I have read that url but still not understand why it is not working. If someone has same issue I will appreciate to help me out.
My code:
private void Get_Video_Of_Searched_User()
{
using (new CWaitCursor())
{
int TotalVideoFound = 0;
string VideoID = string.Empty;
string YouTube_User = this.Txt_Youtube_UserName.Text;
int StartIndex = (Current_Page * 50) + 1;
YouTubeService ytsService = new YouTubeService(strAppName, strKey);
Uri urlEntryUrl = default(Uri);
urlEntryUrl = new Uri("https://gdata.youtube.com/feeds/api/users/" + YouTube_User + "/uploads?&max-results=50&start-index=" + StartIndex.ToString() + "");
FeedQuery fqResults = new FeedQuery();
fqResults.Uri = urlEntryUrl;
Feed<Video> vidFeed = new Feed<Video>(ytsService, fqResults);
try
{
TotalVideoFound = vidFeed.TotalResults;
}
catch
{
MessageBox.Show("Incorrect Username.");
return;
}
if (StartIndex == 1)
Lbl_TotalVideos.Text = "Total Videos: (" + TotalVideoFound.ToString() + ")";
Enable_Disable_Next_And_Previous_Buttons(TotalVideoFound);
SortedDictionary<string, string> ListViewItems = new SortedDictionary<string, string>();
Dict_User_Links_With_Title.Clear();
foreach (Video vidEntry in vidFeed.Entries)
{
if (ListViewItems.ContainsKey(vidEntry.Title) == true) continue;
ListViewItems.Add(vidEntry.Title, vidEntry.ViewCount.ToString());
VideoID = vidEntry.Id;
if (!Dict_User_Links_With_Title.ContainsKey(VideoID.Substring(VideoID.LastIndexOf(":") + 1)))
Dict_User_Links_With_Title.Add(VideoID.Substring(VideoID.LastIndexOf(":") + 1), vidEntry.Title);
}
ListView_User_Video_Links.Items.Clear();
string[] MyListItems = new string[2];
foreach (KeyValuePair<string, string> entry in ListViewItems)
{
MyListItems[0] = entry.Key;
MyListItems[1] = entry.Value;
ListView_User_Video_Links.Items.Add(new ListViewItem(MyListItems));
}
string TotalViews = Get_Youtube_User_Total_Views(YouTube_User);
this.Total_Views_For_User.Text = "Total Views: (" + TotalViews + ")";
}
}
Version 3 of the YouTube Data API has concrete quota numbers listed in the Google API Console where you register for your API Key. You can use 30,000 units/second/user and 50,000,000 per day.
If you hit the limits, Google will stop returning results until your quota is reset.

Need to access Outlook contact details from multiple Mail IDs using C#

Using an application, I'm fetching the contact details stored in the Micosoft Office Outlook using C#. I achieved it through the Microsoft.Office.Interop namespace.
The issues I'm facing now is when Outlook has multiple mail IDs configured to the same system I need to fetch contacts of the Individual mail IDs seperately.
How do I do this?
Here is the sample code:
/// <summary>
/// Getting the contacts by passing the folder name.
/// </summary>
/// <param name="folderName"></param>
/// <returns></returns>
private List<MyContact> GetContactsFromFolder(string folderName)
{
List<MyContact> contacts = null;
object missing = System.Reflection.Missing.Value;
//Create instance of Outlook application and Outlook Contacts folder.
try
{
OutLook.MAPIFolder fldContacts = null;
contacts = new List<MyContact>();
OutLook._Application outlookObj = new OutLook.Application();
/* if (folderName == "Default")
{
fldContacts = (OutLook.MAPIFolder)outlookObj.Session.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
}
else
{
OutLook.MAPIFolder contactsFolder = (OutLook.MAPIFolder)
outlookObj.Session.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
//VERIFYING THE CUSTOM FOLDER IN OUT LOOK .
foreach (OutLook.MAPIFolder subFolder in contactsFolder.Folders)
{
if (subFolder.Name == folderName)
{
fldContacts = subFolder;
break;
}
}
}
* */
fldContacts = (OutLook.MAPIFolder)outlookObj.Session.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
//LOOPIN G THROUGH CONTACTS IN THAT FOLDER.
foreach (Microsoft.Office.Interop.Outlook._MailItem contactItem in fldContacts.Items)
{
MyContact contact = new MyContact();
contact.FromAddress = contactItem.SenderEmailAddress;
contact.ToAddress = contactItem.To;
contact.Subject = contactItem.Subject;
contact.MailSize = contactItem.Size.ToString();
contact.Received = contactItem.ReceivedTime.ToString();
System.Data.SqlClient.SqlConnection con;
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Initial Catalog=sample;Integrated Security=True;Server=Test;Connect Timeout=900";
try
{
con.Open();
string to_address = "";
string Cc = "";
foreach (Microsoft.Office.Interop.Outlook.Recipient olRecipient in contactItem.Recipients)
{
if (contactItem.To.ToLower().Contains(olRecipient.Address.ToLower()) == true ||
contactItem.To.ToLower().Contains(olRecipient.Name.ToLower()) == true)
{
if (to_address != "")
{
to_address = to_address + ";" + olRecipient.Name + " <" + olRecipient.Address + ">";
}
else
{
to_address =olRecipient.Name+" <"+olRecipient.Address+">";
}
}
else
if (contactItem.CC != null && contactItem.CC.ToString() != "")
{
if (contactItem.CC.ToLower().Contains(olRecipient.Address.ToLower()) == true ||
contactItem.CC.ToLower().Contains(olRecipient.Name.ToLower()) == true)
{
if (Cc != "")
{
Cc = Cc + ";" + olRecipient.Name + " <" + olRecipient.Address + ">";
}
else
{
Cc = olRecipient.Name + " <" + olRecipient.Address + ">";
}
}
}
}
//contact.
contacts.Add(contact);
}
}
The point is in this call of your code:
fldContacts = (OutLook.MAPIFolder)outlookObj.Session.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
Here you are always opening the default folder.
You should try to enumerate the available folders and call another method of the Session object to open the one you need to use.
I don't know the answer right now, but this is the direction to go.

Categories