|
I used app.UseAuthentication and the problem solved.
|
|
|
|
|
I am trying to allow my users to check if they have ActiveSync enabled for email and if they do return you are good to go, else tell them they need to complete a form. So a simple test I setup tried to start with a powershell.asp page containing:
<form action="doPowershell.asp" method="post">
Network Username: <input type="textbox" name="userName"/>
<input type="submit"/>
</form>
Then the resulting doPowershell.asp page I have for testing:
<%
Dim userName
userName = Request.Form("userName")
response.write(userName)
Server.Execute("activesync.ps1")
%>
the activesync.ps1 file contains
(Get-CASMailbox -Identity <username>).ActiveSyncEnabled
On the screen it outputs the value the user entered and then outputs the content of the ps1 file. Doesn't physically run anything. Thoughts?
Note: The current form doesn't really effect the PowerShell script. Just a shell I wrote to see if I could run it. The PS1 right now is just hardcoded with a physical username.
|
|
|
|
|
"Classic" ASP is ancient and obsolete. It's been effectively "dead" for 20 years now.
The Server.Execute method executes an ASP file. Since your PowerShell script doesn't contain any ASP code, it simply outputs the content of the file.
Update your application to use ASP.NET, and use the PowerShell class from the System.Management.Automation namespace[^] to execute your PowerShell script.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Thanks. Are there any examples of this with say ASP.NET Web Core 6? I'm pulling out my hair trying to find anyone who did this with recent versions. Also would this still need to rely on a ps1 file or could the commands be loaded directly in code?
|
|
|
|
|
According to this SO thread[^], it's been supported since .NET Core 2.0 and Powershell v6. There's a sample application on GitHub[^].
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hi,
I want to create a web application in my local server. All clients can connect to it through the local network. This server has a static IP and all related settings have been set for port forwarding, so we can access the server and my web application through Internet. I want to use SQLite system in my app.
Is it possible? Can users use data stored in SQLite at the same time?
modified 18-Nov-21 4:00am.
|
|
|
|
|
Assuming you mean SQLite:
SQLite works great as the database engine for most low to medium traffic websites (which is to say, most websites). The amount of web traffic that SQLite can handle depends on how heavily the website uses its database. Generally speaking, any site that gets fewer than 100K hits/day should work fine with SQLite. The 100K hits/day figure is a conservative estimate, not a hard upper bound. SQLite has been demonstrated to work with 10 times that amount of traffic.
Note that writing to the database will lock the entire database file. Concurrent writes will not be supported.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hi all. I'm using vb.net and have a custom templatefield in a datagrid:
<asp:CommandField
ShowEditButton="True" />
<ItemTemplate>
<asp:CheckBox ID="ckbIsCurrentAccount" runat="server" width="30px" checked='<%#Eval("IsCurrent").ToString()%>'/>
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="ckbIsCurrentAccountEdit" runat="server" width="30px" Checked='<%#DataBinder.Eval(Container.DataItem, "IsCurrent") %>'/>
</EditItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="ckbIsCurrentAccountFooter" runat="server" width="30px" checked="true"/>
</FooterTemplate>
</asp:TemplateField>
So when I click 'edit', it gives me the update/cancel options. When I click 'update', it says this checkbox is passing a null value and therefore throwing an error.
I have seen some answers involving the RowDataBound event and tried to adapt them to my scenario, however the same error keeps popping up. Is anyone able to help with this?
Thanks all.
|
|
|
|
|
I have a class which is using shell32.dll and a console exe program. It works well. Howeve, when I used the class with (shell32.dll) in IIS (dotnet Core 5), it doesn't work.
My question is the SHELL32.DLL allowed to be in the IIS?
If not, is there any other dll I can use?
Here is the Error message:
Quote: System.InvalidCastException
HResult=0x80004002
Message=Unable to cast COM object of type 'System.__ComObject' to interface type 'Shell32.Shell'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{286E6F1B-7113-4355-9562-96B7E9D64C54}' failed due to the following error: No such interface supported (0x80004002 (E_NOINTERFACE)).
Source=System.Private.CoreLib
StackTrace:
at System.Runtime.CompilerServices.CastHelpers.ChkCastAny(Void* toTypeHnd, Object obj)
|
|
|
|
|
Shell32 requires an STA thread. ASP.NET doesn't use STA threads, which is why you're getting this error.
There is almost certainly another solution to the problem you're trying to solve. But since you haven't told us anything about it, we can't tell you what the solution is.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Here is the API in MVC controller:
public JsonResult GetMusicFiles()
{
List list = new();
FILE_PATH = @"D:\medias\musics";
list = Helpers.MediaMetaData.SingleDir(FILE_PATH);
foreach (ClassMediaMetaData d in list) {
Console.WriteLine(d.FullFileName);
}
return new JsonResult("Success!");
}
Here is the function in a class
class MediaMetaData
{
[STAThread]
public static List SingleDir(string folder)
{
return GetFilesSingleDir(folder);
}
private static List GetFilesSingleDir(String folder)
{
TimeSpan dur = TimeSpan.Zero;
Shell32.Shell shell = new Shell32.Shell();
Shell32.Folder objFolder = shell.NameSpace(folder);
List list = new();
list.Clear();
foreach (FolderItem2 item in objFolder.Items())
{
if (!item.IsFolder)
{
ClassMediaMetaData md = new ClassMediaMetaData();
dur = TimeSpan.FromSeconds(item.ExtendedProperty("System.Media.Duration") / 10000000);
md.Duration = dur.Duration();
md.FullFileName = item.Name;
md.FullPath = folder;
list.Add(md);
}
}
return list;
}
...
I am using VS2019 with DotNet CORE 5.0 to compile this.
When I used the class in a console application, it works fine. Therefore I know the code is working. The diff is one is console app and the other one is web or IIS.
Thanks.
|
|
|
|
|
As I said, it doesn't work in IIS because it's not running in an STA thread.
There are various suggested workarounds in this SO thread:
c# - Exception when using Shell32 to get File extended properties - Stack Overflow[^]
You can ignore the solution from Nikhil Chavan, since it doesn't apply to ASP.NET applications.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
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
|
|
|
|
|