Sample onedrive winforms app vb.net - winforms

I've been searching the net for a basic sample winforms app that is written in vb.net to upload a file to onedrive. Does anyone know of any?
I'm trying to get a file uploaded with a winforms app in vb.net. I'm as far as getting the auth working... but calling the next method returns a 401...
I did the following:
Shared scope As String = "wl.skydrive_update"
Shared client_id As String = "0000000040144E26"
Shared signInUrl As New Uri([String].Format("https://login.live.com/oauth20_authorize.srf?client_id={0}&redirect_uri=https://login.live.com/oauth20_desktop.srf&response_type=code&scope={1}", client_id, scope))
Private Sub cmdOneDriveAuth_Click(sender As Object, e As EventArgs) Handles cmdOneDriveAuth.Click
Try
Dim auth As New FrmAuthBrowser
auth.WebBrowser1.Navigate(signInUrl)
auth.Show()
Catch ex As Exception
End Try
End Sub
and then in the auth window:
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
Try
If WebBrowser1.Url.AbsoluteUri.Contains("code=") Then
Dim AuthCode As String = System.Web.HttpUtility.ParseQueryString(WebBrowser1.Url.Query)("code")
My.Settings.OneDrive_Enabled = True
My.Settings.OneDrive_AuthCode = AuthCode
My.Settings.Save()
Me.Dispose()
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
but when I try and get the root info, I get a 401...
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim client As New WebClient()
Dim result = client.OpenRead(New Uri("https://apis.live.net/v5.0/me/skydrive?access_token=" + My.Settings.OneDrive_AuthCode))
Dim sr As StreamReader = New StreamReader(result)
MsgBox(sr.ReadToEnd())
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Can anyone provide me with some guidance?

Looks like you're using the 'code' flow of OAuth, but you're missing a step. The 'code' you get back isn't the same as the access_token. You need to make another call to the login server first to exchange your code for an access_token.
POST https://login.live.com/oauth20_token.srf
Content-Type: application/x-www-form-urlencoded
client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}
&code={code}&grant_type=authorization_code
You can find more details here http://onedrive.github.io/auth/msa_oauth.htm#code-flow.
OneDrive just released a new API, so I would encourage you to check it out. http://onedrive.github.io/
There's also a sample Windows/C# app that you can look at for reference on how to sign in and upload files. https://github.com/OneDrive/onedrive-explorer-win

Related

Upload Image using VB.Net and SQL Server

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim command As New SqlCommand("insert into rent(Image,Status)values(#Image,#Status)", connection)
Dim ms As New MemoryStream
PictureBox1.Image.Save("ms", PictureBox1.Image.RawFormat)
command.Parameters.Add("#Image", SqlDbType.VarChar).Value = ms.ToArray
command.Parameters.Add("#Status", SqlDbType.VarChar).Value = TextBox5.Text
connection.Open()
If command.ExecuteNonQuery = 1 Then
MessageBox.Show("Successfully uploaded")
Else
MessageBox.Show("Not uploaded")
End If
connection.Close()
End Sub
I'm trying to upload an image into my SQL Server using Visual Studio; everything is working except when I click the upload button, I keep getting the following error:
I tried every possible solution and no luck, I tried enabling the tcp and changing the ip even in SQL Server.
The error you get means that you can't connect to SQL Server.
Make sure your connection string is correct, and you don't have a firewall blocking the connection between the computer that runs the code and the computer that hosts SQL Server.
However, once you sort the connection error, you still have a few problems with your code.
change PictureBox1.Image.Save("ms", PictureBox1.Image.RawFormat)
to PictureBox1.Image.Save(ms, PictureBox1.Image.RawFormat)
to save the image into the memory stream.
Change command.Parameters.Add("#Image", SqlDbType.VarChar).Value = ms.ToArray
to command.Parameters.Add("#Image", SqlDbType.VarBinary).Value = ms.ToArray
because memoryStream.ToArray returns a byte array, not a string.
make sure the Image column in your table is, in fact, VarBinary.
SqlCommand, SqlConnection and MemoryStream all implements the IDisposable interface, therefor you should use all of them as local variable inside the using statement. Your code suggest you are using a class level SqlConnecion instance. That should be changed.
All communication with the database should be inside a try...catch block, since too many things you can't control can go wrong (network disconnected, for instance).
Your code should look more like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim RowsEffected as int = 0
Using Dim connection As NewSqlConnection(ConnectionString
Using Dim command As New SqlCommand("insert into rent(Image,Status)values(#Image,#Status)", connection)
Using Dim ms As New MemoryStream
PictureBox1.Image.Save(ms, PictureBox1.Image.RawFormat)
command.Parameters.Add("#Image", SqlDbType.VarBinary).Value = ms.ToArray
command.Parameters.Add("#Status", SqlDbType.VarChar).Value = TextBox5.Text
Try
connection.Open()
RowsEffected = command.ExecuteNonQuery()
End Try
Catch Exception ex
MessageBox.Show("Failed to upload image:"& VbCrLf & ex.Message)
End Catch
End Using
End Using
End Using
If RowsEffected = 1 Then
MessageBox.Show("Successfully uploaded")
Else
MessageBox.Show("Not uploaded")
End If
End Sub

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

How to save file on local machine in silverlight 4.0?

I am downloading the file using server file path and want to save file on local machine?
But I am stuck in silver light because I am new in this..
Any Help....
You can save files (1 at a time) by using the SaveFileDialog. Because of security, this is the only way you can write files to the local HD.
Private textDialog As SaveFileDialog
Public Sub New()
InitializeComponent()
textDialog = New SaveFileDialog()
textDialog.Filter = "Text Files | *.txt"
textDialog.DefaultExt = "txt"
End Sub
Private Sub button1_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
Dim result As System.Nullable(Of Boolean) = textDialog.ShowDialog()
If result = True Then
Dim fileStream As System.IO.Stream = textDialog.OpenFile()
Dim sw As New System.IO.StreamWriter(fileStream)
sw.WriteLine("Writing some text in the file.")
sw.Flush()
sw.Close()
End If
End Sub
Reference: MSDN
Silverlight runs in a sandbox - this limits its ability to read/write files to the drive.
This is a security feature, Users are allowed to open files through use of the OpenFileDialog, but there is no Save feature.
The only way of saving to the users drive is to write what you want to the server and let the user download it.

How to configure NBug to send email

I have a WPF application that I would like to configure to use NBug to send error reports via email.
The config tool works correctly, and I receive a test email, but when adding NBug to the application and triggering an uncaught exception, I do not receive an email. The only configuration I have done matches the Getting Started guide (loosely translated to VB.Net).
Private Sub Application_Startup(sender As Object, e As StartupEventArgs) Handles Me.Startup
AddHandler AppDomain.CurrentDomain.UnhandledException, NBug.Handler.UnhandledException
AddHandler Application.Current.DispatcherUnhandledException, NBug.Handler.DispatcherUnhandledException
AddHandler TaskScheduler.UnobservedTaskException, NBug.Handler.UnobservedTaskException
NBug.Settings.UIMode = NBug.Enums.UIMode.Full
NBug.Settings.StoragePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
NBug.Settings.AddDestinationFromConnectionString("Type=Mail;From=bugs#xxx.com;Port=465;SmtpServer=smtp.gmail.com;To=support#xxx.com;UseAttachment=True;UseAuthentication=True;UseSsl=True;Username=bugs#xxx.com;Password=xxx;")
NBug.Settings.ReleaseMode = True
End Sub
The above code has removed username/password from our gmail account that is used for bug reports.
Any ideas what is wrong with the config or how I could debug?
The zip file attachment is being generated, but no email is sent.
Simply use NBug.Settings.ReleaseMode = true; as described in this intro post: http://www.soygul.com/nbug/

Connecting Visual Basic to local database

I've got a question regarding Visual Basic's local database. So far I've managed to: 1. Create a Local Database, named it Database1 2. Create a table with values (username, password, year/section, secretquestion, secretanswer) 3. Create a dataset in form1(to get form2's entries) 4. Create a registration form in form 2( 5 labels/textboxes to get username,password,year/section,secretquestion,secretanswer)
Here's my current code for Form2:
Public Class Form2
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sqlConnection1 As New System.Data.SqlClient.SqlConnection("Data Source=C:\Users\Bounty Hounds\AppData\Local\Temporary Projects\WindowsApplication1\Database1.sdf")
Dim cmd As New System.Data.SqlClient.SqlCommand
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "INSERT Username (user) Password (pass) Year/Section (yns) SecretQuestion (sq) SecretAnswer (sa)"
cmd.Connection = sqlConnection1
sqlConnection1.Open()
cmd.ExecuteNonQuery()
sqlConnection1.Close()
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
Dim user As String
user = TextBox1.Text
End Sub
Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
Dim pass As String
pass = TextBox2.Text
End Sub
Private Sub TextBox3_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox3.TextChanged
Dim yns As String
yns = TextBox3.Text
End Sub
Private Sub TextBox4_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox4.TextChanged
Dim sq As String
sq = TextBox4.Text
End Sub
Private Sub TextBox5_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox5.TextChanged
Dim sa As String
sa = TextBox5.Text
End Sub
End Class
But as soon as I click the register button it gives me an error and points at the sqlConnection1.Open() line, the error is: "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections."
In the Database Explorer I see my Database1.sdf with an X on its icon(the small yellow cylinder) and checked that its state is closed, so I tried opening it by right clicking it, then modify connection, placed the Database1.sdf path in the Database, inputted my password and pressed ok. At that point I see my Database1.sdf state go "Open" but when I ran my application the state went to "Closed" again (btw I see this state thing by right clicking my Database1.sdf in the Solution Explorer).
This text below has little to no connection with my code above and I just wanted your opinions on what is the best approach to the software I want to create so if you only want to help me on my code which I greatly appreaciate, you can stop reading the paragraphs below but if you do take time to consider reading it, It would mean alot to me. THANKS
The connection of a visual basic form and a database is the first step of what I really want to do, what my main goal is a File Storage system between two PCs which I'll increase once I figured out those 2 PCs.
To reach that goal I tried to divide each problems so I can address them accordingly and eventually finishing the entire software.
Establish a connection between 2 PCs (which I've done by setting PC2's dns server with PC1's ip address).
Connect a visual basic form (which in my case is a registration form) with a database for storing user accounts.
Make every registration create a folder for the certain users that registered. The folders created will be the storage of their files (this idea is really vague atm as I don't know how will I do this, AND VERY IMPORTANT PART IS ONLY THE REGISTERED USERS FROM THE DATABASE ONLY HAVE ACCESS TO THE FOLDERS THEY OWN(sorry i'm not shouting, just noting this as I feel this is the hardest part to do)
Implement a disk quota on the folders to limit sizes.
Create a Login system for PC2 to connect to the database of PC1 (Database should verify this and give an error if the infos are incorrect).
Create a Save/Load button for PC2 (I want PC2 to save its myDocuments Folder on PC1's Folder for Storage Files by using the My.Computer.FileSystem.CopyDirectory command. Then load will copy the PC1's Folder and load it into PC2's MyDocuments Folder.
Lastly and the biggest question is that are all these possible to do with Visual Basic? I've tried it with Windows Active Directory using roaming user profiles but I really want to develop my own software.
EDIT:
#Jimmy Smith
Thanks for replying, I've decided to create another database named CCS and my new code for form2 is:
Dim conn As New System.Data.SqlServerCe.SqlCeConnection()
Dim cmd As New System.Data.SqlClient.SqlCommand
conn.ConnectionString = _
"Persist Security Info = False; Data Source = 'C:\Users\Bounty Hounds\Documents\Visual Studio 2010\Projects\WindowsApplication2\WindowsApplication2\CCS.sdf';" & _
"Password = joshua8; File Mode = 'shared read'; "
conn.Open()
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "INSERT Username (user) Password (pass) Year/Section (yns) SecretQuestion (sq) SecretAnswer (sa)"
However, It generates a new error:
There is a file sharing violation. A different process might be using the file. [ C:\Users\Bounty Hounds\Documents\Visual Studio 2010\Projects\WindowsApplication2\WindowsApplication2\CCS.sdf ]
You can't connect to SDF files direct without using the Compact Edition library. Unfortunately, it's not installed by default as Microsoft seems to be phasing it out.
Use System.Data.SqlserverCe.SqlCeConnection in place of System.Data.SqlClient.SqlConnection
http://visualstudiogallery.msdn.microsoft.com/0e313dfd-be80-4afb-b5e9-6e74d369f7a1
http://msdn.microsoft.com/en-us/library/system.data.sqlserverce.sqlceconnection(v=vs.100).aspx

Resources