ASP.NET Web Pages (Razor) Exit Code Block - asp.net

Does anybody know how to exit a code block without interrupting page load in ASP.NET Web Page (Razor) in VB language? Let's say I have a login mechanism that execute in the following order:
Before page load:
Check if user id exist.
Check if password match.
if the user id does not exist, display error message then skip password validation and let the rest of the html page (body, footer) load. My current solution is to use VB specific GoTo.. statement which I think is ugly. Does anybody has a more elegant solution? Below is a simple sample code:
#Code
dim login As New clsLogin 'assume this class handles login validation
dim inputUserID As String 'this variable hold user id entered by user
dim inputPwd As String 'this is password entered by user
'First, check if that ID exist in database
if login.userExist(inputUserID) = false then
#<p>User does not exist !</p>
GoTo skip
End If
'If ID exist, check if password match
if login.checkPwd(inputUserID, inputPwd) = false then
#<p>Password Mismatch !</p>
GoTo skip
End If
'Passes all validation, display success message
#<p>Login Successful !</p>
skip:
End Code
I tried to replace the GoTo statement with return statement. However, it also stopped the page loading. I put the validation server code before any HTML is displayed and if I use return statement it wont show the HTML page. Any idea? Thanks in advance.

Short answer could use a function:
#Functions
function Check(byval inputUserID as integer, byval inputPwd as string) as string
dim login As New clsLogin 'assume this class handles login validation
dim result as string = string.Empty
'First, check if that ID exist in database
if login.userExist(inputUserID) = false then
return "User does not exist !"
End If
'If ID exist, check if password match
if login.checkPwd(inputUserID, inputPwd) = false then
return "Password Mismatch !"
End If
return result
end function
End functions
#Code
dim inputUserID As String 'this variable hold user id entered by user
dim inputPwd As String 'this is password entered by user
dim msg = #Check(inputUserID,inputPwd)
'Passes all validation, display success message
if string.isnullorempty(msg) then
msg = "<p>Login Successful !</p>"
end if
#msg
End Code
Hoever reading your comment seems you are looking for an elegant and sustainable solution, so I think you could approach your problem with a loosely coupled ValidationManager:
VB (translated with Telerik code converted)
Public Interface ILoginProvider
Function UserExist(inputUserID As Integer) As Boolean
Function CheckPwd(inputUserID As Integer, inputPwd As String) As Boolean
End Interface
Public Class LoginProvider
Implements ILoginProvider
Public Function UserExist(inputUserID As Integer) As Boolean
Return True
End Function
Public Function CheckPwd(inputUserID As Integer, inputPwd As String) As Boolean
Return True
End Function
End Class
Public Class ValidationResult
Public Property Result() As Boolean
Get
Return m_Result
End Get
Set
m_Result = Value
End Set
End Property
Private m_Result As Boolean
Public Property ResultMessage() As String
Get
Return m_ResultMessage
End Get
Set
m_ResultMessage = Value
End Set
End Property
Private m_ResultMessage As String
End Class
Public MustInherit Class Validator
Protected _provider As ILoginProvider
Protected _inputUserID As Integer
Protected _inputPwd As String
Public Sub New(provider As ILoginProvider, inputUserID As Integer, inputPwd As String)
_provider = provider
_inputPwd = inputPwd
_inputUserID = inputUserID
End Sub
Public MustOverride Function Validate() As ValidationResult
End Class
Public Class UserExistenceValidator
Inherits Validator
Public Sub New(provider As LoginProvider, inputUserID As Integer, inputPwd As String)
MyBase.New(provider, inputUserID, inputPwd)
End Sub
Public Overrides Function Validate() As ValidationResult
Dim result = New ValidationResult()
Dim check = _provider.UserExist(_inputUserID)
result.Result = check
If Not check Then
result.ResultMessage = "User Doesn't exist"
End If
Return result
End Function
End Class
Public Class UserPasswordValidator
Inherits Validator
Public Sub New(provider As LoginProvider, inputUserID As Integer, inputPwd As String)
MyBase.New(provider, inputUserID, inputPwd)
End Sub
Public Overrides Function Validate() As ValidationResult
Dim result = New ValidationResult()
Dim check = _provider.CheckPwd(_inputUserID, _inputPwd)
result.Result = check
If Not check Then
result.ResultMessage = "Wrong Password"
End If
Return result
End Function
End Class
Public Class ValidationManager
Private _validators As List(Of Validator)
Public Sub New()
_validators = New List(Of Validator)()
End Sub
Public Function Validate() As ValidationResult
Dim result As ValidationResult = Nothing
For Each item As var In _validators
result = item.Validate()
If Not result.Result Then
Return result
End If
Next
Return New ValidationResult() With { _
Key .Result = True, _
Key .ResultMessage = "Successfull validated" _
}
End Function
End Class
C#
public interface ILoginProvider
{
bool UserExist(int inputUserID);
bool CheckPwd(int inputUserID, string inputPwd);
}
public class LoginProvider: ILoginProvider
{
public bool UserExist(int inputUserID)
{
return true;
}
public bool CheckPwd(int inputUserID, string inputPwd)
{
return true;
}
}
public class ValidationResult
{
public bool Result { get; set; }
public string ResultMessage { get; set; }
}
public abstract class Validator
{
protected ILoginProvider _provider;
protected int _inputUserID;
protected string _inputPwd;
public Validator(ILoginProvider provider, int inputUserID, string inputPwd)
{
_provider = provider;
_inputPwd = inputPwd;
_inputUserID = inputUserID;
}
public abstract ValidationResult Validate();
}
public class UserExistenceValidator : Validator
{
public UserExistenceValidator(LoginProvider provider,int inputUserID, string inputPwd): base(provider,inputUserID, inputPwd)
{
}
public override ValidationResult Validate()
{
var result = new ValidationResult();
var check = _provider.UserExist(_inputUserID);
result.Result = check;
if(!check)
result.ResultMessage = "User Doesn't exist";
return result;
}
}
public class UserPasswordValidator : Validator
{
public UserPasswordValidator(LoginProvider provider, int inputUserID, string inputPwd)
: base(provider, inputUserID, inputPwd)
{
}
public override ValidationResult Validate()
{
var result = new ValidationResult();
var check = _provider.CheckPwd(_inputUserID, _inputPwd);
result.Result = check;
if (!check)
result.ResultMessage = "Wrong Password";
return result;
}
}
public class ValidationManager
{
List<Validator> _validators;
public ValidationManager()
{
_validators = new List<Validator>();
}
public ValidationResult Validate()
{
ValidationResult result = null;
foreach (var item in _validators)
{
result = item.Validate();
if(!result.Result)
return result;
}
return new ValidationResult(){Result = true,ResultMessage="Successfull validated" };
}
}
Use
#Function Check() As string
Dim login As New clsLogin 'assume this class handles login validation
Dim inputUserID As String 'this variable hold user id entered by user
Dim inputPwd As String 'this is password entered by user
Dim login As New LoginProvider()
Dim validators = New List(Of Validator)()
validators.Add(New UserExistenceValidator(login, 1, "test1"))
validators.Add(New UserPasswordValidator(login, 1, "test1"))
Dim manager = New ValidationManager(validators)
Dim result = manager.Validate()
return string.format("<p>{0}</p>",result.ResultMessage)
End Function
#Code
#Check()
End Code

Found it! Thx to InvernoMuto to show me how to define functions inside webpage.
First I created a class to hold login result that can provide reason if login fails.
Class LoginResult
Public Property LoginSuccess As Boolean
Public Property Reason As String
End Class
Then I created the following function for login validations
#Functions
Function CheckLogin(User As String, Pwd as String) As LoginResult
dim login As New clsLogin
Dim res as New LoginResult
res.LoginSuccess = True
if login.userExist(inputUserID) = false then
res.LoginSuccess = False
res.Reason = "User does not exist !"
return res
end if
if login.checkPwd(inputUserID, inputPwd) = false then
res.LoginSuccess = False
res.Reason = "Password mismatch !"
return res
end if
return res
End Function
End Functions
Then on the Login HTML page I just call the following code:
dim lr as LoginResult
lr = CheckLogin("someone", "password")
if lr.LoginSuccess = True then
#<p>Login Success !</p>
else
#<p>Error: #lr.Reason</p>
end if

Related

matching password from client with password in AD

the code I have below works, but it doesn't use the password that is passed from the client. After I find the correct user in the AD, is there a way to match the password that is passed from the client with the password in the AD?
Thanks!
Public Class FordLoginController
Inherits ApiController
Public Class StoreCredentials
Public Property UsernameAX As String
Public Property PasswordAX As String
End Class
Public Function PostValue(<FromBody()> ByVal creds As StoreCredentials) As HttpResponseMessage
Dim username As String = creds.UsernameAX
Dim password As String = creds.PasswordAX
Dim ctx As New PrincipalContext(ContextType.Domain, "ford", "dc=biz,dc=ford,dc=com")
Dim user As UserPrincipal = UserPrincipal.FindByIdentity(ctx, username)
Dim response As HttpResponseMessage
If user IsNot Nothing Then
response = Request.CreateResponse(HttpStatusCode.Found)
response.Headers.Location = New Uri("/loginAndContinue/login.aspx")
Return response
End If
response = Request.CreateResponse(HttpStatusCode.Forbidden)
Return response
End Function
End Class
From VBForums
http://www.vbforums.com/showthread.php?352349-Validate-Login-against-Active-Directory
Private Function ValidateActiveDirectoryLogin(ByVal Domain As String, ByVal Username As String, ByVal Password As String) As Boolean
Dim Success As Boolean = False
Dim Entry As New System.DirectoryServices.DirectoryEntry("LDAP://" & Domain, Username, Password)
Dim Searcher As New System.DirectoryServices.DirectorySearcher(Entry)
Searcher.SearchScope = DirectoryServices.SearchScope.OneLevel
Try
Dim Results As System.DirectoryServices.SearchResult = Searcher.FindOne
Success = Not (Results Is Nothing)
Catch
Success = False
End Try
Return Success
End Function
usage
If ValidateActiveDirectoryLogin("VBForums", "Woof", "Mouse") Then
'do something
End If

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

How to return an empty object instead of null in web api

I have a web API built in .NET 4.0 and I have an issue with a simple GET request. My problem is that I want to return an object who has many properties, some strings, ints and other custom data types and in some cases some of those properties doesn't exist in the databsae so I want it to return an empy object {} and I'm just having null.
Here is some of my code
<ActionName("index")>
<HttpGet>
Public Function ObtenerAsegurado(<FromUri> rut As Integer) As Asegurado
Dim ws As New Getter2.GetterSoapClient
Dim aseg As Getter2.AseguradoDTO
aseg = ws.ObtenerAsegurado(rut)
Dim objAsegurado As Asegurado = Convertir.DTOToAsegurado(aseg)
Return objAsegurado
End Function
Public Shared Function DTOToAsegurado(asegDTO As Getter2.AseguradoDTO) As Asegurado
Dim aseg As New Asegurado
If Not asegDTO Is Nothing Then
...
aseg.cuenta = DTOToCuentas(asegDTO.Cuenta)
...
End If
Return aseg
End Function
Private Shared Function DTOToCuentas(cuentaDTO As Getter2.CuentaDTO) As Cuenta
Dim nuevacuenta As New Cuenta
If Not cuentaDTO Is Nothing AndAlso Not cuentaDTO.DescBanco Is Nothing Then
...
Else
nuevacuenta = Nothing
End If
Return nuevacuenta
End Function
As you can see, my action call to another function to make some convertion, and there i return the property of the object as nothing when there isn't present, that becomes null in the http response and I want an empty object instead {}
I also tried returning nuevacuenta = New Cuenta but that return an object with all it's properties set to nothing... Please help how can I return empty instead of null?
I found that it's doable to convert a null instance to empty object {} in JSON. C# code is there https://gist.github.com/juanonsoftware/7067ce53813201abbdae
var settings = new JsonSerializerSettings()
{
ContractResolver = new NullToEmptyObjectResolver(typeof(Child))
};
var str = JsonConvert.SerializeObject(m, settings);
class NullToEmptyObjectResolver : DefaultContractResolver
{
private readonly Type[] _types;
public NullToEmptyObjectResolver(params Type[] types)
{
_types = types;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
return type.GetProperties().Select(p =>
{
var jp = base.CreateProperty(p, memberSerialization);
jp.ValueProvider = new NullToEmptyValueProvider(p, _types);
return jp;
}).ToList();
}
}
class NullToEmptyValueProvider : IValueProvider
{
readonly PropertyInfo _memberInfo;
private readonly Type[] _types;
public NullToEmptyValueProvider(PropertyInfo memberInfo, params Type[] types)
{
_memberInfo = memberInfo;
_types = types;
}
public object GetValue(object target)
{
var result = _memberInfo.GetValue(target);
if (_types.Contains(_memberInfo.PropertyType) && result == null)
{
result = new object();
}
return result;
}
public void SetValue(object target, object value)
{
_memberInfo.SetValue(target, value);
}
}
I'm not sure if this is the problem, but I think it could be the way in which you are testing for nothing?
<ActionName("index")>
<HttpGet>
Public Function ObtenerAsegurado(<FromUri> rut As Integer) As Asegurado
'
Dim ws As New Getter2.GetterSoapClient
Dim aseg As Getter2.AseguradoDTO
'
aseg = ws.ObtenerAsegurado(rut)
Dim objAsegurado As Asegurado = Convertir.DTOToAsegurado(aseg)
Return objAsegurado
'
End Function
'
Public Shared Function DTOToAsegurado(asegDTO As Getter2.AseguradoDTO) As Asegurado
'
Dim aseg As New Asegurado
If (asegDTO Is Nothing) = False Then
'...
aseg.cuenta = DTOToCuentas(asegDTO.Cuenta)
'...
End If
Return aseg
'
End Function
'
Private Shared Function DTOToCuentas(cuentaDTO As Getter2.CuentaDTO) As Cuenta
'
Dim nuevacuenta As New Cuenta
If (cuentaDTO Is Nothing) = False And (cuentaDTO.DescBanco Is Nothing) = False Then
'...
Else
nuevacuenta = Nothing
End If
Return nuevacuenta
'
End Function

System.NullReferenceException on remote Machine?

I have created a web site with window form, I have an error of System.NullReferenceException only in remote page, if I try to open the page with visual studio, in debug mode, there is not problems! WHY!!?!?!?!
[NullReferenceException: Riferimento a un oggetto non impostato su un'istanza di oggetto.]
GeCo.DetaglioMilitare.Page_Load(Object sender, EventArgs e) in C:\Users\j972537\Documents\
Visual Studio 2010\Projects\GeCo\Admin\DettaglioMilitare.aspx.vb:45
System.Web.UI.Control.OnLoad(EventArgs e) +92
System.Web.UI.Control.LoadRecursive() +54
System.Web.UI.Page.ProcessRequestMain(
Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772
this is the code with the error:
Dim militare As New ldap.utente
militare = ldap.ldap_utente(matricola2)
Label7.Text = militare.grado
Label8.Text = militare.cognome
Label9.Text = militare.nome
Label10.Text = militare.codice_reparto
Label11.Text = militare.intestazione_reparto
Label12.Text = militare.email
this is the class module that I created:
Public Class ldap
Public Class utente
Private _matricola As String = ""
Public Property matricola() As String
Get
Return _matricola
End Get
Set(ByVal val As String)
_matricola = val
End Set
End Property
Private _grado As String = ""
Public Property grado() As String
Get
Return _grado
End Get
Set(ByVal val As String)
_grado = val
End Set
End Property
Private _cognome As String = ""
Public Property cognome() As String
Get
Return _cognome
End Get
Set(ByVal val As String)
_cognome = val
End Set
End Property
Private _nome As String = ""
Public Property nome() As String
Get
Return _nome
End Get
Set(ByVal val As String)
_nome = val
End Set
End Property
Private _codice_reparto As String = ""
Public Property codice_reparto() As String
Get
Return _codice_reparto
End Get
Set(ByVal val As String)
_codice_reparto = val
End Set
End Property
Private _intestazione_reparto As String = ""
Public Property intestazione_reparto() As String
Get
Return _intestazione_reparto
End Get
Set(ByVal val As String)
_intestazione_reparto = val
End Set
End Property
Private _email As String = ""
Public Property email() As String
Get
Return _email
End Get
Set(ByVal val As String)
_email = val
End Set
End Property
End Class
' funzione per estrarre i dati relativi ad una matricola
Public Shared Function ldap_utente(matricola As String) As utente
Dim directory As DirectoryServices.DirectorySearcher
Dim result As DirectoryServices.SearchResult
Dim militare As utente = New utente
Try
directory = New DirectoryServices.DirectorySearcher("(cn=" & matricola & ")")
result = directory.FindOne
militare.matricola = matricola
militare.grado = result.Properties("title")(0).ToString
militare.cognome = result.Properties("sn")(0).ToString
militare.nome = result.Properties("givenname")(0).ToString
militare.codice_reparto = Left(result.Properties("physicaldeliveryofficename")(0).ToString, 5)
Dim lenght_string As Integer = result.Properties("description")(0).ToString.Length
militare.intestazione_reparto = Trim(Right(result.Properties("description")(0).ToString, lenght_string - 7))
militare.email = result.Properties("mail")(0).ToString()
Return militare
Catch ex As Exception
Return Nothing
End Try
End Function
Because you did not include information which line is DettaglioMilitare.aspx.vb:45, I can only diagnose what probably happened.
In you function ldap_utente when wxception happened you return Nothing which is same as Null. So to investigate what is wrong in your code you have two options:
Debug your code to see what exception you got
If debugging is not possible add logging to your code or throw this exception to see it in browser window\
I am almost sure that you have problem with connecting to Active Directory, because in 99% your page is installed as IIS user which doesn't have access to Active Directory. You can try to change application pool user to domain user.

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