I am using the following code and the code is working for some images is fine but most images EXIF data is not getting.
ImageMetadata imageMetadata = new ImageMetadata();
public ImageMetadata ReadEXIFMetadata(string filepath)
{
FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
System.Drawing.Image image__1 = System.Drawing.Image.FromStream(fs);
PropertyItem[] imagePropertyItems = image__1.PropertyItems;
foreach (PropertyItem pi in imagePropertyItems)
{
switch ((EXIFProperty)pi.Id)
{
case EXIFProperty.Title:
imageMetadata.Title = Encoding.Unicode.GetString(pi.Value);
break;
case EXIFProperty.Author:
imageMetadata.Author = Encoding.Unicode.GetString(pi.Value);
//imageMetadata.Author = Encoding.UTF8.GetString(pi.Value)
break;
case EXIFProperty.Keywords:
imageMetadata.Keywords = Encoding.Unicode.GetString(pi.Value);
break;
case EXIFProperty.Comments:
imageMetadata.Comments = Encoding.Unicode.GetString(pi.Value);
//imageMetadata.Comments = Encoding.UTF8.GetString(pi.Value)
break;
default:
break;
}
}
fs.Close();
return imageMetadata;
}
public enum EXIFProperty
{
Title = 40091,
Author = 40093,
Keywords = 40094,
Comments = 40092
}
public class ImageMetadata
{
private string _title = string.Empty;
private string _author = string.Empty;
private string _keywords = string.Empty;
private string _comments = string.Empty;
public ImageMetadata()
{
this._title = string.Empty;
this._author = string.Empty;
this._keywords = string.Empty;
this._comments = string.Empty;
}
public ImageMetadata(string title, string author, string keywords, string comments)
{
this._title = title;
this._author = author;
this._keywords = keywords;
this._comments = comments;
}
public string Title
{
get
{
return this._title;
}
set
{
this._title = value;
}
}
public string Author
{
get
{
return this._author;
}
set
{
this._author = value;
}
}
public string Keywords
{
get
{
return this._keywords;
}
set
{
this._keywords = value;
}
}
public string Comments
{
get
{
return this._comments;
}
set
{
this._comments = value;
}
}
}
Correct me if I am doing something wrong in the above code.please help stuck with this problem.
I'm not sure why you've created your own ImageMetaData class as .NET already has one. Try:
BitmapCreateOptions createOptions = BitmapCreateOptions.PreservePixelFormat | BitmapCreateOptions.IgnoreColorProfile;
BitmapMetadata importedMetaData = new BitmapMetadata("jpg");
using (Stream sourceStream = File.Open(fileName, FileMode.Open, FileAccess.Read))
{
BitmapDecoder sourceDecoder = BitmapDecoder.Create(sourceStream, createOptions, BitmapCacheOption.Default);
// Check source is has valid frames
if (sourceDecoder.Frames[0] != null && sourceDecoder.Frames[0].Metadata != null)
{
sourceDecoder.Frames[0].Metadata.Freeze();
// Get a clone copy of the metadata
BitmapMetadata sourceMetadata = sourceDecoder.Frames[0].Metadata.Clone() as BitmapMetadata;
importedMetaData = sourceMetadata;
}
}
return importedMetaData;
Related
I get an memory exception while loading a 4GB file. i have to do that twice but i have enougth memmory to load them. the memmory exception occures when i have 3gb left or more.:(.
Method:
public TableModel LoadTable(string path) {
TableModel model = new TableModel();
using (FileStream filestream = new FileStream(path, FileMode.Open, FileAccess.Read)) {
using (StreamReader reader = new StreamReader(filestream, Encoding.UTF8)) {
string line = "";
bool isHeader = true;
int counter = 0;
List<string> rows = new List<string>();
while ((line = reader.ReadLine()) != null) {
if (isHeader) {
model.Columns = line.Split(new string[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
isHeader = false;
continue;
} else {
if (Settings.Default.RonudSet != 0) {
rows.Add(RoundDecimals(line));
} else {
rows.Add(line);
}
}
counter++;
}
model.RowCount = counter;
model.ColumnsCount = model.Columns.Length;
model.Keys = new HashSet<string>(rows);
}
}
return model;
}
Exception:
System.OutOfMemoryException was unhandled
The function evaluation was disabled because of an out of memory exception.
TableModel:
class TableModel {
private string tableName;
private string[] columns;
private HashSet<string> keys;
public int ColumnsCount { get; set; }
public int RowCount { get; set; }
public string TableName { get { return tableName; } set { this.tableName = value; } }
public string[] Columns { get { return columns; } set { this.columns = value; } }
public HashSet<string> Keys { get { return keys; } set { this.keys = value; } }
}
Start Compare:
if (newFile.Name.Equals(currFile.Name)) {
FileLoader loader = new FileLoader();
TableModel newModel = loader.LoadTable(newFile.ToString());
TableModel currentModel = loader.LoadTable(currFile.ToString());
newModel.TableName = newFile.Name;
currentModel.TableName = currFile.Name;
new Compare(newModel, currentModel, currFile.Directory.Name);
break;
}
Compare:
private void CheckColumns() {
bool sameColumnCount = CheckColumnsCount();
int counter = 0;
currentContent = new HashSet<string>(currentModel.Columns);
newContent = new HashSet<string>(newModel.Columns);
foreach (string header in currentContent) {
if (!newContent.Contains(header)) {
headersNotFoundInN.Add(header);
}
}
foreach (string header in newContent) {
if (!currentContent.Contains(header)) {
headersNotFoundInC.Add(header);
}
}
if (currentModel.ColumnsCount == newModel.ColumnsCount) {
for (int i = 0; i < currentModel.ColumnsCount; i++) {
if (currentModel.Columns[i] == newModel.Columns[i]) {
counter++;
}
}
if (counter == currentModel.ColumnsCount) {
headerSequence = true;
} else {
headerSequence = false;
}
} else {
headerSequence = false;
}
bool emptyNotFoundIn = false;
if (headersNotFoundInC.Count == 0 && headersNotFoundInN.Count == 0) {
emptyNotFoundIn = true;
}
ReportContent(sameColumnCount, headerSequence, emptyNotFoundIn);
}
private void CheckRows() {
bool sameRowCount = CheckRowCount();
currentContent = new HashSet<string>(currentModel.Keys);
newContent = new HashSet<string>(newModel.Keys);
foreach (string key in currentContent) {
if (!newContent.Contains(key)) {
rowNotFoundInN.Add(key);
}
}
foreach (string key in newContent) {
if (!currentContent.Contains(key)) {
rowNotFoundInC.Add(key);
}
}
bool emptyNotFoundIn = false;
if (rowNotFoundInC.Count == 0 && rowNotFoundInN.Count == 0) {
emptyNotFoundIn = true;
}
ReportContent(sameRowCount, emptyNotFoundIn);
}
Its a table with many rows that i have to compare with a similar table. at the end i have to give a report about the diffrences. but i fail here where i have to load this massive file.
try using BufferedStream
using (BufferedStream bs = new BufferedStream(filestream))
{
}
I made an application to download files into a folder inside another folder.
The name for the folder obtained from DataFile name from database and match the name of the image that has been downloaded.
I'm having a problem, that when downloading to a folder for the first bundle of data is fine, but at the time of downloading the data bundle again the previous folder and the new folder also download both files.
When downloading the files that differ it will create a new folder again and the two previous folders are also downloaded the file. For more details, can see in the image below:
And should one folder contains two files.
JSON:
RHData Class:
[PrimaryKey]
public string SKU { get; set; }
public string Judul { get; set; }
public string Tipe { get; set; }
public string Harga { get; set; }
public string Gratis { get; set; }
public string DataFile { get; set; }
RHViewModel class:
class RHViewModel
{
private string sku = string.Empty;
public string SKU
{
get { return sku; }
set
{
if (sku == value)
return;
sku = value;
RaisePropertyChanged("SKU");
}
}
private string judul = string.Empty;
public string Judul
{
get { return judul; }
set
{
if (judul == value)
return;
judul = value;
RaisePropertyChanged("Judul");
}
}
private string tipe = string.Empty;
public string Tipe
{
get { return tipe; }
set
{
if (tipe == value)
return;
tipe = value;
RaisePropertyChanged("Tipe");
}
}
private string harga = string.Empty;
public string Harga
{
get { return harga; }
set
{
if (harga == value)
return;
harga = value;
RaisePropertyChanged("Harga");
}
}
private string cover = string.Empty;
private string gratis = string.Empty;
public string Gratis
{
get { return gratis; }
set
{
if (gratis == value)
return;
gratis = value;
RaisePropertyChanged("Gratis");
}
}
private string dataFile = string.Empty;
public string DataFile
{
get { return dataFile; }
set
{
if (dataFile == value)
return;
dataFile = value;
RaisePropertyChanged("DataFile");
}
}
public RHViewModel GetItem(string itemSku)
{
var item = new RHViewModel();
using (var db = new SQLiteConnection(App.SQLITE_PLATFORM, App.DB_PATH))
{
var _item = (db.Table<RHData>().Where(
c => c.SKU == itemSku)).Single();
item.SKU = _item.SKU;
item.Judul = _item.Judul;
item.Tipe = _item.Tipe;
item.Harga = _item.Harga;
item.Gratis = _item.Gratis;
item.DataFile = _item.DataFile;
}
return item;
}
public string SaveItem(RHViewModel item)
{
string result = string.Empty;
using (var db = new SQLiteConnection(App.SQLITE_PLATFORM, App.DB_PATH))
{
try
{
var existingItem = (db.Table<RHData>().Where(
c => c.SKU == item.sku)).SingleOrDefault();
if (existingItem != null)
{
existingItem.SKU = item.SKU;
existingItem.Judul = item.Judul;
existingItem.Tipe = item.Tipe;
existingItem.Harga = item.Harga;
existingItem.Gratis = item.Gratis;
existingItem.DataFile = item.DataFile;
int success = db.Update(existingItem);
}
else
{
int success = db.Insert(new RHData()
{
SKU = item.SKU,
Judul = item.Judul,
//Deskripsi = item.Deskripsi,
Tipe = item.Tipe,
Harga = item.Harga,
Gratis = item.Gratis,
//Cover = item.Cover,
//File = item.File,
DataFile = item.DataFile
});
}
result = "Success";
}
catch
{
result = "This item was not saved.";
}
}
return result;
}
public string DeleteItem(string itemDataFile)
{
string result = string.Empty;
using (var dbConn = new SQLiteConnection(App.SQLITE_PLATFORM, App.DB_PATH))
{
var existingItem = dbConn.Query<RHData>("select * from RH where DataFile =" + itemDataFile).FirstOrDefault();
if (existingItem != null)
{
dbConn.RunInTransaction(() =>
{
dbConn.Delete(existingItem);
if (dbConn.Delete(existingItem) > 0)
{
result = "Success";
}
else
{
result = "This item was not removed";
}
});
}
return result;
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void RaisePropertyChanged(string propertyName)
{
var handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
RHItemsViewModel Class:
class RHItemsViewModel : RHViewModel
{
private ObservableCollection<RHViewModel> items;
public ObservableCollection<RHViewModel> Items
{
get
{
return items;
}
set
{
items = value;
RaisePropertyChanged("Items");
}
}
public ObservableCollection<RHViewModel> GetItems()
{
items = new ObservableCollection<RHViewModel>();
using (var db = new SQLiteConnection(App.SQLITE_PLATFORM, App.DB_PATH))
{
var query = db.Table<RHData>().OrderBy(c => c.SKU);
foreach (var _item in query)
{
var item = new RHViewModel()
{
//SKU = _item.SKU,
SKU = _item.SKU,
Judul = _item.Judul,
//Deskripsi = _item.Deskripsi,
Tipe = _item.Tipe,
Harga = _item.Harga,
Gratis = _item.Gratis,
//Cover = _item.Cover,
//File = _item.File,
DataFile = _item.DataFile
};
items.Add(item);
}
}
return items;
}
}
}
App.Xaml.CS
public static string DB_PATH = Path.Combine(ApplicationData.Current.LocalFolder.Path, "RH.sqlite");
public static SQLite.Net.Platform.WinRT.SQLitePlatformWinRT SQLITE_PLATFORM;
public App()
{
Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(
Microsoft.ApplicationInsights.WindowsCollectors.Metadata |
Microsoft.ApplicationInsights.WindowsCollectors.Session);
this.InitializeComponent();
this.Suspending += OnSuspending;
SQLITE_PLATFORM = new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT();
if (!CheckFileExists("RH.sqlite").Result)
{
using (var db = new SQLiteConnection(SQLITE_PLATFORM, DB_PATH))
{
db.CreateTable<RHData>();
}
}
}
private async Task<bool> CheckFileExists(string fileName)
{
try
{
var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
return true;
}
catch
{
}
return false;
}
Code:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
//GC.Collect();
BukuAudio dlList = e.Parameter as BukuAudio;
if (dlList != null)
{
Queue<DownloadOperation> downloadOperationList = new Queue<DownloadOperation>();
BackgroundDownloader downloader = new BackgroundDownloader();
DownloadProgress.Visibility = Visibility.Visible;
downloadfilename.Visibility = Visibility.Visible;
statusdownload.Visibility = Visibility.Visible;
deleteBtn.Visibility = Visibility.Collapsed;
viewBtn.Visibility = Visibility.Collapsed;
foreach (var path in dlList.BundlePath)
{
DownloadBuku(path);
for (int i = 0; i<dlList.BundlePath.Count;i++)
{
downloadfilename.Text = dlList.BundleName.ElementAt(i);
Uri uri = new Uri(path);
string filename = path.Substring(uri.LocalPath.LastIndexOf("/") + 1);
downloadfilename.Text = String.Format("Unduh '{0}'", filename);
}
}
DownloadGambar(dlList.Cover);
}
else
{
DownloadProgress.Visibility = Visibility.Collapsed;
downloadfilename.Visibility = Visibility.Collapsed;
statusdownload.Visibility = Visibility.Collapsed;
deleteBtn.Visibility = Visibility.Visible;
viewBtn.Visibility = Visibility.Visible;
}
bookAudio = e.Parameter as BookAudio;
}
private async void downloadClicked(object sender, RoutedEventArgs e)
{
Uri uri = new Uri(itemDetail.BundlePath.First());
string filename = System.IO.Path.GetFileName(uri.LocalPath);
string statustext = String.Format("Download Buku '{0}'?", itemDetail.Judul);
string sudahada = String.Format("Buku '{0}' sudah ada/sedang didownload", itemDetail.Judul);
MessageDialog messageDialog;
try
{
StorageFolder library = await ApplicationData.Current.LocalFolder.CreateFolderAsync("library", CreationCollisionOption.OpenIfExists);
var file = await library.GetFileAsync(filename);
messageDialog = new MessageDialog(sudahada, "Buku sudah ada");
messageDialog.Commands.Add(new UICommand("Library", (command) =>
{
this.Frame.Navigate(typeof(library.LibraryPage));
}));
messageDialog.Commands.Add(new UICommand("Batal", (command) =>
{
//rootPage.NotifyUser("The 'Don't install' command has been selected.", NotifyType.StatusMessage);
}));
}
catch (FileNotFoundException ex)
{
//file not exists show download dialog
// Create the message dialog and set its content and title
messageDialog = new MessageDialog(statustext, "Download");
// Add commands and set their callbacks
messageDialog.Commands.Add(new UICommand("Download", (command) =>
{
itemsViewModel = new RHItemsViewModel();
itemsViewModel.SaveItem(new RHViewModel()
{
SKU = itemDetail.SKU.ToString(),
Judul = itemDetail.Judul.ToString(),
Tipe = itemDetail.Tipe.ToString(),
Harga = itemDetail.Harga.ToString(),
Gratis = itemDetail.Gratis.ToString(),
DataFile = itemDetail.DataFile.ToString()
});
this.Frame.Navigate(typeof(library.LibraryPage), itemDetail);
}));
messageDialog.Commands.Add(new UICommand("Batal", (command) =>
{
//rootPage.NotifyUser("The 'Don't install' command has been selected.", NotifyType.StatusMessage);
}));
}
// Show the message dialog
await messageDialog.ShowAsync();
}
}
Library Page:
private async void DownloadBuku(string fileLocation)
{
itemsViewModel = new RHItemsViewModel();
items = new ObservableCollection<RHViewModel>();
using (var dbConn = new SQLiteConnection(App.SQLITE_PLATFORM, App.DB_PATH))
{
var existingItem = dbConn.Table<RHData>().OrderBy(c => c.DataFile);
if (existingItem != null)
{
foreach (var _item in existingItem)
{
var item = new RHViewModel()
{
DataFile = _item.DataFile
};
items.Add(item);
var uri = new Uri(fileLocation);
var downloader = new BackgroundDownloader();
StorageFolder library = await installedLocation.CreateFolderAsync("library", CreationCollisionOption.OpenIfExists);
StorageFolder pdf = await library.CreateFolderAsync(item.DataFile.ToString(), CreationCollisionOption.OpenIfExists);
string filename = System.IO.Path.GetFileName(uri.LocalPath);
StorageFile file = await pdf.CreateFileAsync(filename,
CreationCollisionOption.ReplaceExisting);
DownloadOperation download = downloader.CreateDownload(uri, file);
await StartDownloadAsync(download);
}
}
}
}
BukuAudio Class:
class BukuAudio
{
public string SKU { get; set; }
public string Judul { get; set; }
public string Deskripsi { get; set; }
public string Tipe { get; set; }
public string NamaTipe { get; set; }
public string Harga { get; set; }
public string Cover { get; set; }
public string File { get; set; }
public string Gratis { get; set; }
public string Tanggal { get; set; }
public string DataFile { get; set; }
public JsonArray Bundle_file { get; set; }
public List<string> BundleName { get; set; }
public List<string> BundlePath { get; set; }
}
How to handle it?
Note:
First Bundle File downloaded in the folder "bundle.24b"
Second Bundle file downloaded files in the folder "bundle.23b"
Third Bundle downloaded file in the folder "bundle.22b
Supposedly the file name "bundle.24b ....." downloaded in folder bundle.24b, the file name "bundle.23b ....." downloaded in folder bundle.23b, the file name "bundle.22b ....." downloaded in folder bundle.22b
I am working on rss feed reader project for Windows Phone. I use the construct below for reading feed in.
It seems to work fine for the 200+ feeds I track - apart for two feeds from NASA
"http://www.nasa.gov/rss/dyn/TWAN_vodcast.rss"
"http://www.nasa.gov/rss/dyn/TWAN_podcast.rss"
for which I get quite frequently problems. Not always and not the same feed, but a few times a week instead of nice utf-8 textual rss feed I get non textual stuff starting (in decimal)
31, 65533, 8, 0, 0..
The strange thing is that reading the feed at the same time with e.g. Chrome shows always good textual result.
Is there something trivial I am missing here? Some black magic that Chrome can do but Windows Phone cannot? Is there some way I can "fix" in my app what Windows Phone fails here? For compatibility reasons I am building for WP7.8 on VS Express 2012
(and yes, I e-mailed to feed owner some time ago but did not get any reply)
public void GetFeed(string _RssUri)
{
WebClient wc = new WebClient();
wc.OpenReadCompleted += wc_OpenReadCompleted;
wc.OpenReadAsync(new Uri(_RssUri));
}
void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
using (StreamReader sr = new StreamReader(e.Result, true))
{
_feedString = sr.ReadToEnd();
}
Assert.IsTrue("0:60 1:63 2:120 3:109 4:108 5:32" == decodeStringContent(rssContent), "Feed does not start with '<?xml '");
// doSomething(_feedString);
}
}
public static string decodeStringContent(string _in, int _maxItems = 5)
{
string _decoding = "";
int _i = 0;
foreach (char x in _in)
{
if (_decoding != "") _decoding = _decoding + " ";
_decoding = _decoding + _i++.ToString() + ":" + Convert.ToInt32(x);
if (_maxItems > 0 && _i > _maxItems) break;
}
return _decoding;
}
Not sure about those particular issues you have had. I also have a feed reader app in the WP8 store and I haven't run into that particular problem when I preview a new feed. I tried with those two feeds and both worked ok.
I pasted a block of code that may help you. A lot of the code you won't need but it should give you a basis to start from.
using FeedModel.Classes;
using FeedModel.Helpers;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Xml.Linq;
namespace FeedModel
{
public class FeedDiscovery
{
private delegate void HttpGetDelegate(IAsyncResult asynchronousResult);
private enum FeedType { RSS, Atom, RDF }
public void FindFeeds(SearchFeedsCallback callback, string searchString)
{
string url = "https://ajax.googleapis.com/ajax/services/feed/find";
string args = string.Format("v=1.0&q={0}", searchString);
httpGet(url, args, (IAsyncResult asynchronousResult) =>
{
try
{
HttpWebRequest sidrequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)sidrequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string subscriptionContent = streamRead.ReadToEnd();
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
JObject jobj = JObject.Parse(subscriptionContent);
JArray subscriptions = (JArray)((JObject)jobj["responseData"])["entries"];
List<FDFeedItem> feeds =
(from f in subscriptions
select new FDFeedItem()
{
Title = WebBrowserHelper.StripHtml((string)f["title"]),
XmlUrl = (string)f["url"],
Description = WebBrowserHelper.StripHtml((string)f["contentSnippet"]),
HtmlUrl = (string)f["link"],
}).ToList();
callback(new SearchFeedsEventArgs(feeds)
{
Failed = false,
Error = "",
});
// return;
}
catch
{
callback(new SearchFeedsEventArgs(new List<FDFeedItem>())
{
Failed = true,
Error = "Failed",
});
}
});
}
public void FeedPreview(FeedPreviewCallback callback, string url)
{
try
{
httpGet(url, "", (IAsyncResult asynchronousResult) =>
{
try
{
HttpWebRequest sidrequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)sidrequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string subscriptionContent = streamRead.ReadToEnd();
XDocument doc = XDocument.Parse(subscriptionContent);
FeedType feedType = FeedType.RSS;
if (doc.Root.ToString().StartsWith("<feed xmlns") || doc.Root.ToString().StartsWith("2005/Atom\">"))
feedType = FeedType.Atom;
List<Article> articles;
string title = "";
string description = "";
switch (feedType)
{
case FeedType.RSS:
articles = ParseRss(doc, out title, out description);
break;
case FeedType.RDF:
articles = ParseRdf(doc, out title, out description);
break;
case FeedType.Atom:
articles = ParseAtom(doc, out title, out description);
break;
default:
throw new NotSupportedException(string.Format("{0} is not supported", feedType.ToString()));
}
FDFeedItem feed = new FDFeedItem();
feed.Title = title;
feed.Description = description;
feed.XmlUrl = url;
callback(new FeedPreviewEventArgs(articles, feed)
{
Failed = false,
Error = ""
});
}
catch
{
callback(new FeedPreviewEventArgs(new List<Article>(), new FDFeedItem())
{
Failed = true,
Error = "Failed to get articles"
});
}
});
}
catch
{
callback(new FeedPreviewEventArgs(new List<Article>(), new FDFeedItem())
{
Failed = true,
Error = "Failed"
});
}
}
public void GetFeedDetails(FeedDetailsCallback callback, string url)
{
try
{
httpGet(url, "", (IAsyncResult asynchronousResult) =>
{
try
{
HttpWebRequest sidrequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)sidrequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string subscriptionContent = streamRead.ReadToEnd();
XDocument doc = XDocument.Parse(subscriptionContent);
callback(new FeedsDetailsEventArgs(new FDFeedItem())
{
Failed = false,
Error = ""
});
}
catch
{
callback(new FeedsDetailsEventArgs(new FDFeedItem())
{
Failed = true,
Error = "Failed to get feed"
});
}
});
}
catch
{
callback(new FeedsDetailsEventArgs(new FDFeedItem())
{
Failed = true,
Error = "Failed"
});
}
}
private void httpGet(string requestUrl, string getArgs, HttpGetDelegate httpGetResponse)
{
string url = requestUrl;
if (getArgs != "")
url = string.Format("{0}?{1}", requestUrl, getArgs);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.BeginGetResponse(new AsyncCallback(httpGetResponse), request);
}
/// <summary>
/// Parses an Atom feed and returns a <see cref="IList<Item>"/>.
/// </summary>
private List<Article> ParseAtom(XDocument doc, out string title, out string description)
{
title = doc.Root.Elements().First(i => i.Name.LocalName == "title").Value;
try
{
description = doc.Root.Elements().First(i => i.Name.LocalName == "subtitle").Value;
}
catch { description = ""; }
try
{
var entries = from item in doc.Root.Elements().Where(i => i.Name.LocalName == "entry")
select new Article
{
Content = item.Elements().First(i => i.Name.LocalName == "content").Value,
Url = item.Elements().First(i => i.Name.LocalName == "link").Attribute("href").Value,
PublishedDate = ParseDate(item.Elements().First(i => i.Name.LocalName == "published").Value),
Title = item.Elements().First(i => i.Name.LocalName == "title").Value,
Summary = WebBrowserHelper.GetSummary(item.Elements().First(i => i.Name.LocalName == "content").Value),
CrawlTime = DateTime.ParseExact("01/01/1970", "dd/MM/yyyy", CultureInfo.InvariantCulture),
Author = item.Elements().First(i => i.Name.LocalName == "author").Elements().First(i=> i.Name.LocalName == "name").Value ,
Read = false,
Starred = false,
FeedProviderName = "NewsBlur",
OpenMode = ArticleOpenMode.UseContent,
Image = WebBrowserHelper.ExtractFirstImageFromHTML(item.Elements().First(i => i.Name.LocalName == "content").Value),
};
return entries.ToList();
}
catch
{
return new List<Article>();
}
}
/// <summary>
/// Parses an RSS feed and returns a <see cref="IList<Item>"/>.
/// </summary>
private List<Article> ParseRss(XDocument doc, out string title, out string description)
{
title = "";
description = "";
try
{
//XDocument doc = XDocument.Load(url);
// RSS/Channel/item
var root = doc.Root.Descendants().First(i => i.Name.LocalName == "channel"); //.Elements() .First(i => i.Name.LocalName == "description").Value;
title = root.Elements().First(i => i.Name.LocalName == "title").Value;
description = root.Elements().First(i => i.Name.LocalName == "description").Value;
var entries = from item in root.Elements().Where(i => i.Name.LocalName == "item")
select new Article
{
Content = item.Elements().First(i => i.Name.LocalName == "description").Value,
Url = item.Elements().First(i => i.Name.LocalName == "link").Value,
PublishedDate = ParseDate(item.Elements().First(i => i.Name.LocalName == "pubDate").Value),
Title = item.Elements().First(i => i.Name.LocalName == "title").Value,
Summary = WebBrowserHelper.GetSummary(item.Elements().First(i => i.Name.LocalName == "description").Value),
//Author = WebBrowserHelper.GetSummary(item.Elements().First(i => i.Name.LocalName == "creator").Value),
Author = "",
Read = false,
Starred = false,
FeedProviderName = "NewsBlur",
OpenMode = ArticleOpenMode.UseContent,
Image = WebBrowserHelper.ExtractFirstImageFromHTML(item.Elements().First(i => i.Name.LocalName == "description").Value),
};
return entries.ToList();
}
catch (Exception e)
{
return new List<Article>();
}
}
/// <summary>
/// Parses an RDF feed and returns a <see cref="IList<Item>"/>.
/// </summary>
private List<Article> ParseRdf(XDocument doc, out string title, out string description)
{
title = "";
description = "";
try
{
//XDocument doc = XDocument.Load(url);
// <item> is under the root
var entries = from item in doc.Root.Descendants().Where(i => i.Name.LocalName == "item")
select new Article
{
Content = item.Elements().First(i => i.Name.LocalName == "description").Value,
FeedUrl = item.Elements().First(i => i.Name.LocalName == "link").Value,
PublishedDate = ParseDate(item.Elements().First(i => i.Name.LocalName == "date").Value),
Title = item.Elements().First(i => i.Name.LocalName == "title").Value,
Summary = WebBrowserHelper.GetSummary(item.Elements().First(i => i.Name.LocalName == "description").Value),
Image = WebBrowserHelper.ExtractFirstImageFromHTML(item.Elements().First(i => i.Name.LocalName == "description").Value),
OpenMode = ArticleOpenMode.UseContent,
};
return entries.ToList();
}
catch
{
return new List<Article>();
}
}
private DateTime ParseDate(string date)
{
DateTime result;
if (DateTime.TryParse(date, out result))
return result;
else
{
int i = date.LastIndexOf(" ");
if (i > date.Length - 6)
{
date = date.Substring(0, i).Trim();
if (DateTime.TryParse(date, out result))
return result;
}
return DateTime.MinValue;
}
}
private string GetSummary(string content)
{
string lContent = content.Trim('\"');
int contentLength = 800;
if (lContent.Length < 800)
contentLength = lContent.Length;
string _localContent = "";
try
{
_localContent = WebBrowserHelper.StripHtml(lContent.Substring(0, contentLength));
}
catch
{
}
if (_localContent.Length > 150)
_localContent = _localContent.Substring(0, 150) + "...";
return _localContent;
}
}
}
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Globalization;
namespace FeedModel.Classes
{
public enum ArticleOpenMode {OpenWebPage,UseContent, Mobilizer};
public class Article
{
private string _id;
protected DateTime _publishedDate;
protected DateTime _crawlTime;
private string _author;
private string _title;
private string _content;
private string _summary;
private string _url;
protected bool _read;
protected bool _starred;
private string _rawDate;
private string _rawCrawlTime;
private ArticleOpenMode _openMode;
protected List<string> _tags;
private string _feedProviderName;
private string _feedTitle;
private string _feedUrl;
private string _feedId;
private string _image;
private AccountTypes _accountType;
public Article()
{
_tags = new List<string>();
_image = "";
}
public ArticleOpenMode OpenMode
{
get { return _openMode; }
set { _openMode = value; }
}
public bool Read
{
get { return _read; }
set { _read = value; }
}
public bool Starred
{
get { return _starred; }
set { _starred = value; }
}
public string Image
{
get { return _image; }
set { _image = value; }
}
public string FeedProviderName
{
get { return _feedProviderName; }
set { _feedProviderName = value; }
}
public string FeedTitle
{
get { return _feedTitle; }
set { _feedTitle = value; }
}
public string FeedUrl
{
get { return _feedUrl; }
set { _feedUrl = value; }
}
public string FeedId
{
get { return _feedId; }
set { _feedId = value; }
}
public string Url
{
get { return _url; }
set { _url = value; }
}
public string Content
{
get { return _content; }
set { _content = value; }
}
public string Summary
{
get { return _summary; }
set { _summary = value; }
}
public string Title
{
get { return _title; }
set { _title = value; }
}
public string Author
{
get { return _author; }
set { _author = value; }
}
public DateTime PublishedDate
{
get { return _publishedDate; }
set { _publishedDate = value; }
}
public DateTime CrawlTime
{
get { return _crawlTime; }
set { _crawlTime = value; }
}
public string Id
{
get { return _id; }
set { _id = value; }
}
public List<string> Tags
{
get { return _tags; }
set { _tags = value; }
}
public string RawPublishDate
{
get { return _rawDate; }
set
{
Double seconds;
_rawDate = value;
try
{
seconds = Convert.ToDouble(_rawDate);
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
_publishedDate = origin.AddSeconds(seconds);
}
catch
{
_publishedDate = DateTime.Now;
}
}
}
public string RawCrawlTime
{
get { return _rawCrawlTime; }
set
{
Double seconds;
_rawCrawlTime = value;
//try
//{
// seconds = Convert.ToDouble(_rawCrawlTime);
// DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
// _crawlTime = origin.AddSeconds(seconds);
//}
//catch
//{
_crawlTime = DateTime.Now;
//}
}
}
public AccountTypes AccountType
{
get { return _accountType; }
set { _accountType = value; }
}
}
}
I have huge problem with saveing and restore ObservableCollection to IsolatedData.
I'm trying with this code.
Helper class for Observable
public class ListItem {
public String Title { get; set; }
public bool Checked { get; set; }
public ListItem(String title, bool isChecked=false) {
Title = title;
Checked = isChecked;
}
private ListItem() { }
}
IsoHelper
public class IsoStoreHelper {
private static IsolatedStorageFile _isoStore;
public static IsolatedStorageFile IsoStore {
get { return _isoStore ?? (_isoStore = IsolatedStorageFile.GetUserStoreForApplication()); }
}
public static void SaveList<T>(string folderName, string dataName, ObservableCollection<T> dataList) where T : class {
if (!IsoStore.DirectoryExists(folderName)) {
IsoStore.CreateDirectory(folderName);
}
if (IsoStore.FileExists(folderName + "\\" + dataName+".dat")) {
IsoStore.DeleteFile(folderName + "\\" + dataName + ".dat");
}
string fileStreamName = string.Format("{0}\\{1}.dat", folderName, dataName);
try {
using (var stream = new IsolatedStorageFileStream(fileStreamName, FileMode.Create, IsoStore)) {
var dcs = new DataContractSerializer(typeof(ObservableCollection<T>));
dcs.WriteObject(stream, dataList);
}
} catch (Exception e) {
Debug.WriteLine(e.Message);
}
}
public static ObservableCollection<T> LoadList<T>(string folderName, string dataName) where T : class {
var retval = new ObservableCollection<T>();
if (!IsoStore.DirectoryExists(folderName) || !IsoStore.FileExists(folderName + "\\" + dataName + ".dat")) {
return retval;
}
string fileStreamName = string.Format("{0}\\{1}.dat", folderName, dataName);
var isf = IsoStore;
try {
var fileStream = IsoStore.OpenFile(fileStreamName, FileMode.OpenOrCreate);
if (fileStream.Length > 0) {
var dcs = new DataContractSerializer(typeof(ObservableCollection<T>));
retval = dcs.ReadObject(fileStream) as ObservableCollection<T>;
}
} catch {
retval = new ObservableCollection<T>();
}
return retval;
}
}
And I'm trying to use it this way
public partial class MainPage : PhoneApplicationPage{
public ObservableCollection<ListItem> ListItems = new ObservableCollection<ListItem>();
bool isListSaved;
private void Panorama_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) {
if (strTag.Equals("list") ) {
isListSave = false;
ListItems = IsoStoreHelper.LoadList<ListItem>("settings", "ListItems");
} else if (!isListSave) {
IsoStoreHelper.SaveList<ListItem>("settings", "ListItems", ListItems);
}
}
}
I keep getting A first chance exception of type 'System.Security.SecurityException' occurred in System.Runtime.Serialization.ni.dll when I try read saved file at line ReadObject(fileStream) but the FileAccess looks fine.
Any conclusion will be appreciated.
SOLVED:
Like Dmytro Tsiniavskyi said I totaly forgot about [DataContract] and [DataMember] in ListItem. Whats more I found better solution for saving and loading data. I end up with this code for ListItem
[DataContract]
public class ListItem {
[DataMember]
public String Title { get; set; }
[DataMember]
public bool Checked { get; set; }
public ListItem(String title, bool isChecked=false) {
Title = title;
Checked = isChecked;
}
private ListItem() { }
}
And this code for save/load collection which was originally founded here and modified a litte bit for better useage.
public partial class IsolatedRW {
public static void SaveData<T>(string fileName, T dataToSave) {
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) {
try {
if (store.FileExists(fileName)) {
store.DeleteFile(fileName);
}
if (!store.DirectoryExists("Settings")) store.CreateDirectory("Settings");
IsolatedStorageFileStream stream;
using (stream = store.OpenFile("Settings/"+fileName+".xml", System.IO.FileMode.Create, System.IO.FileAccess.Write)) {
var serializer = new DataContractSerializer(typeof(T));
serializer.WriteObject(stream, dataToSave);
}
stream.Close();
} catch (System.Security.SecurityException e) {
//MessageBox.Show(e.Message);
return;
}
Debug.WriteLine(store.FileExists("Settings/" + fileName + ".xml"));
}
}
public static T ReadData<T>(string fileName) {
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) {
Debug.WriteLine(store.FileExists("Settings/" + fileName + ".xml"));
if (store.FileExists("Settings/" + fileName + ".xml")) {
IsolatedStorageFileStream stream;
using (stream = store.OpenFile("Settings/"+fileName+".xml", FileMode.OpenOrCreate, FileAccess.Read)) {
try {
var serializer = new DataContractSerializer(typeof(T));
return (T)serializer.ReadObject(stream);
} catch (Exception) {
return default(T);
}
}
stream.Close();
}
return default(T);
}
}
}
Try to add [DataContract] attribute for your ListItem class.
[DataContract]
public class ListItem {
[DataMember]
public String Title { get; set; }
[DataMember]
public bool Checked { get; set; }
public ListItem(String title, bool isChecked=false) {
Title = title;
Checked = isChecked;
}
private ListItem() { }
}
I'm currently trying to make a small program that store the input by the user in the textbox to a file but somehow I couldn't save the input to the file this is what I have done so far:
First Class:
class Name
{
private string SongName;
private string ArtistName;
//Constructor
public Name(string SongName, string ArtistName)
{
this.ArtistName = ArtistName;
this.SongName = SongName;
}
//Properties for SongName
public string songName
{
get { return SongName; }
set { SongName = value; }
}
//Properties for ArtistName
public string artistName
{
get { return ArtistName; }
set { ArtistName = value; }
}
}
And here is the Form1 code:
public Form1()
{
InitializeComponent();
}
private string SongName, ArtistName;
public void Registry()
{
List<Name> MusicList = new List<Name>();
MusicList.Add(new Name(SongName = txtSongName.Text , ArtistName = txtArtistName.Text)); //Add new elements to the NameClass
//Save the list
StreamWriter FileSaving = new StreamWriter("MusicList");
for (int i = 0; i < MusicList.Count; i++)
{
string sName = MusicList[i].songName;
string aName = MusicList[i].artistName;
}
FileSaving.Close();
}
private void btnEnter_Click(object sender, EventArgs e)
{
Registry();
//Set the textbox to emty so the user can enter new data
txtArtistName.Text = "";
txtSongName.Text = "";
}
In your for loop you need to actually write the values to the stream.
for (int i = 0; i < MusicList.Count i++)
{
string sName = MusicList[i].songName;
string aName = MusicList[i].artistName;
FileSaving.WriteLine(sName + ' ' + aName);
}
....You never write anything to the file.....
A quick Google got me this
Notice the call to file.WriteLine(line); also...you realize you are not creating your file with an extension, also?
Here you are creating the StreamWriter but never using it:
StreamWriter FileSaving = new StreamWriter("MusicList");
for (int i = 0; i < MusicList.Count; i++)
{
string sName = MusicList[i].songName;
string aName = MusicList[i].artistName;
}
FileSaving.Close();
strings aName and sName are assigned to but never saved.
See example here on using StreamWriter:
http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx
using (StreamWriter writer = new StreamWriter(filePath))
{
for (int i = 0; i < MusicList.Count; i++)
{
writer.WriteLine(MusicList[i].songName + " , " + MusicList[i].artistName);
}
}
I my opinion You should use XML Serialization
here is my serialization generic class
public static class Serializer<T>
{
public static T Deserialize(string path)
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
System.IO.FileStream stream = null;
try
{
stream = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
return (T)serializer.Deserialize(stream);
}
finally
{
if (stream != null)
{
stream.Close();
stream.Dispose();
}
}
}
public static void Serialize(string path, T obj, bool createFolder = false)
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
if (createFolder)
{
System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path));
}
using (System.Xml.XmlTextWriter xmlWriter = new System.Xml.XmlTextWriter(path, System.Text.Encoding.Unicode))
{
xmlWriter.Formatting = System.Xml.Formatting.Indented;
serializer.Serialize(xmlWriter, obj);
xmlWriter.Flush();
xmlWriter.Close();
}
}
}
Then in Registy Method
public void Registry()
{
List<Name> MusicList = new List<Name>();
MusicList.Add(new Name(SongName = txtSongName.Text , ArtistName = txtArtistName.Text)); //Add new elements to the NameClass
Serializer<List<Name>>.Serialize(#"C:\saved.xml", MusicList);
}
note that you must add default constructor in class Name