Share point 2010 ItemAdding insert Recurrence data on calendar - sharepoint

i am trying to add some Recurrence data on a calendar by using ItemAdding events. My code is as follows :
public override void ItemAdding(SPItemEventProperties properties)
{
string evtTitle = Console.ReadLine();
SPListCollection listCollectioon = properties.List.ParentWeb.Lists;
SPList list = listCollectioon.TryGetList("Calendar");
SPListItemCollection listItems = list.Items;
SPListItem recEvent = listItems.Add();
string recData = "<recurrence><rule>" +
"<firstDayOfWeek>su</firstDayOfWeek>" +
"<repeat><daily dayFrequency='1' /></repeat>" +
"<repeatInstances>1</repeatInstances></rule></recurrence>";
recEvent["Title"] = evtTitle;
recEvent["RecurrenceData"] = recData;
recEvent["EventType"] = 1;
recEvent["EventDate"] = new DateTime(2012, 3, 1, 8, 0, 0);
recEvent["EndDate"] = new DateTime(2012, 3, 12, 9, 0, 0);
recEvent["UID"] = System.Guid.NewGuid();
recEvent["TimeZone"] = 13;
recEvent["Recurrence"] = -1;
recEvent["XMLTZone"] = "<timeZoneRule>" +
"<standardBias>480</standardBias>" +
"<additionalDaylightBias>-60</additionalDaylightBias>" +
"<standardDate><transitionRule month='10' day='su' weekdayOfMonth='last' />" +
"<transitionTime>2:0:0</transitionTime></standardDate>" +
"<daylightDate><transitionRule month='4' day='su' weekdayOfMonth='first' />" +
"<transitionTime>2:0:0</transitionTime>" +
"</daylightDate></timeZoneRule>";
recEvent.Update();
listItems.Add();
base.ItemAdding(properties);
}
But problem is that it is creating 10 separate events on a same date. I am unable to get the reason of this and how i resolve this issue?

This works for me.
SPList calendar = web.Lists["Calendar"];
SPListItem recEvent = calendar.Items.Add();
//string recData = "<recurrence><rule>" +
// "<firstDayOfWeek>su</firstDayOfWeek>" +
// "<repeat><daily dayFrequency=\"1\" /></repeat>" +
// "<repeatInstances>1</repeatInstances></rule></recurrence>";
string recData = "<recurrence><rule><firstDayOfWeek>su</firstDayOfWeek><repeat><daily dayFrequency=\"1\" /></repeat><windowEnd>2012-02-26T01:00:00Z</windowEnd></rule></recurrence>";
recEvent["Title"] = "Test 1";
recEvent["RecurrenceData"] = recData;
recEvent["EventType"] = 1;
recEvent["Start Time"] = new DateTime(2012, 2, 21, 10, 0, 0);
recEvent["End Time"] = new DateTime(2012, 2, 25, 11, 0, 0);
recEvent["TimeZone"] = 10;
recEvent["Recurrence"] = true;
recEvent["XMLTZone"] = "<timeZoneRule><standardBias>300</standardBias><additionalDaylightBias>-60</additionalDaylightBias><standardDate><transitionRule month='11' day='su' weekdayOfMonth='first' /><transitionTime>2:0:0</transitionTime></standardDate><daylightDate><transitionRule month='3' day='su' weekdayOfMonth='second' /><transitionTime>2:0:0</transitionTime></daylightDate></timeZoneRule>";
recEvent.Update();
calendar.Update();
"repeatInstance" if you want to limit the recurrence events to certain number or use "windowEnd"

Related

Azure function not working properly after deployed [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a barcode function which is working great in local environment. But random requests are not working correctly after deploying the barcode to azure.
I have downloaded the demo EAN13 barcodefont and tried with below code to print the barcode.
If I request multiple request in local environment it's working correctly. After deployed to Azure when we request multiple request at a time it's returning wrong barcode randomly. For example failure cases 3 out of 10 request.
c# BarCode Function
public string GenerateBarCodeFont(string barCodeTextP, out bool isError, int widthP = 0, int heightP = 0, string fontNameP = "", int fontP = 0)
{
isError = false;
aa:
try
{
fontArray = new byte[0];
dataLength = 0;
if (widthP == 0)
widthP = 1;
if (heightP == 0)
heightP = 1;
if (fontP == 0)
fontP = 16;
fontArray = VLCEANThirtenBarCode.Properties.Resources.UPCEAN_0;
dataLength = VLCEANThirtenBarCode.Properties.Resources.UPCEAN_0.Length;
barCodeText = EAN13(barCodeTextP);
IntPtr destination = Marshal.AllocCoTaskMem(dataLength);
Marshal.Copy(fontArray, 0, destination, dataLength);
uint pcFonts = 0;
AddFontMemResourceEx(destination, (uint)fontArray.Length, IntPtr.Zero, ref pcFonts);
PrivateFontCollection fonts = new PrivateFontCollection();
fonts.AddMemoryFont(destination, dataLength);
Marshal.FreeCoTaskMem(destination);
this.ff = fonts.Families[0];
int num3 = heightP * 2;
int num5 = Convert.ToInt32((double)(Convert.ToDouble(widthP) * 1.5));
int num6 = (heightP * 100) / 90;
Font font = new Font(this.ff, (float)fontP);
PointF point = new PointF(2f, 2f);
Bitmap bitmap = new Bitmap(widthP, heightP, PixelFormat.Format24bppRgb);
bitmap.SetResolution((float)num6, (float)num6);
Graphics graphics = Graphics.FromImage(bitmap);
graphics.FillRectangle(new SolidBrush(Color.White), 0, 0, widthP, heightP);
graphics.DrawString(barCodeText, font, new SolidBrush(Color.Black), point);
using (MemoryStream stream = new MemoryStream())
{
bitmap.Save(stream, ImageFormat.Png);
byte[] inArray = stream.ToArray();
Convert.ToBase64String(inArray);
barCodeText = Convert.ToBase64String(inArray, 0, inArray.Length);
}
bitmap.Dispose();
}
catch (Exception ex)
{
if (ex.Message == "A generic error occurred in GDI+.")
goto aa;
isError = true;
return ex.Message;
}
return barCodeText;
}
EAN13 BarCodefont logic
public string EAN13(string bcP)
{
string s = "", suppl = "", TempStrL = "";
int CountryFlagL = 0;
switch (bcP.Length)
{
case 12:
case 13:
s = bcP.Substring(0, 12) + CheckDigit(SYMB_EAN13, bcP.Substring(0, 12));
break;
case 14:
case 15:
s = bcP.Substring(0, 12) + CheckDigit(SYMB_EAN13, bcP.Substring(0, 12));
suppl = AddOn(bcP.Substring(bcP.Length - 2));
break;
case 17:
case 18:
s = bcP.Substring(0, 12) + CheckDigit(SYMB_EAN13, bcP.Substring(0, 12));
suppl = AddOn(bcP.Substring(bcP.Length - 5));
break;
}
TempStrL = GetChar(digitsOnly, s.Substring(0, 1));//
TempStrL = TempStrL + "{{{{{";
TempStrL = TempStrL + "|";
CountryFlagL = Convert.ToInt32(s.Substring(0, 1));//
for (int i = 1; i <= 6; i++)
{
if (GetParity(SYMB_EAN13, i - 1, CountryFlagL) == "A")//
TempStrL = TempStrL + GetChar(charsetA, s.Substring(i, 1));//
else
TempStrL = TempStrL + GetChar(charsetB, s.Substring(i, 1));//
}
TempStrL = TempStrL + "{" + "|" + "{";
for (int i = 8; i <= 13; i++)
{
TempStrL = TempStrL + GetChar(charsetC, s.Substring(i - 1, 1));
}
TempStrL = TempStrL + "|";
if (suppl.Length > 0)
TempStrL = TempStrL + "}" + suppl;
return TempStrL;
}
protected string AddOn(string bcP)
{
string parL, ParSectionL = "", TempstrL;
int TotalL = 0, intbcL, MultiplierL, PositionL, CounterL = 0, SectLengthL;
switch (bcP.Length)
{
case 2:
parL = "AA" + "AB" + "BA" + "BB";
intbcL = Convert.ToInt32(bcP);
TotalL = intbcL % 4;
ParSectionL = parL.Substring(TotalL * 2, 2);
break;
case 5:
parL = "BBAAA" + "BABAA" + "BAABA" + "BAAAB" + "ABBAA" + "AABBA" + "AAABB" + "ABABA" + "ABAAB" + "AABAB";
for (int i = 1; i <= 5; i++)
{
MultiplierL = 3;
if (i % 2 == 0)
MultiplierL = 9;
intbcL = Convert.ToInt32(bcP.Substring(i - 1, 1));
TotalL = TotalL + MultiplierL * intbcL;
}
PositionL = (TotalL % 10) * 5;
ParSectionL = parL.Substring(PositionL, 5);
break;
}
TempstrL = "m";
SectLengthL = ParSectionL.Length;
for (int i = 1; i <= SectLengthL; i++)
{
if (ParSectionL.Substring(i - 1, 1) == "A")
TempstrL = TempstrL + GetChar(CharsetASupp, bcP.Substring(i - 1, 1));
else
TempstrL = TempstrL + GetChar(CharsetBSupp, bcP.Substring(i - 1, 1));
if (i < SectLengthL)
TempstrL = TempstrL + "n";
}
return TempstrL;
}
protected string CheckDigit(int SymbologyL, string c)
{
string s = "";
int NumDigitsL = 0, intc = 0, cd;
decimal TotalL = 0;
switch (SymbologyL)
{
case SYMB_UPCA:
NumDigitsL = 11;
break;
case SYMB_EAN13:
NumDigitsL = 12;
break;
case SYMB_EAN8:
NumDigitsL = 7;
break;
}
for (int i = 1; i <= NumDigitsL; i++)
{
if (((NumDigitsL + 1 - i) % 2) == 0)
{
string str = c.Substring(i - 1, 1);
intc = Convert.ToInt32(str);
TotalL = TotalL + 1 * intc;
}
else
{
string str = c.Substring(i - 1, 1);
intc = Convert.ToInt32(str);
TotalL = TotalL + 3 * intc;
}
}
cd = 10 - Convert.ToInt32(TotalL % 10);
if (cd == 10)
cd = 0;
return cd.ToString();
}
protected string GetChar(string c, string DigitP)
{
int intDigitL = Convert.ToInt32(DigitP);
return c.Substring(intDigitL, 1);
}
protected string GetParity(int SymbologyP, int PositionP, int CodeValP)
{
string parL = "", ParityL = "";
switch (SymbologyP)
{
case SYMB_EAN13:
parL = "AAAAAA" + "AABABB" + "AABBAB" + "AABBBA" + "ABAABB" + "ABBAAB" + "ABBBAA" + "ABABAB" + "ABABBA" + "ABBABA";
break;
case SYMB_UPCE:
parL = "BBBAAA" + "BBABAA" + "BBAABA" + "BBAAAB" + "BABBAA" + "BAABBA" + "BAAABB" + "BABABA" + "BABAAB" + "BAABAB";
break;
}
ParityL = parL.Substring(CodeValP * 6, 6);
return ParityL.Substring(PositionP, 1);
}
**Global Variables are below **
[DllImport("gdi32.dll")]
private static extern IntPtr AddFontMemResourceEx(IntPtr pbfont, uint cbfont, IntPtr pdv, [In] ref uint pcFonts);
FontFamily ff;
private string barCodeText = string.Empty;
byte[] fontArray;
int dataLength;
const int SYMB_UPCA = 1, SYMB_EAN13 = 3, SYMB_EAN8 = 4, SYMB_UPCE = 2;
string CharsetASupp = "+,./:;=?#K", CharsetBSupp = #"LMNOP[\]^_";
string charsetA = "ABCDEFGHIJ", charsetB = "QRSTUVWXYZ", charsetC = "0123456789", digitsOnly = "qrstuvwxyz";
The Correct one looks like below
The wrong one looks like below
I have created as vlcbarcode.dll file reference of above function and added the azure project same as refered url and written below function.
Below is the azure function
[FunctionName("GetBarCodes")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "GetBarCodes/")]HttpRequestMessage req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
// Get request body
VLCBarCodes[] barCodeList = await req.Content.ReadAsAsync<VLCBarCodes[]>();
List<QueryStringClass> resultList = new List<QueryStringClass>();
string errorText = "";
string result = "";
bool isError = false;
foreach (var list in barCodeList)
{
errorText = "";
result = "";
if (string.IsNullOrWhiteSpace(list.BarCodeFontType))
errorText = " Bar code Type can not be empty or null";
if (string.IsNullOrWhiteSpace(list.BarCodeValue))
errorText += " Bar code text can not be empty or null";
if (string.IsNullOrWhiteSpace(list.BarCodeFontHeight))
errorText += " Bar code height can not be empty or null";
if (string.IsNullOrWhiteSpace(list.BarCodeFontWidth))
errorText += " Bar code width can not be empty or null";
if (string.IsNullOrWhiteSpace(list.BarCodeFontSize))
errorText += " Bar code font can not be empty or null";
if (list.BarCodeImageUID == 0)
errorText += " Bar Code Image Id can not be empty or null";
if (string.IsNullOrWhiteSpace(list.BarCodeEntryNo))
errorText += " Bar Code entry no can not be empty or null";
if (!string.IsNullOrWhiteSpace(list.BarCodeFontType) && !string.IsNullOrWhiteSpace(list.BarCodeValue) && !string.IsNullOrWhiteSpace(list.BarCodeFontHeight)
&& !string.IsNullOrWhiteSpace(list.BarCodeFontWidth) && list.BarCodeImageUID != 0 && string.IsNullOrWhiteSpace(errorText))
{
switch (list.BarCodeFontType)
{
case "EAN-13":
GenerateEANTBarCode generateEANTBarCode = new GenerateEANTBarCode();
result = generateEANTBarCode.GenerateBarCodeFont(list.BarCodeValue, out isError, Convert.ToInt32(list.BarCodeFontWidth), Convert.ToInt32(list.BarCodeFontHeight), "EAN-13", Convert.ToInt32(list.BarCodeFontSize));
break;
default:
isError = true;
result = "Please specify the bar code font type";
break;
}
if (isError)
resultList.Add(new QueryStringClass { BarCodeEntryNo = list.BarCodeEntryNo, BarCodeImageUID = list.BarCodeImageUID, Type = list.BarCodeFontType, Value = "", ErrorText = result });
else
resultList.Add(new QueryStringClass { BarCodeEntryNo = list.BarCodeEntryNo, BarCodeImageUID = list.BarCodeImageUID, Type = list.BarCodeFontType, Value = result, ErrorText = "" });
}
else
resultList.Add(new QueryStringClass { BarCodeEntryNo = list.BarCodeEntryNo, BarCodeImageUID = list.BarCodeImageUID, Type = list.BarCodeFontType, Value = result, ErrorText = errorText });
}
return req.CreateResponse(HttpStatusCode.OK, resultList);
}
QueryStringClass can get the results from vlcbarcode.dll function and return to the end user.
public class QueryStringClass
{
public int BarCodeImageUID { get; set; }
//public Guid Guid { get; set; }
public string BarCodeEntryNo { get; set; }
public string Type { get; set; }
public string Value { get; set; }
public string ErrorText { get; set; }
}
VLCBarCodes class is refere to original calss fields to validate the request and send the values to .dll file function.
public class VLCBarCodes
{
public int BarCodeImageUID { get; set; }
public string BarCodeValue { get; set; }
public string BarCodeFontWidth { get; set; }
public string BarCodeFontHeight { get; set; }
public string BarCodeFontType { get; set; }
public string BarCodeFontSize { get; set; }
public string BarCodeEntryNo { get; set; }
}
Please suggest if I went anything wrong.
In Azure App service most of the GDI32 system calls are blocked.
All Azure Web Apps (as well as Mobile App/Services, WebJobs and Functions) run in a secure environment called a sandbox.
The sandbox generally aims to restrict access to shared components of Windows. Unfortunately, many core components of Windows have been designed as shared components: the registry, cryptography, and graphics subsystems, among others. This section outlines the limitations placed on usage of these often essential, yet shared components.
For the sake of radical attack surface area reduction, the sandbox prevents almost all of the Win32k.sys APIs from being called, which practically means that most of User32/GDI32 system calls are blocked. For most applications this is not an issue since most Azure Web Apps do not require access to Windows UI functionality (they are web applications after all).
Reference doc: https://github.com/projectkudu/kudu/wiki/Azure-Web-App-sandbox
You can host this Azure function in an Azure Virtual machine if you are willing to use same code else you can try some alternative approach to generate the BAR code as explained in this blog.

Remove bleed from Pdf and merge

I am trying remove 3mm bleed size from pdf. by using below criteria
My source file is Source file
I am using below code to trim left and right
public void TrimLeftandRight(string sourceFilePath, string outputFilePath)
{
PdfReader pdfReader = new PdfReader(sourceFilePath);
float width = (float)GetPDFwidth(sourceFilePath);
float height = (float)GetPDFHeight(sourceFilePath);
float widthTo_Trim = iTextSharp.text.Utilities.MillimetersToPoints(3);
PdfRectangle rectrightside = new PdfRectangle(0, 0, width - widthTo_Trim, height);
PdfRectangle rectLeftside = new PdfRectangle(widthTo_Trim, 0, width, height);
// int[] pagealignment = new int[] { 8, 1, 2, 7, 6, 3, 4, 5 };
int[] pagealignment = new int[] { 6, 1, 2, 5, 4, 3 };
using (var output = new FileStream(outputFilePath, FileMode.CreateNew, FileAccess.Write))
{
// Create a new document
Document doc = new Document();
// Make a copy of the document
PdfSmartCopy smartCopy = new PdfSmartCopy(doc, output);
// Open the newly created document
doc.Open();
// Loop through all pages of the source document
for (int i = 1; i <= pdfReader.NumberOfPages; i++)
{
// Get a page
var page = pdfReader.GetPageN(i);
// Apply the rectangle filter we created
switch (i)
{
case 6:
page.Put(PdfName.CROPBOX, rectLeftside);
page.Put(PdfName.MEDIABOX, rectrightside);
break;
case 2:
page.Put(PdfName.MEDIABOX, rectrightside);
break;
case 4:
page.Put(PdfName.MEDIABOX, rectLeftside);
break;
case 1:
page.Put(PdfName.MEDIABOX, rectLeftside);
break;
case 5:
page.Put(PdfName.MEDIABOX, rectrightside);
// page.Put(PdfName.CROPBOX, rectLeftside);
break;
case 3:
page.Put(PdfName.CROPBOX, rectLeftside);
page.Put(PdfName.MEDIABOX, rectrightside);
break;
}
// Copy the content and insert into the new document
var copiedPage = smartCopy.GetImportedPage(pdfReader, i);
smartCopy.AddPage(copiedPage);
}
// Close the output document
smartCopy.Close();
doc.Close();
doc.Dispose();
}
}
the output of above code produces
Trimmed left and right file
and I used below code to merge trimmed files
public void CreategateFinalOutput(string inputfile)
{
double widthinpoints = iTextSharp.text.Utilities.MillimetersToPoints(897);
string onlyfilename = Path.GetFileName(inputfile);
// string originalfilename = Server.MapPath("~/Uploads/" + onlyfilename);
int Noofpagesinpdf = GetNoofpagesofpdf(inputfile);
// var a3doc = new Document(PageSize.A3.Rotate(), 0, 0, 0, 0);
double originalwidth = GetPDFwidth(inputfile);
float widthTo_Trim = iTextSharp.text.Utilities.MillimetersToPoints(3);
double width = (GetPDFwidth(inputfile) * 3);
width = widthinpoints;
double height = GetPDFHeight(inputfile);
var a3reader = new PdfReader(inputfile);
var a3doc = new Document(new Rectangle((float)width, (float)height));
var a3writer = PdfWriter.GetInstance(a3doc, new FileStream(Server.MapPath("~/RP/" + onlyfilename), FileMode.Create));
a3doc.Open();
var a3cb = a3writer.DirectContent;
PdfImportedPage page;
int totalPages = a3reader.NumberOfPages;
// int[] pagealignment = new int[] { 8, 1, 2, 7, 6, 3, 4, 5 };
int[] pagealignment = new int[] { 5, 6, 1, 2, 3, 4 };
int iteration = 1;
for (int i = 1; i <= totalPages; i++)
{
a3doc.NewPage();
var a3size = new Document(new Rectangle((float)width, (float)height));
//new code
int fistpage = 0;
int secpage = 0;
int thirdpage = 0;
switch (iteration)
{
case 1:
fistpage = 5;
secpage = 6;
thirdpage = 1;
break;
case 2:
fistpage = 2;
secpage = 3;
thirdpage = 4;
break;
}
double trimwidth = iTextSharp.text.Utilities.MillimetersToPoints(3);
page = a3writer.GetImportedPage(a3reader, fistpage);
double pagewidth = page.Width;
a3cb.AddTemplate(page, 0, 0);
i++;
page = a3writer.GetImportedPage(a3reader, secpage);
double pagewidtha = page.Width;
a3cb.AddTemplate(page, (float)(pagewidtha), 0);
i++;
page = a3writer.GetImportedPage(a3reader, thirdpage);
double pagewidthaThird = page.Width;
// a3cb.AddTemplate(page, (int)(a3size.Width / 2), 0); //commented
a3cb.AddTemplate(page, (float)(pagewidthaThird + pagewidth), 0);
iteration++;
a3doc.Close();
}
}
When i merged pdf by using above code the out put is not as per desire
Final output
Here we have removed borders of page 5 and 6 but when we merged there is border appearing .
You can see it downloading pdfs.. apologies for a such a big code. the help will be highly appreciated
I request to download pdfs and check pdfs for better views

How to add text and image in a column in Component One FlexGrid?

I have used the below mentioned snippet to show text with image. However I am unable to display image with it.
Is the path to image not accessible from code?
C1.Win.C1FlexGrid.C1FlexGrid gAuditL = new C1.Win.C1FlexGrid.C1FlexGrid();
.
.
.
gAuditL.DataSource = AuditLogVieweryDT;// this is datasource
for (int i = gAuditL.Row.Fixed; i < gAuditL.Rows.Count; i++)
//foreach row in grid
{
string severity = gAuditL[i, gAuditL.Cols["Severity"].Index].ToString();
if (severity == "Information")
{
this.gAuditL.SetCellImage(i, 0,Image.FromFile(#".\\Resources\information.bmp"));
this.gAuditL.SetData(i, 0, "Information");
}
if (severity == "Warning")
{
this.gAuditL.SetCellImage(i, 0, Image.FromFile(#".\\Resources\warning.bmp"));
this.gAuditL.SetData(i, 0, "Warning");
}
if (severity == "Critical")
{
this.gAuditL.SetCellImage(i, 0, Image.FromFile(#".\\Resources\critical.bmp"));
this.gAuditL.SetData(i, 0, "Critical");
}
if (severity == "Unspecified")
{
this.gAuditL.SetCellImage(i, 0, Image.FromFile(#".\\Resources\unspecified.bmp"));
this.gAuditL.SetData(i, 0, "Unspecified");
}
this.gAuditL.Styles.Normal.ImageAlign = C1.Win.C1FlexGrid.ImageAlignEnum.LeftCenter;
this.gAuditL.Styles.Normal.TextAlign = C1.Win.C1FlexGrid.TextAlignEnum.RightCenter;
}
Please refer this.(Answer posted by OP)
namespace SampleProject.Forms.Maintenance
{
public partial class SampleProject: Form
{
Image img1, img2, img3, img4;// declare member variable
//Load Event
private void AuditLogViewer_Load(object sender, EventArgs e)
{
object information = Resources.ResourceManager.GetObject("information"); //Return an object from the image chan1.png in the project
img1 = (Image)information;
object Warning = Resources.ResourceManager.GetObject("warning"); //Return an object from the image chan1.png in the project
img2 = (Image)Warning;
object critical = Resources.ResourceManager.GetObject("critical"); //Return an object from the image chan1.png in the project
img3 = (Image)critical;
object unspecified = Resources.ResourceManager.GetObject("unspecified"); //Return an object from the image chan1.png in the project
img4 = (Image)unspecified;
}
//Grid Click Event
private void grdAuditLogs_OwnerDrawCell(object sender, OwnerDrawCellEventArgs e)
{
if (e.Col == 2)
{
//let the grid paint the background and border for the cell
e.DrawCell(C1.Win.C1FlexGrid.DrawCellFlags.Background | C1.Win.C1FlexGrid.DrawCellFlags.Border);
//find text width
var width = (int)e.Graphics.MeasureString(e.Text, e.Style.Font).Width;
//x-coordinate for each image
var img1_x = e.Bounds.X + width + 10;
var img2_x = e.Bounds.X + width + 10;
var img3_x = e.Bounds.X + width + 10;
var img4_x = e.Bounds.X + width + 10;
//var img3_x = img2_x + img2.Width + 5;
//location for each image
var img1_loc = new Point(img1_x, e.Bounds.Y + img1.Height - 18);
var img2_loc = new Point(img2_x, e.Bounds.Y + img2.Height - 18);
var img3_loc = new Point(img3_x, e.Bounds.Y + img3.Height - 18);
var img4_loc = new Point(img4_x, e.Bounds.Y + img4.Height - 18);
//draw images at aforementioned points
if (grdAuditLogs[e.Row, grdAuditLogs.Cols["Severity"].Index].ToString() == "Information")
e.Graphics.DrawImage(img1, img1_loc);
if (grdAuditLogs[e.Row, grdAuditLogs.Cols["Severity"].Index].ToString() == "Warning")
e.Graphics.DrawImage(img2, img2_loc);
if (grdAuditLogs[e.Row, grdAuditLogs.Cols["Severity"].Index].ToString() == "Critical")
e.Graphics.DrawImage(img3, img3_loc);
if (grdAuditLogs[e.Row, grdAuditLogs.Cols["Severity"].Index].ToString() == "Unspecified")
e.Graphics.DrawImage(img4, img4_loc);
//e1.Graphics.DrawImage(img3, img3_loc);
//draw text
e.Graphics.DrawString(e.Text, e.Style.Font, Brushes.Black, e.Bounds.Location);
e.Handled = true;
}
}

Google apps script count variables (merging)

I'm trying to count some variables whit google apps script in google spreadsheet.
This isn't working how I wanted to be.
The code is:
for(var n in namen) {
var naam = namen[n];
var nr = n;
if(w == 1) {
var nr = 3+n;
} if(w == 2) {
var nr = 17+n;
} if(w == 3) {
var nr = 31+n;
} if(w == 4) {
var nr = "45"+n;
} if(naam == title){
ssRooster.getRange(nr, col, 1, 1).setValue(dateStr);
var nr = n;
}
}
Or the code is:
} if(naam == title){
ssRooster.getRange(n+row, col, 1, 1).setValue(dateStr);
}
It should be ok, but I get now The number from n lets say 2 and the number from row lets say 17. It results now as 217 instead of 19. How can I fix this?
Prefer the code with the row in it. (It's cleaner)
Thanks Dennis
[edit]
The compleete code is:
function LoadWorkTime() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var Period = Browser.inputBox("Periode","Welke periode wilt U zien. (kies tussen de 1 en de 12.)", Browser.Buttons.OK);
var ErrorPeriod = "De periode die U invoert is onjuist!";
if(Period>12){
Browser.msgBox(ErrorPeriod);
return;
} if(Period<1){
Browser.msgBox(ErrorPeriod);
return;
}
var ssPeriode = ss.setActiveSheet(ss.getSheets()[1]);
var ThisYear = ssPeriode.getRange(2, 1, 1, 1).getValue();
var CheckYear = Browser.msgBox("Jaar","Is het jaar " + ThisYear + " het jaar dat U wilt opvragen.", Browser.Buttons.YES_NO);
if(CheckYear=="yes") {
var CheckYear = ThisYear;
} else {
var PastYear = ThisYear-1;
var AfterYear = ThisYear-0+1;
var CheckYear = Browser.inputBox("Jaar", "Vul in jaar tal in tussen " + PastYear + " en " + AfterYear, Browser.Buttons.OK);
var ErrorYear = "Het jaar wat U heeft ingevuld is onjuist!";
if(CheckYear>PastYear){
Browser.msgBox(ErrorYear);
return;
} if(CheckYear<AfterYear){
Browser.msgBox(ErrorYear);
return;
}
}
ssPeriode.getRange(1, 1, 1, 1).setValue(Period);
ssPeriode.getRange(3, 1, 1, 1).setValue(CheckYear);
var ssRooster = ss.setActiveSheet(ss.getSheets()[0]);
var calRooster = CalendarApp.getCalendarById("0000#group.calendar.google.com");
var calVakantie = CalendarApp.getCalendarById("0000#group.calendar.google.com");
var dateRow = 2
var row = 3;
for(var w = 1; w <= 4; ++w) {
var col = 2;
var namen = ssRooster.getRange(3, 1, 10, 1).getValues();
for(var d = 1; d <= 7; ++d) {
var eventdate = ssPeriode.getRange(dateRow, 2, 1, 1).getValue();
var eventsRooster = calRooster.getEventsForDay(new Date(eventdate));
var dateRow = dateRow+1;
for(var e in eventsRooster) {
var event = eventsRooster[e];
var title = event.getTitle();
var dateStr = event.getStartTime();
Browser.msgBox(title);
for(var n in namen) {
var naam = namen[n];
Browser.msgBox(naam);
}
if(naam == title){
ssPeriode.getRange(5, 1, 1, 1).setFormula('=' + n + '+' + row);
var nr = ssPeriode.getRange(5, 1, 1, 1).getValue();
ssRooster.getRange(nr, col, 1, 1).setValue(dateStr);
}
}
var col = col+2;
}
var row = row+14;
}
}
I can't make this work! In my eye's is this a good code.
To try it your self run this install code and change the calendar addresses for one you own.
function Install() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ssPeriode = ss.setActiveSheet(ss.getSheets()[1]);
var Wt = 1;
ssPeriode
ssPeriode.deleteColumns(2, ssPeriode.getMaxColumns()-1);
ssPeriode.deleteRows(2, ssPeriode.getMaxRows()-1);
ssPeriode.clear();
ssPeriode.clearContents();
ssPeriode.clearFormats();
ssPeriode.insertColumnsAfter(1, 1);
ssPeriode.insertRows(1, 35);
ssPeriode.getRange(1, 1, 4, 1).setValues([["1"], [""], ["2012"], ["3-1-2000"]]);
ssPeriode.getRange(2, 1, 1, 1).setFormula('=TEXT(NOW(); "yyyy")');
ssPeriode.getRange(1, 2, 1, 1).setFormula('=A1');
ssPeriode.getRange(2, 2, 1, 1).setFormula('=(A3-2000)*364+((B1-1)*28)+A4');
for(var i = 3; i <= 29; ++i) {
var c = i-1;
ssPeriode.getRange(i, 2, 1, 1).setFormula('=B' + c + '+1');
}
var c = 2;
for(var i = i+1; i <= 34; ++i) {
ssPeriode.getRange(i, 1, 1, 1).setFormula('=SPLIT(TEXT(B' + c + ';"yyyy-ww");"-")');
var c = c+7;
}
var ssRooster = ss.setActiveSheet(ss.getSheets()[0]);
var Wt = 1;
var week = 31;
var dag = 2;
var nm = 3;
ssRooster.deleteColumns(2, ssRooster.getMaxColumns()-1);
ssRooster.deleteRows(2, ssRooster.getMaxRows()-1);
ssRooster.clear();
ssRooster.clearContents();
ssRooster.clearFormats();
ssRooster.insertColumnsAfter(1, 14);
ssRooster.insertRows(1, 56);
for(var col = 1; col <= ssRooster.getMaxColumns(); ++col) {
ssRooster.setColumnWidth(col, 60);
if(col == 1) {
ssRooster.setColumnWidth(col, 80);
}
}
for(var i = 1; i <= 4; ++i) {
ssRooster.getRange(Wt, 1, 13, 15).setBorder(true, true, true, true, false, false);
ssRooster.getRange(Wt, 1, 2, 15).setBorder(true, true, true, true, false, false);
ssRooster.getRange(Wt+2, 1, 11).setNumberFormat("H:mm")
ssRooster.getRange(Wt, 1, 1, 1).setFormula('=JOIN(P1;"Week ";P1;Periode!B' + week + ')');
var week = week+1;
var col = 2;
for(var j = 1; j <= 7; ++j) {
ssRooster.getRange(Wt, col, 2, 2).setBorder(true, true, true, true, false, false);
ssRooster.getRange(Wt+2, col, 11, 2).setBorder(true, true, true, true, false, false);
ssRooster.getRange(Wt, col, 1, 2).merge();
ssRooster.getRange(Wt, col, 1, 1).setFormula('=CHOOSE(WEEKDAY(Periode!B' + dag + ';2);"Maandag ";"Dinsdag ";"Woensdag ";"Donderdag ";"Vrijdag ";"Zaterdag ";"Zondag ")&DAY(Periode!B' + dag + ')&CHOOSE(MONTH(Periode!B' + dag + ');" jan";" feb";" mrt";" apr";" mei";" jun";" jul";" aug";" sep";" okt";" nov";" dec")');
var dag = dag+1;
var col = col+2;
}
var Wt = Wt+1;
ssRooster.getRange(Wt, 1, 1, 15).setValues([["Naam", "van", "tot", "van", "tot", "van", "tot", "van", "tot", "van", "tot", "van", "tot", "van", "tot"]]);
for(var k = 1; k <= 6; ++k) {
var Wt = Wt+1;
ssRooster.getRange(Wt, 1, 1, 15).setBackground('yellow');
var Wt = Wt+1;
}
var Wt = Wt-12;
if( i == 1) {
var Wt = Wt+13;
}
if( i >= 2) {
for(var k = 1; k <= 11; ++k) {
var Wt = Wt+1;
ssRooster.getRange(Wt, 1, 1, 1).setFormula('=A' + nm);
var nm = nm+1;
}
var Wt = Wt+1;
ssRooster.getRange(Wt, 1, 1, 15).setBorder(true, false, true, false, false, false);
var Wt = Wt+1;
var nm = nm+3;
}
}
ssRooster.getRange(Wt, 1, 1, 15).clearFormat();
}
You can also use var nr = new Number(n); to make sure that nr is an integer.
I am not sure if I understand but I think the solution is to insure nr is an integer:
var nr = parseInt(n);
and do not use quotes in var nr = "45"+n;
I now write the numbers to a cell and let a third cell count it and call that one up.
In the code is now up and running and in the old code need some modification to let it work.
Everything works now fine.

not able to insert image on cell of table when converting griddata to PDF file using iTextsharp in Ext.net

I am using iTextSharp to export Griddata to PDF. I am not able to insert .jpg image to a cell of a table. I want to export griddata(billdata) to PDF I can insert text on a cell but not able to insert image.
My code is as below
protected void ToPDF(object sender, EventArgs e)
{
System.IO.MemoryStream PDFData = new System.IO.MemoryStream();
iTextSharp.text.Document newDocument = new iTextSharp.text.Document(PageSize.A4.Rotate(), 10, 10, 10, 10);
iTextSharp.text.pdf.PdfWriter newPdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(newDocument, PDFData);
DataSet newDataSet = null;
string json = GridData.Value.ToString();
if (json != "[]")
{
StoreSubmitDataEventArgs eSubmit = new StoreSubmitDataEventArgs(json, null);
XmlNode xml = eSubmit.Xml;
if (xml != null)
{
XmlTextReader xtr = new XmlTextReader(xml.OuterXml, XmlNodeType.Element, null);
newDataSet = new DataSet();
newDataSet.ReadXml(xtr);
int totalColumns = newDataSet.Tables[0].Columns.Count;
iTextSharp.text.pdf.PdfPTable newPdfTable = new iTextSharp.text.pdf.PdfPTable(totalColumns - 3+1);
newPdfTable.DefaultCell.Padding = 1;
newPdfTable.WidthPercentage = 80;
newPdfTable.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT;
newPdfTable.DefaultCell.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE;
newPdfTable.HeaderRows = 1;
newPdfTable.DefaultCell.BorderColor = new iTextSharp.text.BaseColor(255, 255, 255);
newPdfTable.DefaultCell.BackgroundColor = new iTextSharp.text.BaseColor(255, 255, 255);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance("D:\\company_logo.jpg");
image.Alignment = iTextSharp.text.Image.ALIGN_LEFT;
iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(image);
cell.Rowspan = 5;
cell.HorizontalAlignment = 0;
//cell.Border = 1;
newPdfTable.AddCell(cell);
cell = new iTextSharp.text.pdf.PdfPCell(new Phrase("Your company name", FontFactory.GetFont("Times New Roman", 18, Font.BOLD, new iTextSharp.text.BaseColor(80, 80, 80))));
cell.Colspan = 6;
cell.HorizontalAlignment = 0;
//cell.Border = 1;
newPdfTable.AddCell(cell);
cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(Environment.NewLine));
cell.Colspan = 6;
cell.HorizontalAlignment = 0;
//cell.Border = 1;
newPdfTable.AddCell(cell);
cell = new iTextSharp.text.pdf.PdfPCell(new Phrase("Street Address", FontFactory.GetFont("Times New Roman", 12, Font.NORMAL, new iTextSharp.text.BaseColor(80, 80, 80))));
cell.Colspan = 6;
cell.HorizontalAlignment = 0;
//cell.Border =1;
newPdfTable.AddCell(cell);
cell = new iTextSharp.text.pdf.PdfPCell(new Phrase("City, Pincode", FontFactory.GetFont("Times New Roman", 12, Font.NORMAL, new iTextSharp.text.BaseColor(80, 80, 80))));
cell.Colspan = 5;
cell.HorizontalAlignment = 0;
//cell.Border = 1;
newPdfTable.AddCell(cell);
string dt=Convert.ToString( Convert.ToDateTime(dtBill.Text).ToShortDateString());
cell = new iTextSharp.text.pdf.PdfPCell(new Phrase("Date : " + dt, FontFactory.GetFont("Times New Roman", 12, Font.NORMAL, new iTextSharp.text.BaseColor(80, 80, 80))));
//cell.Colspan = 2;
cell.HorizontalAlignment = 0;
//cell.Border = 1;
newPdfTable.AddCell(cell);
cell = new iTextSharp.text.pdf.PdfPCell(new Phrase("Phone no., Website, etc.", FontFactory.GetFont("Times New Roman", 12, Font.NORMAL, new iTextSharp.text.BaseColor(80, 80, 80))));
cell.Colspan = 5;
cell.HorizontalAlignment = 0;
//cell.Border =1;
newPdfTable.AddCell(cell);
cell = new iTextSharp.text.pdf.PdfPCell(new Phrase("Bill no : " + cmbBill.Text, FontFactory.GetFont("Times New Roman", 12, Font.NORMAL, new iTextSharp.text.BaseColor(80, 80, 80))));
//cell.Colspan = 2;
cell.HorizontalAlignment = 0;
//cell.Border =1;
newPdfTable.AddCell(cell);
cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(Environment.NewLine));
cell.Colspan = 7;
cell.HorizontalAlignment = 0;
//cell.Border = 1;
newPdfTable.AddCell(cell);
cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(Environment.NewLine));
cell.Colspan = 7;
cell.HorizontalAlignment = 0;
//cell.Border = 1;
newPdfTable.AddCell(cell);
cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(Environment.NewLine));
cell.Colspan = 7;
cell.HorizontalAlignment = 0;
//cell.Border = 1;
newPdfTable.AddCell(cell);
for (int i = 0; i <= totalColumns-1 ; i++)
{
if ((i != 0) & (i != 1) & (i != 2))
{
cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(newDataSet.Tables[0].Columns[i].ColumnName, FontFactory.GetFont("Tahoma", 12, Font.BOLD, new iTextSharp.text.BaseColor(80, 80, 80))));
cell.BorderColor = new iTextSharp.text.BaseColor(80, 80, 80);
cell.BackgroundColor = new iTextSharp.text.BaseColor(System.Drawing.Color.LightGray);
cell.VerticalAlignment =iTextSharp.text.Element.ALIGN_MIDDLE;
if (i == 5)
{
cell.Colspan = 2;
cell.HorizontalAlignment = 1;
}
else
{
cell.HorizontalAlignment = 1;
}
newPdfTable.AddCell(cell);
}
}
int j = 0;
foreach (DataRow record in newDataSet.Tables[0].Rows)
{
for (int i = 0; i <= totalColumns - 1; i++)
{
if ((i != 0) & (i != 1) & (i != 2))
{
if (i == 3)
{
if(record[i].ToString()=="true")
cell = new iTextSharp.text.pdf.PdfPCell(new Phrase("Yes", FontFactory.GetFont("Tahoma", 10, Font.NORMAL, new iTextSharp.text.BaseColor(80, 80, 80))));
else
cell = new iTextSharp.text.pdf.PdfPCell(new Phrase("No", FontFactory.GetFont("Tahoma", 10, Font.NORMAL, new iTextSharp.text.BaseColor(80, 80, 80))));
}
else
{
cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(record[i].ToString(), FontFactory.GetFont("Tahoma", 10, Font.NORMAL, new iTextSharp.text.BaseColor(80, 80, 80))));
}
if ((j % 2) == 0)
{
//cell.BorderColor = new iTextSharp.text.BaseColor(System.Drawing.Color);
}
else
{
cell.BackgroundColor = new iTextSharp.text.BaseColor(System.Drawing.Color.WhiteSmoke);
}
cell.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE;
if (i == 3)
cell.Border = iTextSharp.text.pdf.PdfPCell.NO_BORDER;
else
cell.Border = iTextSharp.text.pdf.PdfPCell.LEFT_BORDER;
if (i == 5)
{
cell.Colspan = 2;
cell.HorizontalAlignment = 0;
}
else
{
if ((i == 6) | (i == 7) | (i == 8))
{
cell.HorizontalAlignment = 2;
}
else
{
cell.HorizontalAlignment = 0;
}
}
newPdfTable.AddCell(cell);
}
}
j++;
}
newDocument.Open();
newDocument.Add(new Phrase(Environment.NewLine));
newDocument.Add(new Phrase(Environment.NewLine));
newDocument.Add(newPdfTable);
//newDocument.Add(new Phrase(" Total " + txtTotalQty.Text + " " + txtTotalAmount.Text, FontFactory.GetFont("Trebuchet MS", 14, Font.BOLD, new iTextSharp.text.BaseColor(21, 66, 157))));
newDocument.Add(new Phrase(Environment.NewLine));
//newDocument.Add(new Phrase("Printed On: " + DateTime.Now.ToString(), FontFactory.GetFont("Tahoma", 9, Font.NORMAL, new iTextSharp.text.BaseColor(80, 80, 80))));
newDocument.Close();
Response.ContentType = "application/pdf";
Response.Cache.SetCacheability(System.Web.HttpCacheability.Public);
Response.AppendHeader("Content-Type", "application/pdf");
Response.AppendHeader("Content-Disposition", "attachment; filename=" + this.ID + ".pdf");
Response.OutputStream.Write(PDFData.GetBuffer(), 0, PDFData.GetBuffer().Length);
Response.OutputStream.Flush();
Response.OutputStream.Close();
}
}
}
Just replace newPdfTable.HeaderRows = 1; to newPdfTable.HeaderRows = 0;
and one more thing
iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(image);
and one more parameter as true
iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(image,true);

Resources