Getting RavenDB Client API to work in Silverlight - silverlight

I just learned that RavenHQ is an easy-to-use database for .NET and especially Silverlight. I'm trying to insert some Test Data (see Code) but it won’t work. I think I am missing something big because I'm new to RavenDB.
I added the references to the project and created clientaccesspolicy.xml and crossdomain.xml. I get (Firebug) an HTTP 200 Response to "GET clientaccesspolicy.xml" from 1.ravenhq.com but nothing else happens and no data is inserted. Any Ideas would be much appreciated.
Private Sub TestRavenDB()
Try
Dim ds = New DocumentStore()
ds.Url = "https://1.ravenhq.com/databases/AppHarbor_60e82bd1-234f-4178-a59a-b527a1d391bb"
ds.ApiKey = "1f827c44-3e38-4e66-8801-83ba03b01f67"
ds.Initialize()
Dim p As New Person("Donald")
Dim session As IAsyncDocumentSession = ds.OpenAsyncSession()
session.Store(p)
session.SaveChangesAsync()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

Note that you have SaveChangesAsync there. Before your test return, you need to wait for that to complete.

Related

Adding a DocumentWindow to a DocumentTabStrip causes the application to hang indefinitely

I have a Winforms application with a primary form that contains (among other things) a Telerik DocumentTabStrip. These tabs are used to hold user controls or web pages (via a web browser control). It has worked fine for quite a while, but I'm running into an issue now.
I recently switched the web browser control from the built-in .NET web browser based on IE to CefSharp. Since doing so, I've noticed that occasionally when trying to add the DocumentWindow to the DocumentTabStrip, the call will hang indefinitely (in debug) or crash outright (running the app normally). This only appears to happen when opening a DocumentWindow that contains the browser control, not any other user controls. The actual call itself is below.
I'm at a bit of a loss as to how to even begin to debug this, since there's no error that gets received - it just hangs inside the Controls.Add() method indefinitely. Any advice would be appreciated.
Private dts As New Telerik.WinControls.UI.Docking.DocumentTabStrip
Try
dts.InvokeIfRequired(Sub()
Dim docWindow As Telerik.WinControls.UI.Docking.DocumentWindow = Nothing
Dim ctrl As ucBaseControl = Nothing
Dim browser As ucBrowser = Nothing
Dim isBrowser As Boolean = False
docWindow = New Telerik.WinControls.UI.Docking.DocumentWindow
docWindow.BackColor = Color.FromArgb(89, 89, 89)
'Do various stuff to determine the type of control to load (ctrl or browser), then setup the applicable control
If isBrowser Then
'Place the browser into the Document Window.
If Not IsNothing(browser) Then
browser.Dock = DockStyle.Fill
docWindow.Controls.Add(browser)
End If
Else
'Place the ctrl into the Document Window.
ctrl.Dock = DockStyle.Fill
docWindow.Controls.Add(ctrl)
End If
'Add the DocumentWindow to the DocumentTabStrip
' Ensure DockWindow not disposed due to lag in bringing up
If IsNothing(docWindow) OrElse docWindow.IsDisposed Then
Exit Sub
End If
Try
docWindow.Padding = New Padding(0)
dts.TabStripElement.Children(0).Children(1).Padding = New Padding(0)
dts.Controls.Add(docWindow) 'This is where the issue is. It only happens sporadically here.
Catch ex As Exception
'Code to log any exceptions here. In the problem described here, no exception is ever generated, though.
End Try
'Bring the control to the front and focus it, here...
End Sub)
Catch ex As Exception
'Error handling code here'
End Try
I'm assuming InvokeIfRequired is an extension method you've created for Controls. Note that if it relies on Invoke, that is a synchronous call, instead use BeginInvoke (see: What's the difference between Invoke() and BeginInvoke())
No exception was ever thrown because you were suffering from deadlock

VB.NET Report Viewer Issue

So I have a report server in a local area network that I want to access via a winform application with a Report viewer
my Report viewer control Name is rpt_ReportViewer
and here's the Code to view reports on the reportviewer rpt_ReportViewer
Private Sub rpt_GenerateReportBtn_Click(sender As Object, e As EventArgs) Handles rpt_GenerateReportBtn.Click
With rpt_ReportViewer
.ServerReport.ReportServerUrl = New Uri("http://SERVER/ReportServer")
.ServerReport.ReportPath = "/Search Assets Table/Search Assets Table"
.RefreshReport()
End With
End Sub
whenever I run this code it generates an exception in the report viewer saying "The Request Failed with HTTP Status 401: Unauthorized."
I don't know whats wrong but I used this very same code on a localhost and it worked http://localhost/reportserver
can anyone help me figuring out whats wrong please ? thanks in advance.
There's the solution
Dim Credential As New NetworkCredential("User name", "Password") 'Was missing this Line
With rpt_ReportViewer
.ServerReport.ReportServerCredentials.NetworkCredentials = Credential 'Was missing this line too
.ServerReport.ReportServerUrl = New Uri("http://SERVER/ReportServer")
.ServerReport.ReportPath = rpt_ReportsListBox.SelectedValue
.RefreshReport()
End With

Detecting wirless network status change in .NET

I have developed winform application using VB.NET. The application is deployed in the machine which is connected to wireless network. The machine is in the car(moving object).
The application has DataGridView loaded with the data get from MSSQL Server(in Remote machine). The data is refreshed for every 5 seconds.
I have used the NetworkAvailabilityChanged event to detect the network status. If the Network is available, then I retrieve the data from the table.
Code:
AddHandler NetworkChange.NetworkAvailabilityChanged, AddressOf NetworkStateChangeHandler
Public Sub NetworkStateChangeHandler(ByVal sender As Object,
ByVal e As NetworkAvailabilityEventArgs)
If e.IsAvailable = True Then
g_bNetworkAlive = True
Else
g_bNetworkAlive = False
End If
End Sub
private Sub GetData()
If g_bNetworkAlive = True
'code to get the data from table
End If
End Sub
Issue:
If the car movers out of the out of the network, the NetworkAvailabilityChanged event is not fired. so it throws the following error for every 5 seconds and application gets crashed.
A network-related or instance-specific error occurred while establishing
a connection to SQL Server. The server was not found or was not accessible.
Temporary fix: I have made Ping request to the SQL server machine for every 5 seconds to detect the network status. It affects the application's performance.
Note: If I manually switch off the Wifi, the NetworkAvailabilityChanged event is fired. The issue is only when the car moves out of the network.
Is there any some other feasible solution to detect the wireless network status?
Indeed there is.
Why send http request to some dummy website when you can check if you are connected to wifi or not locally.
Use ManagedWifi APIs, This will eliminate the slowdown you are facing.
//Create object at the beginning of your application
WlanClient wlanClient = new WlanClient();
//You this code to check wifi availability wherever you need
foreach (WlanInterface _interface in wlanClient.Interfaces)
{
If (_interface.CurrentConnection.wlanAssociationAttributes.dot11Ssid.SSID!=null)
{
// You are connected to wifi
}
}
EDIT: In case you you are not finding dll, direct link. Just reference the Dll and Voila! you are done.
Change your code as
Private Sub GetData()
If My.Computer.Network.IsAvailable AndAlso g_bNetworkAlive
' code to get the data from table
End If
End Sub
You also can check if you have an internet connection by using WebRequest like this:
Private Sub GetData()
If HasInternet AndAlso g_bNetworkAlive Then
'code to get the data from table
End If
End Sub
Public Shared Function HasInternet As Boolean
Return Not (HttpGet("http://www.google.com/") = "Error")
End Function
Public Shared Function HttpGet(url As String) As String
Dim request As WebRequest = WebRequest.Create(url)
request.Method = "GET"
Try
Dim response As WebResponse = request.GetResponse()
Dim dataStream As Stream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
dataStream.Close()
response.Close()
Return responseFromServer
Catch ex As Exception
Return "Error"
End Try
End Function
And you can check the sql connection by using the following function:
Private Function IsDatabaseConnected() As Boolean
Try
Using sqlConn As New SqlConnection("YourConnectionString")
sqlConn.Open()
Return (sqlConn.State = ConnectionState.Open)
End Using
Catch e1 As SqlException
Return False
Catch e2 As Exception
Return False
End Try
End Function
I would simply use try..catch, so if you get exception, you can know, based on its id, why the code failed, and decide what to do next, and finally you can execute some more code regardless of data being retrieved or not
Private Sub GetData()
Try
'code to get the data from table
Catch ex As Exception
' Show the exception's message.
MessageBox.Show(ex.Message)
' Show the stack trace, which is a list of methods
' that are currently executing.
MessageBox.Show("Stack Trace: " & vbCrLf & ex.StackTrace)
Finally
' This line executes whether or not the exception occurs.
MessageBox.Show("in Finally block")
End Try
End Sub

Refresh a OleDbConnection to an Access DB - best practice

For reasons that is too long to explain in my .Net Win-Form Application I use a single global OleDbConnection to connect an Access DB. When I need, I open and close the connection, but generally the connection remains opened.
The problem is that sometimes the reading of the data not returns the updated datas:
Using cm As New OleDb.OleDbCommand(sQuery, cn)
Using rd As OleDb.OleDbDataReader = cm.ExecuteReader()
If rd.HasRows Then
If rd.Read() Then
Me.txtBrand.Text = rd.Item("MA_BRAND")
End If
End If
rd.Close()
End Using
End Using
While if I use a new connection I get the right data:
Using cn As New OleDb.OleDbConnection(sConnectionString)
cn.Open()
Using cm As New OleDb.OleDbCommand(sQuery, cn)
Using rd As OleDb.OleDbDataReader = cm.ExecuteReader()
If rd.HasRows Then
If rd.Read() Then
Me.txtBrand.Text = rd.Item("MA_BRAND")
End If
End If
rd.Close()
End Using
End Using
cn.Close()
End Using
I have to use the global connection then my solution is this
cn.Close()
cn.Open()
Using cm As New OleDb.OleDbCommand(sQuery, cn)
But I ask: there is a better solution to refresh the OledbConnection?
Thank you!
Pileggi
The Jet Access engine caches stuff - that's probably the problem.
Here's a good link:
How to Synchronize Writes and Reads with MS Access
No, do not leave the connection open. The connection pool provides for fast reconnects.
The problem you are facing with reading and writing the data is due to how Jet is implemented:
Microsoft Jet has a read-cache that is updated every PageTimeout milliseconds (default is 5000ms = 5 seconds). It also has a lazy-write mechanism that operates on a separate thread to main processing and thus writes changes to disk asynchronously.
Also, the rd.HasRows() isn't necessary, the If rd.Read() Then will return false if there aren't any rows.
To continue, the rd.Close() isn't necessary either since you are using the Using...End Using declaration. The End Using will close and dispose of it for you.

HttpWebRequest.BeginGetResponse is not Async

I have some code that iterates a few 100 urls and requests the data from the web.
It looks something like this
for each url in urls
Dim hwr = CType(WebRequest.Create(url), HttpWebRequest)
Dim rq = New ReqArgs
rq.Url= url
rq.Request = hwr
Dim res =
hwr.BeginGetResponse(New AsyncCallback(AddressOf FinishWebRequest), rq)
Dim a = 1
next
Does this look ok?
How come the BeginGetresponse line takes about 2-3 seconds to complete before going to dim a=1?.
Actually I debugged and I see that the FinishWebRequest procedure runs completely before the Dim a=1 is reached.
So is this async?
I'm not earning any time by using the async. am I? Or is there a different way to do this?
The point is that the main sub should fire off 300 requests and return control to the UI, then the FinishWebRequest should process them slowly on its own thread and own time , as the requests come in.
How do I do that?
Btw, the main sub is running in a BackgroundWorker, but I checked with out the BackgroundWorker and the problem is the same
It seems that the answer should be here but its just not working for me
I'm WPF 4.0
Appreciate your help and advice. Thanks
yup
the problem was with the POST
i now start the post writing like this
Dim ReqStream = hwr.BeginGetRequestStream(New AsyncCallback(AddressOf FinishRequestStream), rq)
and then my callback is like this
Sub FinishRequestStream(ByVal result As IAsyncResult)
Dim ag = CType(result.AsyncState, ReqArgs)
Dim postStream = ag.Request.EndGetRequestStream(result)
Dim PostBytes = Encoding.UTF8.GetBytes(ag.PostText)
postStream.Write(PostBytes, 0, PostBytes.Length)
postStream.Close()
Dim res = ag.Request.BeginGetResponse(New AsyncCallback(AddressOf FinishResponse), ag)
End Sub
hope this helps someone in the future
Reposting this from another question.
From the documentation on HttpWebRequest.BeginGetResponse Method:
The BeginGetResponse method requires some synchronous setup tasks to complete (DNS resolution, proxy detection, and TCP socket connection, for example) before this method becomes asynchronous. [...]
it might take considerable time (up to several minutes depending on network settings) to complete the initial synchronous setup tasks before an exception for an error is thrown or the method succeeds.
To avoid waiting for the setup, you can use
HttpWebRequest.BeginGetRequestStream Method
but be aware that:
Your application cannot mix synchronous and asynchronous methods for a particular request. If you call the BeginGetRequestStream method, you must use the BeginGetResponse method to retrieve the response.

Resources