How do I save/read to a file - c#

so I have made my code and it works and everything but... now it says that I have to save it to a file. Here's my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Case3Password
{
internal class Program
{
static void Main(string[] args)
{
bool que = false;
while (que == false)
{
Console.WriteLine("Choose whether to login, make or change");
string command = Console.ReadLine();
if (command == "make" && !MadeAccount)
{
MakeAccount();
}
else if (command == "change" && MadeAccount)
{
ChangePassword();
}
else if (command == "login" & MadeAccount)
{
Login();
}
else
{
Console.WriteLine("incorrect choice, type either 'login', 'make' or 'change'");
}
}
}
static bool MadeAccount = false;
static void MakeAccount()
{
Console.WriteLine("Input your username");
string Username = Console.ReadLine();
Console.WriteLine("Input your password");
string password = Console.ReadLine();
if (ContainsUpperAndLower(password) == true && ContainsNumbersAndSpecialCharacters(password) == true && ContainsNoNumbersAtStartOrEnd(password) == true && ContainNoSpace(password) == true && UsernamePasswordTrue(Username, password) == true)
{
string folder = #"C:\Temp\";
string fileName = "Dokumenter.txt";
string fullPath = fileName;
string[] lines = { Username, password };
File.WriteAllLines(fullPath, lines);
MadeAccount = true;
Console.WriteLine("Account succesfully created");
}
else
{
Console.WriteLine("Sorry this password doesn't meet the requirements");
}
}
static void ChangePassword()
{
Console.WriteLine("Input your username");
string username = Console.ReadLine();
Console.WriteLine("Input your password");
string password = Console.ReadLine();
string folder = #"C:\Temp\";
string fileName = "CSharpCornerAuthors.txt";
string fullPath = folder + fileName;
string[] text = File.ReadAllLines(fullPath);
string PreviousUsername = text[0];
string PreviousPassword = text[1];
if (username == PreviousUsername && password == PreviousPassword)
{
Console.WriteLine("What do you want to change your password to?");
string NewPassword = Console.ReadLine();
if (PreviousPassword != NewPassword)
{
if (ContainsUpperAndLower(password) == true && ContainsNumbersAndSpecialCharacters(password) == true && ContainsNoNumbersAtStartOrEnd(password) == true && ContainNoSpace(password) == true && UsernamePasswordTrue(username, password) == true)
{
string[] lines = { username, NewPassword };
File.WriteAllLines(fullPath, lines);
Console.WriteLine("Password succesfully changed");
}
else
{
Console.WriteLine("Sorry this password doesn't meet the requirements");
}
}
}
}
static void Login()
{
Console.WriteLine("Input your username");
string username = Console.ReadLine();
Console.WriteLine("Input your password");
string password = Console.ReadLine();
string folder = #"C:\Temp\";
string fileName = "CSharpCornerAuthors.txt";
string fullPath = folder + fileName;
string[] text = File.ReadAllLines(fullPath);
string PreviousUsername = text[0];
string PreviousPassword = text[1];
if (username == PreviousUsername && password == PreviousPassword)
{
Console.WriteLine("Succesfully logged in");
}
else
{
Console.WriteLine("Sorry either your username or password was incorrect");
}
//6 metoder stillet op --->
//Første metode har jeg kaldet LengthCheck og her har jeg lavet en if/else statement
}
public static bool LengthCheck(string password)
{
if (password.Length >= 12) //Hvis password er større end/lig med 12 tegn så returnere den en true værdi
{
return true;
}
else //En else statement hvis nu den password er mindre end 12
{
return false; //Hvis den er ´mindre end 12 tegn så kommer den tilbage false
}
}
//2. metode hvor jeg siger at password SKAL anvende både store og små bogstaver
public static bool ContainsUpperAndLower(string password)
{
int i = 0; //det her er tælleren som bliver brugt senere i koden
//2 booleans som begge er sat til at være false
bool ContainsUpperCase = false;
bool ContainsLowerCase = false;
//Jeg har brugt en while-loop her som siger at password-længde er større end i
//og UpperCase && LowerCase
while (i < password.Length && !(ContainsUpperCase && ContainsLowerCase))
{
char letter = password[i]; //jeg har sat char letter = password[i]; altså indivduelle bogstaver siden at jeg skal tjekke alle bogstaverne igennem
if (ContainsUpperCase == false)
{
ContainsUpperCase = Char.IsUpper(letter);
}
if (ContainsLowerCase == false)
{
ContainsLowerCase = Char.IsLower(letter);
}
i = i + 1; //Man kan også bruge i++ her. Det præcist det samme
}
return ContainsUpperCase && ContainsLowerCase;
}
public static bool ContainsNumbersAndSpecialCharacters(string password)
{
int i = 0;
bool Numbers = false;
bool SpecialCharacters = false;
while (i < password.Length && !(Numbers && SpecialCharacters))
{
char letter = password[i];
if (Numbers == false)
{
Numbers = Char.IsDigit(letter);
}
if (SpecialCharacters == false)
{
SpecialCharacters = !Char.IsLetterOrDigit(letter);
}
i = i + 1;
}
return Numbers && SpecialCharacters;
}
public static bool ContainsNoNumbersAtStartOrEnd(string password)
{
if (Char.IsDigit(password[0]) == false & Char.IsDigit(password[password.Length - 1]) == false)
{
return true;
}
else
{
return false;
}
}
public static bool ContainNoSpace(string password)
{
int i = 0;
bool NoSpace = false;
while (i < password.Length && !(NoSpace))
{
if (NoSpace == false)
{
NoSpace = Char.IsWhiteSpace(password[i]);
}
i = i + 1;
}
NoSpace = !NoSpace;
return NoSpace;
}
public static bool UsernamePasswordTrue(string password, string Username)
{
if (Username.ToLower() != password.ToLower())
{
return true;
}
else
{
return false;
}
}
}
}
I have tried to look up videos and look up online but I don't really see how I can apply either of what i've seen to my code so i'm hoping someone can help me in here. I've been stuck on this project for so long just because of this whole file thing. I've never really grasped or understood it. Basically I have to save the input from the user when they for example make an account/login/change password etc stuff like that.
Basically I need to Save login and password in clear text in
a text file. Which can again be loaded when logging in or when changing the code.

Related

Cannot validate properly the username and password using Array.Find()

I'm trying to make a username and login system to validate if the username and password passed by an user by input matches the username and password in an array of objects. I did using Array.Find() but when I run the program, the user and password are asked twice and I have to put them twice correct so I can advance which does not make sense...
Utilizador[] usersIniciais = utilizadoresDefault.UtilizadoresDefault(utilizadoresDefault.GenerateID());
PersonalTrainer[] ptsIniciais = ptsDefault.PTsDefault(utilizadoresDefault.GenerateID());
int option = novoLogin.LoginInicial();
Tuple<string, string> strings = novoLogin.DadosLogin(option);
string username = strings.Item1;
string password = strings.Item2;
novoLogin.ValidacaoDados(username, password, usersIniciais);
Console.ReadLine();
}
}
namespace RSGymPT.Classes
{
internal class Login
{
public static void Log(string Username)
{
Console.WriteLine($"User Logged: {Username}");
}
public int LoginInicial()
{
int option;
do
{
Console.Clear();
Console.WriteLine("Seleciona a opção pretendida: \n");
Console.WriteLine("1. Login");
Console.WriteLine("2. Sair\n");
Console.Write("A tua opção: ");
Int32.TryParse(Console.ReadLine(), out option);
} while (option != 1 && option != 2);
return option;
}
public Tuple<string, string> DadosLogin(int option)
{
if (option == 1)
{
Console.Clear();
Console.WriteLine("Please insert your Login data: \n");
Console.Write("User: ");
Username = Console.ReadLine();
Console.Write("Password: ");
Password = Console.ReadLine();
return Tuple.Create(Username, Password);
}
else if (option == 2)
{
Console.Clear();
Console.WriteLine("See you soon.\n");
Console.ReadKey();
Environment.Exit(0);
}
return Tuple.Create(Username, Password);
}
public void ValidacaoDados(string user, string password, Utilizador[] utilizadores)
{
Utilizador utilizador = Array.Find(utilizadores, element => element.NomeUtilizador == user);
do
{
Console.Clear();
Console.Write("User: ");
Username = Console.ReadLine();
Console.Write("Password: ");
Password = Console.ReadLine();
if (utilizador != null && utilizador.Password.Equals(password))
{
Console.WriteLine("Login correct");
}
else
{
Console.WriteLine("Bye");
Console.ReadKey();
Console.WriteLine();
Environment.Exit(0);
}
} while (Username == null || Password == null);
}
}
namespace RSGymPT.Classes
{
internal class Utilizador
{
public Utilizador[] UtilizadoresDefault(int id)
{
Utilizador[] usersInicial = new Utilizador[]
{
new Utilizador {Id = GenerateID(), Nome = "user1", NomeUtilizador = "user1user", Password = "user1234"},
new Utilizador {Id = GenerateID(), Nome = "user2", NomeUtilizador = "user2user", Password = "user1234"},
};
return usersInicial;
}
#endregion
}
}
I tried a lot of different approaches life foreach loop and array.firstOrDefault() but I keep with the same thing. Can someone kindly help me to find my mistake?

CSV-injection in export functionality in asp.net application

While submitting a form, in one of the fields i am inserting vulnerable characters like =cmd|'/C calc'!A0. So in security terms it is termed as CSV-injection in export functionality
I have written code like this for above error. but its not working
[WebMethod]
public static string SaveRecord(RRSOCSaving RRSOCSaving, string Indication)
{
string strReturnId = "";
string strAppURL = ConfigurationManager.AppSettings["AppUrl"].ToString();
string strmail_Content = "";
CommonDB commonObj = new CommonDB();
try
{
// Cross site scripting issue code tag..!!
if (commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_CODE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.CITY)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_SITENAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_SITENAME_LANDL_1)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_SITENAME_LANDL_2)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_ASST_MANAGER_NAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_ASST_MANAGER_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_MANAGER_NAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.MANAGER_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.EMP_NEAREST_STORE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.EMP_NEAREST_STORE_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.SUPERVISOR_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.SECURITY_SUP_NAME_STORE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.SECURITY_SUP_MOBNO_STORE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.ALPM_ALPO_NAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.ALPM_ALPO_MOBNO))
{
strReturnId = "Something went wrong due to malicious script attack..!!!";
}
else
{
if (RRSOCSaving.ROLE_ASSIGNED == "SLP State Head")
{
bool blnState1 = Array.Exists(RRSOCSaving.ASSIGNED_STATE.ToString().ToUpper().Split(','), element => element == (RRSOCSaving.STATE).ToString().ToUpper());
if (blnState1)
{
strmail_Content = Get_Email_Content(RRSOCSaving.STORE_CODE, RRSOCSaving.UserName, Indication, RRSOCSaving.STATE, RRSOCSaving.SITE_STORE_FORMAT, RRSOCSaving.STORE_SITENAME);
// SendEmail(RRSOCSaving.UserName, RRSOCSaving.STORE_CODE, RRSOCSaving.SLP_EMAILID, ConfigurationManager.AppSettings["NHQEmail"].ToString(), strmail_Content, Indication);
strReturnId = CommonDB.INSERT_INTO_RRSOC_INFO(RRSOCSaving, Indication);
}
else
{
strReturnId = "User can add data for " + RRSOCSaving.ASSIGNED_STATE + " only";
}
}
else if (RRSOCSaving.ROLE_ASSIGNED == "NHQ Admin")
{
strmail_Content = Get_Email_Content(RRSOCSaving.STORE_CODE, RRSOCSaving.UserName, Indication, RRSOCSaving.STATE, RRSOCSaving.SITE_STORE_FORMAT, RRSOCSaving.STORE_SITENAME);
// SendEmail(RRSOCSaving.UserName, RRSOCSaving.STORE_CODE, RRSOCSaving.SLP_EMAILID, ConfigurationManager.AppSettings["NHQEmail"].ToString(), strmail_Content, Indication);
strReturnId = CommonDB.INSERT_INTO_RRSOC_INFO(RRSOCSaving, Indication);
//strReturnId = "Record Saved Succesfully";
}
}
// strReturnId = CommonDB.INSERT_INTO_RRSOC_INFO(RRSOCSaving);
}
catch (Exception)
{
throw;
}
return strReturnId;
}
public bool HackerTextExistOrNot(string Text)
{
bool flgValid = false;
Regex htmltags = new Regex(#"<.*?>");
Match chkMatch = htmltags.Match(Text);
if (chkMatch.Success)
{
flgValid = true;
}
return flgValid;
}
Please suggest how to stop this error.
Your HackerTextExistOrNot method is checking for the existance of html tags.
You should however check if the text is starting with one of the formular triggering characters.
To protect yourself against the injection attack ensure that none of the given text begins with any of the following characters:
Equals to ("=")
Plus ("+")
Minus ("-")
At ("#")
So you can check like this:
var attackChars = new char[]{'=','+','-','#'};
if(attackChars.Contains(text[0])
{
}

reenter string in text box if string not found

How to re enter a string in text box if string doesn't match?
code I'm trying is but it stucks in loop and does not allow me to enter string again in textbox.
Can anybody guide me how to do this
the code is:
public void userpass()
{
int us = 0; //for user pass
string readText2 = File.ReadAllText(pathuser);
using (StreamReader sr2 = new StreamReader(pathuser))
{
string usernam = username.Text;
string line;
string[] lines = new String[500];
while ((line = sr2.ReadLine()) != null )
{
lines[us] = line;
if (lines[us] == usernam && usernam != "")
{
check = 1;
MessageBox.Show(usernam);
Form2 f2 = new Form2();
this.Hide();
break;
}
us++;
}
if (lines[us-1] != usernam && usernam != null)
{
this.DialogResult = DialogResult.None;
DialogResult result = new DialogResult();
result = MessageBox.Show("Invalid Username or Password?", "Retry", MessageBoxButtons.OK);
if (result == DialogResult.OK)
{
username.Clear();
}
}
}
Okay so i think your problem is mostly checking if the value exist in the file. You can use this function to check if it exist or not and then you can do what you need :
public bool findValueInFile(string filePath, string value)
{
//Get all lines from the txt file
string[] lines = File.ReadAllLines(filePath);
//Go thru all the lines
foreach(string line in lines)
{
//If we find the line we're looking for
if (line.Equals(value))
{
return true;
}
}
//If we haven't found anything return false
return false;
}
After calling this function depending on the return you can show a messagebox or do something else :
if(findValueInFile(yourPath, yourValue))
{
// We found the value
}
else
{
// We didn't find the value
}

installed apps name verus search name

I will be straight forward and say that I found this code online and therefore is not my own. It works perfectly if I type in the name of the program as shown in Programs and Features but for instance, I want to type Mozilla Firefox and have it find the installed Mozilla Firefox 26.0 (x86 en-US). I tried many times to use .substring and .contains in the line that checks the two strings but each time leads the program to just lock up. Any help is appreciated.
Just for side notes:
I am using a list of programs in a txt file that are read in to check against the installed apps.
I ran a messagebox right after it sets the display name and several of the message boxes show up blank. I tried to limit it with string.length not being 0 and length being equal or greater than the string from the txt file but all still locks up the program.
Code:
private static bool IsAppInstalled(string p_machineName, string p_name)
{
string keyName;
// search in: CurrentUser
keyName = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
if (ExistsInRemoteSubKey(p_machineName, RegistryHive.CurrentUser, keyName, "DisplayName", p_name) == true)
{
return true;
}
// search in: LocalMachine_32
keyName = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
if (ExistsInRemoteSubKey(p_machineName, RegistryHive.LocalMachine, keyName, "DisplayName", p_name) == true)
{
return true;
}
// search in: LocalMachine_64
keyName = #"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall";
if (ExistsInRemoteSubKey(p_machineName, RegistryHive.LocalMachine, keyName, "DisplayName", p_name) == true)
{
return true;
}
return false;
}
private static bool ExistsInRemoteSubKey(string p_machineName, RegistryHive p_hive, string p_subKeyName, string p_attributeName, string p_name)
{
RegistryKey subkey;
string displayName;
using (RegistryKey regHive = RegistryKey.OpenRemoteBaseKey(p_hive, p_machineName))
{
using (RegistryKey regKey = regHive.OpenSubKey(p_subKeyName))
{
if (regKey != null)
{
foreach (string kn in regKey.GetSubKeyNames())
{
using (subkey = regKey.OpenSubKey(kn))
{
displayName = subkey.GetValue(p_attributeName) as string;
MessageBox.Show(displayName);
if (p_name.Equals(displayName, StringComparison.OrdinalIgnoreCase) == true) // key found!
{
return true;
}
}
}
}
}
}
return false;
}
I have tried too many different things to list (or remember)... If it helps this is the majority of the rest of the code calling it:
private void Button_Click(object sender, EventArgs e)
{
string[] lines = new string[250];
string msg = "";
string path = System.Windows.Forms.Application.StartupPath;
if (blah.Checked)
{
try
{
StreamReader filePick = new StreamReader(#path + "\\blah.txt");
int counter = 0;
while ((lines[counter] = filePick.ReadLine()) != null)
{
counter++;
}
filePick.Close();
}
catch (Exception ex)
{
msg += ex.Message;
}
}
else if (blah2.Checked)
{
try
{
StreamReader filePick = new StreamReader(#path + "\\blah2.txt");
int counter = 0;
while ((lines[counter] = filePick.ReadLine()) != null)
{
counter++;
}
filePick.Close();
}
catch (Exception ex)
{
msg += ex.Message;
}
}
string MACHINE_NAME = System.Environment.MachineName;
int counter2 = 0;
string APPLICATION_NAME = "";
string filename = "";
while (lines[counter2] != null)
{
APPLICATION_NAME = lines[counter2];
try
{
bool isAppInstalled = IsAppInstalled(MACHINE_NAME, APPLICATION_NAME);
if (isAppInstalled == true)
{
appsNeedAttention = true;
msg += APPLICATION_NAME + " is still installed.";
}
counter2++;
}
catch (Exception ex)
{
msg += ex.Message;
}
}
if (blah.Checked == true)
{
filename = "blah.txt";
}
else if (blah2.Checked == true)
{
filename = "blah2.txt";
}
if (counter2 == 0 && File.Exists(filename) == true)
{
msg = "There are no programs listed in the file.";
}
if (msg != "")
{
MessageBox.Show(msg, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
Try to change this part :
if (p_name.Equals(displayName, StringComparison.OrdinalIgnoreCase) == true)
{
return true;
}
To this :
//check null to avoid error
if (!string.IsNullOrEmpty(displayName))
{
//convert both string to lower case to ignore case difference
//and use contains to match partially
if (displayName.ToLower().Contains(p_name.ToLower()))
{
return true;
}
}

How to make meeting (in calendar) in outlook 2007 using C#?

How to make meeting (in calendar) in outlook 2007 using C# ?
thank's in advance
This code sample from MSDN should get you started:
private void SetRecipientTypeForAppt()
{
Outlook.AppointmentItem appt =
Application.CreateItem(
Outlook.OlItemType.olAppointmentItem)
as Outlook.AppointmentItem;
appt.Subject = "Customer Review";
appt.MeetingStatus = Outlook.OlMeetingStatus.olMeeting;
appt.Location = "36/2021";
appt.Start = DateTime.Parse("10/20/2006 10:00 AM");
appt.End = DateTime.Parse("10/20/2006 11:00 AM");
Outlook.Recipient recipRequired =
appt.Recipients.Add("Ryan Gregg");
recipRequired.Type =
(int)Outlook.OlMeetingRecipientType.olRequired;
Outlook.Recipient recipOptional =
appt.Recipients.Add("Peter Allenspach");
recipOptional.Type =
(int)Outlook.OlMeetingRecipientType.olOptional;
Outlook.Recipient recipConf =
appt.Recipients.Add("Conf Room 36/2021 (14) AV");
recipConf.Type =
(int)Outlook.OlMeetingRecipientType.olResource;
appt.Recipients.ResolveAll();
appt.Display(false);
}
MSDN
Create object of outlook app using:
private Microsoft.Office.Interop.Outlook.Application outlookApp =
new Microsoft.Office.Interop.Outlook.Application();
and replace Application.CreateItem in code provided by Kyle Rozendo, with outlookApp.
Hope this will help.
This is probably a bit of an overkill but, here is a method that handles Adding, Updating, Deleting events. It also uses almost every calendar event function possible (recurrence by various types, attendees, responses etc.). If you're interested, let me know, I can explain more. It should work off the bat, but I could have missed something, typing this really fast
////BEGIN OUTLOOK DECLARATIONS
public static dynamic objOutlook = Activator.CreateInstance(Type.GetTypeFromProgID("Outlook.Application"));
public static int appointmentItem = 1;
public static int mailItem = 0;
public static int inboxItem = 6;
public static dynamic mapiNamespace = objOutlook.GetNamespace("MAPI");
public static dynamic inboxFolder = mapiNamespace.GetDefaultFolder(inboxItem);
public static dynamic mailObject = objOutlook.CreateItem(mailItem);
public static dynamic appointmentObject = objOutlook.CreateItem(appointmentItem);
public static string defaultEmail = mapiNamespace.DefaultStore.DisplayName; //mapiNamespace.CurrentUser.DefaultStore.DisplayName;
////END OUTLOOK DECLARATIONS
public static string CreateAppointmentOutlookDirect(char StatusType, int ID, string EventID, string EventIDRef, string Subject, string Description, string Location, DateTime EventStart, DateTime EventEnd, string TimeZone, int Duration,
string Recepients, bool isAllDayEvent, bool hasReminder, string ReminderType, int ReminderMinutes, bool isRecurring, int RecurrenceType, string RecurrenceDesc, DateTime RecurrenceStart, DateTime RecurrenceEnd,
DateTime CreatedDate, DateTime ModifiedDate)
{
RefreshOutlookConstants();
//ITEM TYPES
var olMailItem = 0;
var olAppointmentItem = 1;
//
//FOLDER TYPES
var olFolderCalendar = 9;
//
int RecurrenceMask = 0;
var objAppointment = objOutlook.CreateItem(olAppointmentItem);
var objMail = objOutlook.CreateItem(olMailItem);
var OlNamspace = objOutlook.GetNamespace("MAPI");
var AppointmentFolder = OlNamspace.GetDefaultFolder(olFolderCalendar);
var StoreID = AppointmentFolder.StoreID;
AppointmentFolder.Items.IncludeRecurrences = true;
string StatusTypeDesc = "";
string[] Attendees = Recepients.Split(';');
//UPDATE YEARLY RECURRENCE TYPE - BECAUSE THE NUMBER 4 DOES NOT EXIST ACCORDING TO MICROSOFT ( -_-)
if (RecurrenceType == 3)
{
RecurrenceType = 5;
}
//GET DAY OF WEEK
if (RecurrenceDesc.Trim().ToUpper() == "MONDAY")
{
RecurrenceMask = 32;
}
else if (RecurrenceDesc.Trim().ToUpper() == "TUESDAY")
{
RecurrenceMask = 4;
}
else if (RecurrenceDesc.Trim().ToUpper() == "WEDNESDAY")
{
RecurrenceMask = 8;
}
else if (RecurrenceDesc.Trim().ToUpper() == "THURSDAY")
{
RecurrenceMask = 16;
}
else if (RecurrenceDesc.Trim().ToUpper() == "FRIDAY")
{
RecurrenceMask = 32;
}
else if (RecurrenceDesc.Trim().ToUpper() == "SATURDAY")
{
RecurrenceMask = 64;
}
else if (RecurrenceDesc.Trim().ToUpper() == "SUNDAY")
{
RecurrenceMask = 1;
}
else
{
RecurrenceMask = 0;
}
//CHECK ALL DAY EVENT
if (isAllDayEvent)
{
EventStart = Convert.ToDateTime(EventStart.ToString("dd/MM/yyyy") + " 12:00 AM");
EventEnd = Convert.ToDateTime(EventEnd.AddDays(1).ToString("dd/MM/yyyy") + " 12:00 AM");
}
//--RESOLVE EVENT START - END - DURATION
GetEventDates(EventStart, EventEnd, Duration, out EventEnd, out Duration);
if (EventStart == null)
{
return EventID + "#FAIL";
}
//ADD - DELETE - UPDATE MEETING ACCORDINGLY
if (StatusType == 'D')
{
var aObject = OlNamspace.GetItemFromID(EventID, StoreID);
aObject.MeetingStatus = 5;
aObject.Save();
if (Recepients.Trim() != "")
{
foreach (string attendee in Attendees)
{
if (attendee.Trim() != "")
{
string NewAttendee = ExtractEmail(attendee);
aObject.Recipients.Add(NewAttendee.Trim());
}
}
aObject.Send();
}
aObject.Delete();
aObject = null;
}
else
{
if (StatusType == 'U')
{
foreach (var aObject in AppointmentFolder.Items)
{
var EntryID = aObject.EntryID;
if (Convert.ToString(EntryID) == EventID.Trim())
{
aObject.MeetingStatus = 5;
aObject.Save();
if (Recepients.Trim() != "")
{
foreach (string attendee in Attendees)
{
string NewAttendee = ExtractEmail(attendee);
if (NewAttendee.Trim() != "")
{
aObject.Recipients.Add(NewAttendee.Trim());
}
}
aObject.Send();
}
aObject.Delete();
}
}
}
objAppointment.MeetingStatus = 1;
objAppointment.Subject = Subject;
objAppointment.Body = Description;
objAppointment.Location = Location;
if (Recepients.Trim() != "")
{
foreach (string attendee in Attendees)
{
string NewAttendee = ExtractEmail(attendee);
if (NewAttendee.Trim() != "")
{
objAppointment.Recipients.Add(NewAttendee.Trim());
}
}
}
if (isAllDayEvent)
{
objAppointment.AllDayEvent = isAllDayEvent;
}
else
{
objAppointment.Start = EventStart;
objAppointment.End = EventEnd; //Optional if Event has Duration
objAppointment.Duration = Duration; //Optional if Event has Start and End
}
objAppointment.ReminderSet = hasReminder;
if (hasReminder)
{
objAppointment.ReminderMinutesBeforeStart = ReminderMinutes;
}
objAppointment.Importance = 2;
objAppointment.BusyStatus = 2;
if (isRecurring)
{
var pattern = objAppointment.GetRecurrencePattern();
pattern.RecurrenceType = RecurrenceType;
if (RecurrenceType == 1)
{
pattern.DayOfWeekMask = RecurrenceMask;
}
else if (RecurrenceType == 4)
{
pattern.MonthOfYear = RecurrenceMask;
}
if (DateTime.Compare(RecurrenceStart, DateTime.Now) > 1)
{
pattern.PatternStartDate = DateTime.Parse(RecurrenceStart.ToString("dd/MM/yyyy"));
}
if (DateTime.Compare(RecurrenceEnd, DateTime.Now) > 1)
{
pattern.PatternEndDate = DateTime.Parse(RecurrenceEnd.ToString("dd/MM/yyyy"));
}
}
objAppointment.Save();
if (Recepients.Trim() != "")
{
objAppointment.Send();
}
EventID = objAppointment.EntryID;
}
objAppointment = null;
//objOutlook = null;
// CREATE--UPDATE--DELETE EVENT OR APPOINTMENTS
StatusTypeDesc = GetStatusType(StatusType).Trim();
if (StatusTypeDesc == "")
{
clsGlobalFuncs.WriteServiceLog(String.Format("Error Creating Outlook Event: Unknown Status Type [{0}]. Event was Treated as a new event and may contain errors", StatusType));
return EventID + "#FAIL";
}
clsGlobalFuncs.WriteServiceLog(String.Format("Outlook Event Succesfully {2}. [EventID: {0}] ][EventRef: {1}]", EventID, EventIDRef, StatusTypeDesc));
return EventID + "#PASS";
}
public static void SendEmail(string Recepients, string CC, string BCC, string Subject, string Body, string Attachment)
{
RefreshOutlookConstants();
string[] EmailArr = Recepients.Split(';');
foreach (string email in EmailArr)
{
if (email.IndexOf('#') == -1)
{
WriteServiceLog(String.Format("EMAIL ERROR: Invalid Email Address:- [{0}]. This email will be skipped", email));
Recepients = Recepients.Replace(email + ";", "");
Recepients = Recepients.Replace(email, "");
}
}
if (Recepients.Trim() == "")
{
WriteServiceLog(String.Format("Error Sending Email. No recpients were found in string [{0}]", Recepients));
return;
}
try
{
Recepients = StringClean(Recepients);
// SEND EMAIL WITH ATTACHMENT
mailObject.To = Recepients;
if (CC.Trim() != "") { mailObject.CC = CC; }
if (BCC.Trim() != "") { mailObject.BCC = BCC; }
mailObject.Subject = Subject;
mailObject.HTMLBody = Body;
mailObject.Importance = 2;
if (Attachment.Trim() != "")
{
string[] attachmentList = Attachment.Split(';');
foreach (string attachmentFile in attachmentList)
{
if (attachmentFile.Trim() != "")
{
mailObject.Attachments.Add(attachmentFile.Trim());
}
}
}
mailObject.Send();
//objEmail.Display(false);
WriteServiceLog(String.Format("Email Sent [{0}] TO [{1}]", Subject, Recepients));
}
catch (Exception ex)
{
WriteServiceLog("Error sending email");
WriteErrorLog(ex);
}
}
public static string GetStatusType(char StatusCode)
{
string returnValue = "";
if (StatusCode == 'A')
{
returnValue = "Created";
}
else if (StatusCode == 'U')
{
returnValue = "Updated";
}
else if (StatusCode == 'D')
{
returnValue = "Deleted";
}
return returnValue;
}
public static string GetRecurData(bool RecurFlag, string EventType, int RecurrenceType, string RecurrenceDesc, DateTime RecurrenceStart, DateTime RecurrenceEnd, DateTime EventStart)
{
string returnValue = String.Format("RRULE:FREQ=DAILY;UNTIL={0:yyyyMMdd};", EventStart);
if (RecurFlag == true)
{
returnValue = "";
if (RecurrenceType == 0)
{
returnValue = String.Format("{0}RRULE:FREQ=DAILY;", returnValue);
}
else if (RecurrenceType == 1)
{
returnValue = returnValue + "RRULE:FREQ=WEEKLY;";
}
else if (RecurrenceType == 2)
{
returnValue = returnValue + "RRULE:FREQ=MONTHLY;";
}
else
{
returnValue = returnValue + "RRULE:FREQ=YEARLY;";
}
if (RecurrenceEnd != null)
{
returnValue = String.Format("{0}UNTIL={1:yyyyMMdd}T{2:HHmmss}Z;", returnValue, RecurrenceEnd, RecurrenceEnd);
}
if (EventType == "GM")
{
if (RecurrenceType == 1)
{
if ((RecurrenceDesc != null) && (RecurrenceDesc.Trim() != ""))
{
returnValue = String.Format("{0}BYDAY={1};", returnValue, RecurrenceDesc.Substring(0, 2).ToUpper());
}
}
if (RecurrenceType == 3)
{
int i = DateTime.ParseExact(RecurrenceDesc, "MMMM", System.Globalization.CultureInfo.InvariantCulture).Month;
if ((RecurrenceDesc != null) && (RecurrenceDesc.Trim() != ""))
{
returnValue = String.Format("{0}BYMONTH={1};", returnValue, i);
}
}
}
}
return returnValue;
}
public static string GetReminderType(bool ReminderFlag, string EventType, string ReminderCode)
{
string returnValue = "NONE";
if (ReminderFlag == true)
{
if (ReminderCode.Trim() == "PROMPT")
{
if (EventType == "GM")
{
returnValue = "popup";
}
else if (EventType == "OC")
{
returnValue = "DISPLAY";
}
}
else
{
returnValue = "email";
if (EventType == "OC") { returnValue = returnValue.ToUpper(); }
}
}
return returnValue;
}
public static void GetEventDates(DateTime EventStart, DateTime EventEnd, int Duration, out DateTime EventEnd_Ret, out int Duration_Ret)
{
EventEnd_Ret = EventEnd;
Duration_Ret = 0;
if (!(EventStart == null))
{
if (((EventEnd == null) || (DateTime.Compare(EventEnd, EventStart) < 1)) && (Duration > 0))
{
EventEnd_Ret = EventStart.AddMinutes(Duration);
}
else if ((Duration_Ret <= 0) && ((EventEnd != null) && (DateTime.Compare(EventEnd, EventStart) >= 0)))
{
Duration_Ret = Convert.ToInt32((EventEnd - EventStart).TotalMinutes);
}
if ((Duration_Ret <= 0) || ((EventEnd_Ret == null) || (DateTime.Compare(EventEnd_Ret, EventStart) < 1)))
{
WriteServiceLog(String.Format("ERROR UPDATING EVENT - COULD NOT RESOLVE WHEN THE EVENT MUST END USING [END DATE: {0:dd/MM/yyyy HH:mm}] OR [DURATION: {1}] - PLEASE SPECIFY A VALID END DATE OR DURATION", EventEnd, Duration));
}
}
else
{
WriteServiceLog("ERROR UPDATING EVENT - START DATE NOT FOUND");
}
}
public static string StringClean(string StringValue)
{
StringValue = StringValue.Replace(':',' ');
StringValue = StringValue.Replace('[', ' ');
StringValue = StringValue.Replace(']', ' ');
StringValue = StringValue.Replace('\'', ' ');
StringValue = StringValue.Replace('<', ' ');
StringValue = StringValue.Replace('>', ' ');
return StringValue.Trim();
}
And to call it, use this
CreateAppointmentOutlookDirect
(
'A', //'A' = ADD, 'U' = UPDATE, 'D' = DELETE
0,
"EVENT SUBJECT",
"OUTLOOK",
"",
"WHAT IS IT ABOUT",
"EVENT DESCRIPTION",
"EVENT LOCATION",
DateTime.Now,
DateTime.Now.AddMinutes(60),
TimeZone.CurrentTimeZone.StandardName,
0,
"attendee1#email.com; attendee2#email.com",
false,
true,
"PROMPT",
30,
false,
0,
"",
DateTime.Now,
DateTime.Now,
false,
'A',
"APPOINTMENT TEST SYSTEM"
);

Categories

Resources