zeros at start were not fetching while reading the table data in specflow - specflow

I want to read table data from the specflow feature file.
Table value is '000085'
When I create a sales quotation from the table:
| CustomerAccount |
| 000085 |
//Code:
public void CreateSalesQuotation(Table table)
{
dynamic tableData = table.CreateDynamicInstance();
int x = tableData.CustomerAccount;
}
Result:
Expected value is 000085 but actual value i am getting in x variable is 85

What is the version of specflow?
Better you use CreateInstance rather than CreateDynamicInstance to avoid extra operation on string.
public void CreateSalesQuotation(Table table)
{
var tableData = table.CreateInstance<Customer>();
var value = tableData.CustomerAccount;
}
internal class Customer
{
public string CustomerAccount { get; set; }
}
Result: Expected value is 000085 and actual value is 000085

There are two solutions: Using this as a string from the start. Since probably in the database this is a char or varchar as well (similar to string).
string x = tableData.CustomerAccount;
//value is 000085
Or you could manipulate the integer to a string with leading zeros.
int x = tableData.CustomerAccount;
//now it is 85
string y = x.ToString();
//we convert to string so we can use padleft
string z = y.PadLeft(2, '0');
//this will add 2 zeros to the beginning of the string.
Ofcourse you would want to optimize this last bit so that the leading zeros are correct.

Related

How to set value inside nested forEach() in java8?

I have a case in which I am iterating the List<DiscountClass> and need to compare the list value with another List<TypeCode>, based on satisfying the condition (when Discount.code equals TypeCode.code) I need to set Discount.setCodeDescr(). How to achieve this with nested forEach loop in java 8? (I am not able to set after comparing the values in java 8 forEach).
for (Discount dis : discountList) {
for (TypeCode code : typeCodeList) {
if (dis.getCode().equals(code.getCode())) {
dis.setCodeDesc(code.getCodeDesc());
}
}
}
A possible solution using java 8 lambdas could look like this:
discountList.forEach(dis -> {
typeCodeList
.stream()
.filter(code -> dis.getCode().equals(code.getCode()))
.findAny()
.ifPresent(code -> dis.setCodeDesc(code.getCodeDesc()));
});
For each discount you filter the TypeCodes according to the code and if you find any you set the desc poperty to the one of the found TypeCode.
The other answer showed how to convert a nested loop to a nested functional loop.
But instead of iterating over a list of TypeCode, it's better to use a HashMap to get random access, or an enum like this:
public enum TypeCode {
CODE_1("description of code 1"),
CODE_2("description of code 2");
private String desc;
TypeCode(String desc) {
this.desc = desc;
}
public String getDesc() {
return desc;
}
}
public class Discount {
private String typeCode; //assuming you can't have the type as TypeCode
private String desc;
public Discount(String typeCode) {
this.typeCode = typeCode;
}
//getters/setters
}
Then your code will change to:
Discount d1 = new Discount("CODE_1");
Discount d2 = new Discount("CODE_2");
List<Discount> discounts = List.of(d1, d2);
discounts.forEach(discount ->
discount.setDesc(TypeCode.valueOf(discount.getTypeCode()).getDesc()));

How to get the last n-characters in a string in Dart?

How do I get the last n-characters in a string?
I've tried using:
var string = 'Dart is fun';
var newString = string.substring(-5);
But that does not seem to be correct
var newString = string.substring(string.length - 5);
Create an extension:
extension E on String {
String lastChars(int n) => substring(length - n);
}
Usage:
var source = 'Hello World';
var output = source.lastChars(5); // 'World'
While #Alexandre Ardhuin is correct, it is important to note that if the string has fewer than n characters, an exception will be raised:
Uncaught Error: RangeError: Value not in range: -5
It would behoove you to check the length before running it that way
String newString(String oldString, int n) {
if (oldString.length >= n) {
return oldString.substring(oldString.length - n)
} else {
// return whatever you want
}
}
While you're at it, you might also consider ensuring that the given string is not null.
oldString ??= '';
If you like one-liners, another options would be:
String newString = oldString.padLeft(n).substring(max(oldString.length - n, 0)).trim()
If you expect it to always return a string with length of n, you could pad it with whatever default value you want (.padLeft(n, '0')), or just leave off the trim().
At least, as of Dart SDK 2.8.1, that is the case. I know they are working on improving null safety and this might change in the future.
var newString = string.substring((string.length - 5).clamp(0, string.length));
note: I am using clamp in order to avoid Value Range Error. By that you are also immune to negative n-characters if that is somehow calculated.
In fact I wonder that dart does not have such clamp implemented within the substring method.
If you want to be null aware, just use:
var newString = string?.substring((string.length - 5).clamp(0, string.length));
I wrote my own solution to get any no of last n digits from a string of unknown length, for example the 5th to the last digit from an n digit string,
String bin='408 408 408 408 408 1888';// this is the your string
// this function is to remove space from the string and then reverse the
string, then convert it to a list
List reversed=bin.replaceAll(" ","").split('').reversed.toList();
//and then get the 0 to 4th digit meaning if you want to get say 6th to last digit, just pass 0,6 here and so on. This second reverse function, return the string to its initial arrangement
var list = reversed.sublist(0,4).reversed.toList();
var concatenate = StringBuffer();
// this function is to convert the list back to string
list.forEach((item){
concatenate.write(item);
});
print(concatenate);// concatenate is the string you need

Checking a nullable property after a null-conditional check of parent object

Appreciate there have been some question close to what I am asking but not quite like here. I have been checking the ?. operator and I came upon the following scenario. Situation is as follows:
internal class Dog
{
public int? Age { get; set; }
}
Checks in main code were as follows:
Dog d2 = new Dog() { Age = 10 };
int age1 = d2.Age.Value; // compiles okay
int age2 = d2?.Age.Value; // CS0266
I would like to know why the code line with age3 is requesting an explicit cast. d2.Age being type int? and Age.Value being type int doesn't vary between the two usages.
Once you use the null-condicional operator, the resulting value can be null. that's why it can never be int.
What you need is:
int age2 = (d2?.Age).Value;

SumAsync() with nvarchar value

I have tbl_purchase table which has fields such as order_date - DateTime,price - nvarchar, pid - int etc., Requirement is to display total price with respect to each year in a chart. So to get the price, I decided to go with SumAsync. But the problem here is price field will be stored appended with $ as in $12,234.03,$4,453.23 etc., and as mentioned it is a nvarchar field. I Tried splitting the value within SumAsync() but was getting compilation error. Totally blank on how to work with this? Any work-around to split the $ and sum up the values? Below is what I tried.
ChartData.cs
public class ChartData
{
public string period {get;set;}
public int purchase {get;set;}
public string purchaseAmount {get;set;}
}
Controller method
var areaModel = new List<ChartData>();
var yearList = new string[]{'2015','2016'};
foreach (var year in yearList)
{
int yr=Convert.ToInt32(year);
var model = new ChartData
{
period = year,
purchaseAmount=await context.tbl_purchases.Where(x=>x.order_date.Year == yr).SumAsync(x=>(long)x.price.Split('$')[1]); //shows complie error. Its expecting `long` but the conversion doesn't happen well here.
};
areaModel.Add(model);
}
if price format is computed and always the same you can do as follow to calculate the price:
var price = new List<string> { "$4,000.99","$20.99","$40,000.88"};
var sum = price.AsEnumerAble().Sum(x => double.Parse(x.Replace("$", "0")));
I just replace the $ with 0 and calculate the sum.

Invalid rank specifier

I am trying to create a dungeon crawler with a tile-based map. However, I get an error when creating the array of tiles. (Right now, Tile is a class with nothing but an empty constructor.)
class Map
{
Tile[][] Tiles;
static const int DefaultWidth = 640, DefaultHeight = 480;
Random rnd;
public Map(int? Width, int? Height, int? seed)
{
Tiles = new Tile[((Width == null) ? DefaultWidth : (int)Width)]
//This line gives the error "invalid rank specifier: expected ',' or ']'" after the first bracket
[((Height == null) ? DefaultHeight : (int)Height)];
Generate();
}
void Generate()
{
}
}
Why am I getting this error?
In C#, the right way to instantiate a 2D array is to use a comma instead:
int[,] array = new [3,2];
You can still make arrays such as int[][], but you'll need to use a for loop to create every individual array inside it (which can be of different lengths), and this is known as a jagged array. I would recommend, however, to use the comma syntax as it is idiomatic in C# and is the expected way to do things.

Resources