Why i can not save list in c# list? - c#

I'm new in c# and write this class:
public class MANAGER
{
public string VersionName { get; set; }
public Double Value { get; set; }
}
and use this:
List<MANAGER> lstSummary = new List<MANAGER>();
MANAGER summary = new MANAGER();
summary.VersionName = "12";
summary.Value =12;
lstSummary.Add(summary);
summary.VersionName = "13";
summary.Value = 19;
lstSummary.Add(summary);
but up code just save latest class record ,means just save VersionName=13 and Value=19,How can i solve that problem?thanks.

You have to re-instantiate the summary variable like so:
MANAGER summary = new MANAGER();
summary.VersionName = "12";
summary.Value =12;
lstSummary.Add(summary);
summary = new MANAGER(); // <-- add this
summary.VersionName = "13";
summary.Value = 19;
lstSummary.Add(summary);

The problem as described in another answer is that you add the same object to the list multiple times, so you need to have a separate one. You can do it that way or don't use explicit the variable at all, since C# allows initializers. It will be pretty much the same logic, but a bit more nice and readable.
var lstSummary = new List<MANAGER>
{
new Manager
{
VersionName = "12",
Value = 12
},
new Manager
{
VersionName = "13",
Value = 19
}
}

Related

Why i can not call the web service in c#?

I'm new in c# and want too call the bank web service,in bank document write this:
call the BatchBillPaymentRequest method with ClientBatchBillPaymentRequestData object for input argumant :
BatchBillPaymentRequest(ClientBatchBillPaymentRequestData data)
for that purpose write this class:
class ClientBatchBillPaymentRequestData
{
public string CallbackUrl { get; set; }
public string LoginAccount { get; set; }
public int OrderId { get; set; }
public string BillId { get; set; }
public string PayId { get; set; }
public string AdditionalData { get; set; }
}
and write this code:
payment.BillService behzad=new BillService();
ClientBatchBillPaymentRequestData datas = new ClientBatchBillPaymentRequestData();
datas.BillId = "1233";
datas.CallbackUrl = "google.com";
datas.LoginAccount = "213214";
datas.OrderId = 123;
datas.PayId = "2131243";
datas.AdditionalData = "23213";
behzad.BatchBillPaymentRequest(datas);
but in this line:
behzad.BatchBillPaymentRequest(datas);
get this error:
Severity Code Description Project File Line Suppression State
Error CS1503 Argument 1: cannot convert from 'ConsoleApplication1.ClientBatchBillPaymentRequestData' to 'ConsoleApplication1.payment.ClientBatchBillPaymentRequestData' ConsoleApplication1 L:\TEMP\ConsoleApplication1\ConsoleApplication1\Program.cs 23 Active
what happen?how can i solve that problem?thanks.
VS add this class too project:
public ClientBatchBillPaymentResponseData BatchBillPaymentRequest(ClientBatchBillPaymentRequestData requestData) {
object[] results = this.Invoke("BatchBillPaymentRequest", new object[] {
requestData});
return ((ClientBatchBillPaymentResponseData)(results[0]));
}
As per Adriano Repetti's comment - when you added the web service reference Visual Studio created a class for you to use - so change this code from this
payment.BillService behzad=new BillService();
ClientBatchBillPaymentRequestData datas = new ClientBatchBillPaymentRequestData();
datas.BillId = "1233";
datas.CallbackUrl = "google.com";
datas.LoginAccount = "213214";
datas.OrderId = 123;
datas.PayId = "2131243";
datas.AdditionalData = "23213";
behzad.BatchBillPaymentRequest(datas);
to this
payment.BillService behzad=new BillService();
var datas = new ConsoleApplication1.payment.ClientBatchBillPaymentRequestData();
datas.BillId = "1233";
datas.CallbackUrl = "google.com";
datas.LoginAccount = "213214";
datas.OrderId = 123;
datas.PayId = "2131243";
datas.AdditionalData = "23213";
behzad.BatchBillPaymentRequest(datas);
You can streamline this a little by doing this instead too
payment.BillService behzad=new BillService();
var datas = new ConsoleApplication1.payment.ClientBatchBillPaymentRequestData{
BillId = "1233",
CallbackUrl = "google.com",
LoginAccount = "213214",
OrderId = 123,
PayId = "2131243",
AdditionalData = "23213"
}
behzad.BatchBillPaymentRequest(datas);
You should also remove the ClientBatchBillPaymentRequestData class you created as its surplus to requirements.
For each of the Attributes in your object instantiation, highlight it and press CTRL-Space to get autocomplete to correctly case your parameter name.
If you don't know the structure of your Webservice call you can use Wizdler for Chrome https://chrome.google.com/webstore/detail/wizdler/oebpmncolmhiapingjaagmapififiakb?hl=en to find out what the packets should be .
Once you install it, enter the WSDL URL in chrome, click the wizdler button to the right of the address bar and select the method you want to call, this will let you see the parameters (including their names and casing).

How may I store an array of Xamarin.Forms.Point in SQLite?

How may I store an array of Xamarin.Forms.Point in an SQLite database?
I have the following method:
async void OnSaveButtonClicked(object sender, EventArgs e)
{
var temp = padView.Points;
var tempArray = padView.Points.ToArray();
var databaseItem = new DatabaseItem
{
Name = Name.Text,
Date = Date.Date.ToString(),
//PadViewPoints =
};
//var databaseItem = (DatabaseItem)BindingContext;
await App.Database.SaveItemAsync(databaseItem);
await Navigation.PopAsync();
}
Given there is a signature on the padView, when stepping through the aforementioned method, I see that tempArray has a value of Xamarin.Forms.Point[76].
I'd like to store this array of points in the database so that I may load it later when loading the item.
As Jason said, you could store it as a string, a practical implementation of that would be:
var temp = padView.Points;
var tempArray = padView.Points.ToArray();
var databaseItem = new DatabaseItem
{
Name = Name.Text,
Date = Date.Date.ToString(),
PadViewPointsString = JsonConvert.SerializeObject(tempArray)
};
And in the DatabaseItem class:
public class DatabaseItem
{
// All other properties
string padViewPointsString;
public string PadViewPointsString
{
get => padViewPointsString;
set
{
padViewPointsString = value;
PadViewPoints = JsonConvert.DeserializeObject<Xamarin.Forms.Point[]>(value);
}
}
public Xamarin.Forms.Point[] PadViewPoints { get; set; }
}
This will make the class deserialize the string every time you set it's value (e.g. when you get it from the serialized database).
Obs. This example is using Newtonsoft.Json library
Hope this helps! :)

.net generic method VB.Net vs C#, since when vb is more flexible?

Have a generic function, it doesn't really mater what it is doing (FYI coping one list of object to another), main idea is that it has two types Ts and Tp
public static List<Tp> CreateAndFillList<Ts, Tp>(this IEnumerable<Ts> sItems) where Tp : class, new()
{
Type myType = default(Type);
PropertyInfo[] pSourceAllInfos = null;
if (pSourceAllInfos == null)
{
myType = typeof(Ts);
pSourceAllInfos = myType.GetProperties(BindingFlags.Public | BindingFlags.Instance).ToArray();
}
PropertyInfo[] pTargetAllInfos = null;
if (pTargetAllInfos == null)
{
myType = typeof(Tp);
pTargetAllInfos = myType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(pi => pi.CanWrite).ToArray();
}
var joinedPI = (from spi in pSourceAllInfos
join tpi in pTargetAllInfos on spi.Name.ToLower() equals tpi.Name.ToLower()
select new { spi, tpi }).ToList();
List<Tp> retList = new List<Tp>();
foreach (var sItem in sItems)
{
Tp tpNewItem = new Tp();
foreach (var jpi in joinedPI)
{
jpi.tpi.SetValue(tpNewItem, jpi.spi.GetValue(sItem, null), null);
}
retList.Add(tpNewItem);
}
return retList;
}
Have two simple classes
public class SourceInfo
{
public int Id { get; set; }
public string Name { get; set; }
public string SourceData { get; set; }
}
public class TargetInfo
{
public int Id { get; set; }
public string Name { get; set; }
public string TargetData { get; set; }
}
My problem is that following code throw compilation error
private void button1_Click(object sender, EventArgs e)
{
List<SourceInfo> srcLst = new List<SourceInfo>();
srcLst.Add(new SourceInfo() { Id = 1, Name = "First", SourceData = "data1" });
srcLst.Add(new SourceInfo() { Id = 2, Name = "Second", SourceData = "data2" });
var q = from li in srcLst
select new { li.Id, li.Name };
dynamic qD = from li in srcLst
select new { li.Id, li.Name };
var resultLst = srcLst.CreateAndFillList<TargetInfo>();
//Using the generic method 'ExtensionTest.Extensions.CreateAndFillList<Ts,Tp>(System.Collections.Generic.IEnumerable<Ts>)' requires 2 type arguments
var resultLst1 = q.CreateAndFillList<TargetInfo>();
//Using the generic method 'ExtensionTest.Extensions.CreateAndFillList<Ts,Tp>(System.Collections.Generic.IEnumerable<Ts>)' requires 2 type arguments
var resultLst2 = qD.CreateAndFillList<TargetInfo>();
//works but will have to use dynamic...
}
And at the same time in VB.Net everything is ok!!!!
Dim lst As List(Of SourceInfo) = New List(Of SourceInfo)()
lst.Add(New SourceInfo() With {.Id = 1, .Name = "First"})
lst.Add(New SourceInfo() With {.Id = 2, .Name = "Second"})
Dim q = From li In lst
Select New With {li.Id, li.Name}
Dim retLst = lst.CreateAndFillList(Of TargetInfo)()
Dim retLst1 = q.CreateAndFillList(Of TargetInfo)()
My problem is I don't want to use dynamic everywhere because it will require extra coding plus it is run-time compilation.
What I am doing wrong in C#? please help.
The compiler message is quite clear about the problem: You need to specify both type arguments. If you specify only one, it is unclear which of both parameters it should be.
var resultLst = srcLst.CreateAndFillList<SourceInfo, TargetInfo>();
var resultLst1 = q.CreateAndFillList<SourceInfo, TargetInfo>();
And this:
dynamic qD = from li in srcLst
select new { li.Id, li.Name };
does not need to be dynamic. var is more appropriate here and will give you compile-time errors. If you do this, you get the same error for qD:
var resultLst2 = qD.CreateAndFillList<SourceInfo, TargetInfo>();
Otherwise, you will get the error only at runtime.
What I am doing wrong in C#?
The compiler won't partially infer generic parameters. Using dynamic defers that check to runtime, where it will likely fail. You need to supply both the input and output generic parameters in your call to CreateAndFillList.
var resultLst = srcLst.CreateAndFillList<SourceInfo, TargetInfo>();

Create a list of classes

I need to create a list of classes. I don`t want to uses "Insert", since the amount of data is small and adding ll data all together might be more readable.
Unfortunatelly I even cant compile the code :
List<MyArg> perfTestsArgs = new List<MyArg>(
{ new MyArg("columns","1"),
new MyArg("rows","1"),
new MyArg("batch","1"),
new MyArg("trips","400"),
new MyArg("strict","true"),
new MyArg("valueLength","1"),
}); //<- problematic (why?)
public class MyArg
{
public string ArgName { get; set; }
public string ArgValue { get; set; }
public PerformanceTestsArg(string argName, string argValue)
{
ArgName = argName;
ArgValue = argValue;
}
}
I`ll appreciate the advice how to do that correctely
Remove the () from new List<MyArg>.
List<MyArg> perfTestsArgs = new List<MyArg>() // <- close the bracket here, or remove () as #Mihai said
{ new MyArg("columns","1"),
new MyArg("rows","1"),
new MyArg("batch","1"),
new MyArg("trips","400"),
new MyArg("strict","true"),
new MyArg("valueLength","1"),
};
more details on initializing objects here: http://msdn.microsoft.com/en-us/library/bb384062.aspx

Issue with list in C# -- MVC

I have issue in the following code. Below is my model code
public class Comments
{
public string displayComments { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? dTime { get; set; }
public int airPortId { get; set; }
}
public class LstComments
{
private List<Comments> _lstcomment = new List<Comments>();
public List<Comments> lstCommet
{
get
{
return _lstcomment;
}
set
{
_lstcomment = value;
}
}
}
and in mycontroller am getting data from EF and adding it to the properties in For loop. Code Below
Comments com = new Comments();
LstComments savedComments = new LstComments();
AirportEntities airPortEntity = new AirportEntities();
var userComments = from c in airPortEntity.AirportComments
select c;
//List<Comments> savedComments = new List<Comments>();
foreach (var item in userComments)
{
com.displayComments = item.Comments;
com.dTime = item.Time;
savedComments.lstCommet.Add(com);
}
My issue is my entire list is getting updated with same records(recently added data)
For eg. foreach 3rd timn updates both 1st and 2nd 3rd item in list with 3rd item data.
What i am doing wrong ?
You instantiate Comments outside of the loop. This means there are a bunch of references to the same comment object on the heap. You need to do
Comments com = new Comments(); inside of the foreach. This will create a separate instance on each iteration, instead of just giving the one instance new values.
you need to instantiate Comments com = new Comments(); each time in foreach. As for now you just rewrite reference to the same object.
Or which is better to rewrite foreach as:
foreach (var item in userComments)
{
savedComments.lstCommet.Add(
new Comments()
{
com.displayComments = item.Comments,
com.dTime = item.Time
});
}

Categories