How to serialize datatable with protobuffer. I am trying like Protobuff.serialize(dtDatatable);
But it doesn't work.
Getting Exception ::
Type is not expected, and no contract can be inferred: System.Data.DataSet
Related
I'm trying to get data for a gridview and have a cast error.
In the code below, if I just return "myuserlist" - all is good. As soon as I try to select only 2 fields (as in this code), I get the casting error. I've looked at other comments posted here regarding this problem and tried a number of things with no success.
Imports System.Linq
Imports RoutesEntities
Partial Class ProfileTest
Inherits System.Web.UI.Page
Private myentity As New RoutesEntities()
Public Function GridView1_GetData() As IQueryable(Of AllUser)
Return From myuserlist In myentity.AllUsers Select New With {myuserlist.UserName,myuserlist.Email}
End Function
Error:
System.InvalidCastException was unhandled by user code
HResult=-2147467262
Message=Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[VB$AnonymousType_0`2[System.String,System.String]]' to type 'System.Linq.IQueryable`1[AllUser]'.
Source=App_Web_oelfrca5
StackTrace:
at ProfileTest.GridView1_GetData() in C:\xxx\yyy\zzz\Profile.aspx.vb:line 10
InnerException:
I tried this (among other things):
Return From myuserlist In myentity.AllUsers Select New AllUser() With {
.UserName = myuserlist.UserName,
.Email = myuserlist.Email}
and got this:
Exception Details: System.NotSupportedException: The entity or complex type 'RoutesModel.AllUser' cannot be constructed in a LINQ to Entities query.
If you don't need the specific AllUser type at compile-time, you can have your function return an IQueryable(Of Object), or perhaps even a simple IQueryable:
Public Function GridView1_GetData() As IQueryable
Return From myuserlist In myentity.AllUsers Select New With {myuserlist.UserName,myuserlist.Email}
End Function
Update Return IQueryable(Of Object) if you'll need LINQ on the results:
Sub DataTest()
Dim qry = GridView1_GetData
Dim filteredQry = qry.Take(5)
End Sub
It is easier to do this with VB.NET than in C#, because VB.NET supports late binding -- even though the variable `x` is of type `Object`, and thus may not have a `UserName` property, the compiler will allow `UserName` to be resolved at runtime.
This is not as useful as it might be, because you can't pass an expression into the LINQ operator, e.g. you can use .Take or one overload of .Any, but not .Where.
I make some test to see how can bind combobox to some bean property, but i got an exception: "ConversionException: Could not convert value to String at ..........."
My sample work ok with indexedContainer for combobox, but i have some trouble with BeanItem container.
What i have:
1. TestCountry, simple java bean for BeanItemContainer (i don't put here setter and getter or constructor for simplicity):
public class TestCountry implements Serializable {
private String name;
private String shortName;
}
instantiation of BeanItemContainer
BeanItemContainer<TestCountry> _data = new BeanItemContainer<TestCountry>(TestCountry.class);
_data.addItem(new TestCountry("Afganistan","AF"));
_data.addItem(new TestCountry("Albania","AL"));
bean filed group. Here TestBean is another bean with simple string property's ("firstName","phone","contry")
BeanFieldGroup<TestBean> binder = new BeanFieldGroup<TestBean>(TestBean.class);
combobox
ComboBox myCombo = new ComboBox("Select your country", _data);
essential code
binder.bind(myCombo, "country");
When i try to commit the binder i got an error about conversion problem to string. From what i understand reading books and vaadin api, BeanItemContainer uses the beans themselves as identifiers and (here may be wrong) binder use item identifier to bind property. So here is the problem, conversion from Bean to string.
I try'it to implement toString(), hash() and equals() on my TestCountry bean but without success. What can do to use BeanItemContainer in this scenario?
Thanks in advance!!
You let your Vaadin application try to save a Bean (TestCountry) as a String in your TestBean.
That's fine, but then you have to approach it a little bit different. You have two options. You either change your datamodel, so the TestBean looks like this:
TestBean
firstName - String
phone - String
country - TestCountry (1:n)
now the TestBean will have a TestCountry stored instead of a String and your ComboBox shouldnt throw any more errors
or
you dont fill your ComboBox with Beans, but with Country strings, so the Vaadin application knows the datatype that is selected and what to save in your TestBean.
myCombo.addItem(getStringOfCountryYouWantToAdd())
...
then if you bind your String property "country" to the ComboBox which only contains Strings now, the binder will now how and what to save into "country".
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
Given the following declaration:
<Extension()> Public Function ToJSON(ByVal target As Object) As String
Dim serializer = New System.Runtime.Serialization.Json.DataContractJsonSerializer(target.GetType)
Using ms As MemoryStream = New MemoryStream()
serializer.WriteObject(ms, target)
ms.Flush()
Dim bytes As Byte() = ms.ToArray()
Dim json As String = Encoding.UTF8.GetString(bytes, 0, bytes.Length)
Return json
End Using
End Function
And the following lines in the Page_Load of a test page:
Dim kvp = New System.Collections.Generic.KeyValuePair(Of String, Object)(
"date", New HttpCookie("woot", "yikes")
)
Put(New HttpCookie("woot", "yikes").ToJSON)
Put(kvp.ToJSON)
Put(kvp.Value.ToJSON)
Put("here".ToJSON())
The first Put works perfect, and puts out the following JSON:
{"Domain":null,"Expires":"\/Date(-62135578800000-0500)\/",
"HttpOnly":false,"Name":"woot","Path":"\/",
"Secure":false,"Value":"yikes"}
The second Put, however, throws a giant, ugly error as so:
Type 'System.Web.HttpCookie' with data contract name 'HttpCookie:http://schemas.datacontract.org/2004/07/System.Web' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
The third Put throws an error also, but COMPLETELY different:
Public member 'ToJSON' on type 'HttpCookie' not found.
And the fourth Put works perfect.
I am very confused why, when the first line works, and the Extension method is clearly being found on the HttpCookie object, why then in the 2nd and 3rd Puts does it NOT work, and why do I get a different error in both cases? Each of the first three Puts is trying to do the same thing - call the ToJSON extension method on the HttpCookie object.
All exposition welcome!
The problem with the third Put is that VB doesn't support extension methods on anything declared to be of type Object: VB.NET: impossible to use Extension method on System.Object instance
This will work: Put(ToJSON(kvp.Value))
And so will this:
Dim kvp = New System.Collections.Generic.KeyValuePair(Of String, HttpCookie)(
"date", New HttpCookie("woot", "yikes"))
Put(kvp.Value.ToJSON)
Am getting an error mentioned below when I call my WCF service?How do i get rid of it?
There was an error while trying to serialize parameter http://tempuri.org/:MyWCFSvc.svc
The InnerException message was 'Type 'System.String[]' with data contract name 'ArrayOfstring:http://schemas.microsoft.com/2003/10/Serialization/Arrays'
is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.'. Please see InnerException for more details.*
I tried using [ServiceKnownType(typeof(string[]))] in my WCF service interface but no luck
A year late, but I had the same issue and here is what you need to do
List<SomeClass> mylist = new List<SomeClass>();
DataContractSerializer dcs = new DataContractSerializer(mylist.GetType());
XmlWriter writer = XmlWriter.Create(sb, XWS);
dcs.WriteObject(writer, query);
writer.Close();
The problem is when you construct your serializer with the typeof your class, the serialzer does not see it as an arrray, it only sees a single object.
If found it by doing this first:
DataContractSerializer dcs = new DataContractSerializer(SomeClass.GetType());
XmlWriter writer = XmlWriter.Create(sb, XWS);
dcs.WriteObject(writer, query[0]); // Only get the first record from linq to sql
writer.Close();
I too had the same issues but after qualifiying the OperationContract with [ServiceKnownType(typeof(string[]))] and [ServiceKnownType(typeof(int[]))] fixed the issue.
Eg:
[ServiceContract]
public interface IReportService
{
[OperationContract]
[ServiceKnownType(typeof(string[]))]
[ServiceKnownType(typeof(int[]))]
bool GenerateReport(int clientId, int masterId, string reportType, int[] vtIds, DateTime initialDate, DateTime finalDate,
bool descending, string userName, string timeZoneId, bool embedMap,
object[] vtExtraParameters, object[] vtScheduleParameters, string selectedCriteria,
out long reportID, out int scheduleID, out string message);
There's no reason for you to have to KnownType an array of strings. The serializer should already know about that, and arrays are not a problem. I'm moving Lists of things around in WCF without an issue. Could you post a representative sample of what you're doing?
Configuring service references on your client provides "Data Type" options that allow you to specify different types for Collection/Dictionary Types. What settings do you have in there?