/// <summary> /// Returns the buffer contents for a moniker. /// </summary> /// <returns>Buffer contents</returns> protected virtual string GetBufferContents(string fileName, out IVsTextStream srpStream) { Guid CLSID_VsTextBuffer = new Guid("{8E7B96A8-E33D-11d0-A6D5-00C04FB67F6A}"); string bufferContents = ""; srpStream = null; IVsRunningDocumentTable rdt = this.projectMgr.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; if (rdt != null) { IVsHierarchy hier; IVsPersistDocData persistDocData; uint itemid, cookie; bool docInRdt = true; IntPtr docData = IntPtr.Zero; int hr = VSConstants.E_FAIL; try { //Getting a read lock on the document. Must be released later. hr = rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_ReadLock, fileName, out hier, out itemid, out docData, out cookie); if (ErrorHandler.Failed(hr) || docData == IntPtr.Zero) { Guid iid = VSConstants.IID_IUnknown; cookie = 0; docInRdt = false; ILocalRegistry localReg = this.projectMgr.GetService(typeof(SLocalRegistry)) as ILocalRegistry; ErrorHandler.ThrowOnFailure(localReg.CreateInstance(CLSID_VsTextBuffer, null, ref iid, (uint)CLSCTX.CLSCTX_INPROC_SERVER, out docData)); } persistDocData = Marshal.GetObjectForIUnknown(docData) as IVsPersistDocData; } finally { if (docData != IntPtr.Zero) { Marshal.Release(docData); } } //Try to get the Text lines IVsTextLines srpTextLines = persistDocData as IVsTextLines; if (srpTextLines == null) { // Try getting a text buffer provider first IVsTextBufferProvider srpTextBufferProvider = persistDocData as IVsTextBufferProvider; if (srpTextBufferProvider != null) { hr = srpTextBufferProvider.GetTextBuffer(out srpTextLines); } } if (ErrorHandler.Succeeded(hr)) { srpStream = srpTextLines as IVsTextStream; if (srpStream != null) { // QI for IVsBatchUpdate and call FlushPendingUpdates if they support it IVsBatchUpdate srpBatchUpdate = srpStream as IVsBatchUpdate; if (srpBatchUpdate != null) { ErrorHandler.ThrowOnFailure(srpBatchUpdate.FlushPendingUpdates(0)); } int lBufferSize = 0; hr = srpStream.GetSize(out lBufferSize); if (ErrorHandler.Succeeded(hr)) { IntPtr dest = IntPtr.Zero; try { // Note that GetStream returns Unicode to us so we don't need to do any conversions dest = Marshal.AllocCoTaskMem((lBufferSize + 1) * 2); ErrorHandler.ThrowOnFailure(srpStream.GetStream(0, lBufferSize, dest)); //Get the contents bufferContents = Marshal.PtrToStringUni(dest); } finally { if (dest != IntPtr.Zero) { Marshal.FreeCoTaskMem(dest); } } } } } // Unlock the document in the RDT if necessary if (docInRdt && rdt != null) { ErrorHandler.ThrowOnFailure(rdt.UnlockDocument((uint)(_VSRDTFLAGS.RDT_ReadLock | _VSRDTFLAGS.RDT_Unlock_NoSave), cookie)); } if (ErrorHandler.Failed(hr)) { // If this failed then it's probably not a text file. In that case, // we just read the file as a binary bufferContents = File.ReadAllText(fileName); } } return(bufferContents); }
public static IList <PinQueryInfo> EnumeratePins(IBaseFilter filter) { if (filter == null) { throw new ArgumentNullException("filter"); } int hr = 0; var pinsInfo = new List <PinQueryInfo>(); IEnumPins pinsEnum = null; try { hr = filter.EnumPins(out pinsEnum); DsError.ThrowExceptionForHR(hr); if (pinsEnum == null) { throw new InvalidOperationException("pinsEnum is null"); } var pins = new IPin[1]; while (true) { try { int fetched = 0; IntPtr pcFetched = Marshal.AllocCoTaskMem(4); try { hr = pinsEnum.Next(pins.Length, pins, pcFetched); DsError.ThrowExceptionForHR(hr); fetched = Marshal.ReadInt32(pcFetched); } finally { Marshal.FreeCoTaskMem(pcFetched); } if (fetched == 1) { // we have something IPin pin = pins[0]; string queryId; hr = pin.QueryId(out queryId); DsError.ThrowExceptionForHR(hr); PinInfo pinInfo; hr = pin.QueryPinInfo(out pinInfo); DsError.ThrowExceptionForHR(hr); pinsInfo.Add(new PinQueryInfo(pinInfo.dir, pinInfo.name, queryId)); } else { break; } } finally { if (pins[0] != null) { Marshal.ReleaseComObject(pins[0]); } pins[0] = null; } } } finally { if (pinsEnum != null) { Marshal.ReleaseComObject(pinsEnum); } } return(pinsInfo); }
public static IPin FindPinForMajorType(IBaseFilter filter, PinDirection direction, Guid majorType) { if (filter == null) { throw new ArgumentNullException("filter"); } int hr = 0; IEnumPins pinsEnum = null; try { hr = filter.EnumPins(out pinsEnum); DsError.ThrowExceptionForHR(hr); var pins = new IPin[1]; int numberFetched = 1; while (numberFetched > 0) { IntPtr pcFetched = Marshal.AllocCoTaskMem(4); try { hr = pinsEnum.Next(1, pins, pcFetched); DsError.ThrowExceptionForHR(hr); numberFetched = Marshal.ReadInt32(pcFetched); } finally { Marshal.FreeCoTaskMem(pcFetched); } if (numberFetched > 0) { PinDirection currentPinDirection; hr = pins[0].QueryDirection(out currentPinDirection); DsError.ThrowExceptionForHR(hr); if (currentPinDirection != direction) { continue; } IEnumMediaTypes mediaTypesEnum = null; try { var mediaTypes = new AMMediaType[1]; pins[0].EnumMediaTypes(out mediaTypesEnum); int numberFetched2 = 1; while (numberFetched2 > 0) { IntPtr fetched2 = IntPtr.Zero; try { hr = mediaTypesEnum.Next(1, mediaTypes, fetched2); DsError.ThrowExceptionForHR(hr); numberFetched2 = Marshal.ReadInt32(fetched2); } finally { Marshal.FreeCoTaskMem(fetched2); } if (numberFetched2 > 0) { if (mediaTypes[0].majorType == majorType) { // success, return the pin return(pins[0]); } } Marshal.ReleaseComObject(pins[0]); } } finally { if (mediaTypesEnum != null) { Marshal.ReleaseComObject(mediaTypesEnum); } } } } } finally { if (pinsEnum != null) { Marshal.ReleaseComObject(pinsEnum); } } return(null); }
SetOleProperty( Guid fmtid, uint propId, object propVal ) { CheckDisposed(); IPropertyStorage ps = fmtid == FormatId.SummaryInformation ? _psSummInfo : _psDocSummInfo; if (ps == null) { // // The property set does not exist, so create it. // if (propVal != null) { _pss.Create( ref fmtid, ref fmtid, SafeNativeCompoundFileConstants.PROPSETFLAG_ANSI, (uint)_grfMode, out ps ); if (fmtid == FormatId.SummaryInformation) { _psSummInfo = ps; } else { _psDocSummInfo = ps; } } else { // // But if we were going to delete the property anyway, there's // nothing to do. // return; } } PROPSPEC[] propSpecs = new PROPSPEC[1]; PROPVARIANT[] vals = new PROPVARIANT[1]; propSpecs[0].propType = (uint)PropSpecType.Id; propSpecs[0].union.propId = propId; if (propVal == null) { // // New value is null => remove the property. Unlike in the case of ReadMultiple, // we can just let this one throw an exception on failure. There are no non-zero // success codes to worry about. // ps.DeleteMultiple(1, propSpecs); return; } // // New value is non-null => set a new value for the property. // IntPtr pszVal = IntPtr.Zero; try { if (propVal is string) { // // 1) We store string properties internally as UTF-16. // During save, convert the string (UTF-16) to CP_ACP and back // 2) If property value changed during that process, store it in CF OLE Storage as UTF-8 // 3) Otherwise store it as CP_ACP // string inputString = propVal as string; pszVal = Marshal.StringToCoTaskMemAnsi(inputString); string convertedString = Marshal.PtrToStringAnsi(pszVal); if (String.CompareOrdinal(inputString, convertedString) != 0) { // The string is not an ASCII string. Use UTF-8 to encode it! byte[] byteArray = UTF8Encoding.UTF8.GetBytes(inputString); int nLen = byteArray.Length; // // Before memory allocation for holding UTF-8 codes, we need to first free the memory // allocated by Marshal.StringToCoTaskMemAnsi(). // Note that if there is any exception in this try scope, the memory will still be released // by the finally of this try scope. // if (pszVal != IntPtr.Zero) { Marshal.FreeCoTaskMem(pszVal); pszVal = IntPtr.Zero; } pszVal = Marshal.AllocCoTaskMem(checked (nLen + 1)); //The extra one byte is for the string terminator null. Marshal.Copy(byteArray, 0, pszVal, nLen); Marshal.WriteByte(pszVal, nLen, 0); //Put the string terminator null at the end of the array. } vals[0].vt = VARTYPE.VT_LPSTR; vals[0].union.pszVal = pszVal; } else if (propVal is DateTime) { // set FileTime as an Int64 to avoid pointer operations vals[0].vt = VARTYPE.VT_FILETIME; vals[0].union.hVal = ((DateTime)propVal).ToFileTime(); } else { throw new ArgumentException( SR.Get(SRID.InvalidDocumentPropertyType, propVal.GetType().ToString()), "propVal"); } // // Again, we can just let it throw on failure; no non-zero success codes. It won't throw // if the property doesn't exist. // ps.WriteMultiple(1, propSpecs, vals, 0); } finally { if (pszVal != IntPtr.Zero) { Marshal.FreeCoTaskMem(pszVal); } } }
protected override IntPtr HookProc(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lparam) { if (msg == NativeMethods.WM_NOTIFY) { dialogHWnd = UnsafeNativeMethods.GetParent(new HandleRef(null, hWnd)); try { UnsafeNativeMethods.OFNOTIFY notify = (UnsafeNativeMethods.OFNOTIFY)UnsafeNativeMethods.PtrToStructure(lparam, typeof(UnsafeNativeMethods.OFNOTIFY)); switch (notify.hdr_code) { case -601: /* CDN_INITDONE */ MoveToScreenCenter(dialogHWnd); break; case -602: /* CDN_SELCHANGE */ NativeMethods.OPENFILENAME_I ofn = (NativeMethods.OPENFILENAME_I)UnsafeNativeMethods.PtrToStructure(notify.lpOFN, typeof(NativeMethods.OPENFILENAME_I)); // Get the buffer size required to store the selected file names. int sizeNeeded = (int)UnsafeNativeMethods.SendMessage(new HandleRef(this, dialogHWnd), 1124 /*CDM_GETSPEC*/, System.IntPtr.Zero, System.IntPtr.Zero); if (sizeNeeded > ofn.nMaxFile) { // A bigger buffer is required. try { int newBufferSize = sizeNeeded + (FILEBUFSIZE / 4); // Allocate new buffer CharBuffer charBufferTmp = CharBuffer.CreateBuffer(newBufferSize); IntPtr newBuffer = charBufferTmp.AllocCoTaskMem(); // Free old buffer Marshal.FreeCoTaskMem(ofn.lpstrFile); // Substitute buffer ofn.lpstrFile = newBuffer; ofn.nMaxFile = newBufferSize; this.charBuffer = charBufferTmp; Marshal.StructureToPtr(ofn, notify.lpOFN, true); Marshal.StructureToPtr(notify, lparam, true); } catch { // intentionaly not throwing here. } } this.ignoreSecondFileOkNotification = false; break; case -604: /* CDN_SHAREVIOLATION */ // When the selected file is locked for writing, // we get this notification followed by *two* CDN_FILEOK notifications. this.ignoreSecondFileOkNotification = true; // We want to ignore the second CDN_FILEOK this.okNotificationCount = 0; // to avoid a second prompt by PromptFileOverwrite. break; case -606: /* CDN_FILEOK */ if (this.ignoreSecondFileOkNotification) { // We got a CDN_SHAREVIOLATION notification and want to ignore the second CDN_FILEOK notification if (this.okNotificationCount == 0) { this.okNotificationCount = 1; // This one is the first and is all right. } else { // This is the second CDN_FILEOK, so we want to ignore it. this.ignoreSecondFileOkNotification = false; UnsafeNativeMethods.SetWindowLong(new HandleRef(null, hWnd), 0, new HandleRef(null, NativeMethods.InvalidIntPtr)); return(NativeMethods.InvalidIntPtr); } } if (!DoFileOk(notify.lpOFN)) { UnsafeNativeMethods.SetWindowLong(new HandleRef(null, hWnd), 0, new HandleRef(null, NativeMethods.InvalidIntPtr)); return(NativeMethods.InvalidIntPtr); } break; } } catch { if (dialogHWnd != IntPtr.Zero) { UnsafeNativeMethods.EndDialog(new HandleRef(this, dialogHWnd), IntPtr.Zero); } throw; } } return(IntPtr.Zero); }
public static void Print(DataAccess DB) { CultureInfo cultures = CultureInfo.CreateSpecificCulture("ko-KR"); string date = DateTime.Now.ToString(string.Format("yyyy년 MM월 dd일 ddd요일", cultures)); string time; if (DB.SelectTime == "day") { time = "24시간"; } else { time = DB.SelectTime + "시간"; } string charge = String.Format("{0:#,0}", Convert.ToInt32(DB.SelectCharge)); string supply = String.Format("{0:#,0}", (Convert.ToInt32(DB.SelectCharge) * 0.1)); string vat = String.Format("{0:#,0}", (Convert.ToInt32(DB.SelectCharge) * 0.9)); string szString = "SAM4S(C)" + "\n\n"; szString += "777-77-77777 BONG\n"; szString += DB.BrachAddress + "\n"; szString += "Tel : 010-4261-4444\n"; szString += date + " No." + DB.BranchId + DateTime.Now.ToString(string.Format("yyyyMMdd", cultures)) + "\n\n"; szString += "신문화를 창조하는 Book & Cup \n"; szString += "항상 최고로 모시겠습니다.\n\n"; szString += "------------------------------------------\n"; szString += "상 품 금 액\n"; szString += "------------------------------------------\n"; szString += "독서실 이용(" + time + ") " + charge + "원\n"; szString += "면세 공급가 0원\n"; szString += "과세 공급가 " + supply + "원\n"; szString += "부가 가치세 " + vat + "원\n\n"; szString += "------------------------------------------\n"; szString += "SAM4S 보너스 카드\n\n"; szString += "3개월 " + charge + "원\n"; szString += "카드:3333-55**-*666-111 ****/**\n"; szString += "승인:55994411 청구금액: " + charge + "원\n"; szString += "승인 시간: 170411063003\n\n"; szString += "총 품목수 : 1 총 구매수량 : 1\n\n"; szString += "본 영수증은 스터디카페 입장시 필요합니다.\n"; szString += "잘 보관하시기 바랍니다. 감사합니다."; szString += " \n"; szString += " \n"; string szPrinterName = Program.printerName; string code = DB.PhoneNumber; IntPtr pBytes; Int32 dwCount; // How many characters are in the string? dwCount = szString.Length; // Assume that the printer is expecting ANSI text, and then convert // the string to ANSI text. pBytes = Marshal.StringToCoTaskMemAnsi(szString); // Send the converted ANSI string to the printer. SendBytesToPrinter(szPrinterName, pBytes, dwCount); Marshal.FreeCoTaskMem(pBytes); string testStr = code; byte[] tempByte = Encoding.Default.GetBytes(testStr); Byte[] bytes = new Byte[tempByte.Length + 7]; bool bSuccess = false; // Your unmanaged pointer. IntPtr pUnmanagedBytes = new IntPtr(0); int nLength; nLength = bytes.Length; // Set Barcode Height bytes[0] = 29; bytes[1] = 104; bytes[2] = 90; // Print Barcode bytes[3] = 29; bytes[4] = 107; // Barcode Type : Code128 bytes[5] = 73; bytes[6] = (byte)tempByte.Length; for (int i = 0; i < tempByte.Length; i++) { bytes[7 + i] = tempByte[i]; } // Allocate some unmanaged memory for those bytes. pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength); // Copy the managed byte array into the unmanaged array. Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength); // Send the unmanaged bytes to the printer. bSuccess = SendBytesToPrinter(Program.printerName, pUnmanagedBytes, nLength); // Free the unmanaged memory that you allocated earlier. Marshal.FreeCoTaskMem(pUnmanagedBytes); }
/// <summary> /// Initializes XPCOM using the specified directory. /// </summary> /// <param name="binDirectory">The directory which contains xul.dll.</param> public static void Initialize(string binDirectory) { if (_IsInitialized) { return; } Debug.WriteLineIf(Thread.CurrentThread.GetApartmentState() != ApartmentState.STA, "Warning: Main Entry point missing [STAThread] attribute."); Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.STA, "Main Entry point missing [STAThread] attribute."); if (BeforeInitalization != null) { BeforeInitalization(); } Interlocked.Exchange(ref _XpcomThreadId, Thread.CurrentThread.ManagedThreadId); if (IsWindows) { Kernel32.SetDllDirectory(binDirectory); } string folder = binDirectory ?? Environment.CurrentDirectory; string xpcomPath = Path.Combine(folder, IsLinux ? "libxul.so" : "xul.dll"); try { // works on windows // but some classes can be not exist on mono (may be) // so make it in another function(stack allocation is making on function start) ReadXulrunnerVersion(xpcomPath); } catch (Exception) { } if (binDirectory != null) { Environment.SetEnvironmentVariable("PATH", string.Format("{0}{1}{2}", Environment.GetEnvironmentVariable("PATH"), Path.PathSeparator, binDirectory), EnvironmentVariableTarget.Process); } object mreAppDir = null; if (binDirectory != null) { using (nsAString str = new nsAString(Path.GetFullPath(binDirectory))) if (NS_NewLocalFile(str, true, out mreAppDir) != 0) { throw new Exception("Failed on NS_NewLocalFile"); } } // temporarily change the current directory so NS_InitEmbedding can find all the DLLs it needs String oldCurrent = Environment.CurrentDirectory; Environment.CurrentDirectory = folder; NS_ProfileInit(); var ptr = Marshal.AllocCoTaskMem(IntPtr.Size); Marshal.WriteIntPtr(ptr, IntPtr.Zero); XRE_GetBootstrap(ptr); Marshal.FreeCoTaskMem(ptr); nsIServiceManager serviceManager; //int res = NS_InitXPCOM2(out serviceManagerPtr, mreAppDir, new DirectoryServiceProvider()); //Note: the error box that this can generate can't be prevented with try/catch, and res is 0 even if it fails //REVIEW: how else can we determine what happened and give a more useful answer, to help new GeckoFX users, //Telling them that probably the version of firefox or xulrunner didn't match this library version? // calling NS_InitXPCOM2 invokes AddRef to the returned nsIServerManager, but as this gets assigned to the __ComObject serviceManager // Release will be called by the when the GC runs __ComObject finaliser. int res = NS_InitXPCOM2(out serviceManager, mreAppDir, null); // change back Environment.CurrentDirectory = oldCurrent; if (res != 0) { throw new Exception("Failed on NS_InitXPCOM2"); } ServiceManager = (nsIServiceManager)serviceManager; // get some global objects we will need later NS_GetComponentManager(out ComponentManager); NS_GetComponentRegistrar(out ComponentRegistrar); if (IsMono) { _comGC = new COMGC(); } // RegisterProvider is necessary to get link styles etc. nsIDirectoryService directoryService = GetService <nsIDirectoryService>("@mozilla.org/file/directory_service;1"); if (directoryService != null) { directoryService.RegisterProvider(new DirectoryServiceProvider()); } _IsInitialized = true; // On Linux calling CreateWindowlessBrowser too early crashes with passing null to gdk_window_enable_synchronized_configure() // the gdkwidgets window is null. if (!Xpcom.IsLinux) { InitChromeContext(); } XULAppInfoFactory.Init(); OnProfileStartup(); PromptFactoryFactory.Init(); if (AfterInitalization != null) { AfterInitalization(); } if (Xpcom.IsLinux) { // Firefox enable offmainthreadcomposition on Linux around May 2015. // (see https://mozillagfx.wordpress.com/2015/05/19/off-main-thread-compositing-on-linux/ ) // However with geckofx on Linux we end up with two Compositors. // So we end up with a ClientLayerManager with an uninitalzied mTransactionIdAllocator // which causes segfault on Paint. GeckoPreferences.User["layers.offmainthreadcomposition.force-disabled"] = true; } // speclative content security pollicy crashes geckofx 60, // because principal->EnsurePreloadCSP(domDoc, getter_AddRefs(preloadCsp)); // returns null preloadCsp // which isn't checked for. // So we just disable CSP for now. GeckoPreferences.User["security.csp.enable"] = false; }
public static T[] AsArray <T>(this IntPtr ptr, int length, bool freePtr = true) { T[] ret = null; if (typeof(T) == typeof(byte)) { byte[] _array = new byte[length]; Marshal.Copy(ptr, _array, 0, length); ret = _array as T[]; } else if (typeof(T) == typeof(uint)) { int[] _array = new int[length]; Marshal.Copy(ptr, _array, 0, length); ret = Array.ConvertAll(_array, Convert.ToUInt32) as T[]; } else if (typeof(T) == typeof(int)) { int[] _array = new int[length]; Marshal.Copy(ptr, _array, 0, length); ret = _array as T[]; } else if (typeof(T) == typeof(long)) { long[] _array = new long[length]; Marshal.Copy(ptr, _array, 0, length); ret = _array as T[]; } else if (typeof(T) == typeof(ulong)) { long[] _array = new long[length]; Marshal.Copy(ptr, _array, 0, length); ret = Array.ConvertAll(_array, Convert.ToUInt64) as T[]; } else if (typeof(T) == typeof(float)) { float[] _array = new float[length]; Marshal.Copy(ptr, _array, 0, length); ret = _array as T[]; } else if (typeof(T) == typeof(double)) { double[] _array = new double[length]; Marshal.Copy(ptr, _array, 0, length); ret = _array as T[]; } else if (typeof(T) == typeof(bool)) { int[] _array = new int[length]; Marshal.Copy(ptr, _array, 0, length); ret = Array.ConvertAll(_array, Convert.ToBoolean) as T[]; } else if (typeof(T) == typeof(IntPtr)) { IntPtr[] _array = new IntPtr[length]; Marshal.Copy(ptr, _array, 0, length); ret = _array as T[]; } else if (typeof(T) == typeof(string)) { IntPtr[] _array = ptr.AsArray <IntPtr>(length, false); Converter <IntPtr, string> converter = freePtr ? new Converter <IntPtr, string>(AsAnsiStringWithFreeMem) : new Converter <IntPtr, string>(AsAnsiStringWithoutFreeMem); ret = Array.ConvertAll(_array, converter) as T[]; } else { ret = new T[length]; IntPtr iterator = ptr; int size = Marshal.SizeOf(typeof(T)); for (int i = 0; i < ret.Length; i++) { ret[i] = (T)Marshal.PtrToStructure(iterator, typeof(T)); iterator = IntPtr.Add(iterator, size); } } if (freePtr) { Marshal.FreeCoTaskMem(ptr); } return(ret); }
public static Encoding[] DetectOutgoingEncodings(string input, int[] preferedEncodings, bool preserveOrder) { if (input == null) { throw new ArgumentNullException("input"); } // empty strings can always be encoded as ASCII if (input.Length == 0) { return new Encoding[] { Encoding.ASCII } } ; List <Encoding> result = new List <Encoding>(); // get the IMultiLanguage3 interface MultiLanguage.IMultiLanguage3 multilang3 = new MultiLanguage.CMultiLanguageClass(); if (multilang3 == null) { throw new System.Runtime.InteropServices.COMException("Failed to get IMultilang3"); } try { int[] resultCodePages = new int[preferedEncodings.Length]; uint detectedCodepages = (uint)resultCodePages.Length; ushort specialChar = (ushort)'?'; // get unmanaged arrays IntPtr pPrefEncs = Marshal.AllocCoTaskMem(sizeof(uint) * preferedEncodings.Length); IntPtr pDetectedEncs = preferedEncodings == null ? IntPtr.Zero : Marshal.AllocCoTaskMem(sizeof(uint) * resultCodePages.Length); try { if (preferedEncodings != null) { Marshal.Copy(preferedEncodings, 0, pPrefEncs, preferedEncodings.Length); } Marshal.Copy(resultCodePages, 0, pDetectedEncs, resultCodePages.Length); MultiLanguage.MLCPF options = MultiLanguage.MLCPF.MLDETECTF_VALID_NLS | MultiLanguage.MLCPF.MLDETECTF_PREFERRED_ONLY; if (preserveOrder) { options |= MultiLanguage.MLCPF.MLDETECTF_PRESERVE_ORDER; } if (preferedEncodings != null) { options |= MultiLanguage.MLCPF.MLDETECTF_PREFERRED_ONLY; } // finally... call to DetectOutboundCodePage multilang3.DetectOutboundCodePage(options, input, (uint)input.Length, pPrefEncs, (uint)(preferedEncodings == null ? 0 : preferedEncodings.Length), pDetectedEncs, ref detectedCodepages, ref specialChar); // get result if (detectedCodepages > 0) { int[] theResult = new int[detectedCodepages]; Marshal.Copy(pDetectedEncs, theResult, 0, theResult.Length); // get the encodings for the codepages for (int i = 0; i < detectedCodepages; i++) { result.Add(Encoding.GetEncoding(theResult[i])); } } } finally { if (pPrefEncs != IntPtr.Zero) { Marshal.FreeCoTaskMem(pPrefEncs); } Marshal.FreeCoTaskMem(pDetectedEncs); } } finally { Marshal.FinalReleaseComObject(multilang3); } // nothing found return(result.ToArray()); }
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { Blob bl = (Blob)value; bl.Align(); if (bl.fOwn == true) { if (bl.Length == 0L) { if (destinationType == typeof(string)) { return(""); } else { return(null); } } } else if (destinationType == typeof(string)) { return(bl.GrabString((IntPtr)0)); } if (ReferenceEquals(destinationType, typeof(InstanceDescriptor))) { // ' See the next class converter for details on // ' InstanceDescriptor conversion System.Reflection.ConstructorInfo objC; // objC = objT.GetType.GetConstructor(New Type() {GetType(Single), GetType(Single), GetType(Single), GetType(Single), GetType(Ruler.RulerUnits)}) // Return New InstanceDescriptor(objC, New Object() {objT.Left, objT.Top, objT.Width, objT.Height, objT.Units()}) objC = bl.GetType().GetConstructor(new Type[] { typeof(byte[]), typeof(Type) }); return(new InstanceDescriptor(objC, new object[] { (Blob)value, ((Blob)value).Type })); } if (destinationType.IsEnum == true) { return(BlobUtil.BytesToEnum(bl, destinationType)); } else if (destinationType.IsArray == true && destinationType.GetElementType().IsEnum == true) { return(BlobUtil.BytesToEnum(bl, destinationType.GetElementType())); } if (destinationType.IsClass && (destinationType.BaseType == Blob.Types[(int)BlobTypes.Image] || destinationType == Blob.Types[(int)BlobTypes.Image])) { return(BytesToImage(bl.GrabBytes())); } switch (destinationType) { case var @case when @case == typeof(bool): { return(bl.get_ByteAt(0L) != 0); } case var case1 when case1 == typeof(BigInteger): { return(new BigInteger((byte[])bl)); } case var case2 when case2 == typeof(DateTime): { return(BytesToDate(bl)); } case var case3 when case3 == typeof(DateTime[]): { return(BytesToDateArray(bl)); } case var case4 when case4 == typeof(byte[]): { byte[] a; a = new byte[(int)(bl.Length - 1L + 1)]; Array.Copy((byte[])bl, a, bl.Length); return(a); } case var case5 when case5 == typeof(sbyte[]): { return(ToSByteArray(bl)); } case var case6 when case6 == typeof(Guid[]): case var case7 when case7 == typeof(Guid): { if (destinationType == typeof(Guid)) { return(new Guid(bl.GrabBytes((IntPtr)0, 16))); } int l = 16; int e = (int)(bl.Length / (double)l); int i; int c = (int)(bl.Length - 1L); Guid[] gs; gs = new Guid[e]; e = 0; var loopTo = c; for (i = 0; l >= 0 ? i <= loopTo : i >= loopTo; i += l) { gs[e] = new Guid(bl.GrabBytes((IntPtr)i, l)); e += 1; } return(gs); } case var case8 when case8 == typeof(Color[]): case var case9 when case9 == typeof(Color): { if (destinationType == typeof(Color)) { Color cc; cc = Color.FromArgb(bl); return(cc); } int l = 4; int e = (int)(bl.Length / (double)l); int i; int c = (int)(bl.Length - 1L); Color[] cs; cs = new Color[e]; e = 0; var ptr = bl.DangerousGetHandle(); var loopTo1 = c; for (i = 0; l >= 0 ? i <= loopTo1 : i >= loopTo1; i += l) { Native.CopyMemory(ref l, ptr, (IntPtr)4); cs[e] = Color.FromArgb(l); ptr = ptr + l; e += 1; } return(cs); } case var case10 when case10 == typeof(string): { if (bl.Length == 0L) { return(""); } return(bl.ToString()); } case var case11 when case11 == typeof(decimal[]): case var case12 when case12 == typeof(decimal): { decimal[] d; int[] ints = bl; if (Conversions.ToBoolean(ints.Length % 4)) { throw new ArgumentException("Byte array is not aligned for the Decimal data type."); return(null); } if (destinationType == typeof(decimal)) { if (ints.Length != 4) { Array.Resize(ref ints, 4); } return(new decimal(ints)); } var dec = new int[4]; int e = bl.Count - 1; int i; d = new decimal[e + 1]; var loopTo2 = e; for (i = 0; i <= loopTo2; i++) { Array.Copy(ints, i, dec, 0, 4); d[i] = new decimal(dec); } return(d); } case var case13 when case13 == typeof(double): { return(BitConverter.ToDouble(bl, 0)); } case var case14 when case14 == typeof(float): { return(BitConverter.ToSingle(bl, 0)); } case var case15 when case15 == typeof(ulong): { var u = ToULongArray(new[] { BitConverter.ToInt64(bl, 0) }); return(u[0]); } case var case16 when case16 == typeof(long): { return(BitConverter.ToInt64(bl, 0)); } case var case17 when case17 == typeof(uint): { var u = ToUIntegerArray(new[] { BitConverter.ToInt32(bl, 0) }); return(u[0]); } case var case18 when case18 == typeof(int): { return(BitConverter.ToInt32(bl, 0)); } case var case19 when case19 == typeof(ushort): { var u = ToUShortArray(new[] { BitConverter.ToInt16(bl, 0) }); return(u[0]); } case var case20 when case20 == typeof(short): { return(BitConverter.ToInt16(bl, 0)); } case var case21 when case21 == typeof(char): { return(BitConverter.ToChar(bl, 0)); } case var case22 when case22 == typeof(byte): { return(bl.get_ByteAt(0L)); } case var case23 when case23 == typeof(sbyte): { var u = ToSByteArray(bl); return(u[0]); } case var case24 when case24 == typeof(double[]): case var case25 when case25 == typeof(float[]): case var case26 when case26 == typeof(long[]): case var case27 when case27 == typeof(ulong[]): case var case28 when case28 == typeof(int[]): case var case29 when case29 == typeof(uint[]): case var case30 when case30 == typeof(short[]): case var case31 when case31 == typeof(ushort[]): case var case32 when case32 == typeof(char[]): { object a = Array.CreateInstance(destinationType.GetElementType(), 1); int l; int e; int f = 0; IntPtr ptr; byte[] b = bl; l = Marshal.SizeOf(a((object)0)); e = (int)(b.Length / (double)l); l = b.Length; switch (destinationType.GetElementType()) { case var case33 when case33 == typeof(sbyte): { a = Array.CreateInstance(typeof(byte), e); break; } case var case34 when case34 == typeof(ushort): { a = Array.CreateInstance(typeof(short), e); break; } case var case35 when case35 == typeof(uint): { a = Array.CreateInstance(typeof(int), e); break; } case var case36 when case36 == typeof(ulong): { a = Array.CreateInstance(typeof(long), e); break; } default: { a = Array.CreateInstance(destinationType.GetElementType(), e); break; } } ptr = Marshal.AllocCoTaskMem(l); Marshal.Copy(b, 0, ptr, l); Marshal.Copy(ptr, a, (object)0, e); Marshal.FreeCoTaskMem(ptr); switch (destinationType.GetElementType()) { case var case37 when case37 == typeof(sbyte): { a = ToSByteArray((byte[])a); break; } case var case38 when case38 == typeof(ushort): { a = ToUShortArray((short[])a); break; } case var case39 when case39 == typeof(uint): { a = ToUIntegerArray((int[])a); break; } case var case40 when case40 == typeof(ulong): { a = ToULongArray((long[])a); break; } } return(a); } } if (destinationType.IsValueType) { object o = null; BlobToStructure(bl, ref o); return(o); } return(base.ConvertTo(context, culture, value, destinationType)); }
public static unsafe string Test(string szToHashData, string szPin, out string error) { uint dwRet = 0; string szSignData = ""; error = ""; //接口初始化 dwRet = UAI_Initialize(0); if (dwRet != 0) { //Console.WriteLine("UAI_Initialize error = {0}", dwRet); error = "UAI_Initialize error = " + dwRet; goto end; } //获取设备列表 char **pszDeviceList = null; uint dwDeviceCount = 0; dwRet = UAI_GetDeviceList(&pszDeviceList, &dwDeviceCount, 0); if (dwRet != 0) { //Console.WriteLine("UAI_GetDeviceList error = {0}", dwRet); error = "UAI_GetDeviceList error = " + dwRet; goto end; } //打开设备 void *hDev = null; dwRet = UAI_OpenDevice(pszDeviceList[0], &hDev, 0); if (dwRet != 0) { //Console.WriteLine("UAI_OpenDevice error = {0}", dwRet); error = "UAI_OpenDevice error = " + dwRet; goto end; } //PIN码验证 uint dwRetryNum = 0; //string szPin = "136413"; IntPtr pPin = Marshal.StringToCoTaskMemAnsi(szPin); char * chPin = (char *)pPin.ToPointer(); dwRet = UAI_VerifyPIN(hDev, chPin, &dwRetryNum, 0); if (dwRet != 0) { //Console.WriteLine("UAI_VerifyPIN error = {0}", dwRet); error = "UAI_VerifyPIN error = " + dwRet; goto end; } Marshal.FreeCoTaskMem(pPin); //杂凑待签名数据 //string szToHashData = "MTIz"; byte[] byToHashData = Convert.FromBase64String(szToHashData); IntPtr pToHashData = Marshal.AllocCoTaskMem(byToHashData.Length); Marshal.Copy(byToHashData, 0, pToHashData, byToHashData.Length); byte * pbToHashData = (byte *)pToHashData; uint dwToHashDataLen = (uint)byToHashData.Length; const int dwHashResultLen = 20; IntPtr pHashData = Marshal.AllocCoTaskMem(dwHashResultLen); byte * pbHashData = (byte *)pHashData; uint dwHashDataLen = dwHashResultLen; dwRet = UAI_Hash(hDev, 0x00, 0x01, pbToHashData, dwToHashDataLen, pbHashData, &dwHashDataLen, 0); if (dwRet != 0) { Marshal.FreeCoTaskMem(pToHashData); Marshal.FreeCoTaskMem(pHashData); // Console.WriteLine("UAI_Hash error = {0}", dwRet); error = "UAI_Hash error = " + dwRet; goto end; } //待签名数据总共35字节,15字节OID+20字节签名原文杂凑值 byte[] byOID_SHA1 = new byte[] { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04, 0x14 }; byte[] byToSignData = new byte[byOID_SHA1.Length + dwHashDataLen]; Array.Copy(byOID_SHA1, byToSignData, byOID_SHA1.Length); Marshal.FreeCoTaskMem(pToHashData); for (int i = 0; i < dwHashDataLen; i++) { byToSignData[byOID_SHA1.Length + i] = pbHashData[i]; } Marshal.FreeCoTaskMem(pHashData); IntPtr pToSignData = Marshal.AllocCoTaskMem(byToSignData.Length); Marshal.Copy(byToSignData, 0, pToSignData, byToSignData.Length); byte *pbToSignData = (byte *)pToSignData.ToPointer(); uint dwpToSignDataLen = (uint)byToSignData.Length; //对待签名数据进行RSA私钥运算 string szContainerName = "{4A7A26B1-ABA5-48ef-8B6A-24A4BA42E787}"; IntPtr pContainerName = Marshal.StringToCoTaskMemAnsi(szContainerName); char * pchszContainerName = (char *)pContainerName.ToPointer(); const int dwSignResultLen = 128; IntPtr pSignData = Marshal.AllocCoTaskMem(dwSignResultLen); byte * pbSignData = (byte *)pSignData; uint dwSignDataLen = dwSignResultLen; dwRet = UAI_PrivateKeyCalc(hDev, pchszContainerName, 1, pbToSignData, dwpToSignDataLen, pbSignData, &dwSignDataLen, 0); Marshal.FreeCoTaskMem(pContainerName); //Marshal.FreeCoTaskMem(pToHashData);容易出现BUG if (dwRet != 0) { Marshal.FreeCoTaskMem(pSignData); //Console.WriteLine("UAI_PrivateKeyCalc error = {0}", dwRet); error = "UAI_PrivateKeyCalc error = " + dwRet; goto end; } byte[] bySignData = new byte[dwSignDataLen]; for (int i = 0; i < dwSignDataLen; i++) { bySignData[i] = pbSignData[i]; } szSignData = Convert.ToBase64String(bySignData); Marshal.FreeCoTaskMem(pSignData); //关闭设备 dwRet = UAI_CloseDevice(hDev, 0); if (dwRet != 0) { //Console.WriteLine("UAI_CloseDevice error = {0}", dwRet); error = "UAI_PrivateKeyCalc error = " + dwRet; goto end; } //释放设备库 dwRet = UAI_Finalize(0); if (dwRet != 0) { //Console.WriteLine("UAI_Finalize error = {0}", dwRet); error = "UAI_Finalize error = " + dwRet; goto end; } end: if (dwRet == 0) { //Console.WriteLine("all finish"); } //Console.WriteLine("press any key to exit..."); //Console.Read(); return(szSignData); }
/// <summary> /// Gets the control details /// </summary> protected void GetControlDetails() { mixerControlDetails.cbStruct = Marshal.SizeOf(mixerControlDetails); mixerControlDetails.dwControlID = mixerControl.dwControlID; if (IsCustom) { mixerControlDetails.cChannels = 0; } else if ((mixerControl.fdwControl & MixerInterop.MIXERCONTROL_CONTROLF_UNIFORM) != 0) { mixerControlDetails.cChannels = 1; } else { mixerControlDetails.cChannels = nChannels; } if ((mixerControl.fdwControl & MixerInterop.MIXERCONTROL_CONTROLF_MULTIPLE) != 0) { mixerControlDetails.hwndOwner = (IntPtr)mixerControl.cMultipleItems; } else if (IsCustom) { mixerControlDetails.hwndOwner = IntPtr.Zero; // TODO: special cases } else { mixerControlDetails.hwndOwner = IntPtr.Zero; } if (IsBoolean) { mixerControlDetails.cbDetails = Marshal.SizeOf(new MixerInterop.MIXERCONTROLDETAILS_BOOLEAN()); } else if (IsListText) { mixerControlDetails.cbDetails = Marshal.SizeOf(new MixerInterop.MIXERCONTROLDETAILS_LISTTEXT()); } else if (IsSigned) { mixerControlDetails.cbDetails = Marshal.SizeOf(new MixerInterop.MIXERCONTROLDETAILS_SIGNED()); } else if (IsUnsigned) { mixerControlDetails.cbDetails = Marshal.SizeOf(new MixerInterop.MIXERCONTROLDETAILS_UNSIGNED()); } else { // must be custom mixerControlDetails.cbDetails = mixerControl.Metrics.customData; } var detailsSize = mixerControlDetails.cbDetails * mixerControlDetails.cChannels; if ((mixerControl.fdwControl & MixerInterop.MIXERCONTROL_CONTROLF_MULTIPLE) != 0) { // fixing issue 16390 - calculating size correctly for multiple items detailsSize *= (int)mixerControl.cMultipleItems; } IntPtr buffer = Marshal.AllocCoTaskMem(detailsSize); // To copy stuff in: // Marshal.StructureToPtr( theStruct, buffer, false ); mixerControlDetails.paDetails = buffer; MmResult err = MixerInterop.mixerGetControlDetails(mixerHandle, ref mixerControlDetails, MixerFlags.Value | mixerHandleType); // let the derived classes get the details before we free the handle if (err == MmResult.NoError) { GetDetails(mixerControlDetails.paDetails); } Marshal.FreeCoTaskMem(buffer); if (err != MmResult.NoError) { throw new MmException(err, "mixerGetControlDetails"); } }
private Font CreateFont(string fontName, float fontSize) { Font currentFont; if (_defaultFont == null) { _defaultFont = new Font(FontFamily.GenericSansSerif, 12); } FontFamily fontFamily; if (!_fontFamilyCache.TryGetValue(fontName, out fontFamily)) { var ext = Path.GetExtension(fontName); currentFont = _defaultFont; if (!String.IsNullOrEmpty(ext) && ext.ToLower() == ".ttf") { try { // Read the font file bytes var fontBytes = CCContentManager.SharedContentManager.GetAssetStreamAsBytes(fontName); // Pin the font data for the length of the read file var fontData = Marshal.AllocCoTaskMem(fontBytes.Length); // Copy the font data to our memory Marshal.Copy(fontBytes, 0, fontData, fontBytes.Length); // Add the memory data to our private font collection as a Font in Memory loadedFontsCollection.AddMemoryFont(fontData, fontBytes.Length); // Release the pinned data Marshal.FreeCoTaskMem(fontData); // Try to get the family name of the var ttfFontFamily = CCLabelUtilities.GetFontFamily(fontBytes, 0); fontFamily = new FontFamily(ttfFontFamily, loadedFontsCollection); currentFont = new Font(fontFamily, fontSize); } catch { currentFont = _defaultFont; } } else { currentFont = new Font(fontName, fontSize); } _fontFamilyCache.Add(fontName, currentFont.FontFamily); } else { currentFont = new Font(fontFamily, fontSize); } // Create a small bitmap to be used for our graphics context CreateBitmap(1, 1); return(currentFont); }
/// <summary> /// 转换网络映射路径到远程路径;直接捕获了异常 /// (若不是网络映射路径,则原样返回) /// </summary> /// <param name="localPath">本地映射路径</param> /// <returns></returns> public static string GetUniversalName(string localPath) { if (localPath.StartsWith(@"\\")) { return(localPath); } // The return value. string retVal = null; // The pointer in memory to the structure. IntPtr buffer = IntPtr.Zero; // Wrap in a try/catch block for cleanup. try { // First, call WNetGetUniversalName to get the size. int size = 0; // Make the call. // Pass IntPtr.Size because the API doesn't like null, even though // size is zero. We know that IntPtr.Size will be // aligned correctly. int apiRetVal = WNetGetUniversalName(localPath, UNIVERSAL_NAME_INFO_LEVEL, (IntPtr)IntPtr.Size, ref size); // If the return value is not ERROR_MORE_DATA, then // raise an exception. if (apiRetVal != ERROR_MORE_DATA) { // Throw an exception. throw new Exception(apiRetVal.ToString()); } // Allocate the memory. buffer = Marshal.AllocCoTaskMem(size); // Now make the call. apiRetVal = WNetGetUniversalName(localPath, UNIVERSAL_NAME_INFO_LEVEL, buffer, ref size); // If it didn't succeed, then throw. if (apiRetVal != NOERROR) { // Throw an exception. throw new Exception(apiRetVal.ToString());//Win32Exception(apiRetVal); } // Now get the string. It's all in the same buffer, but // the pointer is first, so offset the pointer by IntPtr.Size // and pass to PtrToStringAnsi. retVal = Marshal.PtrToStringAuto(new IntPtr(buffer.ToInt64() + IntPtr.Size), size); retVal = retVal.Substring(0, retVal.IndexOf('\0')); } catch { retVal = localPath; } finally { // Release the buffer. Marshal.FreeCoTaskMem(buffer); } // First, allocate the memory for the structure. // That's all folks. return(retVal); }
internal unsafe IntPtr ToUniStr(bool allocateFromHeap) { EnsureNotDisposed(); int length = m_length; IntPtr ptr = IntPtr.Zero; IntPtr result = IntPtr.Zero; byte * bufferPtr = null; RuntimeHelpers.PrepareConstrainedRegions(); try { RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { if (allocateFromHeap) { ptr = Marshal.AllocHGlobal((length + 1) * 2); } else { ptr = Marshal.AllocCoTaskMem((length + 1) * 2); } } if (ptr == IntPtr.Zero) { throw new OutOfMemoryException(); } UnProtectMemory(); m_buffer.AcquirePointer(ref bufferPtr); Buffer.Memcpy((byte *)ptr.ToPointer(), bufferPtr, length * 2); char *endptr = (char *)ptr.ToPointer(); *(endptr + length) = '\0'; result = ptr; } catch (Exception) { ProtectMemory(); throw; } finally { ProtectMemory(); if (result == IntPtr.Zero) { // If we failed for any reason, free the new buffer if (ptr != IntPtr.Zero) { Win32Native.ZeroMemory(ptr, (UIntPtr)(length * 2)); if (allocateFromHeap) { Marshal.FreeHGlobal(ptr); } else { Marshal.FreeCoTaskMem(ptr); } } } if (bufferPtr != null) { m_buffer.ReleasePointer(); } } return(result); }
private void CMB_videosources_SelectedIndexChanged(object sender, EventArgs e) { if (MainV2.MONO) { return; } int hr; int count; int size; object o; IBaseFilter capFilter = null; ICaptureGraphBuilder2 capGraph = null; AMMediaType media = null; VideoInfoHeader v; VideoStreamConfigCaps c; List <GCSBitmapInfo> modes = new List <GCSBitmapInfo>(); // Get the ICaptureGraphBuilder2 capGraph = (ICaptureGraphBuilder2) new CaptureGraphBuilder2(); IFilterGraph2 m_FilterGraph = (IFilterGraph2) new FilterGraph(); DsDevice[] capDevices; capDevices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice); // Add the video device hr = m_FilterGraph.AddSourceFilterForMoniker(capDevices[CMB_videosources.SelectedIndex].Mon, null, "Video input", out capFilter); try { DsError.ThrowExceptionForHR(hr); } catch (Exception ex) { CustomMessageBox.Show("Can not add video source\n" + ex.ToString()); return; } // Find the stream config interface hr = capGraph.FindInterface(PinCategory.Capture, MediaType.Video, capFilter, typeof(IAMStreamConfig).GUID, out o); DsError.ThrowExceptionForHR(hr); IAMStreamConfig videoStreamConfig = o as IAMStreamConfig; if (videoStreamConfig == null) { throw new Exception("Failed to get IAMStreamConfig"); } hr = videoStreamConfig.GetNumberOfCapabilities(out count, out size); DsError.ThrowExceptionForHR(hr); IntPtr TaskMemPointer = Marshal.AllocCoTaskMem(size); for (int i = 0; i < count; i++) { IntPtr ptr = IntPtr.Zero; hr = videoStreamConfig.GetStreamCaps(i, out media, TaskMemPointer); v = (VideoInfoHeader)Marshal.PtrToStructure(media.formatPtr, typeof(VideoInfoHeader)); c = (VideoStreamConfigCaps)Marshal.PtrToStructure(TaskMemPointer, typeof(VideoStreamConfigCaps)); modes.Add(new GCSBitmapInfo(v.BmiHeader.Width, v.BmiHeader.Height, c.MaxFrameInterval, c.VideoStandard.ToString(), media)); } Marshal.FreeCoTaskMem(TaskMemPointer); DsUtils.FreeAMMediaType(media); CMB_videoresolutions.DataSource = modes; if (MainV2.getConfig("video_options") != "" && CMB_videosources.Text != "") { try { CMB_videoresolutions.SelectedIndex = int.Parse(MainV2.getConfig("video_options")); } catch { } // ignore bad entries } }
internal unsafe IntPtr ToAnsiStr(bool allocateFromHeap) { EnsureNotDisposed(); IntPtr ptr = IntPtr.Zero; IntPtr result = IntPtr.Zero; int byteCount = 0; RuntimeHelpers.PrepareConstrainedRegions(); try { // GetAnsiByteCount uses the string data, so the calculation must happen after we are decrypted. UnProtectMemory(); // allocating an extra char for terminating zero byteCount = GetAnsiByteCount() + 1; RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { if (allocateFromHeap) { ptr = Marshal.AllocHGlobal(byteCount); } else { ptr = Marshal.AllocCoTaskMem(byteCount); } } if (ptr == IntPtr.Zero) { throw new OutOfMemoryException(); } GetAnsiBytes((byte *)ptr.ToPointer(), byteCount); result = ptr; } catch (Exception) { ProtectMemory(); throw; } finally { ProtectMemory(); if (result == IntPtr.Zero) { // If we failed for any reason, free the new buffer if (ptr != IntPtr.Zero) { Win32Native.ZeroMemory(ptr, (UIntPtr)byteCount); if (allocateFromHeap) { Marshal.FreeHGlobal(ptr); } else { Marshal.FreeCoTaskMem(ptr); } } } } return(result); }
/// <summary> /// Creates a new SSL certificate binding. /// </summary> public static void SetSslCertificateBinding(SslCertificateBinding binding) { if (binding == null) { throw new ArgumentNullException("binding"); } // initialize library. HttpError error = NativeMethods.HttpInitialize( new HTTPAPI_VERSION(1, 0), HttpInitFlag.HTTP_INITIALIZE_CONFIG, IntPtr.Zero); if (error != HttpError.NO_ERROR) { throw ServiceResultException.Create( StatusCodes.BadUnexpectedError, "Could not initialize HTTP library.\r\nError={0}", error); } IntPtr pAddress = IntPtr.Zero; IntPtr pThumprint = IntPtr.Zero; IntPtr pConfigInfo = IntPtr.Zero; try { pAddress = ToIntPtr(binding.IPAddress, binding.Port); byte[] thumbprint = Utils.FromHexString(binding.Thumbprint); pThumprint = Marshal.AllocCoTaskMem(thumbprint.Length); Marshal.Copy(thumbprint, 0, pThumprint, thumbprint.Length); HTTP_SERVICE_CONFIG_SSL_SET configSslSet = new HTTP_SERVICE_CONFIG_SSL_SET(); configSslSet.KeyDesc.pIpPort = pAddress; configSslSet.ParamDesc.pSslHash = pThumprint; configSslSet.ParamDesc.SslHashLength = thumbprint.Length; configSslSet.ParamDesc.AppId = binding.ApplicationId; configSslSet.ParamDesc.pSslCertStoreName = binding.StoreName; configSslSet.ParamDesc.DefaultCertCheckMode = binding.DefaultCertCheckMode; configSslSet.ParamDesc.DefaultFlags = binding.DefaultFlags; configSslSet.ParamDesc.DefaultRevocationFreshnessTime = binding.DefaultRevocationFreshnessTime; configSslSet.ParamDesc.DefaultRevocationUrlRetrievalTimeout = binding.DefaultRevocationUrlRetrievalTimeout; configSslSet.ParamDesc.pDefaultSslCtlIdentifier = binding.DefaultSslCtlIdentifier; configSslSet.ParamDesc.pDefaultSslCtlStoreName = binding.DefaultSslCtlStoreName; int size = Marshal.SizeOf(typeof(HTTP_SERVICE_CONFIG_SSL_SET)); pConfigInfo = Marshal.AllocCoTaskMem(size); Marshal.StructureToPtr(configSslSet, pConfigInfo, false); error = NativeMethods.HttpSetServiceConfiguration( IntPtr.Zero, HTTP_SERVICE_CONFIG_ID.HttpServiceConfigSSLCertInfo, pConfigInfo, size, IntPtr.Zero); if (error == HttpError.ERROR_ALREADY_EXISTS) { error = NativeMethods.HttpDeleteServiceConfiguration( IntPtr.Zero, HTTP_SERVICE_CONFIG_ID.HttpServiceConfigSSLCertInfo, pConfigInfo, size, IntPtr.Zero); if (error != HttpError.NO_ERROR) { throw ServiceResultException.Create( StatusCodes.BadUnexpectedError, "Could not delete existing SSL certificate binding.\r\nError={0}", error); } error = NativeMethods.HttpSetServiceConfiguration( IntPtr.Zero, HTTP_SERVICE_CONFIG_ID.HttpServiceConfigSSLCertInfo, pConfigInfo, size, IntPtr.Zero); } if (error != HttpError.NO_ERROR) { throw ServiceResultException.Create( StatusCodes.BadUnexpectedError, "Could not create SSL certificate binding.\r\nError={0}", error); } } finally { if (pConfigInfo != IntPtr.Zero) { Marshal.FreeCoTaskMem(pConfigInfo); } if (pAddress != IntPtr.Zero) { Marshal.FreeCoTaskMem(pAddress); } if (pThumprint != IntPtr.Zero) { Marshal.FreeCoTaskMem(pThumprint); } NativeMethods.HttpTerminate(HttpInitFlag.HTTP_INITIALIZE_CONFIG, IntPtr.Zero); } }
public static bool SetProxy(string strProxy, string strExceptions) { InternetPerConnOptionList request = new InternetPerConnOptionList(); InternetPerConnOption[] options = new InternetPerConnOption[3]; int optionSize = 0; IntPtr optionsPtr = IntPtr.Zero; try { options[0].dwOption = OptionType.INTERNET_PER_CONN_FLAGS; options[0].Value.dwValue = (int)ProxyFlags.PROXY_TYPE_PROXY; options[1].dwOption = OptionType.INTERNET_PER_CONN_PROXY_SERVER; options[1].Value.szValue = String.IsNullOrEmpty(strProxy) ? IntPtr.Zero : Marshal.StringToHGlobalAnsi(strProxy); options[2].dwOption = OptionType.INTERNET_PER_CONN_PROXY_BYPASS; options[2].Value.szValue = String.IsNullOrEmpty(strExceptions) ? IntPtr.Zero : Marshal.StringToHGlobalAnsi(strExceptions); optionSize = Marshal.SizeOf(typeof(InternetPerConnOption)); optionsPtr = Marshal.AllocCoTaskMem(optionSize * options.Length); if (optionsPtr == IntPtr.Zero) { return(false); } for (int i = 0; i < options.Length; ++i) { IntPtr optionPtr = new IntPtr(optionsPtr.ToInt32() + (i * optionSize)); Marshal.StructureToPtr(options[i], optionPtr, false); } request.pszConnection = IntPtr.Zero; request.dwSize = Marshal.SizeOf(typeof(InternetPerConnOptionList)); request.dwOptionCount = options.Length; request.dwOptionError = 0; request.pOptions = optionsPtr; int requestLength = request.dwSize; if (NativeMethods.InternetSetOption(IntPtr.Zero, InternetOptionActions.INTERNET_OPTION_PER_CONNECTION_OPTION, ref request, requestLength)) { NativeMethods.InternetSetOption(IntPtr.Zero, InternetOptionActions.INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0); NativeMethods.InternetSetOption(IntPtr.Zero, InternetOptionActions.INTERNET_OPTION_REFRESH, IntPtr.Zero, 0); return(true); } else { return(false); } } finally { if (optionsPtr != IntPtr.Zero) { Marshal.FreeCoTaskMem(optionsPtr); } for (int i = 1; i < options.Length; i++) { if (options[i].Value.szValue != IntPtr.Zero) { Marshal.FreeHGlobal(options[i].Value.szValue); } } } }
/// <summary> /// Deletes a new SSL certificate binding. /// </summary> public static void DeleteSslCertificateBinding(IPAddress address, ushort port) { if (address == null) { throw new ArgumentNullException("address"); } // initialize library. HttpError error = NativeMethods.HttpInitialize( new HTTPAPI_VERSION(1, 0), HttpInitFlag.HTTP_INITIALIZE_CONFIG, IntPtr.Zero); if (error != HttpError.NO_ERROR) { throw ServiceResultException.Create( StatusCodes.BadUnexpectedError, "Could not initialize HTTP library.\r\nError={0}", error); } IntPtr pAddress = IntPtr.Zero; IntPtr pConfigInfo = IntPtr.Zero; try { pAddress = ToIntPtr(address, port); HTTP_SERVICE_CONFIG_SSL_SET configSslSet = new HTTP_SERVICE_CONFIG_SSL_SET(); configSslSet.KeyDesc.pIpPort = pAddress; int size = Marshal.SizeOf(typeof(HTTP_SERVICE_CONFIG_SSL_SET)); pConfigInfo = Marshal.AllocCoTaskMem(size); Marshal.StructureToPtr(configSslSet, pConfigInfo, false); error = NativeMethods.HttpDeleteServiceConfiguration( IntPtr.Zero, HTTP_SERVICE_CONFIG_ID.HttpServiceConfigSSLCertInfo, pConfigInfo, size, IntPtr.Zero); if (error != HttpError.NO_ERROR) { throw ServiceResultException.Create( StatusCodes.BadUnexpectedError, "Could not delete existing SSL certificate binding.\r\nError={0}", error); } } finally { if (pConfigInfo != IntPtr.Zero) { Marshal.FreeCoTaskMem(pConfigInfo); } if (pAddress != IntPtr.Zero) { Marshal.FreeCoTaskMem(pAddress); } NativeMethods.HttpTerminate(HttpInitFlag.HTTP_INITIALIZE_CONFIG, IntPtr.Zero); } }
public static void Free(this IntPtr pointer) { Marshal.FreeCoTaskMem(pointer); }
public void Dispose() { Marshal.FreeCoTaskMem(pBuffer); }
void LateUpdate() { int frame_count = Time.frameCount; double time = Time.time; #region ROSCsereal (Must be last!) if (!serialConnected) { return; } // Spin for subscribers, should be blocking spinOnce(); // Publish topics foreach (var rp in registeredPublishers) { if (rp.Value == null) { continue; } rosGameObject rGO = new rosGameObject(); // Headers rGO.unique_id = rp.Key; rGO.frame_count = frame_count; rGO.time = time; // Parent (Immutable) rGO.parent = Marshal.StringToCoTaskMemAnsi(rp.Value.parent); // Poses (Transforms) rGO.poses_length = (uint)rp.Value.poses.Count; IntPtr posesPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(new unityPose()) * (int)rGO.poses_length); if (rGO.poses_length > 0) { double[] temp = new double[7 * rGO.poses_length]; for (int i = 0; i != rGO.poses_length; ++i) { temp[7 * i] = rp.Value.poses[i].position.x; temp[7 * i + 1] = rp.Value.poses[i].position.y; temp[7 * i + 2] = rp.Value.poses[i].position.z; temp[7 * i + 3] = rp.Value.poses[i].rotation.x; temp[7 * i + 4] = rp.Value.poses[i].rotation.y; temp[7 * i + 5] = rp.Value.poses[i].rotation.z; temp[7 * i + 6] = rp.Value.poses[i].rotation.w; } Marshal.Copy(temp, 0, posesPtr, 7 * (int)rGO.poses_length); } rGO.poses = posesPtr; // Events rGO.events_length = (uint)rp.Value.events.Count; rGO.has_events = rGO.events_length > 0 ? true : false; // Shorthand because I'm cool IntPtr[] tempEventsPtrArray = new IntPtr [rGO.events_length]; if (rGO.has_events && rGO.events_length > 0) { rGO.events = Marshal.AllocCoTaskMem(Marshal.SizeOf(new IntPtr()) * rp.Value.events.Count); int iterEvents = 0; foreach (var _event in rp.Value.events) { tempEventsPtrArray[iterEvents] = Marshal.StringToCoTaskMemAnsi(_event); iterEvents++; } Marshal.Copy(tempEventsPtrArray, 0, rGO.events, (int)rGO.events_length); } // Values (Attributes or whatever) rGO.values_length = (uint)rp.Value.values.val.Count; rGO.has_values = rGO.values_length > 0 ? true : false; // Shorthand because I'm cool // NOTE: Do not name variables "value". rGO.values_name = Marshal.AllocCoTaskMem(Marshal.SizeOf(new IntPtr()) * (int)rGO.values_length); IntPtr[] tempValuesNameArray = new IntPtr [rGO.values_length]; rGO.values_data = Marshal.AllocCoTaskMem(Marshal.SizeOf(new double()) * (int)rGO.values_length); double[] tempValuesDataArray = new double [rGO.values_length]; int iterValues = 0; foreach (var val in rp.Value.values.val) { tempValuesNameArray[iterValues] = Marshal.StringToCoTaskMemAnsi(val.Key); tempValuesDataArray[iterValues] = val.Value; iterValues++; } Marshal.Copy(tempValuesNameArray, 0, rGO.values_name, (int)rGO.values_length); Marshal.Copy(tempValuesDataArray, 0, rGO.values_data, (int)rGO.values_length); // Publishing publish(rp.Key, rGO); // Housekeeping rp.Value.clearEvents(); Marshal.FreeCoTaskMem(posesPtr); foreach (var item in tempEventsPtrArray) { Marshal.FreeCoTaskMem(item); } foreach (var item in tempValuesNameArray) { Marshal.FreeCoTaskMem(item); } Marshal.FreeCoTaskMem(rGO.values_data); Marshal.FreeCoTaskMem(rGO.values_name); } spinOnce(); #endregion }
public void ShowContextMenu() { IntPtr contextMenu = IntPtr.Zero, iContextMenuPtr = IntPtr.Zero, iContextMenuPtr2 = IntPtr.Zero, iContextMenuPtr3 = IntPtr.Zero; try { if (ShellFolders.GetIContextMenu(parentShellFolder, pidls, out iContextMenuPtr, out iContextMenu)) { // get some properties about our file(s) bool allFolders = true; bool allInStacks = true; foreach (SystemFile file in paths) { if (!file.IsDirectory) { allFolders = false; } else { bool contains = false; foreach (SystemDirectory dir in StacksManager.StackLocations) { if (dir.Equals(file.FullName)) { contains = true; break; } } if (!contains) { allInStacks = false; } } } contextMenu = ShellFolders.CreatePopupMenu(); uint numPrepended = prependItems(contextMenu, allFolders, allInStacks); iContextMenu.QueryContextMenu( contextMenu, numPrepended, ShellFolders.CMD_FIRST, ShellFolders.CMD_LAST, ShellFolders.CMF.EXPLORE | ShellFolders.CMF.CANRENAME | ((Control.ModifierKeys & Keys.Shift) != 0 ? ShellFolders.CMF.EXTENDEDVERBS : 0)); appendItems(contextMenu, allFolders, allInStacks); Marshal.QueryInterface(iContextMenuPtr, ref ShellFolders.IID_IContextMenu2, out iContextMenuPtr2); Marshal.QueryInterface(iContextMenuPtr, ref ShellFolders.IID_IContextMenu3, out iContextMenuPtr3); try { iContextMenu2 = (IContextMenu2)Marshal.GetTypedObjectForIUnknown(iContextMenuPtr2, typeof(IContextMenu2)); iContextMenu3 = (IContextMenu3)Marshal.GetTypedObjectForIUnknown(iContextMenuPtr3, typeof(IContextMenu3)); } catch (Exception) { } uint selected = ShellFolders.TrackPopupMenuEx( contextMenu, ShellFolders.TPM.RETURNCMD, this.x, this.y, this.Handle, IntPtr.Zero); if (selected >= ShellFolders.CMD_FIRST) { string command = ShellFolders.GetCommandString(iContextMenu, selected - ShellFolders.CMD_FIRST, true); // set action strings for us to use in our custom execution function switch ((CairoContextMenuItem)selected) { case CairoContextMenuItem.AddToStacks: command = "addStack"; break; case CairoContextMenuItem.RemoveFromStacks: command = "removeStack"; break; case CairoContextMenuItem.OpenInNewWindow: command = "openWithShell"; break; default: if (command == "open" && allFolders) { // suppress running system code command = "openFolder"; } else { ShellFolders.InvokeCommand( iContextMenu, selected - ShellFolders.CMD_FIRST, parent, new Point(this.x, this.y)); } break; } if (this.itemSelected != null) { itemSelected(command, paths[0].FullName, sender); } } } else { CairoLogger.Instance.Debug("Error retrieving IContextMenu"); } } catch (Exception) { } finally { if (iContextMenu != null) { Marshal.FinalReleaseComObject(iContextMenu); iContextMenu = null; } if (iContextMenu2 != null) { Marshal.FinalReleaseComObject(iContextMenu2); iContextMenu2 = null; } if (iContextMenu3 != null) { Marshal.FinalReleaseComObject(iContextMenu3); iContextMenu3 = null; } if (parentShellFolder != null) { Marshal.FinalReleaseComObject(parentShellFolder); parentShellFolder = null; } if (contextMenu != null) { ShellFolders.DestroyMenu(contextMenu); } if (iContextMenuPtr != IntPtr.Zero) { Marshal.Release(iContextMenuPtr); } if (iContextMenuPtr2 != IntPtr.Zero) { Marshal.Release(iContextMenuPtr2); } if (iContextMenuPtr3 != IntPtr.Zero) { Marshal.Release(iContextMenuPtr3); } for (int i = 0; i < pidls.Length; i++) { Marshal.FreeCoTaskMem(pidls[i]); pidls[i] = IntPtr.Zero; } } }
// Start serving up frames private void DoIt(Capture cam, TcpServer serv, StreamWriter sw, ImageCodecInfo myImageCodecInfo, EncoderParameters myEncoderParameters) { MemoryStream m = new MemoryStream(20000); Bitmap image = null; IntPtr ip = IntPtr.Zero; do { // Wait til a client connects before we start the graph ConnectionReady.WaitOne(); cam.Start(); // While not shutting down, and still at least one client while ((!bShutDown) && (serv.Connections > 0)) { try { // capture image ip = cam.GetBitMap(); image = new Bitmap(cam.Width, cam.Height, cam.Stride, PixelFormat.Format24bppRgb, ip); image.RotateFlip(RotateFlipType.RotateNoneFlipY); // save it to jpeg using quality options m.Position = 10; image.Save(m, myImageCodecInfo, myEncoderParameters); // Send the length as a fixed length string m.Position = 0; m.Write(Encoding.ASCII.GetBytes((m.Length - 10).ToString("d8") + "\r\n"), 0, 10); // send the jpeg image serv.SendToAll(m); // Empty the stream m.SetLength(0); // remove the image from memory image.Dispose(); image = null; } catch (Exception ex) { try { sw.WriteLine(DateTime.Now.ToString()); sw.WriteLine(ex); } catch {} } finally { if (ip != IntPtr.Zero) { Marshal.FreeCoTaskMem(ip); ip = IntPtr.Zero; } } } // Clients have all disconnected. Pause, then sleep and wait for more cam.Pause(); sw.WriteLine("Dropped frames: " + cam.m_Dropped.ToString()); } while (!bShutDown); }
private void ShowFolderMenu() { IntPtr contextMenu = IntPtr.Zero, viewSubMenu = IntPtr.Zero; IntPtr newContextMenuPtr = IntPtr.Zero, newContextMenuPtr2 = IntPtr.Zero, newContextMenuPtr3 = IntPtr.Zero; newSubmenuPtr = IntPtr.Zero; try { contextMenu = ShellFolders.CreatePopupMenu(); ShellFolders.AppendMenu(contextMenu, ShellFolders.MFT.BYCOMMAND, (int)CairoContextMenuItem.OpenInNewWindow, Localization.DisplayString.sStacks_OpenInNewWindow); if (!StacksManager.StackLocations.Contains(directory)) { ShellFolders.AppendMenu(contextMenu, ShellFolders.MFT.BYCOMMAND, (int)CairoContextMenuItem.AddToStacks, Localization.DisplayString.sInterface_AddToStacks); } else { ShellFolders.AppendMenu(contextMenu, ShellFolders.MFT.BYCOMMAND, (int)CairoContextMenuItem.RemoveFromStacks, Localization.DisplayString.sInterface_RemoveFromStacks); } ShellFolders.AppendMenu(contextMenu, ShellFolders.MFT.SEPARATOR, 1, string.Empty); ShellFolders.AppendMenu(contextMenu, ShellFolders.MFT.BYCOMMAND, (int)CairoContextMenuItem.Paste, Localization.DisplayString.sInterface_Paste); if (GetNewContextMenu(out newContextMenuPtr, out newContextMenu)) { ShellFolders.AppendMenu(contextMenu, ShellFolders.MFT.SEPARATOR, 1, string.Empty); newContextMenu.QueryContextMenu( contextMenu, 5, ShellFolders.CMD_FIRST, ShellFolders.CMD_LAST, ShellFolders.CMF.NORMAL); newSubmenuPtr = ShellFolders.GetSubMenu(contextMenu, 5); Marshal.QueryInterface(newContextMenuPtr, ref ShellFolders.IID_IContextMenu2, out newContextMenuPtr2); Marshal.QueryInterface(newContextMenuPtr, ref ShellFolders.IID_IContextMenu3, out newContextMenuPtr3); try { newContextMenu2 = (IContextMenu2)Marshal.GetTypedObjectForIUnknown(newContextMenuPtr2, typeof(IContextMenu2)); newContextMenu3 = (IContextMenu3)Marshal.GetTypedObjectForIUnknown(newContextMenuPtr3, typeof(IContextMenu3)); } catch (Exception) { } } ShellFolders.AppendMenu(contextMenu, ShellFolders.MFT.SEPARATOR, 0, string.Empty); ShellFolders.AppendMenu(contextMenu, 0, (int)CairoContextMenuItem.Properties, Localization.DisplayString.sInterface_Properties); ShellFolders.AppendMenu(contextMenu, ShellFolders.MFT.SEPARATOR, 0, string.Empty); if (!Startup.IsCairoRunningAsShell) { ShellFolders.AppendMenu(contextMenu, 0, (int)CairoContextMenuItem.DisplaySettings, Localization.DisplayString.sDesktop_DisplaySettings); } ShellFolders.AppendMenu(contextMenu, 0, (int)CairoContextMenuItem.Personalize, Localization.DisplayString.sDesktop_Personalize); CairoContextMenuItem selected = (CairoContextMenuItem)ShellFolders.TrackPopupMenuEx( contextMenu, ShellFolders.TPM.RETURNCMD, this.x, this.y, this.Handle, IntPtr.Zero); if ((int)selected >= ShellFolders.CMD_FIRST) { string command = ""; switch (selected) { case CairoContextMenuItem.OpenInNewWindow: command = "openWithShell"; break; case CairoContextMenuItem.AddToStacks: command = "addStack"; break; case CairoContextMenuItem.RemoveFromStacks: command = "removeStack"; break; case CairoContextMenuItem.Personalize: command = "personalize"; break; case CairoContextMenuItem.DisplaySettings: command = "displaySettings"; break; case CairoContextMenuItem.Properties: command = "properties"; ShellFolders.InvokeCommand( folder, parentShellFolder, new IntPtr[] { folderPidl }, command, new Point(this.x, this.y)); break; case CairoContextMenuItem.Paste: command = "paste"; ShellFolders.InvokeCommand( folder, parentShellFolder, new IntPtr[] { folderPidl }, command, new Point(this.x, this.y)); break; default: if ((uint)selected <= ShellFolders.CMD_LAST) { ShellFolders.InvokeCommand( newContextMenu, (uint)selected - ShellFolders.CMD_FIRST, this.folder, new Point(this.x, this.y)); } break; } if (this.folderItemSelected != null) { folderItemSelected(command, folder); } } } catch (Exception) { } finally { if (newContextMenu != null) { Marshal.FinalReleaseComObject(newContextMenu); newContextMenu = null; } if (newContextMenu2 != null) { Marshal.FinalReleaseComObject(newContextMenu2); newContextMenu2 = null; } if (newContextMenu3 != null) { Marshal.FinalReleaseComObject(newContextMenu3); newContextMenu3 = null; } if (contextMenu != null) { ShellFolders.DestroyMenu(contextMenu); } if (viewSubMenu != null) { ShellFolders.DestroyMenu(viewSubMenu); } if (newContextMenuPtr != IntPtr.Zero) { Marshal.Release(newContextMenuPtr); } if (newContextMenuPtr2 != IntPtr.Zero) { Marshal.Release(newContextMenuPtr2); } if (newContextMenuPtr3 != IntPtr.Zero) { Marshal.Release(newContextMenuPtr3); } newSubmenuPtr = IntPtr.Zero; Marshal.FreeCoTaskMem(folderPidl); Marshal.FreeCoTaskMem(folderRelPidl); folderPidl = IntPtr.Zero; folderRelPidl = IntPtr.Zero; } }
public static void SetFilterFormat(AMMediaType streamFormat, IBaseFilter filter) { if (filter == null) { throw new ArgumentNullException("filter"); } int hr; IEnumPins pinsEnum = null; try { hr = filter.EnumPins(out pinsEnum); DsError.ThrowExceptionForHR(hr); if (pinsEnum == null) { throw new SplicerException(Resources.ErrorPinsEnumeratorIsNull); } var pins = new IPin[1]; while (true) { try { int fetched = 0; IntPtr pcFetched = Marshal.AllocCoTaskMem(4); try { hr = pinsEnum.Next(pins.Length, pins, pcFetched); DsError.ThrowExceptionForHR(hr); fetched = Marshal.ReadInt32(pcFetched); } finally { Marshal.FreeCoTaskMem(pcFetched); } if (fetched == 1) { // we have something IPin pin = pins[0]; string queryId; hr = pin.QueryId(out queryId); DsError.ThrowExceptionForHR(hr); PinInfo pinInfo; hr = pin.QueryPinInfo(out pinInfo); DsError.ThrowExceptionForHR(hr); if (pinInfo.dir != PinDirection.Output) { continue; } var streamConfig = (IAMStreamConfig)pin; hr = streamConfig.SetFormat(streamFormat); DsError.ThrowExceptionForHR(hr); } else { break; } } finally { if (pins[0] != null) { Marshal.ReleaseComObject(pins[0]); } pins[0] = null; } } } finally { if (pinsEnum != null) { Marshal.ReleaseComObject(pinsEnum); } } }
public static List <ADLDisplayInfo> GetAllDisplays() { int ADLRet; int NumberOfDisplays = 0; var DisplayInfoData = new List <ADLDisplayInfo>(); var OSAdapterInfoData = GetAdapters(); if (OSAdapterInfoData == null || !OSAdapterInfoData.Value.ADLAdapterInfo.Any()) { return(DisplayInfoData); } var primaryAdapter = OSAdapterInfoData.Value.ADLAdapterInfo.First(); ADLDisplayInfo oneDisplayInfo = new ADLDisplayInfo(); if (null != ADL.ADL_Display_DisplayInfo_Get) { IntPtr DisplayBuffer = IntPtr.Zero; int j = 0; // Force the display detection and get the Display Info. Use 0 as last parameter to NOT force detection ADLRet = ADL.ADL_Display_DisplayInfo_Get(primaryAdapter.AdapterIndex, ref NumberOfDisplays, out DisplayBuffer, 1); if (ADL.ADL_SUCCESS == ADLRet) { for (j = 0; j < NumberOfDisplays; j++) { oneDisplayInfo = (ADLDisplayInfo)Marshal.PtrToStructure(new IntPtr(DisplayBuffer.ToInt32() + j * Marshal.SizeOf(oneDisplayInfo)), oneDisplayInfo.GetType()); DisplayInfoData.Add(oneDisplayInfo); } Console.WriteLine("\nTotal Number of Displays supported: " + NumberOfDisplays.ToString()); Console.WriteLine("\nDispID AdpID Type OutType CnctType Connected Mapped InfoValue DisplayName "); for (j = 0; j < NumberOfDisplays; j++) { int InfoValue = DisplayInfoData[j].DisplayInfoValue; string StrConnected = (1 == (InfoValue & 1)) ? "Yes" : "No "; string StrMapped = (2 == (InfoValue & 2)) ? "Yes" : "No "; int AdpID = DisplayInfoData[j].DisplayID.DisplayLogicalAdapterIndex; string StrAdpID = (AdpID < 0) ? "--" : AdpID.ToString("d2"); Console.WriteLine(DisplayInfoData[j].DisplayID.DisplayLogicalIndex.ToString() + " " + StrAdpID + " " + DisplayInfoData[j].DisplayType.ToString() + " " + DisplayInfoData[j].DisplayOutputType.ToString() + " " + DisplayInfoData[j].DisplayConnector.ToString() + " " + StrConnected + " " + StrMapped + " " + InfoValue.ToString("x4") + " " + DisplayInfoData[j].DisplayName.ToString()); } Console.WriteLine(); } else { Console.WriteLine("ADL_Display_DisplayInfo_Get() returned error code " + ADLRet.ToString()); } // Release the memory for the DisplayInfo structure if (IntPtr.Zero != DisplayBuffer) { Marshal.FreeCoTaskMem(DisplayBuffer); } } return(DisplayInfoData); }
static int Main(string [] args) { string assembly = null; string directory = null; string lockfile = null; string name = null; string logname = null; var assebmlyArgs = new List <string>(); foreach (string s in args) { if (s.Length > 3 && s [0] == '-' && s [2] == ':') { string arg = s.Substring(3); switch (Char.ToLower(s [1])) { case 'd': directory = arg; break; case 'l': lockfile = arg; break; case 'n': name = arg; break; case 'm': logname = arg; break; default: Usage(); break; } } else { if (assembly != null) { assebmlyArgs.Add(s); } else { assembly = s; } } } if (logname == null) { logname = assembly; } if (assembly == null) { error(logname, "Assembly name is missing"); Usage(); } if (directory != null) { if (Syscall.chdir(directory) != 0) { error(logname, "Could not change to directory {0}", directory); return(1); } } // Use lockfile to allow only one instance if (lockfile == null) { lockfile = String.Format("/tmp/{0}.lock", Path.GetFileName(assembly)); } int lfp = Syscall.open(lockfile, OpenFlags.O_RDWR | OpenFlags.O_CREAT | OpenFlags.O_EXCL, FilePermissions.S_IRUSR | FilePermissions.S_IWUSR | FilePermissions.S_IRGRP); if (lfp < 0) { // Provide some useful info if (File.Exists(lockfile)) { error(logname, String.Format("Lock file already exists: {0}", lockfile)); } else { error(logname, String.Format("Cannot open/create lock file exclusively: {0}", lockfile)); } return(1); } if (Syscall.lockf(lfp, LockfCommand.F_TLOCK, 0) < 0) { info(logname, "Daemon is already running."); return(0); } try { // Write pid to lock file string pid = Syscall.getpid().ToString() + Environment.NewLine; IntPtr buf = Marshal.StringToCoTaskMemAnsi(pid); Syscall.write(lfp, buf, (ulong)pid.Length); Marshal.FreeCoTaskMem(buf); // Create new AppDomain to run service AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationBase = Environment.CurrentDirectory; setup.ConfigurationFile = Path.Combine(Environment.CurrentDirectory, assembly + ".config"); setup.ApplicationName = logname; AppDomain newDomain = AppDomain.CreateDomain(logname, AppDomain.CurrentDomain.Evidence, setup); MonoServiceRunner rnr = newDomain.CreateInstanceAndUnwrap( typeof(MonoServiceRunner).Assembly.FullName, typeof(MonoServiceRunner).FullName, true, BindingFlags.Default, null, new object [] { assembly, name, logname, assebmlyArgs.ToArray() }, null, null, null) as MonoServiceRunner; if (rnr == null) { error(logname, "Internal Mono Error: Could not create MonoServiceRunner."); return(1); } return(rnr.StartService()); } finally { // Remove lock file when done if (File.Exists(lockfile)) { File.Delete(lockfile); } } }
/// <summary> /// Invokes the specified generator /// </summary> /// <param name="fileNode">The node on which to invoke the generator.</param> public virtual void InvokeGenerator(FileNode fileNode) { if (fileNode == null) { throw new ArgumentNullException("fileNode"); } SingleFileGeneratorNodeExtenderProperties nodeproperties = fileNode.NodeProperties.Extender(SingleFileGeneratorNodeExtenderProvider.Name) as SingleFileGeneratorNodeExtenderProperties; if (nodeproperties == null) { throw new InvalidOperationException(); } string customToolProgID = nodeproperties.CustomTool; if (string.IsNullOrEmpty(customToolProgID)) { return; } string customToolNamespace = nodeproperties.CustomToolNamespace; try { if (!this.runningGenerator) { //Get the buffer contents for the current node string moniker = fileNode.GetMKDocument(); this.runningGenerator = true; //Get the generator IVsSingleFileGenerator generator; int generateDesignTimeSource; int generateSharedDesignTimeSource; int generateTempPE; SingleFileGeneratorFactory factory = new SingleFileGeneratorFactory(this.projectMgr.ProjectGuid, this.projectMgr.Site); ErrorHandler.ThrowOnFailure(factory.CreateGeneratorInstance(customToolProgID, out generateDesignTimeSource, out generateSharedDesignTimeSource, out generateTempPE, out generator)); //Check to see if the generator supports siting IObjectWithSite objWithSite = generator as IObjectWithSite; if (objWithSite != null) { objWithSite.SetSite(fileNode.OleServiceProvider); } //Determine the namespace if (string.IsNullOrEmpty(customToolNamespace)) { customToolNamespace = this.ComputeNamespace(moniker); } //Run the generator IntPtr[] output = new IntPtr[1]; output[0] = IntPtr.Zero; uint outPutSize; string extension; ErrorHandler.ThrowOnFailure(generator.DefaultExtension(out extension)); //Find if any dependent node exists string dependentNodeName = Path.GetFileNameWithoutExtension(fileNode.FileName) + extension; HierarchyNode dependentNode = fileNode.FirstChild; while (dependentNode != null) { if (string.Equals(dependentNode.ItemNode.GetMetadata(ProjectFileConstants.DependentUpon), fileNode.FileName, StringComparison.OrdinalIgnoreCase)) { dependentNodeName = ((FileNode)dependentNode).FileName; break; } dependentNode = dependentNode.NextSibling; } //If you found a dependent node. if (dependentNode != null) { //Then check out the node and dependent node from SCC if (!this.CanEditFile(dependentNode.GetMKDocument())) { throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED); } } else //It is a new node to be added to the project { // Check out the project file if necessary. if (!this.projectMgr.QueryEditProjectFile(false)) { throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED); } } IVsTextStream stream; string inputFileContents = this.GetBufferContents(moniker, out stream); ErrorHandler.ThrowOnFailure(generator.Generate(moniker, inputFileContents, customToolNamespace, output, out outPutSize, this)); byte[] data = new byte[outPutSize]; if (output[0] != IntPtr.Zero) { Marshal.Copy(output[0], data, 0, (int)outPutSize); Marshal.FreeCoTaskMem(output[0]); } //Todo - Create a file and add it to the Project this.UpdateGeneratedCodeFile(fileNode, data, (int)outPutSize, dependentNodeName); } } finally { this.runningGenerator = false; } }