win8消費者預覽版,vs11,mongodb,metro,win2003,java
考慮:考察了很多nosql數據庫, 也深入研究了cassandra機制,並嘗試編寫程序操作了一番。后來在win8 metro群里受教了,在此也非常感謝“無疆乄炎戎”群主的幫助。后改為考慮mongodb,邏輯層選擇開發簡單快速的框架,所以選擇了asp.net mvc,因安裝了vs11,所以用了mvc 4。mvc web api主要以rest形式服務,故選擇了開源的rest客戶端,目前使用RestSharp。
1、安裝mongodb
下載:http://www.mongodb.org/downloads
選擇2.0.4,windows 32位,沒有選擇Unstable版本。
下載后解壓,需要新建data目錄,以及data目錄下的db目錄。
因為32位的系統,mongodb最大支持數據庫大小為2G,所以官方推薦64位系統。
以上工作做完后,在命令行里運行
>mongod --dbpath e:\mongodb-2.0.4\data即可
在瀏覽器里http://localhost:27017/
會顯示
You are trying to access MongoDB on the native driver port. For http diagnostic access, add 1000 to the port number
至此,安裝完畢。
簡單配置
# 除了啟動時接受命令行參數,MongoDB也可以配置使用一個配置文件,可以以指定使用 -f 或 --config 命令行選項。
mongod -f d:\mongodb-2.0.4\mongodb.conf
# 配置文件范例
# This is an example config file for MongoDB.
dbpath = d:\mongodb-2.0.4\data # 指定數據庫路徑
logpath = d:\mongodb-2.0.4\mongodb.log # 日志路徑
logappend = true # 以追加的方式寫日志
port = 27277 # 指定端口號,默認27017
auth = true # 增加驗證選項
安全
目前mongodb的安全機制很一般,僅僅在用戶權限方面做了些工作(也許我孤陋寡聞,希望不吝賜教)。可以創建只讀用戶和讀取的權限。
默認,mongodb啟動是沒有授權驗證的,需要配置,可以在啟動的時候在命令中添加–auth參數。也可以將-auth加入配置文件。mongodb的授權驗證是在數據庫連接以后。用戶權限有兩種,一種是數據庫管理用戶,一種是個體數據庫私有用戶。
據我看到一位首次接觸mongodb的學習過程中,嘗試掃描一部分計算機的mongodb的默認連接端口,發現只有很少一部分加了驗證。
2、asp.net mvc 4 web api
因為做了小白鼠,所以安裝了win8和vs11。看着別人的示例,簡單做了個流程,發現比spring的簡單多了,基本不需要怎么配置。主要集中學習 rest式數據服務。c#操作mongodb,使用官方的客戶端api。下載地址:https://github.com/mongodb/mongo- csharp-driver/downloads。不需要源碼的,可以直接下載MongoDB.Bson.dll和 MongoDB.Driver.dll。接着引用到mvc工程中。
數據庫連接字符串:mongodb://fred:foobar@localhost/baz fred:foobar是用戶名和密碼,baz相當於你建立的數據庫,即使沒有這個庫,在連接的時候會自動建好。
創建:
var db = MongoDatabase.Create(ConfigurationManager.ConnectionStrings["MongoDB_feni"].ConnectionString);
插入數據:
db["testTable"].Insert(new MongoDB.Bson.BsonDocument {
{ "PhotoID", photo.PhotoID },
{ "Name", photo.Name },
{ "Description", photo.Description },
{ "Data", photo.Data },
{ "DateTime", photo.DateTime } });
刪除數據:
var query = Query.EQ("PhotoID", photo.PhotoID);
db["testTable"].Remove(query);
查找所有數據:
db["testTable"].FindAll();
web api的相對簡單,只需要在里面寫點邏輯即可。運行后默認url/api/action....,可以直接在瀏覽器上測試一下。
3、Rest Client
客戶端api選擇restSharp,導入dll文件后,即可進行數據服務連接,目前沒有考慮安全方面,因其考慮較多,以實現功能為主。
客戶端代碼從國外一個開源項目中剝離出來。
連接url
<add key="ServiceUrl" value="http://localhost:50182/api/photos"/>
//獲取所有記錄
string url = ConfigurationManager.AppSettings["serviceUrl"];
string requestUrl = string.Format("{0}", url);
RestClient client = new RestClient();
client.BaseUrl = requestUrl;
client.ExecuteAsync<List<PhotoItem>>(new RestRequest(),
(response) =>
{
foreach (var photo in response.Data)
photo.UploadedOn = new DateTime(photo.UploadedOn.Ticks, DateTimeKind.Utc).ToLocalTime();
listPhotoItem = response.Data;
});
dgPhotos.ItemsSource = listPhotoItem;
4、測試rest 客戶端
使用restclient-ui-2.3.3-jar.jar,需要java環境。直接運行即可。
sln下載
http://files.cnblogs.com/feni/Projects.part1.rar
http://files.cnblogs.com/feni/Projects.part2.rar
以上是當時僅僅為了走通流程簡單寫的。
這幾天經過一點加工,如下:
1:wei api中對插入圖片文件的操作mongodb的代碼修改一下,使用mongodb里的GridFs保存文件。
2:簡單加了一個驗證,但因為后來做win8 metro的客戶端時候,因為沒有內置的md5和sha之類的,所以暫時屏蔽驗證代碼。
3:web api,post上來的數據:
IEnumerable<HttpContent> parts = await Request.Content.ReadAsMultipartAsync(); foreach (var content in parts) { if (content.Headers.ContentDisposition.Name == "\"fileContents\"") { //如果使用content.ReadAsByteArrayAsync,則會引起超出配置的最大buffer異常
如果使用 content.ReadAsByteArrayAsync()來讀取,會發生Cannot write more bytes to the buffer than the configured maximum buffer size: 65536
這個異常。故用content.ReadAsStreamAsync()來代替。
4:這次增加了win8 metro樣式的客戶端,效果圖如下:
5:metro 讀取圖片代碼:
async private void ImageOpenButon_Click(object sender, RoutedEventArgs e) { if (EnsureUnsnapped()) { FileOpenPicker openPicker = new FileOpenPicker(); openPicker.ViewMode = PickerViewMode.Thumbnail; openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; openPicker.FileTypeFilter.Add(".jpg"); openPicker.FileTypeFilter.Add(".jpeg"); openPicker.FileTypeFilter.Add(".png"); ImageUploadButon.IsEnabled = false; SelectedProgressRing.IsActive = true; StorageFile file = await openPicker.PickSingleFileAsync(); if (null != file) { userTxt.Text = file.Name; using (Stream stream = await file.OpenStreamForReadAsync()) { byte[] buf = new byte[65536]; int nReaded = 0; var tmpMs = new MemoryStream(); while ((nReaded = await stream.ReadAsync(buf, 0, buf.Length)) > 0) { tmpMs.Write(buf, 0, nReaded); } fileData = tmpMs.ToArray(); } ImageUploadButon.IsEnabled = true; SelectedProgressRing.IsActive = false; } else { userTxt.Text = "沒有選擇要上傳的文件"; } } }
6:metro 上傳圖片的代碼:
async private void ImageUploadButon_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrWhiteSpace(userTxt.Text)) { MessageDialog md = new MessageDialog("請選擇一個要上傳的圖片文件", "沒有選擇任何圖片"); await md.ShowAsync(); userTxt.Focus(Windows.UI.Xaml.FocusState.Pointer); } else if (string.IsNullOrWhiteSpace(ImageDescription.Text)) { MessageDialog md = new MessageDialog("請填寫圖片的描述", "圖片描述為空"); await md.ShowAsync(); ImageDescription.Focus(Windows.UI.Xaml.FocusState.Pointer); } else { try { ImageUploadButon.IsEnabled = false; UploadProgressRing.IsActive = true; string url = PhotoItem.SERVICEURL; string requestUrl = string.Format("{0}/", url); RestClient client = new RestClient(); client.BaseUrl = requestUrl; ////加密密碼,以驗證用戶 //HashEncrypt he = new HashEncrypt(true, false); //string hePwd = he.SHA256Encrypt("feni"); //client.Authenticator = new HttpBasicAuthenticator("aaron", hePwd); RestRequest restRequest = new RestRequest(); restRequest.Method = Method.POST; restRequest.AddHeader("fileName", userTxt.Text); restRequest.AddHeader("description", ImageDescription.Text); restRequest.RequestFormat = RestSharp.DataFormat.Json; restRequest.AddFile("fileContents", fileData, userTxt.Text); RestResponse restResponse = client.Execute(restRequest); ImageUploadButon.IsEnabled = true; UploadProgressRing.IsActive = false; if (restResponse.Content == "\"OK\"") { MessageDialog md = new MessageDialog(userTxt.Text + "\r\n圖片保存成功", "上傳結果"); await md.ShowAsync(); var sampleData = new PhotosDataSource(); var rootFrame = new Frame(); rootFrame.Navigate(typeof(GroupedItemsPage), sampleData.ItemGroups); Window.Current.Content = rootFrame; Window.Current.Activate(); } else { MessageDialog md = new MessageDialog(userTxt.Text + "\r\n圖片保存未成功,請重試", "上傳結果"); await md.ShowAsync(); } } catch (Exception ex) { throw new Exception(ex.Message); } } }
代碼稍后上傳