|
I did change my logic to use Thread per your link. However, the problem won't go away - still the same error.
|
|
|
|
|
Sorry, this site does not provide code to order.
|
|
|
|
|
Code? For what?
All you've done is spew some keywords that do not describe any project at all.
Frankly, this "question" is so bad, I think you're a test account for spam. Don't bother, it won't long here.
|
|
|
|
|
We have a login
If you type the username and password and press submit, we called the login.cs
everything is validate and OK,
but we have a password recovery link, where you have to type the username in order
to send you the email, in both case we called the same page: login, but we a parameter: <a href="login?expire=1" class="btn btn-ic btn-link pkg-photo">Olvide mi clave</a>
this is the function called:
if (Get<bool>("expire"))
{
if (!Empty(Username))
{
ExecuteRow("sp_sopv2_EnviarCorreoClave " + Username);
SuccessMessage = "Se a enviado un correo a su cuenta de email que tiene registrado con nosotros favor verificar.Una vez acceda a su cuenta debe cambiar su clave por seguridad";
}
else{
WarningMessage = "Favor de escribir el Usuario!";
}
}
the problem: the username field it passed with no value, only has value if you press submit
Here de login.cshtml:
<div class="box box-primary login-box ewLoginBox">
<div class="login-box-body">
<p class="login-box-msg">@Html.Raw(Language.Phrase("Login"))</p>
<div class="form-group">
<div><input type="text" name="username" id="username" class="form-control ewControl" value="@_login.Username" placeholder="@Language.Phrase("Username")" autocomplete="username"></div>
</div>
<div class="form-group">
<div><input type="password" name="password" id="password" class="form-control ewControl" placeholder="@Language.Phrase("Password")" autocomplete="current-password"></div>
</div>
<div class="checkbox">
<label for="rememberme"><input type="checkbox" name="type" id="rememberme" value="a" @Html.Raw((_login.LoginType == "a") ? " checked" : "")>@Html.Raw(Language.Phrase("RememberMe"))</label>
</div>
<button class="btn btn-primary btn-block ewButton" name="btnsubmit" id="btnsubmit" type="submit">@Html.Raw(Language.Phrase("Login"))</button>
@if (Config.Authentications.Count(kvp => kvp.Value.Enabled) > 0){
<div class="social-auth-links text-center">
<p>@Html.Raw(Language.Phrase("LoginOr"))</p>
@foreach (var kvp in Config.Authentications.Where(kvp => kvp.Value.Enabled)){
<a href="ExternalLogin?provider=@kvp.Key" class="btn btn-block btn-social btn-flat btn-@kvp.Key.ToLower()">class="fa fa-@kvp.Key.ToLower()">@Html.Raw(Language.Phrase("Login" + kvp.Key))</a>
}
</div>
}
<a href="login?expire=1" class="btn btn-ic btn-link pkg-photo">Olvide mi clave</a>
Here the login.cs
Username = "";
string password = "";
if (IsLoggingIn()) {
Username = Session.GetString(Config.SessionUserProfileUserName);
password = Session.GetString(Config.SessionUserProfilePassword);
LoginType = Session.GetString(Config.SessionUserProfileLoginType);
validPassword = Security.ValidateUser(ref Username, ref password, false);
if (validPassword) {
Session[Config.SessionUserProfileUserName] = "";
Session[Config.SessionUserProfilePassword] = "";
}
} else {
if (!Security.IsLoggedIn)
Security.AutoLogin();
Security.LoadUserLevel();
bool encrypted = false;
if (!Empty(Post("username"))) {
Username = RemoveXss(Post("username"));
password = RemoveXss(Post("password"));
LoginType = RemoveXss(Post("type"));
.
.
.
if (Get<bool>("expire"))
{
if (!Empty(Username))
{
ExecuteRow("sp_sopv2_EnviarCorreoClave " + Username);
SuccessMessage = "Se a enviado un correo a su cuenta de email que tiene registrado con nosotros favor verificar.Una vez acceda a su cuenta debe cambiar su clave por seguridad";
}
else{
WarningMessage = "Favor de escribir el Usuario!";
}
}
Any help.
|
|
|
|
|
|
Uff, thanks a lot my friend, I did not knew it, i am new in ASP.NET and i am trying to fix this problem.
But, if we make this:
Olvide mi clave
1. How to a pass the username?
Because it is called the whole login and ask to type the password, which it is not correct, because we only need the username to sent the email.
|
|
|
|
|
To pass the value which has been typed into the form, you must submit the form. If you use an <a> to navigate to the "forgot password" action, none of the values in the form will be sent.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hi all. I've tried for days now (quite literally) to get a simple web service to work, however it's like nothing in the $Ajax section is run at all. Can anyone help me with this, please?
There are two methods I've been trying, with an img with an OnClick or a button.
Both alerts work ("This button was clicked") but nothing else..
<form id="form1" runat="server">
<p>Click on this paragraph.</p>
<div>
<img id="imgMediabtn" src="media/login.gif" onmouseover="this.style.cursor = 'pointer';" />
<asp:Button ID="Button4" runat="server" Text="Button" OnClientClick="BindTreeview()"/>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
</form>
<script>
$(document).ready(function () {
$("p").click(function () {
alert("The paragraph was clicked.");
});
$("#imgMediabtn").click(function () {
alert("The image was clicked.");
$.ajax({
type: "POST",
url: "MyWebService1.asmx/HelloWorld",
data: '{name: "' + $("#<%=TextBox1.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function OnSuccess(response) {
alert("Hello");
},
failure: function (response) {
alert("Goodbye");
}
});
});
});
function BindTreeview() {
alert("The button was clicked.");
$.ajax({
type: "POST",
url: "TestWebService.aspx/GetCurrentTime",
data: '{name: "' + $("#<%=TextBox1.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function OnSuccess(response) {
alert(response.d);
},
failure: function (response) {
alert(response.d);
}
})
}
}
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
' <System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class MyWebService1
Inherits System.Web.Services.WebService
<WebMethod()>
Public Function HelloWorld(ByVal name As String) As String
Return "Hello " & name & Environment.NewLine & "The Current Time is: " &
DateTime.Now.ToString()
End Function
End Class
|
|
|
|
|
Clicking the button will submit the form. You need to prevent that from happening to give your AJAX code a chance to run.
Either:
OnClientClick="BindTreeview();return false;" Or:
OnClientClick="BindTreeview(event);"
function BindTreeview(event){
event.preventDefault();
... Event.preventDefault() - Web APIs | MDN[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Thanks, Richard, however still no luck.
Also, clicking on an image (IMG) doesn't have a postback or 'usual' thing for the ajax code not to run and it still won't call the webservice file.
Can't even get a failure response to my ajax call. Could I be missing an ajax exension or something? I'm using visual studio 2019 and loaded this all in a new webforms project. I would think Ajax is built in, right?
|
|
|
|
|
"Ajax" is just calling xmlhttprequest, which is an object that the browser exposes. What you're using to interface to that, though, is JQuery (as per the $ bit) and that isn't "built in" to either ASP.Net nor to the browser. You'll need to include a SCRIPT reference to JQuery, either via a CDN or on your own server.
|
|
|
|
|
Greetings again,
Sorry that I have to come back for help for this script.
Each time this script runs, it sends email notifications to our Executive team advising them of whether any or all of the apps are either down or up.
The script works very well thanks entirely to the great Richard Deeming.
However, management has asked that I modify the script to add foreground color of red and background color of yellow to any URL of the app that is down along with the text indicating down.
For instance, when app sends out email notifications, it lists the apps and their status as follows:
Please find the status of the DMZ servers below:
https://www.link1: WORKING
https://www.link2.com WORKING
https://www.link3.com DOWN
https://www.link4.com WORKING
They would like any app that is down to display as follows:
Please find the status of the DMZ servers below:
link 1: https://www.link1 WORKING
Link 2 https://www.link2.com WORKING
Link 3 https://www.link3.com DOWN
Link 4 https://www.link4.com WORKING
In this example, Link 3 https://www.link3.com DOWN
They would like the entire row of the URL that is down to be color coded, background color of yellow and text color of red.
Link 1 corresponds to the first URL, Link 2 to second URL, etc.
If it is only possible to just color code just the URL and the DOWN text without the link #, that would be fine too.
I am not sure if this is possible.
I could not figure a way to do this.
Any thought on how I could get this to work?
I recognize the send mail bit has body (IsBodyHtml) set to false but I can change this to true if I can the color thing to work.
Below is the working code.
using System;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Net.NetworkInformation;
using System.Text;
using System.Configuration;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Net.Http;
using System.Linq;
namespace showserverstatus
{
class Program
{
static async Task<int> Main(string[] args)
{
System.Collections.Concurrent.ConcurrentDictionary<string, string> urlToStatus = new();
IEnumerable < Task<bool> > tasks = args.Select(async url =>
{
bool result = await ServerStatusByAsync(url);
return urlToStatus.TryAdd(url, result ? "WORKING" : "DOWN");
});
bool[] results = await Task.WhenAll(tasks);
StringBuilder body = new("Please find the status of the DMZ servers below:");
foreach (var kvp in urlToStatus)
{
body.AppendLine();
body.AppendFormat("{0}: {1}", kvp.Key, kvp.Value);
}
await SendEmailAsync("DMZ Server Status", body.ToString());
await Task.Delay(3000);
return results.Count(result => !result);
}
static async Task<bool> ServerStatusByAsync(string url)
{
HttpClient http = new();
using (HttpResponseMessage response = await http.GetAsync(url))
{
Console.WriteLine("GET {0}: {1}", url, response.StatusCode);
if (response.IsSuccessStatusCode)
{
await SendEmailAsync($"{url} WORKING", $"GET {url} returned {response.StatusCode}");
return true;
}
await SendEmailAsync($"{url} DOWN", $"GET {url} returned {response.StatusCode}");
return false;
}
}
static async Task SendEmailAsync(string subject, string body)
{
using MailMessage mm = new(ConfigurationManager.AppSettings["FromEmail"], "joeblow@gmail.com");
mm.To.Add("janeblow@yahoo.com");
mm.CC.Add("kevin.bruiner@hotmail.com");
mm.Subject = subject;
mm.Body = body;
mm.IsBodyHtml = false;
SmtpClient smtp = new()
{
Host = ConfigurationManager.AppSettings["Host"],
Port = int.Parse(ConfigurationManager.AppSettings["Port"]),
EnableSsl = true,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(ConfigurationManager.AppSettings["Username"], ConfigurationManager.AppSettings["Password"]),
};
await smtp.SendMailAsync(mm);
}
}
}
As always, many thanks in advance
|
|
|
|
|
You would need to format the message body as HTML.
static async Task SendEmailAsync(string subject, string body, bool isBodyHtml = false)
{
using MailMessage mm = new(ConfigurationManager.AppSettings["FromEmail"], "joeblow@gmail.com");
mm.To.Add("janeblow@yahoo.com");
mm.CC.Add("kevin.bruiner@hotmail.com");
mm.Subject = subject;
mm.Body = body;
mm.IsBodyHtml = isBodyHtml;
SmtpClient smtp = new()
{
Host = ConfigurationManager.AppSettings["Host"],
Port = int.Parse(ConfigurationManager.AppSettings["Port"]),
EnableSsl = true,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(ConfigurationManager.AppSettings["Username"], ConfigurationManager.AppSettings["Password"]),
};
await smtp.SendMailAsync(mm);
}
static async Task<int> Main(string[] args)
{
System.Collections.Concurrent.ConcurrentDictionary<string, bool> urlToStatus = new();
IEnumerable<Task<bool>> tasks = args.Select(async url =>
{
bool result = await ServerStatusByAsync(url);
return urlToStatus.TryAdd(url, result);
});
bool[] results = await Task.WhenAll(tasks);
StringBuilder body = new("<p>Please find the status of the DMZ servers below:</p>");
body.Append("<ul>");
foreach (var kvp in urlToStatus)
{
string encodedLink = System.Net.WebUtility.HtmlEncode(kvp.Key);
body.Append(kvp.Value ? "<li>" : "<li style=\"color:red;background-color:yellow;\">");
body.Append(kvp.Value ? "<a href=\"" : "<a style=\"color:red;\" href=\"");
body.Append(encodedLink);
body.Append("\">");
body.Append(encodedLink);
body.Append("</a> - ");
body.Append(kvp.Value ? "WORKING" : "DOWN");
body.Append("</li>");
}
body.Append("</ul>");
await SendEmailAsync("DMZ Server Status", body.ToString(), true);
await Task.Delay(3000);
return results.Count(result => !result);
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Oh wow, this is so incredible.
Just too good.
Many, many THANK YOU sir.
I truly do appreciate your help.
You are the nicest, most generous individual that I never met.
Sir, do you know why they keep getting two different emails?
Let's say for instance that they just wanted to get the status of one link, https://www.link1.com
When they receive email, it displays like this:
DMZ Server Status. Please find the status of the DMZ servers below.
https://www.link1.com WORKING GET https://www.link1.com" returned OK
Is there a way to remove the second email so they always get the bolded one with subject DMZ Server Status and when they open the email, they get details about the link or links?
UPDATE: I *THINK* I got it!
This is the part of the script that is sending the GET email ( the second email)
static async Task<bool> ServerStatusByAsync(string url)
{
HttpClient http = new();
using (HttpResponseMessage response = await http.GetAsync(url))
{
Console.WriteLine("GET {0}: {1}", url, response.StatusCode);
if (response.IsSuccessStatusCode)
{
return true;
}
return false;
}
}
So by commenting out
await SendEmailAsync(...)
for both WORKING and DOWN, allows only one email:
DMZ Server Status... to come through.
I hope it is correct.
If so, all I would need help on now is to create another copy of this same script but this time, to send email to certain group ONLY when any or all of the apps is(are) down and I swear no more changes will be needed.
modified 1-Sep-21 14:57pm.
|
|
|
|
|
That's the correct change to remove the other email.
If you only want to send the main email if any site is down, you'll need to check before sending it:
bool[] results = await Task.WhenAll(tasks);
if (results.Any(up => !up))
{
StringBuilder body = ...
...
await SendEmailAsync("DMZ Server Status", body.ToString(), true);
await Task.Delay(3000);
} If you only want to send the message if all sites are down, use:
if (results.All(up => !up))
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Thank you so so so much sir.
Your complete grasp of technology is truly amazing.
No way I get this solution without your unflinching support and incredible patiences.
May God continue to bless more.
|
|
|
|
|
i need code for bank transaction when i simply give coustermer id
|
|
|
|
|
First you need to design your banking system. You cannot create a transaction until you know what inputs it takes, what outputs it needs to produce, and what rules it must follow.
|
|
|
|
|
|
Hello experts,
I have five (5) public facing REST servers and I have been tasked with coming up with a script that will monitor the status of the servers (whether up or down) and send email notifications three times a day, at &30am, 12:30pm, and 3:30pm.
The email notification should either indicate whether the servers are up or down.
I have had issues thinking up a solution.
However, while googling, I found this article:
Repeat Task every N interval using Windows Service in C# and VB.Net[^]
I am trying to follow it and I have made some minor changes.
For instance, in appSettings, I changed the configuration to this:
<appSettings>
<add key ="Mode" value ="Daily"/>
<add key ="ScheduledTime" value ="24:00"/>
</appSettings>
I am not entirely sure that it is completely correct.
Then, I made this change:
if (mode == "DAILY")
{
scheduledTime = DateTime.Parse(System.Configuration.ConfigurationManager.AppSettings["ScheduledTime"]);
if(DateTime.Now().ToString("HH:mm") = "07:30" || DateTime.Now().ToString("HH:mm") = "12:30" || DateTime.Now().ToString("HH:mm") = "3:30"))
{
scheduledTime = scheduledTime.AddDays(1);
}
}
Do I still need the WriteToFile(...) which saves the server status to a text file?
Here is the complete script from that link:
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
this.WriteToFile("Simple Service started {0}");
this.ScheduleService();
}
protected override void OnStop()
{
this.WriteToFile("Simple Service stopped {0}");
this.Schedular.Dispose();
}
private Timer Schedular;
public void ScheduleService()
{
try
{
Schedular = new Timer(new TimerCallback(SchedularCallback));
string mode = ConfigurationManager.AppSettings["Mode"].ToUpper();
this.WriteToFile("Simple Service Mode: " + mode + " {0}");
DateTime scheduledTime = DateTime.MinValue;
if (mode == "DAILY")
{
scheduledTime = DateTime.Parse(System.Configuration.ConfigurationManager.AppSettings["ScheduledTime"]);
if(DateTime.Now().ToString("HH:mm") = "07:30" || DateTime.Now().ToString("HH:mm") = "12:30" || DateTime.Now().ToString("HH:mm") = "3:30"))
{
scheduledTime = scheduledTime.AddDays(1);
}
}
if (mode.ToUpper() == "INTERVAL")
{
int intervalMinutes = Convert.ToInt32(ConfigurationManager.AppSettings["IntervalMinutes"]);
scheduledTime = DateTime.Now.AddMinutes(intervalMinutes);
if (DateTime.Now > scheduledTime)
{
scheduledTime = scheduledTime.AddMinutes(intervalMinutes);
}
}
TimeSpan timeSpan = scheduledTime.Subtract(DateTime.Now);
string schedule = string.Format("{0} day(s) {1} hour(s) {2} minute(s) {3} seconds(s)", timeSpan.Days, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds);
this.WriteToFile("Simple Service scheduled to run after: " + schedule + " {0}");
int dueTime = Convert.ToInt32(timeSpan.TotalMilliseconds);
Schedular.Change(dueTime, Timeout.Infinite);
}
catch(Exception ex)
{
WriteToFile("Simple Service Error on: {0} " + ex.Message + ex.StackTrace);
using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("SimpleService"))
{
serviceController.Stop();
}
}
}
private void SchedularCallback(object e)
{
this.WriteToFile("Simple Service Log: {0}");
this.ScheduleService();
}
private void WriteToFile(string text)
{
string path = "C:\\ServiceLog.txt";
using (StreamWriter writer = new StreamWriter(path, true))
{
writer.WriteLine(string.Format(text, DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt")));
writer.Close();
}
}
}
Assistance, as always, is greatly appreciated.
|
|
|
|
|
Rather than trying to write your own task scheduler, use the built-in Windows task scheduler.
Task Scheduler for developers - Win32 apps | Microsoft Docs[^]
Create a simple console application which checks your servers, sends the email, and exits. Schedule it to run at whatever time(s) you want.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hi Richard,
As always, thank you sir for your continued assistance.
I *think* this console app will do the trick:
using System.Net.NetworkInformation;
public static void ServerStatusBy(string url)
{
Ping pingSender = new Ping();
PingReply reply = pingSender.Send(url);
Console.WriteLine("Status of Host: {0}", url);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine("IP Address: {0}", reply.Address.ToString());
Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
}
else
Console.WriteLine(reply.Status);
}
Then this will be the call:
Console.Write("Enter server url:");
var url = Console.ReadLine();
Console.Clear();
ServerStatusBy(url);
Console.ReadLine();
I have some questions please.
1, There are 5 API servers as indicated and I can schedule this to run on each server, fine.
However, can you help with not having to interact with the app?
We don't want to have to enter server url in order to get the status.
We just want the app to contact the URL automatically.
So could that mean something like this:
public static void ServerStatusBy(string url)
url = "https://www.something.com/REST" for example?
The second question that I have is that I can essentially write something like:
if (reply.Status == IPStatus.Success)
{
Console.WriteLine("Server APP One is running");
}
else
{
Console.WriteLine("Server APP One is running");
}
Once again, thank you very much sir for your help.
|
|
|
|
|
Just a thought; what if you pass the URL as a command line argument ? This way the program is agnostic to which server it is checking. You could also pass the email addresses on the command line.
|
|
|
|
|
Hi David and thanks a lot for your response.
When you say to pass the URL as command line argument, do you mean when scheduling the app to run?
This is all new for me unfortunately and I ask that you guys forgive me for the questions if they appear silly as probably are.
//UPDATE:
I tried changing the code to the one below so user doesn't have to be prompted to enter URL:
using System;
using System.Net.NetworkInformation;
using System.Text;
namespace showserverstatus
{
class Program
{
static void Main(string[] args)
{
}
public static void ServerStatusBy()
{
Ping pingSender = new Ping();
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 10000;
PingOptions options = new PingOptions(64, true);
PingReply reply = pingSender.Send("www.yahoo.com", timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine("IP Address: {0}", reply.Address.ToString());
Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
}
else
Console.WriteLine(reply.Status);
}
}
I got the following:
Press any key to continue...
When I do, the console closes.
No records shows.
modified 24-Aug-21 23:19pm.
|
|
|
|
|
Any help with this please?
I know this is not your issue but I am being pressured for completion of this task.
Many thanks in advance.
|
|
|
|
|