Adding an array property into an array of another object - c#

I have this call that returns an array of treatments
var procedures = await client.GetProceduresAsync(clinicId);
I was trying to loop and insert all procedureIds (from the array) into an array property of the availableSlotsQuery
var availableSlotsQuery = new AvailableSlotsQuery();
foreach (var procedure in procedures.Select(x=> x.Procedure))
{
availableSlotsQuery = new AvailableSlotsQuery
{
ClinicId = clinicId,
ProcedureIds = new [] { procedure.Id},
Start = request.From.ToDateTimeOffset(),
End = request.To.ToDateTimeOffset(),
CaregiverId = therapistId?.Id
};
}
This is not working.
ProcedureIds is a string [] but after looping I only have one id in the ProcedureIds property
what am I doing wrong here?

with looping
var availableSlotsQuery = new AvailableSlotsQuery();
availableSlotsQuery = new AvailableSlotsQuery
{
ClinicId = clinicId,
Start = request.From.ToDateTimeOffset(),
End = request.To.ToDateTimeOffset(),
CaregiverId = therapistId?.Id
};
var listOfProcedureIds = new List<string>();
foreach (var procedure in procedures.Select(x=> x.Procedure))
{
listOfProcedureIds.Add(procedure.Id);
}
availableSlotsQuery.ProcedureIds = listOfProcedureIds.ToArray();
without looping
availableSlotsQuery = new AvailableSlotsQuery
{
ClinicId = clinicId,
Start = request.From.ToDateTimeOffset(),
End = request.To.ToDateTimeOffset(),
CaregiverId = therapistId?.Id,
ProcedureIds = procedures.Select(x => x.Procedure.Id).ToArray()
};
as mentioned by all, you are creating a new object in your foreach statement
foreach (var procedure in procedures.Select(x=> x.Procedure))
{
//as you can see here with the availableSlotQuery = new AvailableSlotQuery
availableSlotsQuery = new AvailableSlotsQuery
{
//properties
};
}

Related

add two group into one group in c#

I have two groups like below, theyh have different data. Based on both I need to create an xml file .
How can I write a for-loop for both groups and generate a single xml file?
var groups = checkFile.AsEnumerable().GroupBy(x => new { DocNum = x.Field<int>("orderid"), Type = x.Field<string>("Type"), ProdName = x.Field<string>("ProdName"), Status = x.Field<string>("Status"), productno = x.Field<string>("productno"), uom = x.Field<string>("uom"), customer = x.Field<string>("customer"), remark = x.Field<string>("remark"), U_JobNumber = x.Field<string>("U_JobNumber"), U_SalesPerson = x.Field<string>("U_SalesPerson"), U_POnum = x.Field<string>("U_POnum"), U_JobType = x.Field<string>("U_JobType"), PlannedQty = x.Field<decimal>("PlannedQty"), OriginNum = x.Field<int?>("OriginNum"), orderdate = x.Field<DateTime>("orderdate"), duedate = x.Field<DateTime>("duedate"), DocTotal = x.Field<decimal>("DocTotal") });
var groups2 = checkFile2.AsEnumerable().GroupBy(x => new { DocNum = x.Field<int>("DocNum") });
//now i need to take both group data inside this loop to print the file
foreach (var group in groups)
{
var stringwriter = new StringWriter();
using (var xmlWriter = XmlWriter.Create(stringwriter, new XmlWriterSettings { Indent = true }))
{
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("Root");
xmlWriter.WriteEndElement();
}
var xml = stringwriter.ToString();
XmlDocument docSave = new XmlDocument();
docSave.LoadXml(stringwriter.ToString());
docSave.Save(System.IO.Path.Combine(#SystemSettings.ImportBankStatementPendingFolderPath, "DocNum -" + group.Key.DocNum + ".xml"));
count++;
}
Try following :
DataTable checkFile = new DataTable();
var groups = checkFile.AsEnumerable().GroupBy(x => new
{
DocNum = x.Field<int>("orderid"),
Type = x.Field<string>("Type"),
ProdName = x.Field<string>("ProdName"),
Status = x.Field<string>("Status"),
productno = x.Field<string>("productno"),
uom = x.Field<string>("uom"),
customer = x.Field<string>("customer"),
remark = x.Field<string>("remark"),
U_JobNumber = x.Field<string>("U_JobNumber"),
U_SalesPerson = x.Field<string>("U_SalesPerson"),
U_POnum = x.Field<string>("U_POnum"),
U_JobType = x.Field<string>("U_JobType"),
PlannedQty = x.Field<decimal>("PlannedQty"),
OriginNum = x.Field<int?>("OriginNum"),
orderdate = x.Field<DateTime>("orderdate"),
duedate = x.Field<DateTime>("duedate"),
DocTotal = x.Field<decimal>("DocTotal")
});
DataTable checkFile2 = new DataTable();
//now i need to take both group data inside this loop to print the file
foreach (var group in groups)
{
List<DataRow> groups2 = checkFile2.AsEnumerable().Where(x => group.Key.DocNum == x.Field<int>("DocNum")).ToList();
}

how to get all the items of list c#

In a list i have 4 rows and I am try to get all the rows of the list but it is giving only one row, how to get all the rows of the list.
I have tried below code
public async Task<ResponseUserModel> get()
{
List<ResponseUserModel> responseUsers = new List<ResponseUserModel>();
using (nae2sasqld0003Entities context = new nae2sasqld0003Entities())
{
var listt = context.Producers.Select(all => all).ToList();
foreach (var item in listt)
{
responseUsers.Add(new ResponseUserModel
{
ProducerName = item.ProducerName,
ResidentState = item.ResidentState,
ResidentCity = item.ResidentCity,
ProducerStatus = item.ProducerStatus,
ProducerCode = item.ProducerCode,
MasterCode = item.MasterCode,
NationalCode = item.NationalCode,
LegacyChubbCodes = item.LegacyChubbCodes,
LegacyPMSCode = item.LegacyPMSCode,
ProducingBranchCode = item.ProducingBranchCode,
CategoryCode = item.CategoryCode
});
}
return responseUsers;
}
}
please let me know where i to fix the issue
Use list to return all:
List<ResponseUserModel> responseUsers = new List<ResponseUserModel>();
then
foreach (var item in listt)
{
responseUsers.Add(new ResponseUserModel
{
ProducerName = item.ProducerName,
ResidentState = item.ResidentState,
ResidentCity = item.ResidentCity,
ProducerStatus = item.ProducerStatus,
ProducerCode = item.ProducerCode,
MasterCode = item.MasterCode,
NationalCode = item.NationalCode,
LegacyChubbCodes = item.LegacyChubbCodes,
LegacyPMSCode = item.LegacyPMSCode,
ProducingBranchCode = item.ProducingBranchCode,
CategoryCode = item.CategoryCode
});
}
return responseUsers;
Note: change return type of the method to IList<ResponseUserModel>
or in this way
using (var context = new nae2sasqld0003Entities())
{
return context.Producers.Select(item =>
new ResponseUserModel
{
ProducerName = item.ProducerName,
ResidentState = item.ResidentState,
ResidentCity = item.ResidentCity,
ProducerStatus = item.ProducerStatus,
ProducerCode = item.ProducerCode,
MasterCode = item.MasterCode,
NationalCode = item.NationalCode,
LegacyChubbCodes = item.LegacyChubbCodes,
LegacyPMSCode = item.LegacyPMSCode,
ProducingBranchCode = item.ProducingBranchCode,
CategoryCode = item.CategoryCode
}).ToList();
}

Need dynamic variable names in C# for ebay feeds

I need these varaible names to be dynamic.
To give you an example of what I'm looking at > https://ebaydts.com/eBayKBDetails?KBid=1742
Now in the above link, it has some code for variaitons.
//Specify Variations
VariationTypeCollection VarCol = new VariationTypeCollection();
//Variation 1 - Black S
VariationType var1 = new VariationType();
var1.SKU = "VAR1";
var1.Quantity = 10;
var1.StartPrice = new AmountType();
var1.StartPrice.currencyID = CurrencyCodeType.AUD;
var1.StartPrice.Value = 35;
var1.VariationSpecifics = new NameValueListTypeCollection();
NameValueListType Var1Spec1 = new NameValueListType();
StringCollection Var1Spec1Valuecoll = new StringCollection();
Var1Spec1.Name = "Colour";
Var1Spec1Valuecoll.Add("Black");
Var1Spec1.Value = Var1Spec1Valuecoll;
var1.VariationSpecifics.Add(Var1Spec1);
NameValueListType Var1Spec2 = new NameValueListType();
StringCollection Var1Spec2Valuecoll = new StringCollection();
Var1Spec2.Name = "Size";
Var1Spec2Valuecoll.Add("S");
Var1Spec2.Value = Var1Spec2Valuecoll;
var1.VariationSpecifics.Add(Var1Spec2);
VarCol.Add(var1);
//Variation 2 - Black L
VariationType var2 = new VariationType();
var2.SKU = "VAR2";
var2.Quantity = 10;
var2.StartPrice = new AmountType();
var2.StartPrice.currencyID = CurrencyCodeType.AUD;
var2.StartPrice.Value = 45;
var2.VariationSpecifics = new NameValueListTypeCollection();
NameValueListType Var2Spec1 = new NameValueListType();
StringCollection Var2Spec1Valuecoll = new StringCollection();
Var2Spec1.Name = "Colour";
Var2Spec1Valuecoll.Add("Black");
Var2Spec1.Value = Var2Spec1Valuecoll;
var2.VariationSpecifics.Add(Var2Spec1);
NameValueListType Var2Spec2 = new NameValueListType();
StringCollection Var2Spec2Valuecoll = new StringCollection();
Var2Spec2.Name = "Size";
Var2Spec2Valuecoll.Add("L");
Var2Spec2.Value = Var2Spec2Valuecoll;
var2.VariationSpecifics.Add(Var2Spec2);
VarCol.Add(var2);
So the code I'm working with I would Like dynamically create the varaible names, because as you can imagine there is no way for me to know how many variations each product has.
Sure i could count the amount of variations, and set up an if else structure
if (count == 1) {
//some code
}
else if (count == 2) {
//some code
}
But that doesn't seem like a good solution.
At the moment variables are required to be output inside a for each loop
Here is the code I'm working with:
string UPC = "";
string Brand = "";
string MPN = "";
if (!String.IsNullOrEmpty(product.Gtin))
UPC = product.Gtin;
if (!String.IsNullOrEmpty(ebayProduct.EbayProductBrandName))
Brand = ebayProduct.EbayProductBrandName;
if (!String.IsNullOrEmpty(product.ManufacturerPartNumber))
MPN = product.ManufacturerPartNumber;
//create the call object
AddFixedPriceItemCall AddFPItemCall = new AddFixedPriceItemCall(context);
AddFPItemCall.AutoSetItemUUID = true;
//create an item object and set the properties
ItemType item = new ItemType();
//set the item condition depending on the value from GetCategoryFeatures
item.ConditionID = 1000; //new
//Basic properties of a listing
item.Country = CountryCodeType.AU;
item.Currency = CurrencyCodeType.AUD;
//Track item by SKU
item.InventoryTrackingMethod = InventoryTrackingMethodCodeType.SKU;
item.SKU = ebayProduct.EbayProductSKU;
if (!String.IsNullOrEmpty(ebayProduct.EbayProductDescription))
item.Description = ebayProduct.EbayProductDescription;
else
item.Description = "This product is brand new.";
if (!String.IsNullOrEmpty(ebayProduct.EbayProductTitle))
item.Title = ebayProduct.EbayProductTitle;
item.SubTitle = ebayProduct.EbayProductItemSubtitle;
item.ListingDuration = "GTC";
item.ItemSpecifics = new NameValueListTypeCollection();
NameValueListTypeCollection ItemSpecs = new NameValueListTypeCollection();
var productSpecAttributes = product.ProductSpecificationAttributes.ToList();
foreach (var val in productSpecAttributes)
{
StringCollection valueCol1 = new StringCollection();
NameValueListType nv1 = new NameValueListType();
nv1.Name = val.SpecificationAttributeOption.SpecificationAttribute.Name.Replace(":", "");
valueCol1.Add(val.CustomValue);
nv1.Value = valueCol1;
ItemSpecs.Add(nv1);
}
item.ItemSpecifics = ItemSpecs;
item.PaymentMethods = new BuyerPaymentMethodCodeTypeCollection();
item.PaymentMethods.Add(BuyerPaymentMethodCodeType.PayPal);
item.PayPalEmailAddress = "test#test.com";
item.PostalCode = "5000";
//Specify Shipping Services
item.DispatchTimeMax = 3;
item.ShippingDetails = new ShippingDetailsType();
item.ShippingDetails.ShippingServiceOptions = new ShippingServiceOptionsTypeCollection();
ShippingServiceOptionsType shipservice1 = new ShippingServiceOptionsType();
shipservice1.ShippingService = "AU_Regular";
shipservice1.ShippingServicePriority = 1;
shipservice1.ShippingServiceCost = new AmountType();
shipservice1.ShippingServiceCost.currencyID = CurrencyCodeType.AUD;
shipservice1.ShippingServiceCost.Value = 1.0;
shipservice1.ShippingServiceAdditionalCost = new AmountType();
shipservice1.ShippingServiceAdditionalCost.currencyID = CurrencyCodeType.AUD;
shipservice1.ShippingServiceAdditionalCost.Value = 1.0;
item.ShippingDetails.ShippingServiceOptions.Add(shipservice1);
ShippingServiceOptionsType shipservice2 = new ShippingServiceOptionsType();
shipservice2.ShippingService = "AU_Express";
shipservice2.ShippingServicePriority = 2;
shipservice2.ShippingServiceCost = new AmountType();
shipservice2.ShippingServiceCost.currencyID = CurrencyCodeType.AUD;
shipservice2.ShippingServiceCost.Value = 4.0;
shipservice2.ShippingServiceAdditionalCost = new AmountType();
shipservice2.ShippingServiceAdditionalCost.currencyID = CurrencyCodeType.AUD;
shipservice2.ShippingServiceAdditionalCost.Value = 1.0;
item.ShippingDetails.ShippingServiceOptions.Add(shipservice2);
//Specify Return Policy
item.ReturnPolicy = new ReturnPolicyType();
item.ReturnPolicy.ReturnsAcceptedOption = "ReturnsAccepted";
item.StartPrice = new AmountType();
item.StartPrice.currencyID = CurrencyCodeType.AUD;
item.StartPrice.Value = Double.Parse(ebayProduct.EbayProductPrice.ToString());
item.PrimaryCategory = new CategoryType();
item.PrimaryCategory.CategoryID = ebayProduct.EbayCategoryID;
item.ProductListingDetails = new ProductListingDetailsType();
//Specifying UPC as the product identifier. Other applicable product identifiers
//include ISBN, EAN, Brand-MPN.
item.ProductListingDetails.UPC = UPC;
//If multiple product identifiers are specified, eBay uses the first one that
//matches a product in eBay's catalog system.
item.ProductListingDetails.BrandMPN = new BrandMPNType();
item.ProductListingDetails.BrandMPN.Brand = ebayProduct.EbayProductBrandName;
item.ProductListingDetails.BrandMPN.MPN = product.ManufacturerPartNumber;
//If multiple prod matches found, list the item with the 1st product's information
item.ProductListingDetails.UseFirstProduct = true;
//Add pictures
item.PictureDetails = new PictureDetailsType();
item.PictureDetails.PictureURL = new StringCollection();
//Specify GalleryType
item.PictureDetails.GalleryType = GalleryTypeCodeType.None;
item.PictureDetails.GalleryTypeSpecified = true;
/*
* Handle Variations
*/
var childProducts = _productService.GetAssociatedProducts(product.Id);
if (childProducts != null)
{
//Specify VariationsSpecificsSet
item.Variations = new VariationsType();
item.Variations.VariationSpecificsSet = new NameValueListTypeCollection();
var colourSpec = productSpecAttributes.FirstOrDefault(
x => x.SpecificationAttributeOption.SpecificationAttribute.Name == "Colour");
var sizeSpec = productSpecAttributes.FirstOrDefault(
x => x.SpecificationAttributeOption.SpecificationAttribute.Name == "Size");
if (colourSpec != null && sizeSpec == null)
{
List<string> colourSpecsList = new List<string>();
foreach (var cp in childProducts)
{
var colourSpecs = cp.ProductSpecificationAttributes.FirstOrDefault(
x => x.SpecificationAttributeOption.SpecificationAttribute.Name == "Colour");
colourSpecsList.Add(colourSpecs.SpecificationAttributeOption.Name);
}
//sizes
NameValueListType NVListVS2 = new NameValueListType();
NVListVS2.Name = "Colour";
StringCollection VSvaluecollection2 = new StringCollection();
String[] Colour = colourSpecsList.ToArray();
VSvaluecollection2.AddRange(Colour);
NVListVS2.Value = VSvaluecollection2;
item.Variations.VariationSpecificsSet.Add(NVListVS2);
}
//Add Variation Specific Pictures
item.Variations.Pictures = new PicturesTypeCollection();
foreach (var cp in childProducts)
{
//Specify Variations
VariationTypeCollection VarCol = new VariationTypeCollection();
PicturesType pic = new PicturesType();
var specs = cp.ProductSpecificationAttributes.FirstOrDefault(x => x.SpecificationAttributeOption.SpecificationAttribute.Name == "Colour");
var childEbayProduct = _ebayProductService.GetEbayProductById(cp.Id);
if (!String.IsNullOrEmpty(specs.SpecificationAttributeOption.Name))
{
VariationType var1 = new VariationType();
var1.SKU = cp.RexProductId.ToString();
Debug.WriteLine(cp.RexProductId.ToString());
var1.Quantity = cp.StockQuantity;
var1.StartPrice = new AmountType();
var1.StartPrice.currencyID = CurrencyCodeType.AUD;
var1.StartPrice.Value = Double.Parse(cp.Price.ToString());
var1.VariationSpecifics = new NameValueListTypeCollection();
NameValueListType Var1Spec1 = new NameValueListType();
StringCollection Var1Spec1Valuecoll = new StringCollection();
Var1Spec1.Name = "Colour";
Var1Spec1Valuecoll.Add(specs.SpecificationAttributeOption.Name);
Var1Spec1.Value = Var1Spec1Valuecoll;
var1.VariationSpecifics.Add(Var1Spec1);
//pics
pic.VariationSpecificName = "Colour";
pic.VariationSpecificPictureSet = new VariationSpecificPictureSetTypeCollection();
VariationSpecificPictureSetType VarPicSet1 = new VariationSpecificPictureSetType();
VarPicSet1.VariationSpecificValue = specs.SpecificationAttributeOption.Name;
StringCollection PicURLVarPicSet1 = new StringCollection();
PicURLVarPicSet1.Add(childEbayProduct.EbayProductMainImgUrl);
VarPicSet1.PictureURL = PicURLVarPicSet1;
pic.VariationSpecificPictureSet.Add(VarPicSet1);
item.Variations.Pictures.Add(pic);
VarCol.Add(var1);
item.Variations.Variation = VarCol;
}
}
}
Anyone know what I might be able to do here.
Cheers
The closest thing to "dynamic variable names" is a Dictionary.
Dictionary<string, string> variables = new Dictionary<string, string>();
variables.Add("var1", "test1");
variables.Add("var2", "test2");
MessageBox.Show(variables["var1"]); // will display test1
If you have a set of needed data for each "variable", make a class or struct (maybe call it "TheData")
Dictionary<string, TheData> variables = new Dictionary<string, TheData>();
variables.Add("var1", new TheData() { price = 25.28, upc = "01121...", manufacturer = "ACME" });

How to add/update milestones in a feature using rally rest API and C#?

I am not able to add or update milestones field for the Features in the Rally. If anyone having the code available using C# to update the same, please share with me. I am searching and doing from last one week with no luck.
When I am trying to add/Update milestones in the Features. I am getting the error as "Could not read: Could not read referenced object null". My code is as follows:-
public DynamicJsonObject UpdateFeaturesbyName(string fea, string bFun)
{
//getting list of Feature.
Request feat = new Request("PortfolioItem/Feature");
feat.Query = new Query("Name", Query.Operator.Equals, fea);
QueryResult TCSResults = restApi.Query(feat);
foreach (var res in TCSResults.Results)
{
var steps = res["Milestones"];
Request tsteps = new Request(steps);
QueryResult tstepsResults = restApi.Query(tsteps);
foreach (var item in tstepsResults.Results)
{
}
if (res.Name == fea)
{
var targetFeature = TCSResults.Results.FirstOrDefault();
DynamicJsonObject toUpdate = new DynamicJsonObject();
//toUpdate["Milestones"] = "";
// CreateResult createResult = restApi.Create(steps._ref, toUpdate);
// String contentRef = steps._ref;
//String contentRef = createResult._ref;
string[] value = null;
string AccCri = string.Empty;
if (!string.IsNullOrWhiteSpace(bFun))
{
value = bFun.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
foreach (string item in value)
{
//if (string.IsNullOrWhiteSpace(AccCri))
// AccCri = item;
//else
// AccCri = AccCri + "<br/>" + item;
if (!string.IsNullOrWhiteSpace(item))
{
//Query for Milestone.
Request ms = new Request("Milestone");
ms.Fetch = new List<string>() { "Name", "ObjectID" };
ms.Query = new Query("Name", Query.Operator.Equals, item);
QueryResult msResults = restApi.Query(ms);
var targetMLResult = msResults.Results.FirstOrDefault();
long MLOID = targetMLResult["ObjectID"];
DynamicJsonObject tarML = restApi.GetByReference("Milestone", MLOID, "Name", "_ref", "DisplayColor");
DynamicJsonObject targetML = new DynamicJsonObject();
targetML["Name"] = tarML["Name"];
//targetML["_ref"] = tarML["_ref"];
targetML["_ref"] = "/milestone/" + Convert.ToString(MLOID);
targetML["DisplayColor"] = tarML["DisplayColor"];
// Grab collection of existing Milestones.
var existingMilestones = targetFeature["Milestones"];
long targetOID = targetFeature["ObjectID"];
// Milestones collection on object is expected to be a System.Collections.ArrayList.
var targetMLArray = existingMilestones;
var tagList2 = targetMLArray["_tagsNameArray"];
tagList2.Add(targetML);//
//targetMLArray.Add(targetML);
targetMLArray["_tagsNameArray"] = tagList2;
toUpdate["Milestones"] = targetMLArray;
OperationResult updateResult = restApi.Update(res._ref, toUpdate);
bool resp = updateResult.Success;
}
}
}
//toUpdate["c_AcceptanceCriteria"] = AccCri;
//OperationResult updateResult = restApi.Update(res._ref, toUpdate);
}
}
var features = TCSResults.Results.Where(p => p.Name == fea).FirstOrDefault();
var featuresref = features._ref;
return features;
}
Now that v3.1.1 of the toolkit has been released you can use the AddToCollection method to do this.
Otherwise, you can still always just update the full collection. The value should be an arraylist of objects with _ref properties.
Check out this example (which adds tasks to defects, but should be very similar to what you're doing): https://github.com/RallyCommunity/rally-dot-net-rest-apps/blob/master/UpdateTaskCollectionOnDefect/addTaskOnDefect.cs

IQueryable, converting Anonymous Type to Strong Type

Is there a more elegant/concise way of this; I'd like to get rid of foreach loop with the WorkListItem initialization code.
var queryable = registrations.Select(
r => new
{
r.Id, r.AccountNumber, r.DateAdded, r.DateUpdated, r.Patient, r.Patient.InsuranceInfos
});
var list = queryable.ToList();
var workListItems = new List<WorkListItem>();
foreach (var anonymous in list)
{
var w = new WorkListItem
{
Id = anonymous.Id,
ClientAccountId = anonymous.AccountNumber,
DateAdded = anonymous.DateAdded,
DateUpdated = anonymous.DateUpdated,
Patient = anonymous.Patient,
InsuraceInfos = anonymous.Patient.InsuranceInfos
};
workListItems.Add(w);
}
return workListItems;
Yes you can completely cut out the "middle-man" as it were and select straight into a new WorkListItem as below:
var list = registrations.Select(r => new WorkListItem
{
Id = r.Id,
ClientAccountId = r.AccountNumber,
DateAdded = r.DateAdded,
DateUpdated = r.DateUpdated,
Patient = r.Patient,
InsuraceInfos = r.Patient.InsuranceInfos
}).ToList();

Categories