示例#1
0
        public override void sendVectorToSim <ValueType>(string path, ValueType[] value)
        {
            //Need to upgrade to 2D array for Excel
            object[,] sendValueArray = (Object[, ]) new Object[1, value.Length];
            for (int ii = 0; ii < value.Length; ++ii)
            {
                sendValueArray[0, ii] = (object)value[ii];
            }

            try
            {
                string   worksheetName;
                string   cellName;
                string[] addressSplit = path.Split(new char[] { pathSeperator }, 2);
                if (addressSplit.Length != 2)
                {
                    throw new System.IO.IOException(String.Format("Mal-formed Excel address string {0}", path));
                }
                worksheetName = addressSplit[0];
                cellName      = addressSplit[1];

                Excel.Sheets    xlWorksheets = (Excel.Sheets)o_xlWorkbook.Worksheets;
                Excel.Worksheet xlWorksheet  = (Excel.Worksheet)xlWorksheets[worksheetName];
                Excel.Range     xlRange      = xlWorksheet.get_Range(cellName, resolveVectorPath(cellName, value.Length - 1));
                xlRange.Value = sendValueArray;

                Marshal.ReleaseComObject(xlRange);
                Marshal.ReleaseComObject(xlWorksheet);
                Marshal.ReleaseComObject(xlWorksheets);
            }
            catch
            {
                throw new System.IO.IOException("Could not set " + path + " to " + Convert.ToString(value) + ".");
            }
        }
示例#2
0
        internal static EncoderParameters ConvertFromMemory(IntPtr memory)
        {
            if (memory == IntPtr.Zero)
            {
                throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.InvalidParameter);
            }

            int count = Marshal.ReadIntPtr(memory).ToInt32();

            EncoderParameters p = new EncoderParameters(count);
            int  size           = Marshal.SizeOf(typeof(EncoderParameter));
            long arrayOffset    = (long)memory + Marshal.SizeOf(typeof(IntPtr));

            IntSecurity.UnmanagedCode.Assert();

            try {
                for (int i = 0; i < count; i++)
                {
                    Guid guid                      = (Guid)UnsafeNativeMethods.PtrToStructure((IntPtr)(i * size + arrayOffset), typeof(Guid));
                    int  numberOfValues            = Marshal.ReadInt32((IntPtr)(i * size + arrayOffset + 16));
                    EncoderParameterValueType type = (EncoderParameterValueType)Marshal.ReadInt32((IntPtr)(i * size + arrayOffset + 20));
                    IntPtr value                   = Marshal.ReadIntPtr((IntPtr)(i * size + arrayOffset + 24));

                    p.param[i] = new EncoderParameter(new Encoder(guid), numberOfValues, type, value);
                }
            }
            finally {
                System.Security.CodeAccessPermission.RevertAssert();
            }

            return(p);
        }
示例#3
0
        public override void closeSim()
        {
            if (simulatorStatus == sinter_simulatorStatus.si_OPEN)
            {
                try
                {
                    closeDocument();
                    o_xlApp.Quit();

                    GC.Collect();
                    GC.WaitForPendingFinalizers();

                    killExcel();  //If it's still open after quit, kill it dead.

                    Marshal.FinalReleaseComObject(o_xlApp);
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    o_xlApp = null;
                }
                catch (Exception ex)
                {
                    simulatorStatus = sinter_simulatorStatus.si_ERROR;
                    throw ex;
                }
                simulatorStatus = sinter_simulatorStatus.si_CLOSED;
            }
        }
示例#4
0
        public override void recvVectorFromSim <ValueType>(string path, int[] indicies, ValueType[] value)
        {
            try
            {
                string   worksheetName;
                string   cellName;
                string[] addressSplit = path.Split(new char[] { pathSeperator }, 2);
                if (addressSplit.Length != 2)
                {
                    throw new System.IO.IOException(String.Format("Mal-formed Excel address string {0}", path));
                }
                worksheetName = addressSplit[0];
                cellName      = addressSplit[1];

                Excel.Sheets    xlWorksheets = (Excel.Sheets)o_xlWorkbook.Worksheets;
                Excel.Worksheet xlWorksheet  = (Excel.Worksheet)xlWorksheets[worksheetName];
                Excel.Range     xlRange      = xlWorksheet.get_Range(cellName, resolveVectorPath(cellName, value.Length - 1)); //Grab the whole range

                object[,] excelArray = (object[, ])xlRange.get_Value(Excel.XlRangeValueDataType.xlRangeValueDefault);

                for (int ii = 0; ii < value.Length; ++ii)
                {
                    value[ii] = (ValueType)excelArray[1, ii + 1];
                }

                Marshal.ReleaseComObject(xlRange);
                Marshal.ReleaseComObject(xlWorksheet);
                Marshal.ReleaseComObject(xlWorksheets);
            }
            catch
            {
                throw new System.IO.IOException("Could not get value from " + path);
            }
        }
示例#5
0
        public override void sendValueToSim <ValueType>(string path, ValueType value)
        {
            try
            {
                string   worksheetName;
                string   cellName;
                string[] addressSplit = path.Split(new char[] { pathSeperator }, 2);
                if (addressSplit.Length != 2)
                {
                    throw new System.IO.IOException(String.Format("Mal-formed Excel address string {0}", path));
                }
                worksheetName = addressSplit[0];
                cellName      = addressSplit[1];

                Excel.Sheets    xlWorksheets = (Excel.Sheets)o_xlWorkbook.Worksheets;
                Excel.Worksheet xlWorksheet  = (Excel.Worksheet)xlWorksheets[worksheetName];
                Excel.Range     xlRange      = xlWorksheet.get_Range(cellName);
                xlRange.Value = value;
                Marshal.ReleaseComObject(xlRange);
                Marshal.ReleaseComObject(xlWorksheet);
                Marshal.ReleaseComObject(xlWorksheets);
            }
            catch (Exception)
            {
                throw new System.IO.IOException("Could not set " + path + " to " + Convert.ToString(value) + ".");
            }
        }
示例#6
0
 private void closeDocument()
 {
     Debug.WriteLine("o_xlWorkbook.closeDocument", GetType().Name);
     o_xlWorkbook.Close(false, Type.Missing, Type.Missing);
     Debug.WriteLine("Marshal.ReleaseComObject: o_xlWorkbook", GetType().Name);
     Marshal.ReleaseComObject(o_xlWorkbook);
     o_xlWorkbook = null;
 }
示例#7
0
 private static void ReleaseCom(object obj)
 {
     if (obj != null && Marshal.IsComObject(obj))
     {
         Marshal.ReleaseComObject(obj);
     }
     obj = null;
 }
示例#8
0
        /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton.GetTBBUTTONINFO"]/*' />
        /// <devdoc>
        ///     Returns a TBBUTTONINFO object that represents this ToolBarButton.
        /// </devdoc>
        internal NativeMethods.TBBUTTONINFO GetTBBUTTONINFO(bool updateText, int newCommandId) {

            NativeMethods.TBBUTTONINFO button = new NativeMethods.TBBUTTONINFO();
            button.cbSize = Marshal.SizeOf(typeof(NativeMethods.TBBUTTONINFO));
            button.dwMask = NativeMethods.TBIF_IMAGE
                            | NativeMethods.TBIF_STATE | NativeMethods.TBIF_STYLE;

            // Comctl on Win98 interprets null strings as empty strings, which forces
            // the button to leave space for text.  The only workaround is to avoid having comctl 
            // update the text.
            if (updateText) {
                button.dwMask |= NativeMethods.TBIF_TEXT;
            }

            button.iImage = ImageIndexer.ActualIndex;

            if (newCommandId != commandId) {
                commandId = newCommandId;
                button.idCommand = newCommandId;
                button.dwMask |= NativeMethods.TBIF_COMMAND;
            }

            // set up the state of the button
            //
            button.fsState = 0;
            if (enabled) button.fsState |= NativeMethods.TBSTATE_ENABLED;
            if (partialPush && style == ToolBarButtonStyle.ToggleButton) button.fsState |= NativeMethods.TBSTATE_INDETERMINATE;
            if (pushed) button.fsState |= NativeMethods.TBSTATE_CHECKED;
            if (!visible) button.fsState |= NativeMethods.TBSTATE_HIDDEN;

            // set the button style
            //
            switch (style) {
                case ToolBarButtonStyle.PushButton:
                    button.fsStyle = NativeMethods.TBSTYLE_BUTTON;
                    break;
                case ToolBarButtonStyle.ToggleButton:
                    button.fsStyle = NativeMethods.TBSTYLE_CHECK;
                    break;
                case ToolBarButtonStyle.Separator:
                    button.fsStyle = NativeMethods.TBSTYLE_SEP;
                    break;
            }


            if (text == null) {
                button.pszText = Marshal.StringToHGlobalAuto("\0\0");
            }
            else {
                string textValue = this.text;
                PrefixAmpersands(ref textValue);
                button.pszText = Marshal.StringToHGlobalAuto(textValue);
            }

            return button;
        }
        /// <summary>
        /// Collect COM objects
        /// </summary>
        private void GColectorStart()
        {
            int collectorTryCount = 0;

            do
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                collectorTryCount++;
            }while (Marshal.AreComObjectsAvailableForCleanup() && collectorTryCount < 20);
        }
示例#10
0
        private void openDocument()
        {
            Debug.WriteLine("openDocument", GetType().Name);
            var fname = System.IO.Path.Combine(workingDir, simFile);
            //Excel works better with an absolute path.
            string speadsheet = System.IO.Path.GetFullPath(fname);

            Excel.Workbooks workbooks = o_xlApp.Workbooks;
            Debug.WriteLine("workbooks.Open", GetType().Name);
            o_xlWorkbook = workbooks.Open(speadsheet, 0, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, false, false, 0, true, 1, 0);
            Debug.WriteLine("Marshal.ReleaseComObject: workbooks", GetType().Name);
            Marshal.ReleaseComObject(workbooks);
        }
        /// <include file='doc\ShellDocumentManager.uex' path='docs/doc[@for="ShellDocumentManager.GetHostFromFrame"]/*' />
        /// <devdoc>
        ///     Private helper buddy that tries to get an IDesignerHost from a window frame.  This will
        ///     return null if the host could not be resolved.
        /// </devdoc>
        private IDesignerHost GetHostFromFrame(IVsWindowFrame frame)
        {
            if (frame != null)
            {
                // Get the document view and see if it's one of ours
                //
                Object view = null;
                int    hr   = NativeMethods.S_OK;
#if GETPROPERTY_MARSHAL
                hr = frame.GetProperty(__VSFPROPID.VSFPROPID_DocView, ref view);
                if (!NativeMethods.Succeeded(hr))
                {
                    Debug.Fail("Error getting document view for IVsWindowFrame... hresult=0x" + Convert.ToString(hr, 16));
                    throw new COMException("Error getting document view", hr);
                }
#else
                view = frame.GetProperty(__VSFPROPID.VSFPROPID_DocView);
#endif

                IDesignerHost host = null;

                if (view is IServiceProvider)
                {
                    host = ((IServiceProvider)view).GetService(typeof(IVSMDDesigner)) as IDesignerHost;
                }

                if (host == null && view is NativeMethods.IOleServiceProvider)
                {
                    // We query the view for IVSMDDesigner, which will succeed for HTMED and vswindow panes,
                    // etc.
                    //
                    Guid tmpGuid = (typeof(IVSMDDesigner)).GUID;

                    IntPtr pUnk;
                    hr = ((NativeMethods.IOleServiceProvider)view).QueryService(ref tmpGuid, ref tmpGuid, out pUnk);
                    if (NativeMethods.Failed(hr) || pUnk == (IntPtr)0)
                    {
                        Debug.Assert(NativeMethods.Failed(hr), "QueryService succeeded but reurned a NULL pointer.");
                        return(null);
                    }

                    object obj = Marshal.GetObjectForIUnknown(pUnk);
                    Marshal.Release(pUnk);
                    host = (IDesignerHost)obj;
                }

                return(host);
            }

            return(null);
        }
示例#12
0
 private static Application GetOutlook()
 {
     try
     {
         //outlook needs to be clicked on (foreground) once before this script works....weird :/
         //not reliable way to check
         var ol = (Application)Marshal.GetActiveObject("Outlook.Application");
         return(ol);
     }
     catch (COMException ex) when(ex.HResult == -2147221021)  //operation invalid
     {
         return(null);
     }
 }
        /// <include file='doc\SelectionService.uex' path='docs/doc[@for="SelectionService.GetObjects"]/*' />
        /// <devdoc>
        ///     Returns an array of objects.
        /// </devdoc>
        void ISelectionContainer.GetObjects(int flags, int cObjects, IntPtr objects)
        {
            int cnt = 0;

            switch (flags)
            {
            case __GETOBJS.ALL:
                if (container != null)
                {
                    ComponentCollection components = container.Components;
                    foreach (IComponent comp in components)
                    {
                        cnt++;

                        if (cnt > cObjects)
                        {
                            break;
                        }

                        Marshal.WriteIntPtr(objects, Marshal.GetIUnknownForObject(comp));
                        objects = (IntPtr)((long)objects + IntPtr.Size);
                    }
                }
                break;

            case __GETOBJS.SELECTED:
                ICollection comps = GetSelectedComponents();

                int ipSize = IntPtr.Size;

                foreach (object o in comps)
                {
                    cnt++;

                    if (cnt > cObjects)
                    {
                        break;
                    }

                    Marshal.WriteIntPtr(objects, Marshal.GetIUnknownForObject(o));

                    objects = (IntPtr)((long)objects + ipSize);
                }
                break;

            default:
                throw new COMException("Invalid flags", NativeMethods.E_INVALIDARG);
            }
        }
示例#14
0
        // VSWhidbey 177016: This is necessary to get the width of the buttons in the toolbar,
        // including the width of separators, so that we can accurately position the tooltip adjacent
        // to the currently hot button when the user uses keyboard navigation to access the toolbar.
        internal int GetButtonWidth() {

            // Assume that this button is the same width as the parent's ButtonSize's Width
            int buttonWidth = Parent.ButtonSize.Width;
            
            NativeMethods.TBBUTTONINFO button = new NativeMethods.TBBUTTONINFO();
            button.cbSize = Marshal.SizeOf(typeof(NativeMethods.TBBUTTONINFO));
            button.dwMask = NativeMethods.TBIF_SIZE;
            
            int buttonID = (int)UnsafeNativeMethods.SendMessage(new HandleRef(Parent, Parent.Handle), NativeMethods.TB_GETBUTTONINFO, commandId, ref button);
            if (buttonID != -1) {
                buttonWidth = button.cx;
            }
            
            return buttonWidth;
        }
示例#15
0
        protected virtual object CreateDocumentView(string documentMoniker, string physicalView, IVsHierarchy hierarchy, uint itemid, IVsTextLines textLines, bool createdDocData, out string editorCaption, out Guid cmdUI)
        {
            //Init out params
            editorCaption = string.Empty;
            cmdUI         = Guid.Empty;

            if (string.IsNullOrEmpty(physicalView))
            {
                // create code window as default physical view
                return(CreateCodeView(documentMoniker, textLines, createdDocData, ref editorCaption, ref cmdUI));
            }

            // We couldn't create the view
            // Return special error code so VS can try another editor factory.
            throw Marshal.GetExceptionForHR(VSConstants.VS_E_UNSUPPORTEDFORMAT);
        }
示例#16
0
        // This is necessary to get the width of the buttons in the toolbar,
        // including the width of separators, so that we can accurately position the tooltip adjacent
        // to the currently hot button when the user uses keyboard navigation to access the toolbar.
        internal int GetButtonWidth()
        {
            // Assume that this button is the same width as the parent's ButtonSize's Width
            int buttonWidth = Parent.ButtonSize.Width;

            var button = new ComCtl32.TBBUTTONINFOW
            {
                cbSize = (uint)Marshal.SizeOf <ComCtl32.TBBUTTONINFOW>(),
                dwMask = ComCtl32.TBIF.SIZE
            };

            int buttonID = (int)User32.SendMessageW(Parent, (User32.WindowMessage)ComCtl32.TB.GETBUTTONINFOW, (IntPtr)commandId, ref button);

            if (buttonID != -1)
            {
                buttonWidth = button.cx;
            }

            return(buttonWidth);
        }
示例#17
0
        public void Open(string path)
        {
            string parentFolder = Path.GetDirectoryName(path);
            string baseFilename = Path.GetFileName(path);

            parentFolder ??= "";

            var finderDatStream =
                new FileStream(Path.Combine(parentFolder, FINDER_INFO), FileMode.Open, FileAccess.Read);

            while (finderDatStream.Position + 0x5C <= finderDatStream.Length)
            {
                var    datEntry  = new PcExchangeEntry();
                byte[] datEntryB = new byte[Marshal.SizeOf(datEntry)];
                finderDatStream.Read(datEntryB, 0, Marshal.SizeOf(datEntry));
                datEntry = Helpers.Marshal.ByteArrayToStructureBigEndian <PcExchangeEntry>(datEntryB);

                string macName = StringHandlers.PascalToString(datEntry.macName, Encoding.GetEncoding("macintosh"));

                byte[] tmpDosNameB = new byte[8];
                byte[] tmpDosExtB  = new byte[3];
                Array.Copy(datEntry.dosName, 0, tmpDosNameB, 0, 8);
                Array.Copy(datEntry.dosName, 8, tmpDosExtB, 0, 3);

                string dosName = Encoding.ASCII.GetString(tmpDosNameB).Trim() + "." +
                                 Encoding.ASCII.GetString(tmpDosExtB).Trim();

                string dosNameLow = dosName.ToLower(CultureInfo.CurrentCulture);

                if (baseFilename != macName &&
                    baseFilename != dosName &&
                    baseFilename != dosNameLow)
                {
                    continue;
                }

                if (File.Exists(Path.Combine(parentFolder, macName ?? throw new InvalidOperationException())))
                {
                    _dataPath = Path.Combine(parentFolder, macName);
                }
示例#18
0
        internal IntPtr ConvertToMemory()
        {
            int size = Marshal.SizeOf(typeof(EncoderParameter));

            Debug.Assert(size == (16 + 4 + 4 + 4), "wrong size! (" + size + ")");

            IntPtr memory = (IntPtr)((long)Marshal.AllocHGlobal(param.Length * size + Marshal.SizeOf(typeof(Int32))));

            if (memory == IntPtr.Zero)
            {
                throw SafeNativeMethods.StatusException(SafeNativeMethods.OutOfMemory);
            }

            Marshal.WriteInt32(memory, param.Length);

            for (int i = 0; i < param.Length; i++)
            {
                Marshal.StructureToPtr(param[i], (IntPtr)((long)memory + Marshal.SizeOf(typeof(Int32)) + i * size), false);
            }

            return(memory);
        }
示例#19
0
        protected virtual IVsTextLines GetTextBuffer(System.IntPtr docDataExisting, string filename)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            IVsTextLines textLines;

            if (docDataExisting == IntPtr.Zero)
            {
                // Create a new IVsTextLines buffer.
                Type textLinesType = typeof(IVsTextLines);
                Guid riid          = textLinesType.GUID;
                Guid clsid         = typeof(VsTextBufferClass).GUID;
                textLines = _package.CreateInstance(ref clsid, ref riid, textLinesType) as IVsTextLines;

                // set the buffer's site
                ((IObjectWithSite)textLines).SetSite(_serviceProvider.GetService(typeof(IOleServiceProvider)));
            }
            else
            {
                // Use the existing text buffer
                object dataObject = Marshal.GetObjectForIUnknown(docDataExisting);
                textLines = dataObject as IVsTextLines;
                if (textLines == null)
                {
                    // Try get the text buffer from textbuffer provider
                    if (dataObject is IVsTextBufferProvider textBufferProvider)
                    {
                        textBufferProvider.GetTextBuffer(out textLines);
                    }
                }
                if (textLines == null)
                {
                    // Unknown docData type then, so we have to force VS to close the other editor.
                    throw Marshal.GetExceptionForHR(VSConstants.VS_E_INCOMPATIBLEDOCDATA);
                }
            }
            return(textLines);
        }
示例#20
0
        internal static EncoderParameters ConvertFromMemory(IntPtr memory)
        {
            if (memory == IntPtr.Zero)
            {
                throw SafeNativeMethods.StatusException(SafeNativeMethods.InvalidParameter);
            }

            int count;

            count = Marshal.ReadInt32(memory);

            EncoderParameters p;

            p = new EncoderParameters(count);
            int size = (int)Marshal.SizeOf(typeof(EncoderParameter));

            for (int i = 0; i < count; i++)
            {
                Guid guid;
                guid = (Guid)UnsafeNativeMethods.PtrToStructure((IntPtr)(i * size + (long)memory + 4), typeof(Guid));

                int NumberOfValues;
                NumberOfValues = Marshal.ReadInt32((IntPtr)(i * size + (long)memory + 4 + size - 12));

                int Type;
                Type = Marshal.ReadInt32((IntPtr)(i * size + (long)memory + 4 + size - 8));

                int Value;
                Value = Marshal.ReadInt32((IntPtr)(i * size + (long)memory + 4 + size - 4));

                p.param[i] = new EncoderParameter(new Encoder(guid),
                                                  NumberOfValues,
                                                  Type,
                                                  Value);
            }

            return(p);
        }
示例#21
0
        /// <devdoc>
        ///     Copy the EncoderParameters data into a chunk of memory to be consumed by native GDI+ code.
        ///
        ///     We need to marshal the EncoderParameters info from/to native GDI+ ourselve since the definition of the managed/unmanaged classes
        ///     are different and the native class is a bit weird. The native EncoderParameters class is defined in GDI+ as follows:
        ///
        ///      class EncoderParameters {
        ///          UINT Count;                      // Number of parameters in this structure
        ///          EncoderParameter Parameter[1];   // Parameter values
        ///      };
        ///
        ///     We don't have the 'Count' field since the managed array contains it. In order for this structure to work with more than one
        ///     EncoderParameter we need to preallocate memory for the extra n-1 elements, something like this:
        ///
        ///         EncoderParameters* pEncoderParameters = (EncoderParameters*) malloc(sizeof(EncoderParameters) + (n-1) * sizeof(EncoderParameter));
        ///
        ///     Also, in 64-bit platforms, 'Count' is aligned in 8 bytes (4 extra padding bytes) so we use IntPtr instead of Int32 to account for
        ///     that (See VSW#451333).
        /// </devdoc>
        internal IntPtr ConvertToMemory()
        {
            int size = Marshal.SizeOf(typeof(EncoderParameter));

            int    length = param.Length;
            IntPtr memory = Marshal.AllocHGlobal(checked (length * size + Marshal.SizeOf(typeof(IntPtr))));

            if (memory == IntPtr.Zero)
            {
                throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.OutOfMemory);
            }

            Marshal.WriteIntPtr(memory, (IntPtr)length);

            long arrayOffset = checked ((long)memory + Marshal.SizeOf(typeof(IntPtr)));

            for (int i = 0; i < length; i++)
            {
                Marshal.StructureToPtr(param[i], (IntPtr)(arrayOffset + i * size), false);
            }

            return(memory);
        }
示例#22
0
        private object recvValueFromSimInternal(string path)
        {
            if (path == null || path.Contains("*"))    //Paths that contain "*" are incomplete
            {
                return(null);
            }
            try
            {
                string   worksheetName;
                string   cellName;
                string[] addressSplit = path.Split(new char[] { pathSeperator }, 2);
                Object   retVal;
                if (addressSplit.Length != 2)
                {
                    return(null);  //Incomplete path
                }
                worksheetName = addressSplit[0];
                cellName      = addressSplit[1];

                Excel.Sheets    xlWorksheets = (Excel.Sheets)o_xlWorkbook.Worksheets;
                Excel.Worksheet xlWorksheet  = (Excel.Worksheet)xlWorksheets[worksheetName];
                Excel.Range     xlRange      = xlWorksheet.get_Range(cellName);
                retVal = xlRange.Value;
                if (retVal is decimal) //Sinter doesn't really support decimal type, make do with double
                {
                    retVal = Convert.ToDouble(retVal);
                }
                Marshal.ReleaseComObject(xlRange);
                Marshal.ReleaseComObject(xlWorksheet);
                Marshal.ReleaseComObject(xlWorksheets);
                return(retVal);
            }
            catch
            {
                throw new System.IO.IOException("Could not get value from " + path);
            }
        }
示例#23
0
        public override void sendValueToSim <ValueType>(string path, int ii, ValueType value)
        {
            try
            {
                string   worksheetName;
                string   cellName;
                string[] addressSplit = path.Split(new char[] { pathSeperator }, 2);
                if (addressSplit.Length != 2)
                {
                    throw new System.IO.IOException(String.Format("Mal-formed Excel address string {0}", path));
                }
                worksheetName = addressSplit[0];
                cellName      = addressSplit[1];

                //The address is the base of the vector, add ii to the int component to get the individual address.
                string cellLetter    = Regex.Match(cellName, "[a-zA-Z]+").ToString();
                string cellNumber    = Regex.Match(cellName, "[0-9]+").ToString();
                int    cellNumberInt = Convert.ToInt32(cellNumber);

                cellNumberInt += ii;

                string newCellName = string.Format("${0}${1}", cellLetter, cellNumberInt);

                Excel.Sheets    xlWorksheets = (Excel.Sheets)o_xlWorkbook.Worksheets;
                Excel.Worksheet xlWorksheet  = (Excel.Worksheet)xlWorksheets[worksheetName];
                Excel.Range     xlRange      = xlWorksheet.get_Range(newCellName);
                xlRange.Value = value;
                Marshal.ReleaseComObject(xlRange);
                Marshal.ReleaseComObject(xlWorksheet);
                Marshal.ReleaseComObject(xlWorksheets);
            }
            catch (Exception)
            {
                throw new System.IO.IOException("Could not set " + path + " to " + Convert.ToString(value) + ".");
            }
        }
        /// <summary>
        /// Creating Hyper Links of every component in TOC sheet and adding corresponding description against them.
        /// Also Adding Back To Index links and Source file Name texts in every sheets.
        /// </summary>
        /// <param name="PivotOutputReportFullPath"></param>
        /// <param name="htHyperLinks"></param>
        /// <param name="otherNodes"></param>
        public static void Create_HyperLinks(string PivotOutputReportFullPath, List <Hashtable> htHyperLinks, List <XmlNode> otherNodes)
        {
            // Creates a new Excel Application
            Excel.Application excelApp      = new Excel.Application();
            Excel.Workbook    excelWorkbook = null;
            var workbooks = excelApp.Workbooks;

            XmlNode tocNode    = otherNodes.Find(item => item.Name == "TOC");
            XmlNode sourceNode = otherNodes.Find(item => item.Name == "SourceFile");
            XmlNode style      = otherNodes.Find(item => item.Name == "Style");

            Logger.LogInfoMessage(string.Format("[GeneratePivotReports][Create_HyperLinks] Processing Started to add Links in Table of Content Sheet and Back Links in all output sheets"), false);

            try
            {
                excelWorkbook = workbooks.Open(PivotOutputReportFullPath);
            }
            catch
            {
                //Create a new workbook if the existing workbook failed to open.
                excelWorkbook = excelApp.Workbooks.Add();
            }

            try
            {
                // The following gets the Worksheets collection
                Excel.Sheets excelSheets    = excelWorkbook.Worksheets;
                XmlNode      tocHeading     = tocNode.SelectSingleNode("TOCHeading");
                XmlNode      tocTitle       = tocNode.SelectSingleNode("TOCTitle");
                XmlNode      tocDescription = tocNode.SelectSingleNode("TOCDescription");
                XmlNode      sourceHead     = sourceNode.SelectSingleNode("SourceFileHeading");
                XmlNode      backToIndex    = sourceNode.SelectSingleNode("BackToIndex");

                XmlNode tocHeadStyle        = style.SelectSingleNode("TOCStyle").SelectSingleNode("TOCHeading");
                XmlNode tocTitleStyle       = style.SelectSingleNode("TOCStyle").SelectSingleNode("TOCTitle");
                XmlNode tocDescStyle        = style.SelectSingleNode("TOCStyle").SelectSingleNode("TOCDescription");
                XmlNode tocStyle            = style.SelectSingleNode("TOCStyle").SelectSingleNode("Style");
                XmlNode sourceHeadStyle     = style.SelectSingleNode("SourceFileStyle").SelectSingleNode("SourceFileHeading");
                XmlNode sourceFileNameStyle = style.SelectSingleNode("SourceFileStyle").SelectSingleNode("SourceFileName");
                XmlNode backToIndexStyle    = style.SelectSingleNode("SourceFileStyle").SelectSingleNode("BackToIndex");

                string sheetName          = "";
                string sourceFileNameText = "";

                // The following gets Sheet1 for editing
                string          currentSheet   = tocNode.Name;
                Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet);

                //Fixed Table Location
                Excel.Range tRange = excelWorksheet.get_Range("A2", "A22");
                //borders.Weight = 1d;
                int rowNumber = 3;

                foreach (var htRowIndex in htHyperLinks)
                {
                    foreach (DictionaryEntry hyperlink in htRowIndex.Cast <DictionaryEntry>().OrderBy(item => item.Key).ToList())
                    {
                        if (!htRowIndex.Keys.Cast <String>().Contains("SummaryView"))
                        {
                            string[] keyValue = hyperlink.Key.ToString().Split('~');
                            sheetName          = keyValue[0];
                            sourceFileNameText = keyValue[1];
                            //to put the header for the table of contents sheet
                            if (rowNumber == 3)
                            {
                                Excel.Range excelCellRowHeader = (Excel.Range)excelWorksheet.get_Range("A2", "B2");
                                excelCellRowHeader.Merge(Missing.Value);
                                excelCellRowHeader.Value = tocHeading.InnerText;
                                excelCellRowHeader.Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                                excelCellRowHeader.Font.Size  = Convert.ToDouble(CheckAttributes("FontSize", tocHeadStyle, style));
                                excelCellRowHeader.Font.Color = CommonHelper.GetColor(CheckAttributes("FontColor", tocHeadStyle, style));
                                Excel.Borders border = excelCellRowHeader.Borders;
                                border.LineStyle = Excel.XlLineStyle.xlContinuous;
                                excelCellRowHeader.Columns.AutoFit();
                                excelCellRowHeader.Font.Bold      = true;
                                excelCellRowHeader.Font.Underline = true;
                                excelCellRowHeader.Font.Name      = CheckAttributes("FontFamily", tocHeadStyle, style);
                                rowNumber++;
                            }

                            if (rowNumber == 4)
                            {
                                var excelCellRowHeader2 = (Excel.Range)excelWorksheet.get_Range("A3");
                                excelCellRowHeader2.Value      = tocTitle.InnerText;
                                excelCellRowHeader2.Font.Color = CommonHelper.GetColor(CheckAttributes("FontColor", tocTitleStyle, style));
                                Excel.Borders border2 = excelCellRowHeader2.Borders;
                                border2.LineStyle = Excel.XlLineStyle.xlContinuous;
                                excelCellRowHeader2.Columns.AutoFit();
                                excelCellRowHeader2.Font.Bold      = true;
                                excelCellRowHeader2.Font.Size      = Convert.ToDouble(CheckAttributes("FontSize", tocTitleStyle, style));
                                excelCellRowHeader2.Font.Name      = CheckAttributes("FontFamily", tocTitleStyle, style);
                                excelCellRowHeader2.Interior.Color = CommonHelper.GetColor(CheckAttributes("BgColor", tocTitleStyle, style));

                                Excel.Range excelCellRowHeader1 = (Excel.Range)excelWorksheet.get_Range("B3");
                                excelCellRowHeader1.Value = tocDescription.InnerText;

                                excelCellRowHeader1.ColumnWidth = Convert.ToDouble(CheckAttributes("ColumnWidth", tocDescStyle, style));
                                excelCellRowHeader1.Font.Color  = CommonHelper.GetColor(CheckAttributes("FontColor", tocDescStyle, style));
                                Excel.Borders border1 = excelCellRowHeader1.Borders;
                                border1.LineStyle                  = Excel.XlLineStyle.xlContinuous;
                                excelCellRowHeader1.Font.Bold      = true;
                                excelCellRowHeader1.Interior.Color = CommonHelper.GetColor(CheckAttributes("BgColor", tocDescStyle, style));
                                excelCellRowHeader1.Font.Size      = Convert.ToDouble(CheckAttributes("FontSize", tocDescStyle, style));
                                excelCellRowHeader1.Font.Name      = CheckAttributes("FontFamily", tocDescStyle, style);
                                rowNumber++;
                            }
                        }
                        else
                        {
                            sheetName = hyperlink.Key.ToString();
                            rowNumber = 4;
                        }

                        // The following gets cell A1 for editing
                        Excel.Range excelCell = (Excel.Range)excelWorksheet.get_Range("A" + rowNumber);
                        excelWorksheet.Activate();
                        //Add the Text for hyper Link in Table of contents Sheet
                        excelCell.Value = sheetName;
                        //var s = tocStyle.Attributes["BgColor"];
                        //excelCell.Font.Color = CommonHelper.GetColor((tocStyle.Attributes["BgColor"].InnerText == null) ? bgColor : tocStyle.Attributes["BgColor"].InnerText);
                        Excel.Borders borders = excelCell.Borders;
                        borders.LineStyle   = Excel.XlLineStyle.xlContinuous;
                        excelCell.Font.Bold = true;
                        excelWorksheet.Hyperlinks.Add(excelCell, "#" + sheetName + "!A1", Type.Missing, Type.Missing, sheetName);

                        excelWorksheet.Application.Range["A" + rowNumber].Select();
                        //excelApp.Selection.Font;
                        excelWorksheet.Application.Selection.Font.Name = CheckAttributes("FontFamily", tocStyle, style);
                        excelWorksheet.Application.Selection.Font.Size = Convert.ToDouble(CheckAttributes("FontSize", tocStyle, style));

                        Excel.Range excelCell3 = (Excel.Range)excelWorksheet.get_Range("B" + rowNumber);
                        //Add the Text for hyper Link in Table of contents Sheet
                        excelCell3.Value      = hyperlink.Value.ToString().Trim();
                        excelCell3.Font.Color = CommonHelper.GetColor(CheckAttributes("FontColor", tocStyle, style));
                        Excel.Borders borders2 = excelCell3.Borders;
                        borders2.LineStyle   = Excel.XlLineStyle.xlContinuous;
                        excelCell3.Font.Size = Convert.ToDouble(CheckAttributes("FontSize", tocStyle, style));
                        excelCell3.WrapText  = true;

                        Excel.Worksheet excelWorksheet2 = (Excel.Worksheet)excelSheets.get_Item(Convert.ToString(sheetName));
                        excelWorksheet2.Activate();
                        Range Line = (Range)excelWorksheet2.Rows[1];
                        Line.Insert();
                        Excel.Range excelCell2 = (Excel.Range)excelWorksheet2.get_Range(Convert.ToString("A1"));
                        excelCell2.Value = backToIndex.InnerText;
                        excelWorksheet2.Hyperlinks.Add(excelCell2, "#" + currentSheet + "!A1", Type.Missing, Type.Missing, Type.Missing);

                        excelWorksheet2.Application.Range["A1"].Select();
                        //excelApp.Selection.Font;
                        excelWorksheet2.Application.Selection.Font.Name = CheckAttributes("FontFamily", backToIndexStyle, style);
                        excelWorksheet2.Application.Selection.Font.Size = Convert.ToDouble(CheckAttributes("FontSize", backToIndexStyle, style));

                        if (!sheetName.Equals("SummaryView"))
                        {
                            //Get the range of sheet to fill count
                            Excel.Range sourceFileTitle = excelWorksheet2.get_Range("B1", "B1");
                            sourceFileTitle.Value      = sourceHead.InnerText.Trim();
                            sourceFileTitle.Font.Color = CommonHelper.GetColor(CheckAttributes("FontColor", sourceHeadStyle, style));
                            sourceFileTitle.Font.Size  = Convert.ToDouble(CheckAttributes("FontSize", sourceHeadStyle, style));
                            sourceFileTitle.Style.VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignTop;
                            sourceFileTitle.Font.Bold = true;
                            sourceFileTitle.Columns.AutoFit();

                            //Get the range of sheet to fill count
                            Excel.Range sourceFileName = excelWorksheet2.get_Range("C1", "F1");
                            sourceFileName.Merge();
                            sourceFileName.Value      = sourceFileNameText;
                            sourceFileName.Font.Color = CommonHelper.GetColor(CheckAttributes("FontColor", sourceFileNameStyle, style));
                            sourceFileName.Font.Size  = Convert.ToDouble(CheckAttributes("FontSize", sourceFileNameStyle, style));
                            sourceFileName.Style.VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignTop;
                            sourceFileName.Columns.AutoFit();
                        }
                        rowNumber++;
                    }
                }
                tRange.Columns.AutoFit();

                // Close the excel workbook
                excelWorkbook.Close(true, Type.Missing, Type.Missing);
                workbooks.Close();
                excelApp.Application.Quit();
                excelApp.Quit();
                Marshal.ReleaseComObject(excelSheets);
                Marshal.ReleaseComObject(excelWorkbook);
                Marshal.ReleaseComObject(workbooks);

                Logger.LogInfoMessage(string.Format("[GeneratePivotReports][Create_HyperLinks] Process Completed to add Links in Table of Content Sheet and Back Links in all output sheets"), true);
            }
            catch (Exception ex)
            {
                if (excelWorkbook != null)
                {
                    excelWorkbook.Save();
                    excelWorkbook.Close();
                }

                if (excelApp != null)
                {
                    excelApp.Quit();
                    excelApp.Application.Quit();
                }

                Marshal.ReleaseComObject(workbooks);
                Marshal.ReleaseComObject(excelWorkbook);

                Logger.LogErrorMessage(string.Format("[GeneratePivotReports][Create_HyperLinks][Exception]: " + ex.Message + "\n" + ex.StackTrace.ToString()), true);
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "Pivot", ex.Message, ex.ToString(),
                                            "[GeneratePivotReports]: Create_HyperLinks", ex.GetType().ToString(), Constants.NotApplicable);
            }
            finally
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                Marshal.ReleaseComObject(excelApp);
            }
        }
示例#25
0
        public bool Identify(string path)
        {
            string parentFolder = Path.GetDirectoryName(path);

            parentFolder ??= "";

            if (!File.Exists(Path.Combine(parentFolder, FINDER_INFO)))
            {
                return(false);
            }

            if (!Directory.Exists(Path.Combine(parentFolder, RESOURCES)))
            {
                return(false);
            }

            string baseFilename = Path.GetFileName(path);

            bool dataFound = false;
            bool rsrcFound = false;

            var finderDatStream =
                new FileStream(Path.Combine(parentFolder, FINDER_INFO), FileMode.Open, FileAccess.Read);

            while (finderDatStream.Position + 0x5C <= finderDatStream.Length)
            {
                var    datEntry  = new PcExchangeEntry();
                byte[] datEntryB = new byte[Marshal.SizeOf(datEntry)];
                finderDatStream.Read(datEntryB, 0, Marshal.SizeOf(datEntry));
                datEntry = Helpers.Marshal.ByteArrayToStructureBigEndian <PcExchangeEntry>(datEntryB);

                // TODO: Add support for encoding on filters
                string macName = StringHandlers.PascalToString(datEntry.macName, Encoding.GetEncoding("macintosh"));

                byte[] tmpDosNameB = new byte[8];
                byte[] tmpDosExtB  = new byte[3];
                Array.Copy(datEntry.dosName, 0, tmpDosNameB, 0, 8);
                Array.Copy(datEntry.dosName, 8, tmpDosExtB, 0, 3);

                string dosName = Encoding.ASCII.GetString(tmpDosNameB).Trim() + "." +
                                 Encoding.ASCII.GetString(tmpDosExtB).Trim();

                string dosNameLow = dosName.ToLower(CultureInfo.CurrentCulture);

                if (baseFilename != macName &&
                    baseFilename != dosName &&
                    baseFilename != dosNameLow)
                {
                    continue;
                }

                dataFound |=
                    File.Exists(Path.Combine(parentFolder, macName ?? throw new InvalidOperationException())) ||
                    File.Exists(Path.Combine(parentFolder, dosName)) ||
                    File.Exists(Path.Combine(parentFolder, dosNameLow));

                rsrcFound |= File.Exists(Path.Combine(parentFolder, RESOURCES, dosName)) ||
                             File.Exists(Path.Combine(parentFolder, RESOURCES, dosNameLow));

                break;
            }

            finderDatStream.Close();

            return(dataFound && rsrcFound);
        }
示例#26
0
        public static void AllSerializeDeserialize <From, To>(From from, bool noTranscoding = false)
            where From : class
            where To : class
        {
            RoundtripMemory <From, To> memoryRoundtrip = (serialize, deserialize) =>
            {
                var data = serialize(from);
                var to   = deserialize(data);
                Assert.IsTrue(from.IsEqual(to));
            };

            RoundtripPointer <From, To> pointerRoundtrip = (serialize, deserialize) =>
            {
                var ptr  = RMarshal.AllocHGlobal(UnsafeBufferSize);
                var data = serialize(from, ptr, UnsafeBufferSize);
                var to   = deserialize(data, UnsafeBufferSize);
                Assert.IsTrue(from.IsEqual(to));
                RMarshal.FreeHGlobal(data);
            };

            RoundtripMemoryPointer <From, To> memoryPointerRoundtrip = (serialize, deserialize) =>
            {
                var data   = serialize(from);
                var pinned = GCHandle.Alloc(data.Array, GCHandleType.Pinned);
                var to     = deserialize(RMarshal.UnsafeAddrOfPinnedArrayElement(data.Array, data.Offset), data.Count);
                Assert.IsTrue(from.IsEqual(to));
                pinned.Free();
            };

            RoundtripStream <From, To> streamRoundtrip = (serialize, deserialize) =>
            {
                var stream = new MemoryStream();

                serialize(from, stream);
                stream.Position = 0;
                var to = deserialize(stream);

                Assert.IsTrue(from.IsEqual(to));
            };

            MarshalStream <From> streamMarshal = serialize => streamRoundtrip(serialize, stream =>
            {
                stream.Position = 0;
                return(Unmarshal <To> .From(new InputStream(stream)));
            });

            MarshalStream <From> streamMarshalSchema = serialize => streamRoundtrip(serialize, stream =>
            {
                stream.Position = 0;
                return(Unmarshal.From(new InputStream(stream), Schema <From> .RuntimeSchema).Deserialize <To>());
            });

            MarshalStream <From> streamMarshalNoSchema = serialize => streamRoundtrip(serialize, stream =>
            {
                stream.Position = 0;
                return(Unmarshal.From(new InputStream(stream)).Deserialize <To>());
            });

            MarshalMemory <From> memoryMarshal = serialize => memoryRoundtrip(serialize, Unmarshal <To> .From);

            TranscodeStream <From, To> streamTranscode = (serialize, transcode, deserialize) =>
                                                         streamRoundtrip((obj, stream) =>
            {
                using (var tmp = new MemoryStream())
                {
                    serialize(obj, tmp);
                    tmp.Position = 0;
                    transcode(tmp, stream);
                }
            }, deserialize);

            if (noTranscoding)
            {
                streamTranscode = (serialize, transcode, deserialize) => { }
            }
            ;

            // Compact Binary
            streamRoundtrip(SerializeCB, DeserializeCB <To>);
            memoryRoundtrip(SerializeUnsafeCB, DeserializeSafeCB <To>);
            memoryRoundtrip(SerializeUnsafeCB, DeserializeUnsafeCB <To>);
            memoryPointerRoundtrip(SerializeUnsafeCB, DeserializePointerCB <To>);
            pointerRoundtrip(SerializePointerCB, DeserializePointerCB <To>);
            memoryRoundtrip(SerializeSafeCB, DeserializeSafeCB <To>);
            memoryRoundtrip(SerializeSafeCB, DeserializeUnsafeCB <To>);
            memoryPointerRoundtrip(SerializeSafeCB, DeserializePointerCB <To>);
            memoryRoundtrip(SerializeSafeCBNoInlining, DeserializeSafeCB <To>);

            streamMarshal(MarshalCB);
            streamMarshal(SerializerMarshalCB);
            streamMarshalSchema(MarshalCB);
            streamMarshalNoSchema(MarshalCB);
            memoryMarshal(MarshalCB);

            streamTranscode(SerializeCB, TranscodeCBCB, DeserializeCB <To>);
            streamTranscode(SerializeCB, TranscodeCBFB, DeserializeFB <To>);

            streamRoundtrip(SerializeCB, stream =>
            {
                var input  = new InputStream(stream);
                var reader = new CompactBinaryReader <InputStream>(input);
                return(DeserializeTagged <To>(reader));
            });

            // Fast Binary
            streamRoundtrip(SerializeFB, DeserializeFB <To>);
            memoryRoundtrip(SerializeFB, DeserializeSafeFB <To>);
            memoryRoundtrip(SerializeFB, DeserializeUnsafeFB <To>);
            memoryPointerRoundtrip(SerializeFB, DeserializePointerFB <To>);

            streamMarshal(MarshalFB);
            streamMarshal(SerializerMarshalFB);
            streamMarshalSchema(MarshalFB);
            streamMarshalNoSchema(MarshalFB);
            memoryMarshal(MarshalFB);

            streamTranscode(SerializeFB, TranscodeFBFB, DeserializeFB <To>);
            streamTranscode(SerializeFB, TranscodeFBCB, DeserializeCB <To>);

            streamRoundtrip(SerializeFB, stream =>
            {
                var input  = new InputStream(stream);
                var reader = new FastBinaryReader <InputStream>(input);
                return(DeserializeTagged <To>(reader));
            });

            // Simple doesn't support omitting fields
            if (typeof(From) != typeof(Nothing) && typeof(From) != typeof(GenericsWithNothing))
            {
                streamRoundtrip(SerializeSP, DeserializeSP <From, To>);
                memoryRoundtrip(SerializeSP, DeserializeSafeSP <From, To>);
                memoryRoundtrip(SerializeSP, DeserializeUnsafeSP <From, To>);
                memoryPointerRoundtrip(SerializeSP, DeserializePointerSP <From, To>);

                streamRoundtrip(SerializeSP2, DeserializeSP2 <From, To>);
                memoryRoundtrip(SerializeSP2, DeserializeSafeSP2 <From, To>);
                memoryRoundtrip(SerializeSP2, DeserializeUnsafeSP2 <From, To>);

                streamTranscode(SerializeCB, TranscodeCBSP <From>, DeserializeSP <From, To>);
                streamTranscode(SerializeFB, TranscodeFBSP <From>, DeserializeSP <From, To>);
                streamTranscode(SerializeSP, TranscodeSPSP <From>, DeserializeSP <From, To>);
                streamTranscode(SerializeSP, TranscodeSPCB <From>, DeserializeCB <To>);
                streamTranscode(SerializeSP, TranscodeSPFB <From>, DeserializeFB <To>);

                // Pull parser doesn't supprot bonded<T>
                if (AnyField <From>(Reflection.IsBonded))
                {
                    streamTranscode(SerializeSP, TranscodeSPXml <From>, DeserializeXml <To>);

                    // NewtonSoft JSON doesn't support uint64
                    if (typeof(From) != typeof(MaxUInt64))
                    {
                        streamTranscode(SerializeSP, TranscodeSPJson <From>, DeserializeJson <To>);
                    }
                }

                streamRoundtrip(SerializeSP, stream =>
                {
                    var input  = new InputStream(stream);
                    var reader = new SimpleBinaryReader <InputStream>(input);
                    return(DeserializeUntagged <From, To>(reader));
                });

                streamMarshalSchema(MarshalSP);
            }

            // Pull parser doesn't supprot bonded<T>
            if (AnyField <From>(Reflection.IsBonded))
            {
                streamRoundtrip(SerializeXml, DeserializeXml <To>);
                streamTranscode(SerializeCB, TranscodeCBXml <From>, DeserializeXml <To>);
                streamTranscode(SerializeFB, TranscodeFBXml <From>, DeserializeXml <To>);

                // NewtonSoft JSON doesn't support uint64
                if (typeof(From) != typeof(MaxUInt64))
                {
                    streamRoundtrip(SerializeJson, DeserializeJson <To>);
                    streamTranscode(SerializeCB, TranscodeCBJson <From>, DeserializeJson <To>);
                    streamTranscode(SerializeFB, TranscodeFBJson <From>, DeserializeJson <To>);
                }
            }
        }

        delegate bool TypePredicate(Type field);
示例#27
0
        public byte[][] GetServiceRecordsUnparsedWindowsRaw(Guid service)
        {
            WqsOffset.AssertCheckLayout();
            BlobOffsets.AssertCheckLayout();
            //temporary workaround - sockets must be initialised
            Socket s = new Socket(AddressFamily32.Bluetooth, SocketType.Stream, BluetoothProtocolType.RFComm);

            //store variable length collection of records
            System.Collections.ArrayList records = new System.Collections.ArrayList();

            byte[] sdp = null;

            WSAQUERYSET wqs = new WSAQUERYSET();
            wqs.dwSize = WqsOffset.StructLength_60;
            wqs.dwNameSpace = WqsOffset.NsBth_16;

#if NETCF
            CSADDR_INFO sainfo = new CSADDR_INFO(null, this.DeviceAddress , SocketType.Unknown, ProtocolType.Unknown);
            wqs.dwNumberOfCsAddrs = 1;
            
            IntPtr pSaInfo = Marshal32.AllocHGlobal(24);
            IntPtr pBrb = Marshal32.AllocHGlobal(256);
            IntPtr pService = Marshal32.AllocHGlobal(240);

            Marshal.StructureToPtr(sainfo, pSaInfo, false);
            wqs.lpcsaBuffer = pSaInfo;            

            Marshal.WriteInt32(pBrb, 0, (int)SdpQueryType.SearchAttributeRequest);

            //write the service guid
            Marshal.Copy(service.ToByteArray(), 0, new IntPtr(pBrb.ToInt32() + 8), 16);
            Marshal.WriteInt16(pBrb, 24, (short)SdpSpecificType.Uuid128);
            Marshal.WriteInt16(pBrb, 26, 0);

            //write an empty guid to the next position
            Marshal.Copy(Guid.Empty.ToByteArray(), 0, new IntPtr(pBrb.ToInt32() + 28), 16);
            Marshal.WriteInt16(pBrb, 44, 0x0);
            Marshal.WriteInt16(pBrb, 46, 0);

            //number of attribute ranges
            Marshal.WriteInt32(pBrb, 248, 1);
            //min attribute
            Marshal.WriteInt16(pBrb, 252, 0);
            //max attribute
            Marshal.StructureToPtr((ushort)0xffff, (IntPtr)(pBrb.ToInt32() + 254), false);
            //Marshal.WriteInt16(pBrb, 254, 0x800);
            
            BLOB b = new BLOB(256, pBrb);

            IntPtr pb = Marshal32.AllocHGlobal(8);

            Marshal.StructureToPtr(b, pb, false);
            wqs.lpBlob = pb;
            
#endif


#if WinXP
            GCHandle hservice = GCHandle.Alloc(service.ToByteArray(), GCHandleType.Pinned);
            wqs.lpServiceClassId = hservice.AddrOfPinnedObject();
            wqs.lpszContext = "(" + this.DeviceAddress.ToString("C") + ")"; // sb.ToString(); // hContext.AddrOfPinnedObject();
#endif

            IntPtr handle = IntPtr.Zero;

            int lookupresult;

            //start looking for Bluetooth services


#if NETCF
            LookupFlags flagsForBegin; // Move above the #if is changed to use for desktop build too.
            flagsForBegin = 0;
            bool isQueryingLocalhost = false;
            try {
                BluetoothRadio theOne = BluetoothRadio.PrimaryRadio; // Only ever one on CE...
                if (theOne != null) {
                    BluetoothAddress localAddr = theOne.LocalAddress;
                    if (localAddr != null) {
                        if (localAddr == this.DeviceAddress) {
                            isQueryingLocalhost = true;
                        }
                    }
                }
            } catch (Exception ex) {
                System.Diagnostics.Debug.Fail("Exception in hack on CE to check if localhost: " + ex);
            }
            if (isQueryingLocalhost) {
                flagsForBegin |= LookupFlags.ResService;
            }
#endif
#if NETCF
            try
            {
                lookupresult = NativeMethods.WSALookupServiceBegin(ref wqs, flagsForBegin, out handle);
#else
            lookupresult = NativeMethods.WSALookupServiceBegin(ref wqs, LookupFlags.FlushCache | LookupFlags.ReturnName | LookupFlags.ReturnBlob, out handle);
#endif
            SocketBluetoothClient.ThrowSocketExceptionForHR(lookupresult);


#if WinXP
            hservice.Free();
#endif

            while (lookupresult == 0) {
                byte[] sdpBuffer = new byte[6000];
                BitConverter.GetBytes(WqsOffset.StructLength_60).CopyTo(sdpBuffer, WqsOffset.dwSize_0);
                BitConverter.GetBytes(WqsOffset.NsBth_16).CopyTo(sdpBuffer, WqsOffset.dwNameSpace_20);
                int size = sdpBuffer.Length;

#if NETCF
                    lookupresult = NativeMethods.WSALookupServiceNext(handle, (LookupFlags)0, ref size, sdpBuffer);
#else
                lookupresult = NativeMethods.WSALookupServiceNext(handle, LookupFlags.FlushCache | LookupFlags.ReturnBlob, ref size, sdpBuffer);
#endif

                if (lookupresult == -1) {
                    const int WSA_E_NO_MORE = 10110;
                    SocketBluetoothClient.ThrowSocketExceptionForHrExceptFor(lookupresult, WSA_E_NO_MORE);
                } else {
                    IntPtr pBlob = InTheHand.Runtime.InteropServices.Marshal32.ReadIntPtr(sdpBuffer, WqsOffset.lpBlob_56);
                    if (pBlob != IntPtr.Zero) {
                        IntPtr pSdpBlob = InTheHand.Runtime.InteropServices.Marshal32.ReadIntPtr(pBlob, BlobOffsets.Offset_pBlobData_4);
                        int cSdpBlob = Marshal.ReadInt32(pBlob);

                        if (cSdpBlob > 2) {
                            sdp = new byte[cSdpBlob];
                            Marshal.Copy(pSdpBlob, sdp, 0, cSdpBlob);
                            records.Add(sdp);
                        }
                    }

                }

            }

#if NETCF
            }
            finally
            {
                sainfo.Dispose();

                Marshal32.FreeHGlobal(pSaInfo);
                Marshal32.FreeHGlobal(pb);
                Marshal32.FreeHGlobal(pBrb);
            }
#endif

            //stop looking
            lookupresult = NativeMethods.WSALookupServiceEnd(handle);
            SocketBluetoothClient.ThrowSocketExceptionForHR(lookupresult);

            return (byte[][])records.ToArray(typeof(byte[]));
        }
示例#28
0
        /// <summary>
        /// Dispose COM objects
        /// </summary>
        private void DisposeCOMObjects()
        {
            FileWorker fileWorker = new FileWorker();

            try
            {
                xlWorkbook.Close(false);
            }
            catch (Exception ex)
            {
                errorsMessages.Add(ex.Message);
            }

            try
            {
                xlApp.Quit();
            }
            catch (Exception ex)
            {
                errorsMessages.Add(ex.Message);
                if (ex.Message == "Exception from HRESULT: 0x800AC472")
                {
                    GetWindowThreadProcessId((IntPtr)hWnd, out pid);
                    if (hWnd != 0)
                    {
                        try
                        {
                            Process[] procs = Process.GetProcessesByName("EXCEL");
                            if (pid != 0)
                            {
                                foreach (Process p in procs)
                                {
                                    if (p.Id == pid)
                                    {
                                        fileWorker.Logs(p.Id.ToString());
                                        p.Kill();
                                    }
                                }
                            }
                        }
                        catch (Exception ex1)
                        {
                            errorsMessages.Add(ex1.Message);
                        }
                    }
                }
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();

            try
            {
                Marshal.ReleaseComObject(xlWorkbook);
            }
            catch (Exception ex)
            {
                errorsMessages.Add(ex.Message);
            }
            try
            {
                Marshal.ReleaseComObject(xlApp);
            }
            catch (Exception ex)
            {
                errorsMessages.Add(ex.Message);
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
示例#29
0
        /// <summary>
        ///  Returns a TBBUTTONINFOW object that represents this ToolBarButton.
        /// </summary>
        internal ComCtl32.TBBUTTONINFOW GetTBBUTTONINFO(bool updateText, int newCommandId)
        {
            var button = new ComCtl32.TBBUTTONINFOW
            {
                cbSize = (uint)Marshal.SizeOf <ComCtl32.TBBUTTONINFOW>(),
                dwMask = ComCtl32.TBIF.IMAGE | ComCtl32.TBIF.STATE | ComCtl32.TBIF.STYLE
            };

            // Older platforms interpret null strings as empty, which forces the button to
            // leave space for text.
            // The only workaround is to avoid having comctl update the text.
            if (updateText)
            {
                button.dwMask |= ComCtl32.TBIF.TEXT;
            }

            button.iImage = ImageIndexer.ActualIndex;

            if (newCommandId != commandId)
            {
                commandId        = newCommandId;
                button.idCommand = newCommandId;
                button.dwMask   |= ComCtl32.TBIF.COMMAND;
            }

            // set up the state of the button
            button.fsState = 0;
            if (enabled)
            {
                button.fsState |= ComCtl32.TBSTATE.ENABLED;
            }

            if (partialPush && style == ToolBarButtonStyle.ToggleButton)
            {
                button.fsState |= ComCtl32.TBSTATE.INDETERMINATE;
            }

            if (pushed)
            {
                button.fsState |= ComCtl32.TBSTATE.CHECKED;
            }

            if (!visible)
            {
                button.fsState |= ComCtl32.TBSTATE.HIDDEN;
            }

            // set the button style
            switch (style)
            {
            case ToolBarButtonStyle.PushButton:
                button.fsStyle = (byte)ComCtl32.TBSTYLE.BUTTON;
                break;

            case ToolBarButtonStyle.ToggleButton:
                button.fsStyle = (byte)ComCtl32.TBSTYLE.CHECK;
                break;

            case ToolBarButtonStyle.Separator:
                button.fsStyle = (byte)ComCtl32.TBSTYLE.SEP;
                break;
            }

            if (text == null)
            {
                button.pszText = Marshal.StringToHGlobalAuto("\0\0");
            }
            else
            {
                string textValue = text;
                PrefixAmpersands(ref textValue);
                button.pszText = Marshal.StringToHGlobalAuto(textValue);
            }

            return(button);
        }
示例#30
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="grfCreateDoc"></param>
        /// <param name="pszMkDocument"></param>
        /// <param name="pszPhysicalView"></param>
        /// <param name="pvHier"></param>
        /// <param name="itemid"></param>
        /// <param name="punkDocDataExisting"></param>
        /// <param name="ppunkDocView"></param>
        /// <param name="ppunkDocData"></param>
        /// <param name="pbstrEditorCaption"></param>
        /// <param name="pguidCmdUI"></param>
        /// <param name="pgrfCDW"></param>
        /// <returns></returns>
        public virtual int CreateEditorInstance(
            uint createEditorFlags,
            string documentMoniker,
            string physicalView,
            IVsHierarchy hierarchy,
            uint itemid,
            IntPtr docDataExisting,
            out IntPtr docView,
            out IntPtr docData,
            out string editorCaption,
            out Guid commandUIGuid,
            out int createDocumentWindowFlags)
        {
            // Initialize output parameters
            docView                   = IntPtr.Zero;
            docData                   = IntPtr.Zero;
            commandUIGuid             = Guid.Empty;
            createDocumentWindowFlags = 0;
            editorCaption             = null;

            // Validate inputs
            if ((createEditorFlags & (uint)(VSConstants.CEF.OpenFile | VSConstants.CEF.Silent)) == 0)
            {
                return(VSConstants.E_INVALIDARG);
            }

            if (docDataExisting != IntPtr.Zero && PromptEncodingOnLoad)
            {
                return(VSConstants.VS_E_INCOMPATIBLEDOCDATA);
            }

            // Get a text buffer
            IVsTextLines textLines = GetTextBuffer(docDataExisting, documentMoniker);

            // Assign docData IntPtr to either existing docData or the new text buffer
            if (docDataExisting != IntPtr.Zero)
            {
                docData = docDataExisting;
                Marshal.AddRef(docData);
            }
            else
            {
                docData = Marshal.GetIUnknownForObject(textLines);
            }

            try
            {
                object docViewObject = CreateDocumentView(documentMoniker, physicalView, hierarchy, itemid, textLines, docDataExisting == IntPtr.Zero, out editorCaption, out commandUIGuid);
                docView = Marshal.GetIUnknownForObject(docViewObject);
            }
            finally
            {
                if (docView == IntPtr.Zero)
                {
                    if (docDataExisting != docData && docData != IntPtr.Zero)
                    {
                        // Cleanup the instance of the docData that we have addref'ed
                        Marshal.Release(docData);
                        docData = IntPtr.Zero;
                    }
                }
            }
            return(VSConstants.S_OK);
        }