Search Results

Search found 505 results on 21 pages for 'intptr'.

Page 9/21 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • VS 2012 / 2013 AccessViolationException

    - by Goran
    When I run the project (F5) I receive the following exception in IDE: An unhandled exception of type 'System.AccessViolationException' occurred in System.Windows.Forms.dll Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. Stack trace reports at System.Windows.Forms.UnsafeNativeMethods.SendMessage(HandleRef hWnd, Int32 msg, IntPtr wParam, IntPtr lParam) at System.Windows.Forms.Control.SendMessage(Int32 msg, Int32 wparam, IntPtr lparam) at System.Windows.Forms.Form.UpdateWindowIcon(Boolean redrawFrame) at System.Windows.Forms.Form.CreateHandle() at System.Windows.Forms.Control.get_Handle() at Microsoft.VisualStudio.HostingProcess.HostProc.RunParkingWindowThread() at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() I have never noticed receiving the same exception when running without debugger (CTRL+F5). This is a WPF project, but exception occurs before the App_ctor is executed, so this is external code, and my application code did not start to execute. This happens sporadically, sometimes it happens only once, and sometimes I run the project and get this message for several times in a roll. Then it does not pop up for 5-6 runs, and then starts again. Anyone knows why is this happening? I have just installed clean W8.1 64 bit, VS2013 and TFS 2013 (although I had the same problem with W8 and VS2012, but not as often).

    Read the article

  • Cannot resolve TargetName - Silverlight4 C#

    - by Redburn
    I am getting the error Cannot resolve TargetName grdGeneral. What I am trying to do is have a fade out function which accepts a grid and fades the opacity to zero. I have this function called on MouseLeftButtonDown and is loaded after the xaml and form has loaded. Calling the fade out: private void imgNext_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { fadeOut(grdGeneral); } The fade out function: private void fadeOut(Grid pGrid) { Storyboard stb = new Storyboard(); DoubleAnimation da = new DoubleAnimation(); da.From = 1.0; da.To = 0.0; stb.Duration = new Duration(TimeSpan.FromSeconds(.75)); stb.Children.Add(da); Storyboard.SetTargetName(da, pGrid.Name); Storyboard.SetTargetProperty(da, new PropertyPath(Grid.OpacityProperty)); stb.Begin(); } I have been on a handful of tutorial sites and my code seems to follow the same order. I also have been on this stackoverflow question before you say repost. That question has to deal with mutlipages and I am merely trying to start a animation. The Stack Trace System.InvalidOperationException was unhandled by user code Message=Cannot resolve TargetName grdGeneral. StackTrace: at MS.Internal.XcpImports.MethodEx(IntPtr ptr, String name, CValue[] cvData) at MS.Internal.XcpImports.MethodEx(DependencyObject obj, String name) at System.Windows.Media.Animation.Storyboard.Begin() at MeterTesting.QuarterReportGUI.fadeOut(Grid pGrid) at MeterTesting.QuarterReportGUI.imgNext_MouseLeftButtonDown(Object sender, MouseButtonEventArgs e) at MS.Internal.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args) at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName) InnerException:

    Read the article

  • C# BindingSource.AddingNew is never called?

    - by msfanboy
    Hello, BindingSource.AddingNew is never called when I leave the cell of my datagrid. The DataGrid has as datasource the BindingSource which again has a "List" of "Customer". What does the BindingSource need to create a new Customer object and add it to the underlying ICustomerList ? Of course a interface has no constructor... Thats the Exception I get: System.MissingMethodException: The constcructor for the type "SAT.EnCoDe.Administration.ICustomer" was not found. bei System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) bei System.SecurityUtils.SecureCreateInstance(Type type, Object[] args) bei System.ComponentModel.BindingList1.AddNewCore() bei System.ComponentModel.BindingList1.System.ComponentModel.IBindingList.AddNew() bei System.Windows.Forms.BindingSource.AddNew() bei System.Windows.Forms.CurrencyManager.AddNew() bei DevExpress.Data.CurrencyDataController.OnCurrencyManagerAddNew() bei DevExpress.Data.CurrencyDataController.AddNewRow() bei DevExpress.XtraGrid.Views.Grid.GridView.OnActiveEditor_ValueModified(Object sender, EventArgs e) bei DevExpress.XtraEditors.Repository.RepositoryItem.RaiseModified(EventArgs e) bei DevExpress.XtraEditors.BaseEdit.OnEditValueChanging(ChangingEventArgs e) bei DevExpress.XtraEditors.TextEdit.OnMaskBox_ValueChanged(Object sender, EventArgs e) bei DevExpress.XtraEditors.Mask.MaskBox.RaiseEditTextChanged() bei System.Windows.Forms.TextBoxBase.WmReflectCommand(Message& m) bei DevExpress.XtraEditors.Mask.MaskBox.BaseWndProc(Message& m) bei DevExpress.XtraEditors.Mask.MaskBox.WndProc(Message& m) bei DevExpress.XtraEditors.TextBoxMaskBox.WndProc(Message& msg) bei System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) bei System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

    Read the article

  • CreateProcessAsUser doesn't draw the GUI

    - by pavel.tuzov
    Hi, I have a windows service running under "SYSTEM" account that checks if a specific application is running for each logged in user. If the application is not running, the service starts it (under corresponding user name). I'm trying to accomplish my goal using CreateProcessAsUser(). The service does start the application under corresponding user name, but the GUI is not drawn. (Yes, I'm making sure that "Allow service to interact with desktop" check box is enabled). System: XP SP3, labguage: C# Here is some code that might be of interest: PROCESS_INFORMATION processInfo = new PROCESS_INFORMATION(); startInfo.cb = Marshal.SizeOf(startInfo); startInfo.lpDesktop = "winsta0\\default"; bResult = Win32.CreateProcessAsUser(hToken, null, strCommand, IntPtr.Zero, IntPtr.Zero, false, 0, IntPtr.Zero, null, ref startInfo, out processInfo); As far as I understand, setting startInfo.lpDesktop = "winsta0\default"; should have used the desktop of corresponding user. Even contrary to what is stated here: http://support.microsoft.com/kb/165194, I tried setting lpDesktop to null, or not setting it at all, both giving the same result: process was started in the name of expected user and I could see a part of window's title bar. The "invisible" window intercepts mouse click events, handles them as expected. It just doesn't draw itself. Is anyone familiar with such a problem and knows what am I doing wrong?

    Read the article

  • C# Interop with dll

    - by Jim Jones
    Using VS2008 C# am attempting to interop a C++ dll. Have a C++ class constructor: make_summarizer(const char* rdir, const char* lic, const char* key); Need to retain a reference to the object that is created so I can use it in a follow-on function. When I did this in JNI the c code was: declare a static pointer to the object: static summarizer* summrzr; Then in one of the functions I called this constructor as follows: summrzr = make_summarizer(crdir, clic, ckey); Where the parameters all where the requisite const char* type; So in C# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using System.Configuration; namespace SummarizerApp { class SummApp { private IntPtr summarzr; public SummApp() { string resource_dir = ConfigurationManager.AppSettings["resource_dir"]; string license = ConfigurationManager.AppSettings["license"]; string key = ConfigurationManager.AppSettings["key"]; createSummarizer(resource_dir, license, key); } [System.Runtime.InteropServices.DllImportAttribute("lib\\summarizer37.dll", EntryPoint = "#1")] public static extern IntPtr make_summarizer( [InAttribute()][MarshalAsAttribute(UnmanagedType.LPTStr)] string rdir, [InAttribute()][MarshalAsAttribute(UnmanagedType.LPTStr)] string lic, [InAttribute()][MarshalAsAttribute(UnmanagedType.LPTStr)] string key); public void createSummarizer(string resource_dir, string license, string key) { try { this.summarzr = make_summarizer(resource_dir, license, key); } catch (AccessViolationException e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); } } Have also tried using IntPtr created using Marshal.StringToHGlobalAnsi(string). Regardless I get a AccessViolationException on the line where I call the native constructor; So what am I doing wrong? Jim

    Read the article

  • STOP Application Pool Issue Programitically IIS7

    - by Sumit Kute
    In my application I needs to stop a application pool programmitically in IIS 7. I have created a local acccount and given him Administrative Priviledges. Here is the code Private static void StopApplication() { string serviceHostDeploymentType = "local"; if (serviceHostDeploymentType.Equals("local")) { WindowsIdentityImpersonate newIdentity = new WindowsIdentityImpersonate(); if (newIdentity.Impersonate("AccountName", Environment.MachineName, "Password")) { try { ServerManager serverManager = ServerManager.OpenRemote("Server"); string siteName = GetWebSiteNameById(serverManager, 1); Site parentWebsite = serverManager.Sites[siteName]; if (parentWebsite != null) { ApplicationPool apppool = serverManager.ApplicationPools["Application Pool Name"]; if (apppool != null) { apppool.Stop(); } } } finally { newIdentity.Undo(); } } } else { throw new ConfigurationErrorsException("..."); } } I am getting an error Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)). Stack Trace at Microsoft.Web.Administration.Interop.IAppHostMethodInstance.Execute() at Microsoft.Web.Administration.ConfigurationElement.ExecuteMethod(String methodName) at Microsoft.Web.Administration.ApplicationPool.Stop() at ServerManagerTesting.Form1.StopApplication() at ServerManagerTesting.Form1.button1_Click(Object sender, EventArgs e) at System.Windows.Forms.Control.OnClick(EventArgs e) at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ButtonBase.WndProc(Message& m) at System.Windows.Forms.Button.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at ServerManagerTesting.Program.Main() at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart()

    Read the article

  • A generic error in GDI+ with ToolStrip in ManagerRenderMode

    - by volody
    I have a vb.net form with ToolStrip menu RenderMode - ManagerRenderMode LayoutStyle - HorizontalStackWithOverflow My development environment is .net 4.0, VS2010, windows 7 x64; but occasionally I am getting next error A generic error occurred in GDI+. Stacktrace: at System.Drawing.Graphics.CheckErrorStatus(Int32 status) at System.Drawing.Graphics.FillRectangle(Brush brush, Int32 x, Int32 y, Int32 width, Int32 height) at System.Drawing.Graphics.FillRectangle(Brush brush, Rectangle rect) at System.Windows.Forms.ToolStripProfessionalRenderer.FillWithDoubleGradient(Color beginColor, Color middleColor, Color endColor, Graphics g, Rectangle bounds, Int32 firstGradientWidth, Int32 secondGradientWidth, LinearGradientMode mode, Boolean flipHorizontal) at System.Windows.Forms.ToolStripProfessionalRenderer.RenderToolStripBackgroundInternal(ToolStripRenderEventArgs e) at System.Windows.Forms.ToolStripProfessionalRenderer.OnRenderToolStripBackground(ToolStripRenderEventArgs e) at System.Windows.Forms.ToolStripRenderer.DrawToolStripBackground(ToolStripRenderEventArgs e) at System.Windows.Forms.ToolStrip.OnPaintBackground(PaintEventArgs e) at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer) at System.Windows.Forms.Control.WmPaint(Message& m) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ScrollableControl.WndProc(Message& m) at System.Windows.Forms.ToolStrip.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

    Read the article

  • Suppress task switch keys (winkey, alt-tab, alt-esc, ctrl-esc) using low-level keyboard hook

    - by matt
    I'm trying to suppress task switch keys (such as winkey, alt-tab, alt-esc, ctrl-esc, etc.) by using a low-level keyboard hook. I'm using the following LowLevelKeyboardProc callback: IntPtr HookCallback(int nCode, IntPtr wParam, ref KBDLLHOOKSTRUCT lParam) { if (nCode >= 0) { bool suppress = false; // Suppress left and right windows keys. if (lParam.Key == VK_LWIN || lParam.Key == VK_RWIN) suppress = true; // Suppress alt-tab. if (lParam.Key == VK_TAB && HasAltModifier(lParam.Flags)) suppress = true; // Suppress alt-escape. if (lParam.Key == VK_ESCAPE && HasAltModifier(lParam.Flags)) suppress = true; // Suppress ctrl-escape. /* How do I hook CTRL-ESCAPE ? */ // Suppress keys by returning 1. if (suppress) return new IntPtr(1); } return CallNextHookEx(HookID, nCode, wParam, ref lParam); } bool HasAltModifier(int flags) { return (flags & 0x20) == 0x20; } However, I'm at a loss as to how to suppress the CTRL-ESC combination. Any suggestions? Thanks.

    Read the article

  • Unable to connect to UNC share with WindowsIdentity.Impersonate, but works fine using LogonUser

    - by Rob
    Hopefully I'm not missing something obvious here, but I have a class that needs to create some directories on a UNC share and then move files to the new directory. When we connect using LogonUser things work fine with no errors, but when we try and use the user indicated by Integrated Windows authentication we run into problems. Here's some working and non-working code to give you an idea what is going on. The following works and logs the requested information: [DllImport("advapi32.dll", SetLastError = true)] private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] private static extern bool CloseHandle(IntPtr handle); IntPtr token; WindowsIdentity wi; if (LogonUser("user", "network", "password", 8, // LOGON32_LOGON_NETWORK_CLEARTEXT 0, // LOGON32_PROVIDER_DEFAULT out token)) { wi = new WindowsIdentity(token); WindowsImpersonationContext wic = wi.Impersonate(); Logging.LogMessage(System.Security.Principal.WindowsIdentity.GetCurrent().Name); Logging.LogMessage(path); DirectoryInfo info = new DirectoryInfo(path); Logging.LogMessage(info.Exists.ToString()); Logging.LogMessage(info.Name); Logging.LogMessage("LastAccessTime:" + info.LastAccessTime.ToString()); Logging.LogMessage("LastWriteTime:" + info.LastWriteTime.ToString()); wic.Undo(); CloseHandle(token); } The following fails and gives an error message indicating the network name is not available, but the correct user name is indicated by GetCurrent().Name: WindowsIdentity identity = (WindowsIdentity)HttpContext.Current.User.Identity; using (identity.Impersonate()) { Logging.LogMessage(System.Security.Principal.WindowsIdentity.GetCurrent().Name); Logging.LogMessage(path); DirectoryInfo info = new DirectoryInfo(path); Logging.LogMessage(info.Exists.ToString()); Logging.LogMessage(info.Name); Logging.LogMessage("LastAccessTime:" + info.LastAccessTime.ToString()); Logging.LogMessage("LastWriteTime:" + info.LastWriteTime.ToString()); }

    Read the article

  • Accessing a file on a network drive

    - by Rekreativc
    Hello. Background: I have an application that has to read from files on a network drive (Z:) This works great in my office domain, however it does not work on site (in a different domain). As far as I can tell the domain users and network drives are set in the same way, however I do not have access to users etc in the customers domain. When I couldn't access the network drive I figured I needed a token for a user. This is how I impersionate the user: [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); ... const string userName = "Razvoj02"; const string pass = "Programer02"; const string domainName = null; const int LOGON32_PROVIDER_DEFAULT = 0; const int LOGON32_LOGON_INTERACTIVE = 2; IntPtr tokenHandle = new IntPtr(0); bool returnValue = LogonUser(userName, domainName, pass, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle); if (!returnValue) throw new Exception("Logon failed."); WindowsImpersonationContext impersonatedUser = null; try { WindowsIdentity wid = new WindowsIdentity(tokenHandle); impersonatedUser = wid.Impersonate(); } finally { if (impersonatedUser != null) impersonatedUser.Undo(); } Now here is the interesting/weird part. In my network the application can already access the network drive, and if I try to impersonate the active user (exactly the same user, including the same domain) it will not be able to access the network drive. This leaves me helpless since now I have no idea what works and what doesn't, and more to the point, will it work on site? What am I missing?

    Read the article

  • Trouble with an depreciated constrictor visual basic visual studio 2010

    - by VBPRIML
    My goal is to print labels with barcodes and a date stamp from an entry to a zebra TLP 2844 when the user clicks the ok button/hits enter. i found what i think might be the code for this from zebras site and have been integrating it into my program but part of it is depreciated and i cant quite figure out how to update it. below is what i have so far. The printer is attached via USB and the program will also store the entered numbers in a database but i have that part done. any help would be greatly Appreciated.   Public Class ScanForm      Inherits System.Windows.Forms.Form    Public Const GENERIC_WRITE = &H40000000    Public Const OPEN_EXISTING = 3    Public Const FILE_SHARE_WRITE = &H2      Dim LPTPORT As String    Dim hPort As Integer      Public Declare Function CreateFile Lib "kernel32" Alias "CreateFileA" (ByVal lpFileName As String,                                                                           ByVal dwDesiredAccess As Integer,                                                                           ByVal dwShareMode As Integer, <MarshalAs(UnmanagedType.Struct)> ByRef lpSecurityAttributes As SECURITY_ATTRIBUTES,                                                                           ByVal dwCreationDisposition As Integer, ByVal dwFlagsAndAttributes As Integer,                                                                           ByVal hTemplateFile As Integer) As Integer          Public Declare Function CloseHandle Lib "kernel32" Alias "CloseHandle" (ByVal hObject As Integer) As Integer      Dim retval As Integer           <StructLayout(LayoutKind.Sequential)> Public Structure SECURITY_ATTRIBUTES          Private nLength As Integer        Private lpSecurityDescriptor As Integer        Private bInheritHandle As Integer      End Structure            Private Sub OKButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OKButton.Click          Dim TrNum        Dim TrDate        Dim SA As SECURITY_ATTRIBUTES        Dim outFile As FileStream, hPortP As IntPtr          LPTPORT = "USB001"        TrNum = Me.ScannedBarcodeText.Text()        TrDate = Now()          hPort = CreateFile(LPTPORT, GENERIC_WRITE, FILE_SHARE_WRITE, SA, OPEN_EXISTING, 0, 0)          hPortP = New IntPtr(hPort) 'convert Integer to IntPtr          outFile = New FileStream(hPortP, FileAccess.Write) 'Create FileStream using Handle        Dim fileWriter As New StreamWriter(outFile)          fileWriter.WriteLine(" ")        fileWriter.WriteLine("N")        fileWriter.Write("A50,50,0,4,1,1,N,")        fileWriter.Write(Chr(34))        fileWriter.Write(TrNum) 'prints the tracking number variable        fileWriter.Write(Chr(34))        fileWriter.Write(Chr(13))        fileWriter.Write(Chr(10))        fileWriter.Write("A50,100,0,4,1,1,N,")        fileWriter.Write(Chr(34))        fileWriter.Write(TrDate) 'prints the date variable        fileWriter.Write(Chr(34))        fileWriter.Write(Chr(13))        fileWriter.Write(Chr(10))        fileWriter.WriteLine("P1")        fileWriter.Flush()        fileWriter.Close()        outFile.Close()        retval = CloseHandle(hPort)          'Add entry to database        Using connection As New SqlClient.SqlConnection("Data Source=MNGD-LABS-APP02;Initial Catalog=ScannedDB;Integrated Security=True;Pooling=False;Encrypt=False"), _        cmd As New SqlClient.SqlCommand("INSERT INTO [ScannedDBTable] (TrackingNumber, Date) VALUES (@TrackingNumber, @Date)", connection)            cmd.Parameters.Add("@TrackingNumber", SqlDbType.VarChar, 50).Value = TrNum            cmd.Parameters.Add("@Date", SqlDbType.DateTime, 8).Value = TrDate            connection.Open()            cmd.ExecuteNonQuery()            connection.Close()        End Using          'Prepare data for next entry        ScannedBarcodeText.Clear()        Me.ScannedBarcodeText.Focus()      End Sub

    Read the article

  • VB.NET - Object reference not set to an instance of an object

    - by Daniel
    I need some help with my program. I get this error when I run my VB.NET program with a custom DayView control. ***** Exception Text ******* System.NullReferenceException: Object reference not set to an instance of an object. at SeaCow.Main.DayView1_ResolveAppointments(Object sender, ResolveAppointmentsEventArgs args) in C:\Users\Daniel\My Programs\Visual Basic\SeaCow\SeaCow\SeaCow\Main.vb:line 120 at Calendar.DayView.OnResolveAppointments(ResolveAppointmentsEventArgs args) at Calendar.DayView.OnPaint(PaintEventArgs e) at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer) at System.Windows.Forms.Control.WmPaint(Message& m) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) According to the error code, the 'for each' loop below is causing the NullReferenceException error. At default, the 'appointments' list is assigned to nothing and I can't find where the ResolveAppointments function is being called at. Private Sub DayView1_ResolveAppointments(ByVal sender As Object, ByVal args As Calendar.ResolveAppointmentsEventArgs) Handles DayView1.ResolveAppointments Dim m_Apps As New List(Of Calendar.Appointment) For Each m_App As Calendar.Appointment In appointments If (m_App.StartDate >= args.StartDate) AndAlso (m_App.StartDate <= args.EndDate) Then m_Apps.Add(m_App) End If Next args.Appointments = m_Apps End Sub Anyone have any suggestions?

    Read the article

  • ORGetValue from Offline Registry - ERROR_MORE_DATA

    - by user314749
    I am trying to create an offline registry in memory using the offreg.dll provided in the windows ddk 7 package. You can find out more information on the offreg.dll here: MSDN Currently, while attempting to read a value from an open registry hive / key I receive the following error: 234 or ERROR_MORE_DATA Here is the .h code that contains ORGetValue: DWORD ORAPI ORGetValue ( __in ORHKEY Handle, __in_opt PCWSTR lpSubKey, __in_opt PCWSTR lpValue, __out_opt PDWORD pdwType, __out_bcount_opt(*pcbData) PVOID pvData, __inout_opt PDWORD pcbData ); Here is the code that I am using to pull the data [DllImport("offreg.dll", CharSet = CharSet.Auto, EntryPoint = "ORGetValue", SetLastError = true, CallingConvention = CallingConvention.StdCall)] public static extern uint ORGetValue(IntPtr Handle, string lpSubKey, string lpValue, out uint pdwType, out string pvData, out uint pcbData); IntPtr myHive; IntPtr myKey; string myValue; uint pdwtype; uint pcbdata; uint ret3 = ORGetValue(myKey, "", "DefaultUserName", out pdwtype, out myValue, out pcbdata); The goal is to be able to read myValue as a string. I am not sure if I need to use marshaling... or a second call with an adjusted buffer.. Or really how to adjust the buffer in C#. Any help or pointers would be greatly appreciated. Thank you.

    Read the article

  • Silverlight unit testing. Error while running tests.

    - by 1gn1ter
    I'm using VS2010. Silverlight 4, NUnit 2.5.5, and TypeMock TypemockIsolatorSetup6.0.3.619.msi In the test project MVVM is implemented, PeopleViewModel is a ViewModel which I want to test. Please advise if you use other products for unit testing of MVVM Silverlight. Or please help to win this TypeMock. TIA This is the code of the test: [Test] [SilverlightUnitTest] public void SomeTestAgainstSilverlight() { PeopleViewModel o = new PeopleViewModel(); var res = o.People; Assert.AreEqual(15, res.Count()); } While running the test in ReSharper i get the following error: TestA.SomeTestAgainstSilverlight : Failed****************************************** *Loading Silverlight Isolation Aspects...* ****************************************** TEST RESULTS: --------------------------------------------- System.MissingMethodException : Method not found: 'hv TypeMock.ArrangeActAssert.Isolate.a(System.Delegate)'. at a4.a(ref Delegate A_0) at a4.a(Boolean A_0) at il.b() at CThru.Silverlight.SilverlightUnitTestAttribute.Init() at CThru.Silverlight.SilverlightUnitTestAttribute.Execute() at TypeMock.MockManager.a(String A_0, String A_1, Object A_2, Object A_3, Boolean A_4, Object[] A_5) at TypeMock.InternalMockManager.getReturn(Object that, String typeName, String methodName, Object methodParameters, Boolean isInjected) at Tests.TestA.SomeTestAgainstSilverlight() in TestA.cs: line 21 While running test in NUnit i get: Tests.TestA.SomeTestAgainstSilverlight: System.DllNotFoundException : Unable to load DLL 'agcore': The specified module could not be found. (Exception from HRESULT: 0x8007007E) at MS.Internal.XcpImports.Application_GetCurrentNative(IntPtr context, IntPtr& obj) at MS.Internal.XcpImports.Application_GetCurrent(IntPtr& pApp) at System.Windows.Application.get_Current() at ViewModelExample.ViewModel.ViewModelBase.get_IsDesignTime() in C:\Documents and Settings\USER\Desktop\ViewModelExample\ViewModelExample\ViewModel\ViewModelBase.cs:line 20 at ViewModelExample.ViewModel.PeopleViewModel..ctor(IServiceAgent serviceAgent) in C:\Documents and Settings\USER\Desktop\ViewModelExample\ViewModelExample\ViewModel\PeopleViewModel.cs:line 28 at ViewModelExample.ViewModel.PeopleViewModel..ctor() in C:\Documents and Settings\USER\Desktop\ViewModelExample\ViewModelExample\ViewModel\PeopleViewModel.cs:line 24 at Tests.TestA.SomeTestAgainstSilverlight() in C:\Documents and Settings\USER\Desktop\ViewModelExample\Tests\TestA.cs:line 22

    Read the article

  • GetEffectiveRightsFromAcl throws invalid acl error

    - by apoorv020
    I am trying to get the effective rights a user has on a file using interop in C#. Following is the code I am using : public static FileSystemRights GetFileEffectiveRights(string FileName, string UserName) { IntPtr pDacl, pZero = IntPtr.Zero; int Mask = 0; uint errorReturn = GetNamedSecurityInfo(FileName, SE_OBJECT_TYPE.SE_FILE_OBJECT, SECURITY_INFORMATION.Dacl , out pZero, out pZero, out pDacl, out pZero, out pZero); if (errorReturn != 0) { throw new Exception("Win error : " + errorReturn); } Program.TRUSTEE pTrustee = new TRUSTEE(); pTrustee.pMultipleTrustee = IntPtr.Zero; pTrustee.MultipleTrusteeOperation = (int)Program.MULTIPLE_TRUSTEE_OPERATION.NO_MULTIPLE_TRUSTEE; pTrustee.ptstrName = UserName; pTrustee.TrusteeForm = (int)Program.TRUSTEE_FORM.TRUSTEE_IS_NAME; pTrustee.TrusteeType = (int)Program.TRUSTEE_TYPE.TRUSTEE_IS_USER; errorReturn = GetEffectiveRightsFromAcl(pDacl, ref pTrustee, ref Mask); if (errorReturn != 0) { throw new Exception("Win error : " + errorReturn); } return (FileSystemRights)Mask; } This code works fine until I start modifying the ACL structure using the classes FileAccessRule and FileInfo, and then I start getting Windows Error 1336 : ERROR_INVALID_ACL. Same is the case if I debug the process call GetFileEffectiveRights once, pause the process,change the ACL through windows API, and resume and call GetFileEffectiveRights again(the 1st call succeeds but the second gives 1336.) What is going wrong?

    Read the article

  • Retrieving dll version info via Win32 - VerQueryValue(...) crashes under Win7 x64

    - by user256890
    The respected open source .NET wrapper implementation (SharpBITS) of Windows BITS services fails identifying the underlying BITS version under Win7 x64. Here is the source code that fails. NativeMethods are native Win32 calls wrapped by .NET methods and decorated via DllImport attribute. private static BitsVersion GetBitsVersion() { try { string fileName = Path.Combine( System.Environment.SystemDirectory, "qmgr.dll"); int handle = 0; int size = NativeMethods.GetFileVersionInfoSize(fileName, out handle); if (size == 0) return BitsVersion.Bits0_0; byte[] buffer = new byte[size]; if (!NativeMethods.GetFileVersionInfo(fileName, handle, size, buffer)) { return BitsVersion.Bits0_0; } IntPtr subBlock = IntPtr.Zero; uint len = 0; if (!NativeMethods.VerQueryValue(buffer, @"\VarFileInfo\Translation", out subBlock, out len)) { return BitsVersion.Bits0_0; } int block1 = Marshal.ReadInt16(subBlock); int block2 = Marshal.ReadInt16((IntPtr)((int)subBlock + 2 )); string spv = string.Format( @"\StringFileInfo\{0:X4}{1:X4}\ProductVersion", block1, block2); string versionInfo; if (!NativeMethods.VerQueryValue(buffer, spv, out versionInfo, out len)) { return BitsVersion.Bits0_0; } ... The implementation follows the MSDN instructions by the letter. Still during the second VerQueryValue(...) call, the application crashes and kills the debug session without hesitation. Just a little more debug info right before the crash: spv = "\StringFileInfo\040904B0\ProductVersion" buffer = byte[1900] - full with binary data block1 = 1033 block2 = 1200 I looked at the targeted "C:\Windows\System32\qmgr.dll" file (The implementation of BITS) via Windows. It says that the Product Version is 7.5.7600.16385. Instead of crashing, this value should return in the verionInfo string. Any advice?

    Read the article

  • PostMessage does not seem to be working.

    - by Vaccano
    I am trying to use PostMessage to send a tab key. Here is my code: // This class allows us to send a tab key when the the enter key // is pressed for the mooseworks mask control. public class MaskKeyControl : MaskedEdit { // [DllImport("coredll.dll", SetLastError = true, CharSet = CharSet.Auto)] // static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, Int32 wParam, Int32 lParam); [return: MarshalAs(UnmanagedType.Bool)] // I am calling this on a Windows Mobile device so the dll is coredll.dll [DllImport("coredll.dll", SetLastError = true)] static extern bool PostMessage(IntPtr hWnd, uint Msg, Int32 wParam, Int32 lParam); public const Int32 VK_TAB = 0x09; public const Int32 WM_KEYDOWN = 0x100; protected override void OnKeyDown(KeyEventArgs e) { if (e.KeyData == Keys.Enter) { PostMessage(this.Handle, WM_KEYDOWN, VK_TAB, 0); return; } base.OnKeyDown(e); } protected override void OnKeyPress(KeyPressEventArgs e) { if (e.KeyChar == '\r') e.Handled = true; base.OnKeyPress(e); } } When I press enter the code gets called, but nothing happens. Then I press TAB and it works fine. (So there is something wrong with my sending of the Tab Message.)

    Read the article

  • ERROR_MORE_DATA ---- Reading from Registry

    - by user314749
    I am trying to create an offline registry in memory using the offreg.dll provided in the windows ddk 7 package. You can find out more information on the offreg.dll here: MSDN Currently, while attempting to read a value from an open registry hive / key I receive the following error: 234 or ERROR_MORE_DATA Here is the .h code that contains ORGetValue: DWORD ORAPI ORGetValue ( __in ORHKEY Handle, __in_opt PCWSTR lpSubKey, __in_opt PCWSTR lpValue, __out_opt PDWORD pdwType, __out_bcount_opt(*pcbData) PVOID pvData, __inout_opt PDWORD pcbData ); Here is the code that I am using to pull the data [DllImport("offreg.dll", CharSet = CharSet.Auto, EntryPoint = "ORGetValue", SetLastError = true, CallingConvention = CallingConvention.StdCall)] public static extern uint ORGetValue(IntPtr Handle, string lpSubKey, string lpValue, out uint pdwType, out string pvData, out uint pcbData); IntPtr myHive; IntPtr myKey; string myValue; uint pdwtype; uint pcbdata; uint ret3 = ORGetValue(myKey, "", "DefaultUserName", out pdwtype, out myValue, out pcbdata); The goal is to be able to read myValue as a string. I am not sure if I need to use marshaling... or a second call with an adjusted buffer.. Or really how to adjust the buffer in C#. Any help or pointers would be greatly appreciated. Thank you.

    Read the article

  • Trouble with an depreciated constructor visual basic visual studio 2010

    - by VBPRIML
    My goal is to print labels with barcodes and a date stamp from an entry to a zebra TLP 2844 when the user clicks the ok button/hits enter. i found what i think might be the code for this from zebras site and have been integrating it into my program but part of it is depreciated and i cant quite figure out how to update it. below is what i have so far. The printer is attached via USB and the program will also store the entered numbers in a database but i have that part done. any help would be greatly Appreciated.   Public Class ScanForm      Inherits System.Windows.Forms.Form    Public Const GENERIC_WRITE = &H40000000    Public Const OPEN_EXISTING = 3    Public Const FILE_SHARE_WRITE = &H2      Dim LPTPORT As String    Dim hPort As Integer      Public Declare Function CreateFile Lib "kernel32" Alias "CreateFileA" (ByVal lpFileName As String,                                                                           ByVal dwDesiredAccess As Integer,                                                                           ByVal dwShareMode As Integer, <MarshalAs(UnmanagedType.Struct)> ByRef lpSecurityAttributes As SECURITY_ATTRIBUTES,                                                                           ByVal dwCreationDisposition As Integer, ByVal dwFlagsAndAttributes As Integer,                                                                           ByVal hTemplateFile As Integer) As Integer          Public Declare Function CloseHandle Lib "kernel32" Alias "CloseHandle" (ByVal hObject As Integer) As Integer      Dim retval As Integer           <StructLayout(LayoutKind.Sequential)> Public Structure SECURITY_ATTRIBUTES          Private nLength As Integer        Private lpSecurityDescriptor As Integer        Private bInheritHandle As Integer      End Structure            Private Sub OKButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OKButton.Click          Dim TrNum        Dim TrDate        Dim SA As SECURITY_ATTRIBUTES        Dim outFile As FileStream, hPortP As IntPtr          LPTPORT = "USB001"        TrNum = Me.ScannedBarcodeText.Text()        TrDate = Now()          hPort = CreateFile(LPTPORT, GENERIC_WRITE, FILE_SHARE_WRITE, SA, OPEN_EXISTING, 0, 0)          hPortP = New IntPtr(hPort) 'convert Integer to IntPtr          outFile = New FileStream(hPortP, FileAccess.Write) 'Create FileStream using Handle        Dim fileWriter As New StreamWriter(outFile)          fileWriter.WriteLine(" ")        fileWriter.WriteLine("N")        fileWriter.Write("A50,50,0,4,1,1,N,")        fileWriter.Write(Chr(34))        fileWriter.Write(TrNum) 'prints the tracking number variable        fileWriter.Write(Chr(34))        fileWriter.Write(Chr(13))        fileWriter.Write(Chr(10))        fileWriter.Write("A50,100,0,4,1,1,N,")        fileWriter.Write(Chr(34))        fileWriter.Write(TrDate) 'prints the date variable        fileWriter.Write(Chr(34))        fileWriter.Write(Chr(13))        fileWriter.Write(Chr(10))        fileWriter.WriteLine("P1")        fileWriter.Flush()        fileWriter.Close()        outFile.Close()        retval = CloseHandle(hPort)          'Add entry to database        Using connection As New SqlClient.SqlConnection("Data Source=MNGD-LABS-APP02;Initial Catalog=ScannedDB;Integrated Security=True;Pooling=False;Encrypt=False"), _        cmd As New SqlClient.SqlCommand("INSERT INTO [ScannedDBTable] (TrackingNumber, Date) VALUES (@TrackingNumber, @Date)", connection)            cmd.Parameters.Add("@TrackingNumber", SqlDbType.VarChar, 50).Value = TrNum            cmd.Parameters.Add("@Date", SqlDbType.DateTime, 8).Value = TrDate            connection.Open()            cmd.ExecuteNonQuery()            connection.Close()        End Using          'Prepare data for next entry        ScannedBarcodeText.Clear()        Me.ScannedBarcodeText.Focus()      End Sub

    Read the article

  • Why is a NullReferenceException thrown when a ToolStrip button is clicked twice with code in the `Click` event handler?

    - by Patrick
    I created a clean WindowsFormsApplication solution, added a ToolStrip to the main form, and placed one button on it. I've added also an OpenFileDialog, so that the Click event of the ToolStripButton looks like the following: private void toolStripButton1_Click(object sender, EventArgs e) { openFileDialog1.ShowDialog(); } I didn't change any other properties or events. The funny thing is that when I double-click the ToolStripButton (the second click must be quite fast, before the dialog opens), then cancel both dialogs (or choose a file, it doesn't really matter) and then click in the client area of main form, a NullReferenceException crashes the application (error details attached at the end of the post). Please note that the Click event is implemented while DoubleClick is not. What's even more strange that when the OpenFileDialog is replaced by any user-implemented form, the ToolStripButton blocks from being clicked twice. I'm using VS2008 with .NET3.5. I didn't change many options in VS (only fontsize, workspace folder and line numbering). Does anyone know how to solve this? It is 100% replicable on my machine, is it on others too? One solution that I can think of is disabling the button before calling OpenFileDialog.ShowDialog() and then enabling the button back (but it's not nice). Any other ideas? And now the promised error details: System.NullReferenceException was unhandled Message="Object reference not set to an instance of an object." Source="System.Windows.Forms" StackTrace: at System.Windows.Forms.NativeWindow.WindowClass.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.PeekMessage(MSG& msg, HandleRef hwnd, Int32 msgMin, Int32 msgMax, Int32 remove) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(Form mainForm) at WindowsFormsApplication1.Program.Main() w C:\Users\Marchewek\Desktop\Workspaces\VisualStudio\WindowsFormsApplication1\Program.cs:line 20 at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException:

    Read the article

  • Send Click Message to another application process

    - by Nazar
    Hi Guys I have a scenario, i need to send click events to an independent application. I started that application with the following code. private Process app; app = new Process(); app.StartInfo.FileName = app_path; app.StartInfo.WorkingDirectory = dir_path; app.Start(); Now i want to send Mouse click message to that applicaiton, I have specific coordinates in relative to application window. How can i do it using Windows Messaging or any other technique. I used [DllImport("user32.dll")] private static extern void mouse_event(UInt32 dwFlags, UInt32 dx, UInt32 dy, UInt32 dwData, IntPtr dwExtraInfo); It works well but cause the pointer to move as well. So not fit for my need. Then i use. [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)] static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); It works well for minimize maximize, but do not work for mouse events. The codes for mousevents i am using are, WM_LBUTTONDOWN = 0x201, //Left mousebutton down WM_LBUTTONUP = 0x202, //Left mousebutton up WM_LBUTTONDBLCLK = 0x203, //Left mousebutton doubleclick WM_RBUTTONDOWN = 0x204, //Right mousebutton down WM_RBUTTONUP = 0x205, //Right mousebutton up WM_RBUTTONDBLCLK = 0x206, //Right mousebutton do Thanks for the help in advance, and waiting for feedback.

    Read the article

  • Why does GetWindowThreadProcessId return 0 when called from a service

    - by Marve
    When using the following class in a console application, and having at least one instance of Notepad running, GetWindowThreadProcessId correctly returns a non-zero thread id. However, if the same code is included in a Windows Service, GetWindowThreadProcessId always returns 0 and no exceptions are thrown. Changing the user the service launches under to be the same as the one running the console application didn't alter the result. What causes GetWindowThreadProcessId to return 0 even if it is provided with a valid hwnd? And why does it function differently in the console application and the service? Note: I am running Windows 7 32-bit and targeting .NET 3.5. public class TestClass { [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId); public void AttachToNotepad() { var processesToAttachTo = Process.GetProcessesByName("Notepad") foreach (var process in processesToAttachTo) { var threadID = GetWindowThreadProcessId(process.MainWindowHandle, IntPtr.Zero); .... } } } Console Code: class Program { static void Main(string[] args) { var testClass = new TestClass(); testClass.AttachToNotepad(); } } Service Code: public class TestService : ServiceBase { private TestClass testClass = new TestClass(); static void Main() { ServiceBase.Run(new TestService()); } protected override void OnStart(string[] args) { testClass.AttachToNotepad(); base.OnStart(args); } protected override void OnStop() { ... } }

    Read the article

  • Make a form not focusable in C#

    - by Jandex
    Hi! I'm wanting to write a virtual keyboard, like windows onscreen keyboard for touchscreen pcs. But I'm having problem with my virtual keyboard stealing the focus from the application being used. The windows onscreen keyboard mantains the focus on the current application even when the user clicks on it. Is there a way to do the same with windows forms in C#? The only thing I can do for now is to send a keyboard event to an especific application, like notepad in the following code. If I could make the form not focusable, I could get the current focused window with GetForegroundWindow. [DllImport("USER32.DLL", CharSet = CharSet.Unicode)] public static extern IntPtr FindWindow(string lpClassName,string lpWindowName); [DllImport("USER32.DLL")] public static extern bool SetForegroundWindow(IntPtr hWnd); private void button1_Click(object sender, EventArgs e) { IntPtr calculatorHandle = FindWindow("notepad", null); SetForegroundWindow(calculatorHandle); SendKeys.SendWait("111"); } Is there a way this can be done? Any suggestions of a better way to have the form sending keyboard events to the application being used? Thanks!!

    Read the article

  • Calling private constructors with Reflection.Emit?

    - by Jakob Botsch Nielsen
    I'm trying to emit the following IL: LocalBuilder pointer = il.DeclareLocal(typeof(IntPtr)); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Stloc, pointer); il.Emit(OpCodes.Ldloca, pointer); il.Emit(OpCodes.Call, typeof(IntPtr).GetMethod("ToPointer")); il.Emit(OpCodes.Ret); The delegate I bind with has the signature void* TestDelegate(IntPtr ptr) It throws the exception Operation could destabilize the runtime. Anyone knows what's wrong? EDIT: Alright, so I got the IL working now. The entire goal of this was to be able to call a private constructor. The private constructor takes a pointer so I can't use normal reflection. Now.. When I call it, I get an exception saying Attempt by method <built method> to access method <private constructor> failed. Apparently it's performing security checks - but from experience I know that Reflection is able to do private stuff like this normally, so hopefully there is a way to disable that check?

    Read the article

  • Send Click Message to another application process

    - by Nazar Hussain
    I have a scenario, i need to send click events to an independent application. I started that application with the following code. private Process app; app = new Process(); app.StartInfo.FileName = app_path; app.StartInfo.WorkingDirectory = dir_path; app.Start(); Now i want to send Mouse click message to that applicaiton, I have specific coordinates in relative to application window. How can i do it using Windows Messaging or any other technique. I used [DllImport("user32.dll")] private static extern void mouse_event(UInt32 dwFlags, UInt32 dx, UInt32 dy, UInt32 dwData, IntPtr dwExtraInfo); It works well but cause the pointer to move as well. So not fit for my need. Then i use. [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)] static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); It works well for minimize maximize, but do not work for mouse events. The codes for mousevents i am using are, WM_LBUTTONDOWN = 0x201, //Left mousebutton down WM_LBUTTONUP = 0x202, //Left mousebutton up WM_LBUTTONDBLCLK = 0x203, //Left mousebutton doubleclick WM_RBUTTONDOWN = 0x204, //Right mousebutton down WM_RBUTTONUP = 0x205, //Right mousebutton up WM_RBUTTONDBLCLK = 0x206, //Right mousebutton do Thanks for the help in advance, and waiting for feedback.

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >