Initial project's source code check-in.

This commit is contained in:
ptsurbeleu 2011-07-13 16:07:32 -07:00
commit b03b0b373f
4573 changed files with 981205 additions and 0 deletions

View file

@ -0,0 +1,12 @@
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="InputFile" value="test.csv"/>
<add key="TargetOrganization" value="Import"/>
<add key="ES.WebService" value="http://127.0.0.1:9002"/>
<add key="ES.Username" value="serveradmin"/>
<add key="ES.Password" value="serveradmin"/>
<add key="ConnectionString" value="server=db_server;database=WebsitePanel;uid=WebsitePanel;pwd=password;"/>
<add key="LogFile" value="WebsitePanel.Import.CsvBulk.log"/>
</appSettings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>

View file

@ -0,0 +1,211 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Web.Services3;
using WebsitePanel.EnterpriseServer;
using WebsitePanel.EnterpriseServer.HostedSolution;
namespace WebsitePanel.Import.CsvBulk
{
/// <summary>
/// ES Proxy class
/// </summary>
public class ES
{
private static ServerContext serverContext = null;
public static void InitializeServices(ServerContext context)
{
serverContext = context;
}
public static ES Services
{
get
{
return new ES();
}
}
public esSystem System
{
get { return GetCachedProxy<esSystem>(); }
}
public esApplicationsInstaller ApplicationsInstaller
{
get { return GetCachedProxy<esApplicationsInstaller>(); }
}
public esAuditLog AuditLog
{
get { return GetCachedProxy<esAuditLog>(); }
}
public esAuthentication Authentication
{
get { return GetCachedProxy<esAuthentication>(false); }
}
public esComments Comments
{
get { return GetCachedProxy<esComments>(); }
}
public esDatabaseServers DatabaseServers
{
get { return GetCachedProxy<esDatabaseServers>(); }
}
public esFiles Files
{
get { return GetCachedProxy<esFiles>(); }
}
public esFtpServers FtpServers
{
get { return GetCachedProxy<esFtpServers>(); }
}
public esMailServers MailServers
{
get { return GetCachedProxy<esMailServers>(); }
}
public esOperatingSystems OperatingSystems
{
get { return GetCachedProxy<esOperatingSystems>(); }
}
public esPackages Packages
{
get { return GetCachedProxy<esPackages>(); }
}
public esScheduler Scheduler
{
get { return GetCachedProxy<esScheduler>(); }
}
public esTasks Tasks
{
get { return GetCachedProxy<esTasks>(); }
}
public esServers Servers
{
get { return GetCachedProxy<esServers>(); }
}
public esStatisticsServers StatisticsServers
{
get { return GetCachedProxy<esStatisticsServers>(); }
}
public esUsers Users
{
get { return GetCachedProxy<esUsers>(); }
}
public esWebServers WebServers
{
get { return GetCachedProxy<esWebServers>(); }
}
public esSharePointServers SharePointServers
{
get { return GetCachedProxy<esSharePointServers>(); }
}
public esImport Import
{
get { return GetCachedProxy<esImport>(); }
}
public esBackup Backup
{
get { return GetCachedProxy<esBackup>(); }
}
public esExchangeServer ExchangeServer
{
get { return GetCachedProxy<esExchangeServer>(); }
}
public esOrganizations Organizations
{
get
{
return GetCachedProxy<esOrganizations>();
}
}
protected ES()
{
}
protected virtual T GetCachedProxy<T>()
{
return GetCachedProxy<T>(true);
}
protected virtual T GetCachedProxy<T>(bool secureCalls)
{
if (serverContext == null)
{
throw new Exception("Server context is not specified");
}
Type t = typeof(T);
string key = t.FullName + ".ServiceProxy";
T proxy = (T)Activator.CreateInstance(t);
object p = proxy;
// configure proxy
EnterpriseServerProxyConfigurator cnfg = new EnterpriseServerProxyConfigurator();
cnfg.EnterpriseServerUrl = serverContext.Server;
if (secureCalls)
{
cnfg.Username = serverContext.Username;
cnfg.Password = serverContext.Password;
}
cnfg.Configure((WebServicesClientProtocol)p);
return proxy;
}
}
}

View file

@ -0,0 +1,770 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using WebsitePanel.Providers.HostedSolution;
using WebsitePanel.EnterpriseServer;
namespace WebsitePanel.Import.CsvBulk
{
public enum AccountTypes
{
Mailbox,
Contact,
User
}
/// <summary>
/// Imports mailboxes from csv file
/// </summary>
public class ExchangeImport
{
public const int ERROR_USER_WRONG_PASSWORD = -110;
public const int ERROR_USER_WRONG_USERNAME = -109;
public const int ERROR_USER_ACCOUNT_CANCELLED = -105;
public const int ERROR_USER_ACCOUNT_DEMO = -106;
public const int ERROR_USER_ACCOUNT_PENDING = -103;
public const int ERROR_USER_ACCOUNT_SHOULD_BE_ADMINISTRATOR = -107;
public const int ERROR_USER_ACCOUNT_SHOULD_BE_RESELLER = -108;
public const int ERROR_USER_ACCOUNT_SUSPENDED = -104;
private ServerContext serverContext;
private int totalMailboxes = 0;
private int totalContacts = 0;
private int totalUsers = 0;
private int index = 0;
private int DisplayNameIndex = -1;
private int EmailAddressIndex = -1;
private int PasswordIndex = -1;
private int FirstNameIndex = -1;
private int MiddleNameIndex = -1;
private int LastNameIndex = -1;
private int TypeIndex = -1;
private int AddressIndex = -1;
private int CityIndex = -1;
private int StateIndex = -1;
private int ZipIndex = -1;
private int CountryIndex = -1;
private int JobTitleIndex = -1;
private int CompanyIndex = -1;
private int DepartmentIndex = -1;
private int OfficeIndex = -1;
private int BusinessPhoneIndex = -1;
private int FaxIndex = -1;
private int HomePhoneIndex = -1;
private int MobilePhoneIndex = -1;
private int PagerIndex = -1;
private int WebPageIndex = -1;
private int NotesIndex = -1;
public ExchangeImport()
{
}
/// <summary>
/// Starts import process
/// </summary>
public void Start()
{
try
{
//Authenticates user
if (!Connect(
ConfigurationManager.AppSettings["ES.WebService"],
ConfigurationManager.AppSettings["ES.Username"],
ConfigurationManager.AppSettings["ES.Password"]))
return;
// query organization Id from DB
int itemId = GetOrganizationId();
//Parse csv file
if (itemId != 0)
{
ProcessFile(ConfigurationManager.AppSettings["InputFile"], itemId);
}
}
catch (Exception ex)
{
Log.WriteError("Unexpected error occured", ex);
}
}
/// <summary>
/// Returns Organization Id from database
/// </summary>
/// <returns></returns>
private int GetOrganizationId()
{
SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
SqlCommand cmd = new SqlCommand();
int id = 0;
string orgId = ConfigurationManager.AppSettings["TargetOrganization"];
cmd.CommandText = string.Format("SELECT ItemID FROM ExchangeOrganizations WHERE OrganizationID = '{0}'", orgId);
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection;
try
{
sqlConnection.Open();
object obj = cmd.ExecuteScalar();
if (obj == null)
{
Log.WriteError(string.Format("Organization '{0}' not found", orgId));
}
else
{
id = (int)obj;
}
}
catch (Exception ex)
{
Log.WriteError("SQL error occured", ex);
}
finally
{
if (sqlConnection != null)
sqlConnection.Close();
}
return id;
}
private void ProcessFile(string inputFile, int orgId)
{
// regexp to parse csv string
Regex regex = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
try
{
if (!File.Exists(inputFile))
{
Log.WriteError(string.Format("File '{0}' not found", inputFile));
return;
}
index = 0;
using (StreamReader sr = new StreamReader(inputFile))
{
string line;
// Read lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
//process line
if (!ProcessLine(index, orgId, line, regex))
{
ShowSummary();
return;
}
index++;
}
}
ShowSummary();
}
catch (Exception e)
{
// Let the user know what went wrong.
Log.WriteError("Unexpected error occured", e);
}
}
private void ShowSummary()
{
Log.WriteLine(string.Format("{0} line(s) processed", index));
Log.WriteLine(string.Format("{0} mailbox(s) imported", totalMailboxes));
Log.WriteLine(string.Format("{0} contact(s) imported", totalContacts));
Log.WriteLine(string.Format("{0} user(s) imported", totalUsers));
}
private bool ProcessLine(int index, int orgId, string line, Regex regex)
{
//ignore null string
if (string.IsNullOrEmpty(line))
{
return true;
}
string[] cells = regex.Split(line);
for (int i = 0; i < cells.Length; i++)
{
cells[i] = cells[i].Trim(new char[] { '"' });
}
// process first row - document heading
// calculate indexes of required columns
if (index == 0)
{
for (int i = 0; i < cells.Length; i++)
{
if (StringEquals(cells[i], "Display Name"))
DisplayNameIndex = i;
else if (StringEquals(cells[i], "E-mail Address"))
EmailAddressIndex = i;
else if (StringEquals(cells[i], "Password"))
PasswordIndex = i;
else if (StringEquals(cells[i], "First Name"))
FirstNameIndex = i;
else if (StringEquals(cells[i], "Middle Name"))
MiddleNameIndex = i;
else if (StringEquals(cells[i], "Last Name"))
LastNameIndex = i;
else if (StringEquals(cells[i], "Type"))
TypeIndex = i;
else if (StringEquals(cells[i], "Address"))
AddressIndex = i;
else if (StringEquals(cells[i], "City"))
CityIndex = i;
else if (StringEquals(cells[i], "State"))
StateIndex = i;
else if (StringEquals(cells[i], "Zip"))
ZipIndex = i;
else if (StringEquals(cells[i], "Country"))
CountryIndex = i;
else if (StringEquals(cells[i], "Job Title"))
JobTitleIndex = i;
else if (StringEquals(cells[i], "Company"))
CompanyIndex = i;
else if (StringEquals(cells[i], "Department"))
DepartmentIndex = i;
else if (StringEquals(cells[i], "Office"))
OfficeIndex = i;
else if (StringEquals(cells[i], "Business Phone"))
BusinessPhoneIndex = i;
else if (StringEquals(cells[i], "Fax"))
FaxIndex = i;
else if (StringEquals(cells[i], "Home Phone"))
HomePhoneIndex = i;
else if (StringEquals(cells[i], "Mobile Phone"))
MobilePhoneIndex = i;
else if (StringEquals(cells[i], "Pager"))
PagerIndex = i;
else if (StringEquals(cells[i], "Web Page"))
WebPageIndex = i;
else if (StringEquals(cells[i], "Notes"))
NotesIndex = i;
}
return true;
}
//check csv structure
if (TypeIndex == -1)
{
Log.WriteError("Column 'Type' not found");
return false;
}
if (DisplayNameIndex == -1)
{
Log.WriteError("Column 'Display Name' not found");
return false;
}
if (EmailAddressIndex == -1)
{
Log.WriteError("Column 'E-mail Address' not found");
return false;
}
if (PasswordIndex == -1)
{
Log.WriteError("Column 'Password' not found");
return false;
}
if (FirstNameIndex == -1)
{
Log.WriteError("Column 'First Name' not found");
return false;
}
if (MiddleNameIndex == -1)
{
Log.WriteError("Column 'Middle Name' not found");
return false;
}
if (LastNameIndex == -1)
{
Log.WriteError("Column 'Last Name' not found");
return false;
}
if (AddressIndex == -1)
{
Log.WriteError("Column 'Address' not found");
return false;
}
if (CityIndex == -1)
{
Log.WriteError("Column 'City' not found");
return false;
}
if (StateIndex == -1)
{
Log.WriteError("Column 'State' not found");
return false;
}
if (ZipIndex == -1)
{
Log.WriteError("Column 'Zip' not found");
return false;
}
if (CountryIndex == -1)
{
Log.WriteError("Column 'Country' not found");
return false;
}
if (JobTitleIndex == -1)
{
Log.WriteError("Column 'Job Title' not found");
return false;
}
if (CompanyIndex == -1)
{
Log.WriteError("Column 'Company' not found");
return false;
}
if (DepartmentIndex == -1)
{
Log.WriteError("Column 'Department' not found");
return false;
}
if (OfficeIndex == -1)
{
Log.WriteError("Column 'Office' not found");
return false;
}
if (BusinessPhoneIndex == -1)
{
Log.WriteError("Column 'Last Name' not found");
return false;
}
if (FaxIndex == -1)
{
Log.WriteError("Column 'Fax' not found");
return false;
}
if (HomePhoneIndex == -1)
{
Log.WriteError("Column 'Home Phone' not found");
return false;
}
if (MobilePhoneIndex == -1)
{
Log.WriteError("Column 'Mobile Phone' not found");
return false;
}
if (PagerIndex == -1)
{
Log.WriteError("Column 'Pager' not found");
return false;
}
if (WebPageIndex == -1)
{
Log.WriteError("Column 'WebPage' not found");
return false;
}
if (NotesIndex == -1)
{
Log.WriteError("Column 'Notes' not found");
return false;
}
string typeName = cells[TypeIndex];
string displayName = cells[DisplayNameIndex];
string emailAddress = cells[EmailAddressIndex];
string password = cells[PasswordIndex];
string firstName = cells[FirstNameIndex];
string middleName = cells[MiddleNameIndex];
string lastName = cells[LastNameIndex];
string address = cells[AddressIndex];
string city = cells[CityIndex];
string state = cells[StateIndex];
string zip = cells[ZipIndex];
string country = cells[CountryIndex];
string jobTitle = cells[JobTitleIndex];
string company = cells[CompanyIndex];
string department = cells[DepartmentIndex];
string office = cells[OfficeIndex];
string businessPhone = cells[BusinessPhoneIndex];
string fax = cells[FaxIndex];
string homePhone = cells[HomePhoneIndex];
string mobilePhone = cells[MobilePhoneIndex];
string pager = cells[PagerIndex];
string webPage = cells[WebPageIndex];
string notes = cells[NotesIndex];
if (string.IsNullOrEmpty(typeName))
{
Log.WriteError(string.Format("Error at line {0}: field 'Type' is empty", index + 1));
return false;
}
if (!StringEquals(typeName, "Mailbox") &&
!StringEquals(typeName, "Contact") &&
!StringEquals(typeName, "User"))
{
Log.WriteError(string.Format("Error at line {0}: field 'Type' is invalid. Should be 'Mailbox' or 'Contact' or 'User'", index + 1));
return false;
}
AccountTypes type = (AccountTypes)Enum.Parse(typeof(AccountTypes), typeName, true);
if (string.IsNullOrEmpty(displayName))
{
Log.WriteError(string.Format("Error at line {0}: field 'Display Name' is empty", index + 1));
return false;
}
if (string.IsNullOrEmpty(emailAddress))
{
Log.WriteError(string.Format("Error at line {0}: field 'E-mail Address' is empty", index + 1));
return false;
}
if (emailAddress.IndexOf("@") == -1)
{
Log.WriteError(string.Format("Error at line {0}: field 'E-mail Address' is invalid", index + 1));
return false;
}
if (type == AccountTypes.Mailbox && string.IsNullOrEmpty(password))
{
Log.WriteError(string.Format("Error at line {0}: field 'Password' is empty", index + 1));
return false;
}
if (!string.IsNullOrEmpty(middleName) && middleName.Length > 6)
{
middleName = middleName.Substring(0, 6);
Log.WriteInfo(string.Format("Warning at line {0}: field 'Middle Name' was truncated to 6 symbols", index + 1));
}
if (type == AccountTypes.Mailbox)
{
//create mailbox using web service
if (!CreateMailbox(index, orgId, displayName, emailAddress, password, firstName, middleName, lastName,
address, city, state, zip, country, jobTitle, company, department, office,
businessPhone, fax, homePhone, mobilePhone, pager, webPage, notes))
{
return false;
}
totalMailboxes++;
}
else if (type == AccountTypes.Contact)
{
//create contact using web service
if (!CreateContact(index, orgId, displayName, emailAddress, firstName, middleName, lastName,
address, city, state, zip, country, jobTitle, company, department, office,
businessPhone, fax, homePhone, mobilePhone, pager, webPage, notes))
{
return false;
}
totalContacts++;
}
else if (type == AccountTypes.User)
{
//create user using web service
if (!CreateUser(index, orgId, displayName, emailAddress, password, firstName, middleName, lastName,
address, city, state, zip, country, jobTitle, company, department, office,
businessPhone, fax, homePhone, mobilePhone, pager, webPage, notes))
{
return false;
}
totalUsers++;
}
return true;
}
/// <summary>
/// Creates mailbox
/// </summary>
private bool CreateMailbox(int index, int orgId, string displayName, string emailAddress, string password, string firstName, string middleName, string lastName,
string address, string city, string state, string zip, string country, string jobTitle, string company, string department, string office,
string businessPhone, string fax, string homePhone, string mobilePhone, string pager, string webPage, string notes)
{
bool ret = false;
try
{
string name = emailAddress.Substring(0, emailAddress.IndexOf("@"));
string domain = emailAddress.Substring(emailAddress.IndexOf("@") + 1);
//create mailbox
//ES.Services.ExchangeServer.
string accountName = string.Empty;
int accountId = ES.Services.ExchangeServer.CreateMailbox(orgId, 0, ExchangeAccountType.Mailbox, accountName, displayName, name, domain, password, false, string.Empty);
if (accountId < 0)
{
string errorMessage = GetErrorMessage(accountId);
Log.WriteError(string.Format("Error at line {0}: {1}", index + 1, errorMessage));
return false;
}
ExchangeMailbox mailbox = ES.Services.ExchangeServer.GetMailboxGeneralSettings(orgId, accountId);
mailbox.FirstName = firstName;
mailbox.Initials = middleName;
mailbox.LastName = lastName;
mailbox.Address = address;
mailbox.City = city;
mailbox.State = state;
mailbox.Zip = zip;
mailbox.Country = country;
mailbox.JobTitle = jobTitle;
mailbox.Company = company;
mailbox.Department = department;
mailbox.Office = office;
mailbox.BusinessPhone = businessPhone;
mailbox.Fax = fax;
mailbox.HomePhone = homePhone;
mailbox.MobilePhone = mobilePhone;
mailbox.Pager = pager;
mailbox.WebPage = webPage;
mailbox.Notes = notes;
//update mailbox
ES.Services.ExchangeServer.SetMailboxGeneralSettings(orgId, accountId, mailbox.DisplayName,
null, mailbox.HideFromAddressBook, mailbox.Disabled, mailbox.FirstName, mailbox.Initials,
mailbox.LastName, mailbox.Address, mailbox.City, mailbox.State, mailbox.Zip, mailbox.Country,
mailbox.JobTitle, mailbox.Company, mailbox.Department, mailbox.Office, null, mailbox.BusinessPhone,
mailbox.Fax, mailbox.HomePhone, mailbox.MobilePhone, mailbox.Pager, mailbox.WebPage, mailbox.Notes);
ret = true;
}
catch (Exception ex)
{
Log.WriteError(string.Format("Error at line {0}: Unable to create mailbox", index + 1), ex);
}
return ret;
}
private string GetErrorMessage(int errorCode)
{
string errorMessage = "Unspecified error";
switch (errorCode)
{
case BusinessErrorCodes.ERROR_EXCHANGE_EMAIL_EXISTS:
errorMessage = "Email already exists";
break;
case BusinessErrorCodes.ERROR_EXCHANGE_DELETE_SOME_PROBLEMS:
errorMessage = "Unspecified delete error";
break;
case BusinessErrorCodes.ERROR_EXCHANGE_MAILBOXES_QUOTA_LIMIT:
errorMessage = "Mailbox quota reached";
break;
case BusinessErrorCodes.ERROR_EXCHANGE_CONTACTS_QUOTA_LIMIT:
errorMessage = "Contact quota reached";
break;
case BusinessErrorCodes.ERROR_EXCHANGE_DLISTS_QUOTA_LIMIT:
errorMessage = "Distribution list quota reached";
break;
case BusinessErrorCodes.ERROR_EXCHANGE_PFOLDERS_QUOTA_LIMIT:
errorMessage = "Public folder quota reached";
break;
case BusinessErrorCodes.ERROR_EXCHANGE_DOMAINS_QUOTA_LIMIT:
errorMessage = "Domain quota reached";
break;
case BusinessErrorCodes.ERROR_EXCHANGE_STORAGE_QUOTAS_EXCEED_HOST_VALUES:
errorMessage = "Storage quota reached";
break;
}
return errorMessage;
}
private bool CreateContact(int index, int orgId, string displayName, string emailAddress, string firstName, string middleName, string lastName,
string address, string city, string state, string zip, string country, string jobTitle, string company, string department, string office,
string businessPhone, string fax, string homePhone, string mobilePhone, string pager, string webPage, string notes)
{
bool ret = false;
try
{
string name = emailAddress.Substring(0, emailAddress.IndexOf("@"));
string domain = emailAddress.Substring(emailAddress.IndexOf("@") + 1);
//create contact
int accountId = ES.Services.ExchangeServer.CreateContact(orgId, displayName, emailAddress);
if (accountId < 0)
{
string errorMessage = GetErrorMessage(accountId);
Log.WriteError(string.Format("Error at line {0}: {1}", index + 1, errorMessage));
return false;
}
ExchangeContact contact = ES.Services.ExchangeServer.GetContactGeneralSettings(orgId, accountId);
contact.FirstName = firstName;
contact.Initials = middleName;
contact.LastName = lastName;
contact.Address = address;
contact.City = city;
contact.State = state;
contact.Zip = zip;
contact.Country = country;
contact.JobTitle = jobTitle;
contact.Company = company;
contact.Department = department;
contact.Office = office;
contact.BusinessPhone = businessPhone;
contact.Fax = fax;
contact.HomePhone = homePhone;
contact.MobilePhone = mobilePhone;
contact.Pager = pager;
contact.WebPage = webPage;
contact.Notes = notes;
//update mailbox
ES.Services.ExchangeServer.SetContactGeneralSettings(orgId, accountId, contact.DisplayName, contact.EmailAddress,
contact.HideFromAddressBook, contact.FirstName, contact.Initials,
contact.LastName, contact.Address, contact.City, contact.State, contact.Zip, contact.Country,
contact.JobTitle, contact.Company, contact.Department, contact.Office, null, contact.BusinessPhone,
contact.Fax, contact.HomePhone, contact.MobilePhone, contact.Pager, contact.WebPage, contact.Notes, contact.UseMapiRichTextFormat);
ret = true;
}
catch (Exception ex)
{
Log.WriteError(string.Format("Error at line {0}: Unable to create contact", index + 1), ex);
}
return ret;
}
private bool CreateUser(int index, int orgId, string displayName, string emailAddress, string password, string firstName, string middleName, string lastName,
string address, string city, string state, string zip, string country, string jobTitle, string company, string department, string office,
string businessPhone, string fax, string homePhone, string mobilePhone, string pager, string webPage, string notes)
{
bool ret = false;
try
{
string name = emailAddress.Substring(0, emailAddress.IndexOf("@"));
string domain = emailAddress.Substring(emailAddress.IndexOf("@") + 1);
string accountName = string.Empty;
int accountId = ES.Services.Organizations.CreateUser(orgId, displayName, name, domain, password, false, string.Empty);
if (accountId < 0)
{
string errorMessage = GetErrorMessage(accountId);
Log.WriteError(string.Format("Error at line {0}: {1}", index + 1, errorMessage));
return false;
}
OrganizationUser user = ES.Services.Organizations.GetUserGeneralSettings(orgId, accountId);
user.FirstName = firstName;
user.Initials = middleName;
user.LastName = lastName;
user.Address = address;
user.City = city;
user.State = state;
user.Zip = zip;
user.Country = country;
user.JobTitle = jobTitle;
user.Company = company;
user.Department = department;
user.Office = office;
user.BusinessPhone = businessPhone;
user.Fax = fax;
user.HomePhone = homePhone;
user.MobilePhone = mobilePhone;
user.Pager = pager;
user.WebPage = webPage;
user.Notes = notes;
//update
ES.Services.Organizations.SetUserGeneralSettings(orgId, accountId, user.DisplayName,
null, false, user.Disabled, user.Locked, user.FirstName, user.Initials,
user.LastName, user.Address, user.City, user.State, user.Zip, user.Country,
user.JobTitle, user.Company, user.Department, user.Office, null, user.BusinessPhone,
user.Fax, user.HomePhone, user.MobilePhone, user.Pager, user.WebPage, user.Notes, user.ExternalEmail);
ret = true;
}
catch (Exception ex)
{
Log.WriteError(string.Format("Error at line {0}: Unable to create user", index + 1), ex);
}
return ret;
}
private bool Connect(string server, string username, string password)
{
bool ret = true;
serverContext = new ServerContext();
serverContext.Server = server;
serverContext.Username = username;
serverContext.Password = password;
ES.InitializeServices(serverContext);
int status = -1;
try
{
status = ES.Services.Authentication.AuthenticateUser(serverContext.Username, serverContext.Password, null);
}
catch (Exception ex)
{
Log.WriteError("Authentication error", ex);
return false;
}
string errorMessage = "Check your internet connection or server URL.";
if (status != 0)
{
switch (status)
{
case ERROR_USER_WRONG_USERNAME:
errorMessage = "Wrong username.";
break;
case ERROR_USER_WRONG_PASSWORD:
errorMessage = "Wrong password.";
break;
case ERROR_USER_ACCOUNT_CANCELLED:
errorMessage = "Account cancelled.";
break;
case ERROR_USER_ACCOUNT_PENDING:
errorMessage = "Account pending.";
break;
}
Log.WriteError(
string.Format("Cannot connect to the remote server. {0}", errorMessage));
ret = false;
}
return ret;
}
private bool StringEquals(string str1, string str2)
{
return string.Equals(str1, str2, StringComparison.InvariantCultureIgnoreCase);
}
}
}

View file

@ -0,0 +1,204 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
namespace WebsitePanel.Import.CsvBulk
{
/// <summary>
/// Simple log
/// </summary>
public sealed class Log
{
/// <summary>
/// Initializes a new instance of the class.
/// </summary>
private Log()
{
}
private static string logFile = "WebsitePanel.Import.CsvBulk.log";
/// <summary>
/// Initializes trace listeners.
/// </summary>
public static void Initialize(string fileName)
{
logFile = fileName;
FileStream fileLog = new FileStream(logFile, FileMode.Append);
TextWriterTraceListener fileListener = new TextWriterTraceListener(fileLog);
fileListener.TraceOutputOptions = TraceOptions.DateTime;
Trace.UseGlobalLock = true;
Trace.Listeners.Clear();
Trace.Listeners.Add(fileListener);
TextWriterTraceListener consoleListener = new TextWriterTraceListener(System.Console.Out);
Trace.Listeners.Add(consoleListener);
Trace.AutoFlush = true;
}
/// <summary>
/// Write error to the log.
/// </summary>
/// <param name="message">Error message.</param>
/// <param name="ex">Exception.</param>
internal static void WriteError(string message, Exception ex)
{
try
{
string line = string.Format("[{0:G}] ERROR: {1}", DateTime.Now, message);
Trace.WriteLine(line);
Trace.WriteLine(ex);
}
catch { }
}
/// <summary>
/// Write error to the log.
/// </summary>
/// <param name="message">Error message.</param>
internal static void WriteError(string message)
{
try
{
string line = string.Format("[{0:G}] ERROR: {1}", DateTime.Now, message);
Trace.WriteLine(line);
}
catch { }
}
/// <summary>
/// Write to log
/// </summary>
/// <param name="message"></param>
internal static void Write(string message)
{
try
{
string line = string.Format("[{0:G}] {1}", DateTime.Now, message);
Trace.Write(line);
}
catch { }
}
/// <summary>
/// Write line to log
/// </summary>
/// <param name="message"></param>
internal static void WriteLine(string message)
{
try
{
string line = string.Format("[{0:G}] {1}", DateTime.Now, message);
Trace.WriteLine(line);
}
catch { }
}
/// <summary>
/// Write info message to log
/// </summary>
/// <param name="message"></param>
internal static void WriteInfo(string message)
{
try
{
string line = string.Format("[{0:G}] INFO: {1}", DateTime.Now, message);
Trace.WriteLine(line);
}
catch { }
}
/// <summary>
/// Write start message to log
/// </summary>
/// <param name="message"></param>
internal static void WriteStart(string message)
{
try
{
string line = string.Format("[{0:G}] START: {1}", DateTime.Now, message);
Trace.WriteLine(line);
}
catch { }
}
/// <summary>
/// Write end message to log
/// </summary>
/// <param name="message"></param>
internal static void WriteEnd(string message)
{
try
{
string line = string.Format("[{0:G}] END: {1}", DateTime.Now, message);
Trace.WriteLine(line);
}
catch { }
}
internal static void WriteApplicationStart()
{
try
{
string name = typeof(Log).Assembly.GetName().Name;
string version = typeof(Log).Assembly.GetName().Version.ToString(3);
string line = string.Format("[{0:G}] ***** {1} {2} Started *****", DateTime.Now, name, version);
Trace.WriteLine(line);
}
catch { }
}
internal static void WriteApplicationEnd()
{
try
{
string name = typeof(Log).Assembly.GetName().Name;
string line = string.Format("[{0:G}] ***** {1} Ended *****", DateTime.Now, name);
Trace.WriteLine(line);
}
catch { }
}
/// <summary>
/// Opens notepad to view log file.
/// </summary>
public static void ShowLogFile()
{
try
{
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, logFile);
Process.Start("notepad.exe", path);
}
catch { }
}
}
}

View file

@ -0,0 +1,47 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Configuration;
using System.Collections.Generic;
using System.Text;
namespace WebsitePanel.Import.CsvBulk
{
class Program
{
static void Main(string[] args)
{
Log.Initialize(ConfigurationManager.AppSettings["LogFile"]);
Log.WriteApplicationStart();
ExchangeImport import = new ExchangeImport();
import.Start();
Log.WriteApplicationEnd();
}
}
}

View file

@ -0,0 +1,22 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("WebsitePanel.Import.CsvBulk")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("WebsitePanel.Import.CsvBulk")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("506d71c8-2a26-4b3b-b716-dea4758969b7")]

View file

@ -0,0 +1,61 @@
// Copyright (c) 2011, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
namespace WebsitePanel.Import.CsvBulk
{
public class ServerContext
{
private string serverName;
public string Server
{
get { return serverName; }
set { serverName = value; }
}
private string userName;
public string Username
{
get { return userName; }
set { userName = value; }
}
private string password;
public string Password
{
get { return password; }
set { password = value; }
}
}
}

View file

@ -0,0 +1,118 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{CAD845DC-B209-4A07-94DA-B12FD14121F3}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>WebsitePanel.Import.CsvBulk</RootNamespace>
<AssemblyName>WebsitePanel.Import.CsvBulk</AssemblyName>
<FileUpgradeFlags>
</FileUpgradeFlags>
<UpgradeBackupLocation>
</UpgradeBackupLocation>
<OldToolsVersion>3.5</OldToolsVersion>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Web.Services3">
<HintPath>..\..\..\Lib\Microsoft.Web.Services3.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.configuration" />
<Reference Include="System.Data" />
<Reference Include="System.Web.Services" />
<Reference Include="System.Xml" />
<Reference Include="WebsitePanel.EnterpriseServer.Base, Version=1.0.0.0, Culture=neutral, PublicKeyToken=da8782a6fc4d0081, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\Bin\WebsitePanel.EnterpriseServer.Base.dll</HintPath>
</Reference>
<Reference Include="WebsitePanel.EnterpriseServer.Client, Version=1.0.0.0, Culture=neutral, PublicKeyToken=da8782a6fc4d0081, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\Bin\WebsitePanel.EnterpriseServer.Client.dll</HintPath>
</Reference>
<Reference Include="WebsitePanel.Providers.Base, Version=1.0.0.0, Culture=neutral, PublicKeyToken=da8782a6fc4d0081, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\Bin\WebsitePanel.Providers.Base.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\VersionInfo.cs">
<Link>VersionInfo.cs</Link>
</Compile>
<Compile Include="ES.cs" />
<Compile Include="Log.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ServerContext.cs" />
<Compile Include="ExchangeImport.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config">
<SubType>Designer</SubType>
</None>
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include="Microsoft.Net.Client.3.5">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">
<Visible>False</Visible>
<ProductName>Windows Installer 3.1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>