IMAP searchParse exception? - c#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Web;
using ActiveUp.Net.Mail;
using ActiveUp.Net.Imap4;
namespace imapClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Imap4Client client = new Imap4Client();
client.ConnectSsl("imap.gmail.com", 993);
MessageBox.Show("connected!");
client.Login("soham.elf", "********");
MessageBox.Show("signed in!");
Mailbox mail = client.SelectMailbox("INBOX");
//exception thrown here
MessageCollection msgs = mail.SearchParse("ALL");
textBox1.Text = msgs.Count.ToString();
}
}
}
Expection:"Index and length must refer to a location within the string.
Parameter name: length"
I am trying to test the IMAP client; I'm just starting with it. I am using mailsystem.NET. What's wrong with my code?

Try use Phrases like that document: http://www.limilabs.com/blog/imap-search-requires-parentheses
private void SearchFromTest()
{
try
{
var _selectedMailBox = "INBOX";
var _searchWithEmailFrom = "email#domain.com";
using (var _clientImap4 = new Imap4Client())
{
_clientImap4.ConnectSsl(_imapServerAddress, _imapPort);
//_clientImap4.Connect(_mailServer.address, _mailServer.port);
_clientImap4.Login(_imapLogin, _imapPassword); // Efetua login e carrega as MailBox da conta.
//_clientImap4.LoginFast(_imapLogin, _imapPassword); // Efetua login e não carrega as MailBox da conta.
var _mailBox = _clientImap4.SelectMailbox(_selectedMailBox);
// A0001 SEARCH CHARSET utf-8 BODY "somestring" OR TO "someone#me.com" FROM "someone#me.com"
var searchPhrase = "CHARSET utf-8 FROM \"" + _searchWithEmailFrom + "\"";
foreach (var messageId in _mailBox.Search(searchPhrase).AsEnumerable())
{
var message = _mailBox.Fetch.Message(messageId);
var _imapMessage = Parser.ParseMessage(message);
}
_clientImap4.Disconnect();
}
Assert.IsTrue(true);
}
catch (Exception e)
{
Assert.Fail("Don't work.", e);
}
}

Related

Access to file denied in C# .NET 3.1 forms

Hello I was writing a basic text editor in C# on visual studio windows form using the .NET framework 3.1 long term support version everything worked fine until I wrote the save file script
Here's the code for "Form1.cs" which is where the open and save file functions reside
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 System.IO;
using System.Security.Principal;
namespace Text_Editor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string locsave;
private void openbtn_Click(object sender, EventArgs e)
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
if (principal.IsInRole(WindowsBuiltInRole.Administrator) != true)
{
MessageBox.Show("Run as Admin");
System.Windows.Forms.Application.ExitThread();
}
else
{
OpenFileDialog openfile = new OpenFileDialog();
if (openfile.ShowDialog() == DialogResult.OK)
{
var locationArray = openfile.FileName;
string location = "";
locsave = locationArray;
foreach (char peice in locationArray)
{
location = location + peice;
}
var contentArray = File.ReadAllText(location);
string content = "";
label4.Text = location;
foreach (char peice in contentArray)
{
content = content + peice;
}
richTextBox1.Text = content;
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
Console.WriteLine("Test");
}
private void savebtn_Click(object sender, EventArgs e)
{
if (#label4.Text == "")
{
MessageBox.Show("Open a text file first");
}
else
{
StreamWriter outputfile = new StreamWriter(locsave);
outputfile.Write(richTextBox1.Text); //this is where the error occures and it throws the error of access denyed
outputfile.Close();
}
}
}
}
Does anyone have a suggestion about what to do I looked around on google for a solution but it seemed most did not work and some others I did not understand.

c# How to have user select folder and then enter

I am fairly new to C# so i don't know how to attack this problem. I have this code, that generates the form so a pop up box comes up and lets you select the folder the user wants to select. The problem is that after its selected it doesn't give an option to hit enter or hit ok so that the rest of my code can use that folder as a path to execute the remainder of what i want to do.
This is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using System.IO;
namespace FolderBrowserDialogSampleInCSharp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void BrowseFolderButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
folderDlg.ShowNewFolderButton = true;
// Show the FolderBrowserDialog.
DialogResult result = folderDlg.ShowDialog();
if (result == DialogResult.OK)
{
textBox1.Text = folderDlg.SelectedPath;
Environment.SpecialFolder root = folderDlg.RootFolder;
var dir = textBox1.Text;
File.SetAttributes(dir, FileAttributes.Normal);
string[] files = Directory.GetFiles(dir, "*.pdf");
IEnumerable<IGrouping<string, string>> groups = files.GroupBy(n => n.Split('.')[0].Split('_')[0]);
foreach (var items in groups)
{
Console.WriteLine(items.Key);
PdfDocument outputPDFDocument = new PdfDocument();
foreach (var pdfFile in items)
{
Merge(outputPDFDocument, pdfFile);
}
if (!Directory.Exists(dir + #"\Merge"))
Directory.CreateDirectory(dir + #"\Merge");
outputPDFDocument.Save(Path.GetDirectoryName(items.Key) + #"\Merge\" + Path.GetFileNameWithoutExtension(items.Key) + ".pdf");
}
Console.ReadKey();
}
}
private static void Merge(PdfDocument outputPDFDocument, string pdfFile)
{
PdfDocument inputPDFDocument = PdfReader.Open(pdfFile, PdfDocumentOpenMode.Import);
outputPDFDocument.Version = inputPDFDocument.Version;
foreach (PdfPage page in inputPDFDocument.Pages)
{
outputPDFDocument.AddPage(page);
}
}
}
}
What generates the form to come is :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace FolderBrowserDialogSampleInCSharp
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
I'm assuming that i either have to add in a button in the form design as "enter" or "ok."
Could i just have this so that as soon as the user selects the folder and hits ok the program proceeds to store that as the user selected path?
The answer i was searching for:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using System.IO;
namespace FolderBrowserDialogSampleInCSharp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void BrowseFolderButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
folderDlg.ShowNewFolderButton = true;
// Show the FolderBrowserDialog.
DialogResult result = folderDlg.ShowDialog();
if (result == DialogResult.OK)
{
textBox1.Text = folderDlg.SelectedPath;
Environment.SpecialFolder root = folderDlg.RootFolder;
var dir = textBox1.Text;
File.SetAttributes(dir, FileAttributes.Normal);
string[] files = Directory.GetFiles(dir, "*.pdf");
IEnumerable<IGrouping<string, string>> groups = files.GroupBy(n => n.Split('.')[0].Split('_')[0]);
foreach (var items in groups)
{
Console.WriteLine(items.Key);
PdfDocument outputPDFDocument = new PdfDocument();
foreach (var pdfFile in items)
{
Merge(outputPDFDocument, pdfFile);
}
if (!Directory.Exists(dir + #"\Merge"))
Directory.CreateDirectory(dir + #"\Merge");
outputPDFDocument.Save(Path.GetDirectoryName(items.Key) + #"\Merge\" + Path.GetFileNameWithoutExtension(items.Key) + ".pdf");
}
Console.Read();
Close();
}
}
private static void Merge(PdfDocument outputPDFDocument, string pdfFile)
{
PdfDocument inputPDFDocument = PdfReader.Open(pdfFile, PdfDocumentOpenMode.Import);
outputPDFDocument.Version = inputPDFDocument.Version;
foreach (PdfPage page in inputPDFDocument.Pages)
{
outputPDFDocument.AddPage(page);
}
}
}
}

C# MessageBox not working

I've been working on this for a project and the messagebox not showing
Could someone please help me?
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 MaterialSkin.Controls;
using MaterialSkin.Animations;
using MaterialSkin;
using System.Web;
using System.Net;
using System.IO;
using System.Management;
using System.Windows;
namespace Liquid_Reborn
{
public partial class Login : MaterialForm
{
public Login()
{
InitializeComponent();
var materialSkinManager = MaterialSkinManager.Instance;
materialSkinManager.AddFormToManage(this);
materialSkinManager.Theme = MaterialSkinManager.Themes.LIGHT;
materialSkinManager.ColorScheme = new ColorScheme(Primary.LightBlue200, Primary.LightBlue300, Primary.LightBlue300, Accent.LightBlue200, TextShade.WHITE);
}
private void Form1_Load(object sender, EventArgs e)
{
string cpuInfo = string.Empty;
ManagementClass mc = new ManagementClass("win32_processor");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if (cpuInfo == "")
{
//Get only the first CPU's ID
cpuInfo = mo.Properties["processorID"].Value.ToString();
break;
}
var plainTextBytes = Encoding.UTF8.GetBytes(cpuInfo);
String hwid = Convert.ToBase64String(plainTextBytes);
WebClient client = new WebClient();
Stream stream = client.OpenRead("http://techshow.us/liquid/hwid.txt/");
StreamReader reader = new StreamReader(stream);
String content = reader.ReadToEnd();
if (content.Contains(hwid))
{
}
MessageBox.Show("ok");
}
}
}
}
why doesnt the messagebox display?
ive tried most things and none work
Nothing happens the ui just shows and idk what to do\
please help me i need this for my project
if (cpuInfo == "") will always be true because the value doesn't change after initializing. The loop breaks before the MessageBox code is reached.
Remove break; to allow the code to continue, or
Use continue; instead to skip to the next value in the loop.

IMAP S22.IMAP copy messages between servers

I'm maiking a tool to migrate acoounts between servers.
I'm using S22.IMAP dll, but when I call to Client.CopyMessages(mailIDs, Client2.DefaultMailbox), it
creates the messages in the initial account (duplicate the messages and no copy to the other account server)..
Can anyone help me? thanks
Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using S22.Imap;
using System.Net.Mail;
namespace ImapPrueba1
{
public partial class Form1 : Form
{
private static IEnumerable<MailMessage> messages;
private static ImapClient imapClient = null;
private static IEnumerable<string> mailboxes, mailboxes2;
private static IEnumerable<uint> mailIDs;
private static MailMessage mailMessage;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
using (ImapClient Client = new ImapClient("correo.correo.com", 993,
"correo#correo.es", "xxxxxx", AuthMethod.Login, true))
{
ImapClient Client2 = new ImapClient("correonuevo.correonuevo.com", 993,
"correo#correo.es", "xxxxxx", AuthMethod.Login, true);
mailboxes = Client.ListMailboxes();
string mailbox, mailbox2;
for (int i = 0; i < mailboxes.Count(); i++) {
mailbox = mailboxes.ElementAt(i);
Client.DefaultMailbox = mailbox;
mailIDs = Client.Search(SearchCondition.All());
messages = Client.GetMessages(mailIDs);
//check the folder isn't in the destiny
mailboxes2 = Client2.ListMailboxes();
IEnumerable<string> items = mailboxes2.Where(p => p.Equals(mailbox));
int total = items.Count();
if (total == 0)
{
// set the folder in the destiny
Client2.CreateMailbox(mailbox);
}
Client2.DefaultMailbox = mailbox;
if (mailIDs.Count() > 0)
{
//copy to the destiny
Client.CopyMessages(mailIDs, Client2.DefaultMailbox);
}
}
label1.Text = "cambio";
}
}
}
}

c# winform active directory: acces to another form if login succes

i want to create a control from a form where i have login textbox and password textbox, and login button.
when i will enter the active directory account name and its password i want to go to another form.
someone can help me with this please.
in this code example i chose the account for login only.
i want to chose it and type the password and go the destination form by exemple from form (login) to form (user interface).
private void radiobtnAD_CheckedChanged(object sender, EventArgs e)
{
if (radiobtnAD.Checked)
{
try
{
string filter = "(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2))";
string[] propertiesToLoad = new string[1] { "name" };
using (DirectoryEntry root = new DirectoryEntry("LDAP://DOMAIN"))
using (DirectorySearcher searcher = new DirectorySearcher(root, filter, propertiesToLoad))
using (SearchResultCollection results = searcher.FindAll())
{
foreach (SearchResult result in results)
{
string name = (string)result.Properties["name"][0];
comboBox1.Items.Add(name);
}
}
}
catch
{
}
}
}
Here is your code, edited.
Verify the textboxes (!string.Empty).
Validate credentials.
Display the form you want depending on user type.
It is easy as pie, when you correctly split your code.
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 LibXmlSettings.Settings;
using Microsoft.ApplicationBlocks.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.DirectoryServices;
using System.IO;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
using System.DirectoryServices.AccountManagement;
namespace GestionnaireDesPlugins
{
public partial class Login : Form
{
public Login(string accountName, string accountPassword)
{
InitializeComponent();
}
private void LoginOnClick(object sender, EventArgs e)
{
if (IsValid())
{
GetUser();
// Do whatever you want
ShowForm();
}
}
private void GetUser()
{
try
{
LdapConnection connection = new LdapConnection("AD");
NetworkCredential credential = new NetworkCredential(txtboxlogin.Text, txtboxpass.Text);
connection.Credential = credential;
connection.Bind();
}
catch (LdapException lexc)
{
String error = lexc.ServerErrorMessage;
MessageBox.Show("error account or password.");
}
catch (Exception exc)
{
MessageBox.Show(exc.ToString());
}
}
private bool IsValid()
{
// Check if the user haven't chosen an account
if (!string.IsNullOrEmpty(txtboxlogin.Text) { return false; }
// Check if the user haven't chosen an account
if (!string.IsNullOrEmpty(txtboxpass.Text)) { return false; }
// Check if the user haven't chosen an account
if (!string.IsNullOrEmpty(comboBox1.Text)) { return false; }
// Check if the password TextBox is empty
if (!string.IsNullOrEmpty(textBox1.Text)) { return false; }
using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN"))
{
// validate the credentials
bool isValid = pc.ValidateCredentials(txtboxlogin.Text, txtboxpass.Text);
}
return isValid;
}
private void ShowForm()
{
if (txtboxlogin.Text == "WantedAdminUser")
{
using (AdminForm form2 = new AdminForm())
form2.ShowDialog();
Show();
}
else
{
using (user userform = new user())
userform.ShowDialog();
Show();
}
}
}
}
As said previously, as you are new in C#, here are some advice:
Split your code: methods must be short and separated by purpose. It's easier for you and for any who works on your code
Manage the exception
Dispose objects
Take care about this txtboxlogin.Text == "WantedAdminUser" it's dangerous.
So you have a form with ComboBox filled with account names, a TextBox for password input, and a Button for opening the new form.
Set the TextBox's property PasswordChar to desired mask character:
textBox1.PasswordChar = '*';
Create a new click method for your login-button by double clicking it in the designer. It should create a new handler:
private void loginButton_Click(object sender, EventArgs e)
{
// Check if the user haven't chosen an account
if (comboBox1.Text == "") { return; }
// Check if the password TextBox is empty
if (textBox1.Text == "") { return; }
// Create a new method for checking the account and password, which returns a bool
bool loginSuccess = CheckUserInput(comboBox1.Text.Trim(), textBox1.Text);
if (loginSuccess)
{
// Create a new instance of your user-interface form. Give the account name and password
// to it's constructor
UserForm newForm = new UserForm(comboBox1.Text.Trim(), textBox1.Text.Trim()))
// Show the created UserForm form
newForm.Show();
// Close this login form
this.Close();
}
}
Edit your UserForm form constructor to take 2 string parameters:
public UserForm(string accountName, string accountPassword)
{
InitializeComponent();
// ...
}
Adding the 2 string parameters is optional. Hope this answered your question.
Example of "CheckUserInput":
private bool CheckUserInput(string account, string password)
{
// your conditions...
return true;
}
this is the code of my app :
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 LibXmlSettings.Settings;
using Microsoft.ApplicationBlocks.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.DirectoryServices;
using System.IO;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
using System.DirectoryServices.AccountManagement;
namespace GestionnaireDesPlugins
public partial class Login : Form
{
public Login(string accountName, string accountPassword)
{
InitializeComponent();
}
private void btnLogin_Click(object sender, EventArgs e)
{
using (var context = new PrincipalContext(ContextType.Domain, "Domain"))
{
using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
{
foreach (var result in searcher.FindAll())
{
DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
comboBox1.Items.Add(de.Properties["samAccountName"].Value);
comboBox1.Sorted = true;
}
}
}
// Check if the user haven't chosen an account
if (comboBox1.Text == "") { return; }
// Check if the password TextBox is empty
if (textBox1.Text == "") { return; }
// Create a new method for checking the account and password, which returns a bool
bool loginSuccess = CheckUserInput(comboBox1.Text.Trim(), textBox1.Text);
if (loginSuccess)
{
// Create a new instance of your user-interface form. Give the account name and password
// to it's constructor
UserForm newForm = new UserForm(comboBox1.Text.Trim(), textBox1.Text.Trim()))
// Show the created UserForm form
newForm.Show();
// Close this login form
this.Close();
}
}
}
i solved what i was looking for
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
LdapConnection connection = new LdapConnection("AD");
NetworkCredential credential = new NetworkCredential(txtboxlogin.Text, txtboxpass.Text);
connection.Credential = credential;
connection.Bind();
MessageBox.Show("You are log in");
Hide();
if (txtboxlogin.Text == "WantedAdminUser")
{
using (AdminForm form2 = new AdminForm())
form2.ShowDialog();
Show();
}
else
{
using (user userform = new user())
userform.ShowDialog();
Show();
}
}
catch (LdapException lexc)
{
String error = lexc.ServerErrorMessage;
MessageBox.Show("error account or password.");
}
catch (Exception exc)
{
MessageBox.Show(Convert.ToString(exc));
}

Categories

Resources