ComException HRESULT: 0x800A03EC thrown when attempting to add Validation to a Range - c#

When trying to use the Range.Validation.Add() method, I'm consistently getting a very unfriendly error:
************** Exception Text **************
System.Runtime.InteropServices.COMException (0x800A03EC): Exception from HRESULT: 0x800A03EC
at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData)
at Microsoft.Office.Interop.Excel.Validation.Add(XlDVType Type, Object AlertStyle, Object Operator, Object Formula1, Object Formula2)
at TravelPlannerTools.Sheet8.OperaCodesDropDown() in C:\Users\Michael Utz\Documents\Visual Studio 2015\Projects\TravelPlannerTools\TravelPlannerTools\Sheet8.cs:line 39
at TravelPlannerTools.Sheet8.Sheet8_Startup(Object sender, EventArgs e) in C:\Users\Michael Utz\Documents\Visual Studio 2015\Projects\TravelPlannerTools\TravelPlannerTools\Sheet8.cs:line 27
at Microsoft.Office.Tools.Excel.WorksheetImpl.OnStartup()
at Microsoft.Office.Tools.Excel.WorksheetImpl.WorksheetExtensionImpl.Microsoft.Office.Tools.EntryPoint.OnStartup()
at Microsoft.Office.Tools.Excel.WorksheetBase.OnStartup()
at TravelPlannerTools.Sheet8.FinishInitialization() in C:\Users\Michael Utz\Documents\Visual Studio 2015\Projects\TravelPlannerTools\TravelPlannerTools\Sheet8.Designer.cs:line 50
at Microsoft.Office.Tools.Excel.WorksheetBase.Microsoft.Office.Tools.EntryPoint.FinishInitialization()
at Microsoft.VisualStudio.Tools.Office.Runtime.DomainCreator.ExecuteCustomization.ExecutePhase(ExecutionPhases executionPhases)
at Microsoft.VisualStudio.Tools.Office.Runtime.DomainCreator.ExecuteCustomization.Microsoft.VisualStudio.Tools.Office.Runtime.Interop.IExecuteCustomization2.ExecuteEntryPoints()
************** Loaded Assemblies **************
I am using the proper version of Excel and trying to perform a very simple task.
var list = new List<string>();
list.Add("Lann");
list.Add("Latl");
list.Add("LBBB");
var flatList = string.Join(",", list.ToArray());
var cell = Globals.Sheet8.Cells.Range["A2"];
cell.Validation.Delete();
cell.Validation.Add(
Excel.XlDVType.xlValidateList,
Excel.XlDVAlertStyle.xlValidAlertStop,
Excel.XlFormatConditionOperator.xlBetween,
flatList,
System.Type.Missing
);
cell.Validation.IgnoreBlank = true;
cell.Validation.InCellDropdown = true;
Any ideas?

The cell I was trying to write to was on a protected sheet. Using the Worksheet.Protect() and Worksheet.Unprotect() methods to toggle protection before and after the operation cleared up the error!

Related

Cudafy.Net System.ComponentModel.Win32Exception: The system cannot find the file specified

I downloaded cudafy here: https://github.com/lepoco/CUDAfy.NET/releases/tag/v.1.0.0.
I use VS 2022, .NET 4.8.
When executing this code, I get System.ComponentModel.Win32Exception.
CudafyModes.Target = eGPUType.Cuda;
CudafyModes.DeviceId = 0;
CudafyTranslator.Language = CudafyModes.Target == eGPUType.OpenCL ? eLanguage.OpenCL : eLanguage.Cuda;
if (CudafyHost.GetDeviceCount(CudafyModes.Target) == 0)
throw new System.ArgumentException("No suitable devices found.", "original");
GPGPU gpu = CudafyHost.GetDevice(CudafyModes.Target, CudafyModes.DeviceId);
CudafyModule km = CudafyTranslator.Cudafy(); //THE EXCEPTION IS HERE
gpu.LoadModule(km);
StackTrace:
in System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo)
in Cudafy.NvccExe.getClExeDirectory()
in Cudafy.CompilerHelper.Create(ePlatform platform, eArchitecture arch, eCudafyCompileMode mode, String workingDir, Boolean debugInfo)
in Cudafy.Translator.CudafyTranslator.Cudafy()
in Game.Position..ctor() in C:\Users\Lenovo\Desktop\simple\simple\Position.cs:line 464
in Game.Position.StartPos() in C:\Users\Lenovo\Desktop\simple\simple\Position.cs:line 490
in Game.Board..ctor() in C:\Users\Lenovo\Desktop\simple\simple\Board.cs:line 189
in Game.FrmMain..ctor() in C:\Users\Lenovo\Desktop\simple\simple\FrmMain.cs:line 18
in Game.Program.Main() in C:\Users\Lenovo\Desktop\simple\simple\Program.cs:line 19
Exception information:
ErrorCode -2147467259 int
HResult -2147467259 int
HelpLink null string
InnerException null
NativeErrorCode 2 int
Source "System" string
TargetSite {Boolean StartWithCreateProcess(System.Diagnostics.ProcessStartInfo)} System.Reflection.MethodBase {System.Reflection.RuntimeMethodInfo}
The Path environment variable is declared:
Path C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.30.30705\bin\Hostx64\x64
Cuda Toolkit 11.6 has been downloaded.
What can I do about it?
I solved the problem by connecting the source code. In particular, the program did not find the path to the utility vswhere.exe. Also the CUDA Toolkit required VS2010.

C# change console encoding error (bad descriptor)

Today i run Visual Studio and open my project, that i not opened about 5 months.
And running test (it was be OK) invoke IOException with additional information: "Bad descriptor".
It was in this line:
var defaultConsoleEncoding = Console.InputEncoding;
Console.InputEncoding = TryGetEncoding("UTF-8"); // <--- There is error
...
public static Encoding TryGetEncoding(string encoding)
{
try
{
return Encoding.GetEncoding(encoding);
}
catch (ArgumentException)
{
Logger.WarnAndPrint($"Can't using {encoding} encoding. Fallback to utf-8");
return Encoding.UTF8;
}
}
All my tests were OK, but now all fails with that error. I never chage code in project. And i try many encodings - nothing work.
What's the problem?
P.S. This is stack trace
System.IO.IOException was unhandled by user code
HResult=-2147024890
Message=Неверный дескриптор.
Source=mscorlib
StackTrace:
в System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
в System.Console.set_InputEncoding(Encoding value)
в PasswordListGenerator.Substitutions.Substitution.Process() в C:\GITHUB\passwordlistgenerator\PasswordListGenerator\PasswordListGenerator\Substitutions\Substitution.cs:строка 89
в PasswordListGeneratorTest.SubstitutionTests.SkipManySymbols_ShouldReturnSubstitutions() в C:\GITHUB\passwordlistgenerator\PasswordListGenerator\PasswordListGeneratorTest\SubstitutionTests.cs:строка 588
InnerException:

SOAP exception in WPF Application while accessing Web Service

I am learning C#, and in one of the assignment i have to display the data from an Access file into a DataGrid upon button click using a WPF Application, and a web reference.
There is a SOAP Exception which i am not able to resolve, any help is appreciated, thanks in advance -
Web reference asmx file contains the below method, that is called upon button click -
[WebMethod]
public ArrayList queryDB()
{
string selectStmt = "select * from Students";
OleDbConnection conn_obj = new DBConnect().checkDBStatus(databaseLocation);
conn_obj.Open();
OleDbCommand query = new OleDbCommand(selectStmt, conn_obj);
OleDbDataReader dbReader = query.ExecuteReader();
ArrayList dbRecordList = new ArrayList();
foreach (DbDataRecord dbRecord in dbReader)
{
dbRecordList.Add(dbRecord);
}
conn_obj.Close();
return dbRecordList;
}
WPF file code is as below - "Button click method"
private void GetData_Click(object sender, RoutedEventArgs e)
{
ArrayList datagridList = (ArrayList) websrvc.queryDB();
dataGrid.ItemsSource = datagridList;
}
The above code is creating an error - Cannot implicitly convert type 'object[]' to 'System.Collections.ArrayList'
Hence based on a suggestion over web, changed the code as below -
private void GetData_Click(object sender, RoutedEventArgs e)
{
object obj = websrvc.queryDB();
ArrayList datagridList = (ArrayList) obj;
dataGrid.ItemsSource = datagridList;
}
Now, there seems to be no errors, but an exception at the below line of code, which i am not able to solve -
object obj = websrvc.queryDB();
{"System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: System.Data.Common.DataRecordInternal cannot be serialized because it does not have a parameterless constructor.\n at System.Xml.Serialization.TypeDesc.CheckSupported()\n at System.Xml.Serialization.TypeScope.GetTypeDesc(Type type, MemberInfo source, Boolean directReference, Boolean throwOnError)\n at System.Xml.Serialization.XmlSerializationWriter.CreateUnknownTypeException(Type type)\n at System.Xml.Serialization.XmlSerializationWriter.WriteTypedPrimitive(String name, String ns, Object o, Boolean xsiType)\n at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write1_Object(String n, String ns, Object o, Boolean isNullable, Boolean needType)\n at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write2_queryDBResponse(Object[] p)\n at Microsoft.Xml.Serialization.GeneratedAssembly.ArrayOfObjectSerializer1.Serialize(Object objectToSerialize, XmlSerializationWriter writer)\n at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)\n --- End of inner exception stack trace ---\n at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)\n at System.Web.Services.Protocols.SoapServerProtocol.WriteReturns(Object[] returnValues, Stream outputStream)\n at System.Web.Services.Protocols.WebServiceHandler.WriteReturns(Object[] returnValues)\n at System.Web.Services.Protocols.WebServiceHandler.Invoke()\n --- End of inner exception stack trace ---"}
Create a class on web service side named Student with all the properties that you want to send to client.
Mark this class as serializable.
Map the DB object properties one by one to this Student class.
From the service, instead of returning ArrayList, return ArrayList();
Let me know if this works.

GTK# Pixbuf Icon in TreeView

I am trying to load icons/images from the web and put them into my TreeView. I have the following code (below) but each time it is run it throws an exception. I don't understand what I have done wrong here. Would you please be able to help me to write the correct code?
public void ImgCellRenderer(Gtk.TreeViewColumn column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter)
{
Gdk.Pixbuf icon = Gdk.PixbufLoader.LoadFromResource("http:\\\\www.free-icons-download.net\\images\\strawberry-icon-37824.png").Pixbuf;
(cell as Gtk.CellRendererPixbuf).Pixbuf = icon;
}
The exception in full is:
System.ArgumentException: 'http:\\www.free-icons-download.net\images\strawberry-icon-37824.png' is not a valid resource name of assembly 'MDM, Version=1.0.5862.27549, Culture=neutral, PublicKeyToken=null'.
at Gdk.PixbufLoader.InitFromAssemblyResource (System.Reflection.Assembly assembly, System.String resource) [0x00051] in /private/tmp/source-mono-mac-4.2.0-branch-64/bockbuild-mono-4.2.0-branch/profiles/mono-mac-xamarin/build-root/gtk-sharp-2.12.21/gdk/generated/PixbufLoader.custom:104
at Gdk.PixbufLoader..ctor (System.Reflection.Assembly assembly, System.String resource) [0x00020] in /private/tmp/source-mono-mac-4.2.0-branch-64/bockbuild-mono-4.2.0-branch/profiles/mono-mac-xamarin/build-root/gtk-sharp-2.12.21/gdk/generated/PixbufLoader.custom:94
at Gdk.PixbufLoader.LoadFromResource (System.String resource) [0x00007] in /private/tmp/source-mono-mac-4.2.0-branch-64/bockbuild-mono-4.2.0-branch/profiles/mono-mac-xamarin/build-root/gtk-sharp-2.12.21/gdk/generated/PixbufLoader.custom:142
at MDM.TweetSelectorWidget.ImgCellRenderer (Gtk.TreeViewColumn column, Gtk.CellRenderer cell, TreeModel model, TreeIter iter) [0x00006] in /Users/tribehive/Projects/MDM/MDM/TweetSelectorWidget.cs:160
at GtkSharp.TreeCellDataFuncWrapper.NativeCallback (IntPtr tree_column, IntPtr cell, IntPtr tree_model, IntPtr iter, IntPtr data) [0x0002c] in /private/tmp/source-mono-mac-4.2.0-branch-64/bockbuild-mono-4.2.0-branch/profiles/mono-mac-xamarin/build-root/gtk-sharp-2.12.21/gtk/generated/GtkSharp.TreeCellDataFuncNative.cs:57
at GLib.ExceptionManager.RaiseUnhandledException (System.Exception e, Boolean is_terminal) [0x0003b] in /private/tmp/source-mono-mac-4.2.0-branch-64/bockbuild-mono-4.2.0-branch/profiles/mono-mac-xamarin/build-root/gtk-sharp-2.12.21/glib/ExceptionManager.cs:58
at GtkSharp.TreeCellDataFuncWrapper.NativeCallback (IntPtr tree_column, IntPtr cell, IntPtr tree_model, IntPtr iter, IntPtr data) [0x00051] in /private/tmp/source-mono-mac-4.2.0-branch-64/bockbuild-
I have managed to solve it! #andlabs was correct in saying you can achieve this by creating a stream to load it. But this involves the creation of many objects (Stream, BinaryReaders, BinaryWriters, etc). Please see his comment for details. Thanks for your help andlabs.
The easier way to achieve this is with a WebClient. You will notice that you can create a Gdk.Pixbuf from a byte[]. So, to create a pixbuf from a downloaded image:
WebClient webClient = new WebClient();
byte[] image = webClient.DownloadDate(url);
Gdk.Pixbuf myPixbuf = new Gdk.Pixbuf(image);

Unable to cast object of type XXXXXX to type IXXXXX (.NET 4.0)

Can someone please explain what is happening to me? I have a test project that tests a dummy instance of my service. In the test project, I simply reference the dummyService.exe and System.SystemProcess dll.
In my dummyService project however, I have referenced the class library, which itself uses other dlls from other componentsn as well as other projects in my solution.
The problem is that when I run my test, exceptions get thrown( First Chance exceptions for dlls which are loaded and working in the dummyService), in addition invalidcast exception (error message below).
Unable to cast object of type 'Export.CaseOutputGenerator' to type 'Export.ICaseOutputGenerator'.
System.InvalidCastException was caught
Message=Unable to cast object of type 'Export.CaseOutputProcess.CustomCaseOutputGenerator' to type
'Export.CaseOutputProcess.ICaseOutputGenerator'.
Source=Export.CaseOutputProcess
StackTrace:
at Export.CaseOutputProcess.CaseOutputGeneratoryFactory.GetCaseOutputGeneratorObject(String assemblyName, String className)
in C:\Monitor\Export.CaseOutputProcess\CaseOutputGeneratoryFactory.cs:line 56
at Monitor.BOMock.GenerateCaseOutput(String OutputFolder, String iFile, Int32 seqNum, DataTable CaseSettings, String SettingFileName)
in C:\Monitor\BOMock\BOMock.cs:line 1069
at Monitor.BOMock.Handling() in C:\Monitor\BOMock\BOMock.cs:line 492 InnerException:
public static ICaseOutputGenerator GetCaseOutputGeneratorObject(string assemblyName, string className)
{
ICaseOutputGenerator customeOutputGen = null;
var obj = GetObject(assemblyName, className);
if (obj != null)
caseOutputGen = (ICaseOutputGenerator)obj; // FAILS HERE
return caseOutputGen;
}
private static object GetObject(string fullName, string className)
{
try
{
Type caseOutputGen = null;
var localAssembly = Assembly.LoadFrom(fullName);
foreach (var testType in localAssembly.GetTypes())
{
if (!testType.FullName.EndsWith(className, StringComparison.InvariantCultureIgnoreCase)) continue;
caseOutputGen = testType;
break;
}
if (caseOutputGen == null) return null;
var obj = Activator.CreateInstance(caseOutputGen);
return obj;
}
catch (FileNotFoundException ex)
{
throw new Exception("Failed to load assembly: " + Environment.NewLine + fullName, ex);
}
catch (Exception ex)
{
throw new Exception("Failed to load assembly: " + Environment.NewLine + fullName, ex);
}
}
Where assemblyName is the Path to the dll file to load and className happens to be the name of the class to create an instance of.
In the code, as you see, using reflection I load the assembly at the assemblyName PATH provided (String assemblyName) http://msdn.microsoft.com/en-us/library/system.reflection.assembly.loadfrom.aspx , and then using reflection again, I then create an instance of the className (String className ) contained in the loaded assembly. http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx
How do I remedy this problem please? I don't want to have to reference all my dlls in the test project. How do I get around or solve this problem please?? Thanks in advance.
Based on that stack trace, it looks like the assembly where the type lives is not being found. If you just add the reference to the compiled exe, you're probably not going to get the other libraries along with it. I think you've got a couple of choices:
Go ahead and bite the bullet: add the references to the other libraries in your test project. They're typically not transitive: just because your service knows about them doesn't necessarily follow that your test's assembly knows about them as well.
Add a post-compilation step to your test's project that copies over the other assemblies so that they can be found by the app domain running your test.
Use dependency injection and an inversion of control container. There are quite a few out there, but Castle Windsor, StructureMap and Unity come to mind. Scott Hanselman's got a great list of them on his blog: http://www.hanselman.com/blog/ListOfNETDependencyInjectionContainersIOC.aspx

Categories