Error: Expecting state. Could not Deserialize JSON Object - asp.net

We are trying to consume WCF service which returns employee details in JSON Format.
like:
{
"d": [{
"__type": "Employee:#",
"BigThumbNailURI": null,
"ID": 1,
"Name": "E1"
}, {
"__type": "Employee:#",
"BigThumbNailURI": null,
"ID": 2,
"Name": "E1"
}]
}
From VB.net code behind when I am trying to deserialize it it's stating that
"Expecting state 'Element'.. Encountered 'Text' with name '', namespace ''."
Deserialization code snippet:
Dim serializer = New DataContractJsonSerializer(GetType(List(Of Employee)))
Dim memoryStream = New MemoryStream()
Dim s = msg.Content.ReadAsString()
serializer.WriteObject(memoryStream, s)
memoryStream.Position = 0
' Code for Deserilization
Dim obj As List(Of Employee) = serializer.ReadObject(memoryStream)
memoryStream.Close()
'Employee Class
<DataContract()> _
Public Class Employee
Private _Name As String
<DataMember()> _
Public Property Name() As String
Get
Return _Name
End Get
Set(ByVal value As String)
_Name = value
End Set
End Property
Private _id As Integer
<DataMember()> _
Public Property ID() As Integer
Get
Return _id
End Get
Set(ByVal value As Integer)
_id = value
End Set
End Property
End Class
Has anyone encountered this problem?

Found resolution. To solve this issue, do not use that MemoryStream anymore.
Pass the JSON object to deserializer directly as follows:
Dim serializer = New DataContractJsonSerializer(GetType(List(Of Employee)))
' Code for Deserilization
Dim obj As List(Of Employee) = serializer.ReadObject(msg.Content.ReadAsString())
memoryStream.Close()

Here are two generic methods for serializing and deserializing.
/// <summary>
/// Serializes the specified object into json notation.
/// </summary>
/// <typeparam name="T">Type of the object to be serialized.</typeparam>
/// <param name="obj">The object to be serialized.</param>
/// <returns>The serialized object as a json string.</returns>
public static string Serialize<T>(T obj)
{
Utils.ArgumentValidation.EnsureNotNull(obj, "obj");
string retVal;
using (MemoryStream ms = new MemoryStream())
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
serializer.WriteObject(ms, obj);
retVal = Encoding.UTF8.GetString(ms.ToArray());
}
return retVal;
}
/// <summary>
/// Deserializes the specified json string into object of type T.
/// </summary>
/// <typeparam name="T">Type of the object to be returned.</typeparam>
/// <param name="json">The json string of the object.</param>
/// <returns>The deserialized object from the json string.</returns>
public static T Deserialize<T>(string json)
{
Utils.ArgumentValidation.EnsureNotNull(json, "json");
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
}
return obj;
}
You'll need these namespaces
using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

Related

Calling and serializing FB feed

I am calling FB feed from multiple FB pages with
/posts?ids=OI.Plavipingvin,217384491624554&limit=5&fields=message,created_time,id
This is the feed I get:
{
"217384491624554": {
"data": [
{
"message": "Obećanje i zavjet položeni. Dobrodošli u OI Javor ❤",
"created_time": "2017-01-08T01:05:25+0000",
"id": "217384491624554_1575515795811410"
},
{
"message": "Zimovanje u punom tijeku :-)",
"created_time": "2017-01-04T10:06:57+0000",
"id": "217384491624554_1572127976150192"
}
],
"paging": {
"previous": "https://graph.facebook.com/v2.8/217384491624554/posts?fields=message,created_time,id&limit=2&format=json&since=1483837525&access_token=EAACEdEose0cBAMlhIYetCMo0m83Jdo3F7rk4NYmm47Q1T19UDxlKhMQnjDW4Mmelqu3vzTITnVA7E0ZBgl6jDmlHC8J7ZCX4TW2xB0xoHIySu3MK5d9yUWjqMLdUrRab9KTfH1WyzpEfIbxG7JlhPnZACfiFWFfhvO9vrAZCrAZDZD&__paging_token=enc_AdB6GEshkXkXuRJcuiHCF1aoS4rK7Myp3P6mFZAUFeZAPbRVdtmihE7UAOIlFDuTjVKHvmBeiMLmWfIZBfCER7cYrS08kccUDDoixEb2ZABASuwAigZDZD&__previous=1",
"next": "https://graph.facebook.com/v2.8/217384491624554/posts?fields=message,created_time,id&limit=2&format=json&access_token=EAACEdEose0cBAMlhIYetCMo0m83Jdo3F7rk4NYmm47Q1T19UDxlKhMQnjDW4Mmelqu3vzTITnVA7E0ZBgl6jDmlHC8J7ZCX4TW2xB0xoHIySu3MK5d9yUWjqMLdUrRab9KTfH1WyzpEfIbxG7JlhPnZACfiFWFfhvO9vrAZCrAZDZD&until=1483524417&__paging_token=enc_AdBeiIQZBem7NbobO8r183HtpPnZAOY6CRyehrr8uDJZBXkSS5kKS3YpqdmosFZCGZBobXwMnKW4hEsAIEZCjhYCAL2NdAX7ZCZAyWHZB7GhQCS0IQIqEZBwZDZD"
}
},
"OI.Plavipingvin": {
"data": [
{
"message": "Sretnu novu godinu želi vam Uprava odreda. Budite sretni i zadovoljni. I naravno - pripravni za nove avanture! 🎈 🎈 🎈",
"created_time": "2017-01-02T10:07:27+0000",
"id": "379925365427474_1274199672666701"
},
{
"message": "Jutros na Omanovcu. Imamo snijeg! :)",
"created_time": "2016-12-28T07:03:07+0000",
"id": "379925365427474_1269358063150862"
}
],
"paging": {
"previous": "https://graph.facebook.com/v2.8/379925365427474/posts?fields=message,created_time,id&limit=2&format=json&since=1483351647&access_token=EAACEdEose0cBAMlhIYetCMo0m83Jdo3F7rk4NYmm47Q1T19UDxlKhMQnjDW4Mmelqu3vzTITnVA7E0ZBgl6jDmlHC8J7ZCX4TW2xB0xoHIySu3MK5d9yUWjqMLdUrRab9KTfH1WyzpEfIbxG7JlhPnZACfiFWFfhvO9vrAZCrAZDZD&__paging_token=enc_AdDjsccg8E9vHw7XXgXW22NDK0l3MH4mR5XvwXidebNK2Kb8bdewjPiTLGDP8yNw8rpcHYT8VME5YPxLhZC0QZCjdLkHBYJCQZBYdQQWsfmhmC2yQZDZD&__previous=1",
"next": "https://graph.facebook.com/v2.8/379925365427474/posts?fields=message,created_time,id&limit=2&format=json&access_token=EAACEdEose0cBAMlhIYetCMo0m83Jdo3F7rk4NYmm47Q1T19UDxlKhMQnjDW4Mmelqu3vzTITnVA7E0ZBgl6jDmlHC8J7ZCX4TW2xB0xoHIySu3MK5d9yUWjqMLdUrRab9KTfH1WyzpEfIbxG7JlhPnZACfiFWFfhvO9vrAZCrAZDZD&until=1482908587&__paging_token=enc_AdDZCnhwlRCxibv0aGr141JPdbcHcJssKFjhtToaTpfqKbZABvo5g0fhtCgDpwCNoMBopGK4o0CJxXzRyRJKxLCqOh0belZCXBQdTNZCEF5eRuu6agZDZD"
}
}
}
My current FBClass:
Public Class FBData
Public Property data As New List(Of FBFeed)
End Class
Public Class FBFeed
Public Property message As String
Public Property created_time As DateTime
Public Property id As String
End Class
Current GetPosts function, ordering and showing result:
Public Shared Function GetPosts( accessToken As String ) As FBData
Dim APIlink As String = "https://graph.facebook.com/posts?ids=OI.Plavipingvin,217384491624554&limit=5&fields=message,created_time,id&access_token=" & accessToken
Dim client As New WebClient()
client.Encoding = System.Text.Encoding.UTF8
Dim strJson As [String] = client.DownloadString(APIlink)
Dim result As FBData = Newtonsoft.Json.JsonConvert.DeserializeObject(Of FBData)( strJson )
Return result
End Function
Dim array1 As FBData = GetPosts ( accessToken )
For Each Msg As FBFeed In array1.data.OrderByDescending(Function(x) x.created_time)
Response.Write( i & ". " & Msg.created_time & "<br />" )
Next
What FBClass should I use for serialization of this JSON and how to read FBClass list (or array)? I don't need User-ID or data tags.
While my other answer works, it's a bit clumsy if one has a bunch of feeds to deal with, so this should be a more effective answer. I chose not to edit the previous answer because it's valid depending on one's needs.
Given this revised class structure...
Public Class FBFeed
Public Property data As Datum()
Public Property paging As Paging
End Class
Public Class Datum
Public Property message As String
Public Property created_time As DateTime
Public Property id As String
End Class
Public Class Paging
Public Property previous As String
Public Property [next] As String
End Class
...and this revised GetPosts method...
Public Shared Function GetPosts(accessToken As String, ParamArray args() As String) As Dictionary(Of String, FBFeed)
'Dim APIlink As String = "https://graph.facebook.com/posts?ids=OI.Plavipingvin,217384491624554&limit=5&fields=message,created_time,id&access_token=" & accessToken
Dim Ids As String = Join(args, ",")
Dim APITemplate As String = "https://graph.facebook.com/posts?ids={0}&limit=5&fields=message,created_time,id&access_token={1}"
Dim APIlink As String = String.Format(APITemplate, Ids, accessToken)
Using client As New WebClient()
client.Encoding = Text.Encoding.UTF8
Dim strJson As String = client.DownloadString(APIlink)
Return Newtonsoft.Json.JsonConvert.DeserializeObject(Of Dictionary(Of String, FBFeed))(strJson)
End Using
End Function
...the usage in the page request handler becomes...
Dim MyData As New List(Of Datum)
Dim IdList As New List(Of String)
IdList.Add("OI.Plavipingvin")
IdList.Add("217384491624554")
With GetPosts("Access Token Here", IdList.ToArray)
' We have a Dictionary(Of String, FBFeed) we can flatten with SelectMany
' and consolidate the Datum arrays into the MyData List(Of Datum) above
MyData.AddRange(.Values.SelectMany(Function(x) x.data).ToList())
End With
For Each Msg As Datum In MyData.OrderByDescending(Function(x) x.created_time)
Response.Write(Msg.message & ". " & Msg.created_time & "<br />")
Next
The class structure would have to look like this:
Imports Newtonsoft.Json
Public Class FBData
<JsonProperty(PropertyName:="217384491624554")>
Public Property Feed_217384491624554 As FBFeed
<JsonProperty(PropertyName:="OI.Plavipingvin")>
Public Property Feed_OIPlavipingvin As FBFeed
End Class
Public Class FBFeed
Public Property data As Datum()
Public Property paging As Paging
End Class
Public Class Datum
Public Property message As String
Public Property created_time As DateTime
Public Property id As String
End Class
Public Class Paging
Public Property previous As String
Public Property [next] As String
End Class
Update: Usage:
Dim array1 As FBData = GetPosts ( accessToken )
Dim MyData As New List(Of Datum)
MyData.AddRange(array1.Feed_217384491624554.data)
MyData.AddRange(array1.Feed_OIPlavipingvin.data)
For Each Msg As Datum In MyData.OrderByDescending(Function(x) x.created_time)
Response.Write(Msg.message & ". " & Msg.created_time & "<br />")
Next

Asp.net code not working for implementing rijndael encryption, decryption?

I'm reading a book entitled beginning asp.net security from wrox and I'm in this part where it shows a code snippet for using rijndael the problem this example is not included in the downloadable source codes. I decided to seek (professional)help here in the forums.
It would be awesome if you try and test it as well and hopefully give an example(codes) on how I could implement it.
Here is the code:
public class EncryptionRijndael
{
public EncryptionRijndael()
{
//
// TODO: Add constructor logic here
//
}
public static byte[] GenerateRandomBytes(int length)
{
byte[] key = new byte[length];
RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();
provider.GetBytes(key);
return key;
}
public void GetKeyAndIVFromPasswordAndSalt(string password, byte[] salt,SymmetricAlgorithm symmetricAlgorithm,ref byte[] key, ref byte[] iv)
{
Rfc2898DeriveBytes rfc2898DeriveBytes =
new Rfc2898DeriveBytes(password, salt);
key =
rfc2898DeriveBytes.GetBytes(symmetricAlgorithm.KeySize / 8);
iv =
rfc2898DeriveBytes.GetBytes(symmetricAlgorithm.BlockSize / 8);
}
public static byte[] Encrypt(byte[] clearText, byte[] key, byte[] iv)
{
// Create an instance of our encyrption algorithm.
RijndaelManaged rijndael = new RijndaelManaged();
// Create an encryptor using our key and IV
ICryptoTransform transform = rijndael.CreateEncryptor(key, iv);
// Create the streams for input and output
MemoryStream outputStream = new MemoryStream();
CryptoStream inputStream = new CryptoStream(
outputStream,
transform,
CryptoStreamMode.Write);
// Feed our data into the crypto stream.
inputStream.Write(clearText, 0, clearText.Length);
// Flush the crypto stream.
inputStream.FlushFinalBlock();
// And finally return our encrypted data.
return outputStream.ToArray();
}
static byte[] Decrypt(byte[] cipherText, byte[] key, byte[] iv)
{
// Create an instance of our encyrption algorithm.
RijndaelManaged rijndael = new RijndaelManaged();
// Create an decryptor using our key and IV ;
ICryptoTransform transform = rijndael.CreateDecryptor(key, iv);
// Create the streams for input and output
MemoryStream outputStream = new MemoryStream();
CryptoStream inputStream = new CryptoStream(outputStream,transform,CryptoStreamMode.Write);
// Feed our data into the crypto stream.
inputStream.Write(cipherText, 0, cipher.Length);
// Flush the crypto stream.
inputStream.FlushFinalBlock();
// And finally return our decrypted data.
return outputStream.ToArray();
}
}
Sir/Ma'am your answers would be of great help. Thank you++
(it would be awesome if you could show me how to call encrypt and decrypt properly)
I have found that it is best to create a class to wrap your credentials and a separate one to do the encryption. Here is what I created... sorry it's in vb instead of c#:
Public Class SymmetricEncryptionCredentials
Private _keyIterations As Integer
Public ReadOnly Property ivString As String
Get
Return Convert.ToBase64String(Me.iv)
End Get
End Property
Public ReadOnly Property saltString() As String
Get
Return Convert.ToBase64String(Me.salt)
End Get
End Property
Public ReadOnly Property keyIterations As Integer
Get
Return _keyIterations
End Get
End Property
Private Property keyPassword() As String
Private Property salt() As Byte()
Private ReadOnly Property key() As Security.Cryptography.Rfc2898DeriveBytes
Get
Return New Security.Cryptography.Rfc2898DeriveBytes(keyPassword, salt, keyIterations)
End Get
End Property
Private Property iv() As Byte()
''' <summary>
''' Creates a set of encryption credentials based on the
''' provided key, ivPassword, and salt string.
''' </summary>
''' <param name="keyPassword">The Secret key used for encryption</param>
''' <param name="salt">The salt string (not secret) from which the salt
''' bytes are derived.</param>
''' <remarks></remarks>
Public Sub New(ByVal keyPassword As String, ByVal salt As String, ByVal iv As String, ByVal keyIterations As Integer)
Me.keyPassword = keyPassword
Me.iv = Convert.FromBase64String(iv)
Me.salt = Convert.FromBase64String(salt)
_keyIterations = keyIterations
End Sub
''' <summary>
''' Creates a new set of encryption credentials based on the
''' provided key, while making a ivPassword and salt.
''' </summary>
''' <param name="keyPassword">The Secret key used for encryption</param>
''' <remarks>Creates a new set of encryption credentials based on the
''' provided key password, while making a ivPassword and salt.</remarks>
Public Sub New(ByVal keyPassword As String, ByVal keyIterations As Integer)
Me.keyPassword = keyPassword
Me.iv = Passwords.GetRandomPassword(16, 16)
Me.salt = Passwords.GetRandomPassword()
_keyIterations = keyIterations
End Sub
''' <summary>
''' Creates a new set of encryption credentials based on the
''' provided key, while making a ivPassword and salt. Uses
''' default PBKDF iteration count.
''' </summary>
''' <param name="keyPassword">The Secret key used for encryption</param>
''' <remarks>Creates a new set of encryption credentials based on the
''' provided key password, while making a ivPassword and salt.</remarks>
Public Sub New(ByVal keyPassword As String)
Me.New(keyPassword, AppSettings("defaultKeyPBKDFIterations"))
End Sub
''' <summary>
''' Gets an AES Encryptor with key derived from RFC2898.
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Public Function GetAESEncryptor() As Security.Cryptography.ICryptoTransform
Dim aes As New Security.Cryptography.AesManaged
aes.KeySize = 256
aes.Key = Me.key.GetBytes(aes.KeySize / 8)
aes.IV = Me.iv
Return aes.CreateEncryptor()
End Function
Public Function GetAESDecryptor() As Security.Cryptography.ICryptoTransform
Dim aes As New Security.Cryptography.AesManaged
aes.KeySize = 256
aes.Key = Me.key.GetBytes(aes.KeySize / 8)
aes.IV = Me.iv
Return aes.CreateDecryptor
End Function
End Class
Public Class SymmetricEncryption
Public Shared Function Encrypt(ByVal unencryptedValue As String, creds As SymmetricEncryptionCredentials) As String
Dim inBytes() As Byte = System.Text.Encoding.UTF8.GetBytes(unencryptedValue)
Dim outBytes() As Byte
Using outStream As New IO.MemoryStream()
Using encryptStream As New System.Security.Cryptography.CryptoStream(outStream, creds.GetAESEncryptor, Security.Cryptography.CryptoStreamMode.Write)
encryptStream.Write(inBytes, 0, inBytes.Length)
encryptStream.FlushFinalBlock()
outBytes = outStream.ToArray
encryptStream.Close()
End Using
outStream.Close()
End Using
Dim outString As String = Convert.ToBase64String(outBytes)
Return outString
End Function
Public Shared Function Decrypt(ByVal encryptedValue As String, creds As SymmetricEncryptionCredentials) As String
Dim inBytes() As Byte = Convert.FromBase64String(encryptedValue)
Dim outString As String
Using outStream As New IO.MemoryStream
Using decryptionStream As New System.Security.Cryptography.CryptoStream(outStream, creds.GetAESDecryptor, Security.Cryptography.CryptoStreamMode.Write)
decryptionStream.Write(inBytes, 0, inBytes.Length)
decryptionStream.FlushFinalBlock()
Dim outBytes() As Byte = outStream.ToArray
outString = System.Text.Encoding.UTF8.GetString(outBytes)
decryptionStream.Close()
End Using
outStream.Close()
End Using
Return outString
End Function
End Class
Public Class Passwords
Public Shared Function GetRandomPassword(minLength As Integer, maxlength As Integer) As Byte()
' *** 1. Get how long the password will be
Dim rand As New Random
Dim passLength As Integer = rand.Next(minLength, maxlength)
' *** 2. Create an array of Bytes to hold the
' random numbers used to make the string's chars
Dim passBytes(passLength - 1) As Byte
' *** 3. Fill the array with random bytes.
Dim rng As New Security.Cryptography.RNGCryptoServiceProvider
rng.GetBytes(passBytes)
Return passBytes
End Function
Public Shared Function GetRandomPassword() As Byte()
Return GetRandomPassword(12, 32)
End Function
End Class

Query string module encryption not working

I did the query string encryption of my project using the example provided here.
When I run the project locally it works fine:
But when I publish it to my server, the encryption simply doesn't work.
The application on the server is running on Windows Server 2008 R2 and IIS 7.
Maybe there is something I must change on IIS? I have no clue.
Anyone?
Thank you.
EDIT:
Here is the code of the QueryStringModule class:
Imports System
Imports System.IO
Imports System.Web
Imports System.Text
Imports System.Security.Cryptography
''' <summary>
''' Summary description for QueryStringModule
''' </summary>
Public Class QueryStringModule
Implements IHttpModule
#Region "IHttpModule Members"
Sub Init(context As HttpApplication) Implements System.Web.IHttpModule.Init
AddHandler context.BeginRequest, AddressOf context_BeginRequest
End Sub
Sub Dispose() Implements System.Web.IHttpModule.Dispose
' Nothing to dispose
End Sub
#End Region
Private Const PARAMETER_NAME As String = "enc="
Private Const ENCRYPTION_KEY As String = "key"
Private Sub context_BeginRequest(sender As Object, e As EventArgs)
Dim context As HttpContext = HttpContext.Current
If context.Request.Url.OriginalString.Contains("aspx") AndAlso context.Request.RawUrl.Contains("?") Then
Dim query As String = ExtractQuery(context.Request.RawUrl)
Dim path As String = GetVirtualPath()
If query.StartsWith(PARAMETER_NAME, StringComparison.OrdinalIgnoreCase) Then
' Decrypts the query string and rewrites the path.
Dim rawQuery As String = query.Replace(PARAMETER_NAME, String.Empty)
Dim decryptedQuery As String = Decrypt(rawQuery)
context.RewritePath(path, String.Empty, decryptedQuery)
ElseIf context.Request.HttpMethod = "GET" Then
' Encrypt the query string and redirects to the encrypted URL.
' Remove if you don't want all query strings to be encrypted automatically.
Dim encryptedQuery As String = Encrypt(query)
context.Response.Redirect(path + encryptedQuery)
End If
End If
End Sub
''' <summary>
''' Parses the current URL and extracts the virtual path without query string.
''' </summary>
''' <returns>The virtual path of the current URL.</returns>
Private Shared Function GetVirtualPath() As String
Dim path As String = HttpContext.Current.Request.RawUrl
path = path.Substring(0, path.IndexOf("?"))
path = path.Substring(path.LastIndexOf("/") + 1)
Return path
End Function
''' <summary>
''' Parses a URL and returns the query string.
''' </summary>
''' <param name="url">The URL to parse.</param>
''' <returns>The query string without the question mark.</returns>
Private Shared Function ExtractQuery(url As String) As String
Dim index As Integer = url.IndexOf("?") + 1
Return url.Substring(index)
End Function
#Region "Encryption/decryption"
''' <summary>
''' The salt value used to strengthen the encryption.
''' </summary>
Private Shared ReadOnly SALT As Byte() = Encoding.ASCII.GetBytes(ENCRYPTION_KEY.Length.ToString())
''' <summary>
''' Encrypts any string using the Rijndael algorithm.
''' </summary>
''' <param name="inputText">The string to encrypt.</param>
''' <returns>A Base64 encrypted string.</returns>
Public Shared Function Encrypt(inputText As String) As String
Dim rijndaelCipher As New RijndaelManaged()
Dim plainText As Byte() = Encoding.Unicode.GetBytes(inputText)
Dim SecretKey As New PasswordDeriveBytes(ENCRYPTION_KEY, SALT)
Using encryptor As ICryptoTransform = rijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16))
Using memoryStream As New MemoryStream()
Using cryptoStream As New CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)
cryptoStream.Write(plainText, 0, plainText.Length)
cryptoStream.FlushFinalBlock()
Return "?" + PARAMETER_NAME + Convert.ToBase64String(memoryStream.ToArray())
End Using
End Using
End Using
End Function
''' <summary>
''' Decrypts a previously encrypted string.
''' </summary>
''' <param name="inputText">The encrypted string to decrypt.</param>
''' <returns>A decrypted string.</returns>
Public Shared Function Decrypt(inputText As String) As String
Dim rijndaelCipher As New RijndaelManaged()
Dim encryptedData As Byte() = Convert.FromBase64String(inputText)
Dim secretKey As New PasswordDeriveBytes(ENCRYPTION_KEY, SALT)
Using decryptor As ICryptoTransform = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16))
Using memoryStream As New MemoryStream(encryptedData)
Using cryptoStream As New CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)
Dim plainText As Byte() = New Byte(encryptedData.Length - 1) {}
Dim decryptedCount As Integer = cryptoStream.Read(plainText, 0, plainText.Length)
Return Encoding.Unicode.GetString(plainText, 0, decryptedCount)
End Using
End Using
End Using
End Function
#End Region
End Class
Yes it's a ISS configuration issue.
The web.config for ISS 5 or 6 should contain a <httpModules> tag as is described on madskristensen.net.
<system.web>
<httpModules>
<add type="QueryStringModule" name="QueryStringModule"/>
</httpModules>
</system.web>
If your web application is running on IIS 7 then the setting should be in:
<system.webServer>
<modules>
<add type="QueryStringModule" name="QueryStringModule"/>
</modules>
</system.webServer>
This solution is also described here.
I just found a solution:
1-Open IIS on the server;
2-Select the desired web site;
3-Select Modules;
4-Right click then "Add managed modules";
5-Give a name to it and then find the module you you want to add in the dropdownlist;
6-Reset IIS.

Set password for active directory lightweight directory services (ad lds) on .net 2.0

I am trying to create a new user and set their password in AD LDS using asp.net vb. I'm binding to an instance of a directory entry, which is working fine. And I can add a user without a problem. The problem is that I can't seem to set the password when I add the user. Is this the right way to set the password?
Dim objADAM As DirectoryEntry = BindToInstance()
Dim objUser As DirectoryEntry = objADAM.Children.Add("CN=Jimmy", "User")
objUser.Properties("sn").Value = "lloyd"
objUser.Properties("givenName").Value = "Jimmy Smith"
objUser.Properties("userpassword").Value = "THEPASSWORD"
objUser.CommitChanges()
This is the error that I get :
System.DirectoryServices.DirectoryServicesCOMException (0x80072020): An operations error occurred. (Exception from HRESULT: 0x80072020) at System.DirectoryServices.DirectoryEntry.CommitChanges()
I've also tried this :
Dim objADAM As DirectoryEntry = BindToInstance()
Dim objUser As DirectoryEntry = objADAM.Children.Add("CN=Jimmy", "User")
objUser.Properties("sn").Value = "lloyd"
objUser.Properties("givenName").Value = "Jimmy Smith"
objUser.CommitChanges()
objUser.Invoke("SetPassword", New Object() {"123456789A$#"})
objUser.CommitChanges()
Which gave me this error :
System.Reflection.TargetInvocationException:
Exception has been thrown by the
target of an invocation. --->
System.Runtime.InteropServices.COMException
(0x8000500D): The directory property
cannot be found in the cache. --- End
of inner exception stack trace --- at
System.DirectoryServices.DirectoryEntry.Invoke(String
methodName, Object[] args)
My coworker found a solution. You call CreateUserSetPassword to create the user and setup the password in one function call.
FYI, if the set password fails, the user will already be set up, so you'll need to either delete the user or just call the SetPassword function again.
Class variables
Private Uri As String
' { get; set; }
Private OuUri As String
' { get; set;}
Private UserUri As String
' { get; set; }
'You will want to set these two parameters somewhere in .config and pass to
'or otherwise make available to this process
Private userid As String = "danny123"
Private pwd As String = "pa$$word1"
New function
Public Sub New(ByVal uri__1 As String, ByVal ou As String)
Uri = uri__1
OuUri = "LDAP://" & uri__1 & "/" & ou
UserUri = "LDAP://" & uri__1 & "/CN={0}," & ou
End Sub
CreateUserSetPassword
''' <summary>
''' Creates new user and sets password
''' </summary>
''' <param name="userName"></param>
''' <param name="password"></param>
Public Function CreateUserSetPassword(ByVal userName As String, ByVal password As String) As String
Dim oGUID As String = String.Empty
oGUID = CreateUserAccount(userName, password)
If oGUID = String.Empty Then
oGUID = SetPassword(userName, password)
If oGUID = String.Empty Then
oGUID = EnableUser(userName)
End If
End If
Return oGUID
End Function
CreateUserAccount
''' <summary>
''' Create user in the AD-LDS
''' </summary>
''' <param name="userName"></param>
''' <param name="userPassword"></param>
''' <returns></returns>
Public Function CreateUserAccount(ByVal userName As String, ByVal userPassword As String) As String
Dim oGUID As String = String.Empty
Try
Dim connectionPrefix As String = OuUri
Using dirEntry As New DirectoryEntry(connectionPrefix, userid, pwd)
Dim newUser As DirectoryEntry = dirEntry.Children.Add("CN=" & userName, "user")
newUser.Properties("userPrincipalName").Value = userName
newUser.CommitChanges()
newUser.Close()
End Using
'catch (System.DirectoryServices.DirectoryServicesCOMException E)
Catch E As Exception
oGUID = E.Message
End Try
Return oGUID
End Function
SetPassword
''' <summary>
''' Set password for the user in AD-LDS
''' </summary>
''' <param name="user"></param>
''' <param name="password"></param>
Public Function SetPassword(ByVal user As String, ByVal password As String) As String
Dim oGUID As String = String.Empty
Const adsOptionPasswordPortnumber As Long = 6
Const adsOptionPasswordMethod As Long = 7
Const adsPasswordEncodeClear As Integer = 1
Const intPort As Integer = 50000
Dim objUser As DirectoryEntry
' User object.
' Set authentication flags.
Dim AuthTypes As AuthenticationTypes = AuthenticationTypes.Signing Or AuthenticationTypes.Sealing Or AuthenticationTypes.Secure
' Bind to user object using LDAP port.
Try
objUser = New DirectoryEntry(String.Format(UserUri, user), userid, pwd, AuthTypes)
'Get object using GetDirectoryEntry
'objUser = GetDirectoryEntry(user);
objUser.RefreshCache()
objUser.Invoke("SetOption", New Object() {adsOptionPasswordPortnumber, intPort})
objUser.Invoke("SetOption", New Object() {adsOptionPasswordMethod, adsPasswordEncodeClear})
objUser.Invoke("SetPassword", New Object() {password})
objUser.CommitChanges()
Catch e As Exception
oGUID = e.Message & vbLf & vbCr & Convert.ToString(e.InnerException)
End Try
Return oGUID
End Function

How can i convert the C# code listed below into VB

i am using the Json.net to serialize an object. the specific object is eventInstance.Properties which is the properties of a windows event log.
i am getting a
Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property
for C# an example is shown here
string json = JsonConvert.SerializeObject(joe, Formatting.Indented, new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
my line of code is below but i am not sure how to make it work in VB or if it is even possible
command.Parameters.AddWithValue("#f18", JsonConvert.SerializeObject(eventInstance.Properties(), New JsonSerializerSettings() {ReferenceLoopHandling = ReferenceLoopHandling.Ignore}))
i get an error that states 'ReferenceLoopHandling' is an enum type and cannot be used as an expression
thanks for the help
You can use below code:
Private Function getJSON(sJSON As String) As String
Dim objNews = New List(Of News)()
Dim news = New News()
news.id = ""
news.title = "blah"
Dim lst = New List(Of Object)()
lst.Add(New With {.video_identifier = "id1"})
lst.Add(New With {.video_identifier = "id2"})
news.video_identifier = lst.ToArray()
objNews.Add(news)
Return Newtonsoft.Json.JsonConvert.SerializeObject(New With {.data = objNews})
End Function
Class News
Public Property title As String
Get
Return _title
End Get
Set
_title = value
End Set
End Property
Private _title As String
Private _sId As String
Public Property id As String
Get
Return _sId
End Get
Set
_sId = value
End Set
End Property
Private _youtube_videos As Object() = New List(Of Object)().ToArray()
Public Property video_identifier As Object()
Get
Return _youtube_videos
End Get
Set
_youtube_videos = value
End Set
End Property
End Class
Public Class YoutubeVideos
Private _video_identifier As String
Public Property video_identifier As String
Get
Return _video_identifier
End Get
Set
_video_identifier = value
End Set
End Property
End Class

Resources