-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRIWCompile.aspx.cs
3205 lines (2812 loc) · 153 KB
/
RIWCompile.aspx.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.security;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Crypto;
using Microsoft.SharePoint.Utilities;
using System.Collections.Generic;
using System.Net.Mail;
using iTextSharpSign;
using Winnovative.WnvHtmlConvert;
using System.Net;
using System.Text.RegularExpressions;
using System.Linq;
using Microsoft.SharePoint.Administration;
public partial class RIWCompile : System.Web.UI.Page
{
#region Global variables
public static string ErrorSubject = " - PROJ - EInspection - Error on RIWCompile.aspx.cs";
public static string SmtpServer = ConfigurationManager.AppSettings["SmtpServer"];
public static string layoutPath = "_layouts/15/PCW/General/EForms";
public static string LeadRedirectURL = "/Lists/Inspection Lead Tasks/";
public string redirectURL = "";
public string Referrer = "";
string RIWQueryStrID = "", LeadQueryStrID = "";
string MainList = "", LeadTaskList = "", PartTaskList = "";
string StrFullRef = "", ARE = "";
//string Pdftemplatepath = ConfigurationSettings.AppSettings["PdfFilePath"].ToString();
SPList objlist = null;
SPList objlistLeadTasks = null;
SPList objWorkflowTask = null;
SPListItem RIWItem = null;
SPListItem LeadItem = null;
bool ApplyDigitalSign = true;
bool BlankCommentsForm = false;
public static string LeadName = "";
public string Discipline = "";
public DateTime DateClosed ;
public string UserName = "";
#endregion
#region GENERIC EMAIL TEMPLATE VARIABLES
string CurrentUserEmail = "",
Title = "",
EmailType = "",
EmailValue = "",
ListName = "",
HeaderChunk = "",
EditedChunk = "",
FooterChunck = "",
AddNewRow = "",
ColumnInBrackets = "",
value = "";
bool isMulti = false,
isNewRow = false,
isFirstVisit = false;
#endregion
public static SPWeb objweb = null;
public static int Version = GetSPVersion();
protected void Page_Load(object sender, EventArgs e)
{
try
{
#region SESSION EXPIRED THEN REDIRECT TO LOGIN
if (SPContext.Current.Web.CurrentUser == null)
{
string serverRelativeUrl = SPContext.Current.Web.ServerRelativeUrl;
string layoutUrl = HttpContext.Current.Request.Url.PathAndQuery;
//string CurrentUrl = System.Web.HttpUtility.UrlEncode(serverRelativeUrl + layoutUrl);
string CurrentUrl = serverRelativeUrl + layoutUrl;
//Response.Write(layoutUrl);
//string LoginURL = "/_login/default.aspx?ReturnUrl=" + SPContext.Current.Web.Url.Replace("/", "%2f") + "%2f_layouts%2f15%2fAuthenticate.aspx%3fSource%3d" + CurrentUrl.Replace("/", "%252D") + "&Source=" + CurrentUrl.Replace("/", "%2F");
string LoginURL = "/_login/default.aspx?ReturnUrl=" + serverRelativeUrl + "%2f_layouts%2fAuthenticate.aspx%3fSource%3d" + CurrentUrl + "&Source=" + CurrentUrl;
if (Version > 14)
LoginURL = "/_login/default.aspx?ReturnUrl=" + serverRelativeUrl + "%2f_layouts%2f15%2fAuthenticate.aspx%3fSource%3d" + CurrentUrl + "&Source=" + CurrentUrl;
Response.Write("<script>window.location = '" + LoginURL + "';</script>");
return;
}
#endregion
DateTime Start = DateTime.Now;
SPFieldUserValue LeadUser = null;
string TimeLog = "";
if (!IsPostBack)
{
if (Request.UrlReferrer != null)
Referrer = Request.UrlReferrer.ToString();
}
MainList = "Inspection Request";
LeadTaskList = "Inspection Lead Tasks";
PartTaskList = "Inspection Part Tasks";
LeadName = SPContext.Current.Web.CurrentUser.Name;
string UserEmail = "";
try { UserEmail = SPContext.Current.Web.CurrentUser.Email; }
catch { }
//SPSecurity.RunWithElevatedPrivileges(delegate ()
//{
using (SPSite site = new SPSite(SPContext.Current.Web.Site.ID))
{
objweb = site.OpenWeb();
}
objweb.AllowUnsafeUpdates = true;
//});
//ProjectDesc.Text = "E-Inspection Review by Lead Action";
//if (SPContext.Current != null && SPContext.Current.Web != null && SPContext.Current.Web.CurrentUser != null)
// this.UserName = SPContext.Current.Web.CurrentUser.Name;
#region QUERY E-Inspection AND LEAD
objlist = objweb.Lists[MainList];
objlistLeadTasks = objweb.Lists[LeadTaskList];
objWorkflowTask = objweb.Lists[PartTaskList];
loader.ImageUrl = objweb.Url + ConfigurationManager.AppSettings["loaderUrl"];
//string RIWViewFields =//"<FieldRef Name='ID' />" +
// " <FieldRef Name='Attachments' />" +
// "<FieldRef Name='Title' />" +
// "<FieldRef Name='date_closed' />" +
// "<FieldRef Name='FullRef' />" +
// "<FieldRef Name='project_name' />" +
// "<FieldRef Name='project_name_x003a_Title' />" +
// "<FieldRef Name='discipline' />" +
// "<FieldRef Name='LeadAction' />" +
// "<FieldRef Name='bldgar_nbr' />" +
// "<FieldRef Name='sub_name' />" +
// "<FieldRef Name='attach_dwgskt1' />" +
// "<FieldRef Name='ItemOfWork' />" +
// "<FieldRef Name='Quantity' />" +
// "<FieldRef Name='Unit' />";
RIWQueryStrID = HttpContext.Current.Request.QueryString["RIWID"];
LeadQueryStrID = HttpContext.Current.Request.QueryString["ID"];
int LeadItemID = 0;
int RIWItemID = 0;
if (!String.IsNullOrEmpty(RIWQueryStrID))
{
DateTime Start1 = DateTime.Now;
if (int.TryParse(RIWQueryStrID, out RIWItemID))
{
RIWItemID = int.Parse(RIWQueryStrID);
// RIWItem = objlist.GetItemById(RIWItemID);
SPQuery _query = new SPQuery();
_query.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + RIWItemID + "</Value></Eq></Where>";
//_query.ViewFields = RIWViewFields;
_query.ViewAttributes = "Scope=\"Recursive\"";
SPListItemCollection RIWItems = objlist.GetItems(_query);
if (RIWItems.Count == 1)
RIWItem = RIWItems[0];
else
{
MessageAndRedirect("This RIW has issues. Please Contact PWS Administrator.", SPContext.Current.Web.Url + redirectURL);
return;
}
StrFullRef = (RIWItem["FullRef"] != null) ? RIWItem["FullRef"].ToString() : "";
Discipline = (RIWItem["Discipline"] != null) ? RIWItem["Discipline"].ToString().Split('#')[1] : "";
redirectURL = LeadRedirectURL;
}
TimeLog += "GET ITEM FROM MAIN RIW - Page_Load - " + DateTime.Now.Subtract(Start1).TotalSeconds + "<br/><br/>";
}
else if (!String.IsNullOrEmpty(LeadQueryStrID))
{
DateTime Start2 = DateTime.Now;
if (int.TryParse(LeadQueryStrID, out LeadItemID))
{
{
LeadItemID = int.Parse(LeadQueryStrID);
LeadItem = objlistLeadTasks.GetItemById(LeadItemID);
StrFullRef = (LeadItem["Reference"] != null) ? LeadItem["Reference"].ToString() : "";
Discipline = (LeadItem["Trade"] != null) ? LeadItem["Trade"].ToString() : "";
redirectURL = LeadRedirectURL;//"/Lists/RIW/";
LeadUser = (LeadItem["AssignedTo"] != null) ? new SPFieldUserValue(objweb, LeadItem["AssignedTo"].ToString()) : null;
//LeadName = LeadUser.User.Name;// SPContext.Current.Web.CurrentUser.Name;//Used in getting the signature image file
}
}
else //contains text means fullRef
StrFullRef = HttpContext.Current.Request.QueryString["ID"];
TimeLog += "GET ITEM FROM LEAD RIW - Page_Load - " + DateTime.Now.Subtract(Start2).TotalSeconds + "<br/><br/>";
}
//Get RIW and Lead Item by Ref
if (RIWItem == null)
{
DateTime Start3 = DateTime.Now;
SPQuery _query = new SPQuery();
_query.Query = "<Where><Eq><FieldRef Name='FullRef' /><Value Type='Text'>" + StrFullRef + "</Value></Eq></Where>";
_query.ViewAttributes = "Scope=\"Recursive\"";
//_query.ViewFields = RIWViewFields;
SPListItemCollection RIWItems = objlist.GetItems(_query);
if (RIWItems.Count == 1)
RIWItem = RIWItems[0];
else
{
MessageAndRedirect("This RIW has issues. Please Contact PWS Administrator.", SPContext.Current.Web.Url + redirectURL);
return;
}
TimeLog += "GET ITEM FROM MAIN RIW IF NULL - Page_Load - " + DateTime.Now.Subtract(Start3).TotalSeconds + "<br/><br/>";
}
if (LeadItem == null)
{
DateTime Start4 = DateTime.Now;
SPQuery _Leadquery = new SPQuery();
_Leadquery.Query = "<Where><Eq><FieldRef Name='Reference' /><Value Type='Text'>" + StrFullRef + "</Value></Eq></Where>";
_Leadquery.ViewAttributes = "Scope=\"Recursive\"";
SPListItemCollection LeadItems = objlistLeadTasks.GetItems(_Leadquery);
if (LeadItems.Count == 1)
LeadItem = LeadItems[0];
else
{
MessageAndRedirect("This RIW has no lead task. Please contact PWS administrator.", SPContext.Current.Web.Url + redirectURL);
return;
}
TimeLog += "GET ITEM FROM Lead RIW IF NULL - Page_Load - " + DateTime.Now.Subtract(Start4).TotalSeconds + "<br/><br/>";
}
#endregion
#region IS ALLOWED TO CLOSE THE TASK
DateClosed = (RIWItem["SentToContractorDate"] != null) ? (DateTime)RIWItem["SentToContractorDate"] : DateTime.Now;
SPFieldUserValueCollection AssignedToLead = (LeadItem["AssignedTo"] != null) ? new SPFieldUserValueCollection(objweb, LeadItem["AssignedTo"].ToString()) : null;
bool goAhead = false;
for (int i = 0; i < AssignedToLead.Count; i++)
{
if (AssignedToLead[i].User.Email.ToString().ToLower() == UserEmail.ToLower())
goAhead = true;
}
if (!goAhead)
MessageAndRedirect("This task is not assigned to you.", SPContext.Current.Web.Url + redirectURL);
#endregion
if (!IsPostBack)
{
DateTime Start6 = DateTime.Now;
DateTime Start6_1 = DateTime.Now;
#region Creating Data Table with required columns for Final Output.
DataTable dtstore = new DataTable();
dtstore.Columns.Add("ID", typeof(string));
dtstore.Columns.Add("Title", typeof(string));
dtstore.Columns.Add("AssignedTo", typeof(string));
//dtstore.Columns.Add("SeniorEngineer", typeof(string));
//dtstore.Columns.Add("PartRE", typeof(string));
dtstore.Columns.Add("Date", typeof(DateTime));
dtstore.Columns.Add("Status", typeof(string));
dtstore.Columns.Add("Code", typeof(string));
//dtstore.Columns.Add("CMQuantity", typeof(string));
//dtstore.Columns.Add("CMUnit", typeof(string));
dtstore.Columns.Add("Comment", typeof(string));
//dtstore.Columns.Add("DaysHeld", typeof(string));
//dtstore.Columns.Add("WorkflowLink", typeof(string));
DataTable dtFinal = new DataTable();
dtFinal.Columns.Add("ID", typeof(string));
dtFinal.Columns.Add("Title", typeof(string));
dtFinal.Columns.Add("AssignedTo", typeof(string));
//dtFinal.Columns.Add("SeniorEngineer", typeof(string));
//dtFinal.Columns.Add("PartRE", typeof(string));
dtFinal.Columns.Add("Date", typeof(DateTime));
dtFinal.Columns.Add("Status", typeof(string));
dtFinal.Columns.Add("Code", typeof(string));
//dtFinal.Columns.Add("CMQuantity", typeof(string));
//dtFinal.Columns.Add("CMUnit", typeof(string));
dtFinal.Columns.Add("Comment", typeof(string));
//dtFinal.Columns.Add("DaysHeld", typeof(string));
//dtFinal.Columns.Add("WorkflowLink", typeof(string));
#endregion
TimeLog += "checking the Status - Creating Data Table - Page_Load - " + DateTime.Now.Subtract(Start6_1).TotalSeconds + "<br/><br/>";
#region checking the status of the IR from RIW list.
string code = (LeadItem["Code"] != null) ? LeadItem["Code"].ToString() : "";
if (code != "")
btnUpdateAREMergePdf.Visible = true;
if (LeadItem.Attachments.Count == 1)
SubmitCloseIR.Visible = true;
if (LeadItem["Status"].ToString() == "Completed")
{
MessageAndRedirect("This Inspection has already been closed.", SPContext.Current.Web.Url + redirectURL);
//Response.Write("<script>alert('This RIW has already been closed.');</script>");
//Response.Write("<script>window.returnValue = true;window.close();</script>");
return;
}
//DataTable dt = RIWItems.GetDataTable();
DateTime Start6_2 = DateTime.Now;
#region Populate the Inspection info in grid
lblIRNo.Text = (RIWItem["FullRef"] != null) ? RIWItem["FullRef"].ToString() : "";
//lblProjectNo.Text = (RIWItem["project_name_x003a_Title"] != null) ? RIWItem["project_name_x003a_Title"].ToString().Split('#')[1] : "";
lblTrade.Text = (RIWItem[("Discipline")] != null) ? RIWItem[("Discipline")].ToString().Split('#')[1] : "";
lblRE.Text = LeadName; //(RIWItem["RE_Name"] != null) ? RIWItem["RE_Name"].ToString() : "";
//lblFacility.Text = (RIWItem["bldgar_nbr"] != null) ? RIWItem["bldgar_nbr"].ToString().Split('#')[1] : "";
//lblContractor.Text = (RIWItem["sub_name"] != null) ? RIWItem["sub_name"].ToString() : "";
//DrawingRefVal.Text = (RIWItem["attach_dwgskt1"] != null) ? RIWItem["attach_dwgskt1"].ToString() : "";
//lblItemOfWork.Text = (RIWItem["ItemOfWork"] != null) ? RIWItem["ItemOfWork"].ToString() : "";
//lblQuantity.Text = (RIWItem["Quantity"] != null) ? RIWItem["Quantity"].ToString() : "";
//lblUnit.Text = (RIWItem["Unit"] != null) ? RIWItem["Unit"].ToString() : "";
lblRIWTitle.Text = (LeadItem["Title"] != null) ? LeadItem["Title"].ToString() : "";
ddlcode.SelectedIndex = ddlcode.Items.IndexOf(ddlcode.Items.FindByText(code));
PartComments.Text = (LeadItem["PartComments"] != null) ? SPHttpUtility.ConvertSimpleHtmlToText(LeadItem["PartComments"].ToString(), -1) : "";
CommentBox.Text = (LeadItem["Comment"] != null) ? LeadItem["Comment"].ToString() : "";
//CHECK APPROVED DRAWINGS
//string Drawing_Matched = (LeadItem["DrawingMatched"] != null) ? LeadItem["DrawingMatched"].ToString() : "";
//ApprovedDwgbtn.SelectedIndex = ApprovedDwgbtn.Items.IndexOf(ApprovedDwgbtn.Items.FindByText(Drawing_Matched));
//string CMUnit = (LeadItem["CMUnit"] != null) ? LeadItem["CMUnit"].ToString() : "";
//UnitDDL.SelectedIndex = UnitDDL.Items.IndexOf(UnitDDL.Items.FindByText(CMUnit));
//string CMQuantity = (LeadItem["CMQuantity"] != null) ? LeadItem["CMQuantity"].ToString() : "";
//QtyTextBox.Text = CMQuantity;
if (LeadItem.Attachments.Count > 0)
{
HyperLinkLeadAttach.NavigateUrl = LeadItem.Attachments.UrlPrefix + LeadItem.Attachments[0];
HyperLinkLeadAttach.Text = LeadItem.Attachments[0];
lblmsg.Text = "Warning this Lead Task has attachment and pressing Merge again may overwrite the existing attachement.";
}
//lblARE.Text = dt.Rows[0]["SeniorEng"].ToString();
//SPFieldUrlValue value = new SPFieldUrlValue(RIWItem["PDFLink"].ToString().Trim());
if (RIWItem.Attachments.Count == 0)
{
//MessageAndRedirect("This RIW has no attachment to get the cover page from, please close it from Lead Task.", SPContext.Current.Web.Url + LeadRedirectURL + "DispForm.aspx?ID=" + LeadItemID.ToString());
Response.Write("<script>alert('This E-Inspection has no attachment to get the cover page from, please close it from Lead Task.');</script>");
Response.Write("<script>window.location = '" + SPContext.Current.Web.Url + LeadRedirectURL + "DispForm.aspx?ID=" + LeadItem.ID.ToString() + "';</script>");
return;
}
else if (RIWItem.Attachments.Count == 1)
{
if (RIWItem.Attachments[0].ToLower().EndsWith("pdf"))
{
Pdfhyplink.NavigateUrl = RIWItem.Attachments.UrlPrefix + RIWItem.Attachments[0];
Pdfhyplink.Text = RIWItem.Attachments[0];
}
else
{
lblmsg.Text = "The contractor attachment is not of type PDF, you must close this Inspection from lead task.";
return;
}
//Pdfhyplink.NavigateUrl = (value.Url.Contains(" ") ? value.Url.Replace(" ", "") : value.Url);
//Pdfhyplink.Text = "PdfLink";
}
else
{
lblmsg.Text = "This Inspection has multiple attachments, you must close this RIW from lead task.";
return;
}
#endregion
TimeLog += "checking the Status - Populate the Inspection info in grid - Page_Load - " + DateTime.Now.Subtract(Start6_2).TotalSeconds + "<br/><br/>";
DateTime Start6_3 = DateTime.Now;
#region getting the records from Part Tasks
SPQuery _WTQuery = new SPQuery();
_WTQuery.Query = "<Where><Eq><FieldRef Name='Reference' /><Value Type='Text'>" + StrFullRef + "</Value></Eq></Where>";
_WTQuery.ViewAttributes = "Scope=\"Recursive\"";
//_WTQuery.ViewFields = "<FieldRef Name='ID' />" +
// "<FieldRef Name='Title' />" +
// "<FieldRef Name='AssignedTo' />" +
// "<FieldRef Name='PartRE' />" +
// "<FieldRef Name='Date' />" +
// "<FieldRef Name='Status' />" +
// "<FieldRef Name='Code' />" +
// "<FieldRef Name='CMQuantity' />" +
// "<FieldRef Name='CMUnit' />" +
// "<FieldRef Name='Comment' />";
DataTable dtTask = objWorkflowTask.GetItems(_WTQuery).GetDataTable();
SPListItemCollection PartTasks = objWorkflowTask.GetItems(_WTQuery);
if (dtTask != null)
{
//Response.Write("<script>alert('This IR has part " + dtTask.Rows.Count.ToString() + ".');</script>");
string strQueryFilter = "";
if (dtTask.Rows.Count > 0)
{
#region filling the dtstore table.
for (int i = 0; i < dtTask.Rows.Count; i++)
{
DataRow dr = dtstore.NewRow();
dr["ID"] = dtTask.Rows[i]["ID"].ToString();
dr["Title"] = dtTask.Rows[i]["Title"].ToString();
dr["AssignedTo"] = dtTask.Rows[i]["AssignedTo"].ToString();
//Get User collection
if (dtTask.Rows[i]["AssignedTo"].ToString().Contains(";#"))
{
SPListItem taskItem = objWorkflowTask.GetItemById(int.Parse(dtTask.Rows[i]["ID"].ToString()));
SPFieldUserValueCollection usrColl = (taskItem["AssignedTo"] != null) ? new SPFieldUserValueCollection(objweb, taskItem["AssignedTo"].ToString()) : null;
string PartNames = "";
foreach (SPFieldUserValue usrval in usrColl)
if (!PartNames.Contains(usrval.User.Name)) PartNames += usrval.User.Name + "<br/>";
//if (PartNames != "") PartNames += "<br/> " + usrval.User.Name ;
//else PartNames += usrval.User.Name;
dr["AssignedTo"] = PartNames;
}
//dr["SeniorEngineer"] = dtTask.Rows[i]["SeniorEngineer"].ToString();
//dr["PartRE"] = dtTask.Rows[i]["PartRE"].ToString();
dr["Date"] = dtTask.Rows[i]["Date"];
dr["Status"] = dtTask.Rows[i]["Status"].ToString();
dr["Code"] = dtTask.Rows[i]["Code"].ToString();
//dr["CMQuantity"] = dtTask.Rows[i]["CMQuantity"].ToString();
//dr["CMUnit"] = dtTask.Rows[i]["CMUnit"].ToString();
dr["Comment"] = dtTask.Rows[i]["Comment"].ToString();
//dr["WorkflowLink"] = Regex.Match(dtTask.Rows[i]["WorkflowLink"].ToString(), @"ID=(\d+)").Groups[1].Value;
//if (dtTask.Rows[i]["Status"].ToString() == "Completed")
// dr["DaysHeld"] = "";
//else
//{
// DateTime futurDate = Convert.ToDateTime(dtTask.Rows[i]["Date"]);
// DateTime TodayDate = DateTime.Now;
// double numberOfDays = (TodayDate - futurDate).TotalDays;
// int number = Convert.ToInt32(numberOfDays);
// dr["DaysHeld"] = number.ToString();
//}
dtstore.Rows.Add(dr);
//ViewState["AssignedTo"] = dtTask.Rows[i]["AssignedTo"].ToString();
}
#endregion
DataRow[] result = dtstore.Select(strQueryFilter);
if (result.Length > 0)
{
foreach (DataRow row in result)
{
dtFinal.Rows.Add(row.ItemArray);
}
ViewState["FinalData"] = dtFinal;
grdWorkflowtasks.DataSource = dtFinal;
grdWorkflowtasks.DataBind();
}
}
}
#endregion
TimeLog += "checking the Status - getting the records from Part Tasks - Page_Load - " + DateTime.Now.Subtract(Start6_3).TotalSeconds + "<br/><br/>";
//btnUpdateAREMergePdf.Visible = true;
//btnUpdateAREMergePdfNoWT.Visible = true;
//btnSign.Visible = true;
//PanelRE.Visible = true;
//btnCloseIR.Visible = true;
#endregion
TimeLog += "Total checking the status of the IR from RIW list. - Page_Load - " + DateTime.Now.Subtract(Start6).TotalSeconds + "<br/><br/>";
}
int total = (int)DateTime.Now.Subtract(Start).TotalSeconds;
if (total > 5)
{
TimeLog += "TOTAL TIME = " + total;
//SendErrorEmail(StrFullRef + " - Page_Load<br/><br/>" + TimeLog, "RIW Lead Page Load");
}
}
catch (Exception ex)
{
lblmsg.Text = "An error occurred. Please contact your PWS system administrator" + "<br/>" + ex.ToString();
SendErrorEmail("Page Load Error: <br/><br/> User " + SPContext.Current.Web.CurrentUser.Name + "<br/><br/> RIW Ref:" + lblIRNo.Text + "<br/><br/>" + ex.ToString(), ErrorSubject);
}
//finally { if (objweb != null) objweb.Dispose(); }
}
protected void btnUpdateAREMergePdf_Click(object sender, EventArgs e)
{
SPWeb objweb = null;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate ()
{
using (SPSite site = new SPSite(SPContext.Current.Site.ID))
{ objweb = site.OpenWeb(); }
});
objweb.AllowUnsafeUpdates = true;
lblmsg.Text = "";
string UserName = "";//pdfPath = "",strpathSplit1 = "",strpathSplit2 = "", strpath3 = "",
int intotherfilescount = 0, intEngineersComments = 0, Satuscount = 0, WTask = 0, intimagecount = 0; //IRPagescount = 0,
//SPSecurity.RunWithElevatedPrivileges(delegate() {
// using (SPWeb objweb = SPContext.Current.Site.OpenWeb()) {
SPList objlist = objweb.Lists[PartTaskList];
//SPDocumentLibrary _objInspecRepository = objweb.Lists.TryGetList("Inspection Repository") as SPDocumentLibrary;
#region Checking the IR and Attachments count
//if (string.IsNullOrEmpty(UnitDDL.SelectedValue))
//{
// lblmsg.Text = "Not saved, Please select Unit first.";
// return;
//}
//if (string.IsNullOrEmpty(QtyTextBox.Text.Trim()))
//{
// lblmsg.Text = "Not saved, Please select Quantity first.";
// return;
//}
if (ddlcode.SelectedValue == "Select Code")
{
lblmsg.Text = "Please select code first.";
return;
}
if (CommentBox.Text == "")
{
lblmsg.Text = "Please enter final comments.";
return;
}
foreach (GridViewRow gritemcheck in grdWorkflowtasks.Rows)
{
CheckBox CheckBoxWTask = (CheckBox)gritemcheck.FindControl("CheckBoxWTask");
Label lblIDcheck = (Label)gritemcheck.FindControl("lblID");
Label lblWTStatus = (Label)gritemcheck.FindControl("lblWTStatus");
Label lblAssignedTo = (Label)gritemcheck.FindControl("lblAssignedTo");
//Label lblSeniorEngineer = (Label)gritemcheck.FindControl("lblSeniorEngineer");
CheckBoxList chkBxListcheck = (CheckBoxList)gritemcheck.FindControl("Chkattachments");
if (CheckBoxWTask.Checked)
{
WTask++;
if (lblWTStatus.Text != "Completed")
{
#region Checking whether Inspector completed his task or not.
if (UserName == "")
UserName += lblAssignedTo.Text + " ";
else
UserName += " , " + lblAssignedTo.Text + " ";
Satuscount++;
#endregion
}
else if (lblWTStatus.Text == "Completed")
{
#region Checking whether Engineer completed his task or not.
if (chkBxListcheck != null)
{
if (chkBxListcheck.Items.Count == 0)
{
SPListItem item = objlist.GetItemById(Convert.ToInt32(lblIDcheck.Text));
SPAttachmentCollection _attachments = item.Attachments;
if (_attachments != null)
{
if (_attachments.Count != 0)
{
if (UserName == "")
UserName += lblAssignedTo.Text + " ";
else
UserName += " , " + lblAssignedTo.Text + " ";
Satuscount++;
}
}
}
}
#endregion
}
if (chkBxListcheck != null)
{
foreach (System.Web.UI.WebControls.ListItem itemcheck in chkBxListcheck.Items)
{
if (itemcheck.Selected)
{
string UpperCaseFilename = itemcheck.Value.ToUpper();
intotherfilescount++;
//if (itemcheck.Value.Contains(lblIRNo.Text) && itemcheck.Value.ToUpper().Contains(".PDF"))
//{
// intonlyIRPdfcheck++;
//}
//else
if (UpperCaseFilename.Contains(".PDF")) // (itemcheck.Value.ToLower().Contains("engineer")) &&
{
intEngineersComments++;
}
else if (UpperCaseFilename.Contains(".JPG") || UpperCaseFilename.Contains(".PNG")) // (itemcheck.Value.ToLower().Contains("engineer")) &&
{
intimagecount++;
}
}
}
}
}
}
#endregion
#region Validation of counts
//string PDFpagesToInclude = rblist_PDFpagesToInclude.SelectedValue;
//if (WTask == 0)
//{
// if (PDFpagesToInclude == "CoverPageFromRIW")
// {
// lblmsg.Text = "You have chosen to include only cover page from contractor RIW, Please select at least one part task which has PDF attachments in order to close the RIW.";
// return;
// }
//}
if (Satuscount > 0)
{
lblmsg.Text = "Selected Part Task Pending from " + UserName + ". To ignore and close anyway, please unselect the open tasks.";
return;
}
//if (intEngineersComments == 0)
//{
// if (PDFpagesToInclude == "CoverPageFromRIW")
// {
// lblmsg.Text = "You have chosen to include only cover page from contractor RIW, you should select a part task PDF file.";// (OR) The file naming is wrong.";
// return;
// }
//}
#endregion
#region COMMENTED Code for Updating the IR Pdf without attachment
//if (intotherfilescount == 0)
//{
//SPDocumentLibrary DocRepositoryonlypdf = objweb.Lists.TryGetList("Repository") as SPDocumentLibrary;
////Creating Subfolder inside folder
//string subFolderUrlonlypdf = SPContext.Current.Web.Url + "/Repository/ReviewedDeliverables/IR";
//SPList _listSLODonlypdf = objweb.Lists[MainList];
//string strCDSNumber = "";
//SPListItem _itemSLOD = _listSLODonlypdf.GetItemById(Convert.ToInt32(HttpContext.Current.Request.QueryString["ID"]));
//if (_itemSLOD != null)
//{
// strCDSNumber = _itemSLOD["CDSNumber"].ToString();
// var linkItem = new SPFieldUrlValue(_itemSLOD["PDFLink"].ToString());
// pdfPath = linkItem.Url;
//}
//SPListItem subFolder = null;
//string subsubFolderUrl = "";
//if (SPContext.Current.Web.GetFolder(subFolderUrlonlypdf + "/" + strCDSNumber).Exists)
//{
// subsubFolderUrl = subFolderUrlonlypdf + "/" + strCDSNumber;
//}
//else
//{
// subFolder = DocRepositoryonlypdf.Items.Add(subFolderUrlonlypdf, SPFileSystemObjectType.Folder, strCDSNumber);
// subFolder.Update();
// subsubFolderUrl = subFolderUrlonlypdf + "/" + strCDSNumber;
//}
//string subsubsubFolderUrl = "";
//if (SPContext.Current.Web.GetFolder(subFolderUrlonlypdf + "/" + strCDSNumber + "/" + lblTrade.Text).Exists)
//{
// subsubsubFolderUrl = subFolderUrlonlypdf + "/" + strCDSNumber + "/" + lblTrade.Text;
//}
//else
//{
// SPListItem subsubFolder = DocRepositoryonlypdf.Items.Add(subsubFolderUrl, SPFileSystemObjectType.Folder, lblTrade.Text);
// subsubFolder.Update();
// subsubsubFolderUrl = subFolderUrlonlypdf + "/" + strCDSNumber + "/" + lblTrade.Text;
//}
//SPFile _itemAttachmentonlypdf = objweb.GetFile(pdfPath);
//using (Stream filestream = _itemAttachmentonlypdf.OpenBinaryStream())
//{
// pdflink.Value = subsubsubFolderUrl + "/" + lblIRNo.Text + ".pdf";
// SPFile _myfinalIRonlypdf = DocRepositoryonlypdf.RootFolder.Files.Add(subsubsubFolderUrl + "/" + lblIRNo.Text + ".pdf", filestream, true);
// _myfinalIRonlypdf.Update();
// objweb.AllowUnsafeUpdates = false;
// lblmsg.Text = "";
// hyplink.NavigateUrl = pdflink.Value.Split(',')[0];
// hyplink.Text = "Download IR Document";
// lblmsg.Text = "";
// //btnUpdatePdf.Enabled = false;
// btnUpdateAREMergePdf.Visible = false;
// btnUpdateAREMergePdfNoWT.Visible = false;
// btnSign.Visible = true;
// PanelRE.Visible = true;
// btnCloseIR.Visible = false;
// //btnUpdatePdf.Visible = false;
// //btnSign.Visible = true;
// //hyplink.NavigateUrl = pdflink.Value.Split(',')[0];
// //hyplink.Text = "Download IR Document";
// //byte[] bytes = _itemAttachmentonlypdf.OpenBinary();
// //Response.Clear();
// //Response.ContentType = "application/pdf";
// //Response.OutputStream.Write(bytes, 0, bytes.Length);
// //Response.Flush();
// //Response.End();
//}
//}
//else if (intonlyIRPdfcheck == 1 && intEngineersComments > 0)
//else
//if (intEngineersComments > 0) {
#endregion
#region Code for Updating Lead Task with Pdf attachment
Label2.Text = "";
List<String> ListPdffiles = new System.Collections.Generic.List<String>();
ListPdffiles.Add(RIWItem.Attachments.UrlPrefix + RIWItem.Attachments[0]);
//if (PDFpagesToInclude == "AllPagesFromRIW")
//{
// ListPdffiles.Add(RIWItem.Attachments.UrlPrefix + RIWItem.Attachments[0]);
//}
#region Bind Images and get commented pdf attachments
//string strpathImages1 = string.Format(Pdftemplatepath + "\\tempPDFImg1_{0}.pdf", _postFix);
//string _postFix = DateTime.Now.ToString("yyyyMMddHHmmssffff");
//Create target folder
//if (!System.IO.Directory.Exists(Pdftemplatepath)) System.IO.Directory.CreateDirectory(Pdftemplatepath);
Document doc = new Document(PageSize.A4, 0, 0, 70, 60);
MemoryStream BindImagesFileStream = null;
if (intimagecount > 0)
{
//FileStream _filestream = new FileStream(strpathImages1, FileMode.Create);
BindImagesFileStream = new MemoryStream();
PdfWriter _pdfwriter = PdfWriter.GetInstance(doc, BindImagesFileStream);
doc.Open();
}
foreach (GridViewRow gritem in grdWorkflowtasks.Rows)
{
CheckBox CheckBoxWTask = (CheckBox)gritem.FindControl("CheckBoxWTask");
CheckBoxList chkBxList = (CheckBoxList)gritem.FindControl("Chkattachments");
//Label lblID = (Label)gritem.FindControl("lblID");
//Label lblAttachmentsLink = (Label)gritem.FindControl("lblAttachmentsLink");
if (CheckBoxWTask.Checked)
{
if (chkBxList != null)
{
foreach (System.Web.UI.WebControls.ListItem item in chkBxList.Items)
{
if (item.Selected)
{
//if (item.Value.ToLower().Contains("engineer") && item.Value.ToUpper().Contains(".PDF"))
if (item.Value.ToUpper().Contains(".PDF"))
{
//pdfPath = SPContext.Current.Web.Url + "/" + _objInspecRepository.Title.ToString() + "/" + "SE-" + lblID.Text + "/" + item.Value;
ListPdffiles.Add(item.Value);
}
#region Bind Images attachments
if (item.Value.ToUpper().Contains(".JPG") || item.Value.ToUpper().Contains(".PNG"))
{
doc.NewPage();
//string _output = string.Empty;
//lblmsg.Text += "objweb.Title: " + objweb.Title + " item.Value " + item.Value + "<br/>"; continue;//return;
SPFile _itemAttachment = objweb.GetFile(item.Value);
using (Stream s = _itemAttachment.OpenBinaryStream())
{
// Now image in the pdf file
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(s);
//Resize image depend upon your need
jpg.ScaleToFit(350f, 300f);
//Give space before image
jpg.SpacingBefore = 30f;
//Give some space after the image
jpg.SpacingAfter = 1f;
jpg.Alignment = Element.ALIGN_CENTER;
doc.Add(jpg); //add an image to the created pdf document
}
}
#endregion
}
}
}
}
}
if (intimagecount > 0)
{
doc.Close();
//ListPdffiles.Add(strpathImages1);
}
//if (IRPagescount > 2) ListPdffiles.Add(strpathSplit2);
#endregion
#region Apply e-Signature and Comments and Watermark and digtal Signature
#region Merge all PDFs
byte[] FinalContent;
byte[] MergedAtt = MergePDFs(ListPdffiles);
//byte[] MergedAtt = null;
using (MemoryStream outputPdfStream = new MemoryStream())//Stream outputPdfStream = new FileStream(filename3, FileMode.Create))
{
Document document = new Document();
PdfSmartCopy copy = new PdfSmartCopy(document, outputPdfStream);
document.Open();
PdfReader.unethicalreading = true;
PdfReader reader;
int n;
for (int i = 0; i < ListPdffiles.Count; i++)
{
//byte[] bytes = System.IO.File.ReadAllBytes(pdfArrayFiles[i]);
//Response.Write(ListPdffiles[i] + "<br/>");
byte[] bytes = objweb.GetFile(ListPdffiles[i]).OpenBinary();
//reader = new PdfReader(ListPdffiles[i]);
reader = new PdfReader(bytes);
n = reader.NumberOfPages;
for (int page = 0; page < n; )
{
copy.AddPage(copy.GetImportedPage(reader, ++page));
}
reader.Close();
reader.Dispose();
}
//if (ListPdffiles.Count > 0)
//{
document.Close();
document.Dispose();
copy.Close();
copy.Dispose();
MergedAtt = outputPdfStream.GetBuffer();
//outputPdfStream.Close();
//}
}
#endregion
#region CoverPage and comments location
string CommentsLocation = rblist_CommentsLoc.SelectedValue;
if (rblist_CommentsLoc.SelectedItem == null)
{
lblmsg.Text = "Please choose code and comments placement options.";
return;
}
string FormName = "", EmailBody = "", EmailSubject = "";
string BldgType = (RIWItem["InspType"] != null) ? RIWItem["InspType"].ToString().Split('#')[1] : "";
if (BldgType == "Buildings")
FormName = "RIW_BLDG";
else FormName = "OTHER_RIW";
GenericEmailTemplate(objweb, FormName, RIWItem, ref EmailBody, ref EmailSubject);
string FormBody = EmailBody; //htmlforPdfFile(objweb, LeadItem);
byte[] CRSFrom_PDFByte = PDFConvert(FormBody);
FinalContent = MergeBytePDFs(CRSFrom_PDFByte, MergedAtt);
//if (CommentsLocation == "CRSForm")
//{
// string FormBody = htmlforPdfFile(objweb, LeadItem);
// byte[] CRSFrom_PDFByte = PDFConvert(FormBody);
// FinalContent = MergeBytePDFs(CRSFrom_PDFByte, MergedAtt);
//}
//else if (CommentsLocation == "PDFAttachment")
//{
// FinalContent = ApplyESignatureWithComments(MergedAtt);
//}
//else
//{
// if (CommentsLocation == "BlankPage")
// {
// BlankCommentsForm = true;
// CommentsPage = GetPDFEmptyPage();
// CommentsPage = ApplyESignatureWithComments(CommentsPage);
// }
// else if (CommentsLocation == "CoverPageFromRIW")
// {
// CommentsPage = GetRIWCoverPage();
// CommentsPage = ApplyESignatureWithComments(CommentsPage);
// }
// FinalContent = MergeBytePDFs(CommentsPage, MergedAtt);
//}
#endregion
if (intimagecount > 0) FinalContent = MergeBytePDFs(FinalContent, BindImagesFileStream.GetBuffer());
if (ckb_ApplyWaterMark.Checked) FinalContent = ApplyWatermark(FinalContent);
//if (ckb_ApplyDigiSign.Checked)//ApplyDigitalSign
//{
// string pfxFilePath = ConfigurationManager.AppSettings["pfxFilePath"];
// string pfxFilePassword = ConfigurationManager.AppSettings["pfxFilePassword"];
// FinalContent = DarPDFSign.SignDocument(pfxFilePath, pfxFilePassword, FinalContent, "RIW Review", "DarAl Handasah", "Jeddah", true, 0, 0, 0, 0);
//}
#endregion
#region Attach Response To RIW Lead task and update
string attachName = StrFullRef + "-Commented.pdf";
//Delete old Attachement
if (LeadItem.Attachments.Count > 0)
{
try{LeadItem.Attachments.DeleteNow(attachName);}catch { }
}
LeadItem["PartComments"] = PartComments.Text;
LeadItem["Comment"] = CommentBox.Text;
LeadItem["Code"] = ddlcode.SelectedValue;
LeadItem.Attachments.Add(attachName, FinalContent); //File.ReadAllBytes(strpath3)
objweb.AllowUnsafeUpdates = true;
LeadItem.Update();// SystemUpdate(false);
HyperLinkLeadAttach.NavigateUrl = LeadItem.Attachments.UrlPrefix + attachName;
HyperLinkLeadAttach.Text = attachName;// "Download Compiled RIW Document";
embedpdfViewer.Visible = true;
embedpdfViewer.Attributes.Add("src", HyperLinkLeadAttach.NavigateUrl + "#page=1&zoom=150");
lblmsg.Text = "Success. Please review the compiled response previewed above before submiting and closing the E-Inspection Request.";
//Response.Write("<script>window.open(\"" + LeadItem.Attachments.UrlPrefix + attachName + "\");</script>");
//Response.Clear();
//Response.ContentType = "application/pdf";
//Response.AppendHeader("Content-Disposition", "inline; filename=" + attachName);
//Response.TransmitFile(LeadItem.Attachments.UrlPrefix + attachName);
//Response.End();
#endregion
SubmitCloseIR.Visible = true;
#endregion
}
catch (Exception ex)
{
lblmsg.Text = "An error occurred. Please contact your PWS system administrator" + "<br/>" + ex.ToString();
SendErrorEmail("btnUpdateAREMergePdf_Click Error: <br/><br/> User " + SPContext.Current.Web.CurrentUser.Name + "<br/><br/> Reference:" + lblIRNo.Text + "<br/> WebUrl: " + objweb.Url + "<br/><br/>" + ex.ToString(), ErrorSubject);
}
finally { objweb.Dispose(); }
}
public byte[] PDFConvert(string html)
{
PdfConverter pdfConverter = new PdfConverter();
pdfConverter.AuthenticationOptions.Username = CredentialCache.DefaultNetworkCredentials.UserName;
pdfConverter.AuthenticationOptions.Password = CredentialCache.DefaultNetworkCredentials.Password;
pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
pdfConverter.PdfDocumentOptions.PdfPageOrientation = PDFPageOrientation.Portrait;
//pdfConverter.PdfDocumentOptions.ShowHeader = true;
//pdfConverter.PdfHeaderOptions.DrawHeaderLine = false;
//pdfConverter.PdfDocumentOptions.ShowFooter = true;
//pdfConverter.PdfDocumentOptions.LeftMargin = 15;
//pdfConverter.PdfDocumentOptions.RightMargin = 15;
//pdfConverter.PdfDocumentOptions.TopMargin = -15;//20;
//pdfConverter.PdfDocumentOptions.BottomMargin = 10;// 21;
pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.NoCompression;//PdfCompressionLevel.Normal;//PdfCompressionLevel.Best; //
/*
pdfConverter.PdfDocumentOptions.FitWidth = true;
pdfConverter.PdfDocumentOptions.EmbedFonts = true;
pdfConverter.PdfDocumentOptions.GenerateSelectablePdf = true;
pdfConverter.PdfDocumentOptions.JpegCompressionEnabled = true;
pdfConverter.OptimizePdfPageBreaks = true;
pdfConverter.AvoidTextBreak = true;
pdfConverter.NavigationTimeout = 3600;