I'm facing a problem with a WCF Restfull Webservice, the problem is with one method the others are working correctly, then I think it isn't a general configuration problem.
I have an idea of what could be the problem but actually I don't know how to solve it.
The method have access to a third party webservice to retrieve an object of the following class:
[DataContract]
public class DeviceData
{
[DataMember]
public int DeviceDataFull { get; set; }
[DataMember]
public string DeviceDataVersion { get; set; }
[DataMember]
public string DeviceDataModel { get; set; }
[DataMember]
public int DeviceDataZWave_Heal { get; set; }
[DataMember]
public string DeviceDataTemperature { get; set; }
[DataMember]
public string DeviceDataSkin { get; set; }
[DataMember]
public string DeviceDataSerial_Number { get; set; }
[DataMember]
public string DeviceDataFWD1 { get; set; }
[DataMember]
public string DeviceDataFWD1Token { get; set; }
[DataMember]
public string DeviceDataFWD2 { get; set; }
[DataMember]
public string DeviceDataFWD2Token { get; set; }
[DataMember]
public int DeviceDataMode { get; set; }
[DataMember]
public List<Section> DeviceDataSections { get; set; }
[DataMember]
public List<Room> DeviceDataRooms { get; set; }
[DataMember]
public List<Scene> DeviceDataScenes { get; set; }
[DataMember]
public List<DeviceItem> DeviceDataItems { get; set; }
[DataMember]
public List<Category> DeviceDataCategories { get; set; }
[DataMember]
public int DeviceDataIr { get; set; }
[DataMember]
public string DeviceDataIrtx { get; set; }
[DataMember]
public int DeviceDataLoadTime { get; set; }
[DataMember]
public int DeviceDataState { get; set; }
[DataMember]
public string DeviceDataComment { get; set; }
}
The only thing that I did in the method's code is fill this object, well in the piece of code where I'm trying to get the: public List<DeviceItem> DeviceDataItems { get; set; } is the problem because I test the method without it and work perfectly. this list of DeviceItem have objects of inherit classes of Device Item:
DeviceItemPanel : DeviceItem
DeviceItemPanelPartition : DeviceItem
DeviceItemDimmable : DeviceItem
DeviceItemThermostat : DeviceItem
etc..
My question: Is there any restriction in service architecture to return the class of object that I explaining above?
Because when I execute the method it remain load and after a few seconds I get the message: ERR_CONNECTION_RESET, I don't see any other error code or anything else, I also debug the method and everything work fine the problem is when it try to return the object as a JSON format.
If any one could help me to find a solution I will appreciate it a lot.
Note this the code of the webservice method:
public ResultDeviceData GetDeviceData(string User, string Password, string DeviceNumber)
{
ResultDeviceData result = new ResultDeviceData();
try
{
Identity identity = GetUserIdentityPrivate(User, Password);
DeviceInfo info = GetDeviceInfoByNumber(User, Password, DeviceNumber);
string url = "https://" + info.DeviceInfoServerRelay + "/relay/relay/relay/device/" + info.DeviceNumber + "/port_3480/data_request?id=lu_sdata&output_format=json";
string jsonResult = Request_Get(url, null, null, info.DeviceInfoServerRelayToken);
//Read Json
var obj = JObject.Parse(jsonResult);
DeviceData data = new DeviceData();
data.DeviceDataFull = (int)obj.SelectToken("full");
data.DeviceDataVersion = (string)obj.SelectToken("version");
data.DeviceDataModel = (string)obj.SelectToken("model");
data.DeviceDataZWave_Heal = (int)obj.SelectToken("zwave_heal");
data.DeviceDataTemperature = (string)obj.SelectToken("temperature");
data.DeviceDataSkin = (string)obj.SelectToken("skin");
data.DeviceDataSerial_Number = (string)obj.SelectToken("serial_number");
data.DeviceDataFWD1 = (string)obj.SelectToken("fwd1");
data.DeviceDataFWD1Token = Request_Get("https://" + data.DeviceDataFWD1 + "/info/session/token", identity.IdentityFirm, identity.IdentitySignature, null);
data.DeviceDataFWD2 = (string)obj.SelectToken("fwd2");
data.DeviceDataFWD2Token = Request_Get("https://" + data.DeviceDataFWD2 + "/info/session/token", identity.IdentityFirm, identity.IdentitySignature, null);
data.DeviceDataMode = (int)obj.SelectToken("mode");
data.DeviceDataIr = (int)obj.SelectToken("ir");
data.DeviceDataIrtx = (string)obj.SelectToken("irtx");
data.DeviceDataLoadTime = (int)obj.SelectToken("loadtime");
data.DeviceDataState = (int)obj.SelectToken("state");
data.DeviceDataComment = (string)obj.SelectToken("comment");
data.DeviceDataSections = new List<Section>();
data.DeviceDataRooms = new List<Room>();
data.DeviceDataScenes = new List<Scene>();
data.DeviceDataCategories = new List<Category>();
data.DeviceDataItems = new List<DeviceItem>();
//Loading Sections
var sections = JArray.Parse(obj.SelectToken("sections").ToString());
for (int i = 0; i < sections.Count; i++)
{
Section section = new Section();
section.SectionId = (int)sections[i].SelectToken("id");
section.SectionName = (string)sections[i].SelectToken("name");
data.DeviceDataSections.Add(section);
}
//Loading Rooms
var rooms = JArray.Parse(obj.SelectToken("rooms").ToString());
for (int i = 0; i < rooms.Count; i++)
{
Room room = new Room();
room.RoomId = (int)rooms[i].SelectToken("id");
room.RoomName = (string)rooms[i].SelectToken("name");
room.SectionId = (int)rooms[i].SelectToken("section");
data.DeviceDataRooms.Add(room);
}
//Loading Scenes
var scenes = JArray.Parse(obj.SelectToken("scenes").ToString());
for (int i = 0; i < scenes.Count; i++)
{
Scene scene = new Scene();
scene.SceneId = (int)scenes[i].SelectToken("id");
scene.SceneName = (string)scenes[i].SelectToken("name");
scene.RoomId = (int)scenes[i].SelectToken("room");
scene.SceneActive = ((int)scenes[i].SelectToken("active")) != 0;
data.DeviceDataScenes.Add(scene);
}
//Loading Categories
var categories = JArray.Parse(obj.SelectToken("categories").ToString());
for (int i = 0; i < categories.Count; i++)
{
Category category = new Category();
category.CategoryId = (int)categories[i].SelectToken("id");
category.CategoryName = (string)categories[i].SelectToken("name");
data.DeviceDataCategories.Add(category);
}
//Loading Devices
var deviceItems = JArray.Parse(obj.SelectToken("devices").ToString());
for (int i = 0; i < deviceItems.Count; i++)
{
int DeviceItemId = (int)deviceItems[i].SelectToken("id");
string DeviceItemAltId = (string)deviceItems[i].SelectToken("altid");
string DeviceItemName = (string)deviceItems[i].SelectToken("name");
int RoomId = (int)deviceItems[i].SelectToken("room");
int CategoryId = (int)deviceItems[i].SelectToken("category");
int SubCategoryId = (int)deviceItems[i].SelectToken("subcategory");
int DeviceItemParent = (int)deviceItems[i].SelectToken("parent");
switch (CategoryId)
{
case 1:
{
break;
}
case 2:
{
DeviceItemDimmable dimmable = new DeviceItemDimmable();
dimmable.DeviceItemId = DeviceItemId;
dimmable.DeviceItemAltId = DeviceItemAltId;
dimmable.DeviceItemName = DeviceItemName;
dimmable.RoomId = RoomId;
dimmable.CategoryId = CategoryId;
dimmable.SubCategoryId = 0;
dimmable.DeviceItemParent = DeviceItemParent;
dimmable.DeviceItemDimmableStatus = (string)deviceItems[i].SelectToken("status");
dimmable.DeviceItemDimmableLevel = (string)deviceItems[i].SelectToken("level");
dimmable.DeviceItemDimmableState = (int)deviceItems[i].SelectToken("state");
dimmable.DeviceItemDimmableComment = (string)deviceItems[i].SelectToken("comment");
data.DeviceDataItems.Add(dimmable);
break;
}
case 3:
{
break;
}
case 4:
{
break;
}
case 5:
{
switch (SubCategoryId)
{
case 1:
{
DeviceItemThermostat thermostat = new DeviceItemThermostat();
thermostat.DeviceItemId = DeviceItemId;
thermostat.DeviceItemAltId = DeviceItemAltId;
thermostat.DeviceItemName = DeviceItemName;
thermostat.RoomId = RoomId;
thermostat.CategoryId = CategoryId;
thermostat.SubCategoryId = 0;
thermostat.DeviceItemParent = DeviceItemParent;
thermostat.DeviceItemThermostatFanMode = (string)deviceItems[i].SelectToken("fanmode");
thermostat.DeviceItemThermostatHvacState = (string)deviceItems[i].SelectToken("hvacstate");
thermostat.DeviceItemThermostatMode = (string)deviceItems[i].SelectToken("mode");
thermostat.DeviceItemThermostatSetPoint = (string)deviceItems[i].SelectToken("setpoint");
thermostat.DeviceItemThermostatHeat = (string)deviceItems[i].SelectToken("heat");
thermostat.DeviceItemThermostatCool = (string)deviceItems[i].SelectToken("cool");
thermostat.DeviceItemThermostatStatus = (string)deviceItems[i].SelectToken("status");
thermostat.DeviceItemThermostatBatteryLevel = (string)deviceItems[i].SelectToken("batterylevel");
thermostat.DeviceItemThermostatTemperature = (string)deviceItems[i].SelectToken("temperature");
thermostat.DeviceItemThermostatState = (int)deviceItems[i].SelectToken("state");
thermostat.DeviceItemThermostatComment = (string)deviceItems[i].SelectToken("comment");
data.DeviceDataItems.Add(thermostat);
break;
}
case 2:
{
break;
}
case 3:
{
break;
}
default:
break;
}
break;
}
case 6:
{
DeviceItemCamera camera = new DeviceItemCamera();
camera.DeviceItemId = DeviceItemId;
camera.DeviceItemAltId = DeviceItemAltId;
camera.DeviceItemName = DeviceItemName;
camera.RoomId = RoomId;
camera.CategoryId = CategoryId;
camera.SubCategoryId = 0;
camera.DeviceItemParent = DeviceItemParent;
camera.DeviceItemCameraIP = (string)deviceItems[i].SelectToken("ip");
camera.DeviceItemCameraURL = (string)deviceItems[i].SelectToken("url");
camera.DeviceItemCameraStreamming = (string)deviceItems[i].SelectToken("streaming");
camera.DeviceItemCameraVideoUrl = (string)deviceItems[i].SelectToken("videourls");
camera.DeviceItemCameraCommands = ((string)deviceItems[i].SelectToken("commands")).Split(',');
data.DeviceDataItems.Add(camera);
break;
}
case 22:
{
DeviceItemPanel panel = new DeviceItemPanel();
panel.DeviceItemId = DeviceItemId;
panel.DeviceItemAltId = DeviceItemAltId;
panel.DeviceItemName = DeviceItemName;
panel.RoomId = RoomId;
panel.CategoryId = CategoryId;
panel.SubCategoryId = 0;
panel.DeviceItemParent = DeviceItemParent;
data.DeviceDataItems.Add(panel);
break;
}
case 23:
{
DeviceItemPanelPartition panelPartition = new DeviceItemPanelPartition();
panelPartition.DeviceItemId = DeviceItemId;
panelPartition.DeviceItemAltId = DeviceItemAltId;
panelPartition.DeviceItemName = DeviceItemName;
panelPartition.RoomId = RoomId;
panelPartition.CategoryId = CategoryId;
panelPartition.SubCategoryId = 0;
panelPartition.DeviceItemParent = DeviceItemParent;
panelPartition.DeviceItemPanelPartitionAlarm = (string)deviceItems[i].SelectToken("alarm");
panelPartition.DeviceItemPanelPartitionAlarmMemory = (string)deviceItems[i].SelectToken("alarmmemory");
panelPartition.DeviceItemPanelPartitionArmMode = (string)deviceItems[i].SelectToken("armmode");
panelPartition.DeviceItemPanelPartitionDetailedArmMode = (string)deviceItems[i].SelectToken("detailedarmmode");
data.DeviceDataItems.Add(panelPartition);
break;
}
default:
{
}
break;
}
}
result.ResultMessage = "Data Retrieve";
result.ResultObject = data;
result.ResultValue = true;
}
catch (Exception e)
{
result.ResultMessage = e.Message;
result.ResultObject = null;
result.ResultValue = false;
}
return result;
}
I solved the problem returning a string in the method, and Serializing the object inside the code.
return JsonConvert.SerializeObject(result);
Related
I am new to web api and C#. I am creating a function where I am calling values from table which has 33 rows. the query is this:
Select * from T_SVRS_Reg_Trans
I have created a model where I have put out properties like so:
public class UserModel
{
public int ID { get; set; }
public string OrgUnit { get; set; }
public string TDC { get; set; }
public string CustCode { get; set; }
public string CustName { get; set; }
public string DestCode { get; set; }
public string EMV { get; set; }
public string Service { get; set; }
public string SPCCode { get; set; }
public string SPCode { get; set; }
public string Remarks { get; set; }
public int Stage { get; set; }
public string Cost { get; set; }
public string SAPUpdate { get; set; }
public string Active { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedOn { get; set; }
public string UpdatedBy { get; set; }
public DateTime UpdatedOn { get; set; }
}
Now I am calling the table values to get added in these properties. My function for that is this:
[HttpPost]
[Route("GetTableValue")]
public IHttpActionResult GetTableValue()
{
try
{
UserModel objUserModel = new UserModel();
ManageUserData ObjManageUserData = new ManageUserData();
var sqlDataTable = ObjManageUserData.GetTableValue();
if (sqlDataTable.Rows.Count > 0)
{
for (int i = 0; (i < sqlDataTable.Rows.Count); i++)
{
objUserModel.OrgUnit=(sqlDataTable.Rows[i]["TRT_Org_ID"].ToString());
objUserModel.TDC = (sqlDataTable.Rows[i]["TRT_TDC_Code"].ToString());
objUserModel.CustCode = (sqlDataTable.Rows[i]["TRT_Cust_Code"].ToString());
objUserModel.CustName = (sqlDataTable.Rows[i]["TRT_Cust_Name"].ToString());
objUserModel.DestCode = (sqlDataTable.Rows[i]["TRT_Dest_Code"].ToString());
objUserModel.EMV = (sqlDataTable.Rows[i]["TRT_EMV"].ToString());
objUserModel.Service = (sqlDataTable.Rows[i]["TRT_Service"].ToString());
objUserModel.SPCCode = (sqlDataTable.Rows[i]["TRT_SPC_Code"].ToString());
objUserModel.SPCode = (sqlDataTable.Rows[i]["TRT_SP_Code"].ToString());
objUserModel.Remarks = (sqlDataTable.Rows[i]["TRT_Remarks"].ToString());
objUserModel.Stage = (int)(sqlDataTable.Rows[i]["TRT_Stage"]);
objUserModel.Cost = (sqlDataTable.Rows[i]["TRT_Cost_Imp"].ToString());
objUserModel.SAPUpdate = (sqlDataTable.Rows[i]["TRT_SAP_Update_Status"].ToString());
objUserModel.Active = (sqlDataTable.Rows[i]["TRT_IS_ACTIVE"].ToString());
objUserModel.CreatedBy = (sqlDataTable.Rows[i]["TRT_CREATED_BY"].ToString());
objUserModel.CreatedOn = (DateTime)(sqlDataTable.Rows[i]["TRT_CREATED_ON"]);
objUserModel.UpdatedBy = (sqlDataTable.Rows[i]["TRT_UPDATED_BY"].ToString());
objUserModel.UpdatedOn = (DateTime)(sqlDataTable.Rows[i]["TRT_UPDATED_ON"]);
}
}
return Ok(objUserModel);
}
catch (Exception ex)
{
return Content(HttpStatusCode.NoContent, "Something went wrong");
}
However I am noticing that only the last table value is added to the model and the rest of it is not. I want to add all 33 values in model form to the model mentioned. Is there any way to do this?
PLease help
}
You overwrite objUserModel each iteration. Create a new one inside the loop, add them to a List<UserModel>, returning that to your view.
Also consider dropping the archaic Hungarian notation (the "obj" prefix). Also consider using an ORM instead of mapping columns to properties using strings.
You should create a List or Array of type UserModel and adding items into it
try
{
List<UserModel> result = new List<UserModel>();
ManageUserData ObjManageUserData = new ManageUserData();
var sqlDataTable = ObjManageUserData.GetTableValue();
if (sqlDataTable.Rows.Count > 0)
{
for (int i = 0; (i < sqlDataTable.Rows.Count); i++)
{
UserModel objUserModel = new UserModel();
objUserModel.OrgUnit = (sqlDataTable.Rows[i]["TRT_Org_ID"].ToString());
objUserModel.TDC = (sqlDataTable.Rows[i]["TRT_TDC_Code"].ToString());
objUserModel.CustCode = (sqlDataTable.Rows[i]["TRT_Cust_Code"].ToString());
objUserModel.CustName = (sqlDataTable.Rows[i]["TRT_Cust_Name"].ToString());
objUserModel.DestCode = (sqlDataTable.Rows[i]["TRT_Dest_Code"].ToString());
objUserModel.EMV = (sqlDataTable.Rows[i]["TRT_EMV"].ToString());
objUserModel.Service = (sqlDataTable.Rows[i]["TRT_Service"].ToString());
objUserModel.SPCCode = (sqlDataTable.Rows[i]["TRT_SPC_Code"].ToString());
objUserModel.SPCode = (sqlDataTable.Rows[i]["TRT_SP_Code"].ToString());
objUserModel.Remarks = (sqlDataTable.Rows[i]["TRT_Remarks"].ToString());
objUserModel.Stage = (int)(sqlDataTable.Rows[i]["TRT_Stage"]);
objUserModel.Cost = (sqlDataTable.Rows[i]["TRT_Cost_Imp"].ToString());
objUserModel.SAPUpdate = (sqlDataTable.Rows[i]["TRT_SAP_Update_Status"].ToString());
objUserModel.Active = (sqlDataTable.Rows[i]["TRT_IS_ACTIVE"].ToString());
objUserModel.CreatedBy = (sqlDataTable.Rows[i]["TRT_CREATED_BY"].ToString());
objUserModel.CreatedOn = (DateTime)(sqlDataTable.Rows[i]["TRT_CREATED_ON"]);
objUserModel.UpdatedBy = (sqlDataTable.Rows[i]["TRT_UPDATED_BY"].ToString());
objUserModel.UpdatedOn = (DateTime)(sqlDataTable.Rows[i]["TRT_UPDATED_ON"]);
result.Add(objUserModel);
}
}
return Ok(result);
}
catch (Exception ex)
{
return Content(HttpStatusCode.NoContent, "Something went wrong");
}
You need to use the collection instead of single object UserModel.
[HttpPost]
[Route("GetTableValue")]
public IHttpActionResult GetTableValue()
{
try
{
ManageUserData ObjManageUserData = new ManageUserData();
var sqlDataTable = ObjManageUserData.GetTableValue();
List<UserModel> userModels = new List<UserModel>();
if (sqlDataTable.Rows.Count > 0)
{
for (int i = 0; (i < sqlDataTable.Rows.Count); i++)
{
var objUserModel = new UserModel()
objUserModel.OrgUnit = (sqlDataTable.Rows[i]["TRT_Org_ID"].ToString());
objUserModel.TDC = (sqlDataTable.Rows[i]["TRT_TDC_Code"].ToString());
objUserModel.CustCode = (sqlDataTable.Rows[i]["TRT_Cust_Code"].ToString());
objUserModel.CustName = (sqlDataTable.Rows[i]["TRT_Cust_Name"].ToString());
objUserModel.DestCode = (sqlDataTable.Rows[i]["TRT_Dest_Code"].ToString());
objUserModel.EMV = (sqlDataTable.Rows[i]["TRT_EMV"].ToString());
objUserModel.Service = (sqlDataTable.Rows[i]["TRT_Service"].ToString());
objUserModel.SPCCode = (sqlDataTable.Rows[i]["TRT_SPC_Code"].ToString());
objUserModel.SPCode = (sqlDataTable.Rows[i]["TRT_SP_Code"].ToString());
objUserModel.Remarks = (sqlDataTable.Rows[i]["TRT_Remarks"].ToString());
objUserModel.Stage = (int)(sqlDataTable.Rows[i]["TRT_Stage"]);
objUserModel.Cost = (sqlDataTable.Rows[i]["TRT_Cost_Imp"].ToString());
objUserModel.SAPUpdate = (sqlDataTable.Rows[i]["TRT_SAP_Update_Status"].ToString());
objUserModel.Active = (sqlDataTable.Rows[i]["TRT_IS_ACTIVE"].ToString());
objUserModel.CreatedBy = (sqlDataTable.Rows[i]["TRT_CREATED_BY"].ToString());
objUserModel.CreatedOn = (DateTime)(sqlDataTable.Rows[i]["TRT_CREATED_ON"]);
objUserModel.UpdatedBy = (sqlDataTable.Rows[i]["TRT_UPDATED_BY"].ToString());
objUserModel.UpdatedOn = (DateTime)(sqlDataTable.Rows[i]["TRT_UPDATED_ON"]);
userModels.Add(userModels);
}
}
return Ok(userModels);
}
catch (Exception ex)
{
return Content(HttpStatusCode.NoContent, "Something went wrong");
}
}
As you are expecting more than one row to be returned, you need to collect the rows as you iterate your result set into some sort of collection/list/array.
Try making a list of your UserModel
List<UserModel> objUserModels = new List<UserModel>();
And then adding each object to the list after each iteration of your for loop:
for (int i = 0; (i < sqlDataTable.Rows.Count); i++)
{
var objUserModel = new UserModel();
objUserModel.OrgUnit=(sqlDataTable.Rows[i]["TRT_Org_ID"].ToString());
objUserModel.TDC = (sqlDataTable.Rows[i]["TRT_TDC_Code"].ToString());
objUserModel.CustCode = (sqlDataTable.Rows[i]["TRT_Cust_Code"].ToString());
objUserModel.CustName = (sqlDataTable.Rows[i]["TRT_Cust_Name"].ToString());
objUserModel.DestCode = (sqlDataTable.Rows[i]["TRT_Dest_Code"].ToString());
objUserModel.EMV = (sqlDataTable.Rows[i]["TRT_EMV"].ToString());
objUserModel.Service = (sqlDataTable.Rows[i]["TRT_Service"].ToString());
objUserModel.SPCCode = (sqlDataTable.Rows[i]["TRT_SPC_Code"].ToString());
objUserModel.SPCode = (sqlDataTable.Rows[i]["TRT_SP_Code"].ToString());
objUserModel.Remarks = (sqlDataTable.Rows[i]["TRT_Remarks"].ToString());
objUserModel.Stage = (int)(sqlDataTable.Rows[i]["TRT_Stage"]);
objUserModel.Cost = (sqlDataTable.Rows[i]["TRT_Cost_Imp"].ToString());
objUserModel.SAPUpdate = (sqlDataTable.Rows[i]["TRT_SAP_Update_Status"].ToString());
objUserModel.Active = (sqlDataTable.Rows[i]["TRT_IS_ACTIVE"].ToString());
objUserModel.CreatedBy = (sqlDataTable.Rows[i]["TRT_CREATED_BY"].ToString());
objUserModel.CreatedOn = (DateTime)(sqlDataTable.Rows[i]["TRT_CREATED_ON"]);
objUserModel.UpdatedBy = (sqlDataTable.Rows[i]["TRT_UPDATED_BY"].ToString());
objUserModel.UpdatedOn = (DateTime)(sqlDataTable.Rows[i]["TRT_UPDATED_ON"]);
objUserModels.Add(objUserModel);
}
And then return your list of objects:
return Ok(objUserModels);
I have a C# project and looking for simple solution for map one class object data to list of another class object.
This is my input class
public class RatesInput
{
public string Type1 { get; set; }
public string Break1 { get; set; }
public string Basic1 { get; set; }
public string Rate1 { get; set; }
public string Type2 { get; set; }
public string Break2 { get; set; }
public string Basic2 { get; set; }
public string Rate2 { get; set; }
public string Type3 { get; set; }
public string Break3 { get; set; }
public string Basic3 { get; set; }
public string Rate3 { get; set; }
}
This is my another class structure
public class RateDetail
{
public string RateType { get; set; }
public decimal Break { get; set; }
public decimal Basic { get; set; }
public decimal Rate { get; set; }
}
it has a object like below. (For easiering the understanding, I use hardcoded values and actually values assign from a csv file)
RatesInput objInput = new RatesInput();
objInput.Type1 = "T";
objInput.Break1 = 100;
objInput.Basic1 = 50;
objInput.Rate1 = 0.08;
objInput.Type2 = "T";
objInput.Break2 = 200;
objInput.Basic2 = 50;
objInput.Rate2 = 0.07;
objInput.Type3 = "T";
objInput.Break3 = 500;
objInput.Basic3 = 50;
objInput.Rate3 = 0.06;
Then I need to assign values to "RateDetail" list object like below.
List<RateDetail> lstDetails = new List<RateDetail>();
//START Looping using foreach or any looping mechanism
RateDetail obj = new RateDetail();
obj.RateType = //first iteration this should be assigned objInput.Type1, 2nd iteration objInput.Type2 etc....
obj.Break = //first iteration this should be assigned objInput.Break1 , 2nd iteration objInput.Break2 etc....
obj.Basic = //first iteration this should be assigned objInput.Basic1 , 2nd iteration objInput.Basic2 etc....
obj.Rate = //first iteration this should be assigned objInput.Rate1, 2nd iteration objInput.Rate2 etc....
lstDetails.Add(obj); //Add obj to the list
//END looping
Is there any way to convert "RatesInput" class data to "RateDetail" class like above method in C#? If yes, how to iterate data set?
Try this:
public class RatesList : IEnumerable<RateDetail>
{
public RatesList(IEnumerable<RatesInput> ratesInputList)
{
RatesInputList = ratesInputList;
}
private readonly IEnumerable<RatesInput> RatesInputList;
public IEnumerator<RateDetail> GetEnumerator()
{
foreach (var ratesInput in RatesInputList)
{
yield return new RateDetail
{
RateType = ratesInput.Type1,
Break = Convert.ToDecimal(ratesInput.Break1, new CultureInfo("en-US")),
Basic = Convert.ToDecimal(ratesInput.Basic1, new CultureInfo("en-US")),
Rate = Convert.ToDecimal(ratesInput.Rate1, new CultureInfo("en-US"))
};
yield return new RateDetail
{
RateType = ratesInput.Type2,
Break = Convert.ToDecimal(ratesInput.Break2),
Basic = Convert.ToDecimal(ratesInput.Basic2),
Rate = Convert.ToDecimal(ratesInput.Rate2, new CultureInfo("en-US"))
};
yield return new RateDetail
{
RateType = ratesInput.Type3,
Break = Convert.ToDecimal(ratesInput.Break3),
Basic = Convert.ToDecimal(ratesInput.Basic3),
Rate = Convert.ToDecimal(ratesInput.Rate3, new CultureInfo("en-US"))
};
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
And use:
var list = new RatesList(new List<RatesInput>() { objInput });
foreach (var item in list)
{
Console.WriteLine(item.Basic);
}
You can use Reflection to get the properties info like this:
var props = objInput.GetType().GetProperties();
var types = props.Where(x => x.Name.StartsWith("Type"))
.Select(x => x.GetValue(objInput)).ToList();
var breaks = props.Where(x => x.Name.StartsWith("Break"))
.Select(x => x.GetValue(objInput)).ToList();
var basics = props.Where(x => x.Name.StartsWith("Basic"))
.Select(x => x.GetValue(objInput)).ToList();
var rates = props.Where(x => x.Name.StartsWith("Rate"))
.Select(x => x.GetValue(objInput)).ToList();
List<RateDetail> lstDetails = new List<RateDetail>();
for (int i = 0; i < types.Count; i++)
{
lstDetails.Add(new RateDetail
{
RateType = types[i].ToString(),
Break = Convert.ToDecimal(breaks[i]),
Basic = Convert.ToDecimal(basics[i]),
Rate = Convert.ToDecimal(rates[i])
});
}
I am a C# beginner programmer. I have a text file, which is my source, with multiple rows of data. I want to create one xml file with multiple xml documents inside the file. The xml documents are generated from the rows of data in the text file. I can only get one xml document to generate in the A0x.xml file that is created. My code only reads the first row of data and generates one xml document instead to multiple xml documents. Below are 8 rows from the M24EX.txt file. Please help!!
A0ASMSS3110004624190 EA00008FB239980940001RAIR A30 0120505 18094133644FT
A0ASMSS5340011122822 HD00001FB239981000001RAIR A6C 0120503 18100124741FT
A0ASMSS5365002870093 EA00003FB239981000002RAIR A6C 0120503 18100125431FT
A0ASMS 5365001671717 EA00005FB239981010001REY2550A6C 0120503133 18101075536SF
A0ASMS 5365001671717 EA00011FB239981010002RGE A6C 0120505129 18101105015FT
A0AFLZ 6625013922071 EA00001FB239981070001RGRN D6C 0120505110 18107150014FT
A0AFLZ 6650013204283 EA00003FB239981070002NGRN D6C 0120504777 18107151015FT
A0ASMSS1650009937278 EA00006FB239981080001RAIR A6C 0120505 18108082906FT
And the code:
Public class Program
{
public static void Main(string[] arg)
{
XDocument A0x = new XDocument();
var IdCode = "511";
var CtrlNbr = "0001";
var PurposeCode = "00";
var TypeCode = "A0";
var EntyIdCode = "OB";
var IdCodeQlfr = "10";
var EntyIdCode1 = "FR";
var DocNbr = "TN";
var AssignNbr = "1";
var NSN = "FS";
var DD = "74";
var AgncyQlfrCode = "DF";
var LstQlfrCode = "0";
DateTime saveUtcNow = DateTime.UtcNow;
DateTime saveNow = DateTime.Now;
var field = new ParseTextFile().Parse();
var tagBuilder = new TagBuilder();
var parent = tagBuilder.BuildParent("File");
var subParent = tagBuilder.BuildParent("T_Requisition_511");
var ParentST = tagBuilder.BuildParent("S_Transaction_Set_Header");
var ST01 = tagBuilder.BuildChild("E_Transaction_Set_Identifier_Code", IdCode);
var ST02 = tagBuilder.BuildChild("E_Transaction_Set_Control_Number", CtrlNbr);
var ParentBR = tagBuilder.BuildParent("S_Beginning_Segment_for_Material_Management");
var BR01 = tagBuilder.BuildChild("E_Transaction_Set_Purpose_Code", PurposeCode);
var BR02 = tagBuilder.BuildChild("E_Transaction_Type_Code", TypeCode);
var BR03 = tagBuilder.BuildChild("E_Date", saveUtcNow.ToString("yyyyMMdd"));
var BR09 = tagBuilder.BuildChild("E_Time", saveUtcNow.ToString("hhmmss"));
var ParentN1 = tagBuilder.BuildParent("L_Name");
var ParentS = tagBuilder.BuildParent("S_Name");
var N101 = tagBuilder.BuildChild("E_Entity_Identifier_Code", EntyIdCode);
var N103 = tagBuilder.BuildChild("E_Identification_Code_Qualifier", IdCodeQlfr);
var N104 = tagBuilder.BuildChild("E_Identification_Code", field.SRAN);
var N106 = tagBuilder.BuildChild("E_Entity_Identifier_Code_1", EntyIdCode1);
var ParentLX = tagBuilder.BuildParent("L_Assigned_Number");
var ParentAN = tagBuilder.BuildParent("S_Assigned_Number");
var LX01 = tagBuilder.BuildChild("E_Assigned_Number", AssignNbr);
var ParentN9 = tagBuilder.BuildParent("S_Reference_Identification");
var N901 = tagBuilder.BuildChild("E_Reference_Identification_Qualifier", DocNbr);
var N902 = tagBuilder.BuildChild("E_Reference_Identification", field.DocumentNumber);
var ParentPO1 = tagBuilder.BuildParent("S_Baseline_Item_Data");
var PO102 = tagBuilder.BuildChild("E_Quantity_Ordered", Convert.ToString(field.Quantity));
var PO103 = tagBuilder.BuildChild("E_Unit_or_Basis_for_Measurement_Code", field.UnitofIssue);
var PO106 = tagBuilder.BuildChild("E_Product_Service_ID_Qualifier", NSN);
var PO107 = tagBuilder.BuildChild("E_Product_Service_ID", field.StockNumber);
var ParentSE = tagBuilder.BuildParent("S_Transaction_Set_Trailer");
var SE01 = tagBuilder.BuildChild("E_Number_of_Included_Segments", new CountSegmentTags().CountSgmts().ToString());
var SE02 = tagBuilder.BuildChild("E_Transaction_Set_Control_Number", CtrlNbr);
parent.Add(subParent);
subParent.Add(ParentST);
ParentST.Add(ST01);
ParentST.Add(ST02);
subParent.Add(ParentBR);
ParentBR.Add(BR01);
ParentBR.Add(BR02);
ParentBR.Add(BR03);
ParentBR.Add(BR09);
subParent.Add(ParentN1);
ParentN1.Add(ParentS);
ParentS.Add(N101);
ParentS.Add(N103);
ParentS.Add(N104);
ParentS.Add(N106);
subParent.Add(ParentLX);
ParentLX.Add(ParentAN);
ParentAN.Add(LX01);
ParentLX.Add(ParentN9);
ParentN9.Add(N901);
ParentN9.Add(N902);
ParentLX.Add(ParentPO1);
ParentPO1.Add(PO102);
ParentPO1.Add(PO103);
ParentPO1.Add(PO106);
ParentPO1.Add(PO107);
ParentSE.Add(SE01);
ParentSE.Add(SE02);
A0x.Add(parent);
A0x.Declaration = new XDeclaration("1.0", "utf-8", "true");
A0x.Save("M24EX.xml");
}
public class TagBuilder
{
public XElement BuildParent(string name)
{
return new XElement(name);
}
public XElement BuildChild(string name, string value)
{
var tag = new XElement(name);
tag.Add(value);
return tag;
}
}
public void Read()
{
int counter = 0;
string line;
StreamReader file = new StreamReader("M24EX.txt");
while ((line = file.ReadLine()) != null)
if (line.StartsWith("A0")) // only pull "A0x" records
{
counter++;
Console.WriteLine("{0}:{1}", counter, line);
}
file.Close();
}
public class ParseTextFile
{
public TransactionFields Parse()
{
StreamReader file = new StreamReader("M24Ex.txt");
string line;
int counter = 0;
var field = new TransactionFields();
while ((line = file.ReadLine()) != null)
if (line.StartsWith("A0"))
{
//Assigns field to the Transaction field names
field.DocumentIdentifier = line.Substring(0, 3).Trim(); // Tric
field.RoutingIdentifier = line.Substring(4, 3).Trim();
field.MediaStatusCode = line.Substring(7, 1).Trim();
field.StockNumber = line.Substring(7, 15).Trim();
field.UnitofIssue = line.Substring(22, 2).Trim();
field.Quantity = Convert.ToInt32(line.Substring(24, 5));
field.DocumentNumber = line.Substring(29, 14).Trim();
field.SRAN = line.Substring(29, 6).Trim();
field.DemandCode = line.Substring(44, 1).Trim();
field.SupplementaryAddress = line.Substring(45, 6).Trim();
field.SignalCode = line.Substring(51, 1).Trim();
field.FundCode = line.Substring(52, 2).Trim();
field.DistributionCode = line.Substring(54, 3).Trim();
field.ProjectCode = line.Substring(57, 3).Trim();
field.Priority = line.Substring(60, 2).Trim();
field.ReqDeliveryDate = line.Substring(62, 3).Trim();
field.AdviceCode = line.Substring(65, 2).Trim();
field.DateReceiptofReq = line.Substring(67, 3).Trim();
field.PurposeCode = line.Substring(70, 1).Trim();
field.ConditionCode = line.Substring(71, 1).Trim();
field.MgmtCode = line.Substring(72, 1).Trim();
}
file.Close();
return field;
}
}
public class ConvertXmlToText
{
public void ConvertXmlDoc()
{
string onlyContent = string.Empty;
XmlDocument xdoc = new XmlDocument();
xdoc.Load("A0x.xml");
var file = xdoc.SelectNodes("File/T_Requisition_511");
for (int i = 0; i < file.Count; i++)
{
onlyContent += string.Format("\n", i);
foreach (XmlNode node in file[i].ChildNodes)
onlyContent += string.Format("{0},", node.InnerText);
}
File.WriteAllText("A0x.txt", onlyContent);
}
}
public class TransactionFields
{
public string DocumentIdentifier { get; set; }
public string RoutingIdentifier { get; set; }
public string MediaStatusCode { get; set; }
public string StockNumber { get; set; }
public string UnitofIssue { get; set; }
public int Quantity { get; set; }
public string DocumentNumber { get; set; }
public string SRAN { get; set; }
public string DemandCode { get; set; }
public string SupplementaryAddress { get; set; }
public string SignalCode { get; set; }
public string FundCode { get; set; }
public string DistributionCode { get; set; }
public string ProjectCode { get; set; }
public string Priority { get; set; }
public double UnitPrice { get; set; }
public string Date { get; set; }
public string Time { get; set; }
}
This is my code in which a list contains 2 more lists where the WorkItem collection contains a large number of records such as 7,000 it takes 10 minutes.
Is there any way to make it faster and in case it's deciding the WorkItem type if it's a bug, task, or product backlog item?
Please tell me how to make the looping faster.
It's taking 10 minutes to loop 7,000 records. Can we use threading to make it faster?
var workItemList = new List<WorkItemViewModel>();
for (int i = 0; i < workItemCollection.Count; i++)
{
var workItem = workItemCollection[i];
if (workItem.Type.Name == "Product Backlog Item")
{
var model = new WorkItemViewModel()
{
FID = (workItem.WorkItemLinks.Count > 0) ?
((workItem.WorkItemLinks[0].LinkTypeEnd.Name.ToString() != "Child") ?
workItem.WorkItemLinks[0].TargetId : 0) : 0,
ID = workItem.Id,
Name = workItem.Title,
State = workItem.State,
priorty = Convert.ToInt32(workItem.Fields["Priority"].Value),
// Size =(int) workItem.Fields["Size"].Value ,
Size = Convert.ToInt32(workItem.Fields["Effort"].Value),
StoryPoints = Convert.ToInt32(workItem.Fields["Story Points"].Value),
DoneStatus = workItem.Fields["Done Status"].Value.ToString(),
StoryOwner = workItem.Fields["Story Owner"].Value.ToString(),
Assignedto = workItem.Fields["Assigned To"].Value.ToString(),
StoryAuthor = workItem.Fields["Story Author"].Value.ToString(),
IterationPath = workItem.IterationPath
};
workItemList.Add(model);
}
else
{
switch (workItem.Type.Name)
{
case "Task":
var task = new TFSTask()
{
Storyid = (workItem.WorkItemLinks.Count > 0) ?
workItem.WorkItemLinks[0].TargetId : 0,
ID = workItem.Id,
name = workItem.Title,
//activity = workItem.Fields["MyCompany.Activity"].Value.ToString(),
//start = (DateTime?)workItem.Fields["MyCompany.ActivityStart"].Value,
//due = (DateTime?)workItem.Fields["MyCompany.ActivityFinish"].Value,
status = workItem.State,
IterationPath = workItem.IterationPath,
Assignedto = workItem.Fields["Assigned To"].Value.ToString(),
priorty = Convert.ToInt32(workItem.Fields["Priority"].Value),
effort = Convert.ToInt32(workItem.Fields["effort"].Value),
Completed = Convert.ToInt32(workItem.Fields["Completed"].Value)
};
if (task.Storyid != 0)
{
workItemList.Last().Tasks.Add(task);
}
break;
case "Bug":
var bug = new TFSIssue()
{
Storyid = (workItem.WorkItemLinks.Count > 0) ?
workItem.WorkItemLinks[0].TargetId : 0,
ID = workItem.Id,
Name = workItem.Title,
//start = (DateTime?)workItem.Fields["MyCompany.ActivityStart"].Value,
//due = (DateTime?)workItem.Fields["MyCompany.ActivityFinish"].Value,
State = workItem.State,
IterationPath = workItem.IterationPath,
Assignedto = workItem.Fields["Assigned To"].Value.ToString(),
priorty = Convert.ToInt32(workItem.Fields["Priority"].Value),
effort = Convert.ToInt32(workItem.Fields["effort"].Value),
// Completed = Convert.ToInt32(workItem.Fields["Completed"].Value)
};
if (bug.Storyid != 0)
{
workItemList.Last().Issues.Add(bug);
}
break;
default:
break;
}
}
}
public class WorkItemViewModel
{
public string Name { get; set; }
public int ID { get; set; }
public string State { get; set; }
// public DateTime? due { get; set; }
public int priorty { get; set; }
public int Size { get; set; }
// public int effort { get; set; }
public int StoryPoints { get; set; }
public string DoneStatus { get; set; }
public string StoryOwner { get; set; }
public string Assignedto { get; set; }
public string StoryAuthor { get; set; }
public string IterationPath { get; set; }
public int FID { get; set; }
public List<TFSIssue> Issues { get; set; }
public List<TFSTask> Tasks { get; set; }
public WorkItemViewModel() // Added a public constructor
{
Issues = new List<TFSIssue>();
Tasks = new List<TFSTask>();
}
}
I think you can't with the current structure of your data. As I understand it, the relation between your backlog items and the related tasks/bugs is only explained by the relative order in the workItemCollection object. So if you were to use Parrallel.For with a ConccurentBag, you would not know to which backlog item each task/bug item should be added...
On another note, 10 minutes seems like a very long time for a simple loop of 7.000 records. Is there anything else going on that is not clear in the code? You should investigate the sub steps, to see what is taking the time.
I have one modification to suggest but i'm not sure if it's gonna improve the performance since I can't really test it:
var workItemList = new List<WorkItemViewModel>();
for (int i = 0; i < workItemCollection.Count; i++)
{
var workItem = workItemCollection[i];
WorkItemViewModel model = null;
switch (workItem.Type.Name)
{
case "Product Backlog Item":
model = new WorkItemViewModel()
{
// ...
};
workItemList.Add(model);
case "Task":
var task = new TFSTask()
{
// ...
};
if (task.Storyid != 0)
{
model.Tasks.Add(task);
}
break;
case "Bug":
var bug = new TFSIssue()
{
// ...
};
if (bug.Storyid != 0)
{
model.Issues.Add(bug);
}
break;
default:
break;
}
}
This way no need to call Last() each time you wanna add a Task or a Bug, it's better to just save the last model as a variable and make the other switch cases use that variable.
I've been trying to add to a list of lists adding information from an sql db. The error I get when adding new info to a list is this:
"An exception of type 'System.NullReferenceException' occurred in StatusScope.dll but was not handled in user code
Additional information: Object reference not set to an instance of an object."
How would I solve this error?
MapLogic.cs
public static List<MapModel.ClientInfo> GetClientsData()
{
SqlConnection Connection = site.Models.Shared.DBConnection.GetConnection();
SqlDataReader Reader = null;
SqlCommand Command = new SqlCommand("SELECT DocInfo.DocID, DocInfo.DocName, DocInfo.DocPic, DocInfo.PatientAcceptance, ClientInfo.ClientName, ClientInfo.AddressLocal, ClientInfo.AddressBroad, ClientInfo.Phone, ClientInfo.Lat, ClientInfo.Long, ClientInfo.ClientID FROM DocInfo INNER JOIN ClientInfo ON DocInfo.ClientID = ClientInfo.ClientID;", Connection);
Reader = Command.ExecuteReader();
var ClientsData = new List<MapModel.ClientInfo> { };
int IDCounter = 0;
bool FirstRun = false;
while (Reader.Read())
{
if (!FirstRun)
{
ClientsData.Add(new MapModel.ClientInfo { Id = IDCounter, ClientID = Reader["ClientID"].ToString(), ClientName = Reader["ClientName"].ToString(), DocPic = Reader["DocPic"].ToString(), PatientAcceptance = Reader["PatientAcceptance"].ToString(), AddressLocal = Reader["AddressLocal"].ToString(), AddressBroad = Reader["AddressLocal"].ToString(), Phone = Reader["Phone"].ToString(), latitude = Reader["Lat"].ToString(), longitude = Reader["Long"].ToString(), DocNames = { } });
FirstRun = true;
}
else
{
for (var x = 0; x < ClientsData.Count; x++)
{
if (ClientsData[x].ClientID == Reader["ClientID"].ToString())
{
ClientsData[x].DocNames.Add("123"); //error occurs here
}
else
{
ClientsData.Add(new MapModel.ClientInfo { Id = IDCounter, ClientID = Reader["ClientID"].ToString(), ClientName = Reader["ClientName"].ToString(), DocPic = Reader["DocPic"].ToString(), PatientAcceptance = Reader["PatientAcceptance"].ToString(), AddressLocal = Reader["AddressLocal"].ToString(), AddressBroad = Reader["AddressLocal"].ToString(), Phone = Reader["Phone"].ToString(), latitude = Reader["Lat"].ToString(), longitude = Reader["Long"].ToString() });
}
}
}
IDCounter++;
}
Connection.Close();
return ClientsData;
}
MapModel.cs
public class ClientInfo
{
public int Id { get; set; }
public string ClientID { get; set; }
public string ClientName { get; set; }
public List<string> DocNames { get; set; }
public string DocPic { get; set; }
public string PatientAcceptance { get; set; }
public string AddressLocal { get; set; }
public string AddressBroad { get; set; }
public string Phone { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }
}
Do you ever set DocNames to anything? If not, it will be null.
In the constructor for ClientInfo you should have
DocNames = new List<string>();
to initialize an empty list.
Isn't it the case of testing whether ClientsData[x].DocNames is null before adding? You could change your code to
if(ClientsData[x].DocNames == null) {
ClientsData[x].DocNames = new List<string>();
}
ClientsData[x].DocNames.Add("123");
so that it always works.
In both lines where you add a new MapModel.ClientInfo to your ClientsData list, you need to initialize DocNames to a new List() otherwise whenever you try to access DocNames, it's always null. So, in both places you need to do the following:
ClientsData.Add(new MapModel.ClientInfo
{
Id = IDCounter,
//.
//. removing code just to make my answer shorter
//.
DocNames = new List<string>()
});