How to save file on local machine in silverlight 4.0? - silverlight

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.

Related

making my datasource file path auto-detecting when running a build in other devices

i am planning to make my data source to auto detect the file path of my .mdf file and my current code is this
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con.ConnectionString = "Data Source=
(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\xxeno\source\repos\Keyboard Part Picker
Layout(2)\keyboardpartpickerDB.mdf;Integrated Security=True"
If con.State = ConnectionState.Open Then
con.Close()
End If
con.Open()
disp_data()
End Sub
i any solution so that it "auto-detects the attach db filename?
That's a very bad location for your data file in the first place. You are referring to the file in the project folder and that's bad. The way this should work is that you place the source data file in the project folder and then, when you build, that file is copied to the output folder. It is that copy that your application uses when it runs. That means that you can make as much of a mess of the copy as you want while testing as you will always have the original source file to go back to. When you want to reset your test data file, you simply create a new copy and overwrite the existing one. When you're ready to deploy your app, a copy of the clean source file will be created in the Release output folder and you're good to go. If you do it that way then you can simply use "|DataDirectory|" for the folder path in your connection string and it will just work:
con.ConnectionString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\keyboardpartpickerDB.mdf;Integrated Security=True"

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

prompt for users to browse database connection if current database connection fails

I am building a data-entry program in vb.net that 5 people will share using, and I have problems setting the right database connection. It would do basic things like: pulling up the stock units, save job, load jobs operations.
The database I'm using is Access database (.mdb). This database will be located in a local server drive (mine is in Z drive) and the connection string looks like this
Provider=Microsoft.Jet.OLEDB.4.0;Data Source="Z:\Jimmy's Files\Quality Enclosures.mdb"
This works fine on my computer, but the problem is it does not work on my coworkers computer.
d (\dc-qenclosures) (Z:) is the loacation to my local server drive, but on my coworker's computer, it is set up as
d (\dc-qenclosures) (Q:).
So, whenever I open the program on my co-worker's computer, it gives me an error saying that the database Provider=Microsoft.Jet.OLEDB.4.0;Data Source="Z:\Jimmy's Files\Quality Enclosures.mdb" does not exist (which makes sense because it is not under Z: on his computer)
I know how to use the OpenFileDialog to browse for mbd files.. but how do I set this as the new database connection?
I want to create a properties menu to set the database location.
This is the code I have so far to browse for the database file
Private Sub RadButton6_Click(sender As Object, e As EventArgs) Handles RadButton6.Click
Dim myStream As Stream = Nothing
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.InitialDirectory = "c:\"
openFileDialog1.Filter = "mdb files (*.mdb)|*.mdb|All files (*.*)|*.*"
openFileDialog1.FilterIndex = 1
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
myStream = openFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
myConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & openFileDialog1.FileName
con.ConnectionString = myConString
con.Open()
End If
Catch Ex As Exception
MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
Finally
' Check this again, since we need to make sure we didn't throw an exception on open.
If (myStream IsNot Nothing) Then
myStream.Close()
End If
End Try
End If
End Sub
I'd second #OneFineDay's suggestion of trying the UNC path first, but to answer your main question of browsing for and saving a database path, you may want to look at storing elements of your connection string in My.Settings, so you could make the path a user-level setting. There's an MSDN article with examples here:
Using My.Settings in Visual Basic 2005
In short, you'd have the code sample you shared save the value to My.Settings.DataPath (or whatever you decide to call the setting). Then when you're connecting to the database and need the connection string, you'd make it read from My.Settings.DataPath.
Of course, that'd store your path to the database in a plain-text app.config file by default, so you'll want to be conscious of that and take appropriate steps if there are any security concerns around your app or database.

Sample onedrive winforms app vb.net

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

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