-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDefault.aspx.cs
1293 lines (1139 loc) · 50.3 KB
/
Default.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 Newtonsoft.Json;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Gff3_tools
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial; // Imposta il contesto di licenza su NonCommercial
List<BioTizio> dati = Session["data"] as List<BioTizio>;
if (dati != null)
{
if (Session["contiene"] != null)
{
valoriContiene.Value = Session["contiene"].ToString();
}
if (Session["noncontiene"] != null)
{
valoriNonContiene.Value = Session["noncontiene"].ToString();
}
aggiornaTabella(impostaFiltri());
}
visualizzaFileCaricato();
ImpostaVisibilitaBottoni();
}
}
private void ImpostaVisibilitaBottoni()
{
if (Session["data"] == null)
{
divFileAggiuntivi.Visible = false;
CardEsportazione.Visible = false;
CardFiltri.Visible = false;
}
else
{
List<BioTizio> dati = Session["data"] as List<BioTizio>;
divFileAggiuntivi.Visible = true;
CardEsportazione.Visible = true;
CardFiltri.Visible = true;
btnEsportaCds.Visible = dati.Any(x => !String.IsNullOrWhiteSpace(x.CDS));
}
}
protected void ImportGff3Files(object sender, EventArgs e)
{
//Create a DataTable.
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[12] {
new DataColumn("File", typeof(string)),
new DataColumn("Fasta", typeof(string)),
new DataColumn("CDS", typeof(string)),
new DataColumn("Sequid", typeof(string)),
new DataColumn("Source", typeof(string)),
new DataColumn("Type", typeof(string)),
new DataColumn("Start", typeof(string)),
new DataColumn("End", typeof(string)),
new DataColumn("Score", typeof(string)),
new DataColumn("Strand", typeof(string)),
new DataColumn("Phase", typeof(string)),
new DataColumn("Attributes",typeof(string)) });
var listaTizi = new List<BioTizio>();
//Read the contents of CSV file.
//string csvPath;
//using (StreamReader inputStreamReader = new StreamReader(fileCaricato.PostedFile.InputStream))
//{
// csvPath = inputStreamReader.ReadToEnd();
//}
var listaFile = new List<string>();
if (fileCaricato.HasFiles)
{
foreach (HttpPostedFile uploadedFile in fileCaricato.PostedFiles)
{
listaFile.Add(Path.ChangeExtension(uploadedFile.FileName, null));
StreamReader inputStreamReader = new StreamReader(uploadedFile.InputStream);
string streamFile = inputStreamReader.ReadToEnd();
//Execute a loop over the rows.
foreach (string row in streamFile.Split('\n'))
{
// Se la riga non è vuota e non è un commento la aggiungo
if (!string.IsNullOrEmpty(row) && !row.StartsWith("#"))
{
var tizio = new BioTizio();
tizio.File = uploadedFile.FileName;
tizio.Fasta = "";
int i = 0;
//Execute a loop over the columns.
foreach (string cell in row.Split('\t'))
{
if (i == 0)
{
tizio.Sequid = cell;
}
else if (i == 1)
{
tizio.Source = cell;
}
else if (i == 2)
{
tizio.Type = cell;
}
else if (i == 3)
{
tizio.Start = cell;
}
else if (i == 4)
{
tizio.End = cell;
}
else if (i == 5)
{
tizio.Score = cell;
}
else if (i == 6)
{
tizio.Strand = cell;
}
else if (i == 7)
{
tizio.Phase = cell;
}
else if (i == 8)
{
tizio.Attributes = cell.Split(';');
}
i++;
}
listaTizi.Add(tizio);
}
}
}
}
Session["nomeFile"] = listaFile;
Session["data"] = listaTizi;
//Bind the DataTable.
aggiornaTabella(listaTizi);
visualizzaFileCaricato();
ImpostaVisibilitaBottoni();
}
public List<SearchResult> SearchSamplesIMicrobe(string valoreDaRicercare)
{
int tentativi = 3;
try
{
if(tentativi > 0)
{
tentativi--;
return APISearchSamplesIMicrobe(valoreDaRicercare);
}
else
{
return null;
}
}
catch
{
if(tentativi > 0)
{
tentativi--;
return APISearchSamplesIMicrobe(valoreDaRicercare);
}
else
{
return null;
}
}
}
public List<SearchResult> APISearchSamplesIMicrobe(string valoreDaRicercare)
{
string api = $"https://www.imicrobe.us/api/v1/search/{valoreDaRicercare}";
var request = (HttpWebRequest)WebRequest.Create(api);
try
{
request.Timeout = 5000;
request.ContentType = "application/json";
request.Method = "GET";
WebResponse response = request.GetResponse() as HttpWebResponse;
var stream = response.GetResponseStream();
StreamReader reader2 = new StreamReader(stream);
// Leggo la risposta.
string stringaRisultato = reader2.ReadToEnd();
if (String.IsNullOrWhiteSpace(stringaRisultato))
{
return null;
}
else
{
var risultati = JsonConvert.DeserializeObject<List<SearchResult>>(stringaRisultato);
return risultati != null ? risultati.Where(x => x.table_name == "sample").ToList() : null;
}
}
catch
{
request.Abort();
return null;
}
}
public RootSample GetSampleInfoIMicrobe(int id)
{
try
{
return APISampleInfoIMicrobe(id);
}
catch
{
return APISampleInfoIMicrobe(id);
}
}
public RootSample APISampleInfoIMicrobe(int id)
{
try
{
string api = $"https://www.imicrobe.us/api/v1/samples/{id}";
var request = (HttpWebRequest)WebRequest.Create(api);
request.ContentType = "application/json";
request.Method = "GET";
WebResponse response = request.GetResponse() as HttpWebResponse;
var stream = response.GetResponseStream();
StreamReader reader2 = new StreamReader(stream);
// Leggo la risposta.
string stringaRisultato = reader2.ReadToEnd();
if (String.IsNullOrWhiteSpace(stringaRisultato))
{
return null;
}
else
{
var sample = JsonConvert.DeserializeObject<RootSample>(stringaRisultato);
return sample;
}
}
catch
{
throw;
}
}
protected void ImportFasta(object sender, EventArgs e)
{
List<BioTizio> dati = Session["data"] as List<BioTizio>;
var arrayRigheSelezionate = GetRigheSelezionate();
var listaFiltrata = impostaFiltri();
var datiOrdinati = OrdinaTabella(listaFiltrata);
var datiFiltrati = arrayRigheSelezionate.Length == 0 ? datiOrdinati : FiltraListaPerSelezionati(datiOrdinati, arrayRigheSelezionate);
var listaFile = new List<string>();
List<string> cdsFound = new List<string>();
if (fileCaricatoFasta.HasFiles)
{
var listaSequid = datiFiltrati.Select(x => x.Sequid).Distinct().Select(x => new RicercaSequid { sequid = x, Trovato = false }).ToList();
foreach (HttpPostedFile uploadedFile in fileCaricatoFasta.PostedFiles)
{
using (StreamReader reader = new StreamReader(uploadedFile.InputStream))
{
string line;
bool keywordFound = false; // Flag per indicare se la parola chiave corrente è stata trovata nel file corrente
string cds = "";
string sequidFound = "";
while ((line = reader.ReadLine()) != null && listaSequid.Any(x => !x.Trovato))
{
if (line.StartsWith(">"))
{
if (keywordFound)
{
foreach (var dato in dati)
if (dato.Sequid.Contains(sequidFound))
{
dato.Fasta = cds;
}
cds = "";
sequidFound = "";
}
keywordFound = false;
var split = line.Split('|');
string sequid = $"{split[2]}|{split[3]}";
// verifico se la riga che sto controllando è quella del sequid e se il sequid è nella mia lista
if (listaSequid.Any(s => s.sequid.StartsWith(sequid)))
{
sequidFound = sequid;
cds += line;
keywordFound = true;
foreach (var seq in listaSequid)
if (seq.sequid == sequid)
seq.Trovato = true;
}
}
else if (keywordFound)
{
cds += line;
}
// Break the loop if the delimiter is found in the line
if (listaSequid.All(x => x.Trovato))
break;
}
}
}
}
Session["data"] = dati;
//Bind the DataTable.
aggiornaTabella(impostaFiltri());
//visualizzaFileCaricato();
}
protected void ImportCDS(object sender, EventArgs e)
{
List<BioTizio> dati = Session["data"] as List<BioTizio>;
var arrayRigheSelezionate = GetRigheSelezionate();
var listaFiltrata = impostaFiltri();
var datiOrdinati = OrdinaTabella(listaFiltrata);
var datiFiltrati = arrayRigheSelezionate.Length == 0 ? datiOrdinati : FiltraListaPerSelezionati(datiOrdinati, arrayRigheSelezionate);
var listaFile = new List<string>();
List<string> cdsFound = new List<string>();
if (fileCaricatoCDS.HasFiles)
{
var listaSequid = datiFiltrati.Select(x => x.Sequid).Distinct().Select(x => new RicercaSequid{ sequid = x, Trovato = false }).ToList();
foreach (HttpPostedFile uploadedFile in fileCaricatoCDS.PostedFiles)
{
using (StreamReader reader = new StreamReader(uploadedFile.InputStream))
{
string line;
bool keywordFound = false; // Flag per indicare se la parola chiave corrente è stata trovata nel file corrente
string cds = "";
string sequidFound = "";
while ((line = reader.ReadLine()) != null && listaSequid.Any(x => !x.Trovato))
{
if (line.StartsWith(">"))
{
if (keywordFound)
{
foreach (var dato in dati)
if(dato.Sequid == sequidFound)
{
dato.CDS = cds;
}
cds = "";
sequidFound = "";
}
keywordFound = false;
// Rimuovi il carattere ">" iniziale
string trimmedInput = line.TrimStart('>');
// Trova l'indice del primo spazio in modo da rimuovere la parte successiva
int spaceIndex = trimmedInput.IndexOf(' ');
// Estrai la sottostringa fino all'indice dello spazio
string sequid = trimmedInput.Substring(0, spaceIndex);
// verifico se la riga che sto controllando è quella del sequid e se il sequid è nella mia lista
if (listaSequid.Any(s => s.sequid == sequid))
{
sequidFound = sequid;
cds += line + "\n";
keywordFound = true;
foreach (var seq in listaSequid)
if(seq.sequid == sequid)
seq.Trovato = true;
}
}
else if (keywordFound)
{
cds += line + "\n";
}
// Break the loop if the delimiter is found in the line
if (listaSequid.All(x => x.Trovato))
break;
}
}
}
}
Session["data"] = dati;
//Bind the DataTable.
aggiornaTabella(impostaFiltri());
//visualizzaFileCaricato();
ImpostaVisibilitaBottoni();
}
public void btnSearch_Click(object sender, EventArgs e)
{
aggiornaTabella(impostaFiltri());
}
public List<BioTizio> impostaFiltri()
{
List<BioTizio> dati = Session["data"] as List<BioTizio>;
if (dati != null)
{
var contiene = valoriContiene.Value;
var noncontiene = valoriNonContiene.Value;
var colAttive = impostaColonneRicerca();
IEnumerable<BioTizio> query = dati;
//(prova as DataTable).DefaultView.RowFilter = string.Format("Attributes = '{0}'", txtRicerca.Text);
if (contiene != "")
{
Session["contiene"] = contiene;
var listaParole = contiene.Split(';');
int conteggioParole = listaParole.Count();
foreach (var parola in listaParole)
{
query =
query.Where(x =>
colAttive.inFile && x.File.ToLower().Contains(parola.ToLower()) ||
colAttive.inAttributes && x.Attributes.Any(y => y.ToLower().Contains(parola.ToLower())) ||
colAttive.inSequid && x.Sequid.ToLower().Contains(parola.ToLower()) ||
colAttive.inSource && x.Source.ToLower().Contains(parola.ToLower()) ||
colAttive.inType && x.Type.ToLower().Contains(parola.ToLower()) ||
colAttive.inStart && x.Start.ToLower().Contains(parola.ToLower()) ||
colAttive.inEnd && x.End.ToLower().Contains(parola.ToLower()) ||
colAttive.inScore && x.Score.ToLower().Contains(parola.ToLower()) ||
colAttive.inStrand && x.Strand.ToLower().Contains(parola.ToLower()) ||
colAttive.inPhase && x.Phase.ToLower().Contains(parola.ToLower())
);
}
}
if (noncontiene.Trim() != "")
{
Session["noncontiene"] = noncontiene;
var listaParole = noncontiene.Split(';');
foreach (var parola in listaParole)
{
query =
query.Where(x =>
(!colAttive.inFile || !x.File.ToLower().Contains(parola.ToLower())) &&
(!colAttive.inAttributes || !x.Attributes.Any(y => y.ToLower().Contains(parola.ToLower()))) &&
(!colAttive.inSequid || !x.Sequid.ToLower().Contains(parola.ToLower())) &&
(!colAttive.inSource || !x.Source.ToLower().Contains(parola.ToLower())) &&
(!colAttive.inType || !x.Type.ToLower().Contains(parola.ToLower())) &&
(!colAttive.inStart || !x.Start.ToLower().Contains(parola.ToLower())) &&
(!colAttive.inEnd || !x.End.ToLower().Contains(parola.ToLower())) &&
(!colAttive.inScore || !x.Score.ToLower().Contains(parola.ToLower())) &&
(!colAttive.inStrand || !x.Strand.ToLower().Contains(parola.ToLower())) &&
(!colAttive.inPhase || !x.Phase.ToLower().Contains(parola.ToLower()))
);
}
}
dati = query.ToList();
}
return dati;
}
public InColonne impostaColonneRicerca()
{
var colAttive = new InColonne();
foreach (ListItem item in cklColonne.Items)
{
if (item.Value == "File")
{
if (item.Selected) { colAttive.inFile = true; } else { colAttive.inFile = false; }
}
else if (item.Value == "Sequid")
{
if (item.Selected) { colAttive.inSequid = true; } else { colAttive.inSequid = false; }
}
else if (item.Value == "Source")
{
if (item.Selected) { colAttive.inSource = true; } else { colAttive.inSource = false; }
}
else if (item.Value == "Type")
{
if (item.Selected) { colAttive.inType = true; } else { colAttive.inType = false; }
}
else if (item.Value == "Start")
{
if (item.Selected) { colAttive.inStart = true; } else { colAttive.inStart = false; }
}
else if (item.Value == "End")
{
if (item.Selected) { colAttive.inEnd = true; } else { colAttive.inEnd = false; }
}
else if (item.Value == "Score")
{
if (item.Selected) { colAttive.inScore = true; } else { colAttive.inScore = false; }
}
else if (item.Value == "Strand")
{
if (item.Selected) { colAttive.inStrand = true; } else { colAttive.inStrand = false; }
}
else if (item.Value == "Phase")
{
if (item.Selected) { colAttive.inPhase = true; } else { colAttive.inPhase = false; }
}
else if (item.Value == "Attributes")
{
if (item.Selected) { colAttive.inAttributes = true; } else { colAttive.inAttributes = false; }
}
}
return colAttive;
}
protected void gdvBiocoso_RowDataBound(object sender, GridViewRowEventArgs e)
{
}
public void aggiornaTabella(List<BioTizio> lista)
{
if (lista != null)
{
gdvBiocoso.DataSource = lista;
gdvBiocoso.DataBind();
stato.Text = "Ci sono <strong>" + lista.Count + "</strong> risultati.";
messaggio.Text = "";
pulsantiColonne.Visible = true;
GridView grid = gdvBiocoso as GridView;
if (lista.Any(x => !String.IsNullOrWhiteSpace(x.Fasta)))
{
grid.Columns[2].Visible = true;
}
else
{
grid.Columns[2].Visible = false;
}
if (lista.Any(x => !String.IsNullOrWhiteSpace(x.CDS)))
{
grid.Columns[3].Visible = true;
}
else
{
grid.Columns[3].Visible = false;
}
}
else
{
pulsantiColonne.Visible = false;
}
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
public void visualizzaFileCaricato()
{
if (Session["nomeFile"] != null)
{
var files = Session["nomeFile"] as List<string>;
var listaSamples = new List<RootSample>();
foreach (var file in files)
{
var risultati = SearchSamplesIMicrobe(file);
var sample = risultati != null && risultati.Count == 1 ? GetSampleInfoIMicrobe(risultati.FirstOrDefault().id) : null;
if (sample != null)
{
listaSamples.Add(sample);
}
else
{
listaSamples.Add(new RootSample { sample_name = file });
}
}
repBtnModalFile.DataSource = listaSamples;
repBtnModalFile.DataBind();
btnResetFiles.Visible = true;
}
else
{
btnResetFiles.Visible = false;
}
}
//protected void btnEsportaExcel_Click(object sender, EventArgs e)
//{
// ExportGridToExcel();
//}
protected void btnEsportaGFF3_Click(object sender, EventArgs e)
{
ExportToGFF3(gdvBiocoso, "Gff3 file merged - " + DateTime.Now.ToShortDateString());
}
protected void btnEsportaCDS_Click(object sender, EventArgs e)
{
ExportToCDS(gdvBiocoso, "CDS file merged - " + DateTime.Now.ToShortDateString());
}
//private void ExportGridToExcel()
//{
// gdvBiocoso.AllowPaging = false;
// var dati = impostaFiltri();
// aggiornaTabella(dati);
// gdvBiocoso.BorderStyle = BorderStyle.Solid;
// gdvBiocoso.BorderWidth = 1;
// gdvBiocoso.BackColor = Color.WhiteSmoke;
// gdvBiocoso.GridLines = GridLines.Both;
// gdvBiocoso.Font.Name = "Verdana";
// gdvBiocoso.Font.Size = FontUnit.XXSmall;
// gdvBiocoso.HeaderStyle.BackColor = Color.DimGray;
// gdvBiocoso.HeaderStyle.ForeColor = Color.White;
// gdvBiocoso.RowStyle.HorizontalAlign = HorizontalAlign.Left;
// gdvBiocoso.RowStyle.VerticalAlign = VerticalAlign.Top;
// string FileName = "Gff3ToExcel_" + DateTime.Now + ".xls";
// HttpResponse response = HttpContext.Current.Response;
// response.Clear();
// response.Charset = "";
// response.ContentType = "application/vnd.ms-excel";
// Response.ContentEncoding = Encoding.UTF8;
// Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
// using (var sw = new StringWriter())
// {
// using (var htw = new HtmlTextWriter(sw))
// {
// gdvBiocoso.RenderControl(htw);
// response.Write(sw.ToString());
// response.End();
// gdvBiocoso.AllowPaging = true;
// var datiNuovi = impostaFiltri();
// aggiornaTabella(datiNuovi);
// }
// }
//}
protected void ExportToNewExcel_Click(object sender, EventArgs e)
{
var arrayRigheSelezionate = GetRigheSelezionate();
var dati = impostaFiltri();
var datiOrdinati = OrdinaTabella(dati);
var listaFinale = arrayRigheSelezionate.Length == 0 ? datiOrdinati : FiltraListaPerSelezionati(datiOrdinati, arrayRigheSelezionate);
if (listaFinale != null)
{
// Crea un nuovo pacchetto Excel in memoria
using (ExcelPackage package = new ExcelPackage())
{
// Crea un foglio di lavoro
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Dati");
// Riga di intestazione
int rowIndex = 1;
PropertyInfo[] properties = typeof(BioTizio).GetProperties();
for (int columnIndex = 1; columnIndex <= properties.Length; columnIndex++)
{
PropertyInfo property = properties[columnIndex - 1];
worksheet.Cells[rowIndex, columnIndex].Value = property.Name;
}
// Riempimento dei dati
rowIndex = 2;
foreach (BioTizio bioTizio in listaFinale)
{
for (int columnIndex = 1; columnIndex <= properties.Length; columnIndex++)
{
PropertyInfo property = properties[columnIndex - 1];
object value = property.GetValue(bioTizio);
if (property.Name == "Attributes")
{
// Gestisci la colonna "Attributes"
string attributesString = string.Join(", ", (string[])value);
worksheet.Cells[rowIndex, columnIndex].Value = attributesString;
}
else
{
worksheet.Cells[rowIndex, columnIndex].Value = value != null ? value.ToString() : string.Empty;
}
}
rowIndex++;
}
// Auto-dimensiona le colonne
worksheet.Cells.AutoFitColumns();
// Converti il pacchetto Excel in un array di byte
byte[] excelBytes = package.GetAsByteArray();
// Invia il file come download al client
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=Dati.xlsx");
HttpContext.Current.Response.BinaryWrite(excelBytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
}
}
protected int[] GetRigheSelezionate()
{
List<int> selectedRowIndexes = new List<int>();
foreach (GridViewRow row in gdvBiocoso.Rows)
{
CheckBox checkBox = row.FindControl("chkSelezione") as CheckBox;
if (checkBox != null && checkBox.Checked)
{
int rowIndex = row.RowIndex;
selectedRowIndexes.Add(rowIndex);
}
}
// Salva gli indici delle colonne selezionate in un array o in un'altra struttura dati
int[] selectedRowsArray = selectedRowIndexes.ToArray();
// Esegui altre operazioni con l'array degli indici delle colonne selezionate
return selectedRowsArray;
}
protected List<BioTizio> FiltraListaPerSelezionati(List<BioTizio> originalList, int[] rowIndexes)
{
List<BioTizio> filteredList = new List<BioTizio>();
for (int i = 0; i < originalList.Count; i++)
{
if (rowIndexes.Contains(i))
{
filteredList.Add(originalList[i]);
}
}
return filteredList;
}
public void ExportToGFF3(GridView gridView, string fileName)
{
var arrayRigheSelezionate = GetRigheSelezionate();
var dati = impostaFiltri();
var datiOrdinati = OrdinaTabella(dati);
var listaFinale = arrayRigheSelezionate.Length == 0 ? datiOrdinati : FiltraListaPerSelezionati(datiOrdinati, arrayRigheSelezionate);
string gff3String = "##gff-version 3\n";
if(listaFinale != null)
{
foreach(var riga in listaFinale)
{
var attributi = string.Join(";", riga.Attributes);
var stringRiga = $"{riga.Sequid}\t{riga.Source}\t{riga.Type}\t{riga.Start}\t{riga.End}\t{riga.Score}\t{riga.Strand}\t{riga.Phase}\t{attributi}\n";
gff3String += stringRiga;
}
}
using (MemoryStream ms = new MemoryStream())
{
// Conversione della stringa GFF3 in array di byte
byte[] gff3Bytes = Encoding.UTF8.GetBytes(gff3String);
// Scrittura dell'array di byte nel flusso di memoria
ms.Write(gff3Bytes, 0, gff3Bytes.Length);
// Impostazione della risposta HTTP
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "text/plain";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".gff3");
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
}
public void ExportToCDS(GridView gridView, string fileName)
{
var arrayRigheSelezionate = GetRigheSelezionate();
var dati = impostaFiltri();
var datiOrdinati = OrdinaTabella(dati);
var listaFinale = arrayRigheSelezionate.Length == 0 ? datiOrdinati : FiltraListaPerSelezionati(datiOrdinati, arrayRigheSelezionate);
var listaRighe = listaFinale.Select(x => x.CDS).Distinct().ToArray();
listaRighe = listaRighe.Where(x => !string.IsNullOrEmpty(x)).ToArray();
//for (int i = 0; i < listaRighe.Length; i++)
//{
// if (listaRighe[i].Length > 100)
// {
// string[] stringheDivise = listaRighe[i].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
// listaRighe[i] = stringheDivise[0];
// List<string> stringheAggiuntive = new List<string>(stringheDivise);
// stringheAggiuntive.RemoveAt(0);
// listaRighe = InserisciElementi(listaRighe, i + 1, stringheAggiuntive);
// }
//}
var stringaFinale = string.Join("", listaRighe);
using (MemoryStream ms = new MemoryStream())
{
// Conversione della stringa GFF3 in array di byte
byte[] CDSBytes = Encoding.UTF8.GetBytes(stringaFinale);
// Scrittura dell'array di byte nel flusso di memoria
ms.Write(CDSBytes, 0, CDSBytes.Length);
// Impostazione della risposta HTTP
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "text/plain";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".cds.fa");
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
}
public void mostraNascondiColonne(object sender, EventArgs e)
{
Button button = (Button)sender;
GridView grid = gdvBiocoso as GridView;
if (button.CommandName == "1")
{
grid.Columns[1].Visible = grid.Columns[1].Visible == true ? false : true;
aggiornaBottoni(button, grid.Columns[1].Visible);
}
else if (button.CommandName == "4")
{
grid.Columns[4].Visible = grid.Columns[4].Visible == true ? false : true;
aggiornaBottoni(button, grid.Columns[4].Visible);
}
else if (button.CommandName == "5")
{
grid.Columns[5].Visible = grid.Columns[5].Visible == true ? false : true;
aggiornaBottoni(button, grid.Columns[5].Visible);
}
else if (button.CommandName == "6")
{
grid.Columns[6].Visible = grid.Columns[6].Visible == true ? false : true;
aggiornaBottoni(button, grid.Columns[6].Visible);
}
else if (button.CommandName == "7")
{
grid.Columns[7].Visible = grid.Columns[7].Visible == true ? false : true;
aggiornaBottoni(button, grid.Columns[7].Visible);
}
else if (button.CommandName == "8")
{
grid.Columns[8].Visible = grid.Columns[8].Visible == true ? false : true;
aggiornaBottoni(button, grid.Columns[8].Visible);
}
else if (button.CommandName == "9")
{
grid.Columns[9].Visible = grid.Columns[9].Visible == true ? false : true;
aggiornaBottoni(button, grid.Columns[9].Visible);
}
else if (button.CommandName == "10")
{
grid.Columns[10].Visible = grid.Columns[10].Visible == true ? false : true;
aggiornaBottoni(button, grid.Columns[10].Visible);
}
else if (button.CommandName == "11")
{
grid.Columns[11].Visible = grid.Columns[11].Visible == true ? false : true;
aggiornaBottoni(button, grid.Columns[11].Visible);
}
else if (button.CommandName == "12")
{
grid.Columns[12].Visible = grid.Columns[12].Visible == true ? false : true;
aggiornaBottoni(button, grid.Columns[12].Visible);
}
//Bind the DataTable.
aggiornaTabella(impostaFiltri());
}
public void aggiornaBottoni(Button button, bool attivo)
{
button.CssClass = attivo ? "btn btn-success" : "btn btn-danger";
}
protected void gdvBiocoso_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gdvBiocoso.PageIndex = e.NewPageIndex;
aggiornaTabella(impostaFiltri());
}
protected void ddlNumeroRisultati_SelectedIndexChanged(object sender, EventArgs e)
{
List<BioTizio> dati = Session["data"] as List<BioTizio>;
gdvBiocoso.PageSize = Convert.ToInt32(ddlNumeroPagine.SelectedValue);
gdvBiocoso.DataSource = dati;
aggiornaTabella(impostaFiltri());
}
private void GridViewSortDirection(GridView g, GridViewSortEventArgs e, out SortDirection d, out string f)
{
f = e.SortExpression;
d = e.SortDirection;
//Check if GridView control has required Attributes
if (g.Attributes["CurrentSortField"] != null && g.Attributes["CurrentSortDir"] != null)
{
if (f == g.Attributes["CurrentSortField"])
{
d = SortDirection.Descending;
if (g.Attributes["CurrentSortDir"] == "ASC")
{
d = SortDirection.Ascending;
}
}
g.Attributes["CurrentSortField"] = f;
g.Attributes["CurrentSortDir"] = (d == SortDirection.Ascending ? "DESC" : "ASC");
impostaFiltri();
var tab = OrdinaTabella();
aggiornaTabella(tab);
}
}
public List<BioTizio> OrdinaTabella(List<BioTizio> tabella = null)
{
var ordine = gdvBiocoso.Attributes["CurrentSortField"];
var direzione =
String.IsNullOrEmpty(gdvBiocoso.Attributes["CurrentSortDir"])
? SortDirection.Ascending
: gdvBiocoso.Attributes["CurrentSortDir"] == "ASC"
? SortDirection.Ascending
: SortDirection.Descending;
tabella = tabella == null ? Session["data"] as List<BioTizio> : tabella;
if (tabella == null)
{
return null;
}
else
{
IOrderedEnumerable<BioTizio> tab = null;
if (ordine == "file")
{
tab = direzione == SortDirection.Ascending ? tabella.OrderBy(x => x.File) : tabella.OrderByDescending(x => x.File);
}