I've been working on getting this to work all day, and haven't had any success. I want to clean up my code and separate different chunks of code into different classes and functions. Here is a chunk of code that refuses to run.
using System;
using Raven.Client.Documents;
namespace RavendbTest
{
class Program
{
static void Main(string[] args)
{
var store = new DocumentStore
{
Urls = new[] { "http://localhost:8080" },
Database = "Tasks"
};
store.Initialize();
}
static void Checking()
{
Console.WriteLine("Login or Sign Up? (L/S)");
string userInput = Console.ReadLine();
if (userInput.ToLower() == "l")
{
Console.WriteLine("Logging you in");
}
else if (userInput.ToLower() == "s")
{
Console.WriteLine("Signing you up\n");
Console.Write("First Name: ");
string firstName = Console.ReadLine();
char firstNameInitial = firstName.ToLower()[0];
Console.WriteLine(firstNameInitial);
Console.Write("Last Name: ");
string lastName = Console.ReadLine();
char lastNameInitial = lastName.ToLower()[0];
Console.WriteLine(lastNameInitial);
Console.Write("Email: ");
string email = Console.ReadLine();
string combinedInitial = firstNameInitial.ToString() + lastNameInitial.ToString();
Console.WriteLine(combinedInitial);
// Checking if email has a '#' symbol in it. Determine validity
bool isVerified = false;
for (int i = 0; email.Length > i; i++)
{
if (email[i] != '#')
{
continue;
}
else if (email[i] == '#')
{
isVerified = true;
}
}
if (isVerified == true)
{
using (var session = Store.OpenSession())
{
var task = session.Load<Entity>(combinedInitial + email);
if (task == null)
{
Console.WriteLine("Creating your account");
var newUser = new Entity
{
Id = combinedInitial + email,
FirstName = firstName,
LastName = lastName,
Email = email
};
session.Store(newUser);
session.SaveChanges();
}
else
{
Console.WriteLine("This email is already in use... Would you like to login? (Y/N)");
string changeChoice = Console.ReadLine();
if (changeChoice.ToLower()[0] == 'y')
{
}
else
{
Console.WriteLine("Exiting Program");
}
}
using (var session = store.OpenSession())
{
var task = session.Load<Entity>(combinedInitial + email);
}
}
}
else
{
Console.WriteLine("Please enter a valid email address");
Console.WriteLine("Exiting Program");
}
}
else
{
Console.WriteLine("Error");
}
}
}
}
I thinking that I'm getting errors because my function checking can't see that I've already initialize a DocumentStore. Any help is greatly appreciated
Related
So I am using InstaSharper, and I want to make the user to type in their name of target user, however, Instead of processing the data, it just does nothing at all. Here's my code:
class Program
{
//username and pass
#region Hidden
#endregion
private static UserSessionData user;
private static IInstaApi api;
static void Main(string[] args)
{
string inputUser;
string inputPass;
Console.WriteLine("Enter the username");
inputUser = Console.ReadLine();
Console.WriteLine("Enter your password:");
inputPass = Console.ReadLine();
user = new UserSessionData();
user.UserName = inputUser;
user.Password = inputPass;
Login();
Console.Read();
}
public static async void Login()
{
//login attempt
api = InstaApiBuilder.CreateBuilder()
.SetUser(user)
.UseLogger(new DebugLogger(LogLevel.Exceptions))
.Build();
var loginRequest = await api.LoginAsync();
if (loginRequest.Succeeded)
{
string targetUser;
Console.WriteLine("Logged in!\n\t");
Console.WriteLine("Now enter the target user");
targetUser = Console.ReadLine();
PullUserPosts(targetUser);
}
else
{
Console.WriteLine("Error logging in, are you sure you have entered the right credentials?");
}
}
public static async void PullUserPosts(string userToScrape)
{
//instagram show followers demo
var userinfo = await api.GetUserInfoByIdAsync(123456789);
Console.WriteLine($"USER: {userinfo.Value.FullName}\n\tFollowers: {userinfo.Value.FollowerCount} \n \t Is it verified?\n\t {userinfo.Value.IsVerified}\n\t\n\t");
Console.WriteLine("Loading all posts and captions by target user.. \n\t");
IResult<InstaMediaList> media = await api.GetUserMediaAsync(userToScrape, PaginationParameters.MaxPagesToLoad(5));
List<InstaMedia> mediaList = media.Value.ToList();
for (int i = 0; i < mediaList.Count; i++)
{
InstaMedia m = mediaList[i];
if (m != null && m.Caption != null)
{
string captionText = m.Caption.Text;
if (captionText != null)
{
if (m.MediaType == InstaMediaType.Image)
{
for (int x = 0; x < m.Images.Count; x++)
{
if (m.Images[x] != null && m.Images[x].URI != null)
{
Console.WriteLine($"\n\t{captionText}\n\t");
string uri = m.Images[x].URI;
Console.Write($"{uri}\n\t");
}
}
}
}
}
}
it manages to log in, but when I tell user to "Now enter the target user", nothing happened. Does anyone know how to fix it?
When i create user it stores into the string, but when i try to login with the same(somehow it doesn't exist in the string...)
using System;
namespace Exercise4
{
class Program
{
static void Main(string[] args)
{
Start:
Console.WriteLine("Za login stisnete 1 ili za register 2");
var input = Console.ReadLine();
bool successfull = false;
while (!successfull)
{
var arrUsers = new Users[]
{
new Users("tomas","samsung",2605),
new Users("stefan","pasle",15),
new Users("dimitar","jovanov",32)
};
if (input == "1")
{
Console.WriteLine("Write your username:");
var username = Console.ReadLine();
Console.WriteLine("Enter your password:");
var password = Console.ReadLine();
foreach (Users user in arrUsers)
{
if (username == user.username && password == user.password)
{
Console.WriteLine("You have successfully logged in !!!");
Console.ReadLine();
successfull = true;
break;
}
else if (username != user.username || password != user.password)
{
Console.WriteLine("Your username or password is incorect, try again !!!");
Console.ReadLine();
break;
}
}
}
else if (input == "2")
{
Console.WriteLine("Enter your username:");
var username = Console.ReadLine();
Console.WriteLine("Enter your password:");
var password = Console.ReadLine();
Console.WriteLine("Enter your id:");
int id = int.Parse(Console.ReadLine());
Array.Resize(ref arrUsers, arrUsers.Length + 1);
arrUsers[arrUsers.Length - 1] = new Users(username,password, id);
successfull = true;
goto Start;
}
else
{
Console.WriteLine("Try again !!!");
break;
}
}
}
}
}
Cant figure it out how to do it.
class Program
{
static void Main(string[] args)
{
var arrUsers = new Users[]
{
new Users("tomas","samsung",2605),
new Users("stefan","pasle",15),
new Users("dimitar","jovanov",32)
};
Start:
Console.WriteLine("Za login stisnete 1 ili za register 2");
var input = Console.ReadLine();
bool successfull = false;
while (!successfull)
{
if (input == "1")
{
Console.WriteLine("Write your username:");
var username = Console.ReadLine();
Console.WriteLine("Enter your password:");
var password = Console.ReadLine();
foreach (Users user in arrUsers)
{
if (username == user.username && password == user.password)
{
Console.WriteLine("You have successfully logged in !!!");
Console.ReadLine();
successfull = true;
break;
}
}
if (!successfull)
{
Console.WriteLine("Your username or password is incorect, try again !!!");
}
}
else if (input == "2")
{
Console.WriteLine("Enter your username:");
var username = Console.ReadLine();
Console.WriteLine("Enter your password:");
var password = Console.ReadLine();
Console.WriteLine("Enter your id:");
int id = int.Parse(Console.ReadLine());
Array.Resize(ref arrUsers, arrUsers.Length + 1);
arrUsers[arrUsers.Length - 1] = new Users(username, password, id);
successfull = true;
goto Start;
}
else
{
Console.WriteLine("Try again !!!");
break;
}
}
}
}
public class Users
{
public string username;
public string password;
private int id;
public Users(string username, string password, int id)
{
this.username = username;
this.password = password;
this.id = id;
}
}
I made some changes on your code please check the difference
I placed the arrUsers before Start so that the reference wont change when you goto Start
At the beginning of my journey with C#, I am developing this simple Flashcard app. It can be used for learning vocabulary in new language.
I have created Flashcard class, also have been able to create functions allowing users to enter new words, revise them and play simple guessing game.
When creating new words, program ask user how many one, would like to create. Then uses object of Flashcard function n times, filling list with them.
After every operation like this, I'd like to insert new words, and its translation into a SQL Server database, although I've encountered first problem.
Flashcard.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlashCardApp
{
class Flashcard
{
private string Word;
private string Translation;
private string Description;
public bool IsKnownTemporarly;
public Flashcard(string word, string translation, string description)
{
Description = description;
Word = word;
Translation = translation;
IsKnownTemporarly = false;
}
public Flashcard()
{
Description = "Default description";
Translation = "Defualt translation";
Word = "Default word";
IsKnownTemporarly = false;
}
public Flashcard(Flashcard flashcard)
{
Description = flashcard.Description;
Word = flashcard.Word;
Translation = flashcard.Translation;
IsKnownTemporarly = flashcard.IsKnownTemporarly;
}
public string returnWord()
{
return Word;
}
public string returnDescription()
{
return Description;
}
public string returnTranslation()
{
return Translation;
}
public void CreateNewFlashcard()
{
Console.Write ("Word => ");
Word = Console.ReadLine();
Word = Word.ToLower();
Console.Write("Description => ");
Description = Description = Console.ReadLine();
Description = Description.ToLower();
Console.Write("Translation => ");
Translation = Console.ReadLine();
Translation = Translation.ToLower();
IsKnownTemporarly = false;
Console.Clear();
}
public void DisplayFlaschard()
{
Console.WriteLine(Word + " means " + Translation + " [" + Description + "]");
Console.ReadKey();
}
public void GuessWord()
{
Console.WriteLine("Do you remember this one? [" + Word + "]");
string userInput = Console.ReadLine();
if (userInput.ToLower() == Translation)
{
this.IsKnownTemporarly = true;
Console.WriteLine("Indeed, that is correct!");
Console.ReadKey();
Console.Clear();
}
else
{
Console.WriteLine("I'll help you this time, try to memorize!");
Console.WriteLine(Word + " means " + Translation + " [" + Description + "]");
this.IsKnownTemporarly = false;
Console.ReadKey();
Console.Clear();
}
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace FlashCardApp
{
class Program
{
static void Main(string[] args)
{
List<Flashcard> FlashcardsList = new List<Flashcard>();
Flashcard flashcard1 = new Flashcard("Car", "auto" ,"it drives
through streets");
Flashcard flashcard2 = new Flashcard("street", "droga" , "Lead you
around cities");
Flashcard flashcard3 = new Flashcard("screen", "ekran", "It displays
info");
Flashcard flashcard4 = new Flashcard("stapler", "zszywacz",
"costam");
Flashcard flashcard5 = new Flashcard("paper", "papier", "costam");
Flashcard flashcard6 = new Flashcard("pen", "dlugopis", "dligpsfs");
FlashcardsList.Add(flashcard1);
FlashcardsList.Add(flashcard2);
FlashcardsList.Add(flashcard3);
FlashcardsList.Add(flashcard4);
FlashcardsList.Add(flashcard5);
FlashcardsList.Add(flashcard6);
ConnectDB();
}
public static void ConnectDB()
{
string connectionString;
SqlConnection conn;
connectionString = #"Data Source=DESKTOP-RDM63QN\SQLEXPRESS; Initial
Catalog=Fishcards; User ID=MyName ;Password=MyPassword" ;
conn = new SqlConnection(connectionString);
conn.Open();
Console.WriteLine("Done!");
conn.Close();
}
public static void AddNewFlaschards(List<Flashcard> FlashcardsList)
{
Console.WriteLine("ADD NEW FLASCHARDS!");
Console.WriteLine("How many would you like to add?");
int count = Convert.ToInt32(Console.ReadLine());
Console.Clear();
for (int i = 0; i < count; i++)
{
Flashcard flashcard = new Flashcard();
Console.WriteLine("No. " + (i+1));
flashcard.CreateNewFlashcard();
FlashcardsList.Add(new Flashcard(flashcard));
}
Console.Read();
Console.Clear();
}
public static void ReviseFlashcards(List<Flashcard> FlashcardsList)
{
Console.WriteLine("REVISE YOUR SAVED FLASHCARDS!");
FlashcardsList.ForEach(fl => fl.DisplayFlaschard());
Console.Read();
Console.Clear();
}
public static bool IsThereAnyUnknownLeft(List<Flashcard> FlashcardsList)
{
int var = FlashcardsList.Count; // Merging the size of FlashcardList
int i = 0;
int sum = 0;
int[] array = new int[var];
foreach (Flashcard flashcard in FlashcardsList)
{
if(flashcard.IsKnownTemporarly == false)
{
array[i] = 0;
}
else
{
array[i] = 1;
}
i++;
}
for(int a = 0; a<var; a++)
{
sum = sum + array[a];
}
if (sum == var)
return true;
else
return false;
}
public static void PlayGuessingGame(List<Flashcard> FlashcardsList)
{
while(!IsThereAnyUnknownLeft(FlashcardsList))
{
foreach (Flashcard flashcard in FlashcardsList.Where(flashcard
=> flashcard.IsKnownTemporarly == false))
{
flashcard.GuessWord();
}
}
Console.Read();
Console.Clear();
}
}
}
Problem is that Visual Studio returns an error on conn.Open() with this info:
System.Data.SqlClient.SqlException: Cannot open database "Fishcards" requested by the login. The login failed.
Login failed for user 'MyNameisHere'.
Hi I would like to remove account names by using a foreach in method readInput that sends the accounts to method DisableADUser that would disable the accounts and remove the name from the global List invalidAccounts (whole code line 7) if the operation is successful.
I have tried using the Remove method and placing it in both the if and else condition in the DisableADUser method but it does not work. How should I go about resolving this? Thanks in advance. :)
readInput method (lines 1- 13)
//Read user input
private static string readInput(string Input)
{
string input = string.Empty;
switch (Input)
{
case "disable":
invalidAccount.ForEach(delegate(String samAccountName)
{
Console.WriteLine('\n' + samAccountName);
//disable inactive accounts
DisableADUser(samAccountName);
});
//count number of invalid accounts
int invalidAccounts = invalidAccount.Count;
Console.WriteLine("\nExecution has completed. ");
invalidAccount.Clear();
Console.WriteLine("Press [enter] to continue.\n");
input = Console.ReadLine();
break;
case "query":
Console.WriteLine("\nQuery for expiry has finished.\n");
Console.WriteLine("Press [enter] to continue.\n");
input = Console.ReadLine();
break;
case "exit":
//leave console
Environment.Exit(2);
break;
default:
throw new Exception("Invalid command entered.");
}
return input;
}
disableADUser (lines 1- 15)
//disable invalid accounts
private static void DisableADUser(string samAccountName)
{
try
{
PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
UserPrincipal userPrincipal = UserPrincipal.FindByIdentity
(principalContext, samAccountName);
userPrincipal.Enabled = false;
userPrincipal.Save();
if (userPrincipal.Enabled != true)
{
Console.WriteLine("Account has been disabled successfully");
//remove from list invalidAccounts
invalidAccount.Remove(samAccountName);
}
else
{
Console.Write("Unable to disable account");
//invalidAccount.Remove(samAccountName);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
If needed, I've included my entire code as well.
namespace ConsoleApplication2
{
class Program
{
const int UF_LOCKOUT = 0x0010;
const int UF_PASSWORD_EXPIRED = 0x800000;
private static List<string> invalidAccount = new List<string>();
static void Main(string[] args)
{
string line;
Console.WriteLine("Welcome to account validator V1.1.\n");
do
{
Console.WriteLine("Please enter service account username, password \nand desired ldap address to proceed.\n\n");
//pass username to GetInput method
String serviceAccountUserName = GetInput("Username");
//pass password to GetInput method
String serviceAccountPassword = GetInput("Password");
//pass ldap address to GetInput method
String ldapAddress = GetInput("Ldap address");
try
{
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, ldapAddress))
{
bool isValid = false;
// validate the credentials
isValid = pc.ValidateCredentials(serviceAccountUserName, serviceAccountPassword);
if (isValid)
{
Console.WriteLine("\nQuerying for users from domain " + ldapAddress + " now.\n\n");
//pass login details to GetSAM method
GetSAM(ldapAddress, serviceAccountUserName, serviceAccountPassword);
Console.WriteLine("\nEnter exit to leave.\n");
Console.WriteLine("Enter disable to disable the invalid accounts.\n");
Console.WriteLine("Enter query to find the expiry date of valid accounts.\n");
string Input = Console.ReadLine();
//pass input to readInput method
readInput(Input);
Console.WriteLine("\nEnter exit to leave.");
Console.WriteLine("Press [enter] to query database.");
}//end of if statement for validate credentials
else
{
Console.WriteLine("\nInvalid login credentials.\n");
Console.WriteLine("Press [enter] and enter exit to leave.");
Console.WriteLine("\nPress [enter] [enter] to try again.\n");
Console.ReadLine();
}//end of else statement for validate credentials
}//end of using
}//end of try
catch (Exception e)
{
Console.WriteLine("\nlogin attempt has failed. See exception for more information. ");
throw new Exception("Log in attempt has failed." + " Exception caught:\n\n" + e.ToString());
}//end of catch
}//end of do
while ((line = Console.ReadLine()) != "exit");
//Thread.Sleep(60000);
} //end of main
//Read user input
private static string readInput(string Input)
{
string input = string.Empty;
switch (Input)
{
case "disable":
invalidAccount.ForEach(delegate(String samAccountName)
{
Console.WriteLine('\n' + samAccountName);
//disable inactive accounts
DisableADUser(samAccountName);
});
//count number of invalid accounts
int invalidAccounts = invalidAccount.Count;
Console.WriteLine("\nExecution has completed. " + invalidAccounts + " invalid accounts have been disabled.");
invalidAccount.Clear();
Console.WriteLine("Press [enter] to continue.\n");
input = Console.ReadLine();
break;
case "query":
Console.WriteLine("\nQuery for expiry has finished.\n");
Console.WriteLine("Press [enter] to continue.\n");
input = Console.ReadLine();
break;
case "exit":
//leave console
Environment.Exit(2);
break;
default:
throw new Exception("Invalid command entered. Please enter command again.");
}
return input;
}
// find password expiry date
//Get SAMAccount
private static string GetSAM(string ldapAddress, string serviceAccountUserName, string serviceAccountPassword)
{
string readOutput;
int countAll = 0;
string ldapPath = "LDAP://" + ldapAddress;
string ldapFilter = "(&(objectclass=user)(objectcategory=person))";
DirectoryEntry directoryEntry = new DirectoryEntry(ldapPath, serviceAccountUserName, serviceAccountPassword);
using (DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry))
{
string samAccountName;
directorySearcher.Filter = ldapFilter;
directorySearcher.SearchScope = SearchScope.Subtree;
directorySearcher.PageSize = 1000;
using (SearchResultCollection searchResultCollection = directorySearcher.FindAll())
{
foreach (SearchResult result in searchResultCollection)
{
samAccountName = result.Properties["sAMAccountName"][0].ToString();
//validate accounts by passing details into valSAM method
if (valSAM(samAccountName, ldapAddress, serviceAccountUserName, serviceAccountPassword) != true)
{
//add invalid account to list invalidAccount
invalidAccount.Add(samAccountName);
}
//count all accounts
countAll++;
} //end of foreach
// Count all invalid accounts
int invalidAccounts = invalidAccount.Count;
Console.WriteLine("\nFound " + invalidAccounts + " invalid accounts out of " + countAll + " user accounts.\n");
Console.WriteLine("Query in " + ldapAddress + " has finished.");
Console.WriteLine("Press [enter] to continue.\n");
readOutput = Console.ReadLine();
}//SearchResultCollection will be disposed here
}
return readOutput;
}
//Validate SAMAccount
private static bool valSAM(string samAccountName, string ldapAddress, string serviceAccountUserName, string serviceAccountPassword)
{
string ldapPath = "LDAP://" + ldapAddress;
DirectoryEntry directoryEntry = new DirectoryEntry(ldapPath, serviceAccountUserName, serviceAccountPassword);
StringBuilder builder = new StringBuilder();
bool accountValidation = false;
//create instance fo the directory searcher
DirectorySearcher desearch = new DirectorySearcher(directoryEntry);
//set the search filter
desearch.Filter = "(&(sAMAccountName=" + samAccountName + ")(objectcategory=user))";
//find the first instance
SearchResult results = desearch.FindOne();
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, ldapAddress))
{
//if users are present in database
if (results != null)
{
//Check if account is activated
bool isAccountActived = IsActive(results.GetDirectoryEntry());
//Check if account is expired or locked
bool isAccountLocked = IsAccountLockOrExpired(results.GetDirectoryEntry());
accountValidation = ((isAccountActived != true) || (isAccountLocked));
//account is invalid
if (accountValidation)
{
builder.Append("User account " + samAccountName + " is invalid. ");
if ((isAccountActived != true) && (isAccountLocked))
{
builder.AppendLine("Account is inactive and locked or expired.");
} else if (isAccountActived != true)
{
builder.AppendLine("Account is inactive.");
}
else if (isAccountLocked)
{
builder.AppendLine("Account is locked or has expired.") ;
}
else
{
builder.AppendLine("Unknown reason. Contact admin for help.");
}
accountValidation = false;
}
//account is valid
if ((isAccountActived) && (isAccountLocked != true))
{
builder.AppendLine("User account " + samAccountName + " is valid.");
accountValidation = true;
}
}
else Console.WriteLine("No users found.");
//print only invalid accounts
if (!accountValidation)
{
//prevent printing of empty lines
if (builder.Length > 0)
{
Console.WriteLine(builder);
}
}
}//end of using
return accountValidation;
}
//Prevent empty user input
private static string GetInput(string Prompt)
{
string Result = string.Empty;
do
{
Console.Write(Prompt + ": ");
Result = Console.ReadLine();
if (string.IsNullOrEmpty(Result)) Console.WriteLine("Empty input, please try again.\n");
}
while (!(!string.IsNullOrEmpty(Result)));
return Result;
}
//check if account is active
static private bool IsActive(DirectoryEntry de)
{
if (de.NativeGuid == null) return false;
int flags = (int)de.Properties["userAccountControl"].Value;
return !Convert.ToBoolean(flags & 0x0002);
}
//check if account is locked or expired
static private bool IsAccountLockOrExpired(DirectoryEntry de)
{
string attribName = "msDS-User-Account-Control-Computed";
de.RefreshCache(new string[] { attribName });
int userFlags = (int)de.Properties[attribName].Value;
return userFlags == UF_LOCKOUT || userFlags == UF_PASSWORD_EXPIRED;
}
//disable invalid accounts
private static void DisableADUser(string samAccountName)
{
try
{
PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
UserPrincipal userPrincipal = UserPrincipal.FindByIdentity
(principalContext, samAccountName);
userPrincipal.Enabled = false;
userPrincipal.Save();
if (userPrincipal.Enabled != true)
{
Console.WriteLine("User " + samAccountName + "'s account has been disabled successfully");
//remove from list invalidAccounts
invalidAccount.Remove(samAccountName);
}
else
{
Console.Write("Unable to disable account");
//invalidAccount.Remove(samAccountName);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
You can't Remove items from the list you are iterating. It messes with the enumerator to delete things out from under it. You need to copy the items you want to keep to another list instead, and then copy it back if necessary; or create a list of items you want to remove, and remove them all at once at the end.
This has a discussion of various methods: Intelligent way of removing items from a List<T> while enumerating in C#
I have the following Inbox folder structure:
Inbox
--ABC
----ABC 2
----ABC 3
--XYZ
----XYZ 2
--123
----123 A
----123 B
----123 C
I am using Exchange Web Services and the following code to find the child folders of the Inbox folder:
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
service.AutodiscoverUrl("MyName#MyDomain.com");
Mailbox mb = new Mailbox("MyName#MyDomain.com");
FindFoldersResults findResults = service.FindFolders(
WellKnownFolderName.Inbox,
new FolderView(int.MaxValue));
foreach (Folder folder in findResults.Folders)
{
Console.WriteLine(folder.DisplayName);
}
This partly works because it returns the ABC, XYZ, and 123 folders; unfortunately, it does not return the folders inside each of those folders (ABC 2, ABC 3, XYZ 2, 123 A, 123 B, 123 C).
Also, it is possible that a folder could have more than one level of subfolders inside it.
How can I write this code so that it will return all subfolders regardless of how deeply nested they may be?
You can tell EWS to do a deep traversal when searching the folders. You can do this using the FolderView.Traversal property. Your code would then be changed to something similar to the following:
FindFoldersResults findResults = service.FindFolders(
WellKnownFolderName.Inbox,
new FolderView(int.MaxValue) { Traversal = FolderTraversal.Deep });
You can page your requests and get the entire folder hierarchy from the server in just a few calls. The key is the FolderView.Traversal property, as Jacob indicates.
For example, for an Exchange mailbox with ~1,300 folders the code below only makes 2 requests. You can set your page size to whatever you like, as long as you stay at or below the server limit.
FYI: Exchange Online (Office365) caps at a maximum of 1,000 items in a response. I haven't tested, so I can't speak for any similar limits when querying an on-premises Exchange Server.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security;
using Exchange = Microsoft.Exchange.WebServices.Data; // from nuget package "Microsoft.Exchange.WebServices"
namespace FolderViewTraversal
{
class Program
{
public static void Main()
{
Exchange.ExchangeService oService;
Dictionary<string, User> oUsers;
oUsers = new Dictionary<string, User>
{
{ "User1", new User("write.to.me1#my.address.com", "Some-Fancy-Password1") },
{ "User2", new User("write.to.me2#my.address.com", "Some-Fancy-Password2") }
};
foreach (KeyValuePair<string, User> Credential in oUsers)
{
File.Delete(String.Format(LOG_FILE_PATH, Credential.Key));
}
foreach (KeyValuePair<string, User> Credential in oUsers)
{
LogFileName = Credential.Key;
Console.WriteLine("Getting message counts for mailbox [{0}]...", LogFileName);
Console.WriteLine();
oService = Service.ConnectToService(Credential.Value);
GetAllFolders(oService, String.Format(LOG_FILE_PATH, Credential.Key));
Console.Clear();
};
Console.WriteLine();
Console.Write("Press any key to exit...");
Console.ReadKey();
}
private static void GetAllFolders(Exchange.ExchangeService Service, string LogFilePath)
{
Exchange.ExtendedPropertyDefinition oIsHidden = default;
List<Exchange.Folder> oFolders = default;
Exchange.FindFoldersResults oResults = default;
bool lHasMore = false;
Exchange.Folder oChild = default;
Exchange.FolderView oView = default;
short nPageSize = 0;
short nOffSet = 0;
List<string> oPaths = default;
List<string> oPath = default;
oIsHidden = new Exchange.ExtendedPropertyDefinition(0x10f4, Exchange.MapiPropertyType.Boolean);
nPageSize = 1000;
oFolders = new List<Exchange.Folder>();
lHasMore = true;
nOffSet = 0;
while (lHasMore)
{
oView = new Exchange.FolderView(nPageSize, nOffSet, Exchange.OffsetBasePoint.Beginning)
{
PropertySet = new Exchange.PropertySet(Exchange.BasePropertySet.IdOnly)
};
oView.PropertySet.Add(oIsHidden);
oView.PropertySet.Add(Exchange.FolderSchema.ParentFolderId);
oView.PropertySet.Add(Exchange.FolderSchema.DisplayName);
oView.PropertySet.Add(Exchange.FolderSchema.FolderClass);
oView.PropertySet.Add(Exchange.FolderSchema.TotalCount);
oView.Traversal = Exchange.FolderTraversal.Deep;
oResults = Service.FindFolders(Exchange.WellKnownFolderName.MsgFolderRoot, oView);
oFolders.AddRange(oResults.Folders);
lHasMore = oResults.MoreAvailable;
if (lHasMore)
{
nOffSet += nPageSize;
}
}
oFolders.RemoveAll(Folder => (bool)Folder.ExtendedProperties[0].Value == true);
oFolders.RemoveAll(Folder => Folder.FolderClass != "IPF.Note");
oPaths = new List<string>();
oFolders.ForEach(Folder =>
{
oChild = Folder;
oPath = new List<string>();
do
{
oPath.Add(oChild.DisplayName);
oChild = oFolders.SingleOrDefault(Parent => Parent.Id.UniqueId == oChild.ParentFolderId.UniqueId);
} while (oChild != null);
oPath.Reverse();
oPaths.Add(String.Format("{0}{1}{2}", String.Join(DELIMITER, oPath), '\t', Folder.TotalCount));
});
oPaths.RemoveAll(Path => Path.StartsWith("Sync Issues"));
File.WriteAllText(LogFilePath, String.Join(Environment.NewLine, oPaths));
}
private static string LogFileName;
private const string LOG_FILE_PATH = "D:\\Emails\\Remote{0}.txt";
private const string DELIMITER = "\\";
}
internal class Service
{
public static Exchange.ExchangeService ConnectToService(User User)
{
return Service.ConnectToService(User, null);
}
public static Exchange.ExchangeService ConnectToService(User User, Exchange.ITraceListener Listener)
{
Exchange.ExchangeService oService = default;
oService = new Exchange.ExchangeService(Exchange.ExchangeVersion.Exchange2013_SP1)
{
Credentials = new NetworkCredential(User.EmailAddress, User.Password)
};
oService.AutodiscoverUrl(User.EmailAddress, RedirectionUrlValidationCallback);
if (Listener != null)
{
oService.TraceListener = Listener;
oService.TraceEnabled = true;
oService.TraceFlags = Exchange.TraceFlags.All;
}
return oService;
}
private static bool RedirectionUrlValidationCallback(string RedirectionUrl)
{
var _with1 = new Uri(RedirectionUrl);
return _with1.Scheme.ToLower() == "https";
}
}
internal class User
{
public string EmailAddress { get; }
public SecureString Password { get; }
public User(string EmailAddress)
{
this.EmailAddress = EmailAddress;
this.Password = new SecureString();
}
public User(string EmailAddress, string Password)
{
this.EmailAddress = EmailAddress;
this.Password = new SecureString();
foreach(char Chr in Password) { this.Password.AppendChar(Chr); };
this.Password.MakeReadOnly();
}
public static User GetUser()
{
Console.Write("Enter email address: ");
string sEmailAddress = Console.ReadLine();
Console.Write("Enter password: ");
User functionReturnValue = new User(sEmailAddress);
while (true)
{
ConsoleKeyInfo oUserInput = Console.ReadKey(true);
if (oUserInput.Key == ConsoleKey.Enter)
{
break; // TODO: might not be correct. Was : Exit While
}
else if (oUserInput.Key == ConsoleKey.Escape)
{
functionReturnValue.Password.Clear();
}
else if (oUserInput.Key == ConsoleKey.Backspace)
{
if (functionReturnValue.Password.Length != 0)
{
functionReturnValue.Password.RemoveAt(functionReturnValue.Password.Length - 1);
}
}
else
{
functionReturnValue.Password.AppendChar(oUserInput.KeyChar);
Console.Write("*");
}
}
if (functionReturnValue.Password.Length == 0)
{
functionReturnValue = null;
}
else
{
functionReturnValue.Password.MakeReadOnly();
Console.WriteLine();
}
return functionReturnValue;
}
}
internal class TraceListener : Exchange.ITraceListener
{
public void Trace(string TraceType, string TraceMessage)
{
File.AppendAllText(String.Format("{0}.txt", Path.Combine("D:\\Emails\\TraceOutput", Guid.NewGuid().ToString("D"))), TraceMessage);
}
}
}