I want to take the new implementation of taking a photo then converting it into a byte[] using the preview version of Xamarin Essentials See below the code I have to take the image then load it. async Task TakePhotoAsync() {     try     {         var photo = await MediaPicker.CapturePhotoAsync();         await LoadPhotoAsync(photo);         Console.WriteLine($&quot;CapturePhotoAsync COMPLETED: {PhotoPath}&quot;);     }     catch (Exception ex)     {         Console.WriteLine($&quot;CapturePhotoAsync THREW: {ex.Message}&quot;);     } }  async Task LoadPhotoAsync(FileResult photo) {     // canceled     if (photo == null)     {         PhotoPath = null;         return;     }     // save the file into local storage     var newFile = Path.Combine(FileSystem.CacheDirectory, photo.FileName);     using (var stream = await photo.OpenReadAsync())     using (var newStream = File.OpenWrite(newFile))         await stream.CopyToAsync(newStream);      PhotoPath = newFile; }  I want to take the image and convert it into a byte[]
12987
What is the prefered method for creating a byte array from an input stream?   Here is my current solution with .NET 3.5.   Stream s; byte[] b;  using (BinaryReader br = new BinaryReader(s)) {     b = br.ReadBytes((int)s.Length); }   Is it still a better idea to read and write chunks of the stream?
16442
I would like to write a small program in C# which goes through my jpeg photos and, for example, sorts them into dated folders (using MY dating conventions, dammit...).   Does anyone know a relatively easy way to get at the EXIF data such as Date And Time or Exposure programatically? Thanks!
13551
UPDATE   I have combined various answers from here into a 'definitive' answer on a .  Original question  In my code I have an event publisher, which exists for the whole lifetime of the application (here reduced to bare essentials):  public class Publisher {     //ValueEventArgs&lt;T&gt; inherits from EventArgs     public event EventHandler&lt;ValueEventArgs&lt;bool&gt;&gt; EnabledChanged;  }   Because this publisher can be used all over the place, I was quite pleased with myself for creating this little helper class to avoid re-writing the handling code in all subscribers:  public static class Linker {     public static void Link(Publisher publisher, Control subscriber)     {          publisher.EnabledChanged += (s, e) =&gt; subscriber.Enabled = e.Value;     }      //(Non-lambda version, if you're not comfortable with lambdas)     public static void Link(Publisher publisher, Control subscriber)     {          publisher.EnabledChanged +=              delegate(object sender, ValueEventArgs&lt;bool&gt; e)              {                   subscriber.Enabled = e.Value;              };     } }   It worked fine, until we started using it on smaller machines, when I started getting the occasional:  System.ComponentModel.Win32Exception Not enough storage is available to process this command   As it turns out, there is one place in the code where subscribers controls are being dynamically created, added and removed from a form. Given my advanced understanding of garbage collection etc (i.e. none, until yesterday), I never thought to clear up behind me, as in the vast majority of cases, the subscribers also live for the lifetime of the application.  I've fiddled around a while with , but it doesn't work with anonymous delegates (not for me anyway).  Is there anyway out of this problem? I really would like to avoid having to copy-paste boiler-plate code all over the shop.  (Oh, and don't bother with asking me WHY we are creating and destroying controls all the time, it wasn't my design decision...)  (PS: It's a winforms application, but we've upgraded to VS2008 and .Net 3.5, should I consider using the ?)  (PPS: Good , but if anyone can come up with an equivalent to the WeakEventHandler which avoids me having to remember to explicitly UnLink/Dispose, that would be cool...)  EDIT I must admit that I worked around this problem by "recycling" the controls in question. However the workaround has come back to haunt me as the 'key' I was using is apparently non-unique (sob). I've just discovered other links  (tried this - seems to be a bit too weak - GC clears delegates even if target is still alive, same problem with  below),  (forces you to modify publisher, and doesn't really work with anonymous delegates) and  (cited-as-incomplete by Dustin Campbell).   It occurs to me that what I'm looking for may be semantically impossible - closures are designed to 'hang around even after I'm gone'.   I've found another workaround, so I'll stick with that, pending a .
35807
I have created a VF page and used "render as pdf"  &lt;apex:commandButton value="Save to Opportunity" action="{!savePdf}"  /&gt;   Its working fine when i am using above line without rerender and oncomplete but when i am adding rerender or oncomplete it is not working.I am able to save the PDF in attachment folder but when i am trying to open its showing  "Unable to load document"  Even if i remove oncomplete and use Rerender then also its saving the attachment in Attachment object and when i view ,it is not loading and says "Unable to load document"      &lt;apex:commandButton value="Save to Opportunity" action="{!savePdf}"  oncomplete="myClose();"/&gt;   Javascript Code  function myClose(){      self.close();     window.opener.location.href="/{!$CurrentPage.parameters.Id}";  }   Class Code  public void savePdf() {      PageReference pdf = Page.GenerateQuotePDF;     pdf.getParameters().put('id',parentId);      Attachment attach = new Attachment();      Blob body;     body = pdf.getContent();     attach.Body = body;     attach.Name = 'Opportunity'+ '.pdf';       attach.IsPrivate = false;     attach.ParentId = parentId;     attach.ContentType = 'application/pdf';     insert attach;     }     Please help..
72820
It's very easy to mark an image file to become an embedded resource however how does one access the image thereafter. Please can I have some example code?
14231
What would be the best way to fill a C# struct from a byte[] array where the data was from a C/C++ struct?  The C struct would look something like this (my C is very rusty):  typedef OldStuff {     CHAR Name[8];     UInt32 User;     CHAR Location[8];     UInt32 TimeStamp;     UInt32 Sequence;     CHAR Tracking[16];     CHAR Filler[12]; }   And would fill something like this:  [StructLayout(LayoutKind.Explicit, Size = 56, Pack = 1)] public struct NewStuff {     [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]     [FieldOffset(0)]     public string Name;      [MarshalAs(UnmanagedType.U4)]     [FieldOffset(8)]     public uint User;      [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]     [FieldOffset(12)]     public string Location;      [MarshalAs(UnmanagedType.U4)]     [FieldOffset(20)]     public uint TimeStamp;      [MarshalAs(UnmanagedType.U4)]     [FieldOffset(24)]     public uint Sequence;      [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]     [FieldOffset(28)]     public string Tracking; }   What is best way to copy OldStuff to NewStuff, if OldStuff was passed as byte[] array?  I'm currently doing something like the following, but it feels kind of clunky.  GCHandle handle; NewStuff MyStuff;  int BufferSize = Marshal.SizeOf(typeof(NewStuff)); byte[] buff = new byte[BufferSize];  Array.Copy(SomeByteArray, 0, buff, 0, BufferSize);  handle = GCHandle.Alloc(buff, GCHandleType.Pinned);  MyStuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff));  handle.Free();   Is there better way to accomplish this?    Would using the BinaryReader class offer any performance gains over pinning the memory and using Marshal.PtrStructure?
78478
Looking through some code I came across the following code  trTuDocPackTypdBd.update(TrTuDocPackTypeDto.class.cast(packDto));   and I'd like to know if casting this way has any advantages over   trTuDocPackTypdBd.update((TrTuDocPackTypeDto)packDto);   I've asked the developer responsible and he said he used it because it was new (which doesn't seem like a particularly good reason to me), but I'm intrigued when I would want to use the method.
101236
Is there some way of saving (basic) non-destructive RAW developing/adjustments that is not limited to a particular app ecosystem (eg Adobe)? Understandably some transformations are proprietary (eg. some cool denoise algorithm, or a spot removal tool) but others are rather generic that I think could easily be standardized (eg. crop, exposure, white balance) and be read by other applications.  At first I thought sidecar xmp files could be useful in that respect, since Camera RAW/Lightroom and darktable save their adjustments inside such files, but seems that adjustments created by Camera RAW/Lightroom can not be previewed/edited by darktable and vice versa.  Any solution that has worked for you?  This question is mostly about creating a futureproof way of storing the original camera data, but also the edit history (adjustments in a non-destructive way)
47330
Is there a tool like  available for Android or Windows systems? I'd like to  turn images into polygones/triangles like shown on the app site.
78323
I have an excel document represented as a byte[] and I'm wanting to send it as an attachment in an email.  I'm having a bit of trouble constructing the attachment.  I can create an Attachment which has the following constructors:  (Stream contentStream, ContentType contentType) (Stream contentStream, string name) (Stream contentStream, string name, string mediaType)   My idea at the moment is to create a MemoryStream from the byte[] and pass it to the method which creates the attachment.  Unfortunately I can't see a way to obtain the intended filename and content type from the MemoryStream and I also can't see how to supply the correct content type. There are options for plain text, Pdf, Rtf etc but none that I can see that immediately jump out at me as the one I should use for an Excel document.   The closest I can find is  which states:      The Octet member designates that the   attachment contains generic binary   data.   However, even if this is the one to use, unless it can be passed as a property of the Stream then my method for sending emails will only be able to send a byte[] as an Excel document...  Is there perhaps some other sort of Stream I could use? Or will I have to create my own type of Stream that has the details I need.  Surely someone out there has done this thing before and surely Microsoft would have thought this through to this level....  Any help would be much appreciated.  Update: Please don't vote for any answers that use the constructors that take the filename as a string. I'm really needing help using the ones that take a Stream...I want to avoid having to write the file to disk, email it, and then immediately delete it. Since there is a method that allows me to do that I'd like to use that one if at all possible.  Solution Update  Conrad managed to find what I was looking for! Thanks heaps man!  I'll just document the suggested solution just in case something happens to the content at the supplied link.  Credit for this solution goes to   static void AttachmentFromStream() {  //create the mail message MailMessage mail = new MailMessage();  //set the addresses mail.From = new MailAddress("me@mycompany.com"); mail.To.Add("you@yourcompany.com");  //set the content mail.Subject = "This is an email"; mail.Body = "this content is in the body";  //Get some binary data byte[] data = GetData();  //save the data to a memory stream MemoryStream ms = new MemoryStream(data);  //create the attachment from a stream. Be sure to name the data  //with a file and  //media type that is respective of the data mail.Attachments.Add( new Attachment( ms, "example.txt", "text/plain" ));  SmtpClient smtp = new SmtpClient("127.0.0.1"); smtp.Send(mail); }   In my case, it just means I'll have to change my method to take the filename and fileformat as strings. I'll try using the Octet one...but failing that I'll just pass in the official MIME type.  All things considered, this is a pretty obvious solution...but I do appreciate the help in solving it...and the good thing is this solution will be documented for future programmers who have the same problem.  Thanks again everyone for you help!
104015
Is there a built in method for waiting for a file to be created in c#?  How about waiting for a file to be completely written?  I've baked my own by repeatedly attempting File.OpenRead() on a file until it succeeds (and failing on a timeout), but spinning on a file doesn't seem like the right thing to do.  I'm guessing there's a baked-in method in .NET to do this, but I can't find it.
93776
I'm trying to write out a  Byte[] array representing a complete file to a file.  The original file from the client is sent via TCP and then received by a server. The received stream is read to a byte array and then sent to be processed by this class.   This is mainly to ensure that the receiving TCPClient is ready for the next stream and separate the receiving end from the processing end.   The FileStream class does not take a byte array as an argument or another Stream object ( which does allow you to write bytes to it).  I'm aiming to get the processing done by a different thread from the original ( the one with the TCPClient).   I don't know how to implement this, what should I try?
29637
I want to implement a paperless filing system and was looking to use WIA with C# for the image acquisition. There are quite a few sample projects on CodeProject, etc. However, after downloading every one of them that I can find, I have run into a problem.  In each and every one of them, the reference to WIALib is broken. When I go to add "Microsoft Windows Image Acquisition" as a reference, the only version available on my development workstation (also the machine that will run this) is 2.0.  Unfortunately, every one of these sample projects appear to have been coded against 1.x. The reference goes in as "WIA" instead of "WIALib". I took a shot, just changing the namespace import, but clearly the API is drastically different.  Is there any information on either implementing v2.0 or on upgrading one of these existing sample projects out there?
80278
I'm trying to get images to display in a WPF ListView styled like a WrapPanel as described in this old ATC Avalon Team article: .    When I try to populate the ListView with a LINQ-to-Entities queried collection of ADO.NET Entity Framework objects I get the following exception:  Exception     Items collection must be empty before   using ItemsSource.   My code&hellip;  Visual Basic  Private Sub Window1_Loaded(...) Handles MyBase.Loaded     ListViewImages.ItemsSource = From g In db.Graphic _                                  Order By g.DateAdded Ascending _                                  Select g End Sub   XAML  &lt;ListView Name="ListViewImages"           SelectionMode="Single"           ItemsSource="{Binding}"&gt;     &lt;local:ImageView /&gt; &lt;/ListView&gt;   I put a breakpoint on that line.  ListViewImages.ItemsSource is Nothing just before the LINQ assignment.
59157
I have a StreamReader object that I initialized with a stream, now I want to save this stream to disk (the stream may be a .gif or .jpg or .pdf).  Existing Code:  StreamReader sr = new StreamReader(myOtherObject.InputStream);    I need to save this to disk (I have the filename). In the future I may want to store this to SQL Server.   I have the encoding type also, which I will need if I store it to SQL Server, correct?
56487
I want image to get download or disply after clicking on link.  Visualforce page :-      &lt;apex:pageBlockTable value="{!DORESAttachmentsWrapperList}" var="AttachVar" border="3px" width="98.5%"&gt;     &lt;apex:column &gt;     &lt;apex:facet name="header"&gt;File&lt;/apex:facet&gt;     &lt;apex:commandLink action="{!DORESupdateHistory1}" styleClass="{!IF(AttachVar.DoresViewingStatus == 'Not Viewed' &amp;&amp; (runningUser.Profile.Name == 'Profile1' || runningUser.Profile.Name =='Profile2'),'actionLink disableLink','actionLink')}"     value="{!AttachVar.attachmentName}" &gt;   &lt;apex:param value="{!AttachVar.attachmentID}" name="DORESupdateHistory1" assignTo="{!DORESSelectedId1}"/&gt;   &lt;/apex:commandLink &gt;   &lt;/apex:column&gt;     Controller - DORESupdateHistory1 will update the timing and name of the person in a table who clicks on the new attached image.     public String DORESSelectedId1{get;set;}         public PageReference DORESupdateHistory1(){            system.debug('--DORESSelectedId1---' + DORESSelectedId1);            List&lt;Profile&gt; Profile= [Select Name from Profile where Id =:UserInfo.getProfileId() LIMIT 1];              list&lt;attachment&gt; relatedPaadAttachment = [select ID,parentID,name from attachment where ID=:DORESSelectedId1 limit 1];            system.debug('--DORESSelectedId1---' + DORESSelectedId1);              List&lt;PAAD_Application_Attachment__c&gt; ClickedAttachList1 = [Select id,Name,Type__c,CreatedDate,Dores_Viewer_Name__c,Dores_Viewed_Time__c,Dores_Viewing_Status__c from PAAD_Application_Attachment__c where id = :relatedPaadAttachment[0].parentID]; //To get the clicked attachment Id    if(ClickedAttachList1[0].Dores_Viewing_Status__c == 'Not Viewed' &amp;&amp; Profile[0].Name == 'Profile1' || Profile[0].Name == 'Profile2'){    ClickedAttachList1[0].Dores_Viewing_Status__c = 'Viewed';    ClickedAttachList1[0].Dores_Viewed_Time__c = system.now();    ClickedAttachList1[0].Dores_Viewer_Name__c = UserInfo.getName();    update ClickedAttachList1;    List&lt;PAAD_Application_Attachment__c&gt; viewedattach1= [SELECT Id,Dores_Viewing_Status__c FROM PAAD_Application_Attachment__c where Dores_Viewing_Status__c != 'Viewed' and PAAD_Applicant__c=:app.ID];   List&lt;PAAD_Application_Attachment__c&gt; attach1 = [SELECT Id FROM PAAD_Application_Attachment__c where PAAD_Applicant__c=:app.ID];     if(viewedattach1.size() == attach1.size()){    List&lt;PAAD_Applicant__c&gt; attachcheck1= [SELECT Id,New_Dores_Attachment_Checker__c FROM PAAD_Applicant__c where ID=:app.ID];                   if(attachcheck1[0].New_Dores_Attachment_Checker__c == 'Y') {                       attachcheck1[0].New_Dores_Attachment_Checker__c = '';                       update attachcheck1;                   }                  }       List&lt;AttachmentWrapper&gt;  dummyWrapperList = new List&lt;AttachmentWrapper&gt;();                for(AttachmentWrapper wrap : DORESAttachmentsWrapperList){                   if(DORESSelectedId1 !=  wrap.attachmentID){                       dummyWrapperList.add(wrap);                   }else{                       dummyWrapperList.add(new AttachmentWrapper(ClickedAttachList1[0].Type__c,ClickedAttachList1[0].Member__c, ClickedAttachList1[0].Description_Final__c, relatedPaadAttachment[0].ID,relatedPaadAttachment[0].name, ClickedAttachList1[0].CreatedDate,'Attached', ClickedAttachList1[0].Dores_Viewed_Time__c, ClickedAttachList1[0].Dores_Viewer_Name__c, ClickedAttachList1[0].Dores_Viewing_Status__c));                     }               }               DORESAttachmentsWrapperList.clear();               DORESAttachmentsWrapperList.addAll(dummyWrapperList);            }              return null;        }
60818
I need to test if a file is a shortcut. I'm still trying to figure out how stuff will be set up, but I might only have it's path, I might only have the actual contents of the file (as a byte[]) or I might have both.  A few complications include that I it could be in a zip file (in this cases the path will be an internal path)