Why does my if else return false? - asp.net

In my Appcode folder as seen above I have a Class called BaseClass. In BaseClass I have a function called CheckWAN() that defines IP ranges so that later I can auto authenticate local users to my site via their IP address range.
Public Function CheckWAN() As Boolean
Try
Dim url As String = Request.Url.ToString()
'Get the client ip address
Dim RemoteAddress As String = Request.UserHostAddress
Dim strRemoteAddress As String = RemoteAddress
Dim myWAN As String = "192.168.254.254"
'add Some other ips
Dim SOther001 As String = "192.168.254.1"
Dim SOther002 As String = "192.168.254.2"
Dim SOther003 As String = "192.168.254.3"
If strRemoteAddress.Contains(myWAN) Then
Return True
ElseIf strRemoteAddress.Contains(SOther001) Then
Return True
ElseIf strRemoteAddress.Contains(SOther002) Then
Return True
ElseIf strRemoteAddress.Contains(SOther003) Then
Return True
Else
Return False
End If
Catch
Return False
End Try
End Function
Finally I have a set up a login on the site default.aspx that Checks the IP address of the user connecting if the If CheckWAN() returns true then I get passed along to the content page however if it is false then it shows me the login with a message that it is returning false
Public Class BaseClass
Inherits System.Web.UI.Page
If CheckWAN() = True Then
Response.Redirect("/content.aspx")
Else
Response.Write("The CheckWAN is returning False")
'this else also causes a redirect loop if its changed to
'Response.Write(/default.aspx) not sure why
End If
I have also checked with networking to verify the IP's used in my code and they all are valid.
Edited!
here is what Request.UserHostAdress returns
debug

First of all, this should not even compile. Apparently it does, so you must have Option Strict Off. Request.UserHostAdress returns a complex object, and you declared your variable as a string. I suspect that what you actually want is some property of that object, although I don't know which one.

Related

vb.net multiple webproxy in httpwebrequest

I am currently working on a VB.net project where I need to get http responses from a certain URI but the requests needs to go through http proxy which I am perfectly fine with. The problem occurred when I realised sometimes our proxy servers are not working and then the application throws an error. I want my app to check whether the proxy is working or not, if not then I want it to take another proxy from the proxy list/array. And also, please feel free to share if you have any alternative ideas.
Currently I am using this (which is static and when it throws an error I need to manually change the proxy):
Dim proxyObject As WebProxy = New WebProxy("192.168.0.10:80")
request.Proxy = proxyObject
What I want is something like this:
If WebProxy("192.168.0.10:80") is working fine Then
Execute the response
Else
Take the next proxy address from the list/array and go back to the starting
of "If"
End If
FYI: my proxies doesn't require authentication.
I apologise if I couldn't explain it properly and to be honest I'm fairly new in VB.net.
Thanks a lot for your time and patience. Appreciate your help.
Borrowing from this question
Dim urlList As New List(Of String) 'Urls stored here
For each urlString as string in urlList
If CheckProxy(urlString) Then
'Execute the response
else
Continue For 'or something else here, mark it as bad?
End If
next
Public Shared Function CheckProxy(ByVal Proxy As String) As Boolean
Dim prx As Uri = Nothing
If Uri.TryCreate(Proxy, UriKind.Absolute, prx) Then
Return CheckProxy(prx)
ElseIf Uri.TryCreate("http://" & Proxy, UriKind.Absolute, prx) Then
Return CheckProxy(prx)
Else
Return False
End If
End Function
Public Shared Function CheckProxy(ByVal Proxy As Uri) As Boolean
Dim iProxy As Socket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
iProxy.ReceiveTimeout = 500 : iProxy.SendTimeout = 500
Try
'' Connect using a timeout (1/2 second)
Dim result As IAsyncResult = iProxy.BeginConnect(Proxy.Host, Proxy.Port, Nothing, Nothing)
Dim success As Boolean = result.AsyncWaitHandle.WaitOne(500, True)
If (Not success) Then
iProxy.Close() : Return False
End If
Catch ex As Exception
Return False
End Try
Dim bytData() As Byte, strData As String
Dim iDataLen As Integer = 1024
strData = String.Format("CONNECT {0}:{1} HTTP/1.0{2}{2}", "www.google.com", 80, vbNewLine)
bytData = System.Text.ASCIIEncoding.ASCII.GetBytes(strData)
If iProxy.Connected Then
iProxy.Send(bytData, bytData.Length, SocketFlags.None)
ReDim bytData(1024)
Do
Try
iDataLen = iProxy.Receive(bytData, bytData.Length, SocketFlags.None)
Catch ex As Exception
iProxy.Close() : Return False
End Try
If iDataLen > 0 Then
strData = System.Text.ASCIIEncoding.ASCII.GetString(bytData)
Exit Do
End If
Loop
Else
Return False
End If
iProxy.Close()
Dim strAttribs() As String
strAttribs = strData.Split(" "c)
If strAttribs(1).Equals("200") Then
Return True
Else
Return False
End If
End Function

ASP.net 2010 (VB) Object reference not set to an instance of an object

Morning All,
I am using VS2010 with VB and im trying to get a ping test working in my web application. In order to do this and test that it works i have simply created a button that when clicks should ping a specified IP address.
I believe that the code for the button should work fine. The only issue i have is the following error message on my web page...
System.NullReferenceException: Object reference not set to an instance of an object.
It bugs on the cole line...
Console.WriteLine("Address: {0}", vPingReply.Address)
I thought that this was due to 'Properties' needing to be set up for the .Address and .Status objects. Im not too sure if i have added these correctly as i have added some properties but i still have the same issue when i run the page?
Can someone please take a look and advise?
Here is my full code...
Imports Microsoft.VisualBasic
Imports System.Text
Imports System.Net.NetworkInformation
Imports System.Net.NetworkInformation.PingReply
Partial Class Ping
Inherits System.Web.UI.Page
Private mSend As PingReply
Private Property Send(p1 As String) As PingReply
Get
Return mSend
End Get
Set(value As PingReply)
mSend = value
End Set
End Property
Private mAddress As PingReply
Private Property Address(p2 As String) As PingReply
Get
Return mAddress
End Get
Set(value As PingReply)
mAddress = value
End Set
End Property
Private mStatus As PingReply
Private Property Status(p3 As String) As PingReply
Get
Return mStatus
End Get
Set(value As PingReply)
mStatus = value
End Set
End Property
Protected Sub btnPing_Click(sender As Object, e As System.EventArgs) Handles btnPing.Click
Dim vPing As New Ping
Dim vPingReply As PingReply = vPing.Send("xxx.xx.xxx.xx")
Console.WriteLine("Address: {0}", vPingReply.Address)
Console.WriteLine("Status: {0}", vPingReply.Status)
End Sub
End Class
Any help is much appriechiated.
Betty.
You cannot access the content of Address property if the Status is not Success
Dim vPing As New Ping
Dim vPingReply As PingReply = vPing.Send("xxx.xx.xxx.xx")
if vPingReply.Status = IPStatus.Success Then
Console.WriteLine("Address: {0}", vPingReply.Address)
End If
Console.WriteLine("Status: {0}", vPingReply.Status)
The docs says
If the value of Status is not Success, you should not use the values
returned by the RoundtripTime, Options or Buffer properties. The
RoundtripTime property will return zero, the Buffer property will
return an empty array, and the Options property will return null.
but I found that the Address property is null (Nothing in VB) also if the Send is for a non-existant ip address or DNS name
However, looking better at your code, it is clear that all the calls made inside the btnPing_Click method are handled by your class Ping not to the framework class Ping. And your class uses variables not correctly initialized. I suggest to remove those methods from your class or just rename the class with something different.
Another option (not recommended) is this
Private Property Send(p1 As String) As PingReply
Get
' Specify the full namespace to remove ambiguity between this class and framework class
Dim p = new System.Net.NetworkInformation.Ping()
mSend = p.Send(p1)
Return mSend
End Get
Set(value As PingReply)
mSend = value
End Set
End Property
Private Property Address() As String
Get
if mSend IsNot Nothing Then
Return mSend.Address
else
Return string.Empty
End If
End Get
' Meaningless ???
'Set(value As PingReply)
' mAddress = value
'End Set
End Property
Private mStatus As PingReply
Private Property Status() As String
Get
if mSend IsNot Nothing Then
Return mSend.Status.ToString()
else
Return string.Empty
End If
End Get
' Meaningless ???
'Set(value As PingReply)
' mStatus = value
'End Set
End Property

How to write response into Buffer instead of rendering on Screen?

I am developing app where I need to capture an Information from Webpage after giving credentials automatically. Some how I managed to do Automatic login and redirection of page. Here is my code :
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://abcd.com.au/categories/A_dfn/sdf");
HttpWebResponse res = req.GetResponse() as HttpWebResponse;
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[10000];
Stream resStream = res.GetResponseStream();
string s = null;
int c = 0;
do
{
c = resStream.Read(buf, 0, buf.Length);
if (c != 0) {
s = ASCIIEncoding.ASCII.GetString(buf, 0, c);
sb.Append(s);
}
} while (c > 0);
string oldhead = "class=\"login_button\">";
string newhead = "class=\"login_button\"> <script type=\"text/javascript\">document.getElementById('btn').click()</script>";
sb.Replace(oldhead, newhead);
string oldbtn = "value=\"Submit\"";
string newbtn = "value=\"Submit\" id=\"btn\" ";
sb.Replace(oldbtn, newbtn);
string oldAction = "<form action=\"/login\" method=\"post\">";
string newAction = "<form action=\"https://abcd.com.au/login?orig_req_url=%2Fcategories/A_dfn/sdf\" method=\"post\">";
sb.Replace(oldAction, newAction);
string oldUsername = "<input id=\"login_email\" type=\"text\" name=\"user[email_address]\" class=\"textBox\" value=\"\">";
string newUserName = "<input id=\"login_email\" type=\"text\" name=\"user[email_address]\" class=\"textBox\" value=\"abc#xyz.com.au\">";
sb.Replace(oldUsername, newUserName);
string oldPass = "<input id=\"login_password\" type=\"password\" name=\"user[password]\" class=\"textBox\" value=\"\">";
string newPass = "<input id=\"login_password\" type=\"password\" name=\"user[password]\" class=\"textBox\" value=\"abc\">";
sb.Replace(oldPass,newPass);
Response.Write(sb);
This is show me expected output as I want by rendering page(Response.write(sb)). But, now I want to do same thing without redirecting to "https://abcd.com.au/login?orig_req_url=%2Fcategories/A_dfn/sdf" and want to do more stuff on this. I expect to get output of Response.Write(sb) in some buffer. Is it possible to do?
Here is example, that explains exactly what I want to do.
I am looking for an product's qty say name : Screw 15mm, this resides in page https://abcd.com.au/%2Fcategories/A_dfn/sdf.
So, I am requesting this url first, but as need login to access that page, its redirecting me to login page, filling username and password, pressing login button by using javascript,and then redirected to Originally Requested page. And on this page I want to find for that product, and return information to my web app.
All this I want to do without showing to user.
I just want to show retrieved information.
Thanks.
What you are looking for is a persisted session. Your approach towards this problem is incorrect. You are triggering the submit on the client-side. What you are trying to achieve should be done on the server-side.
The key to your scenario is to persist (store) the session & cookies set by the login page; then before your next request for the product info, inject the credential into the requesting webRequest.
Use the WebRequest object to load the login page.
Store any info (cookies) sent by the login page Response header.
create a new WebRequest object with the provided Response header, inject in userid/password.
Store any credentials returned by the Response.
Proceed to request for the quote info.
There is no generic way to do this without knowing the website you are trying to screen-scrap from. But the general step is as above. Basically, you need to create a custom class for this.
Also, you need HTMLAgilityPack to parse the HTML nodes. It is the correct method.
EDIT: Added my codes. Just so happen that I've created this class before sometime ago. So, you're in luck. However, you will need HTMLAgilityPack installed & referenced to use it. You can download HAP at: http://htmlagilitypack.codeplex.com/ If you want to do any serious screen-scraping, HAP is the de-facto standard.
Public Class clsBrowserSession
'=================================================================================================================================
'This is a special Browser Post class
' Instead of just POST to a URL as per the clsWeb.fnsPostResponse()
' clsBrowserSession allows us to LOAD a page first, persist all the cookies and variables, and then only POST to the target URL.
' The reason is that some program will drop (lets say) a SessionID as an input when you first load the page.
' and when you post, without the SessionID (variable), it will reject the POST. Thus clsBrowserSession can solve this problem.
'=================================================================================================================================
' USAGE:
' Dim voBrowserSession As New clsBrowserSession
' voBrowserSession.sbLoadPage("https://xxx.yyy.net.my/publicncdenq/index.htm")
' voBrowserSession.proFormElements("UserID") = "myID"
' voBrowserSession.proFormElements("Password") = "myPassword"
' Dim vsResponseHTML As String = voBrowserSession.Post("https://xxx.yyy.net.my/publicncdenq/index.htm")
Private vbIsPostingInProgress As Boolean
Public voCookies As System.Net.CookieCollection
Public proHTMLDoc As HtmlAgilityPack.HtmlDocument
Public proFormElements As clsFormElementCollection
Public Sub sbLoadPage(pvsURL As String)
vbIsPostingInProgress = False
fnoCreateWebRequestObject().Load(pvsURL)
End Sub
Public Function Post(pvsURL As String) As String
vbIsPostingInProgress = True
fnoCreateWebRequestObject().Load(pvsURL, "POST")
Return proHTMLDoc.DocumentNode.InnerHtml
End Function
Private Function fnoCreateWebRequestObject() As HtmlAgilityPack.HtmlWeb
Dim voWeb As New HtmlAgilityPack.HtmlWeb
voWeb.UseCookies = True
voWeb.PreRequest = New HtmlAgilityPack.HtmlWeb.PreRequestHandler(AddressOf event_OnPreRequest)
voWeb.PostResponse = New HtmlAgilityPack.HtmlWeb.PostResponseHandler(AddressOf event_OnAfterResponse)
voWeb.PreHandleDocument = New HtmlAgilityPack.HtmlWeb.PreHandleDocumentHandler(AddressOf event_OnPreHandleDocument)
Return voWeb
End Function
Private Sub sbAddPostDataTo(pvoRequest As Net.HttpWebRequest)
Dim vsPayload As String = proFormElements.fnsAssemblePostPayload()
Dim vabyteBuffer As Byte() = Text.Encoding.UTF8.GetBytes(vsPayload.ToCharArray())
pvoRequest.ContentLength = vabyteBuffer.Length
pvoRequest.ContentType = "application/x-www-form-urlencoded"
pvoRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11"
pvoRequest.GetRequestStream().Write(vabyteBuffer, 0, vabyteBuffer.Length)
End Sub
Private Sub sbAddvoCookiesTo(pvoRequest As Net.HttpWebRequest)
If (Not IsNothing(voCookies)) Then
If voCookies.Count > 0 Then pvoRequest.CookieContainer.Add(voCookies)
End If
End Sub
Private Sub sbSaveCookiesFrom(pvoResponse As Net.HttpWebResponse)
If pvoResponse.Cookies.Count > 0 Then
If IsNothing(voCookies) Then voCookies = New Net.CookieCollection
voCookies.Add(pvoResponse.Cookies)
End If
End Sub
Private Sub sbSaveHtmlDocument(pvoHTMLDocument As HtmlAgilityPack.HtmlDocument)
proHTMLDoc = pvoHTMLDocument
proFormElements = New clsFormElementCollection(proHTMLDoc)
End Sub
Protected Function event_OnPreRequest(pvoRequest As Net.HttpWebRequest) As Boolean
sbAddvoCookiesTo(pvoRequest)
If vbIsPostingInProgress Then sbAddPostDataTo(pvoRequest)
Return True
End Function
Protected Sub event_OnAfterResponse(pvoRequest As System.Net.HttpWebRequest, pvoResponse As Net.HttpWebResponse)
sbSaveCookiesFrom(pvoResponse)
End Sub
Protected Sub event_OnPreHandleDocument(pvoHTMLDocument As HtmlAgilityPack.HtmlDocument)
sbSaveHtmlDocument(pvoHTMLDocument)
End Sub
'-----------------------------------------------------------------------------------------------------
'Form Elements class
' Note: This element class will only capture (any) INPUT elements only, which should be enough
' for most cases. It can be easily modified to add other SELECT, TEXTAREA, etc voInputs
'-----------------------------------------------------------------------------------------------------
Public Class clsFormElementCollection
Inherits Dictionary(Of String, String)
Public Sub New(htmlDoc As HtmlAgilityPack.HtmlDocument)
Dim voInputs As Collections.Generic.IEnumerable(Of HtmlAgilityPack.HtmlNode) = htmlDoc.DocumentNode.Descendants("input")
For Each voInput As HtmlAgilityPack.HtmlNode In voInputs
Dim vsName = voInput.GetAttributeValue("name", "undefined")
Dim vsValue = voInput.GetAttributeValue("value", "")
If vsName <> "undefined" Then Add(vsName, vsValue)
Next
End Sub
Public Function fnsAssemblePostPayload() As String
Dim sb As New Text.StringBuilder
For Each voKeyValuePair In Me
Dim vsValue = System.Web.HttpUtility.UrlEncode(voKeyValuePair.Value)
sb.Append("&" & voKeyValuePair.Key & "=" & vsValue)
Next
Return sb.ToString.Substring(1)
End Function
End Class
End Class
Just make the above into a class object and instantiate it. The usage example is in the comment. You want the vsResponseHTML string.

Validate ASP.NET membership Username and Password when IsApproved is false

How can I check if the password entered by the user matches the password stored in the database when the IsApproved value is FALSE?
What I hope to do is as follows...
User registers - details saved and IsApproved is set to false
User recieves welcome email with membership confiirmation link
User clicks link in email - IsApproved is set to True at this point
User can NOW login
Okay everyting is fine with all of the above and i dont percieve any problems.
Where I'm having issues is...
When the user attempts to login and his/her IsApproved flag is FALSE
I need to cross reference his/her password wih the one stored in DB
And thats where i'm stuck.
The idea was to cross check the password, and if the user entered VALID credentials then to show a message to the user to say ACTIVATE your membership by clicking in the email blah blah blah.
But even if the password entered matches, because I cannot check it in the code the ValidateUser function always returns false because IsApproved is set to false!
Can anyone point me in the right direction please?
ALSO I dont actually need to see the password, so even if theres a sealed function I can call that simply confirms if the pasword matches thats fine too...
Below is my code block..
Public Function ValidateUser(ByVal Username As String, ByVal Password As String, ByRef PwdMatches As Boolean, ByRef Approved As Boolean) As Boolean Implements IMembershipService.ValidateUser
'
Dim ThisMember As MembershipUser = Nothing
Dim ThisResult As Boolean = Nothing
'
Approved = False
ThisResult = False
PwdMatches = False
If String.IsNullOrEmpty(Username) Then
Throw New ArgumentException("Value cannot be null or empty.", "Username")
ElseIf String.IsNullOrEmpty(Password) Then
Throw New ArgumentException("Value cannot be null or empty.", "Password")
ElseIf _Provider.ValidateUser(Username, Password) Then
ThisResult = True
Else
Try
ThisMember = _Provider.GetUser(Username, False)
Try
If (ThisMember Is Nothing) = False Then
Approved = ThisMember.IsApproved
Try
<!-- This is the point im stuck on -->
If Password_Matches_With_Password_In_Db Then
PwdMatches = True
Else
PwdMatches = False
End If
Catch ex As Exception
ThisResult = False
End Try
Else
ThisResult = False
End If
Catch ex As Exception
ThisResult = False
End Try
Catch ex As Exception
ThisResult = False
End Try
End If
Return ThisResult
ThisMember = Nothing
ThisResult = Nothing
End Function
I think one way to do it create a table that stores user accounts pending for approval. When user registers, populate this table with the userID or userName or set some flags indicating users who account has not been activated and who mails have been sent. Check this table when user logs in, if exist or flag not set, display "Activate your account to user"
Write a function that connects to the DB and use the userId to get the approval status from Aspnet_Membership table. The column name is IsApproved which is true or false
Dim user As MembershipUser = Membership.GetUser(userName);
Dim isApproved As Boolean = myMethodCheckIfUserIsApproved(user.ProviderUserKey); //userID
You should be able to call the Membership GetPassword method, passing Nothing in as the passwordAnswer parameter, which should just cause the password to be returned.
A disclaimer on this approach, however: we have implemented our own membership provider and SQL, and I don't have the original code to validate this against, so there may be something in the default provider that would prevent this approach, but it is worth trying.
EDIT:
In the case that the password is hashed, a possible solution to the problem is to perform a direct database query against the users table to get the state of the IsApproved flag. You could do this either before or after the call to GetUser, depending on how much you trust your end users (if you don't trust them, I would call it after in order to prevent someone from trying multiple users to see which are active).
UPDATE & ANSWER TO MY QUESTION
Hello everyone who replied to my question and thank you for your help,
It seems I was barking up the wrong tree by trying to validate the PASSWORD before trying to see if the account membership had been approved.
I have resolved the issue in a VERY SIMPLE WAY indeed.
This is how I did and I did not need to DIRECTLY interogate the database password field nor did i have to worry about hashing the password.
First of all I modified the default VALIDATELUSER call declaration....
in the SERVICES region of the ACCOUNTS MODEL
from...
Function ValidateUser(ByVal Username As String, ByVal Password As String) As Boolean
To...
Function ValidateUser(ByVal Username As String, ByVal Password As String, ByRef IsApproved As Boolean) As Boolean
This enabled me to call my newly modfied validation process also in the SERVICES region of the Accounts model where the ORGINIAL CODE was as follows...
Public Function ValidateUser(ByVal userName As String, ByVal password As String) As Boolean Implements IMembershipService.ValidateUser
If String.IsNullOrEmpty(userName) Then Throw New ArgumentException("Value cannot be null or empty.", "userName")
If String.IsNullOrEmpty(password) Then Throw New ArgumentException("Value cannot be null or empty.", "password")
Return _provider.ValidateUser(userName, password)
End Function
And the MODIFIED function which is now as follows...
Public Function ValidateUser(ByVal Username As String, ByVal Password As String, ByRef Approved As Boolean) As Boolean Implements IMembershipService.ValidateUser
Dim ThisMember As MembershipUser = Nothing
Dim ThisResult As Boolean = Nothing
'
Approved = False
ThisResult = False
If String.IsNullOrEmpty(Username) Then
Throw New ArgumentException("Value cannot be null or empty.", "Username")
ElseIf String.IsNullOrEmpty(Password) Then
Throw New ArgumentException("Value cannot be null or empty.", "Password")
ElseIf _Provider.ValidateUser(Username, Password) Then
ThisResult = True
Else
ThisMember = _Provider.GetUser(Username, False)
If (ThisMember Is Nothing) = False Then
Approved = ThisMember.IsApproved
End If
End If
Return ThisResult
ThisMember = Nothing
ThisResult = Nothing
End Function
I'm much happier with this prcoedure than with messing about with direct manipulation of the DB and also hashing the password.
So in effect, it was more about the original sequence of processing being back to front....
IE.
Not (1)validate login credentials then (2)check if email confirmed? (via link in welcome message)
but rather...
(1)Email Confirmed then (2)validate login credentials

System.Net.Mail.MailAddress allows commas in email address?

Recently, I updated some code to use System.Net.Mail.MailAddress() to check if an e-mail address is valid or not. Shortly after, I noticed some email addresses with commas in the domain name are considered valid, for example, the code below will indicate the email address is Valid???
Good grief! -- how are the rest of you handling this??
dim ok as Boolean
dim test_str as String = "someone#comma,com"
dim email as System.Net.Mail.MailAddress
ok = true
Try
email = new System.Net.Mail.MailAddress( test_str )
Catch ex As Exception
ok = false
End Try
if ( ok ) then
response.write( "Valid" )
else
response.write( "INVALID" )
end if

Resources