EPPlus ColumnStacked chart data point colors - asp.net

I am able to generate Column Stacked chart using EPPlus. There is is requirement to change the color of datapoint.
I found the solution of at enter link description here but it only changes the color of first datapoint of the series. Can I get help to change the color of other datapoints as well. Here is the concept that I am looking for enter image description here
Here is the function that helps to change datapoint first color
public void SetDataPointStyle(OfficeOpenXml.Drawing.Chart.ExcelChart chart, ExcelChartSerie series, int totalDataPoint, Color color)
{
var i = 0;
var found = false;
foreach (var s in chart.Series)
{
if (s == series)
{
found = true;
break;
}
++i;
}
if (!found) throw new InvalidOperationException("series not found.");
var nsm = chart.WorkSheet.Drawings.NameSpaceManager;
var nschart = nsm.LookupNamespace("c");
var nsa = nsm.LookupNamespace("a");
var node = chart.ChartXml.SelectSingleNode(#"c:chartSpace/c:chart/c:plotArea/c:barChart/c:ser[c:idx[#val='" + i.ToString(System.Globalization.CultureInfo.InvariantCulture) + "']]", nsm);
var doc = chart.ChartXml;
var spPr = doc.CreateElement("c:spPr", nschart);
var solidFill = spPr.AppendChild(doc.CreateElement("a:solidFill", nsa));
var srgbClr = solidFill.AppendChild(doc.CreateElement("a:srgbClr", nsa));
var valattrib = srgbClr.Attributes.Append(doc.CreateAttribute("val"));
valattrib.Value = ToHex(color).Substring(1);
//var ln = spPr.AppendChild(doc.CreateElement("a:ln", nsa));
//var lnSolidFill = ln.AppendChild(doc.CreateElement("a:solidFill", nsa));
//var lnSrgbClr = lnSolidFill.AppendChild(doc.CreateElement("a:srgbClr", nsa));
//var lnValattrib = lnSrgbClr.Attributes.Append(doc.CreateAttribute("val"));
//lnValattrib.Value = ToHex(Color.Gray).Substring(1);
node.AppendChild(spPr);
}
public String ToHex(Color c)
{
return "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
}
SetDataPointStyle(chart, chart.Series[0], 1, Color.Tan);

You have to populate a series of data point colors per series. Here is an extension method that will set the series data points to random colors. Just have to specify the serie number. If pick your own colors just override the logic or send in an array to use:
public static void SetChartPointRandomColors(this ExcelChart chart, int serieNumber)
{
var chartXml = chart.ChartXml;
var nsa = chart.WorkSheet.Drawings.NameSpaceManager.LookupNamespace("a");
var nsuri = chartXml.DocumentElement.NamespaceURI;
var nsm = new XmlNamespaceManager(chartXml.NameTable);
nsm.AddNamespace("a", nsa);
nsm.AddNamespace("c", nsuri);
var serieNode = chart.ChartXml.SelectSingleNode(#"c:chartSpace/c:chart/c:plotArea/c:barChart/c:ser[c:idx[#val='" + serieNumber + "']]", nsm);
var serie = chart.Series[serieNumber];
var points = serie.Series.Length;
var rand = new Random(serieNumber);
for (var i = 1; i <= points; i++)
{
var dPt = chartXml.CreateNode(XmlNodeType.Element, "dPt", nsuri);
var idx = chartXml.CreateNode(XmlNodeType.Element, "idx", nsuri);
var att = chartXml.CreateAttribute("val", nsuri);
att.Value = i.ToString();
idx.Attributes.Append(att);
dPt.AppendChild(idx);
var srgbClr = chartXml.CreateNode(XmlNodeType.Element, "srgbClr", nsa);
att = chartXml.CreateAttribute("val");
//Generate a random color - override with own logic to specify
var color = Color.FromArgb(rand.Next(256), rand.Next(256), rand.Next(256));
att.Value = $"{color.R:X2}{color.G:X2}{color.B:X2}";
srgbClr.Attributes.Append(att);
var solidFill = chartXml.CreateNode(XmlNodeType.Element, "solidFill", nsa);
solidFill.AppendChild(srgbClr);
var spPr = chartXml.CreateNode(XmlNodeType.Element, "spPr", nsuri);
spPr.AppendChild(solidFill);
dPt.AppendChild(spPr);
serieNode.AppendChild(dPt);
}
}
Here is an example of usage:
[TestMethod]
public void Chart_BarChart_Colors_Test()
{
//Throw in some data
var datatable = new DataTable("tblData");
datatable.Columns.AddRange(new[]{new DataColumn("Col1", typeof(int)),new DataColumn("Col2", typeof(int)),new DataColumn("Col3", typeof(int))});
for (var i = 0; i < 10; i++){var row = datatable.NewRow();row[0] = i;row[1] = i * 10;row[2] = i * 15;datatable.Rows.Add(row);}
//Create a test file
var fileInfo = new FileInfo(#"c:\temp\Chart_BarChart_Colors.xlsx");
if (fileInfo.Exists)
fileInfo.Delete();
using (var pck = new ExcelPackage(fileInfo))
{
var workbook = pck.Workbook;
var worksheet = workbook.Worksheets.Add("Sheet1");
worksheet.Cells.LoadFromDataTable(datatable, true);
var chart = worksheet.Drawings.AddChart("chart test", eChartType.ColumnStacked);
chart.Series.Add(worksheet.Cells["B2:B11"], worksheet.Cells["A2:A11"]);
chart.Series.Add(worksheet.Cells["C2:C11"], worksheet.Cells["A2:A11"]);
chart.SetChartPointRandomColors(0);
chart.SetChartPointRandomColors(1);
pck.Save();
}
}
Will give you this:

I had a similar use case, I needed to set the color of a slice (datapoint) of a doughnut chart. This question/answer helped immensely and I figured I would share the result in case anyone else hits this issue.
Note 1: I am using C# 9 with nullability enabled; you can remove the !'s if you aren't using nullability.
Note 2: I have no use case for multiple series in a doughnut chart, so this is hardcoded to series 0. You can parameterize the SelectSingleNode index if this doesn't work for you.
public void SetDoughnutChartDataPointFill(ExcelChart chart, int dataPointIdx, Color color)
{
var nsm = chart.WorkSheet.Drawings.NameSpaceManager;
var nschart = nsm.LookupNamespace("c");
var nsa = nsm.LookupNamespace("a");
var node = chart.ChartXml.SelectSingleNode(#"c:chartSpace/c:chart/c:plotArea/c:doughnutChart/c:ser[c:idx[#val='0']]", nsm)!;
var doc = chart.ChartXml;
var dPt = doc.CreateElement("c:dPt", nschart);
var cdpIdx = doc.CreateElement("c:idx", nschart);
var valattr = cdpIdx.Attributes!.Append(doc.CreateAttribute("val"));
valattr.Value = dataPointIdx.ToString();
dPt.AppendChild(cdpIdx);
var spPr = doc.CreateElement("c:spPr", nschart);
var solidFill = spPr.AppendChild(doc.CreateElement("a:solidFill", nsa))!;
var srgbClr = solidFill.AppendChild(doc.CreateElement("a:srgbClr", nsa))!;
var valattrib = srgbClr.Attributes!.Append(doc.CreateAttribute("val"));
valattrib.Value = string.Format("{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);
dPt.AppendChild(spPr);
node.AppendChild(dPt);
}

Related

First page is blackened after adding watermark

Page is blackened after adding watermark in case of some pdf files . Please see attached image.
What could be the reason , and possible fix.
see the blacked out page image
It does not happen for all the files but for some files only.
Code is here in dotnetfiddle.
var _pdfInBytes = File.ReadAllBytes("c:\\test\\test123.pdf");
string watermarkText = "This watermark text on left side";
var coordinates = new Point(25, 200);
using (var pdfNewDoc = new PdfDocument())
{
using (var pdfImport = PdfReader.Open(new MemoryStream(_pdfInBytes, true), PdfDocumentOpenMode.Import))
{
if (pdfImport.PageCount == 0)
{
return;
}
foreach (var pg in pdfImport.Pages)
{
pdfNewDoc.AddPage(pg);
}
var page = pdfNewDoc.Pages[0];
// overlapping trick #165910
var xOffset = 100.0;
for (var index = 0; index < page.Contents.Elements.Count; index++)
{
var stream = page.Contents.Elements.GetDictionary(index).Stream;
var x = GetMinXOffsetDraft(stream.ToString());
if (xOffset > x)
{
xOffset = x;
}
}
xOffset *= 0.6; // magic number :)
// blank page trick #165910
if (page.CropBox.IsEmpty && !page.MediaBox.IsEmpty)
{
page.CropBox = page.MediaBox;
}
// Get an XGraphics object for drawing beneath the existing content
var gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);
var tf = new XTextFormatter(gfx);
var xFont = new XFont("Arial", 10, XFontStyle.Regular);
// Get watermark text size
var wmSize = gfx.MeasureString(watermarkText, xFont);
// Middle Y coordinate
var wmY = (gfx.PageSize.Height - wmSize.Width) / 2;
var coords = new XPoint(page.CropBox.Location.X + (xOffset < coordinates.X ? xOffset : coordinates.X),
page.CropBox.Location.Y + (coordinates.Y > wmY ? coordinates.Y : wmY));
// Define a rotation transformation at the center of the page
gfx.TranslateTransform(coordinates.X, coordinates.Y);
gfx.RotateTransform(90);
gfx.TranslateTransform(-coordinates.X, -coordinates.Y);
// Create brush
var brushColor = Color.Red;
var brush1= new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
brush1.Overprint = false;
XBrush brush =
new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
var rect = new XRect(coordinates.X, coordinates.Y, gfx.PageSize.Height - coordinates.Y,
coordinates.X);
tf.DrawString(watermarkText, xFont, brush, rect);
byte[] outputBytes = null;
using (var outStream = new MemoryStream())
{
pdfNewDoc.Save(outStream, false);
outputBytes = outStream.ToArray();
}
File.WriteAllBytes("c:\\test\\test-"+DateTime.Now.ToString("ddmmyyyyhhmmss") +".pdf", outputBytes);
private double GetMinXOffsetDraft(string v)
{
var result = 100.0;
using (var str = new StringReader(v))
{
var s = str.ReadLine();
do
{
var sarr = s?.Split(' ');
if (sarr?.Length == 7 && sarr[6] == "Tm")
{
var x = double.Parse(sarr[4]);
x = x < 0 ? 200 : x;
result = result > x ? x : result;
}
s = str.ReadLine();
} while (s != null);
}
return result;
} var _pdfInBytes = File.ReadAllBytes("c:\\test\\test123.pdf");
string watermarkText = "This watermark text on left side";
var coordinates = new Point(25, 200);
using (var pdfNewDoc = new PdfDocument())
{
using (var pdfImport = PdfReader.Open(new MemoryStream(_pdfInBytes, true), PdfDocumentOpenMode.Import))
{
if (pdfImport.PageCount == 0)
{
return;
}
foreach (var pg in pdfImport.Pages)
{
pdfNewDoc.AddPage(pg);
}
var page = pdfNewDoc.Pages[0];
// overlapping trick #165910
var xOffset = 100.0;
for (var index = 0; index < page.Contents.Elements.Count; index++)
{
var stream = page.Contents.Elements.GetDictionary(index).Stream;
var x = GetMinXOffsetDraft(stream.ToString());
if (xOffset > x)
{
xOffset = x;
}
}
xOffset *= 0.6; // magic number :)
// blank page trick #165910
if (page.CropBox.IsEmpty && !page.MediaBox.IsEmpty)
{
page.CropBox = page.MediaBox;
}
// Get an XGraphics object for drawing beneath the existing content
var gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);
var tf = new XTextFormatter(gfx);
var xFont = new XFont("Arial", 10, XFontStyle.Regular);
// Get watermark text size
var wmSize = gfx.MeasureString(watermarkText, xFont);
// Middle Y coordinate
var wmY = (gfx.PageSize.Height - wmSize.Width) / 2;
var coords = new XPoint(page.CropBox.Location.X + (xOffset < coordinates.X ? xOffset : coordinates.X),
page.CropBox.Location.Y + (coordinates.Y > wmY ? coordinates.Y : wmY));
// Define a rotation transformation at the center of the page
gfx.TranslateTransform(coordinates.X, coordinates.Y);
gfx.RotateTransform(90);
gfx.TranslateTransform(-coordinates.X, -coordinates.Y);
// Create brush
var brushColor = Color.Red;
var brush1= new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
brush1.Overprint = false;
XBrush brush =
new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
var rect = new XRect(coordinates.X, coordinates.Y, gfx.PageSize.Height - coordinates.Y,
coordinates.X);
tf.DrawString(watermarkText, xFont, brush, rect);
byte[] outputBytes = null;
using (var outStream = new MemoryStream())
{
pdfNewDoc.Save(outStream, false);
outputBytes = outStream.ToArray();
}
File.WriteAllBytes("c:\\test\\test-"+DateTime.Now.ToString("ddmmyyyyhhmmss") +".pdf", outputBytes);
private double GetMinXOffsetDraft(string v)
{
var result = 100.0;
using (var str = new StringReader(v))
{
var s = str.ReadLine();
do
{
var sarr = s?.Split(' ');
if (sarr?.Length == 7 && sarr[6] == "Tm")
{
var x = double.Parse(sarr[4]);
x = x < 0 ? 200 : x;
result = result > x ? x : result;
}
s = str.ReadLine();
} while (s != null);
}
return result;
}

Wordpress Woocommerce - Send order data to GoogleSheets via Webhooks

So I wrote this code and it is not working as it should, it is pulling data from woocommerce Webhook with a "code.gs" code in GoogleSheets.
Problem is, if var product_name = myData.line_items[1].name; (and [2], [3] and [4].... and others) does not exist, the code does not work in GoogleSheets...
What i would like to achieve is, when i have two products in an order (myData.line_items[1].name exists, myData.line_items[2].name exists,...) that GoogleSheets would make a new line with that data for each one of the products.
function doGet(e) {
return HtmlService.createHtmlOutput("request received");
}
function doPost(e) {
var myData = JSON.parse([e.postData.contents]);
var order_number = myData.number;
var order_created = myData.date_created;
var product_name = myData.line_items[0].name;
var product_qty = myData.line_items[0].quantity;
var product_total = myData.line_items[0].total;
var produktsku = myData.line_items[0].sku;
var product_name = myData.line_items[1].name;
var product_qty = myData.line_items[1].quantity;
var product_total = myData.line_items[1].total;
var produktsku = myData.line_items[1].sku;
var product_namea = myData.line_items[2].name;
var product_qtya = myData.line_items[2].quantity;
var product_totala = myData.line_items[2].total;
var produktskua = myData.line_items[2].sku;
var product_nameb = myData.line_items[3].name;
var product_qtyb = myData.line_items[3].quantity;
var product_totalb = myData.line_items[3].total;
var produktskub = myData.line_items[3].sku;
var product_namec = myData.line_items[4].name;
var product_qtyc = myData.line_items[4].quantity;
var product_totalc = myData.line_items[4].total;
var produktskuc = myData.line_items[4].sku;
var product_named = myData.line_items[5].name;
var product_qtyd = myData.line_items[5].quantity;
var product_totald = myData.line_items[5].total;
var produktskud = myData.line_items[5].sku;
var order_total = myData.total;
var billing_email = myData.billing.email;
var billing_first_name = myData.billing.first_name;
var billing_last_name = myData.billing.last_name;
var billing_countryshort = myData.billing.country;
var payment_method = myData.payment_method_title;
var shipping_method = myData.shipping_lines[0].method_title;
var shipping_total = myData.shipping_lines[0].total;
var shipping_total = myData.shipping_lines[0].total;
var klingi = "1";
var timestamp = new Date();
var sheet = SpreadsheetApp.getActiveSheet();
sheet.appendRow([timestamp,order_created,order_number,product_name,produktsku,product_qty,product_total,order_total,billing_email,billing_first_name,billing_last_name,payment_method,shipping_method,shipping_total,billing_countryshort]);
if( produktskua ) {
sheet.appendRow(["Izdelek 2", "",order_number,product_namea,produktskua,product_qtya,product_totala]);
};
if( produktskub ) {
sheet.appendRow(["Izdelek 3", "",order_number,product_nameb,produktskub,product_qtyb,product_totalb]);
};
if( produktskuc ) {
sheet.appendRow(["Izdelek 4", "",order_number,product_namec,produktskuc,product_qtyc,product_totalc]);
};
}
Any ideas?
It stops working, even if I wrap it, it works only if value exists...
if( myData.line_items[1].name ) {
var product_namea = myData.line_items[1].name;
var product_qtya = myData.line_items[1].quantity;
var product_totala = myData.line_items[1].total;
var produktskua = myData.line_items[1].sku;
};
When assigning your post data to variables, you can use the ternary operator
This allows you to verify either a certain postData exists, and if not - assign an empty string to the variable in order to prevent problems with Google Sheets.
Syntax:
condition ? exprIfTrue : exprIfFalse
Sample:
var product_namea = (myData.line_items[2].name) ? myData.line_items[2].name : " ";
Also: Be careful with overwriting variable names, in your code you
have e.g. twice var product_name
Is solved like this:
function doPost(e) {
var myData = JSON.parse([e.postData.contents]);
var timestamp = new Date();
var order_created = myData.date_created;
var billing_first_name = myData.billing.first_name;
var billing_phone = myData.billing.phone;
var billing_email = myData.billing.email;
var shipping_address = myData.billing.address_1 + myData.billing.address_2;
var order_total = myData.total;
var order_number = myData.number;
var billing_last_name = myData.billing.last_name;
var billing_countryshort = myData.billing.country;
var payment_method = myData.payment_method_title;
var shipping_method = myData.shipping_lines[0].method_title;
var shipping_total = myData.shipping_lines[0].total;
var quantity_prvi = myData.line_items[0].quantity;
var linetotal_prvi = myData.line_items[0].total;
var produktsku_prvi = myData.line_items[0].sku;
var sheet = SpreadsheetApp.getActiveSheet();
sheet.appendRow([billing_countryshort,timestamp,order_created,"Order",order_number,billing_first_name,billing_last_name,shipping_address,billing_email,billing_phone,produktsku_prvi,quantity_prvi,linetotal_prvi,shipping_total,shipping_method,order_total,payment_method]);
var lineitems=""
for (i in myData.line_items)
if(i>0){
{
var quantity = myData.line_items[i].quantity;
var linetotal = myData.line_items[i].total;
var produktsku = myData.line_items[i].sku;
var sheet = SpreadsheetApp.getActiveSheet();
sheet.appendRow([billing_countryshort,timestamp,order_created,"Dodaten produkt",order_number,"","","","","",produktsku,quantity,linetotal]);
}
}
}

Trouble integrating Woocommerce order details into Google Sheet with Google App Script API

I have an API that automatically pulls new order details from my Woocommerce store into a Google Sheet. It seems to be working however, it has failed to pull the first 7 orders into my google sheet. It has all of the orders after the first 7. How do I get it to pull the first 7 orders into the sheet?
Here is my Google App Script:
function start_sync() {
// Followed instructions at https://github.com/mithunmanohar/woocommerce-orders-google-sheets-integration
var sheet_name = "OrderDetails"
update_order_5_min(sheet_name)
}
function update_order_5_min(sheet_name) {
var ck = "ck_ed82fae51e5bafce28dde95224db9c9c4bd36dba";
var cs = "cs_9a16fd7b641769a65412f336de3e7a928f7e153c";
var website = "https://www.funtrackdayz.com";
var now = new Date();
var website_t ="240";
var min = website_t * 60
now.setMinutes(now.getMinutes() - min);
var n = now.toISOString();
var surl = website + "/wc-api/v3/orders?consumer_key=" + ck + "&consumer_secret=" + cs + "&status=processing&filter[created_at_min]=" + n //"&after=2016-10-27T10:10:10Z"
// var surl = website + "/wc-api/v3/orders?consumer_key=" + ck + "&consumer_secret=" + cs + "&status=processing"
// &filter[created_at_min]=" + n //"&after=2016-10-27T10:10:10Z"
var url = surl
var options = {
"method": "GET",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"muteHttpExceptions": true,
};
var result = UrlFetchApp.fetch(url, options);
if (result.getResponseCode() == 200) {
var params = JSON.parse(result.getContentText());
}
var doc = SpreadsheetApp.getActiveSpreadsheet();
var temp = doc.getSheetByName(sheet_name);
var consumption = {}
//"orders"
arrayLength = params["orders"].length
for (var i = 0; i < arrayLength; i++) {
var container = [];
a = container.push(params["orders"][i]["billing_address"]["first_name"]);
a = container.push(params["orders"][i]["billing_address"]["last_name"]);
a = container.push(params["orders"][i]["billing_address"]["address_1"] + ", " + params["orders"][i]["billing_address"]["address_2"]);
a = container.push("");
a = container.push(params["orders"][i]["billing_address"]["city"]);
a = container.push(params["orders"][i]["billing_address"]["state"]);
a = container.push(params["orders"][i]["billing_address"]["postcode"]);
a = container.push(params["orders"][i]["billing_address"]["phone"]);
a = container.push(params["orders"][i]["billing_address"]["email"]);
a = container.push(params["orders"][i]["total"]); //price
a = container.push(params["orders"][i]["payment_details"]["method_id"]);
c = params["orders"][i]["line_items"].length;
items = "";
skus="";
for (var k = 0; k < c; k++) {
item = params["orders"][i]["line_items"][k]["name"];
qty = params["orders"][i]["line_items"][k]["quantity"];
sku = params["orders"][i]["line_items"][k]["sku"];
meta = ""
try {
meta = params["orders"][i]["line_items"][k]["meta"][0]["value"];
meta = " - " + meta
} catch (err) {
meta = ""
}
item_f = qty + " x " + item + meta
items = items + item_f + ",\n"
skus = skus + ",\n"
}
a = container.push(items)
a = container.push(sku)
// a = container.push(params["orders"][i]["total_line_items_quantity"]); // Quantity
a = container.push(params["orders"][i]["order_number"]); //
a = container.push(params["orders"][i]["note"])
a = container.push(params["orders"][i]["created_at"]);
var doc = SpreadsheetApp.getActiveSpreadsheet();
var temp = doc.getSheetByName(sheet_name);
temp.appendRow(container);
removeDuplicates(sheet_name)
}
}
function removeDuplicates(sheet_name) {
var doc = SpreadsheetApp.getActiveSpreadsheet();
var sheet = doc.getSheetByName(sheet_name);
var data = sheet.getDataRange().getValues();
var newData = new Array();
for (i in data) {
var row = data[i];
var duplicate = false;
for (j in newData) {
if (row.join() == newData[j].join()) {
duplicate = true;
}
}
if (!duplicate) {
newData.push(row);
}
}
sheet.clearContents();
sheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
}

ASP.Net - Conditions within a public class

I have this public class below and I want to include a condition which placed it inside and it doesn't work. Any suggestions?
public SummaryDates GetSummaryDates()
{
SummaryDates result = new SummaryDates();
var getDay = 3;
DateTime now = DateTime.UtcNow.Date;
var getMonth = 0;
var getQuarter = 0;
var quarterNow = now.AddMonths(3 * getQuarter);
var quarterNumber = Math.Ceiling(quarterNow.Month / 3m);
var quarterLabel2 = 0;
var quarterLabel1 = 0;
var quarterLabelA = 0;
var quarterLabelB = 0;
result.summaryDates = new SummaryDates
{
startOfQuarter2 = now,
endOfQuarter2 = now,
endOfQuarter2Plus1Day = now,
endOfQuarter1Plus1Day = now,
startOfQuarter1 = now,
endOfQuarter1 = now,
startOfQuarterA = now,
startOfQuarterB = now,
endOfQuarterA = now,
endOfQuarterB = now,
endOfQuarterAPlus1Day = now,
endOfQuarterBPlus1Day = now,
if (quarterNumber == 4)
{
startOfQuarter2 = new DateTime(getSummaryDates.quarter2Year, 10, 01);
endOfQuarter2 = new DateTime(getSummaryDates.quarter2Year, 12, 31);
endOfQuarter2Plus1Day = getSummaryDates.endOfQuarter2.AddDays(1);
quarterLabel2 = Convert.ToInt16(Math.Ceiling(getSummaryDates.endOfQuarter2.Month / 3m));
}
return result;
}
}
I've placed the conditions inside. It doesn't work.

d3 putting multi pie chart on map

I want to put multi pie chart on d3 map but I'm confused how to do it.
I'm noob at d3 so I searched about the issue and made below code.
Someone suggested that I should make two seperate svgs so I did it.
There are two svgs. one has a map, and the other has multiple pie chart.
Now I have a problem with mapping these pies on map.
I don't know how to map these pies with geo coordinates...
It's just browser(?) coordinates so I want to change it.
and I want to zoom and pan map correctly with pies...
hope your help...
summary
I have two problems
putting multiple pie charts on right map place
zoom and pan correctly
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v0.min.js"></script>
<script>
var width = 960, height = 500;
var projection = d3.geo.mercator().center([ 127.46, 36.00 ])
.scale(4000).translate([ width / 2, height / 2 ]);
var color = d3.scale.category20();
//first svg
var svg = d3.select("body").append("svg").attr("width", width).attr(
"height", height);
var path = d3.geo.path().projection(projection);
var radius = 30;
var arc = d3.svg.arc().innerRadius(radius - 100).outerRadius(
radius - 20);
var g = svg.append("g");
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "/tourdata.txt", false);
var allText;
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
allText = rawFile.responseText;
}
}
}
rawFile.send(null);
var lines = allText.split('\n');
var timeTable = new Array();
var res = lines[0].split(", ");
var currentTime = res[1];
var currentDate = res[0];
var timeInformation = new Array();
var corInformation = new Array();
var timeCorTable = new Array();
for ( var i = 0; i < lines.length; i++) {
var res = lines[i].split(", ");
if (currentDate != res[0] || currentTime != res[1]) {
currentDate = res[0];
currentTime = res[1];
timeTable[currentDate + ":" + currentTime] = timeInformation;
timeCorTable[currentDate + ":" + currentTime] = timeCorTable;
timeInformation = new Array();
corInformation = new Array();
}
if (timeInformation[res[2] + "," + res[3]] == undefined) {
corInformation.push(res[2] + "," + res[3]);
timeInformation.push([ res[4], res[5], res[6], res[7], res[8],
res[9], res[10], res[11], res[12], res[13] ]);
}
}
timeTable.push(timeInformation);
timeCorTable.push(corInformation);
var data = timeTable;
console.log(timeCorTable[0]);
// load and display the World
d3.json("kor.json",
function(error, topology) {
// load and display the cities
var geo = topojson.object(topology,
topology.objects['kor.geo']).geometries;
g.selectAll('path').data(geo).enter().append('path').attr(
'd', path)
});
console.log(data[0]);
//second svg that has multiple pies
var svgSvg = d3.select("body").select("svg").selectAll("g").data(timeTable[0]).enter().append("svg:svg").attr(
"width", width).attr("height", height).append("svg:g").style(//svg:g make pie group
"opacity", 0.8).attr("transform", function(d, i) {
var split = timeCorTable[0][i].split(",");
//console.log(split[0]);
var point = [split[0], split[1]];
console.log(projection(point[0], point[1])[0]);
return ("translate(" + projection(point[0], point[1])[0] + "," + projection(point[0], point[1])[1] + ")");
});
svgSvg.selectAll("path").data(d3.layout.pie()).enter().append(
"svg:path").attr("d",
d3.svg.arc().innerRadius(10).outerRadius(30)).style("fill", function(d, i) { return color(i); });
// zoom and pan
var zoom = d3.behavior.zoom().on(
"zoom",
function() {
g.attr("transform", "translate("
+ d3.event.translate.join(",") + ")scale("
+ d3.event.scale + ")");
g.selectAll("path").attr("d", path.projection(projection));
svgSvg.attr("transform", "translate("
+ d3.event.translate.join(",") + ")scale("
+ d3.event.scale + ")");
});
svg.call(zoom)
</script>

Resources