How to determine if a user is in a security group? - asp.net

I am using the code below to get the user groups but I am not sure how to code it to say that if the user is in "TestGroup" do something if not redirect the page?
Dim resEnt As SearchResult
Try
For Each resEnt In mySearcher.FindAll()
LabelUser.Text = resEnt.GetDirectoryEntry.Properties.Item("DisplayName").Value
LabelLocation.Text = resEnt.GetDirectoryEntry.Properties.Item("SystemUserLocation").Value
LabelState.Text = resEnt.GetDirectoryEntry.Properties.Item("st").Value
LabelCountry.Text = resEnt.GetDirectoryEntry.Properties.Item("c").Value
Dim result As SearchResult = mySearcher.FindOne()
If (result Is Nothing) Then
Else
Dim groupColl As Object
For Each groupColl In resEnt.Properties("memberof")
Dim GroupArray As Array = groupColl.split(",")
Select Case GroupArray(0).replace("CN=", "")
Case "TestGroup"
'Continue loading page
Case Else
'Prevent page from loading????
End Select
Next groupColl
End If
Next
Catch f As Exception
Console.WriteLine(f.ToString)
End Try

Related

ASP NET MVC VB if searchstring is empty do or else LINQ

Function Index(SearchString As String, page As Integer?) As ActionResult
If page Is Nothing Then
page = 1
Else
page = page
End If
Dim List = (From m In db.maintenances Where (m.description OrElse m.description.Contains(SearchString)))
Dim pagesize = 25
Dim pageNumber As Integer = (If(page, 1))
Return View(List.OrderBy(Function(o) o.id).ToPagedList(pageNumber, pagesize))
End Function
Now i have this piece of code in my controller
what i would like to do if searchstring is empty return all results but if its not empty filter those that contain the searchstring how can i make this so i dont have to write multple queries to filter out the data?
You could add the Where clause only if it is required. Instead of
Dim List = (From m In db.maintenances Where (m.description OrElse m.description.Contains(SearchString)))
you change to Linq extension method syntax and add the Where clause only if it is required:
Dim List = db.maintenances.AsQueryable()
If Not String.IsNullOrWhitespace(SearchString) Then
List = List.Where(Function(x) m.description IsNot Nothing AndAlso m.description.Contains(SearchString))
End If
The query will only be executed at the end of your method when you call ToPagedList, so all the records are only retrieved if there is no search clause.
If you need to add another condition, just add another Where clause, for example:
Dim List = db.maintenances.AsQueryable()
If Not String.IsNullOrWhitespace(SearchString) Then
List = List.Where(Function(x) m.description IsNot Nothing AndAlso m.description.Contains(SearchString))
End If
If selectedBranchId IsNot Nothing Then
List = List.Where(Function(x) m.branch_id = selectedBranchId)
End If

aspnet/vbnet clear label after response redirect

I'm building an asp.net web page with vb.net code behind.
My web page is designed to display an error when the user clicks a button without filling the relevant textbox; the code below shows how this works:
If txtOrderNumber.Text = "" Then
lblStatus.Text = orderNoWarning
lblStatus.CssClass = "error"
ElseIf txtPhaseNumber.Text = "" Then
lblStatus.Text = phaseNoWarning
lblStatus.CssClass = "error"
ElseIf txtOrderNumber.Text.Length > 0 AndAlso txtPhaseNumber.Text.Length > 0 Then
Try
Dim intOrderNumber As Integer = CInt(txtOrderNumber.Text)
Try
Dim intPhaseNumber As Integer = CInt(txtPhaseNumber.Text)
Dim objWIP_Tracking As New wsWIP_Tracking.WIP_TrackingSoapClient
Dim myResults As wsWIP_Tracking.TicketType2 = objWIP_Tracking.GetTicketType2(intOrderNumber, intPhaseNumber)
If myResults = wsWIP_Tracking.TicketType2.AME Or _
myResults = wsWIP_Tracking.TicketType2.Orion Then
lblStatus.Text = ""
Response.Redirect("http://ligrptsvr2/default.aspx?Report=JoinerySummarybyComponent.rpt&username=imservices&FOLDER=Analytics&OrderNo=" & intOrderNumber.ToString & "&PhaseNo=" & intPhaseNumber.ToString & "&ParameterPrompt=yes")
ElseIf myResults = wsWIP_Tracking.TicketType2.GS Then
lblStatus.Text = ""
Response.Redirect("http://ligrptsvr2/default.aspx?Report=JoinerySummary_GreenScreen.rpt&username=wip&FOLDER=Analytics&JobNo=" & intOrderNumber.ToString & "&PhaseNo=" & intPhaseNumber.ToString & "&ParameterPrompt=yes")
ElseIf myResults <> wsWIP_Tracking.TicketType2.AME Or _
myResults <> wsWIP_Tracking.TicketType2.Orion Or _
myResults = wsWIP_Tracking.TicketType2.GS Then
lblStatus.Text = warning
lblStatus.CssClass = "warning"
Else
Response.End()
End If
Catch ex As Exception
End Try
Catch ex As Exception
End Try
Else
lblStatus.Text = ""
End If
However, when a response.redirect (redirects to new page) occurs , I would like to clear the label(lblstatus). The code 'lblstatus.text=""' does not work. When the user gets redirected to a new page then goes back (using browser back button), the label still shows an error. Iv tried disabling and enabling viewstate; doesn't make any difference. What can I do to clear this label?
Please see: What happens when I press browser BACK button?
When you press back button in a browser, most browsers will just display the cached copy of the html page in it's latest state, before the redirect happened. The functionality is totally browser dependent. Hence, your VB code or viewstate can hardly do anything.
One option is to use java-script on page load, to dynamically toggle the error message (which is what I do when I have this kind of a problem).

Comparing variables to SQL / Troubleshooting session

I am trying to send some variables, using a session, to the next page "ProcedureSelectionForm.aspx". As you can see, the sessions have been commented out. The code below will work (without sending the variable of course). However, when you remove the comments the .onclick function reloads the page rather than navigating to "ProcedureSelectionForm.aspx". For this reason, I believe this is where my problem is. The first two columns are "Account" and "Password" in the database. I have not misspelled anything. I am new to VB and ASP.net and would appreciate some explanation as to what is happening and why my desired functionality isn't materializing. Thank you for your help!
If IsValid Then
Try
Dim strSQL = "select * from CreatePatient where Account = #Account and Password = #Password"
Using CCSQL = New SqlConnection(ConfigurationManager.ConnectionStrings("CreatePatientConnectionString").ConnectionString)
Using CCUser = New SqlCommand(strSQL, CCSQL)
CCSQL.Open()
CCUser.Parameters.Add("#Account", Data.SqlDbType.VarChar).Value = PatientAccount.Text
CCUser.Parameters.Add("#Password", Data.SqlDbType.VarChar).Value = PatientPass.Text
CCUser.ExecuteNonQuery()
'Using reader As SqlDataReader = CCUser.ExecuteReader()
'If reader.HasRows Then
'reader.Read()
'Session("user") = reader("Account")
'Session("pass") = reader("Password")
Response.Redirect("ProcedureSelectionForm.aspx")
'End If
'End Using
End Using
End Using
Catch ex As Exception
Label1.Text = ex.Message
End Try
End If
My friend was able to make time to help me out. I am unsure of what he did differently besides closing connections
If IsValid Then
Dim CCSQL As New SqlConnection
Dim CCUser As New SqlCommand
Dim strSQL As String
Dim dtrUser As SqlDataReader
Try
CCSQL.ConnectionString = ConfigurationManager.ConnectionStrings("CreatePatientConnectionString").ConnectionString
strSQL = "Select * from CreatePatient where Account=#user and Password=#pwd"
CCUser.CommandType = Data.CommandType.Text
CCUser.CommandText = strSQL
CCUser.Parameters.Add("#user", Data.SqlDbType.VarChar).Value = PatientAccount.Text
CCUser.Parameters.Add("#pwd", Data.SqlDbType.VarChar).Value = PatientPass.Text
CCSQL.Open()
CCUser.Connection = CCSQL
dtrUser = CCUser.ExecuteReader()
If dtrUser.HasRows Then
dtrUser.Read()
Session("user") = dtrUser("Account")
Session("level") = dtrUser("Password")
Response.Redirect("ProcedureSelectionForm.aspx")
Else
Label1.Text = "Please check your user name and password"
End If
dtrUser.Close()
CCSQL.Close()
Catch ex As Exception
Label1.Text = ex.Message
End Try
End If
I am on a tight deadline but i will get back to those interested with an answer. Thank you for your effort.
You don't want to do .ExecuteNonQuery() when you are actually doing a query (i.e. a SQL "SELECT" statement. You can just do the .ExecuteReader() to read those two values.
Also, I presume you are trying to validate the Account and Password; otherwise you could just set Session("user") = PatientAccount.Text and set Session("pass") = PatientPass.Text.

My code isn't giving the user's the correct feedback. Any ideas how to fix this?

I have a very simple code that invokes a stored procedure. The stored proc is used for sending out reminders to user's on expiring account.
When a user enters correct email address, the user gets a reminder email with the message, "Reminder sent successfully"
This is exactly what we want.
However, if the user enters an invalid email address, the user still sees same message, "Reminder sent successfully"
This is not good.
Can you please help with what I am doing wrong?
Please see entire (actual) code below:
Protected Sub BtnSubmit_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles BtnSubmit.Click
Dim oConnection As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("sConnectionString").ConnectionString)
Dim oCommand As SqlCommand = New SqlCommand()
Try
oConnection.Open()
oCommand.Connection = oConnection
oCommand.CommandText = "AcountExpiration"
oCommand.CommandType = CommandType.StoredProcedure
oCommand.Parameters.Add(New SqlParameter("#Email", Data.SqlDbType.VarChar, 50)).Value = Email.Text
Dim adpt As New SqlDataAdapter(oCommand)
Dim ds As New DataSet()
adpt.Fill(ds)
oCommand.ExecuteReader()
lblMsg.Text="Reminder successfully sent"
Catch ex As SqlException
Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('" + ex.Message + "')</SCRIPT>")
Finally
oConnection.Close()
End Try
End Sub
c# solution is welcome as well.
Dim scmd As SqlCommand = New SqlCommand("AcountExpiration", Conn)
scmd.CommandType = CommandType.StoredProcedure
scmd.Parameters.AddWithValue("#Email", Email.Text)
'Dim r As SqlDataReader = scmd.ExecuteReader()
Dim validEmail As Boolean = False
Dim reader As SqlDataReader = scmd.ExecuteReader()
While reader.Read()
'if we are here then something got returned.
'so probably a valid email.
validEmail = True
End While
If validEmail = True Then
lblMsg.Text = "Success"
Else
lblMsg.Text = "email does not exit on our system"
End If
You have a couple of different options as I see it.
Have the sproc throw an error if the email address isn't valid.
Have validation on the dataset to check and make sure you are getting back the expected values. Only display the success message if there was actually a success.
I would not use a SqlDataAdapter or Dataset for this. just use the SqlDataReader
bool validEmail = false;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//if we are here then something got returned.
//so probably a valid email.
validEmail = true;
}
Or use ExecuteScalar
bool validEmail = Convert.ToBoolean(command.ExecuteScalar());
then
if(validEmail)
{
}
else
{
}
UPDATE
Will add an update for this as some people don't realise that certain code wont magically work. I have already included links for ExecuteScalar and ExecuteReader to show how to use these methods.
If you wanted to use ExecuteScalar you would have to change your stored procedure to return a value that could then be parsed as a Boolean.
The above methods is simply for checking if an email exists in the DB. No this does not valdate an email address, as I would expect that to occur before this code would be reached.

Why doesn't this code work in another solution?

I have the below code in my current solution, which returns an error of 'The value '' is invalid'. The below snippet has been shortened to just show the problem area as opposed to the entire ActionResult.
Dim tComment As New hdComment
tComment.Comment = collection("wmd-input")
tComment.MadeOn = DateTime.Now
tComment.UserID = Session("LoggedInUser")
tComment.CallID = id
If Not tComment.Comment.Trim().Length = 0 Then
db.hdComments.InsertOnSubmit(tComment)
End If
db.SubmitChanges()
Return Redirect("/Calls/Details/" & id)
However, in a previous project, I have used exactly the same code, even the view is the same, but it still returns the above error.
Everything is receiving a value ok.
The only thing that's different is that it's a different project.
I'm at a bit of a loss with this one.
Anyone have any ideas?
EDIT For reference, here is the entire ActionResult.
'
' POST: /Calls/Details/5
<Authorize()> _
<AcceptVerbs(HttpVerbs.Post)> _
<ValidateInput(False)> _
Function Details(ByVal id As Integer, ByVal collection As FormCollection) As ActionResult
Dim calls As hdCall = callRepository.GetCall(id)
ViewData("MyCallID") = calls.CallID
ViewData("UserThatLogged") = calls.UserID
ViewData("TimeLogged") = calls.loggedOn.ToLongDateString & " " & calls.loggedOn.ToLongTimeString
ViewData("Title") = calls.Title
Dim dataContext As New CustomerServiceModelDataContext
ViewData("Status") = New SelectList(dataContext.hdStatus, "StatusID", "Status", calls.StatusID)
ViewData("Type") = New SelectList(dataContext.hdCategories, "CategoryID", "Title", calls.CategoryID)
ViewData("Company") = calls.hdCompany.Company
ViewData("Priority") = New SelectList(dataContext.hdPriorities, "PriorityID", "Priority", calls.PriorityID)
ViewData("CallDetails") = calls.CallDetails
ViewData("Customer") = calls.hdCustomer.CustomerName
ViewData("CustomerID") = calls.hdCustomer.CustomerID
ViewData("CustomerCallCount") = callRepository.CountCallsForThisCustomer(calls.hdCustomer.CustomerID).Count()
ViewData("ContactNumber") = calls.hdCustomer.Telephone
ViewData("AssignedTo") = New SelectList(dataContext.aspnet_Users, "UserName", "UserName", calls.AssignedTo)
Dim callComments = callRepository.GetCallComments(id)
Dim db As New CustomerServiceModelDataContext
Try
Dim tComment As New hdComment
tComment.Comment = collection("wmd-input")
tComment.MadeOn = DateTime.Now
tComment.UserID = Session("LoggedInUser")
tComment.CallID = id
If Not tComment.Comment.Trim().Length = 0 Then
db.hdComments.InsertOnSubmit(tComment)
End If
'Update any call changes
Dim tCall = (From c In db.hdCalls _
Where c.CallID = id _
Select c).SingleOrDefault
tCall.updatedOn = DateTime.Now
tCall.UpdatedBy = Session("LoggedInUser")
tCall.StatusID = collection("Status")
tCall.AssignedTo = collection("AssignedTo")
tCall.CategoryID = collection("Type")
tCall.PriorityID = collection("Priority")
db.SubmitChanges()
Return Redirect("/Calls/Details/" & id)
Catch ex As Exception
ModelState.AddModelError("Error", ex)
Return View(callComments)
End Try
Return View(callComments)
End Function
The rest of the code works, if the wmd-input field is left blank on the form, it's only when there is something in it does it throw the error.
EDIT bit of an update to this, this line:
If Not tComment.Comment.Trim().Length = 0 Then
now reads
If (Not tComment.Comment.Trim().Length = 0) Then
and the page updates if nothing is in the wmd-input box, but if there is, it returns the The value '' is invalid.
You are probably missing a reference. Or the framework version is different.
Also is it the same development machine, is asp.net-mvc installed both places?
I managed to fix this, the problem actually lay in the Foriegn Key Contraints between hdCalls and hdComments.
I removed the contraints and recreated them and all of a sudden it was fine.

Resources