SqlConnection DBConnection Windowsce - compact-framework

I'm writing this piece of code in Compact Framework 3.5 under Windows CE 5.0 to handle two different databases:
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlServerCe;
using System.Data.Common;
public myClass
{
private DbConnection dbCn;
private DbCommand dbCmd;
public void myClass(bool ce)
{
if (ce)
{
dbCn = new SqlCeConnection();
dbCmd = new SqlCeCommand();
}
else
{
dbCn = new SqlConnection(); // COMPILER ERROR Cannot implicitly convert type 'System.Data.SqlClient.SqlConnection' to 'System.Data.Common.DbConnection'
dbCmd = new SqlCommand();// COMPILER ERROR Cannot implicitly convert type 'System.Data.SqlClient.SqlCommand' to 'System.Data.Common.DbCommand'
}
}
Why it cannot convert SqlXX to DbXX ??? from MSDN SqlXX are children of DbXX! Btw, no problem with SqlCeXX.
I can not use DbPoviderfactory that is missing from cf.
Thanks

What you are trying to do is Covariance and Contravariance in Generics, but that did not come out until .NET 4.0.
[Update] It appears that casting from [DbConnection] to [SqlConnection] could leave out a few parameters, so Microsoft does not allow simple casts.
If you really want to get it done, check out this thread on SO with some good How To code:
C# DbConnection cast to SqlConnection

Related

How can I implement Bulk insert in ASP.NET Core 1.0?

I want to import the data from database in .csv format and want to export .csv into my SQL server/Oracle database. I am using ASP.NET Core RC 1 at this moment. I looked into SQLBulkCopy class but the issue is that it is not ported to ASP.NET Core.
Can someone tell me how can I do it or is there any other compatible nuget package available (with ASP.NET Core)?
Microsoft has added SqlBulkCopy to .NET Core, so you can bring it in as part of the System.Data.SqlClient NuGet package. I opted to use FastMember by #MarcGravell to handle the work of mapping my data, but you don't have to.
FastMember will take a collection of parameters, and a collection of objects, and pull the values off your objects that map to your collection of parameters. Really simplifies the code.
private async Task OutputPerformanceDataToStorage(List<PerformanceData> dataToSave)
{
var storageParameters = new[]
{
nameof(PerformanceData.PerformanceId),
nameof(PerformanceData.IPAddress),
nameof(PerformanceData.ControllerName),
nameof(PerformanceData.ActionName),
nameof(PerformanceData.ActionParameters),
nameof(PerformanceData.ViewPath),
nameof(PerformanceData.TotalRequestTimeInMilliseconds),
nameof(PerformanceData.RequestStartedTimestamp),
nameof(PerformanceData.RequestEndedTimestamp),
nameof(PerformanceData.CreatedDateTime),
};
var sqlCopy = new SqlBulkCopy(this.connectionString, SqlBulkCopyOptions.Default);
sqlCopy.DestinationTableName = "[Performance]";
using (var reader = ObjectReader.Create(dataToSave, storageParameters))
{
await sqlCopy.WriteToServerAsync(reader);
}
}
internal class PerformanceData
{
public Guid PerformanceId;
public double TotalRequestTimeInMilliseconds;
public long RequestStartedTimestamp;
public long RequestEndedTimestamp;
public string IPAddress;
public string ControllerName;
public string ActionName;
public string ViewPath;
public string ActionParameters;
public List<string> ActionParametersList;
public DateTime CreatedDateTime;
}
.NET Standard 2.0 now supports many of the .NET framework libraries which means that SqlBulkCopy class can be used with ASP.NET Core. Dataset, Datatables and SQLBulkCopy will do the job for bulk insertion. Find more details about .NETStandard 2.0 here.

.NET 4.5.1 WCF Serialization exception

Our LOB application is a client server application which uses CSLA business objects, those business objects are being serialized using the NetDataContractSerializer. The server side is running on WCF and the client has endpoints.
This all works when the client software is running from Windows 7 or Windows 8 having .NET 4.5 installed.
When running the client software on Windows 8 or Windows 8.1 with the latest .NET 4.5.1 Framework the following exception occurs.
The formatter threw an exception while trying to deserialize the
message: There was an error while trying to deserialize parameter
http://ws.lhotka.net/WcfDataPortal:FetchResult. The InnerException
message was 'Error in line 1 position 11619. 'Element'
'm_serializationArray' from namespace
'http://schemas.microsoft.com/2003/10/Serialization/Arrays' is not
expected. Expecting element 'm_keyRehashCount'.'. Please see
InnerException for more details.
The most inner exception is
Error in line 1 position 11619. 'Element' 'm_serializationArray' from
namespace 'http://schemas.microsoft.com/2003/10/Serialization/Arrays'
is not expected. Expecting element 'm_keyRehashCount'.
I cannot find anything about this on stackoverflow or on google, i have posted this same question on the CSLA forums and perhaps i should also post it on Connect. But maybe i'm lucky here?
I need some time to backup my development environment before i update the .NET Framework to 4.5.1
I can think of two possible solutions:
upgrade the 2008 server to .NET 4.5.1.
force the client software to use .NET 4.5
Is it possible to force the client software to use .NET 4.5 only?
Any other idea's?
I can reproduce this issue from my end. I would like to give a few facts to see if this would help you in the meantime.
NetDataContractSerializer is more restrictive than a DataContractSerializer as per the documentation.
The NetDataContractSerializer differs from the DataContractSerializer in one important way: the NetDataContractSerializer includes CLR type information in the serialized XML, whereas the DataContractSerializer does not. Therefore, the NetDataContractSerializer can be used only if both the serializing and deserializing ends share the same CLR types.
I believe the type ConcurrentDictionary in 4.5.1 has added a property or member variable named m_keyRehashCount which is not found in the 4.5 version of the ConcurrentDictionary. While trying to de-serialize this object on a 4.5.1 machine – the serializer expects this missing property resulting in this exception.
<m_keyRehashCount>0</m_keyRehashCount>
Here are a few ways to solve this problem:
Upgrade your server machine as well to 4.5.1. .net 4.5.1 is a free upgrade to .net 4.5 which also has fixes for some compat issues found in .net 4.5.
Use DataContractSerializer instead of NetDataContractSerializer as this
does not expect the exact same CLR types at both serializing and
deserializing ends.
Change to use Dictionary instead
of a ConcurrentDictionary as I see this type works
fine.
If you have previously serialized objects (serialized with pre 4.5.1) which contain ConcurrentDictionary you can deserialize it in 4.5.1 using the following example.
This example only help deserializing already serialized ConcurrentDictionary objects by creating new class which can deserialize using the ConcurrentDictionary serialization XML, see also other answers.
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using ClassLibrary1.Model;
namespace SerializaerDesrializer
{
[DataContract]
public class CompositeDictionaryHolder
{
// Old serialized data member:
//[DataMember]
//private MyConcurrentDictionary<int, string> _concuurentDictionary = new MyConcurrentDictionary<int, string>();
private ConcurrentDictionary<int, string> _concuurentDictionaryInternal = new ConcurrentDictionary<int, string>();
[DataMember]
private InternalArray _concuurentDictionary;
public CompositeDictionaryHolder()
{
// Just an example:
_concuurentDictionaryInternal.TryAdd(1, "1");
_concuurentDictionaryInternal.TryAdd(2, "2");
_concuurentDictionaryInternal.TryAdd(3, "3");
}
/// <summary>
/// Get the data array to be serialized
/// </summary>
[OnSerializing]
private void OnSerializing(StreamingContext context)
{
// save the data into the serialization array to be saved
_concuurentDictionary = new InternalArray(_concuurentDictionaryInternal.ToArray());
}
/// <summary>
/// Construct the dictionary from a previously seiralized one
/// </summary>
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
_concuurentDictionaryInternal = new ConcurrentDictionary<int, string>(_concuurentDictionary.m_serializationArray);
}
}
[DataContract(
Namespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays")]
public class InternalArray
{
public InternalArray()
{
}
public InternalArray(KeyValuePair<int, string>[] serializationArray)
{
m_serializationArrayInternal = serializationArray;
}
[DataMember]
public KeyValuePair<int, string>[] m_serializationArray
{
get { return m_serializationArrayInternal; }
set { m_serializationArrayInternal = value; }
}
private KeyValuePair<int, string>[] m_serializationArrayInternal;
}
}

Ninject configuration - generics

I have a group of base repositories that are setup like this ...
Bind<IRepository<SomeObject>>().To<SomeObjectRepository>().WithConstructorArgument("connection", connection);
Bind<IRepository<SomeOtherObject>>().To<SomeOtherObjectRepository>().WithConstructorArgument("connection", connection);
//and so on
Those repositories are simple - the whole class goes as such.
public class SomeObjectRepository : Repository<SomeObject>
{
public SomeObjectRepository (string connection) : base(connection)
{
}
}
So I thought, hey that's kinda dumb, so I created a generic base repository and replaced all those bindings with this.
Bind(typeof(IRepository<>)).To(typeof(Repository<>)).WithConstructorArgument("connection", connection);
which of course broke and got hit with an error
Error activating
IRepository{SomeObject} using binding
from IRepository{T} to Repository{T}
No constructor was available to create
an instance of the implementation
type.
Why wouldn't this work?
A little late but you need to be binding IRepository to SomeObjectRepository.

using jna with FAR PASCAL custom dll

I am using JNA to access a custom DLL which seems to be using the FAR PASCAL Calling Conventions, but the JVM crashes every time i try to access it.
Development Guide of the dll says:
BOOL FAR PASCAL GetIomemVersion(LPSTR);
And Dependency Walker tells me:
_GetIomemVersion#4
public class PebblePrinter {
public interface Iomem extends StdCallLibrary {
boolean _GetIomemVersion(String version);
}
String version;
Iomem INSTANCE;
StdCallFunctionMapper myMapper;
public PebblePrinter() {
HashMap optionMap = new HashMap();
myMapper = new StdCallFunctionMapper();
optionMap.put(Library.OPTION_FUNCTION_MAPPER, myMapper);
INSTANCE = (Iomem)Native.loadLibrary("iomem", Iomem.class,optionMap);
}
public String getIomemVersion(){
INSTANCE._GetIomemVersion(version);
return version;
}
}
With C# code it works well using
[DllImport("iomem.dll", EntryPoint = "_GetIomemVersion#4")]
public static extern bool GetIomemVersion(IntPtr version);
Can you tell me what i am doing wrong?
Thanks in advance!!!
Problem solved,
I've just used the wrong parameter ..
GetIomemVersion needs a Pointer
boolean _GetIomemVersion(Pointer version);
public String getIomemVersion(){
Memory m = new Memory(1024);
Pointer x = m.getPointer(0);
INSTANCE._GetIomemVersion(x);
return x.getString(0);
}

Class is not found in SQL assembly

I am trying to make my first CLR Assembly\stored procedure. I have compiled the code using CSC, and added the assembly to SQL server. The assembly shows up, but the class seems to be missing.
C# CODE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.SqlServer.Server;
namespace TextFunctions
public class RegularExpressions
{
[Microsoft.SqlServer.Server.SqlFunction]
public static string RegExReplace(string input, string pattern, string replacement)
{
Regex Reginstance = new Regex(pattern);
return Reginstance.Replace(input, replacement);
}
}
END C# CODE
CREATE FUNCTION CODE
CREATE Function RegExReplace(#Input NVARCHAR(512),#Pattern NVARCHAR(127), #Replacement NVARCHAR(512))
RETURNS NVARCHAR(512) EXTERNAL NAME RegEx.RegularExpressions.RegExReplace
ERROR
Could not find Type 'RegularExpressions' in assembly 'RegEx'.
1) Can you see what I am doing rough?
2) Is there a table or view in sql server that lets me see the classes and functions inside an assembly?
According to your code snippet your RegularExpressions class is in the TextFunctions namespace.
Changing your T-SQL code to use TextFunctions.RegularExpressions.RegExReplace should fix it.