File Uploading to Azure Storage by ASP.NET Webpages - asp.net

There are some reference about File Uploading to Azure BY ASP.NET MVC but I can't find none in field of ASP.NET Webpages
How to implement such code to upload to Azure Storage?
Well.. For more information,
My goal is image uploading in CK Editor
but Due to Azure Hosting, ordinary CKEditor reference is not working.
So I googled and use this code block
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference("lawimage");
// Retrieve reference to a blob named "myblob".
CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob");
// Create or overwrite the "myblob" blob with contents from a local file.
using (var fileStream = System.IO.File.OpenRead(name))
{
blockBlob.UploadFromStream(fileStream);
}
But it doesn't work,
and my 'web.config' is
<appSettings>
<add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=lawcbt;AccountKey=[MyAccountKey]/>
</appSettings>
Is anyone ever did upload to Azure Storage via ASP.NET WebPages?
P.S> To be more clear, My 'upload.aspx' source file is this
upload.aspx

Sure, you have to upload the file first to you Asp.Net webpage. From there you can upload it to your blobstorage. In your code it seems you are trying to upload a file from the server to blobstorage. First you have to upload the file to server, and then you can send the stream to the blobstorage.

I have solved myself! By using Visual Studio, I found a bugging point. olleh!!
Even though I don't like Visual Studio, Visual Studio is very powerful tool Tongue Out
Maybe It's heavyness is worth for that.
This code will work!
<%# Import namespace="System.Configuration" %>
<%# Import namespace="Microsoft.WindowsAzure" %>
<%# Import namespace="Microsoft.WindowsAzure.Storage" %>
<%# Import namespace="Microsoft.WindowsAzure.Storage.Auth" %>
<%# Import namespace="Microsoft.WindowsAzure.Storage.Blob" %>
......
HttpPostedFile theFile = HttpContext.Current.Request.Files[0];
// Azure Upload
// Retrieve storage account from connection string.
StorageCredentials sc = new StorageCredentials("[MyStorageName]", "[MyKey]");
CloudStorageAccount storageAccount = new CloudStorageAccount(sc, false);
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference("lawimage");
// Retrieve reference to a blob named "myblob".
CloudBlockBlob blockBlob = container.GetBlockBlobReference(sFileName);
// Create or overwrite the "myblob" blob with contents from a local file.
using (var fileStream = theFile.InputStream)
{
blockBlob.UploadFromStream(fileStream);
}
.....

Related

What is the path of the Json file in Android at Xamarin.Forms?

I am developing an application for Android using Xamarin.
I have created a JsonData folder in the Android project and created a Setting.json file.
\MyApp\MyApp.Android\JsonData\Setting.json
In the properties, we set the Copy when new.
The following folders in the local environment contain the files.
\MyApp\MyApp.Android\bin\Debug\JsonData\Setting.json
I want to load this file in the actual Android device.
When I do this, it tells me that the file is missing.
Could not find a part of the path "/JsonData/Setting.json."
Try
{
var text = File.ReadAllText("JsonData/Setting.json", Encoding.UTF8);
var setting = JsonConvert.DeserializeObject<Setting>(text);
}
catch(Exception exception)
{
var error = exception.Message;
}
What is the path of the file in Android?
I think you're using File Handling in Xamarin.Forms incorrectly.
From the parameter of function File.ReadAllText, the app will access the file system to getSetting.json from folder JsonData in your android device.
The path of the file on each platform can be determined from a .NET Standard library by using a value of the Environment.SpecialFolder enumeration as the first argument to the Environment.GetFolderPath method. This can then be combined with a filename with the Path.Combine method:
string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "temp.txt");
And you can read the file by code:
string text = File.ReadAllText(fileName);
In addition, from your code,I guess you want to Load your Embedded file( Setting.json) as Resources,right?
In this case,we should make sure the Build Action of your Setting.json is Embedded Resource.
And GetManifestResourceStream is used to access the embedded file using its Resource ID.
You can refer to the following code:
var assembly = IntrospectionExtensions.GetTypeInfo(typeof(LoadResourceText)).Assembly;
Stream stream = assembly.GetManifestResourceStream("YourAppName.JsonData.Setting.json");
string text = "";
using (var reader = new System.IO.StreamReader (stream))
{
text = reader.ReadToEnd ();
}
For more , you can check document : File Handling in Xamarin.Forms.
And you can also check the sample code here: https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/workingwithfiles/ .

Embedding a readonly SQLite Database in a DLL and conenct via Entity Framework

I have a requirement that my DLL should have a readonly database. I made my database as a embedded resource but i am not able to figure it out to connect to the database via entity framework.
try
{
var dataSet = ConfigurationManager.GetSection("system.data") as System.Data.DataSet;
dataSet.Tables[0].Rows.Add("SQLite Data Provider"
, ".Net Framework Data Provider for SQLite"
, "System.Data.SQLite"
, "System.Data.SQLite.SQLiteFactory, System.Data.SQLite");
}
catch (System.Data.ConstraintException) { }
string providerName = "System.Data.SQLite";
string serverName = "NameSpace.DB.sqlite";
// Initialize the connection string builder for the
// underlying provider.
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
// Set the properties for the data source.
sqlBuilder.DataSource = serverName;
sqlBuilder.InitialCatalog = "DB.sqlite";
sqlBuilder.IntegratedSecurity = true;
// Build the SqlConnection connection string.
string providerString = sqlBuilder.ToString();
// Initialize the EntityConnectionStringBuilder.
EntityConnectionStringBuilder entityBuilder =
new EntityConnectionStringBuilder();
//Set the provider name.
entityBuilder.Provider = providerName;
// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = providerString;
// Set the Metadata location.
entityBuilder.Metadata = #"res://*/DataModel.DB.csdl|
res://*/DataModel.DB.ssdl|
res://*/DataModel.DB.msl";
Console.WriteLine(entityBuilder.ToString());
using (EntityConnection conn =
new EntityConnection(entityBuilder.ToString()))
{
conn.Open();
Console.WriteLine("Just testing the connection.");
_container = new MyEntities(conn);
var usersList = _container.UserTable.ToList();
}
It works only when we are copying the database to the client application. I don't want to provide the database as a separate file. I want to embedded it in the dll and give only the dll to other applications.
Regards,
Vivek
As CL. said SQLite has to be in an independent .sqlite file, It cannot be embedded. Take a look at SQL Server Compact. It is all you need, an embedded SQL Database that you can access using Entity Framework.
Here's a tutorial in how to connect to EF.
SQLite databases are based on files.
The SQLite library has the ability to access files through a virtual file system, which would allow redirecting file accessing to somewhere else. So it would be possible to implement a VFS that accesses a resource.
However, System.Data.SQLite does not appear to allow registering your own VFS.

ASP.NET Web API 2 file upload

I would like to know how best to handle file upload and addtional information added to the file to be uploaded using ASP.NET Web API 2 without MVC components. I have google the net and I can tell you I am more confused than I expected.
The Additional info will be stored in db and the file on the disk.
So far the Web API app I am building does not support multipart/form-data. It only supports the default media types. I know I need to create a media formatter.
Pls help.
I had wrote Javascript split File and upload to WEB API . i think you can reference my backend codes
In front-end you need using below code to upload your File
var xhr = new self.XMLHttpRequest();
xhr.open('POST', url, false);
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.send(chunk);
In backend use Request.InputStream.Read to catch your file bytes
[HttpPost]
[ValidateInput(false)]
public string fileUpload(string filename)
{
byte[] file = new byte[Request.InputStream.Length];
Request.InputStream.Read(file, 0, Convert.ToInt32(Request.InputStream.Length));
BinaryWriter binWriter = new BinaryWriter(new MemoryStream());
binWriter.Write(file);
StreamReader reader = new StreamReader(binWriter.BaseStream);
reader.BaseStream.Position = 0;
//This example is recevied text file
while ((line = reader.ReadLine()) != null)
{
};
}
You can just serialize your file data into BASE64 and send them as a string in case of multipart/from-data is not allowed for some reason.

How do I Pass an Image from Flash to ASP.NET?

Quick version:
How do I get an image that was generated on the users browser back to the server?
The current plan is this:
The Flash developer will convert the bitmap to JPEG
He will then POST the JPEG to a page on the site.
I'm thinking I can create a WebService which will use a StreamReader to read the post and save it as a file.
Would that work? Any existing code/samples for doing this?
I suppose we should be able to look at code for doing any file upload to ASP.NET.
In this example, I've created a Flash file with a button on the stage. When you click that button, the Flash sends the image of the button to an ASPX file which saves it out as a JPEG. As you'll see this is done by drawing the DisplayObject into a BitmapData object and as such, you can easily replace the reference to the button with anything that inherits from DisplayObject (including a movie clip that contains the canvas for a paint application etc).
I’ll walk you through the Flash element first and then the .NET backend.
Flash
To send a generated image like this from Flash to ASP.NET (or any other backend) you’re going to need a couple of 3rd party libraries. We’ll need a JPEG Encoder (which Flash doesn’t have, but recent versions of Flex do) which we can get from the AS3 Core Lib http://code.google.com/p/as3corelib/. We’ll also need a base64 encoder for sending the data over the wire. I’ll use the one from Dynamic Flash, available at http://dynamicflash.com/goodies/base64/.
Download these and extract them somewhere sensible on your hard disk (like a C:\lib folder).
I created a new AS3 Flash file and saved it as uploader.fla. I added a button component to the stage and named it btnUpload. Next I edited the ActionScript settings and added my c:\lib folder to the classpath. Then I gave the document a class name of Uploader and saved the file.
Next, I created an ActionScript file and added the following code to it:
package
{
import flash.display.BitmapData;
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.URLVariables;
import flash.utils.ByteArray;
import fl.controls.Button;
import com.adobe.images.JPGEncoder;
import com.dynamicflash.util.Base64;
public class Uploader extends MovieClip
{
// Reference to the button on the stage
public var btnUpload:Button;
// Encoder quality
private var _jpegQuality:int = 100;
// Path to the upload script
private var _uploadPath:String = "/upload.aspx";
public function Uploader()
{
btnUpload.addEventListener(MouseEvent.CLICK, buttonClick);
}
private function buttonClick(e:MouseEvent):void
{
// Create a new BitmapData object the size of the upload button.
// We're going to send the image of the button to the server.
var image:BitmapData = new BitmapData(btnUpload.width, btnUpload.height);
// Draw the button into the BitmapData
image.draw(btnUpload);
// Encode the BitmapData into a ByteArray
var enc:JPGEncoder = new JPGEncoder(_jpegQuality);
var bytes:ByteArray = enc.encode(image);
// and convert the ByteArray to a Base64 encoded string
var base64Bytes:String = Base64.encodeByteArray(bytes);
// Add the string to a URLVariables object
var vars:URLVariables = new URLVariables();
vars.imageData = base64Bytes;
// and send it over the wire via HTTP POST
var url:URLRequest = new URLRequest(_uploadPath);
url.data = vars;
url.method = URLRequestMethod.POST;
var loader:URLLoader = new URLLoader();
loader.load(url);
}
}
}
I saved this file next to the FLA with the name Uploader.as.
I published the SWF into the root of my Asp.NET website.
This code assumes you want to upload the jpeg with a quality of 100% and that the script which will receive the data is called upload.aspx and is located in the root of the site.
ASP.NET
In the root of my website I created a WebForm named upload.aspx. In the .aspx file, i removed all the content apart from the page directive. It’s content look like this:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="upload.aspx.cs" Inherits="upload" %>
Then in the CodeBehind, I added the following:
using System;
using System.IO;
public partial class upload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Get the data from the POST array
string data = Request.Form["imageData"];
// Decode the bytes from the Base64 string
byte[] bytes = Convert.FromBase64String(data);
// Write the jpeg to disk
string path = Server.MapPath("~/save.jpg");
File.WriteAllBytes(path, bytes);
// Clear the response and send a Flash variable back to the URL Loader
Response.Clear();
Response.ContentType = "text/plain";
Response.Write("ok=ok");
}
}
There are obviously hard-coded values such as the save path but from this you should be able to create whatever system you require.
If you need to manipulate the image, as long as you can get a byte[] or a Stream of the POSTed file, you can create an image of it, e.g.
MemoryStream mstr = new MemoryStream(myByteArray);
Image myImage = Image.FromStream(mstr);
Have him post the files like a standard HTML form. You can access those files in the Page_Load event of the page he is posting to by using the following collection
Request.Files
This will return a collection of HttpPostedFiles just like what a FileUpload control does.

Upload files directly to Amazon S3 from ASP.NET application

My ASP.NET MVC application will take a lot of bandwidth and storage space. How can I setup an ASP.NET upload page so the file the user uploaded will go straight to Amazon S3 without using my web server's storage and bandwidth?
Update Feb 2016:
The AWS SDK can handle a lot more of this now. Check out how to build the form, and how to build the signature. That should prevent you from needing the bandwidth on your end, assuming you need to do no processing of the content yourself before sending it to S3.
If you need to upload large files and display a progress bar you should consider the flajaxian component.
It uses flash to upload files directly to amazon s3, saving your bandwidth.
The best and the easiest way to upload files to amazon S3 via asp.net . Have a look at following blog post by me . i think this one will help. Here i have explained from adding a S3 bucket to creating the API Key, Installing Amazon SDK and writing code to upload files. Following are are the sample code for uploading files to amazon S3 with asp.net C#.
using System
using System.Collections.Generic
using System.Linq
using System.Web
using Amazon
using Amazon.S3
using Amazon.S3.Transfer
///
/// Summary description for AmazonUploader
///
public class AmazonUploader
{
public bool sendMyFileToS3(System.IO.Stream localFilePath, string bucketName, string subDirectoryInBucket, string fileNameInS3)
{
// input explained :
// localFilePath = we will use a file stream , instead of path
// bucketName : the name of the bucket in S3 ,the bucket should be already created
// subDirectoryInBucket : if this string is not empty the file will be uploaded to
// a subdirectory with this name
// fileNameInS3 = the file name in the S3
// create an instance of IAmazonS3 class ,in my case i choose RegionEndpoint.EUWest1
// you can change that to APNortheast1 , APSoutheast1 , APSoutheast2 , CNNorth1
// SAEast1 , USEast1 , USGovCloudWest1 , USWest1 , USWest2 . this choice will not
// store your file in a different cloud storage but (i think) it differ in performance
// depending on your location
IAmazonS3 client = new AmazonS3Client("Your Access Key", "Your Secrete Key", Amazon.RegionEndpoint.USWest2);
// create a TransferUtility instance passing it the IAmazonS3 created in the first step
TransferUtility utility = new TransferUtility(client);
// making a TransferUtilityUploadRequest instance
TransferUtilityUploadRequest request = new TransferUtilityUploadRequest();
if (subDirectoryInBucket == "" || subDirectoryInBucket == null)
{
request.BucketName = bucketName; //no subdirectory just bucket name
}
else
{ // subdirectory and bucket name
request.BucketName = bucketName + #"/" + subDirectoryInBucket;
}
request.Key = fileNameInS3 ; //file name up in S3
//request.FilePath = localFilePath; //local file name
request.InputStream = localFilePath;
request.CannedACL = S3CannedACL.PublicReadWrite;
utility.Upload(request); //commensing the transfer
return true; //indicate that the file was sent
}
}
Here you can use the function sendMyFileToS3 to upload file stream to amazon S3.
For more details check my blog in the following link.
Upload File to Amazon S3 via asp.net
I hope the above mentioned link will help.
Look for a javascript library to handle the client side upload of these files. I stumbled upon a javascript and php example Dojo also seems to offer a clientside s3 file upload.
ThreeSharp is a library to facilitate interactions with Amazon S3 in a .NET environment.
You'll still need to host the logic to upload and send files to s3 in your mvc app, but you won't need to persist them on your server.
Save and GET data in aws s3 bucket in asp.net mvc :-
To save plain text data at amazon s3 bucket.
1.First you need a bucket created on aws than
2.You need your aws credentials like
a)aws key b) aws secretkey c) region
// code to save data at aws
// Note you can get access denied error. to remove this please check AWS account and give //read and write rights
Name space need to add from NuGet package
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
var credentials = new Amazon.Runtime.BasicAWSCredentials(awsKey, awsSecretKey);
try`
{
AmazonS3Client client = new AmazonS3Client(credentials, RegionEndpoint.APSouth1);
// simple object put
PutObjectRequest request = new PutObjectRequest()
{
ContentBody = "put your plain text here",
ContentType = "text/plain",
BucketName = "put your bucket name here",
Key = "1"
//put unique key to uniquly idenitify your data
// you can pass here any data with unique id like primary key
//in db
};
PutObjectResponse response = client.PutObject(request);
}
catch(exception ex)
{
//
}
Now go to your AWS account and check the bucket you can get data with "1" Name in the AWS s3 bucket.
Note:- if you get any other issue please ask me a question here will try to resolve it.
To get data from AWS s3 bucket:-
try
{
var credentials = new Amazon.Runtime.BasicAWSCredentials(awsKey, awsSecretKey);
AmazonS3Client client = new AmazonS3Client(credentials, RegionEndpoint.APSouth1);
GetObjectRequest request = new GetObjectRequest()
{
BucketName = bucketName,
Key = "1"// because we pass 1 as unique key while save
//data at the s3 bucket
};
using (GetObjectResponse response = client.GetObject(request))
{
StreamReader reader = new
StreamReader(response.ResponseStream);
vccEncryptedData = reader.ReadToEnd();
}
}
catch (AmazonS3Exception)
{
throw;
}

Resources