hexadecimal value 0x1F, is an invalid character - asp.net

I am getting the following error:
' ', hexadecimal value 0x1F, is an invalid character
Here is my function. I get this error when it hits "reader.MoveToContent()" for the first time. Can anyone point me in the right direction?
Public Function GetSyndicationFeedData(ByVal urlFeedLocation As String) As SyndicationFeed
Dim settings As New XmlReaderSettings() With { _
.IgnoreWhitespace = True, _
.CheckCharacters = True, _
.CloseInput = True, _
.IgnoreComments = True, _
.IgnoreProcessingInstructions = True _
}
If [String].IsNullOrEmpty(urlFeedLocation) Then
Return Nothing
End If
Using reader As XmlReader = XmlReader.Create(urlFeedLocation, settings)
If reader.ReadState = ReadState.Initial Then
reader.MoveToContent()
End If
' Now try reading...
Dim atom As New Atom10FeedFormatter()
Dim rss20 As New Rss20FeedFormatter()
' Atom
If atom.CanRead(reader) Then
atom.ReadFrom(reader)
Return atom.Feed
'Rss 2.0
ElseIf rss20.CanRead(reader) Then
rss20.ReadFrom(reader)
Return rss20.Feed
Else
Return Nothing
End If
End Using
End Function

You can use the following code (sorry but it is in c#) to download the feed and replace the offending character.
var client = new WebClient();
var feedAsString = client.DownloadString(urlFeedLocation).Replace((char)(0x1F), Convert.ToChar(""));
using (XmlReader reader = XmlReader.Create(new MemoryStream(Encoding.Default.GetBytes(feedAsString)), settings))
{
// remainder of your code here
}

Related

reCaptcha - reading JSON response

I get a response from the reCapture and need to read the "success" value, but get the error:
Public member 'success' on type 'Dictionary(Of String,Object)' not found.
Response
{ "success": true, "challenge_ts": "2017-02-20T13:55:01Z", "hostname": "domain.co.uk" }
I'm trying to access it using:
data.success
Full code
Dim Response As String = Request.Form("g-recaptcha-response")
Dim Valid As Boolean = False
Dim req As HttpWebRequest = DirectCast(WebRequest.Create(Convert.ToString("https://www.google.com/recaptcha/api/siteverify?secret=" & SecretKey & "&response=") & Response), HttpWebRequest)
Try
Using wResponse As WebResponse = req.GetResponse()
Using readStream As New StreamReader(wResponse.GetResponseStream())
Dim jsonResponse As String = readStream.ReadToEnd()
Dim js As New JavaScriptSerializer()
Dim data As Object = js.Deserialize(Of Object)(jsonResponse)
Valid = Convert.ToBoolean(data.success)
End Using
End Using
Return Valid
Catch ex As WebException
Throw ex
End Try
Got the answer in the end so in case this helps anyone it's:
data("success")
Rather than
data.success

Trying to get a querystring variable with an ashx

I have been trying to sort this out all day with lots of Googling but with little effect so thanks in advance if you read and are able to help.
I have a simple page which allows a user to select files and upload to an Amazon bucket, the first page looks like this:
var checkError = false;
$(window).load(
function () {
$("#<%=FileImages.ClientID %>").fileUpload({
'fileSizeLimit': '100MB',
'uploader': 'scripts/uploader.swf',
'cancelImg': 'images/cancel.png',
'buttonText': 'Upload Files',
'script': 'UploadVB.ashx?gid=56',
'folder': 'uploads',
'multi': true,
'auto': true,
'onAllComplete': function (uploads) {
if (!checkError) {
location.href = "finished";
}
},
'onComplete': function (event, ID, fileObj, response, data) {
if (200 != parseInt(response)) {
checkError = true;
$('#FileImages' + ID).addClass('uploadifyError');
$('#FileImages' + ID + ' .percentage').text(' - ' + response);
return false;
}
}
});
}
);
Note the gid=56. It then sends the files over to UploadVB.ashx and this looks like this:
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim awsRegion As Amazon.RegionEndpoint = Amazon.RegionEndpoint.EUWest1
Dim client As New AmazonS3Client(System.Configuration.ConfigurationManager.AppSettings("AWSAccessKey").ToString(), System.Configuration.ConfigurationManager.AppSettings("AWSSecretKey").ToString(), awsRegion)
Dim fileID As String = Guid.NewGuid().ToString("N")
Dim postedFile As HttpPostedFile = context.Request.Files("Filedata")
Dim galleryid = context.Request.QueryString("gid")
Try
Dim filename As String = Path.GetFileName(postedFile.FileName)
'### I WANT TO SUBMIT THE FILENAME AND ID INTO A TABLE HERE ######
AddPortfolioPhoto(filename, Convert.ToInt16(galleryid))
'#################################################################
Dim S3_KEY As [String] = filename.Replace(" ", "")
Dim request As New PutObjectRequest()
With request
.BucketName = System.Configuration.ConfigurationManager.AppSettings("AWSBucketName").ToString()
.Key = S3_KEY
.InputStream = postedFile.InputStream
End With
client.PutObject(request)
context.Response.Write("200")
context.Response.StatusCode = 200
Catch ex As Exception
context.Response.Write("AWS ERROR :: " + ex.Message)
End Try
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
Every time I run this above it just doesn't do anything, If I remove this line:
AddPortfolioPhoto(filename, Convert.ToInt16(galleryid))
it works great but it is crucial I get this inserted into the database someway and I just can't seem to be able to grab the gid value.
Any help is greatly appreciated.
Public Shared Sub AddPortfolioPhoto(ByVal fn As String, gid As Integer)
Dim Writer As New Data.SqlClient.SqlCommand
Writer.CommandType = Data.CommandType.StoredProcedure
Writer.CommandText = "BCMS_AddGalleryPhoto"
Writer.Connection = New Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.AppSettings("sqlstr"))
Writer.Parameters.AddWithValue("#imgstr", Data.SqlTypes.SqlString.Null).Value = fn
Writer.Parameters.AddWithValue("#galleryid", Data.SqlTypes.SqlInt32.Null).Value = gid
Writer.Parameters.AddWithValue("#so", Data.SqlTypes.SqlInt32.Null).Value = 0
Writer.Parameters.AddWithValue("#featured", Data.SqlTypes.SqlInt32.Null).Value = 0
Writer.Prepare()
Writer.Connection.Open()
Writer.ExecuteNonQuery()
Writer.Connection.Close()
End Sub
Looks like with your help I may have gotten to the bottom of this, the value I was expecting (56) wasn't what I was actually getting, I was actually getting "uploads" in the same variable so sending a string down to this method was never going to work, thanks #matt-dot-net for suggesting and thanks Andrew Morton for the tip on dispose, I will use that rather than close.

Consuming Webservice - Sending Signature- Error X509Certificate2 type was not expected

I'm consume an external webservice for sending data, using a web application in asp.net and Visual Studio 2010. The
sending of data must be digitally signed using a digital signature. The webservice contains the Signature class, where I
can fill all required values ​​(SignedInfo, SignatureValue, KeyInfo).
I'm trying to fill the KeyInfo structure with the certificate like this:
Dim Sig As New RSP.SignatureType
(...)
Sig.SignedInfo = Sig_info
(...)
Sig.SignatureValue = Sig_value
Dim rspKey_info As New RSP.KeyInfoType()
Dim rspX509 As New RSP.X509DataType()
Dim arrCertificate As X509Certificate2()
arrCertificate = myF.ReturnCertificateCC()
rspKey_info.ItemsElementName = New RSP.ItemsChoiceType2(0) {}
rspKey_info.ItemsElementName(0) = RSP.ItemsChoiceType2.X509Data
rspKey_info.Items = New Object(0) {}
rspX509.ItemsElementName = New RSP.ItemsChoiceType2(0) {}
rspX509.ItemsElementName(0) = RSP.ItemsChoiceType2.X509Data
rspX509.Items = New Object(0) {}
rspX509.Items(0) = arrCertificate (0)
Sig.KeyInfo = rspKey_info
xmlString = myF.SerializeAnObject(Sig)
When I try to serialize the Signature Object, an error occur:
"Error generating the XML document."
InnerException:
"{ " The System.Security.Cryptography.X509Certificates.X509Certificate2 type was not expected . Use XmlInclude or
SoapInclude attribute to specify types that are not known statically. "}"
Public Function SerializeAnObject(ByVal obj As Object) As String
Dim doc As System.Xml.XmlDocument = New XmlDocument()
Dim serializer As System.Xml.Serialization.XmlSerializer = New System.Xml.Serialization.XmlSerializer(obj.GetType())
Dim stream As System.IO.MemoryStream = New System.IO.MemoryStream()
Try
serializer.Serialize(stream, obj)
stream.Position = 0
doc.Load(stream)
Return doc.InnerXml
Catch ex As Exception
Return ""
Finally
stream.Close()
stream.Dispose()
End Try
'#utilização
'dim xmlObject As string = SerializeAnObject(myClass)
End Function
Please help me...
I'm at several days trying to solve this...
Thanks in advance!
Regards!
rspX509.ItemsElementName = New RSP.ItemsChoiceType(0) {}
rspX509.ItemsElementName(0) = RSP.ItemsChoiceType.X509Certificate
rspX509.Items = New Object(0) {}
rspX509.Items(0) = arrCertificate (0)
rspKey_info.Items(0) = rspX509

Json A circular reference was detected while serializing an object of type… »

i'm traying to display a list of competitions contained in my data base , but it strikes me each time this error:
A circular reference was detected while serializing an object of type 'WhereSelectListIterator2[jTableSampleDatabaseLayer.Hik.JTable.Models.Concour,VB$AnonymousType_28[System.String,System.Nullable1[System.Int32],System.Nullable1[System.Int32],System.DateTime,System.Int32,System.Int32,System.String,System.Int32]]' on type 'System.Collections.Generic.IEnumerable1[jTableSampleDatabaseLayer.Hik.JTable.Models.Concour]``'.
here is my code in vb :
Dim x As jTableSampleDatabaseLayer.totofootEntities = _
New jTableSampleDatabaseLayer.totofootEntities
Dim dataSource = New MemoryDataSource()
Dim liste As List(Of Concour) = x.Concours.ToList()
dataSource.Concours.AddRange(liste)
''ajout
Try
Dim concours = dataSource.Concours
Return Json(New With { _
Key .Result = "OK", _
Key .Records = concours _
}, JsonRequestBehavior.AllowGet)
Catch ex As Exception
Return Json(New With { _
Key .Result = "ERROR", _
Key .Message = ex.Message _
}, JsonRequestBehavior.AllowGet)
End Try
How can I avoid this error ?
I've tried to change the code in order to avoid this error
now i don't get anymore the error but i'm getting the result with all the attribute are equal to null and the same number of registration in my DB
{"Result":"OK","Records":[{"numero_concours":null,"numero_etape":0,"numero_type":null,"numero_nature":null,"titre_concours":null,"date_de_sortie":"/Date(-62135596800000)/","nbre_matchs":0,"nbre_rangs":0,"Etape":null,"Nature":null,"Type":null,"Primes":[],"Rangs":[],"Recettes":[],"Rencontres":[]},{"numero_concours":null,"numero_etape":0,"numero_type":null,"numero_nature":null,"titre_concours":null,"date_de_sortie":"/Date(-62135596800000)/","nbre_matchs":0,"nbre_rangs":0,"Etape":null,"Nature":null,"Type":null,"Primes":[],"Rangs":[],"Recettes":[],"Rencontres":[]}]}``'.
the new code :
Dim x As jTableSampleDatabaseLayer.totofootEntities = New jTableSampleDatabaseLayer.totofootEntities
Dim dataSource = New MemoryDataSource()
Dim liste As List(Of Concour) = x.Concours.ToList()
dataSource.Concours.AddRange(liste.Select(Function(p) New Concour))
''ajout
Try
Dim concours = dataSource.Concours
Return Json(New With {Key .Result = "OK", Key .Records = concours}, JsonRequestBehavior.AllowGet)
Catch ex As Exception
Return Json(New With {Key .Result = "ERROR", Key .Message = ex.Message}, JsonRequestBehavior.AllowGet)
End Try

Active Directory - check if password never expires?

Is there a way in Visual Basic to check if the user's password is set to never expire in Active Directory?
I've found a way to find the last date it was changed, but I can't find the other available options.
Dim de As DirectoryServices.DirectoryEntry = GetUser(uDetails.username)
Dim objUser = GetObject(de.Path)
If objUser.PasswordLastChanged < DateTime.Now.AddMonths(-3) Then
...
Where can I find a list of all available objUser properties?
If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:
Managing Directory Security Principals in the .NET Framework 3.5
MSDN docs on System.DirectoryServices.AccountManagement
Basically, you can define a domain context and easily find users and/or groups in AD:
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");
if(user != null)
{
// one of the properties exposed is "PasswordNeverExpires" (bool)
if(user.PasswordNeverExpires)
{
// do something here....
...
}
}
The new S.DS.AM makes it really easy to play around with users and groups in AD!
For .NET 2.0 you can use some LDAP. The magic part is userAccountControl:1.2.840.113556.1.4.803:=65536. The first part is the property that you want to search, the second means "bitwise AND" and the third is the bitwise flag to check, in this case the 17th bit. You can see more on the bitwise AND and OR in Active Directory in How to query Active Directory by using a bitwise filter.
In the code below update the SearchRoot variable with your domain controller (DC) and FQDN.
Imports System.DirectoryServices
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
''//Bind to the root of our domain
''// YOU_DOMAIN_CONTROLLER should be one of your DCs
''// EXAMPLE and COM are the parts of your FQDN
Dim SearchRoot As DirectoryEntry = New DirectoryEntry("LDAP://YOUR_DOMAIN_CONTROLLER/dc=EXAMPLE,dc=COM")
''//Create a searcher bound to the root
Dim Searcher As DirectorySearcher = New DirectorySearcher(SearchRoot)
''//Set our filer. The last part is dumb but that is the way that LDAP was built.
''//It basically does a bitwise AND looking for the 17th bit to be set on that property "userAccountControl" which is the "password never expires" bit
''//See this if you care to learn more http://support.microsoft.com/kb/269181
Searcher.Filter = "(&(objectCategory=person)(objectClass=user)(userAccountControl:1.2.840.113556.1.4.803:=65536))"
''//Find all of the results
Dim Results = Searcher.FindAll()
Dim DE As DirectoryEntry
''//Loop through each result
For Each R As SearchResult In Results
''//Get the result as a DirectoryEntry object
DE = R.GetDirectoryEntry()
''//Output the object name
Console.WriteLine(DE.Name)
Next
End Sub
End Class
public bool isPasswordExpired(String p_UserName, String p_DomainName)
{
bool m_Check=false;
int m_Val1 = (int)de1.Properties["userAccountControl"].Value;
int m_Val2 = (int) 0x10000;
if (Convert.ToBoolean(m_Val1 & m_Val2))
{
m_Check = true;
} //end
return m_Check
}
You could use the following code originally from here that I've translated from C# and modified a little bit according to your question (added a getter):
Dim pwdNeverExpires = getPasswordNeverExpires("Tim")
setPasswordNeverExpires("Tim", True)
' See http://msdn.microsoft.com/en-us/library/aa772300(VS.85).aspx
<Flags()> _
Private Enum ADS_USER_FLAG_ENUM
ADS_UF_SCRIPT = 1
' 0x1
ADS_UF_ACCOUNTDISABLE = 2
' 0x2
ADS_UF_HOMEDIR_REQUIRED = 8
' 0x8
ADS_UF_LOCKOUT = 16
' 0x10
ADS_UF_PASSWD_NOTREQD = 32
' 0x20
ADS_UF_PASSWD_CANT_CHANGE = 64
' 0x40
ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 128
' 0x80
ADS_UF_TEMP_DUPLICATE_ACCOUNT = 256
' 0x100
ADS_UF_NORMAL_ACCOUNT = 512
' 0x200
ADS_UF_INTERDOMAIN_TRUST_ACCOUNT = 2048
' 0x800
ADS_UF_WORKSTATION_TRUST_ACCOUNT = 4096
' 0x1000
ADS_UF_SERVER_TRUST_ACCOUNT = 8192
' 0x2000
ADS_UF_DONT_EXPIRE_PASSWD = 65536
' 0x10000
ADS_UF_MNS_LOGON_ACCOUNT = 131072
' 0x20000
ADS_UF_SMARTCARD_REQUIRED = 262144
' 0x40000
ADS_UF_TRUSTED_FOR_DELEGATION = 524288
' 0x80000
ADS_UF_NOT_DELEGATED = 1048576
' 0x100000
ADS_UF_USE_DES_KEY_ONLY = 2097152
' 0x200000
ADS_UF_DONT_REQUIRE_PREAUTH = 4194304
' 0x400000
ADS_UF_PASSWORD_EXPIRED = 8388608
' 0x800000
ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 16777216
' 0x1000000
End Enum
Protected Overridable Function getPasswordNeverExpires(ByVal userName As String) As Boolean
Const userNameString As String = "userName"
Const userFlagsString As String = "userFlags"
Dim machineName As String = Environment.MachineName
Dim userInThisComputerDirectoryEntry As DirectoryEntry = getUserInThisComputerDirectoryEntry(machineName, userName)
If userInThisComputerDirectoryEntry Is Nothing Then
Throw New ArgumentException("not found in " & machineName, userNameString)
End If
Dim userFlagsProperties As PropertyValueCollection = userInThisComputerDirectoryEntry.Properties(userFlagsString)
Dim userFlags As ADS_USER_FLAG_ENUM = CType(userFlagsProperties.Value, ADS_USER_FLAG_ENUM)
Return userFlags = (userFlags Or ADS_USER_FLAG_ENUM.ADS_UF_DONT_EXPIRE_PASSWD)
End Function
Protected Overridable Sub setPasswordNeverExpires(ByVal userName As String, ByVal passwordNeverExpires As Boolean)
Const userNameString As String = "userName"
Const userFlagsString As String = "userFlags"
Dim machineName As String = Environment.MachineName
Dim userInThisComputerDirectoryEntry As DirectoryEntry = getUserInThisComputerDirectoryEntry(machineName, userName)
If userInThisComputerDirectoryEntry Is Nothing Then
Throw New ArgumentException("not found in " & machineName, userNameString)
End If
Dim userFlagsProperties As PropertyValueCollection = userInThisComputerDirectoryEntry.Properties(userFlagsString)
Dim userFlags As ADS_USER_FLAG_ENUM = CType(userFlagsProperties.Value, ADS_USER_FLAG_ENUM)
Dim newUserFlags As ADS_USER_FLAG_ENUM = userFlags
If passwordNeverExpires Then
newUserFlags = newUserFlags Or ADS_USER_FLAG_ENUM.ADS_UF_DONT_EXPIRE_PASSWD
Else
newUserFlags = newUserFlags And (Not ADS_USER_FLAG_ENUM.ADS_UF_DONT_EXPIRE_PASSWD)
End If
userFlagsProperties.Value = newUserFlags
userInThisComputerDirectoryEntry.CommitChanges()
End Sub
Protected Overridable Function getUserInThisComputerDirectoryEntry(ByVal machineName As String, ByVal userName As String) As DirectoryEntry
Dim computerDirectoryEntry As DirectoryEntry = getComputerDirectoryEntry(machineName)
Const userSchemaClassName As String = "user"
Return computerDirectoryEntry.Children.Find(userName, userSchemaClassName)
End Function
Protected Overridable Function getComputerDirectoryEntry(ByVal machineName As String) As DirectoryEntry
'Initiate DirectoryEntry Class To Connect Through WINNT Protocol
' see: http://msdn.microsoft.com/en-us/library/system.directoryservices.directoryentry.path.aspx
Const pathUsingWinNTComputerMask As String = "WinNT://{0},computer"
Dim path As String = String.Format(pathUsingWinNTComputerMask, machineName)
Dim thisComputerDirectoryEntry As New DirectoryEntry(path)
Return thisComputerDirectoryEntry
End Function
You have to add a reference to System.DirectoryServices. I have tested it on Windows Server 2008 with .NET Framework 4 (it should also work under 2.0) without Active Directory. But check it out yourself and feel free to extend it to get/set other properties as well or connect to other machines (SomeDomain/OtherComputerName instead of Environment.MachineName).

Resources