I'm trying to implement a Splash Screen on my application but I'm getting this error: A first chance exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll  from this function: (if matter, it's part of a single instance application implmentation, take from ) protected override void WndProc(ref Message m)         {             if (m.Msg == NativeMethods.WM_SHOWME)             {                 ShowMe();             }              base.WndProc(ref m);         }  I modified my program.cs to like this:   Application.EnableVisualStyles();   Application.SetCompatibleTextRenderingDefault(false);   Application.Run(new SplashScreen(new Form1()))  And here's SplashScreen class: public partial class SplashScreen : Form     {         Form1 mainForm;         public SplashScreen(Form1 mainForm)         {             InitializeComponent();             this.mainForm = mainForm;             backgroundWorker1.RunWorkerAsync();         }          private void SplashScreen_Load(object sender, EventArgs e)         {          }          private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)         {             if (mainForm.InvokeRequired)                 mainForm.BeginInvoke(new Action(initMainForm));             else                 initMainForm();              //mainForm.Show();         }          private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)         {             this.Close();         }          void initMainForm()         {             mainForm.Show();         }     }  UPDATE: stack trace: System.InvalidOperationException: DragDrop registration did not succeed. ---&gt; System.Threading.ThreadStateException: The current thread must be defined in STA mode (single thread apartment) before OLE calls can be made. Check if the Main function has STAThreadAttribute marked.    em System.Windows.Forms.Control.SetAcceptDrops(Boolean accept)  (note: the error message isn't written in english but in my native language so I translated it myself. Sorry for any error.) Why am I getting that error and hwo do I fix this?
93347
I still have a problem with the splash screen. I don't want to use the property SC.TopMost=true.  Now my application scenario is as follows:  in progeram.cs:  [STAThread] static void Main() {     new SplashScreen(_tempAL);// where _tempAL is an arrayList     Application.Run(new Form1(_tempAL)); }   in SplashScreen class:  public SplashScreen(ArrayList _Data) {     DisplaySplash() }  private void DisplaySplash() {     this.Show();     this.TopMost = true;     this.CenterToScreen();     this.SetTopLevel(true);      _allServerNarrators = new string[10];     for (int i = 0; i &lt; _allServerNarrators.Length; i++)         _allServerNarrators[i] = null;      GetFromServer();      this.Hide();     _serverData = new ArrayList();     _thisData.Add(_allServerNarrators);     _thisData.Add(_serverNarrators);  } private void GetFromServer() {     _serverNarrators = new ArrayList();     string _file = "Suras.serverNar";      if (!Directory.Exists("c:\\ASGAQuraan"))         Directory.CreateDirectory("c:\\ASGAQuraan");      while (counter &lt; 4 &amp;&amp; _serverFiles == null)     {         if (Download("c:\\ASGAQuraan", _ftpServerIP, _file))         {             StreamReader _strReader = new StreamReader                          ("c:\\ASGAQuraan\\"+_file,System.Text.Encoding.Default);             string _line = _strReader.ReadLine();             string _word;              while (true)             {                 while (_line != null)                 {                     _word = _line.Substring(0, _line.IndexOf("*"));                     int _narId = Convert.ToInt32(_word);                     _line = _line.Substring(2);                     int k = 0;                     _serverNarratorNode = new ArrayList();                     while (true)                     {                         int ind = _line.IndexOf("*");                         if (ind &gt; 0 &amp;&amp; ind &lt; _line.Length)                         {                             string str = _line.Substring(0, (ind));                             if (k == 0)                             {                                 _allServerNarrators[_narId] = str;                                 _serverNarratorNode.Add(str);                             }                             else                             {                                 _serverNarratorNode.Add(str);                             }                             _line = _line.Substring(ind + 1);                             k++;                         }                         else                         {                             _line = null;                             break;                         }                     }                     _serverNarrators.Add(_serverNarratorNode);                     _serverFiles = "added";                 }                 _line = _strReader.ReadLine();                 if (_line == null)                 {                     break;                 }             }         }         else             counter++;     } }   What I want is something in the splash screen class which waits until the thread finishes.  For more details, please tell me what I need to tell you.
115907
I am trying to addError on the opportunities based on one condition. But getting System.FinalException: SObject row does not allow errors error while saving the record. Below I have given the code snippet. Please let me know how I can resolve the issue.  if(Trigger.isUpdate &amp;&amp; Trigger.isBefore){         map&lt;Id,Opportunity&gt; newOpptyMap = (map&lt;Id,Opportunity&gt;)trigger.newMap;         OpportunityTriggerHelper.checkforStageDuration(newOpptyMap,Trigger.OldMap);     }   The function is below where I am adding the error statement  public static void checkforStageDuration(Map&lt;Id,Opportunity&gt; oldMap, Map&lt;Id,Opportunity&gt; newMap){         Map&lt;Id,Opportunity&gt; recordsToCheck = new Map&lt;Id,Opportunity&gt;();         for(Id oppId : newMap.keyset()){             if(newMap.get(oppId).StageName != oldMap.get(oppId).StageName){                 recordsToCheck.put(oppId,newMap.get(oppId));             }         }         List&lt;Opportunity_Stage_History__c&gt; oppStageHistory = [select Id,Expected_Stage_Duration__c,Opportunity__c,Duration__c,Reason_For_Delay__c from Opportunity_Stage_History__c where Opportunity__c IN :recordsToCheck.keyset()];         for(Opportunity_Stage_History__c oppHistory : oppStageHistory){             if(oppHistory.Duration__c&gt;oppHistory.Expected_Stage_Duration__c &amp;&amp; oppHistory.Reason_For_Delay__c==null){                 newMap.get(oppHistory.Opportunity__c).addError('The Opportunity has crossed it\'s Stage Duration, Please fill the Reason for Delay !!');             }         }     }
52358
I'm writing an application that can be started either as a standard WinForms app or in unattended mode from the command-line. The application was built using the VS 2k5 standard WinForms template.  When the application is executed from the command-line, I want it to output information that can be captured by the script executing the application. When I do this directly from Console.WriteLine(), the output does not appear, although it can be captured by piping to a file.  On the other hand, I can force the application to pop up a second console by doing a P/Invoke on AllocConsole() from kernel32. This is not what I want, though. I want the output to appear in the same window the application was called from.  This is the salient code that allows me to pop up a console from the command line:  &lt;STAThread()&gt; Public Shared Sub Main()      If My.Application.CommandLineArgs.Count = 0 Then         Dim frm As New ISECMMParamUtilForm()         frm.ShowDialog()     Else         Try             ConsoleControl.AllocConsole()             Dim exMan As New UnattendedExecutionManager(ConvertArgs())             IsInConsoleMode = True             OutputMessage("Application started.")             If Not exMan.SetSettings() Then                 OutputMessage("Execution failed.")             End If         Catch ex As Exception             Console.WriteLine(ex.ToString())         Finally             ConsoleControl.FreeConsole()         End Try      End If  End Sub  Public Shared Sub OutputMessage(ByVal msg As String, Optional ByVal isError As Boolean = False)     Trace.WriteLine(msg)     If IsInConsoleMode Then         Console.WriteLine(msg)     End If      If isError Then         EventLog.WriteEntry("ISE CMM Param Util", msg, EventLogEntryType.Error)     Else         EventLog.WriteEntry("ISE CMM Param Util", msg, EventLogEntryType.Information)     End If  End Sub
92671
public class ExampleClass {       public static void publishCaseUpdateNotifications(List&lt;Case&gt; cases) {     List&lt;Case_Updated__e&gt; notifications = new List&lt;Case_Updated__e&gt;();     for (Case c: cases) {         notifications.add(new Case_Updated__e(             Case__c = (String)c.Id,             CreatedByName__c = UserInfo.getName(),             CaseNumber__c = c.CaseNumber         ));     }       List&lt;Database.SaveResult&gt; results = EventBus.publish(notifications);      for (Database.SaveResult result : results) {         if (!result.isSuccess()) {             for (Database.Error error : result.getErrors()) {                 System.debug('Error returned: ' +                     error.getStatusCode() +' - '+                     error.getMessage());             }         }       }      }    }   My Test Class: getting error   @isTest   public class ExampleTestClass {    @isTest   static void testClassforExample(){         Case testcase = new Case(Subject ='Test',);      list&lt;Case_Updated__e&gt; caseUpdate =      ExampleClass.publishCaseUpdateNotifications(testcase );       }      }   My Error is Method does not exist or incorrect signature: void publishCaseUpdateNotifications(Case) from the type ExampleTestClass   Please suggest me how to resolve this error.     trigger Cases on Case (after insert) { if(Trigger.isAfter) {     System.debug('I will be replaced shortly!'); }  }   Do we need test class for above trigger. Please suggest me too
122980
This is my code:  internal enum WindowsMessagesFlags {     WM_EXITSIZEMOVE      = 0x00000232,     WM_DISPLAYCHANGE     = 0x0000007e,     WM_MOVING            = 0x00000216, }  protected override void WndProc(ref Message m) {     switch(m.Msg) {         case (int)WindowsMessagesFlags.WM_DISPLAYCHANGE:             FixWindowSnapping();             break;         case (int)WindowsMessagesFlags.WM_EXITSIZEMOVE:             SaveWindowProperties();             break;         case (int)WindowsMessagesFlags.WM_MOVING:             KeepProperLocation(ref m);             break;     } }   Is there anyway to prevent the casting?
43765
I just installed SSMS 18 GA on a computer with only VS2019 installed, and when I try to open SSMS the splash screen will come up, but then the process exits.    Running ssms with the -log parameter reveals an error message:     CreateInstance failed for package [Task Scheduler Package]Source:   'mscorlib' Description: Could not load file or assembly   'Microsoft.VisualStudio.Shell.Interop.8.0, Version=15.0.0.0,   Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its   dependencies. The located assembly's manifest definition does not   match the assembly reference. (Exception from HRESULT: 0x80131040)   System.IO.FileLoadException: Could not load file or assembly   'Microsoft.VisualStudio.Shell.Interop.8.0, Version=15.0.0.0,   Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its   dependencies. The located assembly's manifest definition does not   match the assembly reference. (Exception from HRESULT: 0x80131040)   File name: 'Microsoft.VisualStudio.Shell.Interop.8.0,   Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'   ---> System.IO.FileLoadException: Could not load file or assembly 'Microsoft.VisualStudio.Shell.Interop.8.0, Version=8.0.0.0,   Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its   dependencies. The located assembly's manifest definition does not   match the assembly reference. (Exception from HRESULT: 0x80131040)   File name: 'Microsoft.VisualStudio.Shell.Interop.8.0, Version=8.0.0.0,   Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'      WRN: Assembly binding logging is turned OFF. To enable assembly bind   failure logging, set the registry value   [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1. Note: There   is some performance penalty associated with assembly bind failure   logging. To turn this feature off, remove the registry value   [HKLM\Software\Microsoft\Fusion!EnableLog].      at System.Reflection.RuntimeAssembly.GetType(RuntimeAssembly   assembly, String name, Boolean throwOnError, Boolean ignoreCase,   ObjectHandleOnStack type)    at   System.Reflection.RuntimeAssembly.GetType(String name, Boolean   throwOnError, Boolean ignoreCase)    at   System.Activator.CreateInstance(String assemblyString, String   typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder,   Object[] args, CultureInfo culture, Object[] activationAttributes,   Evidence securityInfo, StackCrawlMark&amp; stackMark)    at   System.Activator.CreateInstance(String assemblyName, String typeName)    at System.AppDomain.CreateInstance(String assemblyName, String   typeName)      System.IO.FileLoadException: Could not load file or assembly   'Microsoft.VisualStudio.Shell.Interop.8.0, Version=8.0.0.0,   Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its   dependencies. The located assembly's manifest definition does not   match the assembly reference. (Exception from HRESULT: 0x80131040)   File name: 'Microsoft.VisualStudio.Shell.Interop.8.0, Version=8.0.0.0,   Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'      WRN: Assembly binding logging is turned OFF. To enable assembly bind   failure logging, set the registry value   [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1. Note: There   is some performance penalty associated with assembly bind failure   logging. To turn this feature off, remove the registry value   [HKLM\Software\Microsoft\Fusion!EnableLog].   I tried running "Repair" on SSMS, and tried a repair of C:\ProgramData\Package Cache\{AAA9F15B-AF45-4562-9991-93A848D3A902}v15.0.28307.421\redist\vs2017_isoshell_for_ssms.msi, but the problem persists.
95856
I have some Python code that works correctly when I use python.exe to run it, but fails if I use pythonw.exe.       def runStuff(commandLine):         outputFileName = 'somefile.txt'         outputFile = open(outputFileName, "w")          try:             result = subprocess.call(commandLine, shell=True, stdout=outputFile)         except:             print 'Exception thrown:', str(sys.exc_info()[1])      myThread = threading.Thread(None, target=runStuff, commandLine=['whatever...'])     myThread.start()   The message I get is:       Exception thrown: [Error 6] The handle is invalid   However, if I don't specify the 'stdout' parameter, subprocess.call() starts okay.  I can see that pythonw.exe might be redirecting output itself, but I can't see why I'm blocked from specifying stdout for a new thread.
116653
I have this:  If String.IsNullOrEmpty(editTransactionRow.pay_id.ToString()) = False Then     stTransactionPaymentID = editTransactionRow.pay_id 'Check for null value End If   Now, when editTransactionRow.pay_id is Null Visual Basic throws an exception. Is there something wrong with this code?
37207
Sometime I see many application such as msn, windows media player etc that are single instance applications (when user executes while application is running a new application instance will not created).  In C#, I use Mutex class for this but I don't know how to do this in Java.
76874
In Windows Forms, I'd just override WndProc, and start handling messages as they came in.  Can someone show me an example of how to achieve the same thing in WPF?
90464
We noticed that lots of bugs in our software developed in C# (or Java) cause a NullReferenceException.  Is there a reason why "null" has even been included in the language?  After all, if there were no "null", I would have no bug, right?  In other words, what feature in the language couldn't work without null?
54872
I'm generating a level, and I have an optional delay to show the steps level generation one by one.  If my generationDelay boolean is true, I want to use StartCoroutine to spread the generation out over time. If it's false, I want to call the same method but without StartCoroutine.  The problem is that the method is type IEnumerator.  I can make two methods one type of IEnumerator and one not. But I wonder if there is a way to use one method.  In the first script top i did:  public bool generationDelay = false;   Then in a method:  private void BeginGame()     {         mazeInstance = Instantiate(mazePrefab) as Maze;          if (generationDelay == true)         {             StartCoroutine(mazeInstance.Generate(generationDelay));         }         else         {             mazeInstance.Generate(generationDelay);         }     }   Then the other script where the method Generate is: In the top:  public float generationStepDelay = 0.01f;   Then the method Generate:  public IEnumerator Generate (bool generationDelay) {          if (generationDelay == true)             WaitForSeconds delay = new WaitForSeconds(generationStepDelay);         cells = new MazeCell[size.x, size.z];         List&lt;MazeCell&gt; activeCells = new List&lt;MazeCell&gt;();         DoFirstGenerationStep(activeCells);         while (activeCells.Count &gt; 0) {             yield return delay;             DoNextGenerationStep(activeCells);         }     }   I'm getting an error on the line:   WaitForSeconds delay = new WaitForSeconds(generationStepDelay);      "Embedded statement cannot be a declaration or labeled statement"   And an error on the line:  yield return delay;      "The name 'delay' does not exist in the current context"   The reason I want to use a bool variable is that when i'm using StartCoroutine it's kind of slow, even if I change the value of generationStepDelay to 0 it's kind of slow. And if I'm not using StartCoroutine and not using the Generate method as IEnumerator it will work fast.  So i wonder what should I do and how?
98616
I can hookup to AppDomain.CurrentDomain.UnhandledException to log exceptions from background threads, but how do I prevent them terminating the runtime?
102790
For deployment reasons, I am trying to use IJW to wrap a C# assembly in C++ instead of using a COM Callable Wrapper.    I've done it on other projects, but on this one, I am getting an EEFileLoadException.  Any help would be appreciated!  Managed C++ wrapper code (this is in a DLL):  extern "C" __declspec(dllexport) IMyObject* CreateMyObject(void) {     //this class references c# in the constructor     return new CMyWrapper( ); }  extern "C" __declspec(dllexport)  void DeleteMyObject(IMyObject* pConfigFile) {     delete pConfigFile; }  extern "C" __declspec(dllexport) void TestFunction(void) {     ::MessageBox(NULL, _T("My Message Box"), _T("Test"), MB_OK); }   Test Code (this is an EXE):  typedef void* (*CreateObjectPtr)(); typedef void (*TestFunctionPtr)();  int _tmain testwrapper(int argc, TCHAR* argv[], TCHAR* envp[]) {     HMODULE hModule = ::LoadLibrary(_T("MyWrapper"));     _ASSERT(hModule != NULL);      PVOID pFunc1 = ::GetProcAddress(hModule, "TestFunction");     _ASSERT(pFunc1 != NULL);     TestFunctionPtr pTest = (TestFunctionPtr)pFunc1;      PVOID pFunc2 = ::GetProcAddress(hModule, "CreateMyObject");     _ASSERT(pFunc2 != NULL);     CreateObjectPtr pCreateObjectFunc = (CreateObjectPtr)pFunc2;      (*pTest)();  //this successfully pops up a message box     (*pCreateObjectFunc)();  //this tosses an EEFileLoadException      return 0; }   For what it's worth, the Event Log reports the following: .NET Runtime version 2.0.50727.143 -  Fatal Execution Engine Error (79F97075) (80131506)  Unfortunately, Microsoft has no information on that error.
113159
I'm not sure why I'm getting this error, but shouldn't this code compile, since I'm already checking to see if queue is getting initialized?   public static void Main(String[] args) {     Byte maxSize;     Queue queue;      if(args.Length != 0)     {         if(Byte.TryParse(args[0], out maxSize))             queue = new Queue(){MaxSize = maxSize};         else             Environment.Exit(0);     }     else     {         Environment.Exit(0);     }      for(Byte j = 0; j &lt; queue.MaxSize; j++)         queue.Insert(j);     for(Byte j = 0; j &lt; queue.MaxSize; j++)         Console.WriteLine(queue.Remove()); }   So if queue is not initialized, then the for loops aren't reachable right? Since the program already terminates with Environment.Exit(0)?  Hope ya'll can give me some pointers :)  Thanks.
90436
How can I launch an application using C#?  Requirements: Must work on  and .  I have seen a sample from DinnerNow.net sampler that only works in Windows&nbsp;Vista.
96022
I had the following exception thrown at me when trying to process more than one selected records via a custom button in the list view.    Class Code  global class MerchandiseInventoryClass {      webservice static void ConverttoInventory(String[] merchandise_id)    {        //Convert Merchandise collection into Inventory Collection...         Merchandise__c[] merchandise_collection = [SELECT ID,Author__c,Book_Title__c,Edition__c,Publisher__c,Total_Merchandise_QtyTotal_Qty__c,Status__c FROM Merchandise__c WHERE ID = :merchandise_id];          Inventory__c i = new Inventory__c(); //Line 1        List&lt;Inventory__c&gt; newInventory = new List&lt;Inventory__c&gt;();        for(Merchandise__c m : merchandise_collection )        {            if(m.Status__c !='Fully Converted')            {            i.Author__c = m.Author__c ;            i.Book_Title__c = m.Book_Title__c;            i.Edition__c = m.Edition__c;            i.Publisher__c = m.Publisher__c;            i.Qty_Available__c = m.Total_Merchandise_QtyTotal_Qty__c;            i.Merchandise__c = m.Id;            m.Uninventoried_Qty__c = 0;            m.Status__c = 'Fully Converted';            newInventory.add(i);            }        }        insert newInventory;        update merchandise_collection;    }  }   By moving the Line 1 to within the for loop solved the issue for me.  Thanks to this post (refer the Best Answer in that post)    What puzzles me is that WHY i have to instantiate "i" for every iteration within the loop.  Why the list collection ("newInventory") is complaining that are duplicate elements and why should it even confuse in the first place when I am performing an "insert" even ?