Search Results

Search found 296 results on 12 pages for 'marshal'.

Page 4/12 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Searching for Windows User SID's in C#

    - by Ubiquitous Che
    Context Context first - issues I'm trying to resolve are below. One of our clients has asked as to quote how long it would take for us to improve one of our applications. This application currently provides basic user authentication in the form of username/password combinations. This client would like the ability for their employees to log-in using the details of whatever Windows User account is currently logged in at the time of running the application. It's not a deal-breaker if I tell them know - but the client might be willing to pay the costs of development to add this feature to the application. It's worth looking into. Based on my hunting around, it seems like storing the user login details against Domain\Username will be problematic if those details are changed. But Windows User SID's aren't supposed to change at all. I've got the impression that it would be best to record Windows Users by SID - feel free to relieve me of that if I'm wrong. I've been having a fiddle with some Windows API calls. From within C#, grabbing the current user's SID is easy enough. I can already take any user's SID and process it using LookupAccountSid to get username and domain for display purposes. For the interested, my code for this is at the end of this post. That's just the tip of the iceberg, however. The two issues below are completely outside my experience. Not only do I not know how to implement them - I don't even known how to find out how to implement them, or what the pitfalls are on various systems. Any help getting myself aimed in the right direction would be very much appreciated. Issue 1) Getting hold of the local user at runtime is meaningless if that user hasn't been granted access to the application. We will need to add a new section to our application's 'administrator console' for adding Windows Users (or groups) and assigning within-app permissions against those users. Something like an 'Add Windows User Login' button that will raise a pop-up window that will allow the user to search for available Windows User accounts on the network (not just the local machine) to be added to the list of available application logins. If there's already a component in .NET or Windows that I can shanghai into doing this for me, it would make me a very happy man. Issue 2) I also want to know how to take a given Windows User SID and check it against a given Windows User Group (probably taken from a database). I'm not sure how to get started with this one either, though I expect it to be easier than the issue above. For the Interested [STAThread] static void Main(string[] args) { MessageBox.Show(WindowsUserManager.GetAccountNameFromSID(WindowsIdentity.GetCurrent().User.Value)); MessageBox.Show(WindowsUserManager.GetAccountNameFromSID("S-1-5-21-57989841-842925246-1957994488-1003")); } public static class WindowsUserManager { public static string GetAccountNameFromSID(string SID) { try { StringBuilder name = new StringBuilder(); uint cchName = (uint)name.Capacity; StringBuilder referencedDomainName = new StringBuilder(); uint cchReferencedDomainName = (uint)referencedDomainName.Capacity; WindowsUserManager.SID_NAME_USE sidUse; int err = (int)ESystemError.ERROR_SUCCESS; if (!WindowsUserManager.LookupAccountSid(null, SID, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse)) { err = Marshal.GetLastWin32Error(); if (err == (int)ESystemError.ERROR_INSUFFICIENT_BUFFER) { name.EnsureCapacity((int)cchName); referencedDomainName.EnsureCapacity((int)cchReferencedDomainName); err = WindowsUserManager.LookupAccountSid(null, SID, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse) ? (int)ESystemError.ERROR_SUCCESS : Marshal.GetLastWin32Error(); } } if (err != (int)ESystemError.ERROR_SUCCESS) throw new ApplicationException(String.Format("Could not retrieve acount name from SID. {0}", SystemExceptionManager.GetDescription(err))); return String.Format(@"{0}\{1}", referencedDomainName.ToString(), name.ToString()); } catch (Exception ex) { if (ex is ApplicationException) throw ex; throw new ApplicationException("Could not retrieve acount name from SID", ex); } } private enum SID_NAME_USE { SidTypeUser = 1, SidTypeGroup, SidTypeDomain, SidTypeAlias, SidTypeWellKnownGroup, SidTypeDeletedAccount, SidTypeInvalid, SidTypeUnknown, SidTypeComputer } [DllImport("advapi32.dll", EntryPoint = "GetLengthSid", CharSet = CharSet.Auto)] private static extern int GetLengthSid(IntPtr pSID); [DllImport("advapi32.dll", SetLastError = true)] private static extern bool ConvertStringSidToSid( string StringSid, out IntPtr ptrSid); [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern bool LookupAccountSid( string lpSystemName, [MarshalAs(UnmanagedType.LPArray)] byte[] Sid, StringBuilder lpName, ref uint cchName, StringBuilder ReferencedDomainName, ref uint cchReferencedDomainName, out SID_NAME_USE peUse); private static bool LookupAccountSid( string lpSystemName, string stringSid, StringBuilder lpName, ref uint cchName, StringBuilder ReferencedDomainName, ref uint cchReferencedDomainName, out SID_NAME_USE peUse) { byte[] SID = null; IntPtr SID_ptr = IntPtr.Zero; try { WindowsUserManager.ConvertStringSidToSid(stringSid, out SID_ptr); int err = SID_ptr == IntPtr.Zero ? Marshal.GetLastWin32Error() : (int)ESystemError.ERROR_SUCCESS; if (SID_ptr == IntPtr.Zero || err != (int)ESystemError.ERROR_SUCCESS) throw new ApplicationException(String.Format("'{0}' could not be converted to a SID byte array. {1}", stringSid, SystemExceptionManager.GetDescription(err))); int size = (int)GetLengthSid(SID_ptr); SID = new byte[size]; Marshal.Copy(SID_ptr, SID, 0, size); } catch (Exception ex) { if (ex is ApplicationException) throw ex; throw new ApplicationException(String.Format("'{0}' could not be converted to a SID byte array. {1}.", stringSid, ex.Message), ex); } finally { // Always want to release the SID_ptr (if it exists) to avoid memory leaks. if (SID_ptr != IntPtr.Zero) Marshal.FreeHGlobal(SID_ptr); } return WindowsUserManager.LookupAccountSid(lpSystemName, SID, lpName, ref cchName, ReferencedDomainName, ref cchReferencedDomainName, out peUse); } }

    Read the article

  • In apache cxf, How do i know the soap request message is gzip compressed?

    - by aspirant75
    I'm using Apache CXF to send soap message. in specific case, i have to send a soap message gzip compressed. Using log4j, i printed detailed info. would you let me know how i can know the message is gzip compressed and transfered to server. thanks in advance. Below is my java code for gzip and log info. java code Client cxfClient = ClientProxy.getClient(port); /** Logging Interceptor */ cxfClient.getInInterceptors().add(new GZIPInInterceptor()); cxfClient.getOutInterceptors().add(new GZIPOutInterceptor()); log info 20120814 18:56:15,351 DEBUG Interceptors contributed by bus: [] 20120814 18:56:15,351 DEBUG Interceptors contributed by client: [org.apache.cxf.transport.http.gzip.GZIPOutInterceptor@1682a53] 20120814 18:56:15,351 DEBUG Interceptors contributed by endpoint: [org.apache.cxf.interceptor.MessageSenderInterceptor@1b2d7df, org.apache.cxf.jaxws.interceptors.SwAOutInterceptor@7a9224, org.apache.cxf.jaxws.interceptors.WrapperClassOutInterceptor@110b640, org.apache.cxf.jaxws.interceptors.HolderOutInterceptor@2d59a3] 20120814 18:56:15,351 DEBUG Interceptors contributed by binding: [org.apache.cxf.interceptor.AttachmentOutInterceptor@158015a, org.apache.cxf.interceptor.StaxOutInterceptor@c0c8b5, org.apache.cxf.binding.soap.interceptor.SoapHeaderOutFilterInterceptor@b914b3, org.apache.cxf.interceptor.BareOutInterceptor@fdfc58, org.apache.cxf.binding.soap.interceptor.SoapPreProtocolOutInterceptor@c22a3b, org.apache.cxf.binding.soap.interceptor.SoapOutInterceptor@1629e71] 20120814 18:56:15,351 DEBUG Interceptors contributed by databinding: [] 20120814 18:56:15,357 DEBUG Adding interceptor org.apache.cxf.transport.http.gzip.GZIPOutInterceptor@1682a53 to phase prepare-send 20120814 18:56:15,358 DEBUG Adding interceptor org.apache.cxf.interceptor.MessageSenderInterceptor@1b2d7df to phase prepare-send 20120814 18:56:15,358 DEBUG Adding interceptor org.apache.cxf.jaxws.interceptors.SwAOutInterceptor@7a9224 to phase pre-logical 20120814 18:56:15,358 DEBUG Adding interceptor org.apache.cxf.jaxws.interceptors.WrapperClassOutInterceptor@110b640 to phase pre-logical 20120814 18:56:15,358 DEBUG Adding interceptor org.apache.cxf.jaxws.interceptors.HolderOutInterceptor@2d59a3 to phase pre-logical 20120814 18:56:15,358 DEBUG Adding interceptor org.apache.cxf.interceptor.AttachmentOutInterceptor@158015a to phase pre-stream 20120814 18:56:15,358 DEBUG Adding interceptor org.apache.cxf.interceptor.StaxOutInterceptor@c0c8b5 to phase pre-stream 20120814 18:56:15,358 DEBUG Adding interceptor org.apache.cxf.binding.soap.interceptor.SoapHeaderOutFilterInterceptor@b914b3 to phase pre-logical 20120814 18:56:15,358 DEBUG Adding interceptor org.apache.cxf.interceptor.BareOutInterceptor@fdfc58 to phase marshal 20120814 18:56:15,358 DEBUG Adding interceptor org.apache.cxf.binding.soap.interceptor.SoapPreProtocolOutInterceptor@c22a3b to phase post-logical 20120814 18:56:15,359 DEBUG Adding interceptor org.apache.cxf.binding.soap.interceptor.SoapOutInterceptor@1629e71 to phase write 20120814 18:56:15,360 DEBUG Chain org.apache.cxf.phase.PhaseInterceptorChain@31688f was created. Current flow: pre-logical [HolderOutInterceptor, SwAOutInterceptor, WrapperClassOutInterceptor, SoapHeaderOutFilterInterceptor] post-logical [SoapPreProtocolOutInterceptor] prepare-send [MessageSenderInterceptor, GZIPOutInterceptor] pre-stream [AttachmentOutInterceptor, StaxOutInterceptor] write [SoapOutInterceptor] marshal [BareOutInterceptor] 20120814 18:56:15,361 DEBUG Invoking handleMessage on interceptor org.apache.cxf.jaxws.interceptors.HolderOutInterceptor@2d59a3 20120814 18:56:15,361 DEBUG op: [OperationInfo: {https://asp.cyberbooking.co.kr/TopasApiSvc/services}getAirAvail] 20120814 18:56:15,361 DEBUG op.hasOutput(): true 20120814 18:56:15,361 DEBUG op.getOutput().size(): 2 20120814 18:56:15,361 DEBUG Invoking handleMessage on interceptor org.apache.cxf.jaxws.interceptors.SwAOutInterceptor@7a9224 20120814 18:56:15,364 DEBUG Invoking handleMessage on interceptor org.apache.cxf.jaxws.interceptors.WrapperClassOutInterceptor@110b640 20120814 18:56:15,364 DEBUG Invoking handleMessage on interceptor org.apache.cxf.binding.soap.interceptor.SoapHeaderOutFilterInterceptor@b914b3 20120814 18:56:15,365 DEBUG Invoking handleMessage on interceptor org.apache.cxf.binding.soap.interceptor.SoapPreProtocolOutInterceptor@c22a3b 20120814 18:56:15,365 DEBUG Invoking handleMessage on interceptor org.apache.cxf.interceptor.MessageSenderInterceptor@1b2d7df 20120814 18:56:15,365 DEBUG Adding interceptor org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor@dc9065 to phase prepare-send-ending 20120814 18:56:15,366 DEBUG Chain org.apache.cxf.phase.PhaseInterceptorChain@31688f was modified. Current flow: pre-logical [HolderOutInterceptor, SwAOutInterceptor, WrapperClassOutInterceptor, SoapHeaderOutFilterInterceptor] post-logical [SoapPreProtocolOutInterceptor] prepare-send [MessageSenderInterceptor, GZIPOutInterceptor] pre-stream [AttachmentOutInterceptor, StaxOutInterceptor] write [SoapOutInterceptor] marshal [BareOutInterceptor] prepare-send-ending [MessageSenderEndingInterceptor] 20120814 18:56:15,366 DEBUG Invoking handleMessage on interceptor org.apache.cxf.transport.http.gzip.GZIPOutInterceptor@1682a53 20120814 18:56:15,366 DEBUG Requestor role, so gzip enabled 20120814 18:56:15,366 DEBUG gzip permitted: YES 20120814 18:56:15,367 DEBUG Invoking handleMessage on interceptor org.apache.cxf.interceptor.AttachmentOutInterceptor@158015a 20120814 18:56:15,367 DEBUG Invoking handleMessage on interceptor org.apache.cxf.interceptor.StaxOutInterceptor@c0c8b5 20120814 18:56:15,370 DEBUG Adding interceptor org.apache.cxf.interceptor.StaxOutInterceptor$StaxOutEndingInterceptor@1f488f1 to phase pre-stream-ending 20120814 18:56:15,370 DEBUG Chain org.apache.cxf.phase.PhaseInterceptorChain@31688f was modified. Current flow: pre-logical [HolderOutInterceptor, SwAOutInterceptor, WrapperClassOutInterceptor, SoapHeaderOutFilterInterceptor] post-logical [SoapPreProtocolOutInterceptor] prepare-send [MessageSenderInterceptor, GZIPOutInterceptor] pre-stream [AttachmentOutInterceptor, StaxOutInterceptor] write [SoapOutInterceptor] marshal [BareOutInterceptor] pre-stream-ending [StaxOutEndingInterceptor] prepare-send-ending [MessageSenderEndingInterceptor] 20120814 18:56:15,370 DEBUG Invoking handleMessage on interceptor org.apache.cxf.binding.soap.interceptor.SoapOutInterceptor@1629e71 20120814 18:56:15,383 DEBUG Adding interceptor org.apache.cxf.binding.soap.interceptor.SoapOutInterceptor$SoapOutEndingInterceptor@1ce663c to phase write-ending 20120814 18:56:15,384 DEBUG Chain org.apache.cxf.phase.PhaseInterceptorChain@31688f was modified. Current flow: pre-logical [HolderOutInterceptor, SwAOutInterceptor, WrapperClassOutInterceptor, SoapHeaderOutFilterInterceptor] post-logical [SoapPreProtocolOutInterceptor] prepare-send [MessageSenderInterceptor, GZIPOutInterceptor] pre-stream [AttachmentOutInterceptor, StaxOutInterceptor] write [SoapOutInterceptor] marshal [BareOutInterceptor] write-ending [SoapOutEndingInterceptor] pre-stream-ending [StaxOutEndingInterceptor] prepare-send-ending [MessageSenderEndingInterceptor] 20120814 18:56:15,384 DEBUG Invoking handleMessage on interceptor org.apache.cxf.interceptor.BareOutInterceptor@fdfc58 20120814 18:56:15,387 DEBUG Compressing message. 20120814 18:56:15,388 DEBUG Sending POST Message with Headers to http://test.co.kr:80/###/###/###Conduit :{https://test.co.kr/###/####}###.http-conduit Content-Type: text/xml; charset=UTF-8 20120814 18:56:15,388 DEBUG SOAPAction: "getAirAvail" 20120814 18:56:15,388 DEBUG Accept: */* 20120814 18:56:15,388 DEBUG Accept-Encoding: gzip;q=1.0, identity; q=0.5, *;q=0 20120814 18:56:15,388 DEBUG Content-Encoding: gzip 20120814 18:56:15,388 DEBUG No Trust Decider for Conduit '{https://test.co.kr/###/###}###.http-conduit'. An afirmative Trust Decision is assumed. 20120814 18:56:15,394 DEBUG Invoking handleMessage on interceptor org.apache.cxf.binding.soap.interceptor.SoapOutInterceptor$SoapOutEndingInterceptor@1ce663c 20120814 18:56:15,394 DEBUG Invoking handleMessage on interceptor org.apache.cxf.interceptor.StaxOutInterceptor$StaxOutEndingInterceptor@1f488f1 20120814 18:56:15,394 DEBUG Invoking handleMessage on interceptor org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor@dc9065 20120814 18:56:15,459 DEBUG Response Code: 200 Conduit: {https://test.co.kr/###/###}###.http-conduit 20120814 18:56:15,459 DEBUG Content length: 11034 20120814 18:56:15,459 DEBUG Header fields: null: [HTTP/1.1 200 OK] Content-Language: [ko-KR] Date: [Tue, 14 Aug 2012 09:56:15 GMT] Content-Length: [11034] P3P: [CP='CAO PSA CONi OTR OUR DEM ONL'] Expires: [Thu, 01 Dec 1994 16:00:00 GMT] Keep-Alive: [timeout=10, max=100] Set-Cookie: [WMONID=mL6rq_Irpa_; Expires=Wed, 14 Aug 2013 09:56:15 GMT; Path=/] Connection: [Keep-Alive] Content-Type: [text/xml; charset=utf-8] Server: [IBM_HTTP_Server] Cache-Control: [no-cache="set-cookie, set-cookie2"]

    Read the article

  • Read binary file into a struct C#

    - by Robert Höglund
    I'm trying to read binary data using C#. I have all information about the layout of the data in the files I want to read. I'm able to read the data "chunk by chunk", i.e. getting the first 40 bytes of data converting it to a string, get the next 40 bytes, ... Since there are at least three slighlty different version of the data, I would like to read the data directly into a struct. It just feels so much more right than by reading it "line by line". I have tried the following approach but to no avail:StructType aStruct; int count = Marshal.SizeOf(typeof(StructType)); byte[] readBuffer = new byte[count]; BinaryReader reader = new BinaryReader(stream); readBuffer = reader.ReadBytes(count); GCHandle handle = GCHandle.Alloc(readBuffer, GCHandleType.Pinned); aStruct = (StructType) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(StructType)); handle.Free(); The stream is an opened FileStream from which I have began to read from. I get an AccessViolationException when using Marshal.PtrToStructure. The stream contains more information than I'm trying to read since I'm not interested in data at the end of the file. The struct is defined like:[StructLayout(LayoutKind.Explicit)] struct StructType { [FieldOffset(0)] public string FileDate; [FieldOffset(8)] public string FileTime; [FieldOffset(16)] public int Id1; [FieldOffset(20)] public string Id2; } The examples code is changed from original to make this question shorter. How would I read binary data from a file into a struct?

    Read the article

  • Ruby -- looking for some sort of "Regexp unescape" method

    - by RubyNoobie
    I have a bunch of strings that appear to have been double-escaped -- eg, I have "\\014\"\\000\"\\016smoothing\"\\011mean\"\\022color\"\\011zero@\\016" but I want "\014"\000"\016smoothing"\011mean"\022color"\011zero@\016" Is there a method I can use to unescape them? I imagine that I could make a regex to remove 1 backslash from every consecutive n backslashes, but I don't have a lot of regex experience and it seems there ought to be a "more elegant" way to do it. For example, when I puts MyString it displays the output I'd like, but I don't know how I might capture that into a variable. Thanks! Edited to add context: I have this class that is being used to marshal / restore some stuff, but when I restore some old strings it spits out a type error which I've determined is because they weren't -- for some inexplicable reason -- stored as base64. They instead appear to be 'double-escaped', when I need them to be 'single-escaped' to get restored. require 'base64' class MarshaledStuff < ActiveRecord::Base validates_presence_of :marshaled_obj def contents obj = self.marshaled_obj return Marshal.restore(Base64.decode64(obj)) end def contents=(newcontents) self.marshaled_obj = Base64.encode64(Marshal.dump(newcontents)) end end

    Read the article

  • Excel process not ending in Cluster environment

    - by Vasanth
    When we try to close excel object, it fails to close to cluster environment. The same is working fine in QA and UAT environment. public bool KillExcelProcess() { try { object misValue = System.Reflection.Missing.Value; wbObj.Save(); wbObj.Close(true, misValue, misValue); appC.Workbooks.Close(); appC.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(objSheet); System.Runtime.InteropServices.Marshal.ReleaseComObject(wbObj); System.Runtime.InteropServices.Marshal.ReleaseComObject(appC); wbObj = null; appC = null; } catch (Exception ex) { //throw ex; } finally { System.Threading.Thread.Sleep(5000); GC.Collect(); } return true; Calling function #endregion try { log.Info("CloseExcelService (MeasureSavingsComputeBO) Starts ..."); exConverter.KillExcelProcess(); while (true) { try { File.Delete(strFilename); break; } catch (Exception ex) { } }

    Read the article

  • Java: jaxb Generircs

    - by Mac
    How can I get jaxb to bind to my Vector? I cannot seem to get it to bind a Vector that contains generics as it complains that it cannot recognize my class "shape" or any of its subtypes.. "[javax.xml.bind.JAXBException: class shape.shape nor any of its super class is known to this context.]"? import java.util.Vector; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlAccessorType(XmlAccessType.NONE) @XmlRootElement(name = "XVector") public class XVector<shape> { private Vector<shape> q; public XVector() {} @XmlElement(name = "q") public Vector<shape> getVector() { return q; } public void setVector(Vector<shape> q) { this.q = q; } } I get the following errors: javax.xml.bind.MarshalException - with linked exception: [javax.xml.bind.JAXBException: class shape.Rectangle nor any of its super class is known to this context.] at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:317) at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:243) at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(AbstractMarshallerImpl.java:75) public void saveFile(File filename) { try { FileOutputStream fout = new FileOutputStream(filename); objs.setVector(objVec); JAXBContext context = JAXBContext.newInstance(XVector.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(objs, fout); fout.close(); } catch (JAXBException e) { e.printStackTrace (); } catch (Exception ex) { JOptionPane.showMessageDialog(this, ex.toString(), "Error", JOptionPane.ERROR_MESSAGE); } }

    Read the article

  • Word Automation : Replace do not work after TypeText

    - by wishper
    I need to generate doc (real doc, not docx) files, the "best" way i have found is to use word automation (Word 2010). I have files that I open, and then replace values inside before saving it on a new name. (Ex : I replace "" with "155023"). To do this, I use the Application.Selection.Find. I just had a problem when the new value had more than 255 characters (Thanks Microsofts limitations ...). To avoid this problem, i use TypeText in this case. My problem now is once I use TypeText, the Replace do not work anymore .. And I can't find why. Any idea will be greatly appreciated. My code is in a function, called in a foreach with each values to replace : private void Replace(Application app, string name, string newValue) { Selection selection = app.Selection; Find find = selection.Find; Replacement replacement = find.Replacement; find.ClearFormatting(); find.Text = "<" + name + ">"; // Word limitation : can't replace with more than 255 characters, // use another way to do it if that's the case if (tempNewValue.Length < 255) { replacement.ClearFormatting(); replacement.Text = tempNewValue; find.Execute(Replace: replaceAll); } else { while (find.Execute()) { selection.TypeText(tempNewValue); } } Marshal.ReleaseComObject(replacement); Marshal.ReleaseComObject(find); Marshal.ReleaseComObject(selection); }

    Read the article

  • Replacing/Adding resources (icon) programmatically in c#?

    - by reverendo
    I am trying to replace (or add in the case it doesn't exists) icons from .exe files using c#. So far I got this: string filename = "c:\\test.exe"; IntPtr hResource = BeginUpdateResource(filename, true); if (hResource.ToInt32() == 0) throw new Exception("File Not Found"); byte[] ico = System.IO.File.ReadAllBytes("C:\\icon.ico"); IntPtr unmanagedPointer = Marshal.AllocHGlobal(ico.Length); Marshal.Copy(ico, 0, unmanagedPointer, ico.Length); if (UpdateResource(hResource, "Icon", "1", 1033, unmanagedPointer, Convert.ToUInt32(ico.Length)) != false) { MessageBox.Show("Updated"); EndUpdateResource(hResource, false); } Marshal.FreeHGlobal(unmanagedPointer); "Icon", "1", 1033 <- I got this data by opening test.exe with Resource Hacker. I do get the messagebox "Updated", and if I open the resulting exe in Resource Hacker the resource gets replaced but the icon doesn't appear, its just empty. Also that code wont replace, the type "Icon" in the resource, it will delete everything and add that "Icon" and if I use BeginUpdateResource(path, false); it will not replace it neither but it will add ANOTHER "Icon". Where can I find an example to replace/add the icon using c# disregarding the name the resource use for the icon or if the resource doesn't exist?

    Read the article

  • Why my application ask for a codec to pla the MVI(.MOV) video files while i can play them on WMP and QuickTime?

    - by Daniel Lip
    I have an application i did some time ago when im loading the video file its ok when trying to play/use the file im getting the messageBox message say that its need a codec to use gspot or search the internet. Wehn im playing this files on my hard disk with Windows Media Play or either QuickTime there is no problems. The Video files for example name are: MVI_2483 in the file name properties i see its type: Quick Time Movie (.MOV) In my application im using DirectShowLib-2005.dll this is the class im using in my case to extract the video file im using it in my application to extract only lightnings from the video file name. In Form1 i have a button click event that just starting the action: private void button8_Click(object sender, EventArgs e) { viewToolStripMenuItem.Enabled = false; fileToolStripMenuItem.Enabled = false; button2.Enabled = false; label14.Visible = false; label15.Visible = false; label21.Visible = false; label22.Visible = false; label24.Visible = false; label25.Visible = false; ExtractAutomatic = true; DirectoryInfo info = new DirectoryInfo(_videoFile); string dirName = info.Name; automaticModeDirectory = dirName + "_Automatic"; subDirectoryName = _outputDir + "\\" + automaticModeDirectory; if (secondPass == true) { Start(true); } Start(false); } This is the function start in Form1: private void Start(bool secondpass) { setpicture(-1); if (Directory.Exists(_outputDir) && secondpass == false) { } else { Directory.CreateDirectory(_outputDir); } if (ExtractAutomatic == true) { string subDirectory_Automatic_Name = _outputDir + "\\" + automaticModeDirectory; Directory.CreateDirectory(subDirectory_Automatic_Name); f = new WmvAdapter(_videoFile, Path.Combine(subDirectory_Automatic_Name)); } else { string subDirectory_Manual_Name; if (Directory.Exists(subDirectoryName)) { subDirectory_Manual_Name = subDirectoryName; f = new WmvAdapter(_videoFile, Path.Combine(subDirectory_Manual_Name)); } else { subDirectory_Manual_Name = _outputDir + "\\" + averagesListTextFileDirectory + "_Manual"; Directory.CreateDirectory(subDirectory_Manual_Name); f = new WmvAdapter(_videoFile, Path.Combine(subDirectory_Manual_Name)); } } button1.Enabled = false; f.Secondpass = secondpass; f.FramesToSave = _fts; f.FrameCountAvailable += new WmvAdapter.FrameCountEventHandler(f_FrameCountAvailable); f.StatusChanged += new WmvAdapter.EventHandler(f_StatusChanged); f.ProgressChanged += new WmvAdapter.ProgressEventHandler(f_ProgressChanged); this.Text = "Processing Please Wait..."; label5.ForeColor = Color.Green; label5.Text = "Processing Please Wait"; button8.Enabled = false; button5.Enabled = false; label5.Visible = true; pictureBox1.Image = Lightnings_Extractor.Properties.Resources.Weather_Michmoret; Hrs = 0; //number of hours Min = 0; //number of Minutes Sec = 0; //number of Sec timeElapsed = 0; label10.Text = "00:00:00"; label11.Visible = false; label12.Visible = false; label9.Visible = false; label8.Visible = false; this.button1.Enabled = false; myTrackPanelss1.trackBar1.Enabled = false; this.checkBox2.Enabled = false; this.checkBox1.Enabled = false; numericUpDown1.Enabled = false; timer1.Start(); label2.Text = ""; label1.Visible = true; label2.Visible = true; label3.Visible = true; label4.Visible = true; f.Start(); } And this is the class wich is not my oqn class i just just defined it in some places wich making the problem: using System; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Runtime.InteropServices; using DirectShowLib; using System.Collections.Generic; using Extracting_Frames; using System.Windows.Forms; namespace Polkan.DataSource { internal class WmvAdapter : ISampleGrabberCB, IDisposable { #region Fields_Properties_and_Events bool dis = false; int count = 0; const string fileName = @"d:\histogramValues.dat"; private IFilterGraph2 _filterGraph; private IMediaControl _mediaCtrl; private IMediaEvent _mediaEvent; private int _width; private int _height; private readonly string _outFolder; private int _frameId; //better use a custom EventHandler that passes the results of the action to the subscriber. public delegate void EventHandler(object sender, EventArgs e); public event EventHandler StatusChanged; public delegate void FrameCountEventHandler(object sender, FrameCountEventArgs e); public event FrameCountEventHandler FrameCountAvailable; public delegate void ProgressEventHandler(object sender, ProgressEventArgs e); public event ProgressEventHandler ProgressChanged; private IMediaSeeking _mSeek; private long _duration = 0; private long _avgFrameTime = 0; //just save the averages to a List (not to fs) public List<double> AveragesList { get; set; } public List<long> histogramValuesList; public bool Secondpass { get; set; } public List<int> FramesToSave { get; set; } #endregion #region Constructors and Destructors public WmvAdapter(string file, string outFolder) { _outFolder = outFolder; try { SetupGraph(file); } catch { Dispose(); MessageBox.Show("A codec is required to load this video file. Please use http://www.headbands.com/gspot/ or search the web for the correct codec"); } } ~WmvAdapter() { CloseInterfaces(); } #endregion public void Dispose() { CloseInterfaces(); } public void Start() { EstimateFrameCount(); int hr = _mediaCtrl.Run(); WaitUntilDone(); DsError.ThrowExceptionForHR(hr); } public void WaitUntilDone() { int hr; const int eAbort = unchecked((int)0x80004004); do { System.Windows.Forms.Application.DoEvents(); EventCode evCode; if (dis == true) { return; } hr = _mediaEvent.WaitForCompletion(100, out evCode); }while (hr == eAbort); DsError.ThrowExceptionForHR(hr); OnStatusChanged(); } //Edit: added events protected virtual void OnStatusChanged() { if (StatusChanged != null) StatusChanged(this, new EventArgs()); } protected virtual void OnFrameCountAvailable(long frameCount) { if (FrameCountAvailable != null) FrameCountAvailable(this, new FrameCountEventArgs() { FrameCount = frameCount }); } protected virtual void OnProgressChanged(int frameID) { if (ProgressChanged != null) ProgressChanged(this, new ProgressEventArgs() { FrameID = frameID }); } /// <summary> build the capture graph for grabber. </summary> private void SetupGraph(string file) { ISampleGrabber sampGrabber = null; IBaseFilter capFilter = null; IBaseFilter nullrenderer = null; _filterGraph = (IFilterGraph2)new FilterGraph(); _mediaCtrl = (IMediaControl)_filterGraph; _mediaEvent = (IMediaEvent)_filterGraph; _mSeek = (IMediaSeeking)_filterGraph; var mediaFilt = (IMediaFilter)_filterGraph; try { // Add the video source int hr = _filterGraph.AddSourceFilter(file, "Ds.NET FileFilter", out capFilter); DsError.ThrowExceptionForHR(hr); // Get the SampleGrabber interface sampGrabber = new SampleGrabber() as ISampleGrabber; var baseGrabFlt = sampGrabber as IBaseFilter; ConfigureSampleGrabber(sampGrabber); // Add the frame grabber to the graph hr = _filterGraph.AddFilter(baseGrabFlt, "Ds.NET Grabber"); DsError.ThrowExceptionForHR(hr); // --------------------------------- // Connect the file filter to the sample grabber // Hopefully this will be the video pin, we could check by reading it's mediatype IPin iPinOut = DsFindPin.ByDirection(capFilter, PinDirection.Output, 0); // Get the input pin from the sample grabber IPin iPinIn = DsFindPin.ByDirection(baseGrabFlt, PinDirection.Input, 0); hr = _filterGraph.Connect(iPinOut, iPinIn); DsError.ThrowExceptionForHR(hr); // Add the null renderer to the graph nullrenderer = new NullRenderer() as IBaseFilter; hr = _filterGraph.AddFilter(nullrenderer, "Null renderer"); DsError.ThrowExceptionForHR(hr); // --------------------------------- // Connect the sample grabber to the null renderer iPinOut = DsFindPin.ByDirection(baseGrabFlt, PinDirection.Output, 0); iPinIn = DsFindPin.ByDirection(nullrenderer, PinDirection.Input, 0); hr = _filterGraph.Connect(iPinOut, iPinIn); DsError.ThrowExceptionForHR(hr); // Turn off the clock. This causes the frames to be sent // thru the graph as fast as possible hr = mediaFilt.SetSyncSource(null); DsError.ThrowExceptionForHR(hr); // Read and cache the image sizes SaveSizeInfo(sampGrabber); //Edit: get the duration hr = _mSeek.GetDuration(out _duration); DsError.ThrowExceptionForHR(hr); } finally { if (capFilter != null) { Marshal.ReleaseComObject(capFilter); } if (sampGrabber != null) { Marshal.ReleaseComObject(sampGrabber); } if (nullrenderer != null) { Marshal.ReleaseComObject(nullrenderer); } GC.Collect(); } } private void EstimateFrameCount() { try { //1sec / averageFrameTime double fr = 10000000.0 / _avgFrameTime; double frameCount = fr * (_duration / 10000000.0); OnFrameCountAvailable((long)frameCount); } catch { } } public double framesCounts() { double fr = 10000000.0 / _avgFrameTime; double frameCount = fr * (_duration / 10000000.0); return frameCount; } private void SaveSizeInfo(ISampleGrabber sampGrabber) { // Get the media type from the SampleGrabber var media = new AMMediaType(); int hr = sampGrabber.GetConnectedMediaType(media); DsError.ThrowExceptionForHR(hr); if ((media.formatType != FormatType.VideoInfo) || (media.formatPtr == IntPtr.Zero)) { throw new NotSupportedException("Unknown Grabber Media Format"); } // Grab the size info var videoInfoHeader = (VideoInfoHeader)Marshal.PtrToStructure(media.formatPtr, typeof(VideoInfoHeader)); _width = videoInfoHeader.BmiHeader.Width; _height = videoInfoHeader.BmiHeader.Height; //Edit: get framerate _avgFrameTime = videoInfoHeader.AvgTimePerFrame; DsUtils.FreeAMMediaType(media); GC.Collect(); } private void ConfigureSampleGrabber(ISampleGrabber sampGrabber) { var media = new AMMediaType { majorType = MediaType.Video, subType = MediaSubType.RGB24, formatType = FormatType.VideoInfo }; int hr = sampGrabber.SetMediaType(media); DsError.ThrowExceptionForHR(hr); DsUtils.FreeAMMediaType(media); GC.Collect(); hr = sampGrabber.SetCallback(this, 1); DsError.ThrowExceptionForHR(hr); } private void CloseInterfaces() { try { if (_mediaCtrl != null) { _mediaCtrl.Stop(); _mediaCtrl = null; dis = true; } } catch (Exception ex) { Debug.WriteLine(ex); } if (_filterGraph != null) { Marshal.ReleaseComObject(_filterGraph); _filterGraph = null; } GC.Collect(); } int ISampleGrabberCB.SampleCB(double sampleTime, IMediaSample pSample) { Marshal.ReleaseComObject(pSample); return 0; } int ISampleGrabberCB.BufferCB(double sampleTime, IntPtr pBuffer, int bufferLen) { if (Form1.ExtractAutomatic == true) { using (var bitmap = new Bitmap(_width, _height, _width * 3, PixelFormat.Format24bppRgb, pBuffer)) { if (!this.Secondpass) { long[] HistogramValues = Form1.GetHistogram(bitmap); long t = Form1.GetTopLumAmount(HistogramValues, 1000); Form1.averagesTest.Add(t); } else { //this is the changed part if (_frameId > 0) { if (Form1.averagesTest[_frameId] / 1000.0 - Form1.averagesTest[_frameId - 1] / 1000.0 > 150.0) { count = 6; } if (count > 0) { bitmap.RotateFlip(RotateFlipType.Rotate180FlipX); bitmap.Save(Path.Combine(_outFolder, _frameId.ToString("D6") + ".bmp")); count --; } } } _frameId++; //let only report each 100 frames for performance if (_frameId % 100 == 0) OnProgressChanged(_frameId); } } else { using (var bitmap = new Bitmap(_width, _height, _width * 3, PixelFormat.Format24bppRgb, pBuffer)) { if (!this.Secondpass) { //get avg double average = GetAveragePixelValue(bitmap); if (AveragesList == null) AveragesList = new List<double>(); //save avg AveragesList.Add(average); //***************************\\ // for (int i = 0; i < (int)framesCounts(); i++) // { // get histogram values long[] HistogramValues = Form1.GetHistogram(bitmap); if (histogramValuesList == null) histogramValuesList = new List<long>(256); histogramValuesList.AddRange(HistogramValues); //***************************\\ //} } else { if (FramesToSave != null && FramesToSave.Contains(_frameId)) { bitmap.RotateFlip(RotateFlipType.Rotate180FlipX); bitmap.Save(Path.Combine(_outFolder, _frameId.ToString("D6") + ".bmp")); // get histogram values long[] HistogramValues = Form1.GetHistogram(bitmap); if (histogramValuesList == null) histogramValuesList = new List<long>(256); histogramValuesList.AddRange(HistogramValues); using (BinaryWriter binWriter = new BinaryWriter(File.Open(fileName, FileMode.Create))) { for (int i = 0; i < histogramValuesList.Count; i++) { binWriter.Write(histogramValuesList[(int)i]); } binWriter.Close(); } } } _frameId++; //let only report each 100 frames for performance if (_frameId % 100 == 0) OnProgressChanged(_frameId); } } return 0; } /* int ISampleGrabberCB.SampleCB(double sampleTime, IMediaSample pSample) { Marshal.ReleaseComObject(pSample); return 0; } int ISampleGrabberCB.BufferCB(double sampleTime, IntPtr pBuffer, int bufferLen) { using (var bitmap = new Bitmap(_width, _height, _width * 3, PixelFormat.Format24bppRgb, pBuffer)) { if (!this.Secondpass) { //get avg double average = GetAveragePixelValue(bitmap); if (AveragesList == null) AveragesList = new List<double>(); //save avg AveragesList.Add(average); //***************************\\ // for (int i = 0; i < (int)framesCounts(); i++) // { // get histogram values long[] HistogramValues = Form1.GetHistogram(bitmap); if (histogramValuesList == null) histogramValuesList = new List<long>(256); histogramValuesList.AddRange(HistogramValues); long t = Form1.GetTopLumAmount(HistogramValues, 1000); //***************************\\ Form1.averagesTest.Add(t); // to add this list to a text file or binary file and read the averages from the file when its is Secondpass !!!!! //} } else { if (FramesToSave != null && FramesToSave.Contains(_frameId)) { bitmap.RotateFlip(RotateFlipType.Rotate180FlipX); bitmap.Save(Path.Combine(_outFolder, _frameId.ToString("D6") + ".bmp")); // get histogram values long[] HistogramValues = Form1.GetHistogram(bitmap); if (histogramValuesList == null) histogramValuesList = new List<long>(256); histogramValuesList.AddRange(HistogramValues); using (BinaryWriter binWriter = new BinaryWriter(File.Open(fileName, FileMode.Create))) { for (int i = 0; i < histogramValuesList.Count; i++) { binWriter.Write(histogramValuesList[(int)i]); } binWriter.Close(); } } for (int x = 1; x < Form1.averagesTest.Count; x++) { double fff = Form1.averagesTest[x] / 1000.0 - Form1.averagesTest[x - 1] / 1000.0; if (Form1.averagesTest[x] / 1000.0 - Form1.averagesTest[x - 1] / 1000.0 > 180.0) { bitmap.RotateFlip(RotateFlipType.Rotate180FlipX); bitmap.Save(Path.Combine(_outFolder, _frameId.ToString("D6") + ".bmp")); _frameId++; } } } _frameId++; //let only report each 100 frames for performance if (_frameId % 100 == 0) OnProgressChanged(_frameId); } return 0; }*/ private unsafe double GetAveragePixelValue(Bitmap bmp) { BitmapData bmData = null; try { bmData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); int stride = bmData.Stride; IntPtr scan0 = bmData.Scan0; int w = bmData.Width; int h = bmData.Height; double sum = 0; long pixels = bmp.Width * bmp.Height; byte* p = (byte*)scan0.ToPointer(); for (int y = 0; y < h; y++) { p = (byte*)scan0.ToPointer(); p += y * stride; for (int x = 0; x < w; x++) { double i = ((double)p[0] + p[1] + p[2]) / 3.0; sum += i; p += 3; } //no offset incrementation needed when getting //the pointer at the start of each row } bmp.UnlockBits(bmData); double result = sum / (double)pixels; return result; } catch { try { bmp.UnlockBits(bmData); } catch { } } return -1; } } public class FrameCountEventArgs { public long FrameCount { get; set; } } public class ProgressEventArgs { public int FrameID { get; set; } } } I remember i had this codec problem/s before and i installed the codec/'s that were needed but in this case both quick time and windows media player can play the video files so why the application cant detect and find the codec/'s on my computer ? Gspot say that the codec is AVC1 but again wmp and quicktime play the video files no problems. The video files are from my digital camera !

    Read the article

  • .NET Framework generates strange DCOM error

    - by Anders Oestergaard Jensen
    Hello, I am creating a simple application that enables merging of key-value pairs fields in a Word and/or Excel document. Until this day, the application has worked out just fine. I am using the latest version of .NET Framework 4.0 (since it provides a nice wrapper API for Interop). My sample merging method looks like this: public byte[] ProcessWordDocument(string path, List<KeyValuePair<string, string>> kvs) { logger.InfoFormat("ProcessWordDocument: path = {0}", path); var localWordapp = new Word.Application(); localWordapp.Visible = false; Word.Document doc = null; try { doc = localWordapp.Documents.Open(path, ReadOnly: false); logger.Debug("Executing Find->Replace..."); foreach (Word.Range r in doc.StoryRanges) { foreach (KeyValuePair<string, string> kv in kvs) { r.Find.Execute(Replace: Word.WdReplace.wdReplaceAll, FindText: kv.Key, ReplaceWith: kv.Value, Wrap: Word.WdFindWrap.wdFindContinue); } } logger.Debug("Done! Saving document and cleaning up"); doc.Save(); doc.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(doc); localWordapp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(localWordapp); logger.Debug("Done."); return System.IO.File.ReadAllBytes(path); } catch (Exception ex) { // Logging... // doc.Close(); if (doc != null) { doc.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(doc); } localWordapp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(localWordapp); throw; } } The above C# snippet has worked all fine (compiled and deployed unto a Windows Server 2008 x64) with latest updates installed. But now, suddenly, I get the following strange error: System.Runtime.InteropServices.COMException (0x80080005): Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80080005 Server execution failed (Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE)). at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) at System.Activator.CreateInstance(Type type, Boolean nonPublic) at Meeho.Integration.OfficeHelper.ProcessWordDocument(String path, List`1 kvs) in C:\meeho\src\webservices\Meeho.Integration\OfficeHelper.cs:line 30 at Meeho.IntegrationService.ConvertDocument(Byte[] template, String ext, String[] fields, String[] values) in C:\meeho\src\webservices\MeehoService\IntegrationService.asmx.cs:line 49 -- I googled the COM error, but it returns nothing of particular value. I even gave the right permissions for the COM dll's using mmc -32, where I allocated the Word and Excel documents respectively and set the execution rights to the Administrator. I could not, however, locate the dll's by the exact COM CLSID given above. Very frustrating. Please, please, please help me as the application is currently pulled out of production. Anders EDIT: output from the Windows event log: Faulting application name: WINWORD.EXE, version: 12.0.6514.5000, time stamp: 0x4a89d533 Faulting module name: unknown, version: 0.0.0.0, time stamp: 0x00000000 Exception code: 0xc0000005 Fault offset: 0x00000000 Faulting process id: 0x720 Faulting application start time: 0x01cac571c4f82a7b Faulting application path: C:\Program Files (x86)\Microsoft Office\Office12\WINWORD.EXE Faulting module path: unknown Report Id: 041dd5f9-3165-11df-b96a-0025643cefe6 - 1000 2 100 0x80000000000000 2963 Application meeho3 - WINWORD.EXE 12.0.6514.5000 4a89d533 unknown 0.0.0.0 00000000 c0000005 00000000 720 01cac571c4f82a7b C:\Program Files (x86)\Microsoft Office\Office12\WINWORD.EXE unknown 041dd5f9-3165-11df-b96a-0025643cefe6

    Read the article

  • unsigned char* buffer (FreeType2 Bitmap) to System::Drawing::Bitmap.

    - by Dennis Roche
    Hi, I'm trying to convert a FreeType2 bitmap to a System::Drawing::Bitmap in C++/CLI. FT_Bitmap has a unsigned char* buffer that contains the data to write. I have got somewhat working save it disk as a *.tga, but when saving as *.bmp it renders incorrectly. I believe that the size of byte[] is incorrect and that my data is truncated. Any hints/tips/ideas on what is going on here would be greatly appreciated. Links to articles explaining byte layout and pixel formats etc. would be helpful. Thanks!! C++/CLI code. FT_Bitmap *bitmap = &face->glyph->bitmap; int width = (face->bitmap->metrics.width / 64); int height = (face->bitmap->metrics.height / 64); // must be aligned on a 32 bit boundary or 4 bytes int depth = 8; int stride = ((width * depth + 31) & ~31) >> 3; int bytes = (int)(stride * height); // as *.tga void *buffer = bytes ? malloc(bytes) : NULL; if (buffer) { memset(buffer, 0, bytes); for (int i = 0; i < glyph->rows; ++i) memcpy((char *)buffer + (i * width), glyph->buffer + (i * glyph->pitch), glyph->pitch); WriteTGA("Test.tga", buffer, width, height); } // as *.bmp array<Byte>^ values = gcnew array<Byte>(bytes); Marshal::Copy((IntPtr)glyph->buffer, values, 0, bytes); Bitmap^ systemBitmap = gcnew Bitmap(width, height, PixelFormat::Format24bppRgb); // create bitmap data, lock pixels to be written. BitmapData^ bitmapData = systemBitmap->LockBits(Rectangle(0, 0, width, height), ImageLockMode::WriteOnly, bitmap->PixelFormat); Marshal::Copy(values, 0, bitmapData->Scan0, bytes); systemBitmap->UnlockBits(bitmapData); systemBitmap->Save("Test.bmp"); Reference, FT_Bitmap typedef struct FT_Bitmap_ { int rows; int width; int pitch; unsigned char* buffer; short num_grays; char pixel_mode; char palette_mode; void* palette; } FT_Bitmap; Reference, WriteTGA bool WriteTGA(const char *filename, void *pxl, uint16 width, uint16 height) { FILE *fp = NULL; fopen_s(&fp, filename, "wb"); if (fp) { TGAHeader header; memset(&header, 0, sizeof(TGAHeader)); header.imageType = 3; header.width = width; header.height = height; header.depth = 8; header.descriptor = 0x20; fwrite(&header, sizeof(header), 1, fp); fwrite(pxl, sizeof(uint8) * width * height, 1, fp); fclose(fp); return true; } return false; } Update FT_Bitmap *bitmap = &face->glyph->bitmap; // stride must be aligned on a 32 bit boundary or 4 bytes int depth = 8; int stride = ((width * depth + 31) & ~31) >> 3; int bytes = (int)(stride * height); target = gcnew Bitmap(width, height, PixelFormat::Format8bppIndexed); // create bitmap data, lock pixels to be written. BitmapData^ bitmapData = target->LockBits(Rectangle(0, 0, width, height), ImageLockMode::WriteOnly, target->PixelFormat); array<Byte>^ values = gcnew array<Byte>(bytes); Marshal::Copy((IntPtr)bitmap->buffer, values, 0, bytes); Marshal::Copy(values, 0, bitmapData->Scan0, bytes); target->UnlockBits(bitmapData);

    Read the article

  • Marshalling the value of a char* ANSI string DLL API parameter into a C# string

    - by Brian Biales
    For those who do not mix .NET C# code with legacy DLL's that use char* pointers on a regular basis, the process to convert the strings one way or the other is non-obvious. This is not a comprehensive article on the topic at all, but rather an example of something that took me some time to go find, maybe it will save someone else the time. I am utilizing a third party too that uses a call back function to inform my application of its progress.  This callback includes a pointer that under some circumstances is a pointer to an ANSI character string.  I just need to marshal it into a C# string variable.  Seems pretty simple, yes?  Well, it is, (as are most things, once you know how to do them). The parameter of my callback function is of type IntPtr, which implies it is an integer representation of a pointer.  If I know the pointer is pointing to a simple ANSI string, here is a simple static method to copy it to a C# string: private static string GetStringFromCharStar(IntPtr ptr) {     return System.Runtime.InteropServices.Marshal.PtrToStringAnsi(ptr); } The System.Runtime.InteropServices is where to look any time you are mixing legacy unmanaged code with your .NET application.

    Read the article

  • How to deploy a visual studio custom tool?

    - by Aen Sidhe
    Hello. I have a my own custom tool for Visual Studio 2008 SP1. It consists of 5 assemblies: 3 assemblies with code that used heavily in my other projects, 1 assembly-wrapper above VS2008 SDK and assembly with the tool. If I'd debug my tool from visual studio, using "Run external program" option with command line "C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe" and arguments "/ranu /rootsuffix Exp" all work perfectly. After that I trying to deploy it to my working VS copy, not to experimental hive doing: gacutil /i Asm1.dll for all my assemblies and doing RegAsm Asm1.dll only for assembly with custom tool. Neither of utils prints any error, all work as planned, even registry keys appeared. But my tool don't work even after PC restart. What did I do wrong? Wrapper looks like that: [ComVisible(true)] public abstract class CustomToolBase : IVsSingleFileGenerator, IObjectWithSite { #region IVsSingleFileGenerator Members int IVsSingleFileGenerator.DefaultExtension(out string pbstrDefaultExtension) { pbstrDefaultExtension = ".cs"; return 0; } int IVsSingleFileGenerator.Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace, IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress pGenerateProgress) { GenerationEventArgs gea = new GenerationEventArgs( bstrInputFileContents, wszInputFilePath, wszDefaultNamespace, new ServiceProvider(Site as Microsoft.VisualStudio.OLE.Interop.IServiceProvider) .GetService(typeof(ProjectItem)) as ProjectItem, new GenerationProgressFacade(pGenerateProgress) ); if (OnGenerateCode != null) { OnGenerateCode(this, gea); } byte[] bytes = gea.GetOutputCodeBytes(); int outputLength = bytes.Length; rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength); Marshal.Copy(bytes, 0, rgbOutputFileContents[0], outputLength); pcbOutput = (uint)outputLength; return VSConstants.S_OK; } #endregion #region IObjectWithSite Members void IObjectWithSite.GetSite(ref Guid riid, out IntPtr ppvSite) { IntPtr pUnk = Marshal.GetIUnknownForObject(Site); IntPtr intPointer = IntPtr.Zero; Marshal.QueryInterface(pUnk, ref riid, out intPointer); ppvSite = intPointer; } void IObjectWithSite.SetSite(object pUnkSite) { Site = pUnkSite; } #endregion #region Public Members public object Site { get; private set; } public event EventHandler<GenerationEventArgs> OnGenerateCode; [ComRegisterFunction] public static void Register(Type type) { using (var parent = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\VisualStudio\9.0", true)) foreach (CustomToolRegistrationAttribute ourData in type.GetCustomAttributes(typeof(CustomToolRegistrationAttribute), false)) ourData.Register(x => parent.CreateSubKey(x), (x, name, value) => x.SetValue(name, value)); } [ComUnregisterFunction] public static void Unregister(Type type) { using (var parent = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\VisualStudio\9.0", true)) foreach (CustomToolRegistrationAttribute ourData in type.GetCustomAttributes(typeof(CustomToolRegistrationAttribute), false)) ourData.Unregister(x => parent.DeleteSubKey(x, false)); } #endregion } My tool code: [ComVisible(true)] [Guid("55A6C192-D29F-4e22-84DA-DBAF314ED5C3")] [CustomToolRegistration(ToolName, typeof(TransportGeneratorTool))] [ProvideObject(typeof(TransportGeneratorTool))] public class TransportGeneratorTool : CustomToolBase { private const string ToolName = "TransportGeneratorTool"; public TransportGeneratorTool() { OnGenerateCode += GenerateCode; } private static void GenerateCode(object s, GenerationEventArgs e) { try { var serializer = new XmlSerializer(typeof (Parser.System)); using (var reader = new StringReader(e.InputText)) using (var writer = new StringWriter(e.OutputCode)) { Generator.System = (Parser.System) serializer.Deserialize(reader); Generator.System.Namespace = e.Namespace; Generator.GenerateSource(writer); } } catch (Exception ex) { e.Progress.GenerateError(ex.ToString()); } } } Resulting registry keys: Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\Generators] [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\Generators\{FAE04EC1-301F-11D3-BF4B-00C04F79EFBC}] [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\Generators\{FAE04EC1-301F-11D3-BF4B-00C04F79EFBC}\TransportGeneratorTool] @="TransportGeneratorTool" "CLSID"="{55a6c192-d29f-4e22-84da-dbaf314ed5c3}" "GeneratesDesignTimeSource"=dword:00000001 "GeneratesSharedDesignTimeSource"=dword:00000001

    Read the article

  • How should VertexBuffers be used with Multiple Monitors in DirectX 9

    - by Joshua C
    I am currently using DirectX 9 on a machine with two GPUs and three monitors. I am currently trying to draw a triangle on each monitor using vertexbuffers; A directx helloworld with multiple monitors if you will. I am familiar with some DirectX coding, but new to multiple monitor DirectX coding. I may be going about this the wrong way, so please do correct me if I'm doing something wrong. I have created a Direct3D Device for each enumerated adapter sharing the same Form handle. This allows me to successfully use all three monitors in full-screen mode. For Each Adapter In Direct3D.Adapters Dim PresentParameters As New PresentParameters 'Setup PresentParameters PresentParameters.Windowed = False PresentParameters.DeviceWindowHandle = MainForm.Handle Dim Device as New Device(Direct3D, Adapter.Adapter, DeviceType.Hardware, PresentParameters.DeviceWindowHandle, CreateFlags.HardwareVertexProcessing, PresentParameters) Device.SetRenderState(RenderState.Lighting, False) Devices.Add(Device) Next I can also draw text to each device successfully using a different Font for each Device. When I render a triangle using a different VertexBuffer for each Device, only two monitors display the triangle. One of the two monitors on the same GPU, and the monitor on it's own GPU display properly. VertexBuffer = New VertexBuffer(Device, 4 * Marshal.SizeOf(GetType(ColoredVertex)), Usage.WriteOnly, VertexFormat.None, Pool.Managed) Dim Verts = VertexBuffer.Lock(0, 0, LockFlags.None) Verts.WriteRange({ New ColoredVertex(-.5, -.5, 1, ForeColor), New ColoredVertex(0, .5, 1, ForeColor), New ColoredVertex(.5, -.5, 1, ForeColor) }) VertexBuffer.Unlock() VertexDeclaration = New VertexDeclaration(Device, { New VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0), New VertexElement(0, 12, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0), VertexElement.VertexDeclarationEnd }) Render Code: Device.SetStreamSource(0, VertexBuffer, 0, Marshal.SizeOf(GetType(ColoredVertex))) Device.VertexDeclaration = VertexDeclaration Device.DrawPrimitives(PrimitiveType.TriangleList, 0, 1) I have to assume the fact that they share the same physical card comes into play. Should I use multiple buffers on the same card, and if so, how? Or what is the way I should access the VertexBuffer across Devices? Another thought I had was the non working monitor acts like there are no lights. Is turning off lighting on each device on the same card causing issues somehow?

    Read the article

  • JAXB Web Services: Multiple Object Marshalling

    - by Luke Evans
    I can marshal and unmarshal 1 object with no problems (in netbeans); I need to know how to do this with multiple objects? I can't generate anything but null pointer exceptions when trying to unmarshal 3 objects into an array from XML; so I don't even know if I've marshalled the 3 out correctly. I know the basic idea of declaring the object, then using the jaxbu or jaxbm command, but I'd like to see this working for more than one object. **TLDR: How do I marshal/unmarshal multiple objects of a single class into/out of XML?? THANKS Code I have that marshals one object from XML: try { JAXBContext jc = JAXBContext.newInstance ("myOffers"); Unmarshaller u = jc.createUnmarshaller (); myOffers.Offer flight = (myOffers.Offer) u.unmarshal( new FileInputStream( "offers.xml" )); System.out.println ("Airline is : " + flight.getAirline()); System.out.println ("Origin is : " + flight.getOrigin()); System.out.println ("Destination is : " + flight.getDestination()); System.out.println ("Seats available : " + flight.getSeats()); System.out.println("Proximity to City Centre is : " + flight.getProximity()); System.out.println("Currency : " + flight.fare.getCurrency()); System.out.println("Value : " + flight.fare.getValue()); } catch (JAXBException e) { System.out.println("Error " + e);} ok so the Xml is: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <ns2:offer xmlns:ns2="http://simple.example.com/CInfoXmlDoc"> <Origin>Nottingham</Origin> <Destination>Istanbul</Destination> <Airline>Lufthansa</Airline> <Proximity>10</Proximity> <Seats>260</Seats> <Fare> <Currency>GBP</Currency> <Value>300</Value> </Fare> </ns2:offer> <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <ns2:offer xmlns:ns2="http://simple.example.com/CInfoXmlDoc"> <Origin>Birmingham</Origin> <Destination>Cairo</Destination> <Airline>Monarch</Airline> <Proximity>15</Proximity> <Seats>350</Seats> <Fare> <Currency>GBP</Currency> <Value>300</Value> </Fare> </ns2:offer> public static void main(String[] args) throws FileNotFoundException { int i = 0; int arraySize = 2; myOffers.Offer offer[] = new myOffers.Offer[arraySize]; offer[i] = new myOffers.Offer(); offer[i].fare = new myOffers.Offer.Fare(); offer[i].setAirline("Lufthansa"); offer[i].setOrigin("Nottingham"); offer[i].setDestination("Istanbul"); offer[i].setSeats(260); offer[i].setProximity(10); offer[i].fare.currency = "GBP"; offer[i].fare.value = 300; i++; offer[i] = new myOffers.Offer(); offer[i].fare = new myOffers.Offer.Fare(); offer[i].setAirline("Monarch"); offer[i].setOrigin("Birmingham"); offer[i].setDestination("Cairo"); offer[i].setSeats(350); offer[i].setProximity(15); offer[i].fare.currency = "GBP"; offer[i].fare.value = 300; try { int n = 0; FileOutputStream f = new FileOutputStream("offers.xml"); javax.xml.bind.JAXBContext jaxbCtx = javax.xml.bind.JAXBContext.newInstance(offer[n].getClass().getPackage().getName()); javax.xml.bind.Marshaller marshaller = jaxbCtx.createMarshaller(); marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "UTF-8"); //NOI18N marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); while (n < arraySize) { marshaller.marshal(offer[n], f); n++; } } catch (javax.xml.bind.JAXBException ex) { // XXXTODO Handle exception java.util.logging.Logger.getLogger("global").log(java.util.logging.Level.SEVERE, null, ex); //NOI18N } } Which was generated by my marshal code found here: public static void main(String[] args) throws FileNotFoundException { int i = 0; int arraySize = 2; myOffers.Offer offer[] = new myOffers.Offer[arraySize]; offer[i] = new myOffers.Offer(); offer[i].fare = new myOffers.Offer.Fare(); offer[i].setAirline("Lufthansa"); offer[i].setOrigin("Nottingham"); offer[i].setDestination("Istanbul"); offer[i].setSeats(260); offer[i].setProximity(10); offer[i].fare.currency = "GBP"; offer[i].fare.value = 300; i++; offer[i] = new myOffers.Offer(); offer[i].fare = new myOffers.Offer.Fare(); offer[i].setAirline("Monarch"); offer[i].setOrigin("Birmingham"); offer[i].setDestination("Cairo"); offer[i].setSeats(350); offer[i].setProximity(15); offer[i].fare.currency = "GBP"; offer[i].fare.value = 300; try { int n = 0; FileOutputStream f = new FileOutputStream("offers.xml"); javax.xml.bind.JAXBContext jaxbCtx = javax.xml.bind.JAXBContext.newInstance(offer[n].getClass().getPackage().getName()); javax.xml.bind.Marshaller marshaller = jaxbCtx.createMarshaller(); marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "UTF-8"); //NOI18N marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); while (n < arraySize) { marshaller.marshal(offer[n], f); n++; } } catch (javax.xml.bind.JAXBException ex) { // XXXTODO Handle exception java.util.logging.Logger.getLogger("global").log(java.util.logging.Level.SEVERE, null, ex); //NOI18N } } Apologies, I'm fining this editor quite appalling but thats another matter. Whats wrong with [code][/code] tags...

    Read the article

  • Set Proxy Credential in Web Browser Control

    - by rockacola
    I am working on a legacy code where an application uses AxSHDocVw.AxWebBrowser (NOT System.Windows.Forms.Control) to open up web pages and am extending it to take proxy into considerations. I have following example on http://www.pinvoke.net/default.aspx/wininet/internetsetoption.html to use InternetSetOption() to go through specified proxy and tested that it works. Now the hurdle is I tried everything but failed to pass username and password with following code: //-- Set Proxy Username bool resultF = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY_USERNAME, username, username.Length+1); var errorF = Marshal.GetLastWin32Error(); //-- Set Proxy Password bool resultG = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY_PASSWORD, password, password.Length+1); var errorG = Marshal.GetLastWin32Error(); Both resultF and resultG return true and has no errors but it still working. Any hint on what may be happening here? and what method do I have to debug this? Thanks in advance.

    Read the article

  • Word Spell Check pops up hidden and "freezes" my App

    - by Refracted Paladin
    I am using Word's Spell Check in my in house WinForm app. My clients are all XP machines with Office 2007 and randomly the spell check suggestion box pops up behind the App and makes everything "appear" frozen as you cannot get at it. Suggestions? What do other people do to work around this or stop it altogether? Thanks Below is my code, for reference, though I am doubtful that this has anything to do with my code but I'll take anything. public class SpellCheckers { public string CheckSpelling(string text) { Word.Application app = new Word.Application(); object nullobj = Missing.Value; object template = Missing.Value; object newTemplate = Missing.Value; object documentType = Missing.Value; object visible = false; object optional = Missing.Value; object savechanges = false; app.ShowMe(); Word._Document doc = app.Documents.Add(ref template, ref newTemplate, ref documentType, ref visible); doc.Words.First.InsertBefore(text); Word.ProofreadingErrors errors = doc.SpellingErrors; var ecount = errors.Count; doc.CheckSpelling(ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional); object first = 0; object last = doc.Characters.Count - 1; var results = doc.Range(ref first, ref last).Text; doc.Close(ref savechanges, ref nullobj, ref nullobj); app.Quit(ref savechanges, ref nullobj, ref nullobj); Marshal.ReleaseComObject(doc); Marshal.ReleaseComObject(app); Marshal.ReleaseComObject(errors); return results; } } And I call it from my WinForm app like so -- public static void SpellCheckControl(Control control) { if (IsWord2007Available()) { if (control.HasChildren) { foreach (Control ctrl in control.Controls) { SpellCheckControl(ctrl); } } if (IsValidSpellCheckControl(control)) { if (control.Text != String.Empty) { control.BackColor = Color.FromArgb(180, 215, 195); control.Text = Spelling.CheckSpelling(control.Text); control.Text = control.Text.Replace("\r", "\r\n"); control.ResetBackColor(); } } } }

    Read the article

  • SendMessage vs. WndProc

    - by Poma
    I'm trying to extend TextBox control to add watermarking functionality. The example I've found on CodeProject is using imported SendMessage function. [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)] static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, uint wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam); void SetWatermark() { SendMessage(this.Handle, 0x1501, 0, "Sample"); } I'm wondering why not use protected WndProc instead void SetWatermark() { var m =new Message() { HWnd = this.Handle, Msg = 0x1501, WParam = (IntPtr)0, LParam = Marshal.StringToHGlobalUni("Sample") }; WndProc(ref m); } Both seem to work fine. Almost all examples I've seen on internet use SendMessagefunction. Why is that? Isn't WndProc function designed to replace SendMessage? P.S. I don't know right to convert string to IntPtr and found that Marshal.StringToHGlobalUni works ok. Is it right function to do this?

    Read the article

  • Properly clean up excel interop objects revisited: Wrapper objects

    - by chiccodoro
    Hi all, Excel 2007 Hangs When Closing via .NET How to properly clean up Excel interop objects in C# How to properly clean up interop objects in C# All of these struggle with the problem that C# does not release the Excel COM objects properly after using them. There are mainly two directions of working around this issue: Kill the Excel process when Excel is not used anymore. Take care to assign each COM object used explicitly to a variable and to Marshal.ReleaseComObject all of these. Some have stated that 2 is too tedious and there is always some uncertainty whether you forget to stick to this rule at some places in the code. Still 1 seems dirty and dangerous to me, also I could imagine that in an environment with restricted access killing processes is not allowed. So I've been thinking about solving 2 by creating another proxy object model which mimics the Excel object model (for me, it would suffice to implement the objects I actually need). The principle would look as follows: Each Excel Interop class has its proxy which wraps an object of that class. The proxy releases the COM object in its destructor. The proxy mimics the interface of the Interop class (maybe by inheriting it). Any methods that usually return another COM object return a proxy instead. The other methods simply delegate the implementation to the inner COM object. This is a rough sketch of the code: public class Application : Microsoft.Office.Interop.Excel.Application { private Microsoft.Office.Interop.Excel.Application innerApplication = new Microsoft.Office.Interop.Excel.Application innerApplication(); ~Application() { Marshal.ReleaseCOMObject(innerApplication); } public Workbooks Workbooks { get { return new Workbooks(innerApplication.Workbooks); } } } public class Workbooks { private Microsoft.Office.Interop.Excel.Workbooks innerWorkbooks; Workbooks(Microsoft.Office.Interop.Excel.Workbooks innerWorkbooks) { this.innerWorkbooks = innerWorkbooks; } ~Workbooks() { Marshal.ReleaseCOMObject(innerWorkbooks); } } My questions to you are in particular: Who finds this a bad idea and why? Who finds this a gread idea? If so, why hasn't anybody implemented/published such a model yet? Just due to the effort, or am I missing a killing problem with that idea? Is it impossible/bad/dangerous to do the ReleaseCOMObject in the destructor? (I've only seen proposals to put it in a Dispose() rather than in a destructor - why?) If the approach makes sense, any suggestions to improve it?

    Read the article

  • Fastest way to access VB6 String in C#

    - by Simon Woods
    Hi I am using COMInterop. I have a call in VB6 which returns a string of roughly 13000 chars. If I execute the call in pure VB6 it takes about 800ms to execute. If I execute it via c# and COMInterop it takes about 8 seconds. I'm assuming the delay is caused by marshalling. If I am correct about marshalling, I'd be grateful if someone could suggest the fastest way I can get this into C#. e.g. Would it be better to a) expose it as a byte array b) provide a byref string param into the VB6 layer I would appreciate some sample code as well. I tried the Marshal.PtrToStringAuto(Marshal.ReadIntPtr(myCOMObject.GetString, 0) to no avail Many thx S

    Read the article

  • Still getting duplicate token error after calling DuplicateTokenEx for impersonated token

    - by atconway
    I'm trying to return a Sytem.IntPtr from a service call so that the client can use impersonation to call some code. My imersonation code works properly if not passing the token back from a WCF service. I'm not sure why this is not working. I get the following error: "Invalid token for impersonation - it cannot be duplicated." Here is my code that does work except when I try to pass the token back from a service to a WinForm C# client to then impersonate. [DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx")] public extern static bool DuplicateTokenEx(IntPtr ExistingTokenHandle, uint dwDesiredAccess, ref SECURITY_ATTRIBUTES lpThreadAttributes, int TokenType, int ImpersonationLevel, ref IntPtr DuplicateTokenHandle); private IntPtr tokenHandle = new IntPtr(0); private IntPtr dupeTokenHandle = new IntPtr(0); [StructLayout(LayoutKind.Sequential)] public struct SECURITY_ATTRIBUTES { public int Length; public IntPtr lpSecurityDescriptor; public bool bInheritHandle; } public enum SecurityImpersonationLevel { SecurityAnonymous = 0, SecurityIdentification = 1, SecurityImpersonation = 2, SecurityDelegation = 3 } public enum TokenType { TokenPrimary = 1, TokenImpersonation = 2 } private const int MAXIMUM_ALLOWED = 0x2000000; [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")] public System.IntPtr GetWindowsUserToken(string UserName, string Password, string DomainName) { IntPtr tokenHandle = new IntPtr(0); IntPtr dupTokenHandle = new IntPtr(0); const int LOGON32_PROVIDER_DEFAULT = 0; //This parameter causes LogonUser to create a primary token. const int LOGON32_LOGON_INTERACTIVE = 2; //Initialize the token handle tokenHandle = IntPtr.Zero; //Call LogonUser to obtain a handle to an access token for credentials supplied. bool returnValue = LogonUser(UserName, DomainName, Password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle); //Make sure a token was returned; if no populate the ResultCode and throw an exception: int ResultCode = 0; if (false == returnValue) { ResultCode = Marshal.GetLastWin32Error(); throw new System.ComponentModel.Win32Exception(ResultCode, "API call to LogonUser failed with error code : " + ResultCode); } SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES(); sa.bInheritHandle = true; sa.Length = Marshal.SizeOf(sa); sa.lpSecurityDescriptor = (IntPtr)0; bool dupReturnValue = DuplicateTokenEx(tokenHandle, MAXIMUM_ALLOWED, ref sa, (int)SecurityImpersonationLevel.SecurityDelegation, (int)TokenType.TokenImpersonation, ref dupTokenHandle); int ResultCodeDup = 0; if (false == dupReturnValue) { ResultCodeDup = Marshal.GetLastWin32Error(); throw new System.ComponentModel.Win32Exception(ResultCode, "API call to DuplicateToken failed with error code : " + ResultCode); } //Return the user token return dupTokenHandle; } Any idea if I'm not using the call to DuplicateTokenEx correctly? According to the MSDN documentation I read here I should be able to create a token valid for delegation and use across the context on remote systems. When 'SecurityDelegation' is used, the server process can impersonate the client's security context on remote systems. Thanks!

    Read the article

  • When does the .NET runtime hold a reference count > 1 for COM objects?

    - by Wim Coenen
    Until recently, I believed that the .NET runtime only increases the reference count of COM objects by 1 when creating a runtime-callable wrapper, and that only one such runtime-callable wrapper is created for any given COM object. If I'm not mistaken, the above implies that Marshal.FinalReleaseComObject and Marshal.ReleaseComObject do the same thing in practice. However, today I was writing some tests to verify that COM objects are properly released by my code. I do this by invoking the supposedly released object and checking for the expected InvalidComObjectException. It turns out that there are cases where the exception is thrown after a FinalReleaseComObject, but not after a ReleaseComObject. Does this mean that the .NET 2.0 runtime can hold more than one reference to a COM object? If so, when does it do this?

    Read the article

  • Releasing an OLE IStorage file handle in C#

    - by Bernard Darnton
    I'm trying to embed a PDF file into a Word document using the OLE technique described here: http://blogs.msdn.com/brian_jones/archive/2009/07/21/embedding-any-file-type-like-pdf-in-an-open-xml-file.aspx I've tried to implement to C++ code provided in C# so that the whole project's in one place and am almost there except for one roadblock. When I try to feed the generated OLE object binary data into the Word document I get an IOException. IOException: The process cannot access the file 'C:\Wherever\Whatever.pdf.bin' because it is being used by another process. There is a file handle open the .bin file and I don't know how to get rid of it. I don't know a huge amount about COM - I'm winging it here - and I don't know where the file handle is or how to release it. Here's what my C#-ised code looks like. What am I missing? public void ExportOleFile(string oleOutputFileName, string emfOutputFileName) { OLE32.IStorage storage; var result = OLE32.StgCreateStorageEx( oleOutputFileName, OLE32.STGM.STGM_READWRITE | OLE32.STGM.STGM_SHARE_EXCLUSIVE | OLE32.STGM.STGM_CREATE | OLE32.STGM.STGM_TRANSACTED, OLE32.STGFMT.STGFMT_DOCFILE, 0, IntPtr.Zero, IntPtr.Zero, ref OLE32.IID_IStorage, out storage ); var CLSID_NULL = Guid.Empty; OLE32.IOleObject pOle; result = OLE32.OleCreateFromFile( ref CLSID_NULL, _inputFileName, ref OLE32.IID_IOleObject, OLE32.OLERENDER.OLERENDER_NONE, IntPtr.Zero, null, storage, out pOle ); result = OLE32.OleRun(pOle); IntPtr unknownFromOle = Marshal.GetIUnknownForObject(pOle); IntPtr unknownForDataObj; Marshal.QueryInterface(unknownFromOle, ref OLE32.IID_IDataObject, out unknownForDataObj); var pdo = Marshal.GetObjectForIUnknown(unknownForDataObj) as IDataObject; var fetc = new FORMATETC(); fetc.cfFormat = (short)OLE32.CLIPFORMAT.CF_ENHMETAFILE; fetc.dwAspect = DVASPECT.DVASPECT_CONTENT; fetc.lindex = -1; fetc.ptd = IntPtr.Zero; fetc.tymed = TYMED.TYMED_ENHMF; var stgm = new STGMEDIUM(); stgm.unionmember = IntPtr.Zero; stgm.tymed = TYMED.TYMED_ENHMF; pdo.GetData(ref fetc, out stgm); var hemf = GDI32.CopyEnhMetaFile(stgm.unionmember, emfOutputFileName); storage.Commit((int)OLE32.STGC.STGC_DEFAULT); pOle.Close(0); GDI32.DeleteEnhMetaFile(stgm.unionmember); GDI32.DeleteEnhMetaFile(hemf); }

    Read the article

  • C++/CLI .ToString() returning error

    - by George Johnston
    I am a beginner to C++/CLI as I come from a C# background. I am currently writing a wrapper for some native C++ code. I have the following methods: void AddToBlockList(System::String^ address) { char* cAddress = (char*)(void*)Marshal::StringToHGlobalAnsi(address); _packetFilter->AddToBlockList(cAddress); } void AddToBlockList(IPAddress^ address) { char* cAddress = (char*)(void*)Marshal::StringToHGlobalAnsi(address.ToString()); _packetFilter->AddToBlockList(cAddress); } ...The first method works fine and converts my string into the character array. However, the second function with the IPAddress object as the signiture gives me the following error: error C2228: left of '.ToString' must have class/struct/union ...When I type ? address.ToString() ...in the command window, the IP Address prints. Not sure where I'm going wrong. Any ideas?

    Read the article

  • Problem getting correct parameters for C# P/Invoke call to C++ dll

    - by Jim Jones
    Trying to Interop a functionality from the Outside In API from Oracle. Have the following function: SCCERR EXOpenExport {VTHDOC hDoc, VTDWORD dwOutputId, VTDWORD dwSpecType, VTLPVOID pSpec, VTDWORD dwFlags, VTSYSPARAM dwReserved, VTLPVOID pCallbackFunc, VTSYSPARAM dwCallbackData, VTLPHEXPORT phExport); From the header files I reduced the parameters to: typedef VTSYSPARAM VTHDOC, VTLPHDOC * typedef DWORD_PTR VTSYSPARAM typedef unsigned long DWORD_PTR typedef unsigned long VTDWORD typedef VTVOID* VTLPVOID #define VTVOID void typedef VTHDOC VTHEXPORT, *VTLPEXPORT These are for 32 bit windows Going through the header files, the example programs, and the documentation I found: 1. That pSpec could be a pointer to a buffer or NULL, so I set it to a IntPtr.Zero (documentation). 2. That dwFlags and dwReserved according to the documentation "Must be set by the developer to 0". 3. That pCallbackFunc can be set to NULL if I don't want to handle callbacks. 4. That the last two are based on structs that I wrote C# wrappers for using the [StructLayout(LayoutKind.Sequential)]. Then instatiated an instance and generated the parameters by first creating a IntPtr with Marshal.AllocHGlobal(Marshal.SizeOf(instance)), then getting the address value which is passed as a uint for dwCallbackData and a IntPtr for phExport. The final parameter list is as follows: 1. phDoc as a IntPtr which was loaded with an address by the DAOpenDocument function called before. 2. dwOutputId as uint set to 1535 which represents FI_JPEGFIF 3. dwSpecType as int set to 2 which represents IOTYPE_ANSIPATH 4. pSpec as an IntPtr.Zero where the output will be written 5. dwFlags as uint set to 0 as directed 6. dwReserved as uint set to 0 as directed 7. pCallbackFunc as IntPtr set to NULL as I will handle results 8. dwCallBackDate as uint the address of a buffer for a struct 9. phExport as IntPtr to another struct buffer still get an undefined error from the API. Meaning that the call returns a 961 which is not defined in any of the header files. In the past I have gotten this when my choice of parameter types are incorrect. I started out using Interop Assistant which was helpful in learning how many of the parameter types get translated. It is however limited by how well I am able to glean the correct native type from the header files. For example the hDoc parameter used in the preceding function was defined as a non-filesytem handle, so attempted to use Marshal to create a handle, then used an IntPtr, and finally it turned out to be an int (actually it was &phDoc used here). So is there a more scientific way of doing this, other than trial and error? Jim

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >