I want to ask you regarding for the searching in C# and why there is a Not Found statement if already found the answer or the data itself.
Here is the code:
Console.WriteLine("Enter Plate Number: ");
string plateNumber1 = Console.ReadLine();
var searchPlateNumberDAL = new ParkingSystemDAL(_iconfiguration);
var listSlotParking = searchPlateNumberDAL.GetList();
listSlotParking.ForEach(item =>
{
bool searchItem = item.plateNumber == plateNumber1;
if (searchItem == true)
{
Console.WriteLine(item.parkingId);
}
else
{
Console.WriteLine("Not Found");
}
});
output
I think there some garbage value is present.
So, code will be
if(item.plateNumber.ToString().Trim().ToUpper() == plateNumber1.ToString().Trim().ToUpper())
{
Console.WriteLine(item.parkingId);
}
you can also use Linq Where expression instead of ForEach
if( listSlotParking.Where(x =>x.planteNumberplateNumber.ToString().Trim().ToUpper() == plateNumber1.ToString().Trim().ToUpper()).ToList().Count()>0)
{
Console.WriteLine(item.parkingId);
}
Try
item.plateNumber.Trim() == plateNumber1.Trim()
Related
Here is the code for my work.
public void InsertValue(WordprocessingDocument doc, string bookMark, string txt)
{
try
{
RemoveBookMarkContent(doc, bookMark);
var bmStart = FindBookMarkStart(doc, bookMark);
if (bmStart == null)
return;
var run = new Run();
run.Append(GetRunProperties());
run.Append(new Text(txt));
bmStart.Parent.InsertAfter(run, bmStart);
}
catch (Exception c)
{
//not Exception
}
}
private void RemoveBookMarkContent(WordprocessingDocument doc, string bmName)
{
BookmarkStart bmStart = FindBookMarkStart(doc, bmName);
if (bmStart == null)
return;
BookmarkEnd bmEnd = FindBookMarkEnd(doc, bmStart.Id);
while (true)
{
var run = bmStart.NextSibling();
if (run == null)
{
break;
}
if (run is BookmarkEnd && (BookmarkEnd)run == bmEnd)
{
break;
}
run.Remove();
}
}
There are still several auxiliary classes not written.Work process, first find the bookmark location, delete the content of the bookmark location, and then add it.I've also tried to add one Paragraph to the bookmark location.But that doesn't work.
Document to insert in bookmark eg:露点:U=0.15℃(k=2);相对湿度:U=1.0%RH(k=2).Both u and K must be italics.Any help will be appreciated.Thanks.
I tried a new component.[Spire.Office.][1]
At the beginning, I didn't think of a solution, but I used the global search and replacement to determine whether the search location has bookmarks, which perfectly solved the problem.
Here is the code for my work.
var selection = document.FindAllString("U", false, true);
foreach (var sec in selection)
{
var t = sec.GetAsOneRange();
if (sec.GetAsOneRange()?.Owner?.LastChild?.DocumentObjectType == DocumentObjectType.BookmarkEnd)
{
sec.GetAsOneRange().CharacterFormat.Italic = true;
}
}
I didn't try to do this with openxml, but I think the principle should be consistent.
[1]: https://www.e-iceblue.cn/Buy/Spire-PDF-NET.html
Im facing performance issue in below code in multiple foreach loops. First im getting a list of ReturnDetails and then based on detail id get the HandlingInfo object. Then based on value of action, update the ReturnsDetail Object again.
It take more than a minute for loading 3000 records of ReturnsDetail. While debugging locally, it runs for infinite amount of time.
Please let me know in anyway i can refactor this code .
Thanks for your help.
lstReturnsDetail = dcReturnsService.GetReturnDetailsInfo(header_id);
List<HandlingInfo> lstHandlingInfo = null;
foreach (ReturnsDetail oReturnsDetail in lstReturnsDetail)
{
using (DCReturns_Entities entities = new DCReturns_Entities())
{
lstHandlingInfo = entities.HandlingInfoes.Where(f => f.detail_id == oReturnsDetail.id).ToList();
if(lstHandlingInfo != null)
{
foreach (HandlingInfo oHandlingInfo in lstHandlingInfo)
{
if (oHandlingInfo.action == "DST")
{
oReturnsDetail.destroy += Convert.ToInt32(oHandlingInfo.qty);
}
else if (oHandlingInfo.action == "SHP")
{
oReturnsDetail.to_shop += Convert.ToInt32(oHandlingInfo.qty);
}
else if (oHandlingInfo.action == "RBX")
{
oReturnsDetail.in_stock += Convert.ToInt32(oHandlingInfo.qty);
}
}
}
}
oReturnsDetail.received_qty = oReturnsDetail.destroy + oReturnsDetail.to_shop + oReturnsDetail.in_stock;
}
dgReturnsDetail.DataSource = lstReturnsDetail.OrderByDescending(g => g.id).ToList();
Session[DCReturnsConstants.Returns_Detail_Entity] = lstReturnsDetail;
dgReturnsDetail.DataBind();
this is su-do code! but you should get the jist.
//modify this to return all of them into mem, and then filter on this...
//if it can not be done here then do below..
var lstReturnsDetail = dcReturnsService.GetReturnDetailsInfo(header_id);
//then create a list here which fetches all,
List<[type]> somelist
List<int> listId = lstReturnsDetail.select(x=>x.id).tolist();
using (var db = new DCReturns_Entities())
{
somelist = db.HandlingInfoes.Where(f => listId.Contains( f.detail_id)).ToList();
}
foreach (ReturnsDetail oReturnsDetail in lstReturnsDetail)
{
//performance issue is here
//using (DCReturns_Entities entities = new DCReturns_Entities())
//{
// lstHandlingInfo = entities.HandlingInfoes.Where(f => f.detail_id == oReturnsDetail.id).ToList();
//}
//insead fetach all before, into mem and filter from that list.
var lstHandlingInfo = somelist.Where(f => f.detail_id == oReturnsDetail.id).ToList();
//code ommited for reaablity
}
//code ommited for reaablity
My requirement is to create a web api in c# that will create another API According to the document.
User will send api name, action method name , Request and type of operation that need to be performed by the new api and our api will create the required api and return response that contain API url and request/response type.
I have searched in lot of different website but i did't found anything related to it. if anyone have solution of it or any close idea please share. i need to do this in asp.net MVC
I have a sample program that uses CodeDomCompiler that generates a standard Telemetry implementation for any given interface. The code is compiled to memory and loaded into the address space. This sounds like what you are trying to do. If so, take stab at generating some code using the samples and ask questions as you encounter problems.
This may help you get started.
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using TelemeterFactory;
namespace ConsoleTelemeter
{
/// <summary>Generate a CSharp Telemeter that calls Console.WriteLine as its output.</summary>
public class Factory : FactoryBase
{
public override string[] GenerateSource(SourceGenerationOptions options)
{
var generatedClassName = options.Type.Name + "_" + options.FactoryOptions.ClassName;
var text = this.CSharpTemplate()
.Replace("<codeGenerationTool>", $"{nameof(ConsoleTelemeter)} {Assembly.GetExecutingAssembly().GetName().Version} {DateTimeOffset.UtcNow:yyyy-MM-dd HH:mm:ss zzz}")
.Replace("<generatedNamespace>", options.FactoryOptions.Namespace)
.Replace("<generatedClassName>", generatedClassName)
.Replace("<interfaceImplemented>", options.Type.FullName)
.Replace("//<privateFields>", "private const string Null = \"<null>\";")
.Replace("//<publicMethodImplementations>", Methods(options.Methods))
.Replace("\t", " ")
;
return new[] { text, $"{options.FactoryOptions.Namespace}.{generatedClassName}" };
}
private string Methods(IReadOnlyList<MethodInfo> methods)
{
var sb = new StringBuilder(4096);
foreach (var method in methods)
{
// method start
sb.AppendFormat("\n\t\tpublic {0} {1} (", method.ReturnType, method.Name);
var comma = string.Empty;
foreach (ParameterInfo parameter in method.GetParameters())
{
sb.AppendFormat("{0}{1} {2}", comma, parameter.ParameterType, parameter.Name);
comma = ", ";
}
sb.Append(") {\n");
sb.Append("\t\t\tvar result = $\"{DateTimeOffset.UtcNow:yyyy-MM-dd HH:mm:ss.ffffff} ");
sb.Append("{nameof(");
sb.Append(method.Name);
sb.Append(")}: ");
comma = string.Empty;
foreach (ParameterInfo parameter in method.GetParameters())
{
var t = parameter.ParameterType;
sb.AppendFormat("{0}{{nameof({1})}}={{", comma, parameter.Name);
// special case for boolean parameters to be coerced to strings below. Not strictly necessary for this Telemeter but show how one could do it if necessary.
sb.AppendFormat("{1}{0}", parameter.Name, t == typeof(Boolean) ? "(" : string.Empty);
if (t == typeof(string))
{
sb.Append(" ?? Null");
}
else if (t == typeof(Int32)
|| t == typeof(float)
|| t == typeof(double)
|| t == typeof(Int64)
|| t == typeof(decimal)
|| t == typeof(Int16))
{
sb.Append(":#0");
}
else if (t.BaseType == typeof(Enum))
{
sb.Append(":D");
}
else if (t == typeof(Boolean))
{
sb.Append("? \"1\" : \"0\")");
}
else
{
sb.Append(".ToString() ?? Null");
}
sb.Append("}");
comma = ",";
}
sb.Append("\";\n\t\t\treturn result;\n");
// method end
sb.Append("\t\t}\n");
}
return sb.ToString();
}
}
}
I'm not a developer so maybe the answer is out there for a different solution but I can't really translate it from python or something else.
I'm trying to use the AWS .NET SDK to find an instance and then get the instance's tags. I've gotten as far as being able to determine if an instance is up and running or not. I also see how I can create and delete tags (not in code example below). But I don't see an easy way to actually check if a tag exists and get the value of the tag if it does exist.
Sorry if I'm missing the obvious but this is all new to me. Here's an example of the code I'm using to check if an instance is running.
instanceID = "i-myInstanceID";
do {
var myrequest = new DescribeInstanceStatusRequest();
DescribeInstanceStatusResponse myresponse = ec2.DescribeInstanceStatus(myrequest);
int isCount = myresponse.DescribeInstanceStatusResult.InstanceStatuses.Count;
for (int isc=0; isc < isCount; isc++) {
InstanceStatus instanceStatus = myresponse.DescribeInstanceStatusResult.InstanceStatuses[isc];
if (instanceStatus.InstanceId.Contains(instanceID)) {
Console.WriteLine("It looks like instance "+instanceID+" is running.");
idIdx = isc;
foundID = true;
break;
}
}
if ((foundID==false) && (secondCounter==1)) {
Console.Write("Looking for instance "+instanceID);
} else {
Console.Write(".");
}
Thread.Sleep(1000);
secondCounter++;
if (secondCounter > 5) {
break;
}
} while (foundID == false) ;
First send a DescribeInstancesRequest to get the list of Instances:
public DescribeInstancesResult GetInstances(Ec2Key ec2Key)
{
_logger.Debug("GetInstances Start.");
AmazonEC2 ec2 = CreateAmazonEc2Client(ec2Key);
var ec2Request = new DescribeInstancesRequest();
DescribeInstancesResponse describeInstancesResponse = ec2.DescribeInstances(ec2Request);
DescribeInstancesResult result = describeInstancesResponse.DescribeInstancesResult;
_logger.Debug("GetInstances End.");
return result;
}
Then loop through the instances until you find the one you want, and then use the Tag.GetTagValueByKey method:
// This just calls the above code
DescribeInstancesResult ec2Instances = _ec2ResourceAccess.GetInstances(ec2Key);
var returnInstances = new List<Ec2UtilityInstance>();
foreach (var reservation in ec2Instances.Reservation)
{
foreach (var runningInstance in reservation.RunningInstance)
{
var returnInstance = new Ec2UtilityInstance();
returnInstance.InstanceId = runningInstance.InstanceId;
returnInstance.InstanceName = runningInstance.Tag.GetTagValueByKey("Name");
returnInstance.Status = (Ec2UtilityInstanceStatus)Enum.Parse(typeof(Ec2UtilityInstanceStatus), runningInstance.InstanceState.Name, true);
returnInstance.DefaultIp = runningInstance.Tag.GetTagValueByKey("DefaultIp");
returnInstance.InstanceType = runningInstance.InstanceType;
returnInstance.ImageId = runningInstance.ImageId;
returnInstances.Add(returnInstance);
}
}
Here is the link for full source that this was taken from:
https://github.com/escherrer/EC2Utilities
Common\Manager
and
Common\ResourceAccess
I've just started foraying into EF, and I'm trying to get my head around it (Generally easy enough). However for some reason it's not actually saving the results, though it appears to be maybe cacheing the values for a time, and then rolling back to the previous values?
using (IAPlayerEntities IAPE = new IAPlayerEntities()) {
ObjectSet<Player> Players = IAPE.Players;
if (Players.Count() > 0) {
Player currentPlayer = new Player();
bool LoggedIn = false;
Players.DefaultIfEmpty(null);
while (!LoggedIn) {
Console.WriteLine("Please enter your Username:");
string username = Console.ReadLine();
Console.WriteLine("Please enter your Password:");
string password = MaskLine();
currentPlayer = Players.FirstOrDefault(r => r.Password == password && r.Name == username);
LoggedIn = (currentPlayer != null);
if (!LoggedIn) {
Console.WriteLine("{0}Invalid combination, please try again.", Environment.NewLine);
}
}
Console.WriteLine("{0}Please choose your colony.", Environment.NewLine);
foreach (Colony col in currentPlayer.Colonies) {
Console.WriteLine(#"{0}{1}:{0}{2}{0}Level {3}", Environment.NewLine, col.ID, col.Name, col.Level);
}
Console.WriteLine();
int colID = -1;
string colStr = Console.ReadLine();
while (!int.TryParse(colStr, out colID) || !currentPlayer.Colonies.Any(e => e.ID == colID)) {
if (colStr.ToLower() == "q") {
Console.WriteLine("Goodbye!");
return;
}
Console.WriteLine("{0}Invalid Colony. Please try again.", Environment.NewLine);
colStr = Console.ReadLine();
}
Console.WriteLine("Please enter a new name for the colony:");
string colName = Console.ReadLine();
bool b = IAPE.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Deleted | EntityState.Modified).Any();
currentPlayer.Colonies.First(e => e.ID == colID).Name = colName;
int change = IAPE.SaveChanges();
if (change >= 1) {
Console.WriteLine("{0}Colony has been renamed.", Environment.NewLine);
} else {
Console.WriteLine("{0}Colony could not be renamed.", Environment.NewLine);
}
} else {
Console.WriteLine("No Registered users");
}
}
Ignore the über secure login, it's only in there to get a player entity from it for testing.
the bool b is set to true before the save, and then if I use the debugger to run the same line in the "Immediate Window" pane then it shows false. Which to me, means it saved? And If I re-run the application after it's closed then the changed value is in place. But eventually it will return to the previous value, and if I check the database straight after it still shows the original name, so I'm not quite sure what's going on here?
It's running on VCS2010, so Framework 4.
Thanks, Psy
Checked the SQL going over to the database, and it's fine, after some investigation, turned out that I had a copy of the database within the project, which was over-riding the one in the output everytime I rebuilt it.
IAPE.Savechanges() at some point.