insert date to database using silverlight-enabled wcf service, visual basic - sql

I have difficulties in inserting record from silverlight interface to database using silverlight-enabled wcf service, visual basic. I followed a few tutorials in this topic, but somehow I couldn't finish my project in inserting data into database.
I followed VBRocks' blog on "Silverlight 3: Displaying SQL Server data " (http://garylima.blogspot.com/2009/09/silverlight-3-displaying-sql-server.html)to display data from database but failed to write record to the database.
I have 6 textboxes to receive user input, and I want to submit the information from the 6 boxes to the database.
Here is the Operationcontract in the register.svc.vb page:
<OperationContract()>
Public Sub InsertData(registerid As Integer, firstname As String, emailid As String, phoneno As String, loginname As String, password As String)
Dim db As New SilverlightDataContext()
Dim record As New Registration With {.registerID = registerid, .FirstName = firstname, .EmailID = emailid,
.PhoneNo = phoneno, .LoginName = loginname, .Password = password}
db.Registrations.InsertOnSubmit(record)
Try
db.SubmitChanges()
Catch ex As Exception
End Try
Here are the subs in the Mainpage.xaml.vb, there is no error but no result too:
Private Sub SubmitRegister_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
Dim mbservice As New RegisterClient()
Dim registerid = Convert.ToInt32(BoxRegisterID.Text)
mService.InsertDataAsync(registerid, BoxFirstName.Text, BoxEmailID.Text, BoxPhoneNo.Text, BoxLoginName.Text, BoxPassword.Text)
End Sub
Those are the main things in the project. Any ideas will be greatly appreciated!
Thanks in advance!

For some reason, the code I have is right and I am able to insert a record into the database which I didn't notice by the time I posted this question. Hope this will help later.

Related

Using LINQ to set up a login page from an access database

I currently have a small table of 4 records of people in an Access Database each with just three fields, Role, Username and Password. Im trying to set up a login page where I'm using LINQ to read the Username and Password fields and then if they are both correct then to login to one of 4 possible roles depending on what role that person is allocated to on database. I currently have this.
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim strUsername As String
Dim strPassword As String
Dim strRole As String
Dim query1 = From loginUsername In database1.tblStaff
Where loginUsername.FirstName = txtUsername.Text
Select loginUsername.FirstName
Dim query2 = From loginPassword In database1.tblStaff
Where loginPassword.Password = txtPassword.Text
Select loginPassword.Password
End Sub
End Class
As you can see, I'm trying to take what the user enters in each text box and match it to the database and then somehow set up an if statement checking if it's right but I'm not sure if I'm even on the right track.
Any help is great, thanks.
I guess it should be something like this (disclaimer: I'm not familiar with VB)
Dim role = (From entry In database1.tblStaff
Where entry .FirstName = txtUsername.Text
AndAlso entry.Password = txtPassword.Text
Select entry.Role)
.FirstOrDefault() 'execute query explicitly
'if a role is null, then login or password incorrect
If role Is Nothing Then
'No match
Else
'Use role here
End If
There is no point to separate queries. You can merge them in a single query
Thank you sm Chris this has been a lifesaver for Yvonne's project! Our group was really struggling with this. You probably already have you answer by now, that code works really well. You just have to add your If statements after:
If query1.Count = 1 And query2.Count = 1 Then
Me.Hide()
FrmExample.Show()
Else
MessageBox.Show("Incorrect username or password", "Warning")
End If
Idk if that's any help, thank you!

Efficient way to dynamically populate ListBox vb.net

I have a program that allows a user to search for a customer by name. The way I have done this so far (code below) is have the user start typing the customer name in a TextBox (tbCust), the code fires on the TextChanged event and repopulates the ListBox based on what the user has typed. I think the idea here is obvious and commonly used.
This works without minimal lag on my computer but on some other users computers which are more base level machines, there is anywhere from 100ms to 300ms delay between updates which makes for a pretty crappy user experience.
Correct me if i'm wrong here but I feel like this functionality should be easily attainable without any perceived lag for just about any computer out there.
I assume there is a more correct/efficient way of doing this that I'm just not smart enough to come up with on my own (enter, all of you!)
Please shed some light on maybe a more 'appropriate' way of doing this that results in much better performance. I assume my problem lies with querying the database each time the routine runs (every time the user types a letter) but I'm not sure how else to do it while still working with live data.
Many Many Thanks in Advance!
Video of acceptable performance on my computer: Youtube Video #1
Video of unacceptable performance on user computer: YouTube Video #2
User Computer Specs:
Private Sub tbCust_TextChanged(sender As Object, e As EventArgs) Handles tbCust.TextChanged
'This populates the Customer Selection list box with customers whose names start with the
'string of letters in the customer name text box.
If tbCust.TextLength > 0 Then
lbCustSelect.Visible = True
Dim SQL As String
SQL = "SELECT C_CUSTOMER as ID, C_SHIPNAME as Name FROM CUSTOMER WHERE LEFT(C_SHIPNAME," & tbCust.TextLength & ") ='" & tbCust.Text & "'"
'Query Database
AeroDBcon.RunQuery(SQL)
'Fill DataTable with Query results
dtCustomers = AeroDBcon.DBds.Tables(0)
'Tie DataTable to ListBox
lbCustSelect.DataSource = dtCustomers
lbCustSelect.DisplayMember = "Name"
lbCustSelect.ValueMember = "ID"
'If there are no results, hide the ListBox
If dtCustomers.Rows.Count = 0 Then
lbCustSelect.Visible = False
End If
Else
'if there is no text in the customer name text box, hide the listbox
lbCustSelect.Visible = False
End If
End Sub
Filtering in SQL is usually quicker than filtering on client side. But since table CUSTOMER is probably not that large, and there seems to be an overhead issue with querying the database, let's query it all at once, and filter on the client side.
I like strong-typing. Even though you don't use an ORM, we can still create a class to hold your results:
Private Class Customer
Public Property ID As String
Public Property Name As String
End Class
And if we hold a collection of all customers,
Private customers As IEnumerable(Of Customer)
it's simply filtered like this
Dim filteredCustomers = customers.Where(Function(c) c.Name.StartsWith(filterString)).ToList()
Also, I wouldn't run the query on keypress. Nor would I run it on the UI thread (UI event handlers run on the UI, and that will cause your UI to freeze while the query runs). Run the query after a set amount of time since the last keypress, and run it off the UI. A System.Threading.Timer is perfect for this.
Private ReadOnly queryTimer As New System.Threading.Timer(AddressOf executeQuery, Nothing, -1, -1)
Private ReadOnly keyPressDelay As Integer = 100
Private customers As IEnumerable(Of Customer)
Private filterString As String = ""
Private Sub tbCust_TextChanged(sender As Object, e As EventArgs) Handles tbCust.TextChanged
filterString = tbCust.Text
lbCustSelect.Visible = filterString.Length > 0
If filterString.Length > 0 Then queryTimer.Change(keyPressDelay, -1)
End Sub
Private Sub executeQuery(state As Object)
' this could alternately be run in Form_Load
If customers Is Nothing Then
Dim sql = "SELECT C_CUSTOMER as ID, C_SHIPNAME as Name FROM CUSTOMER"
AeroDBCon.RunQuery(sql)
customers =
AeroDBCon.DBds.Tables(0).
AsEnumerable().Select(Function(dr) New Customer With {.ID = dr("ID").ToString(), .Name = dr("Name").ToString()})
End If
Dim filteredCustomers = customers.Where(Function(c) c.Name.StartsWith(filterString)).ToList()
' Dim filteredCustomers = customers.Where(Function(c) c.Name.Contains(filterString)).ToList()
' update the control on the UI thread
lbCustSelect.Invoke(
Sub()
lbCustSelect.DataSource = Nothing
lbCustSelect.DisplayMember = "Name"
lbCustSelect.ValueMember = "ID"
lbCustSelect.DataSource = filteredCustomers
End Sub)
End Sub
You should also dispose the timer when the form disposes. Modify your Dispose method to this
Protected Overrides Sub Dispose(disposing As Boolean)
Try
If disposing Then
components?.Dispose()
queryTimer?.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub

VB.NET adding a user to distribution list. An operations error occurred

So this is what I've got -
Public Shared Function GetDirectoryEntry() As DirectoryEntry
Try
Dim entryRoot As New DirectoryEntry("LDAP://RootDSE")
Dim Domain As String = DirectCast(entryRoot.Properties("defaultNamingContext")(0), String)
Dim de As New DirectoryEntry()
de.Path = "LDAP://" & Domain
de.AuthenticationType = AuthenticationTypes.Secure
Return de
Catch
Return Nothing
End Try
End Function
Protected Sub rbAddUser_Click(sender As Object, e As EventArgs) Handles rbAddUser.Click
AddMemberToGroup("LDAP://DOMAIN.local/CN=" & !DISTRIBUTIONNAME! & ",CN=Users,DC=DOMAIN,DC=local", "/CN=" & !SELECTEDUSER! & ",CN=Users,DC=DOMAIN,DC=local")
End Sub
Private Sub AddMemberToGroup(ByVal bindString As String, ByVal newMember As String)
Dim ent As DirectoryEntry = GetDirectoryEntry()
ent.Properties("member").Add(newMember)
ent.CommitChanges()
End Sub
I hope this is easy enough for people to read, anyway the group and user are selected by the users in a table and when they click the add button I want the selected users to be adding to the selected distribution list.
when it gets to the CommitChanges() I get this error
An exception of type 'System.DirectoryServices.DirectoryServicesCOMException' occurred in System.DirectoryServices.dll but was not handled in user code Additional information: An operations error occurred.Error -2147016672
This is a common issue with the Process Model application pool configuration, from the official documentation:
By using the <processModel> element, you can configure many of the security, performance, health, and reliability features of application pools on IIS 7 and later.
This issue exists as CommitChanges() requires elevated privileges, and can be fixed by setting your web-application to run under NetworkManager; this can be done in two ways:
Directly in your code, place the problem code inside this Using statement:
Using HostingEnvironment.Impersonate()
'Problem code goes here.
End Using
Via IIS Manager:
Navigate to your website's application pool;
Navigate to Advanced Settings;
Scroll down to the Process Model group;
Change Identity to NetworkService
I solved the error by passing through my user credentials
Private Sub AddMemberToGroup(ByVal bindString As String, ByVal newMember As String)
Dim ent As New GetDirectoryEntry(bindString)
ent.Properties("member").Add(newMember)
ent.Username = "DOMAIN\USERNAME"
ent.Password = "PASSWORD"
ent.CommitChanges()
End Sub
However my code still doesn't work, I just get no errors.

Calling custom SQL Server stored procedure and URL redirect in VB.NET

I'm building an aspx web application. I have a 'Submit' button in my app that calls a custom stored procedure. I'm trying to figure out the code for redirecting users, once the stored procedure is executed.
Here is my VB.NET code for the button + stored procedure:
Public Overrides Sub SubmitRequisition1_Click(ByVal sender As Object, ByVal args As EventArgs)
Try
Dim CatalogID as Integer
CatalogID = Ctype(me.CatalogID.text, int32)
DbUtils.StartTransaction()
Dim spName As BaseClasses.Data.StoredProcedure = Nothing
Dim firstParameter as BaseClasses.Data.StoredProcedureParameter = Nothing
firstParameter = New BaseClasses.Data.StoredProcedureParameter("#p_CatalogID", CatalogID, System.Data.SqlDbType.Int, System.Data.ParameterDirection.Input)
Dim parameterList(0) As BaseClasses.Data.StoredProcedureParameter
parameterList(0) = firstParameter
spName = New StoredProcedure("DatabaseStoktrak1", "dbo.pHSEProcessWardReqsParams", parameterList)
spName.RunNonQuery()
DbUtils.CommitTransaction()
Catch ex As Exception
' Report the error message to the end user'
BaseClasses.Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
DbUtils.RollBackTransaction()
Finally
DbUtils.EndTransaction()
End Try
End Sub
When I insert this line of code
Response.Redirect("../LocationCatalog/WARDEditLocationCatalog.aspx")
I get a compiler error
Compiler Error Message: BC30451: Name 'Response' is not declared.
Is this line of code correct, and if so, where does it need to go? Do I need to declare something?
Any help is greatly appreciated.
Regards, Tomas
Just out of interest does using HttpContext.Current.Response.Redirect("../LocationCatalog/WARDEditLocationCatalog.aspx") instead.
I had this issue with a previous ASP Web Application and this fixed it.
EDIT
If not then I believe you may need to declare this to the top of your VB Code Page.
Imports System.Web

How to pass parameters to crystal report from vb.net code

I have created a crystal report (cross tab). I'm not using any dataset, instead I used the wizard in crystal report to call an procedure from my Database schema
(Provider given is Microsoft OLEDB provider for oracle, after which I gave my DB credentials(i.e. schema, username, password) and selected the procedure and selected the columns I wanted to display in the report).
There are 5 parameters that I need to pass it from the front end to generate the report. While viewing the crystal report preview, by giving parameters, the report works fine.
Now i want to pass these 5 parameters from the front end(vb.net) to show the report in the CrystalReportViewer. Please suggest the code to write in aspx.vb file.
(PS:- I did go through other forums and found out some code, but all of them were giving some or the other error, so am posting one so that i can get the code specific to my requirement).
Thanks in advance..
I have gotten the report to work...
I wrote the code below:
Dim RptDocument As New ReportDocument
RptDocument.Load(Server.MapPath("rpt\Report.rpt"))
RptDocument.SetParameterValue("param1", Session("param1"))
RptDocument.SetParameterValue("param2", ddlparam2.SelectedValue)
RptDocument.SetParameterValue("param3", param3.text)
RptDocument.SetParameterValue("param4", param4.text)
RptDocument.SetParameterValue("param5", param5.text)
'Set login info
Dim myLogin As CrystalDecisions.Shared.TableLogOnInfo
Dim myTable As Table
For Each myTable In RptDocument.Database.Tables
myLogin = myTable.LogOnInfo
myLogin.ConnectionInfo.ServerName = "server name"
myLogin.ConnectionInfo.DatabaseName = ""
myLogin.ConnectionInfo.UserID = "userid"
myLogin.ConnectionInfo.Password = "pwd"
myTable.ApplyLogOnInfo(myLogin)
myTable.Location = myTable.Location
CrystalReportViewer1.ReportSource = RptDocument
Created a System DNS and had to add Oracle.DataAccess.dll to reference and a class file (with functions same as that in connectooracle.vb class file but with different name), also set up a connection in global.asax to refer to that class connection and using
Imports Oracle.DataAccess.Client instead of Imports System.Data.OracleClient (to avoid ambiguity)...
This somehow made it work and there might be some other solution for that..:)
(For ref:- Adding myLogin.ConnectionInfo.IntegratedSecurity = True gave me this error--
Logon failed. Error in File C:\DOCUME~1\Username\LOCALS~1\Temp\Report {1AG3DD86-141D-43YA-B6A2-AEDF3459AE49}.rpt: Unable to connect: incorrect log on parameters.)
This works for me and I'm using Visual Studio 2008 for this one since VS2010 doesn't have crystal engine for the reference.
First, make sure you have imported these two:
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Now, on my part I was using the odbc because as what I have noticed crystal report works fine with this and since we are working with odbc. So I did not include the login property on the report in my code. On the report just choose odbc connection.
Private Sub ReportViewer_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim cryRpt As New ReportDocument
Dim str1 As String
Try
str1 = Title.str1
str2 =Title.str2
cryRpt.Load("c:\Program Files\Report\" & str2 & "")
Dim crParameterFieldDefinitions As ParameterFieldDefinitions
Dim crParameterFieldDefinition As ParameterFieldDefinition
Dim crParameterValues As New ParameterValues
Dim crParameterDiscreteValue As New ParameterDiscreteValue
crParameterDiscreteValue.Value = strStore
crParameterFieldDefinitions = cryRpt.DataDefinition.ParameterFields
crParameterFieldDefinition = crParameterFieldDefinitions.Item("Store")
crParameterValues = crParameterFieldDefinition.CurrentValues
crParameterValues.Clear()
crParameterValues.Add(crParameterDiscreteValue)
crParameterFieldDefinition.ApplyCurrentValues(crParameterValues)
rptviewer.Cursor = Cursors.AppStarting
rptviewer.ReportSource = cryRpt
rptviewer.Refresh()
rptviewer.Cursor = Cursors.Default
Catch ex As Exception
MsgBox(ex.Message)
Me.Close()
ReportInterface.Show()
End Try
End Sub
I have a class that will get the data inputted by the user. But this will not work using stored procedure parameters.
please mark as accepted if it works for you
Thank You