How to combine lists into single data entity in c# - c#

I have a web method in a c# web service which creates three lists, which are filled from xml input. I want to combine these three lists into one entity (a DataSet would be the best, as the iOS app that is consuming this web service is already programmed to accept and parse DataSets), and return them from the web method.
Here is currently what my code looks like:
[WebMethod]
public DataSet SelectObjects(string ExternalID, string Password)
{
DataSet ds = new DataSet();
MembershipAuthServiceReference.MembershipAuthenticationService objService = new MembershipAuthServiceReference.MembershipAuthenticationService();
MembershipAuthServiceReference.SoapHeaderCredentials objSoapHeader = new MembershipAuthServiceReference.SoapHeaderCredentials();
MembershipAuthServiceReference.MemberUserInfo objMemberInfo = new MembershipAuthServiceReference.MemberUserInfo();
try
{
objSoapHeader.UserName = ExternalID;
objSoapHeader.Password = Password;
objMemberInfo = objService.GetMembershipInfo();
List<Obj1> ListObj1 = new List<Obj1>();
for (int i = 0; i < objMemberInfo.Obj1.Length; i++)
{
Obj1 obj_Obj1 = new Obj1();
obj_Obj1.Stuff = objMemberInfo.Obj1[i].Stuff.ToString();
ListObj1.Add(obj_Obj1);
}
List<Obj2> ListObj2 = new List<Obj2>();
for (int i = 0; i < objMemberInfo.Obj2.Length; i++)
{
Obj2 obj_Obj2 = new Obj2();
obj_Obj2.Stuff = objMemberInfo.Obj2[i].Stuff.ToString();
ListObj2.Add(obj_Obj2);
}
List<Obj3> ListObj3 = new List<Obj3>();
for (int i = 0; i < objMemberInfo.Obj3.Length; i++)
{
Obj3 obj_Obj3 = new Obj3();
obj_Obj3.Stuff = objMemberInfo.Obj3[i].Stuff.ToString();
ListObj3.Add(obj_Obj3);
}
}
catch (Exception ex)
{
string sError;
sError = ex.Message.ToString();
}
return ds;
}
How do I combine these lists into a DataSet? I'm assuming it's possible? If not, is there a viable alternative that does the same thing?

First concatenate your lists as shown below and then use the link to generate the dataset
var combinedList= ListObj1.Concat(ListObj2).Concat(ListObj3);
How do I transform a List<T> into a DataSet?

Related

Converting ArrayOfStrings to string array

I have searched for a long time and tried different ways to solve this problem without any success.
My current program is as follows:
Web service: DAL, Controller and WebService(with web methods)
Windows form: Controller(receives the web service) and Form
I receive a string array in the DAL that I try to send through the web service to my Controller in the windows form program. But receive the error:
Cannot implicity convert type
'WindowsFormApplication.ServiceReference1.ArrayOfString' to
'System.Collections.Generic.List<string[]>'
Controller in form:
public List<string[]> GetAllEmployee()
{
return client.GetAllEmployee();
}
Webservice:
public List<string[]> GetAllEmployee()
{
return cont.GetAllEmployee();
}
DAL:
public List<string[]> GetAllEmployee()
{
GetConnection();
con.Open();
stmt = con.CreateCommand();
stmt.CommandText = "SELECT [No_],[First Name],[Last Name],[Initials],[Job Title],[E-Mail] FROM [CRONUS Sverige AB$Employee]";
OdbcDataReader reader = stmt.ExecuteReader();
List<string[]> allEmployee = new List<string[]>();
String[] cols = new string[5];
for (int i = 0; i < cols.Length; ++i)
{
cols[i] = reader.GetName(i);
}
allEmployee.Add(cols);
while (reader.Read())
{
string[] s = new string[cols.Length];
for (int i = 0; i < s.Length; ++i)
{
s[i] = reader.GetValue(i).ToString();
}
allEmployee.Add(s);
}
con.Close();
return allEmployee;
}
Controller:
public List<string[]> GetAllEmployee()
{
return dal.GetAllEmployee();
}
client:
ServiceReference1.WebService1SoapClient client = new ServiceReference1.WebService1SoapClient();
Your service returns the type WindowsFormApplication.ServiceReference1.ArrayOfString which needs to be explicitly converted to List<string> with ToList Method:
return dal.GetAllEmployee().ToList();

insert only new data instead duplicate the existing data

I have this code running calling the data from the core system,
public int MuatTurunMTS(hopesWcfRef.Manifest2 entParam, string destination, int capacity)
{
try
{
EL.iSeriesWcf.IiSeriesClient iClient = new iSeriesWcf.IiSeriesClient();
EL.iSeriesWcf.Manifest2 manifest2 = new iSeriesWcf.Manifest2();
manifest2 = iClient.GetManifest2(entParam.NOKT, destination, capacity);
DataTable dt = new DataTable();
dt = manifest2.Manifest2Table;
List<hopesWcfRef.Manifest2> LstManifest2 = new List<hopesWcfRef.Manifest2>();
for (int i = 0; i < dt.Rows.Count; i++)
{
hopesWcfRef.Manifest2 newDataRow = new hopesWcfRef.Manifest2();
newDataRow.NOPASPOT = dt.Rows[i][1].ToString();
newDataRow.NOKT = dt.Rows[i][0].ToString();
newDataRow.KOD_PGKT = dt.Rows[i][2].ToString();
newDataRow.KOD_KLGA = dt.Rows[i][3].ToString();
newDataRow.NAMA = dt.Rows[i][4].ToString();
newDataRow.TKHLAHIR = (dt.Rows[i][5].ToString() == "1/1/0001 12:00:00 AM" ? DateTime.Now : Convert.ToDateTime(dt.Rows[i][5])); //Convert.ToDateTime(dt.Rows[i][5]);
newDataRow.JANTINA = dt.Rows[i][6].ToString();
newDataRow.WARGANEGARA = dt.Rows[i][7].ToString();
newDataRow.JNS_JEMAAH = dt.Rows[i][8].ToString();
newDataRow.NO_SIRI = dt.Rows[i][9].ToString();
newDataRow.NO_MS = Convert.ToInt16(dt.Rows[i][10]);
newDataRow.BARKOD = dt.Rows[i][13].ToString();
newDataRow.NO_DAFTAR = dt.Rows[i][14].ToString();
//bydefault make cell empty
newDataRow.STS_JEMAAH = "";
newDataRow.SEAT_NO = "";
newDataRow.SEAT_ZONE = "";
newDataRow.BERAT = 0;
newDataRow.JUM_BEG = 0;
LstManifest2.Add(newDataRow);
}
int cntr = 0;
if (LstManifest2.Count != 0)
{
foreach (hopesWcfRef.Manifest2 manifest in LstManifest2)
{
cntr++;
SaveManifestTS(manifest);
}
}
return LstManifest2.Count;
}
catch (Exception ex)
{
throw ex;
}
}
And goes to :
public void SaveManifestTS(hopesWcfRef.Manifest2 manifest)
{
try
{
ent.BeginSaveChanges(SaveChangesOptions.Batch, null, null);
ent.AddObject("Manifest2", manifest);
ent.SaveChanges(SaveChangesOptions.Batch);
}
catch (Exception ex)
{
//Uri u = new Uri(ent.BaseUri + "GetErrorMsg"
// , UriKind.RelativeOrAbsolute);
//string datas = (ent.Execute<string>(u)).FirstOrDefault();
//Exception ex = new Exception(datas);
throw ex;
}
}
When SaveChanges run, if the data exist it will duplicate the entire row,
How to avoid the data being duplicate when insert (savechanges)??????
Many Thanks
What about: Do not insert.
In these cases I am using a MERGE statement that updates existing data (based on primary key) and inserts new data.
Oh, and all the code example you loved to post is totally irrelevant to the question, which is a pure SQL side question. You literally quote your car manual then asking which direction to turn.

Input data into a gridview with C#, ASP.net.

I am using a dataset that was created seperatley and is being used as a reference.
I need to create a gridview with data that comes from the dataset.
Coding is not the ASP.net code, but the C# code.
I just need to make one column of information.
Teacher has not taught us this and is on an assignment. If you can give me a link or type an example that would be great.
one way to doing is to bind the required columns with empty rows to the datatable and then binding the datatable to the girdview...i have given you a sample below
public void GenerateColumns()
{
dtblDummy = new DataTable("dtblDummy");
dtDummyColumn = new DataColumn("FirstName");
dtblDummy.Columns.Add(dtDummyColumn);
dtDummyColumn = new DataColumn("LastName");
dtblDummy.Columns.Add(dtDummyColumn);
dtDummyColumn = new DataColumn("Email");
dtblDummy.Columns.Add(dtDummyColumn);
dtDummyColumn = new DataColumn("Login");
dtblDummy.Columns.Add(dtDummyColumn);
dtDummyColumn = new DataColumn("Password");
dtblDummy.Columns.Add(dtDummyColumn);
dtDummyColumn = new DataColumn("Role");
dtblDummy.Columns.Add(dtDummyColumn);
dtDummyColumn = new DataColumn("RoleId");
dtblDummy.Columns.Add(dtDummyColumn);
}
public void GenerateRows(int intRow)
{
for(int intCounter = intRow; intCounter < intRow; intCounter++)
{
dtDummyRow = dtblDummy.NewRow();
dtDummyRow["FirstName"] = "";
dtDummyRow["LastName"] = "";
dtDummyRow["Email"] = "";
dtDummyRow["Login"] = "";
dtblDummy.Rows.Add(dtDummyRow);
}
dgrdUsers.DataSource = dtblDummy;
dgrdUsers.DataBind();
dtblDummy = null;
dtDummyRow = null;
dtDummyColumn = null;
}
in the above code dgrdUsers is the gridview control, and declare the dummy row, column and datatable above the page load function.
call the above two functions in your page load under ispostback....
dont forget the create the same no of columns as template column in your gridview...

How to get SQL Server version only by the server name?

Say, if what I have is only a server name obtained from this enumeration:
//Collect server names
List<string> arrServerNames = new List<string>();
try
{
// Perform the enumeration
DataTable dataTable = null;
try
{
dataTable = System.Data.Sql.SqlDataSourceEnumerator.Instance.GetDataSources();
}
catch
{
dataTable = new DataTable();
dataTable.Locale = System.Globalization.CultureInfo.InvariantCulture;
}
// Create the object array of server names (with instances appended)
for (int i = 0; i < dataTable.Rows.Count; i++)
{
string name = dataTable.Rows[i]["ServerName"].ToString();
string instance = dataTable.Rows[i]["InstanceName"].ToString();
if (instance.Length == 0)
{
arrServerNames.Add(name);
}
else
{
arrServerNames.Add(name + "\\" + instance);
}
}
}
catch
{
//Error
}
How can I know the SQL Server version installed on that server?
Checking the official MSDN documentation for GetDataSources() would have easily revealed that there is a Version column in the result set:
// Create the object array of server names (with instances appended)
for (int i = 0; i < dataTable.Rows.Count; i++)
{
string name = dataTable.Rows[i]["ServerName"].ToString();
string instance = dataTable.Rows[i]["InstanceName"].ToString();
string version = dataTable.Rows[i]["Version"].ToString(); // this gets the version!
..........
}

xml data into a dataset

I'm trying to get this xml info into a table.
I've tried reading the xml into a dataset...
string myXMLfile = #"..\..\..\BR7.xml";
//http://tatts.com/pagedata/racing/2011/10/5/BR7.xml
//http://tatts.com/racing/2011/10/5/BR/7
DataSet ds = new DataSet();
try
{
ds.ReadXml(myXMLfile);
for (int i = 0; i < ds.Tables.Count; i++)
{
listBox1.Items.Add(ds.Tables[i].TableName);
}
dgvRunner.DataSource = ds;
dgvRunner.DataMember = "Runner";
dgvWinOdds.DataSource = ds;
dgvWinOdds.DataMember = "WinOdds";
dgvPlaceOdds.DataSource = ds;
dgvPlaceOdds.DataMember = "PlaceOdds";
dgvFixedOdds.DataSource = ds;
dgvFixedOdds.DataMember = "FixedOdds";
but I get four separate tables. Runner, WinOdds, PlaceOdds, and fixedOdds
How do I get all the information for a Runner into a single table?
Here's some of the xml...
-<Runner RunnerNo="1" Rtng="93" LastResult="0X1" Form="W" Weight="57.0" Handicap="0" Barrier="10" RiderChanged="N" Rider="P SCHMIDT(A)" Scratched="N" RunnerName="PREACHER BOY">
<WinOdds CalcTime="2011-10-05T16:51:07" LastCalcTime="2011-10-05T16:46:32" Short="N" Lastodds="11.50" Odds="10.70"/>
<PlaceOdds Short="N" Lastodds="3.50" Odds="3.30"/>
-<FixedOdds RaceDayDate="2011-10-05T00:00:00" MeetingCode="BR" RaceNo="07" RunnerNo="01" LateScratching="0" Status="w" OfferName="PREACHER BOY" RetailPlaceOdds="3.3500" RetailWinOdds="12.0000" PlaceOdds="3.3500" WinOdds="12.0000" OfferId="981020"><Book SubEventId="863449" BookStatus="F"/>
</FixedOdds>
</Runner>
You should have the information about RunnerNo in every table (it is missing on WinOdd and PlaceOdds) so that you can relate your four datatables. You can define a the RunnerNo as Unique
After that you and use only one gridview and assing that relation between the four datatables as the gridview's DataMember.
here is a sample of how a relation should look like
I would propose an approach of moving all the attributes of the Runner children attributes to the Runner node attributes collection. This takes the following assumptions:
Each nested element in the Runner nodes has maximum 1 nested element inside it (i.e. there is only one Book element inside the FixedOdds element)
The attributes will be renamed by prefixing them with the name of their originating node (the CalcTime attribute in the WinOdds element will be copied in the Runner attribute's collection with the name WinOddsCalcTime)
You can keep or delete the children nodes (I chose to delete them in the code sample)
Here's the code:
string myXMLfile = #"xml.xml";
DataSet ds = new DataSet();
try
{
XmlDocument doc = new XmlDocument();
doc.Load(myXMLfile);
var runners = doc.SelectNodes("/Runner");
foreach (XmlNode runner in runners)
{
foreach (XmlNode child in runner.ChildNodes)
{
for (int i = 0; i < child.Attributes.Count; i++)
{
var at =doc.CreateAttribute(child.Name + child.Attributes[i].Name);
at.Value=child.Attributes[i].Value;
runner.Attributes.Append(at);
}
if (child.Name == "FixedOdds")
{
foreach (XmlNode book in child.ChildNodes)
{
for (int i = 0; i < book.Attributes.Count; i++)
{
var at = doc.CreateAttribute(book.Name + book.Attributes[i].Name);
at.Value = book.Attributes[i].Value;
runner.Attributes.Append(at);
}
}
}
// delete the attributes and the children nodes
child.RemoveAll();
}
// delete the child noeds
while (runner.ChildNodes.Count > 0)
{
runner.RemoveChild(runner.ChildNodes[0]);
}
}
doc.Save("xml1.xml");
ds.ReadXml("xml1.xml");
for (int i = 0; i < ds.Tables.Count; i++)
{
listBox1.Items.Add(ds.Tables[i].TableName);
}
dgvRunner.DataSource = ds;
dgvRunner.DataMember = "Runner";
//dgvWinOdds.DataSource = ds;
//dgvWinOdds.DataMember = "WinOdds";
//dgvPlaceOdds.DataSource = ds;
//dgvPlaceOdds.DataMember = "PlaceOdds";
//dgvFixedOdds.DataSource = ds;
//dgvFixedOdds.DataMember = "FixedOdds";
}
catch (Exception)
{ }
}
}

Categories