I have a winform with a button and a datagridview.
The scenario is:
I have a winform:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
CreateItems();
}
private List<Store> stores = new List<Store>();
public void CreateItems()
{
Store newStore1 = new Store();
newStore1.StoreName = "My Store 1";
newStore1.City = "My City 1";
newStore1.PlannedSales = 10;
newStore1.RealizedSales = 5;
newStore1.SalesDate = new DateTime(2012, 01, 12, 12, 30, 54, DateTimeKind.Unspecified);
Store newStore2 = new Store();
newStore2.StoreName = "My Store 2";
newStore2.City = "My City 2";
newStore2.PlannedSales = 200000;
newStore2.RealizedSales = 250000;
newStore2.SalesDate = new DateTime(2012, 04, 12, 12, 30, 54, DateTimeKind.Unspecified);
Store newStore3 = new Store();
newStore3.StoreName = "My Store 3";
newStore3.City = "My City 3";
newStore3.PlannedSales = 100000;
newStore3.RealizedSales = 10000;
newStore3.SalesDate = new DateTime(2012, 05, 12, 12, 30, 54, DateTimeKind.Unspecified);
Store newStore4 = new Store();
newStore4.StoreName = "My Store 1";
newStore4.City = "My City 1";
newStore4.PlannedSales = 20;
newStore4.RealizedSales = 10;
newStore4.SalesDate = new DateTime(2012, 02, 12, 12, 30, 54, DateTimeKind.Unspecified);
Store newStore5 = new Store();
newStore5.StoreName = "My Store 1";
newStore5.City = "My City 1";
newStore5.PlannedSales = 30;
newStore5.RealizedSales = 20;
newStore5.SalesDate = new DateTime(2012, 03, 12, 12, 30, 54, DateTimeKind.Unspecified);
stores.Add(newStore1);
stores.Add(newStore2);
stores.Add(newStore3);
stores.Add(newStore4);
stores.Add(newStore5);
}
private void btnQuery_Click(object sender, EventArgs e)
{
var query1 = stores.GroupBy(x => new
{
x.City,
x.StoreName,
x.SalesDate.Year,
x.SalesDate.Month
}).Select(group => new
{
Planned = group.Sum(x => x.PlannedSales),
Realised = group.Sum(x => x.RealizedSales),
Count = group.Count(),
City = group.Key.City,
StoreName = group.Key.StoreName,
Year = group.Key.Year,
Month = group.Key.Month
}).OrderBy(x => x.Year).ThenBy(x => x.Month).Where(x => x.StoreName.Equals("My Store 1"));
List<Store> total = new List<Store>();
foreach (var value in query1)
{
Store newStore = new Store()
{
MonthYear = value.Month.ToString() + " - " + value.Year.ToString(),
RealizedSales = value.Realised,
PlannedSales = value.Planned
};
total.Add(newStore);
};
var query2 = total.Select((s, i) => new
{
MonthYear = s.MonthYear,
RealizedSales = s.RealizedSales + total.Take(i).Sum(sa => sa.RealizedSales),
PlannedSales = s.PlannedSales + total.Take(i).Sum(sa => sa.PlannedSales)
});
List<Store> totalFinal = new List<Store>();
foreach (var value in query2)
{
Store newStore = new Store()
{
MonthYear = value.MonthYear,
RealizedSales = value.RealizedSales,
PlannedSales = value.PlannedSales
};
totalFinal.Add(newStore);
};
dataGridView1.DataSource = totalFinal;
}
}
public class Store
{
public string StoreName { get; set; }
public string City { get; set; }
public int PlannedSales { get; set; }
public int RealizedSales { get; set; }
public DateTime SalesDate { get; set; }
public string MonthYear { get; set; }
}
}
When the form is instantiated, the method CreateItems is called. This method will populate a List with some demo Store data.
When the button from the form is pressed, than the List stores is queried with Linq in a way that will return all the PlannedSales and RealizedSales per MonthYear from my List stores WHERE the StoreName = My Store 1
An example of the query result is here: http://i49.tinypic.com/vz1c6.jpg
Any idea how to optimize this query to make it more simpler but get the same result?
Basically I need to return all planned and realized sales per month-year for a specific store name only!
Thanks!
This should be as easy as:
var totalPlanned = 0;
var totalRealized = 0;
var result = stores.Where(s => s.StoreName.Equals("My Store 1"))
.Select(s => {
totalPlanned += s.PlannedSales;
totalRealized += s.RealizedSales;
return new Store(){
MonthYear = s.SalesDate.ToString("MM - yyyy"),
PlannedSales = totalPlanned,
RealizedSales = totalRealized
};
});
Live example showing this new code alongside your original to show same result: http://rextester.com/PAF27531
from s in stores
where s.StoreName == "My Store 1"
group s by new { s.StoreName, s.SalesDate.Year, s.SalesDate.Month } into g
select new
{
g.Key.StoreName,
MonthYear = g.Key.Year.ToString() + " - " + g.Key.Month.ToString(),
Planned = g.Sum(st => st.PlannedSales),
Realized = g.Sum(st => st.RealizedSales)
}
Related
I'm making a journal application for myself in c# where i can make journals with dates attached to it.
I'm using a foreach statement to let the data display in the textboxes. I can't figure out how to display the journals in order (old->new) with the dates in Textbox3 (t3). I live in Europe so It's DD/MM/YYYY. I hope it's clear, thanks.
string[] journalfolder = Directory.GetDirectories(#"D:\panel\Journal\", "*");
foreach (string file in journalfolder)
{
Color grey = new Color();
TextBox t1 = new TextBox();
t1.Name = "t1_" + (t1.Controls.Count + 1);
t1.Location = new Point(265, 20);
grey = Color.FromArgb(31, 31, 31);
t1.Width = 332;
t1.BackColor = grey;
t1.BorderStyle = BorderStyle.None;
t1.ForeColor = Color.White;
try
{
string[] lines = File.ReadAllLines(file + #"\text.txt");
t1.Text = lines[0];
}
catch { }
TextBox t2 = new TextBox();
t2.Name = "t2_" + (t2.Controls.Count + 1);
t2.Location = new Point(265, 39);
t2.Width = 332;
t2.Height = 155;
grey = Color.FromArgb(31,31,31);
t2.BackColor = grey;
t2.Multiline = true;
t2.BorderStyle = BorderStyle.None;
t2.ForeColor = Color.White;
try
{
using (var sr = new StreamReader(file + #"\text.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
t2.Text = line;
}
}
}
catch { }
TextBox t3 = new TextBox();
t3.Name = "t3_" + (t3.Controls.Count + 1);
t3.Location = new Point(265, 199);
grey = Color.FromArgb(31, 31, 31);
t3.Width = 332;
t3.BackColor = grey;
t3.BorderStyle = BorderStyle.None;
t3.ForeColor = Color.White;
try
{
string[] lines = File.ReadAllLines(file + #"\date.txt");
t3.Text = lines[0];
}
catch { }
Panel image = new Panel();
image.Name = "image" + (image.Controls.Count + 1);
image.Location = new Point(20, 20);
image.BackgroundImageLayout = ImageLayout.Zoom;
image.Width = 223;
image.Width = 192;
try
{
string supportedExtensions = "*.jpg,*.gif,*.png,*.bmp,*.jpe,*.jpeg,*.wmf,*.ico,*.eps,*.tif,*.tiff";
foreach (string imageFile in Directory.GetFiles(file + #"\Files", "*.*", SearchOption.AllDirectories).Where(s => supportedExtensions.Contains(Path.GetExtension(s).ToLower())))
{
Console.WriteLine(imageFile);
image.BackgroundImage = Image.FromFile(imageFile);
}
}
catch { }
Panel p = new Panel();
p.Name = "panel" + (flowLayoutPanel1.Controls.Count + 1);
p.BackColor = Color.FromArgb(49,49,49);
p.Width = 628;
p.Height = 236;
p.Controls.Add(t1);
p.Controls.Add(t2);
p.Controls.Add(t3);
p.Controls.Add(image);
flowLayoutPanel1.Controls.Add(p);
}
I'm not quite sure I understand your requirement correctly, but I'll give it a try ...
The date is managed in a date.txt file. It contains the date in the format DD/MM/YYYY, correct?
DateTime timestamp = DateTime.Parse("ValueFromFile");
It is best to put the title, text and date in a class or struct. Maybe something like this:
public class Data
{
public string Title { get; set; }
public string Text { get; set; }
public DateTime Timestamp { get; set; }
}
You should put all the elements you have read into a list or a dictionary before displaying them on the UI and processing them further. Once all the data is in this list, you can easily sort it by date using LINQ.
List<Data> values = new List<Data>();
// TODO
// Add the items
foreach (Data item in values.OrderBy((item) => item.Timestamp))
{
}
// Or
foreach (Data item in values.OrderByDescending((item) => item.Timestamp))
{
}
I need to save my list of objects to Firestore database. Below is my code:
How I Create the List of object
private async void LoadPlazaListAndSummary()
{
_plazaList = await _dc.GetPlazas();
foreach(var item in _plazaList)
{
var par = new ParameterManualTags
{
Plaza = item.Code,
Lane = item.Lane,
DateTo = System.DateTime.Now,
DateFrom = System.DateTime.Today
};
var manualCount = await _dc.GetManualAndTransactionCount(par);
var model = new Summary
{
Name = item.Name,
Lane = item.Lane,
Code = item.Code,
DateRun = System.DateTime.Now,
ManualAverage = 100.00,
ManualCount = manualCount[0],
ReadCount = 1,
TotalTransaction = manualCount[1],
Type = item.Type,
Plaza = item,
DateFrom = par.DateFrom,
DateTo = par.DateTo,
RfidAddress = item.ReaderIpAddress,
IsDedicated = item.IsDedicated ? "Dedicated" : "Mixed"
};
model.ManualAverage = Math.Round(ComputeManualPercentage(model), 2);
_summaryList.Add(model);
DgSummary.Items.Add(model);
}
}
This is my sample to save data to Firestore:
public void SetData()
{
if (_isConnected)
{
try
{
var doc = _database.Collection("MyCollection").Document("myDocument");
Dictionary<string, object> data = new Dictionary<string, object>()
{
{"FirstName", "MyFirstName"},
{"LastName", "MyLastName"},
{"PhoneNumber", "PhoneNumber"}
};
var x = doc.SetAsync(data);
Console.WriteLine("Saved");
}
catch (Exception ex)
{
Console.WriteLine($#"An error occured in saving the data: {ex.Message}");
}
}
}
Using my sample code, I can insert one at a time to Firestore but, I do not know how to save a list of objects to Firestore.
I'm using IText 7 in dotnet core to manipulate a PDF file.
Once the process has completed I'm finding myself with a 5-page PDF at 14.2MB.
When I open the generated PDF in Adobe Reader I am prompted to save when closing Reader. If i choose Yes it shrinks the pdf by 50%.
Here is the pertinent code:
// ASDLine Model
public class ASDLine
{
public long ARInvoiceHeaderKey { get; set; }
public string BillingCode { get; set; }
public string Description { get; set; }
public decimal Amount { get; set; }
public bool? MatchProfile { get; set; }
}
public AuditSummaryDocument Create()
{
// Load in the template
MemoryStream outputDoc = new MemoryStream();
// Attempt to shrink the PDF..(didn't make any difference)
var w = new PdfWriter(outputDoc);
var wb = w.IsFullCompression();
w.SetCompressionLevel(9);
w.SetSmartMode(true);
PdfDocument pdfDoc = new PdfDocument(new PdfReader("mytemplate.pdf"), w);
font = PdfFontFactory.CreateRegisteredFont("Calibri");
Document doc = new Document(pdfDoc);
PdfAcroForm pdfAcroForm = PdfAcroForm.GetAcroForm(pdfDoc, true);
var fields = pdfAcroForm.GetFormFields();
//header:
fields["generated"].SetValue($"{DateTime.Now.ToShortDateString()} {DateTime.Now.ToShortTimeString()}");
// .... lots of fields
pdfAcroForm.FlattenFields();
// Add lines
Table table = GenerateTable();
table.SetRelativePosition(0, 510, 0, 0);
doc.Add(table);
// attempt to shrink PDF
pdfDoc.SetFlushUnusedObjects(true);
pdfDoc.Close();
//outputDoc.Position = 0;
var r = new AuditSummaryDocument
{
Data = outputDoc.ToArray()
};
return r;
}
The table looks like this:
private Table GenerateTable()
{
// Example list of ASDLine
var list = new List<ASDLine>();
list.Add(new ASDLine { Amount = 20, ARInvoiceHeaderKey = 1, BillingCode = "ABC123", Description = "A billing code 1", MatchProfile = null });
list.Add(new ASDLine { Amount = 40, ARInvoiceHeaderKey = 1, BillingCode = "ABC456", Description = "A billing code 2", MatchProfile = true });
list.Add(new ASDLine { Amount = 60, ARInvoiceHeaderKey = 1, BillingCode = "ABC789", Description = "A billing code 3", MatchProfile = false });
list.Add(new ASDLine { Amount = 80, ARInvoiceHeaderKey = 1, BillingCode = "ABC987", Description = "A billing code 4", MatchProfile = true });
Table table = new Table(new UnitValue[] { new UnitValue(UnitValue.POINT, 80)
,new UnitValue(UnitValue.POINT, 370)
,new UnitValue(UnitValue.POINT, 80)
,new UnitValue(UnitValue.POINT, 80)});
table.SetWidth(new UnitValue(UnitValue.PERCENT, 102));
Style hs = new Style();
hs.SetFont(font);
hs.SetFontSize(10);
hs.SetBold();
hs.SetTextAlignment(TextAlignment.CENTER);
Style cs = new Style();
cs.SetFont(font);
cs.SetFontSize(10);
table.AddHeaderCell(new Cell().AddStyle(hs).Add(new Paragraph("Billing Code")));
table.AddHeaderCell(new Cell().AddStyle(hs).Add(new Paragraph("Description")));
table.AddHeaderCell(new Cell().AddStyle(hs).Add(new Paragraph("Amount")));
table.AddHeaderCell(new Cell().AddStyle(hs).Add(new Paragraph("Match Profile")));
list.ForEach(line =>
{
table.AddCell(new Cell().AddStyle(cs).SetTextAlignment(TextAlignment.CENTER).Add(new Paragraph(line.BillingCode)));
table.AddCell(new Cell().AddStyle(cs).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph(line.Description)));
table.AddCell(new Cell().AddStyle(cs).SetTextAlignment(TextAlignment.RIGHT).Add(new Paragraph(line.Amount.ToString("C"))));
table.AddCell(new Cell().AddStyle(cs).SetTextAlignment(TextAlignment.CENTER).Add(new Paragraph(line.MatchProfile.HasValue ? line.MatchProfile.Value ? "Yes" : "No" : "-")));
});
return table;
}
What am I doing wrong with my code that results in this PDF being twice the size it should be - and why does Adobe prompt to save changes?
enter image description here
[WebMethod]
public void AddEmployementRequest(EmployementRequest emp)
{
EmployeeSkill employeeSkill = new EmployeeSkill
{
Skill = emp.,
Description = emp.
};
EmployeeLanguage employeeLanguage = new EmployeeLanguage
{
Name = emp.,
ConversationLevel = emp.
};
EmployeeCours employeeCours = new EmployeeCours
{
Date =emp. ,
Course = emp.,
Duration = emp.,
Association = emp.,
Description = emp.
};
EmployementRequest employementRequest = new EmployementRequest
{
Name = emp.Name,
Address = emp.Address,
Surnam = emp.Surnam,
Father = emp.Father,
IDNumber = emp.IDNumber,
IDCardNumber = emp.IDNumber,
IDCity = emp.IDCity,
Birthday = emp.Birthday,
Birthplace = emp.Birthplace,
Nationality = emp.Nationality,
Religion = emp.Religion,
Phone = emp.Phone,
Cell = emp.Cell,
EmergencyAddress = emp.EmergencyAddress,
EmergencyName = emp.EmergencyName,
EmergencyPhone = emp.EmergencyPhone,
ParentedPeople = emp.ParentedPeople,
Gender = emp.Gender,
MarriageStatus = emp.MarriageStatus,
Residency = emp.Residency,
InsuranceCode = emp.InsuranceCode,
InsuranceStatus = emp.InsuranceStatus,
VehicleType = emp.VehicleType,
MilitaryServiceStatus = emp.MilitaryServiceStatus,
EducatedFrom = emp.EducatedFrom,
EducationField = emp.EducationField,
EducationGrade = emp.EducationGrade,
ExtraWorkCapability = emp.ExtraWorkCapability,
LeisureTimeHobbies = emp.LeisureTimeHobbies,
Salary = emp.Salary,
IntroducerName = emp.IntroducerName,
IntroductionMethod = emp.IntroductionMethod,
Illness = emp.Illness,
VehicleStatus = emp.VehicleStatus,
PKEmploymentRequest = Guid.NewGuid(),
};
employementRequest.EmployeeLanguages.Add(employeeLanguage);
employementRequest.EmployeeSkills.Add(employeeSkill);
employementRequest.EmployeeCourses.Add(employeeCours);
using (var db = new UKN_DBNAMEEntities())
{
db.EmployementRequests.Add(employementRequest);
db.SaveChanges();
}
}
I want to insert to all parent and child tables at once ,As you can see I can't access the properties in child tables and also there's no intellisense to show the properties unlike the parent
I think I need a Linq query but I have no idea
have you tried
[WebMethod]
public void AddEmployementRequest(EmployementRequest emp) {
emp.PKEmploymentRequest = Guid.NewGuid();
using (var db = new UKN_DBNAMEEntities()) {
db.EmployementRequests.Add(emp);
db.SaveChanges();
}
}
It may/should do, but...
Consider:
using automapper or the like;
use some query to avoid recreation of Language or Skil
i am new to travelport universal api. i receive response from api. I perform LOW FARE SEARCH and in response the fare information and the flight information return in two different list.the problem is that i don't find any relationship in these LIST's. and also WHAT IS THE BEST WAY TO DECODE THE WSDL RESPONSE. i am using WSDL below is my code
string TargetBranch = "P7004961";
string OriginApplication = "uAPI";
string Origin="DXB";
string Destination="LHR";
string Departuredate = "2014-03-25T00:00:00";
string FlightStatus = "One-way";
string url = "https://americas-uapi.copy-webservices.travelport.com/B2BGateway/connect/uAPI/AirService";
string ReturnDate = "2014-04-05T00:00:00";
string UserName = "Universal API/uAPI6035036525-8ff7f8fc", Password = "DSXSEDn3fme9d6m2DfKP5rEaW";
LowFareSearchReq req = new LowFareSearchReq();
req.TargetBranch = TargetBranch;
BillingPointOfSaleInfo biPOS = new BillingPointOfSaleInfo();
biPOS.OriginApplication = OriginApplication;
req.BillingPointOfSaleInfo = biPOS;
/////////// Origin to Destination////////////////
SearchAirLeg airLeg = new SearchAirLeg();
Airport fromAirPort = new Airport() { Code = Origin };
typeSearchLocation fromTypLoc = new typeSearchLocation() { Item = fromAirPort };
airLeg.SearchOrigin = new typeSearchLocation[1] { fromTypLoc };
Airport toAirPort = new Airport() { Code = Destination };
typeSearchLocation toTypLoc = new typeSearchLocation() { Item = toAirPort };
airLeg.SearchDestination = new typeSearchLocation[1] { toTypLoc };
typeTimeSpec origDep = new typeTimeSpec() { PreferredTime = Departuredate };
airLeg.Items = new typeTimeSpec[1] { origDep };
/////////////////// Destination to Origin ////////////////////
SearchAirLeg returnLeg = new SearchAirLeg();
Airport RetfromAirport = new Airport() { Code = Destination };
typeSearchLocation fromLocation = new typeSearchLocation() { Item = RetfromAirport };
returnLeg.SearchOrigin = new typeSearchLocation[1] { fromLocation };
Airport retToAirpot = new Airport() { Code = Origin };
typeSearchLocation tolocation = new typeSearchLocation() { Item = retToAirpot };
returnLeg.SearchDestination = new typeSearchLocation[1] { tolocation };
typeTimeSpec retdate = new typeTimeSpec() { PreferredTime = ReturnDate };
returnLeg.Items = new typeTimeSpec[1] { retdate };
///////// checking for one way or return//////////////////////////
if (FlightStatus == "One-way")
{
req.Items = new object[] { airLeg };
}
else
{
req.Items = new object[] { airLeg, returnLeg };
}
AirSearchModifiers AirsearchModifier = new AirSearchModifiers()
{
DistanceType = typeDistance.KM,
IncludeFlightDetails = true,
PreferNonStop = true,
MaxSolutions = "300",
PreferredProviders= new Provider[1]{ new Provider(){ Code="1G"}}
};
req.AirSearchModifiers = AirsearchModifier;
SearchPassenger pass1 = new SearchPassenger() { Code = "ADT" };
req.SearchPassenger = new SearchPassenger[] { pass1 };
string Currency = "PKR";
AirPricingModifiers AirPriceMode = new AirPricingModifiers() { CurrencyType = Currency, };
req.AirPricingModifiers = AirPriceMode;
LowFareSearchRsp response = new LowFareSearchRsp();
AirLowFareSearchBinding binding = new AirLowFareSearchBinding();
binding.Url = url;
binding.Credentials = new NetworkCredential(UserName, Password);
response = binding.service(req);
Thanks to all.Finally i found result which is below quit easy in fact In the LowFareSearch response you get back among other info a list of AirSegments and a list of AirPricingSolutions. Each AirPricingSolution contains AirPricingInfo with the applicable SegmentRef keys and BookingCode info. Each SegmentRef key corresponds to a flight in the AirSegment list. This is how you know which flights (AirSegments) correspond to a specific price (AirPricingSolution).