Clean up Validation Logic, Avoid Using Too Many If Statments - c#

I am currently writing a validation that reads data from an api and checks for differet "domaintypes". There are 6 domaintypes types in total (windows, low, high, and dot, linux low, high, and dot) that need to present, I am currently checking by using a bunch of if statements, but I feel like it's super drawn out and messy. I've been trying to tweak it to make it more concise, but it keeps messing with the logic and I don't get what I need. I'm fairly new to c# so I'm probably missing something super obvious. Here is the current code below:
// get api response
var products = responseProvider.GetServiceResponse
var count = 0;
List<string> missingdomainskus = new List<string>();
foreach (var product in products)
{
var productInfo = responseProvider.GetProductResponse(product).Result;
var skus = productInfo.Skus;
foreach (Sku sku in skus)
{
string Name = sku.Aspects[Name];
if (sku.Aspects.ContainsKey(Item) && Item.Equals("Dot", StringComparison.OrdinalIgnoreCase) && sku.Aspects[Group].Contains("Windows"))
{
count++;
}
if (sku.Aspects.ContainsKey(Item) && Item.Equals("Low", StringComparison.OrdinalIgnoreCase) && sku.Aspects[Group].Contains("Windows"))
{
count++;
}
//Null orwhitespace = "high"
if ((!sku.Aspects.ContainsKey(Item) || string.IsNullOrWhiteSpace(Item)) && sku.Aspects[Group].Contains("Windows"))
{
count++;
}
if (sku.Aspects.ContainsKey(Item) && Item.Equals("Dot", StringComparison.OrdinalIgnoreCase) && !sku.Aspects[Group].Contains("Windows"))
{
count++;
}
if (sku.Aspects.ContainsKey(Item) && Item.Equals("Low Priority", StringComparison.OrdinalIgnoreCase) && !sku.Aspects[Group].Contains("Windows"))
{
count++;
}
if ((!sku.Aspects.ContainsKey(Item) || string.IsNullOrWhiteSpace(Item)) && !sku.Aspects[Group].Contains("Windows"))
{
count++;
}
if (count < 6)
{
missingdomainskus.Add(Name);
}
}
}
if (missingdomainskus.Any())
{
string convert = string.Join(",", missingdomainskus);
throw new CheckException($"These skus are missing domains: : {convert} i. There should be 6-7 domains per sku");
}

Related

Paragraphs formatting slow in VSTO

I am using VSTO to get some paragraphs and save their formatting in a List.The code is working fine but the problem is that this function is taking almost 50% of the execution time of my program.
It is also known that the loop is making performance slow.
I want to know that how can I optimize the time of this function.Any alternative to list or any other thing?
public static void GetFormattedParas(Range content, Driver currentDriver)
{
// TODO add check for tables row end "\r\a" words to ignore them for query
Paragraphs paras = content.Paragraphs;
List<Paragraph> paraList = paras.Cast<Paragraph>().ToList();
List<Range> Ranges = new List<Range>();
if (paraList != null)
{
paraList.RemoveAll(range => range.Range.Text == null);
paraList.RemoveAll(range => range.Range.Text.Equals("\r\a") && range.Range.Tables.Count != 0 && range.Range.Rows[1].Range.End == range.Range.End);
for (int i = 0, ParaCount = paraList.Count; i < ParaCount; i++)
{
Range range = paraList[i].Range;
if (range.Font.Shading.BackgroundPatternColorIndex != WdColorIndex.wdNoHighlight
|| range.HighlightColorIndex != WdColorIndex.wdNoHighlight
|| range.Shading.BackgroundPatternColorIndex != WdColorIndex.wdNoHighlight)
{
Ranges.Add(paraList[i].Range);
}
}
//Ranges = (from range in paraList
// where range.Range.Font.Shading.BackgroundPatternColorIndex != WdColorIndex.wdNoHighlight
// || range.Range.HighlightColorIndex != WdColorIndex.wdNoHighlight
// || range.Range.Shading.BackgroundPatternColorIndex != WdColorIndex.wdNoHighlight
// select range.Range).OrderBy(o => o.Start).ToList();
if (Ranges != null)
{
Ranges = Ranges.OrderBy(o => o.Start).ToList();
if (Ranges.Count > 0)
{
//if (Ranges.Count == 1)
//{
// currentDriver.formattedParas.Add(content);
//}
//else
//{
currentDriver.formattedParas.AddRange(Ranges);
//}
}
}
}
}

Serialize arithmetic expression-tree

I'm doing a simple task for investigation purposes. The problem is as follows:
Create an arithmetic expression with variables.
Build an AST for the expression.
Send it to the server (using Sockets)
Calculate an result of the server side and return the results.
Now I can to build a tree. This method doing it:
private readonly Stack<Expression> expressionStack = new Stack<Expression>();
private readonly Stack<Symbol> operatorStack = new Stack<Symbol>();
private readonly List<string> parameters = new List<string>();
public Expression<Func<decimal[], decimal>> Parse(string expression)
{
if (string.IsNullOrWhiteSpace(expression))
{
return s => 0;
}
var arrayParameter = Expression.Parameter(typeof(decimal[]), "args");
parameters.Clear();
operatorStack.Clear();
expressionStack.Clear();
using (var reader = new StringReader(expression))
{
int peek;
while ((peek = reader.Peek()) > -1)
{
var next = (char)peek;
if (char.IsDigit(next))
{
expressionStack.Push(ReadOperand(reader));
continue;
}
if (char.IsLetter(next))
{
expressionStack.Push(ReadParameter(reader, arrayParameter));
continue;
}
if (Operation.IsDefined(next))
{
if (next == '-' && expressionStack.Count == 0)
{
reader.Read();
operatorStack.Push(Operation.UnaryMinus);
continue;
}
var currentOperation = ReadOperation(reader);
EvaluateWhile(() => operatorStack.Count > 0 && operatorStack.Peek() != Parentheses.Left &&
currentOperation.Precedence <= ((Operation)operatorStack.Peek()).Precedence);
operatorStack.Push(currentOperation);
continue;
}
if (next == '(')
{
reader.Read();
operatorStack.Push(Parentheses.Left);
if (reader.Peek() == '-')
{
reader.Read();
operatorStack.Push(Operation.UnaryMinus);
}
continue;
}
if (next == ')')
{
reader.Read();
EvaluateWhile(() => operatorStack.Count > 0 && operatorStack.Peek() != Parentheses.Left);
operatorStack.Pop();
continue;
}
if (next == ' ')
{
reader.Read();
}
else
{
throw new ArgumentException(string.Format("Encountered invalid character {0}", next),
"expression");
}
}
}
EvaluateWhile(() => operatorStack.Count > 0);
return Expression.Lambda<Func<decimal[], decimal>>(expressionStack.Pop(), arrayParameter);
}
This method works, and returns the expected result.
Before being sent to the server I want to serialize a tree to binary type. My question is as follows. Which is the simplest way I can apply for this?
I found a lot of solutions for LINQ serialization, but they are too big. I don't need the full functionality of these solutions. In addition, usually, they provide the JSON or XML-serialization, but I need a binary serialization.
Can somebody suggest a simple and easy solution for this problem?

Parsing CSV strings (not files) in C#

Using C#, I need to parse a CSV string that doesn't come from a file. I've found a great deal of material on parsing CSV files, but virtually nothing on strings. It seems as though this should be simple, yet thus far I can come up only with inefficient methods, such as this:
using Microsoft.VisualBasic.FileIO;
var csvParser = new TextFieldParser(new StringReader(strCsvLine));
csvParser.SetDelimiters(new string[] { "," });
csvParser.HasFieldsEnclosedInQuotes = true;
Are there good ways of making this more efficient and less ugly? I will be processing huge volumes of strings, so I wouldn't want to pay the cost of all the above. Thanks.
Here is a lightly tested parser that handles quotes
List<string> Parse(string line)
{
var columns = new List<string>();
var sb = new StringBuilder();
bool isQuoted = false;
int nQuotes = 0;
foreach(var c in line)
{
if (sb.Length == 0 && !isQuoted && c == '"')
{
isQuoted = true;
continue;
}
if (isQuoted)
{
if (c == '"')
{
nQuotes++;
continue;
}
else
{
if (nQuotes > 0)
{
sb.Append('"', nQuotes / 2);
if (nQuotes % 2 != 0)
{
isQuoted = false;
}
nQuotes = 0;
}
}
}
if (!isQuoted && c == ',')
{
columns.Add(sb.ToString());
sb.Clear();
continue;
}
sb.Append(c);
}
if (nQuotes > 0)
{
sb.Append('"', nQuotes / 2);
}
columns.Add(sb.ToString());
return columns;
}

Merging of Two space objects into single space

Here, Space is a class with (xposition, yposition, zposition, length, depth, height) as its elements and there is a list of type space.
I need to check with in the list whether it follows some conditions which are in if condition.
If it satisfies, then I merge the two spaces into single space. After that, I remove both the spaces which I have used. It actually means merging of two spaces into single space.
The new List is created. Again I treat it as new list and do the same procedure until it does not satisfies the conditions.
My problem is, it is going into infinite loop. I want to resolve this.
public class MergeSpace
{
public List<Space> Mergespace(List<Space> Listofspaces)
{
foreach (Space space1 in Listofspaces)
{
foreach (Space space2 in Listofspaces)
{
//int count = 0;
if ((space1.sheight == space2.sheight)
&& (space1.sdepth == space2.sdepth)
&& (space2.xposition == space1.xposition + space1.slength)
&& (space2.yposition == space1.yposition)
&& (space2.zposition == space1.zposition)
&& (space1.semptyspace == true)
&& (space2.semptyspace == true))
{
Space space = new Space();
space.xposition = space1.xposition;
space.yposition = space1.yposition;
space.zposition = space1.zposition;
space1.slength = space1.slength + space2.slength;
space.sheight = space1.sheight;
space.sdepth = space1.sdepth;
space.semptyspace = true;
Listofspaces.Add(space);
Listofspaces.Remove(space1);
Listofspaces.Remove(space2);
Mergespace(Listofspaces);
}
public class MergeSpace
{
public List<Space> Mergespace(List<Space> Listofspaces)
{
List<Space> mergedspacelist = new List<Space>();
int count=0;
foreach (Space space1 in Listofspaces)
{
foreach (Space space2 in Listofspaces)
{
//int count = 0;
if ((space1.sheight == space2.sheight)
&& (space1.sdepth == space2.sdepth)
&& (space2.xposition == space1.xposition + space1.slength)
&& (space2.yposition == space1.yposition)
&& (space2.zposition == space1.zposition)
&& (space1.semptyspace == true)
&& (space2.semptyspace == true))
{
Space space = new Space();
space.xposition = space1.xposition;
space.yposition = space1.yposition;
space.zposition = space1.zposition;
space1.slength = space1.slength + space2.slength;
space.sheight = space1.sheight;
space.sdepth = space1.sdepth;
space.semptyspace = true;
mergedspacelist .Add(space);
count++;
}
}
}
if(count>0)
{
Mergespace(mergedspacelist );
}
}
i dont know what your actual need is, i think this will avoid the infinite loop
Your conditions always will satisfy for same instance of Space. The instance will merge with itself.
if (!space1.Equals(space2))
{
if ((space1.sheight == space2.sheight)
...
}

how to iterate collection and change value

I know this is a dumb question because you cannot modify the loop collection while in a loop, but I do need to change it. I know I must not change the referenced objects, but I have no idea how to do this.
var orders = _orderService.GetOrders(o => !o.Deleted &&
o.OrderStatus != OrderStatus.Cancelled &&
o.OrderStatus != OrderStatus.Complete);
foreach (var order in orders)
{
if (order.PaymentStatus == PaymentStatus.Paid)
{
if (order.ShippingStatus == ShippingStatus.ShippingNotRequired || order.ShippingStatus == ShippingStatus.Delivered)
{
var tempOrder = _orderService.GetOrderById(order.Id);
SetOrderStatus(tempOrder , OrderStatus.Complete, true);
}
}
}
I always get an error.
UPDATED: I changed to this
var orders = _orderService.GetOrders(o => !o.Deleted &&
o.OrderStatus != OrderStatus.Cancelled && o.OrderStatus != OrderStatus.CompletE);
List<int> orderIndex = new List<int>();
orders.ToList().ForEach(x => orderIndex.Add(x.Id));
foreach(var index in orderIndex)
{
var order = _orderService.GetOrderById(index);
if (order.PaymentStatus == PaymentStatus.Paid)
{
if (order.ShippingStatus == ShippingStatus.ShippingNotRequired || order.ShippingStatus == ShippingStatus.Delivered)
{
SetOrderStatus(order, OrderStatus.Complete, true);
}
}
}
try
int count = orders.Count; // the length of the collect : may need a different method for different collection types.
for(int i = 0; i < count; i++)
{
var current = orders[i];
// do stuff with current.
}
use for loop instead of foreach loop
for(int i=0; i<orders.Count; i++)
{
if (orders[i].PaymentStatus == PaymentStatus.Paid)
{
if (orders[i].ShippingStatus == ShippingStatus.ShippingNotRequired || orders[i].ShippingStatus == ShippingStatus.Delivered)
{
var tempOrder = _orderService.GetOrderById(orders[i].Id);
SetOrderStatus(tempOrder , OrderStatus.Complete, true);
}
}
}

Categories

Resources