Search Results

Search found 45804 results on 1833 pages for 'large files'.

Page 72/1833 | < Previous Page | 68 69 70 71 72 73 74 75 76 77 78 79  | Next Page >

  • Lost files after installing Ubuntu

    - by Joshua Rosato
    I installed Ubuntu on my laptop over windows, I had 2 partitions on one hard disk. It seems like my second partition is gone with all my files. How can I recover the old files? They weren't on the same partition as Windows. I read that the partition has probably just not been mounted so ran sudo fdisk -l to find all the partitions and then ran sudo mount, however I can't tell from the results of sudo mount what is not mounted and I am also unsure how to mount it once I find the unmounted partition. sudo fdisk -l - Results Disk /dev/sda: 250.1 GB, 250059350016 bytes 255 heads, 63 sectors/track, 30401 cylinders, total 488397168 sectors Units = sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disk identifier: 0x0002c6dc Device Boot Start End Blocks Id System /dev/sda1 * 2048 486322175 243160064 83 Linux /dev/sda2 486324222 488396799 1036289 5 Extended /dev/sda5 486324224 488396799 1036288 82 Linux swap / Solaris sudo mount - Results /dev/sda1 on / type ext4 (rw,errors=remount-ro) proc on /proc type proc (rw,noexec,nosuid,nodev) sysfs on /sys type sysfs (rw,noexec,nosuid,nodev) none on /sys/fs/cgroup type tmpfs (rw) none on /sys/fs/fuse/connections type fusectl (rw) none on /sys/kernel/debug type debugfs (rw) none on /sys/kernel/security type securityfs (rw) udev on /dev type devtmpfs (rw,mode=0755) devpts on /dev/pts type devpts (rw,noexec,nosuid,gid=5,mode=0620) tmpfs on /run type tmpfs (rw,noexec,nosuid,size=10%,mode=0755) none on /run/lock type tmpfs (rw,noexec,nosuid,nodev,size=5242880) none on /run/shm type tmpfs (rw,nosuid,nodev) none on /run/user type tmpfs (rw,noexec,nosuid,nodev,size=104857600,mode=0755) none on /sys/fs/pstore type pstore (rw) systemd on /sys/fs/cgroup/systemd type cgroup (rw,noexec,nosuid,nodev,none,name=systemd) gvfsd-fuse on /run/user/1000/gvfs type fuse.gvfsd-fuse (rw,nosuid,nodev,user=joshy1)

    Read the article

  • Web browser downloads only open target folders - cannot open files

    - by Pavlos G.
    After installing xubuntu packages in order to check xfce, I reverted back to gnome2. During the first login, I noticed that thunar was now selected as the default file manager. Preferred applications menu is also missing now, so I could not set nautilus as the default. I removed all the xubuntu packages (including thunar) and then when I tried to open a folder, I was asked to select the default file manager - that's how I got nautilus back. The next problem I'm now facing has to do with the downloaded files from web browsers: Open and Open containing folder options produce exactly the same result. If I double-click on a file, it'll just open the containing folder, instead of opening the file with it's associated application (e.g. libreoffice writer for .doc,.odt, smplayer for .avi,.wmv, etc). The problem happens both in Firefox and Chrome. Through nautilus, all files open correctly. Up until now I've tried the following: Delete/recreate mimeTypes.rdf in my FF profile Create a new profile in FF Delete/recreate ~/.local/share/applications/mimeapps.list Already checked this similar article None of them worked. Any ideas on the issue would be appreciated.

    Read the article

  • Keeping files that are often changed in sync between desktop and laptop

    - by N.N.
    I'm looking for a way to keep a desktop and a laptop in sync. What I want to keep in sync are some folders, mainly ~/Documents, that are changed often when working on them. If it matters I can connect to my desktop from anywhere via an URL but my laptop is harder to access since it might be behind NAT and such. I have been looking at Ubuntu One but it seems to not go well with working on documents written in LaTeX. If I work on a .tex file in the Ubuntu One directory and compile it (with pdflatex) every now and then (as often as every 10 sec when working) it will create several new files including a pdf which are uploaded to Ubuntu One and this seems stupid since it will create continuous upload when working on .tex files. I also usually keep .tex documents version controlled by git and then every commit (which also can happen frequently) will cause upload (by changes in ./.git) so that it happens continuously when working. Another example is editing images that are saved often. What I think would be best is for sync to happen every tenth minute or at the end of every working session (but there might be some other way to handle this?).

    Read the article

  • Any good reason open files in text mode?

    - by Tinctorius
    (Almost-)POSIX-compliant operating systems and Windows are known to distinguish between 'binary mode' and 'text mode' file I/O. While the former mode doesn't transform any data between the actual file or stream and the application, the latter 'translates' the contents to some standard format in a platform-specific manner: line endings are transparently translated to '\n' in C, and some platforms (CP/M, DOS and Windows) cut off a file when a byte with value 0x1A is found. These transformations seem a little useless to me. People share files between computers with different operating systems. Text mode would cause some data to be handled differently across some platforms, so when this matters, one would probably use binary mode instead. As an example: while Windows uses the sequence CR LF to end a line in text mode, UNIX text mode will not treat CR as part of the line ending sequence. Applications would have to filter that noise themselves. Older Mac versions only use CR in text mode as line endings, so neither UNIX nor Windows would understand its files. If this matters, a portable application would probably implement the parsing by itself instead of using text mode. Implementing newline interpretation in the parser might also remove some overhead of using text mode, as buffers would need to be rewritten (and possibly resized) before returning to the application, while this may be less efficient than when it would happen in the application instead. So, my question is: is there any good reason to still rely on the host OS to translate line endings and file truncation?

    Read the article

  • FTP gives me a error when uploading and deleting files [on hold]

    - by AR Games
    Here's the error I get when trying to delete files... Command: DELE index.html Response: 550 Delete operation failed. Here's the error I get when trying to upload files... Command: OPTS UTF8 ON Response: 200 Always in UTF8 mode. Status: Connected Status: Starting upload of C:\wamp\www\.DS_Store Command: CWD /var/www/html Response: 250 Directory successfully changed. Command: TYPE A Response: 200 Switching to ASCII mode. Command: PASV Response: 227 Entering Passive Mode (76,185,76,101,78,222). Command: STOR .DS_Store Response: 553 Could not create file. Error: Critical file transfer error Status: Retrieving directory listing... Command: TYPE I Response: 200 Switching to Binary mode. Command: PASV Response: 227 Entering Passive Mode (76,185,76,101,23,94). Command: LIST Response: 150 Here comes the directory listing. Response: 226 Directory send OK. Status: Directory listing successful Response: 421 Timeout. Error: Connection closed by server Status: Disconnected from server IM running windows OS and using filezilla FTP client

    Read the article

  • Convert uploaded video files to mp4 using PHP [closed]

    - by Subin
    I created a PHP video uploading script. I need to convert these files to mp4 for HTML5 VIDEO PLAYER using PHP while uploading . How can I do that ? Here is the PHP code. <?php if(isset($_POST['submit'])){ $user=$_COOKIE['VisitorName']; include('config.php'); session_start(); $session_id='1'; //$session id $path = "/home/simsu/subins/videos/data/videos/"; $valid_formats = array("wmv", "ogv", "mp4", "3gp", "ogg"); if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") { $name = $_FILES['uploadedfile']['name']; $size = $_FILES['uploadedfile']['size']; if(strlen($name)) { list($txt, $ext) = explode(".", $name); if(in_array($ext,$valid_formats)) { if($size<(100024*100024)) { $actual_image_name = $path.time().".mp4"; $tmp = $_FILES['uploadedfile']['tmp_name']; $upurl="http://vtube.subins.com/files/video?vid=".time(); $title=$_POST['vn']; mysql_query("INSERT INTO videos(title,user,url,vid,ext) VALUES ('$title', '$user','$upurl',NOW(),'$ext')"); echo '<br><h1>'.$_FILES['uploadedfile']['name'] . " uploaded.</h1>"; } else echo "<br><h1>Video file size max 100 MB"; } else echo "<br><h1>Invalid file format.."; } else echo "<br><h1>Please select a video..!"; exit; } } ?>

    Read the article

  • accessing files on a shared folder via IIS

    - by Darkcat Studios
    Im not sure if this suits stackexchange, serverfault or here... so i'll go with here for a start. I'm having issues setting up a network share to be accessed by IIS, all I need to do is read/write files on the Other server. We have 2 servers set up (Both 2008 R2 & IIS 7.5), one is the WEB server, which is externally accessible and NOT part of the domain. We also have an Intranet server which has no internet connectivity and is part of the domain. These 2 servers can talk to each other happily, I have the SQL server on the WEB server shared across to the intranet server so that the web content is editable from the intranet. I can share a folder on the web server (say, wwwroot/Images/) and connect to it from the intranet server, even have it as a mapped drive (but i know thats not going to work for IIS to access it), So there seems not to be a connectivity issue. I can also set up a Virtual folder in IIS on the Intranet server - this is where it gets annoying - I cant connect using pass-through authentication because there is no suitable user on the web server (which is not on the domain). If i set up a user on the web server, eg Intranet_USR, and give it appropriate rights to the folder, files and share, i can connect, but only view folder contents in IIS, not read, although that user has read privileges!! Any help much appreciated!

    Read the article

  • TraceTune supports uploading Zip files

    - by Bill Graziano
    I’ve been using the online version of ClearTrace more and more lately.  When I get to a new client it’s just much easier to upload a trace file rather than install ClearTrace. That means I’ve finally been adding more features to it.  The two latest features are around ease of use. You can now upload a ZIP file that contains a trace file.  Trace files are already somewhat compressed.  Putting it in a ZIP file further compresses it by a factor of 8X or 9X in my testing. That means you can start with a 100MB trace and end up with a 10Mb-12MB ZIP file to upload.  I’m consistently able to get over 150,000 events in a 100MB ZIP file.  That gives me a pretty good look at a system. The second part of this is that files are now processed asynchronously.  After you upload a file you’ll be taken to a processing page that updates every few seconds with the number of rows processed.  It generally takes under a minute to process a 100MB trace file but I *hated* staring at a blank screen. Give TraceTune a try.  It’s getting easier to use every day.

    Read the article

  • Files in /home deleted

    - by long-time user....2006
    In the most specific, unemotional terms: Reinstalled os, using 11.10(1 month after release to skip initial issues that usually crop up). Configured system to my specifications(just ways of organizing config files, etc). Log out Log back in after after an hour or so...to find my home directory obliterated and just a few skeleton files existing. think oh well, try again (this has happened before with an install for reasons I've never been able to pinpoint, usually around install time with some sort of update but its never been a major recurring issue) same thing happens I thought something was awry, so I reinstalled again (another 20 minutes, meh) Set up system, arranged home directory a bit differently thinking maybe I tread on something I shouldn't have. log out, come back --- the same thing. Most of the directories I added were deleted (e.g. .xmonad which links to xmonad.hs in my portable config directory) tl;dr every change I make in my home directory gets deleted. The emotional part: UNACCEPTABLE. I need to configure my system the way I want, not get punched in the face everytime I make a change. I'll willingly fill in details as needed, this was just a start to see if anyone can help, I've found no trace of this issue in a search.

    Read the article

  • Re-installing Ubuntu without losing files, how to?

    - by moraleida
    Sometime back i bought a second PC to serve as my backup machine, but i've never managed to have it as i would like. Now i want to start over, but i've messed so much with it's disks that i'm kinda afraid to lose something on the way, thus this question. Right now, I have a 1Tb disk partitioned like this (as per GParted): /dev/sda1 (ext4) 346.12Gb - Is almost full, has an old install of Ubuntu 11.10. It no longer boots, ever since i installed Windows7 on /sda3. Everything that matters to me is tucked into /var/www/ all the rest can just go. /dev/sda2 (ext4) 196.45Gb - has an old install of 12.04 and nothing important, it's pretty much empty and also doesn't boot. /dev/sda3 (ntfs) 377.97Gb - is my boot partition with Windows 7, some important files and I'd like to keep it untouched. /dev/sda4 (extended) 10.97Gb - was created when i first installed Ubuntu, i think. In my ideal world, I'd like to safely reinstall Ubuntu from the 12.04 liveUSB and merge sda1 and sda2 without losing any files. Is that possible? How?

    Read the article

  • java : writing large files ?

    - by umanga
    Greetings , I get huge number of records from database and write into a file.I was wondering what the best way to write huge files. (1Gb - 10Gb). Currently I am using BufferedWriter BufferedWriter mbrWriter=new BufferedWriter(new FileWriter(memberCSV)); while(done){ //do writings } mbrWriter.close();

    Read the article

  • ZipArchive memory problems on iPhone for large archive

    - by Mithin
    Hi, I am trying to compress multiple files into a single zip archive and I am running into low memory warning. Since the complete zip file is loaded into the memory I guess that's the problem. Is there a way by which I can manage the compression/decompression better using ZipArchive so that not all the data is in the memory at once? Thanks!

    Read the article

  • Robust Large File Transfer with WCF

    - by Sharov
    I want to transfer big files (1GB) over unreliable transport channels. When connection is interrupted, I don't want start file transfering from the begining. I can partially store it in a temp table and store last readed position, so when connection is reestablished I can request continue uploading of file from this position. Is there any best-practice for such kind of things. I'm currently use chunking channel.

    Read the article

  • Redirect Large Number of URLs (HTML Files) to Wordpress

    - by Chetan
    Hi, I have over 2000 HTML files that are now in Wordpress blog. I have the URL Map of Old_file.html and new wordpress URL. I want 301 redirect but don't want to add 2000 lines to htaccess. Can you please suggest how to accomplish this using PHP so that when there is a request for old url, the php script should lookup into the database and redirect(301) to the new URL ? Thanks.

    Read the article

  • Sending Big Files with WCF

    - by Sean Feldman
    I had to look into a project that submits large files to WCF service. Implementation is based on data chunking. This is a good approach when your client and server are not both based on WCF, bud different technologies. The problem with something like this is that chunking (either you wish it or not) complicates the overall solution. Alternative would be streaming. In WCF to WCF scenario, this is a piece of cake. When client is Java, it becomes a bit more challenging (has anyone implemented Java client streaming data to WCF service?). What I really liked about .NET implementation with WCF, is that sending header info along with stream was dead simple, and from the developer point of view looked like it’s all a part of the DTO passed into the service. [ServiceContract] public interface IFileUpload { [OperationContract] void UploadFile(SendFileMessage message); } Where SendFileMessage is [MessageContract] public class SendFileMessage { [MessageBodyMember(Order = 1)] public Stream FileData; [MessageHeader(MustUnderstand = true)] public FileTransferInfo FileTransferInfo; }

    Read the article

  • How To View and Write To System Log Files on Ubuntu

    - by Chris Hoffman
    Linux logs a large amount of events to the disk, where they’re mostly stored in the /var/log directory in plain text. Most log entries go through the system logging daemon, syslogd, and are written to the system log. Ubuntu includes a number of ways of viewing these logs, either graphically or from the command-line. You can also write your own log messages to the system log — particularly useful in scripts. How to Banish Duplicate Photos with VisiPic How to Make Your Laptop Choose a Wired Connection Instead of Wireless HTG Explains: What Is Two-Factor Authentication and Should I Be Using It?

    Read the article

  • How can I monitor a website for malicious changes to the files

    - by rossmcm
    I had an occasion recently where our website was compromised - a link farm was added to a couple of the pages on one occasion, and on another occasion, a large and nasty aspx file was put on the server. I won't mention the host's name (Hostway), but I was pretty annoyed that someone was able to do this. No, it wasn't a leaky password - around 10 sites hosted by HW with consecutive IP addresses got trashed. Anyway. What I need is a utility or service (preferably free) that takes a snapshot of my websites contents, and then regularly monitors the files (size and datestamp) for unauthorized changes or additions, and alerts me. I've used web services that monitor one file for changes, but I'm looking for something a bit more aggressive.

    Read the article

  • Using a back-end mechanism to copy files to DB and notify the application

    - by BDotA
    This Scenario: User copies large files to a local folder. I want to watch that folder and when a new file is dropped then go and copy it to Database, so later when coping is done I can actually use it in my application. ( A C# WinForms App). It would be awesome to also find a way to somehow get notified in the Application that hey copying the file to DB is finished and ready for use... I am using C#.net, Windows... What solutions/architecture do you suggest for this? For example having a windows service running all the time watching that folder, when something copied goes and write it to DB ... then how about getting notified? MSMQ is something I can use? don't know much about it yet. Thanks.

    Read the article

  • How can I monitor a website for malicious changes to the files

    - by user41421
    I had an occasion recently where our website was compromised - a link farm was added to a couple of the pages on one occasion, and on another occasion, a large and nasty aspx file was put on the server. I won't mention the host's name (Hostway), but I was pretty annoyed that someone was able to do this. No, it wasn't a leaky password - around 10 sites hosted by HW with consecutive IP addresses got trashed. Anyway. What I need is a utility or service (preferably free) that takes a snapshot of my websites contents, and then regularly monitors the files (size and datestamp) for unauthorized changes or additions, and alerts me. I've used web services that monitor one file for changes, but I'm looking for something a bit more aggressive.

    Read the article

  • Sass interface in HTML6 for upload files.

    - by Anirudha
    Originally posted on: http://geekswithblogs.net/anirugu/archive/2013/11/04/sass-interface-in-html6-for-upload-files.aspx[This post is about experiment & imagination] From Windows XP (ever last OS I tried) I have seen a feature that is about send file to pen drive and make shortcut on Desktop. In XP, Win7 (Win8 have this too, not removed) just select the file right click > send to and you can send this file to many places. In my menu it’s show me Skype because I have installed it. this skype confirm that we can add our own app here to make it more easy for user to send file in our app. Nowadays Many people use Cloud or online site to store the file. In case of html5 drag and drop you need to have site opened and have opened that page which is about file upload. You need to select all  and drag and drop. after drag and drop file is simply uploaded to server and site show you on list (if no error happen). but this file upload is seriously not worthy since I have to open the site when I do this operation.   Through this post I want to describe a feature that can make this thing better.  This API is simply called SASS FILE UPLOAD API Through This API when you surf the site and come into file upload page then the page will tell you that we also have SASS FILE API support. Enable it for better result.   How this work This API feature are activated on 2 basis. 1. Feature are disabled by default on site (or you can change it if it’s not) 2. This API allow specific site to upload the files. Files upload may have some rule. For example (minimum or maximum size of file to uploaded, which format the site allowed you to upload). In case of resume site you will be allowed to use .doc (according to code of site)   How browser recognize that Site have SASS service. In HTML source of  the site, the code have a meta tag similar to this <meta name=”sass-upload-api” path=”/upload.json”/> Remember that upload.json is one file that has define the value of many settings {   "cookie_name": "ck_file",   "maximum_allowed_perday": 24,   "allowed_file_extensions","*.png,*.jpg,*.jpeg,*.gif",   "method": [       {           "get": "file/get",           "routing":"/file/get/{fileName}"       },       {           "post": "file/post",           "routing":"/file/post/{fileName}"       },       {           "delete": "file/delete",           "routing":"/file/delete/{fileName}"       },         {           "put": "file/put",           "routing":"/file/put/{fileName}"       },        {           "all": "file/all",           "routing":"/file/all/{fileName}"       }    ] } cookie name is simply a cookie which should be stored in browser and define in json. we define the cookie_name so we can easily share then with service in Windows system. This cookie will be accessible with the service so it’s security based safe. other cookie will not be shared.   The cookie will be post,put, get from this location. The all location will be simply about showing a whole list of file. This will gave a treeview kind of json to show the directories on sever.   for example example.com if you have activated the API with this site then you will seen a send to option in your explorer.exe when you send you will got a windows open which folder you want to use to send the file. The windows will also describe the limit and how much you can upload. This thing never required site to opened. When you upload the file this will be uploaded through FTP protocol. FTP protocol are better for performance.   How this API make thing faster. Suppose you want to ask a question and want to post image. you just do it and get it ready when you open stackoverflow.com now stackoverflow will only tell you which file you want to put on your current question that you asking for. second use is about people use cloud app.   There is no need of drag and drop anymore. we just need to do it without drag and drop it. we doesn’t need to open the site either. This thing is still in experiment level. I will update this post when I got some progress on this API.

    Read the article

  • How large should I make root, home, and swap partitions?

    - by starcorn
    Hello, I have a laptop with win7 installed. I have now made a 60gb partition which I want to install ubuntu into. The question I have, before I do the installation, is how large each of the root, swap, and home partition should be? I have read some place that root could be as small as 8GB, but isn't that too small? Since I guess beside ubuntu all the softwares installed will reside there as well? And I think I'm going to set my swap to be 2GB large. My main concern is how large should the root partition should be. I'm mainly going to use ubuntu for programming and browse the web.

    Read the article

  • How much time do you need in between large projects?

    - by Mattio
    You've launched a large project at work, something that's been in progress and taken up large chunks of your life for more than 6 months. The post-launch triage is over. Tech support isn't calling you every hour because they don't know how to troubleshoot an issue. Your hours drop from 60+/wk to whatever is normal in your organization (which is hopefully less than 60+!). How much time do you (or your team) need before the next large project begins? I was asked this question at work and I think the ideal minimum is two weeks -- one week to clear your desk and inbox + one week to clear your head and remember what it's like to have a life outside of work. I'd frankly acknowledge that just being asked this question is a huge boon to work/life balance. But I do think it's possible to go too long in between.

    Read the article

  • Read XML Files using LINQ to XML and Extension Methods

    - by psheriff
    In previous blog posts I have discussed how to use XML files to store data in your applications. I showed you how to read those XML files from your project and get XML from a WCF service. One of the problems with reading XML files is when elements or attributes are missing. If you try to read that missing data, then a null value is returned. This can cause a problem if you are trying to load that data into an object and a null is read. This blog post will show you how to create extension methods to detect null values and return valid values to load into your object. The XML Data An XML data file called Product.xml is located in the \Xml folder of the Silverlight sample project for this blog post. This XML file contains several rows of product data that will be used in each of the samples for this post. Each row has 4 attributes; namely ProductId, ProductName, IntroductionDate and Price. <Products>  <Product ProductId="1"           ProductName="Haystack Code Generator for .NET"           IntroductionDate="07/01/2010"  Price="799" />  <Product ProductId="2"           ProductName="ASP.Net Jumpstart Samples"           IntroductionDate="05/24/2005"  Price="0" />  ...  ...</Products> The Product Class Just as you create an Entity class to map each column in a table to a property in a class, you should do the same for an XML file too. In this case you will create a Product class with properties for each of the attributes in each element of product data. The following code listing shows the Product class. public class Product : CommonBase{  public const string XmlFile = @"Xml/Product.xml";   private string _ProductName;  private int _ProductId;  private DateTime _IntroductionDate;  private decimal _Price;   public string ProductName  {    get { return _ProductName; }    set {      if (_ProductName != value) {        _ProductName = value;        RaisePropertyChanged("ProductName");      }    }  }   public int ProductId  {    get { return _ProductId; }    set {      if (_ProductId != value) {        _ProductId = value;        RaisePropertyChanged("ProductId");      }    }  }   public DateTime IntroductionDate  {    get { return _IntroductionDate; }    set {      if (_IntroductionDate != value) {        _IntroductionDate = value;        RaisePropertyChanged("IntroductionDate");      }    }  }   public decimal Price  {    get { return _Price; }    set {      if (_Price != value) {        _Price = value;        RaisePropertyChanged("Price");      }    }  }} NOTE: The CommonBase class that the Product class inherits from simply implements the INotifyPropertyChanged event in order to inform your XAML UI of any property changes. You can see this class in the sample you download for this blog post. Reading Data When using LINQ to XML you call the Load method of the XElement class to load the XML file. Once the XML file has been loaded, you write a LINQ query to iterate over the “Product” Descendants in the XML file. The “select” portion of the LINQ query creates a new Product object for each row in the XML file. You retrieve each attribute by passing each attribute name to the Attribute() method and retrieving the data from the “Value” property. The Value property will return a null if there is no data, or will return the string value of the attribute. The Convert class is used to convert the value retrieved into the appropriate data type required by the Product class. private void LoadProducts(){  XElement xElem = null;   try  {    xElem = XElement.Load(Product.XmlFile);     // The following will NOT work if you have missing attributes    var products =         from elem in xElem.Descendants("Product")        orderby elem.Attribute("ProductName").Value        select new Product        {          ProductId = Convert.ToInt32(            elem.Attribute("ProductId").Value),          ProductName = Convert.ToString(            elem.Attribute("ProductName").Value),          IntroductionDate = Convert.ToDateTime(            elem.Attribute("IntroductionDate").Value),          Price = Convert.ToDecimal(elem.Attribute("Price").Value)        };     lstData.DataContext = products;  }  catch (Exception ex)  {    MessageBox.Show(ex.Message);  }} This is where the problem comes in. If you have any missing attributes in any of the rows in the XML file, or if the data in the ProductId or IntroductionDate is not of the appropriate type, then this code will fail! The reason? There is no built-in check to ensure that the correct type of data is contained in the XML file. This is where extension methods can come in real handy. Using Extension Methods Instead of using the Convert class to perform type conversions as you just saw, create a set of extension methods attached to the XAttribute class. These extension methods will perform null-checking and ensure that a valid value is passed back instead of an exception being thrown if there is invalid data in your XML file. private void LoadProducts(){  var xElem = XElement.Load(Product.XmlFile);   var products =       from elem in xElem.Descendants("Product")      orderby elem.Attribute("ProductName").Value      select new Product      {        ProductId = elem.Attribute("ProductId").GetAsInteger(),        ProductName = elem.Attribute("ProductName").GetAsString(),        IntroductionDate =            elem.Attribute("IntroductionDate").GetAsDateTime(),        Price = elem.Attribute("Price").GetAsDecimal()      };   lstData.DataContext = products;} Writing Extension Methods To create an extension method you will create a class with any name you like. In the code listing below is a class named XmlExtensionMethods. This listing just shows a couple of the available methods such as GetAsString and GetAsInteger. These methods are just like any other method you would write except when you pass in the parameter you prefix the type with the keyword “this”. This lets the compiler know that it should add this method to the class specified in the parameter. public static class XmlExtensionMethods{  public static string GetAsString(this XAttribute attr)  {    string ret = string.Empty;     if (attr != null && !string.IsNullOrEmpty(attr.Value))    {      ret = attr.Value;    }     return ret;  }   public static int GetAsInteger(this XAttribute attr)  {    int ret = 0;    int value = 0;     if (attr != null && !string.IsNullOrEmpty(attr.Value))    {      if(int.TryParse(attr.Value, out value))        ret = value;    }     return ret;  }   ...  ...} Each of the methods in the XmlExtensionMethods class should inspect the XAttribute to ensure it is not null and that the value in the attribute is not null. If the value is null, then a default value will be returned such as an empty string or a 0 for a numeric value. Summary Extension methods are a great way to simplify your code and provide protection to ensure problems do not occur when reading data. You will probably want to create more extension methods to handle XElement objects as well for when you use element-based XML. Feel free to extend these extension methods to accept a parameter which would be the default value if a null value is detected, or any other parameters you wish. NOTE: You can download the complete sample code at my website. http://www.pdsa.com/downloads. Choose “Tips & Tricks”, then "Read XML Files using LINQ to XML and Extension Methods" from the drop-down. Good Luck with your Coding,Paul D. Sheriff  

    Read the article

< Previous Page | 68 69 70 71 72 73 74 75 76 77 78 79  | Next Page >