protected void TextBox1_TextChanged(object sender, EventArgs e)
    {
        ReportManager rManager = new ReportManager(ctx);

        DropDownList1.DataBind();
        if (DropDownList1.Items.Count > 0)
        {
            Report dalReport = rManager.GetByDateAndName(TestDate, DropDownList1.SelectedValue);
            if (dalReport != null)
            {
                TextBox1.Text = dalReport.TestDate.ToString("dd/MM/yyyy");
                TextBox2.Text = dalReport.PrintDate.ToString("dd/MM/yyyy");
                TextBox3.Text = dalReport.ReportNumber.ToString();
            }
            else
            {
                TextBox3.Text = string.Empty;
                TextBox2.Text = DateTime.Now.ToString("dd/MM/yyyy");
            }
        }
        if (TextBox2.Text.Trim() == "")
        {
            TextBox2.Text = DateTime.Now.ToString("dd/MM/yyyy");
        }
    }
		public void Save(Report report)
		{

			if(report.Id > 0)
			{
				report.Updated = DateTime.Now;
				repo.Update(report);
			}
			else
			{
				report.Created = DateTime.Now;
				report.Application = application;
				repo.Insert(report);
			}
		}
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        ReportManager rManager  = new ReportManager(ctx);
        Report        dalReport = rManager.GetByDateAndId(TestDate, ObjectId);

        if (dalReport != null)
        {
            TextBox1.Text = dalReport.TestDate.ToString("dd/MM/yyyy");
            TextBox2.Text = dalReport.PrintDate.ToString("dd/MM/yyyy");
            TextBox3.Text = dalReport.ReportNumber.ToString();
        }
        else
        {
            TextBox3.Text = string.Empty;
            TextBox2.Text = DateTime.Now.ToString("dd/MM/yyyy");
        }
    }
    public void CreateReport()
    {
        ReportManager rManager = new ReportManager(ctx);

        LocalReport report = new LocalReport();

        byte[] file;
        string mimeType, encoding, fileExtension;

        string[]  streams;
        Warning[] warnings;

        long   reportNumber;
        Report dalReport = rManager.GetOrCreateReport(FCCLReportType.FCB, -1
                                                      , DropDownList1.SelectedItem.Text, TestDate, PrintDate, long.TryParse(TextBox3.Text, out reportNumber) ? (long?)reportNumber : null);

        TextBox3.Text = dalReport.ReportNumber.ToString();

        ReportDataSource rds = new ReportDataSource();

        rds.Name = "MostreFabrica";

        List <MostreFabrica> mostre = MostreFabrica.GetMostreFCB(DropDownList1.SelectedValue, TextBox1.Text);

        rds.Value = mostre;
        string datatestare = TextBox1.Text;

        string datatmin      = datatestare;
        string datatmax      = datatestare;
        string datatesttitlu = datatestare;
        string dataprimirii  = "";
        string datapmin      = dataprimirii;
        string datapmax      = dataprimirii;
        string dataprimtitlu = dataprimirii;

        string combi = mostre[0].Combi;

        foreach (MostreFabrica mf in mostre)
        {
            string datamin = mf.DataTestare;
            string datamax = mf.DataTestareFinala;
            dataprimirii = mf.DataPrimirii;
            if (datapmin == "")
            {
                datapmin = dataprimirii;
            }
            if (datapmax == "")
            {
                datapmax = dataprimirii;
            }
            if (datamin != datatmin)
            {
                DateTime dt1 = new DateTime(Int32.Parse(datamin.Substring(6, 4)), Int32.Parse(datamin.Substring(3, 2)), Int32.Parse(datamin.Substring(0, 2)));
                DateTime dt2 = new DateTime(Int32.Parse(datatmin.Substring(6, 4)), Int32.Parse(datatmin.Substring(3, 2)), Int32.Parse(datatmin.Substring(0, 2)));
                if (DateTime.Compare(dt1, dt2) < 0)
                {
                    datatmin = datamin;
                }
            }
            if (datamax != datatmax)
            {
                DateTime dt1 = new DateTime(Int32.Parse(datamax.Substring(6, 4)), Int32.Parse(datamax.Substring(3, 2)), Int32.Parse(datamax.Substring(0, 2)));
                DateTime dt2 = new DateTime(Int32.Parse(datatmax.Substring(6, 4)), Int32.Parse(datatmax.Substring(3, 2)), Int32.Parse(datatmax.Substring(0, 2)));
                if (DateTime.Compare(dt1, dt2) > 0)
                {
                    datatmax = datamax;
                }
            }
            // data primirii
            if (dataprimirii != datapmin)
            {
                DateTime dt1 = new DateTime(Int32.Parse(dataprimirii.Substring(6, 4)), Int32.Parse(dataprimirii.Substring(3, 2)), Int32.Parse(dataprimirii.Substring(0, 2)));
                DateTime dt2 = new DateTime(Int32.Parse(datapmin.Substring(6, 4)), Int32.Parse(datapmin.Substring(3, 2)), Int32.Parse(datapmin.Substring(0, 2)));
                if (DateTime.Compare(dt1, dt2) < 0)
                {
                    datapmin = dataprimirii;
                }
            }
            if (dataprimirii != datapmax)
            {
                DateTime dt1 = new DateTime(Int32.Parse(dataprimirii.Substring(6, 4)), Int32.Parse(dataprimirii.Substring(3, 2)), Int32.Parse(dataprimirii.Substring(0, 2)));
                DateTime dt2 = new DateTime(Int32.Parse(datapmax.Substring(6, 4)), Int32.Parse(datapmax.Substring(3, 2)), Int32.Parse(datapmax.Substring(0, 2)));
                if (DateTime.Compare(dt1, dt2) > 0)
                {
                    datapmax = dataprimirii;
                }
            }
        }
        if (datatmin != datatmax)
        {
            datatesttitlu = datatmin + " - " + datatmax;
        }
        if (datapmin != datapmax)
        {
            dataprimtitlu = datapmin + " si " + datapmax;
        }
        else
        {
            dataprimtitlu = datapmin;
        }

        rds.Value = mostre;

        report.DataSources.Clear();
        report.DataSources.Add(rds);

        report.ReportPath = "ReportFCB4.rdlc";
        report.Refresh();

        string client = DropDownList1.SelectedValue;

        // read fabrica
        SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["fccl2ConnectionString"].ConnectionString);
        SqlCommand    cmd = new SqlCommand();

        cmd.Connection = cnn;

        cmd.CommandText = "SELECT MostreTancuri.AdresaClient,MostreTancuri.NumeClient,MostreTancuri.Localitate,MostreTancuri.Judet,MostreTancuri.NrComanda "
                          + "FROM MostreTancuri WHERE MostreTancuri.NumeClient='" + client + "'";

        cnn.Open();
        SqlDataReader reader = cmd.ExecuteReader();

        reader.Read();

        string fabricastrada = mostre[0].FabriciStrada;
        string fabricaoras   = mostre[0].FabriciOras;
        string fabricajudet  = mostre[0].FabriciJudet;
        string nrcomanda     = mostre[0].NrComanda;

        reader.Close();
        cnn.Close();
        string nrb = dalReport.ReportNumber.ToString();;
        //set report parameters
        string laborator   = ddlLaborator.Items[ddlLaborator.SelectedIndex].ToString();
        string responsabil = ddlResponsabil.Items[ddlResponsabil.SelectedIndex].ToString();

        ReportParameter pDatatestare   = new ReportParameter("datatestare", datatesttitlu);
        ReportParameter pDataprimirii  = new ReportParameter("dataprimirii", dataprimtitlu);
        ReportParameter pCombi         = new ReportParameter("combi", combi);
        ReportParameter pDatab         = new ReportParameter("datab", TextBox2.Text);
        ReportParameter pNrb           = new ReportParameter("nrb", nrb);
        ReportParameter pFabricanume   = new ReportParameter("fabricanume", client);
        ReportParameter pFabricastrada = new ReportParameter("fabricastrada", fabricastrada);
        ReportParameter pComanda       = new ReportParameter("nrcomanda", nrcomanda);
        ReportParameter pFabricaoras   = new ReportParameter("fabricaoras", fabricaoras);
        ReportParameter pFabricajudet  = new ReportParameter("fabricajudet", fabricajudet);
        ReportParameter pLaborator     = new ReportParameter("laborator", laborator);
        ReportParameter pResponsabil   = new ReportParameter("responsabil", responsabil);
        ReportParameter pVersiune      = new ReportParameter("Versiune", new SettingManager(StaticDataHelper.FCCLDbContext).GetValueByName("ReportFCB4"));

        ReportParameter[] p = { pDatatestare, pDataprimirii, pCombi, pDatab, pNrb, pFabricanume, pFabricastrada, pComanda, pFabricaoras, pFabricajudet, pLaborator, pResponsabil, pVersiune };
        report.SetParameters(p);

        file = report.Render("PDF", StaticData.DEVICE_INFO_PDF, out mimeType, out encoding, out fileExtension, out streams, out warnings);
        string httppath = StaticDataHelper.SettingsManager.CaleRapoarteHttp;
        string filepath = StaticDataHelper.SettingsManager.CaleRapoarte;

        string parse_client = replace_special_car(client);


        string raport_name  = "RaportFCB" + datatestare.Replace("/", "_") + "_" + nrb + "_" + parse_client + ".pdf";
        string raport_excel = "RaportFCB" + datatestare.Replace("/", "_") + "_" + nrb + "_" + parse_client + ".xls";

        string path_raport_http = "http://" + Request.ServerVariables.Get("HTTP_HOST") + "/" + httppath;
        string pdf_link         = path_raport_http + @"FCB/" + raport_name;
        string pdf_file         = filepath + @"FCB/" + raport_name;
        // writefile

        string excel_link = path_raport_http + @"FCB/" + raport_excel;
        string excel_file = filepath + @"FCB/" + raport_excel;

        report.SetParameters(new ReportParameter("BkImage", ""));
        File.WriteAllBytes(pdf_file, file);
        dalReport.SampleCount = mostre.Count;
        dalReport.PageCount   = PDFHelper.GetNumberOfPdfPages(pdf_file);
        rManager.Save(dalReport);
        ctx.SaveChanges();

        byte[] file_xls = report.Render("EXCEL", StaticData.DEVICE_INFO_XLS, out mimeType, out encoding, out fileExtension, out streams, out warnings);
        File.WriteAllBytes(excel_file, file_xls);

        pdflink.Visible     = true;
        pdflink.NavigateUrl = pdf_link;
        pdflink.Text        = raport_name;

        xlslink.Visible     = true;
        xlslink.NavigateUrl = excel_link;
        xlslink.Text        = raport_excel;
    }
    public void CreateReport()
    {
        Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator = ".";
        logger.Info(string.Format("GetMostreFerma|CreateReport"));

        LocalReport report = new LocalReport();

        byte[] file;
        string mimeType, encoding, fileExtension;

        string[]      streams;
        Warning[]     warnings;
        long          reportNumber;
        ReportManager rManager  = new ReportManager(ctx);
        Report        dalReport = rManager.GetOrCreateReport(FCCLReportType.Crotalii, ObjectId
                                                             , DropDownList1.SelectedItem.Text, TestDate, PrintDate, long.TryParse(TextBox3.Text, out reportNumber) ? (long?)reportNumber : null);

        TextBox3.Text = dalReport.ReportNumber.ToString();
        ReportDataSource rds = new ReportDataSource();

        rds.Name = "MostreFabrica";

        List <MostreFabrica> mostre = MostreFabrica.GetMostreFerma(DropDownList1.SelectedValue, DateTime.Parse(TextBox1.Text));

        logger.Info(string.Format("GetMostreFerma|mostre cnt:{0}", mostre.Count));
        rds.Value = mostre;
        DateTime datatestare = DateTime.Parse(TextBox1.Text);

        DateTime datatmin      = datatestare;
        DateTime datatmax      = datatestare;
        string   datatesttitlu = datatestare.ToShortDateString();

        DateTime datapmin = DateTime.MaxValue;
        DateTime datapmax = DateTime.MinValue;
        string   dataprimtitlu;

        string nrcomanda = "";
        string combi     = mostre[0].Combi;

        foreach (MostreFabrica mf in mostre)
        {
            DateTime datamin = mf.DataTestare;
            DateTime datamax = mf.DataTestareFinala;

            if (mf.NrComanda.Trim() != "")
            {
                nrcomanda = mf.NrComanda.Trim();
            }

            if (DateTime.Compare(datamin, datatmin) < 0)
            {
                datatmin = datamin;
            }

            if (DateTime.Compare(datamax, datatmax) > 0)
            {
                datatmax = datamax;
            }

            if (DateTime.Compare(mf.DataPrimirii, datapmin) < 0)
            {
                datapmin = mf.DataPrimirii;
            }

            if (DateTime.Compare(mf.DataPrimirii, datapmax) > 0)
            {
                datapmax = mf.DataPrimirii;
            }
        }

        if (datatmin != datatmax)
        {
            datatesttitlu = datatmin.ToShortDateString() + " - " + datatmax.ToShortDateString();
        }
        if (datapmin != datapmax)
        {
            dataprimtitlu = datapmin.ToShortDateString() + " si " + datapmax.ToShortDateString();
        }
        else
        {
            dataprimtitlu = datapmin.ToShortDateString();
        }

        rds.Value = mostre;

        report.DataSources.Clear();
        report.DataSources.Add(rds);


        report.ReportPath = "ReportCrotalii.rdlc";

        report.Refresh();

        string fermaid   = DropDownList1.SelectedValue;
        string fermaname = DropDownList1.Items[DropDownList1.SelectedIndex].ToString();
        // read fabrica
        SqlConnection cnn = new SqlConnection(
            ConfigurationManager.ConnectionStrings
            ["fccl2ConnectionString"].ConnectionString);
        SqlCommand cmd = new SqlCommand();

        cmd.Connection = cnn;

        cmd.CommandText = "SELECT Ferme_CCL.Cod,Ferme_CCL.Strada,Ferme_CCL.Numar,Ferme_CCL.Oras,Judete.Denloc "
                          + "FROM Ferme_CCL,Judete WHERE Ferme_CCL.ID=" + fermaid
                          + " AND Ferme_CCL.Judet=Judete.ID";
        cnn.Open();
        SqlDataReader reader = cmd.ExecuteReader();

        reader.Read();
        string fermastrada = Convert.ToString(reader["Strada"]);
        string fermanumar  = Convert.ToString(reader["Numar"]);
        string fermaoras   = Convert.ToString(reader["Oras"]);
        string fermajudet  = Convert.ToString(reader["Denloc"]);
        string fermacod    = Convert.ToString(reader["Cod"]);

        reader.Close();
        cnn.Close();


        cmd.CommandText = "SELECT Fabrici.Nume, Ferme_CCL.FabricaID from Ferme_CCL, Fabrici  "
                          + " WHERE Ferme_CCL.ID =" + fermaid + " AND Ferme_CCL.FabricaID = Fabrici.ID";
        cnn.Open();
        reader = cmd.ExecuteReader();
        reader.Read();
        string asocid   = Convert.ToString(reader["FabricaID"]);
        string asocnume = Convert.ToString(reader["Nume"]);

        reader.Close();
        cnn.Close();

        FermaName.Text = fermaname;
        FermaCod.Text  = fermacod;
        FermaId.Text   = "" + fermaid;


        string datab = TextBox2.Text;
        string nrb   = dalReport.ReportNumber.ToString();
        //set report parameters
        string laborator   = ddlLaborator.Items[ddlLaborator.SelectedIndex].ToString();
        string responsabil = ddlResponsabil.Items[ddlResponsabil.SelectedIndex].ToString();

        ReportParameter pAsocnume = new ReportParameter("asocnume", asocnume);

        ReportParameter pNrcomanda = new ReportParameter("nrcomanda", nrcomanda);

        ReportParameter pDatatestare  = new ReportParameter("datatestare", datatesttitlu);
        ReportParameter pDataprimirii = new ReportParameter("dataprimirii", dataprimtitlu);

        ReportParameter pCombi = new ReportParameter("combi", combi);

        ReportParameter pDatab = new ReportParameter("datab", TextBox2.Text);
        ReportParameter pNrb   = new ReportParameter("nrb", nrb);

        ReportParameter pFermanume   = new ReportParameter("fabricanume", fermaname);
        ReportParameter pFermastrada = new ReportParameter("fabricastrada", fermastrada);
        ReportParameter pFermanumar  = new ReportParameter("fabricanumar", fermanumar);
        ReportParameter pFermaoras   = new ReportParameter("fabricaoras", fermaoras);
        ReportParameter pFermajudet  = new ReportParameter("fabricajudet", fermajudet);

        ReportParameter pLaborator = new ReportParameter("laborator", laborator);

        ReportParameter pResponsabil = new ReportParameter("responsabil", responsabil);

        ReportParameter pVersiune = new ReportParameter("Versiune", new SettingManager(StaticDataHelper.FCCLDbContext).GetValueByName("ReportCrotalii"));

        ReportParameter[] p = { pDatatestare, pDataprimirii, pCombi, pNrcomanda, pDatab, pNrb, pFermanume, pFermastrada, pFermanumar, pFermaoras, pFermajudet, pAsocnume, pLaborator
                                ,             pResponsabil,  pVersiune };
        report.SetParameters(p);


        file = report.Render("PDF", StaticData.DEVICE_INFO_PDF, out mimeType, out encoding, out fileExtension, out streams, out warnings);

        string httppath = StaticDataHelper.SettingsManager.CaleRapoarteHttp;
        string filepath = StaticDataHelper.SettingsManager.CaleRapoarte;

        fermaname = replace_special_car_null(fermaname);
        string nrcom = nrcomanda.Replace("/", "_");

        nrcom = nrcom.Replace(".", "");
        string raport_name  = "Raport" + nrcom + "-" + fermaname + "_" + fermacod + "-" + datatestare.ToShortDateString().Replace("/", "") + ".pdf";
        string raport_excel = "Raport" + nrcom + "-" + fermaname + "_" + fermacod + "-" + datatestare.ToShortDateString().Replace("/", "") + ".xls";

        string path_raport_http = "http://" + Request.ServerVariables.Get("HTTP_HOST") + "/" + httppath;
        string pdf_link         = path_raport_http + @"Ferme/" + raport_name;
        string pdf_file         = filepath + @"Ferme/" + raport_name;
        // writefile

        string excel_link = path_raport_http + @"Ferme/" + raport_excel;
        string excel_file = filepath + @"Ferme/" + raport_excel;

        //	Trace.Write(pdf_file);
        File.WriteAllBytes(pdf_file, file);
        logger.Info(string.Format("GetMostreFerma|pdf done"));

        dalReport.SampleCount = mostre.Count;
        dalReport.PageCount   = PDFHelper.GetNumberOfPdfPages(pdf_file);
        rManager.Save(dalReport);
        ctx.SaveChanges();
        logger.Info(string.Format("GetMostreFerma|saved report"));

        // raport excel
        LocalReport rapexcel = new LocalReport();

        ReportDataSource rdse = new ReportDataSource();

        rdse.Name = "MostreFabrica";

        rdse.Value = mostre;

        rapexcel.DataSources.Clear();
        rapexcel.DataSources.Add(rdse);


        rapexcel.ReportPath = "ReportCrotalii.rdlc";

        rapexcel.SetParameters(p);

        rapexcel.Refresh();

        rapexcel.SetParameters(new ReportParameter("BkImage", ""));
        byte[] file_xls = rapexcel.Render("EXCEL", StaticData.DEVICE_INFO_XLS, out mimeType, out encoding, out fileExtension, out streams, out warnings);
        // end raport excel
        File.WriteAllBytes(excel_file, file_xls);
        logger.Info(string.Format("GetMostreFerma|excel done"));

        int firstyear;

        if (int.TryParse(ConfigurationManager.AppSettings["firstyear"], out firstyear))
        {
            // test rep. portal
            SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
            SqlCommand    cmda       = new SqlCommand("Select aspnet_Users.UserName from aspnet_users join usersinformation on aspnet_Users.userid = usersinformation.userid where usersinformation.asocid=" + asocid, connection);
            connection.Open();
            string username = "";
            using (SqlDataReader rdr = cmda.ExecuteReader())
            {
                if (rdr.Read())
                {
                    username = rdr["UserName"].ToString();
                }

                rdr.Close();
            }
            connection.Close();
            if (username.Length > 0)
            {
                try
                {
                    MembershipUser User = Membership.Providers["PortalProvider"].GetUser(username, false);

                    Username.Text = User.UserName;
                    //Start generating from test date
                    for (int year = firstyear; year <= DateTime.Now.Year; year++)
                    {
                        logger.Info(string.Format("GetMostreFerma|ext call year:{0}", year));
                        CreateReportExt(year);
                    }
                }
                catch { }
            }
        }


        string raport_csv = "CSV_Registru_" + datatestare.ToShortDateString().Replace("/", "") + "_" + fermaid + "_" + fermaname + ".csv";
        string csv_link   = path_raport_http + @"Registru/" + raport_csv;
        string csv_file   = filepath + @"Registru/" + raport_csv;

        logger.Info(string.Format("CreateReportExt|write csv file {0}", csv_file));
        CreateExcelFile(mostre, csv_file);

        logger.Info(string.Format("GetMostreFerma|processing done"));

        pdflink.Visible     = true;
        pdflink.NavigateUrl = pdf_link;
        pdflink.Text        = raport_name;

        xlslink.Visible     = true;
        xlslink.NavigateUrl = excel_link;
        xlslink.Text        = raport_excel;

        csvlink.Visible     = true;
        csvlink.NavigateUrl = csv_link;
        csvlink.Text        = raport_csv;
    }
    public void CreateReport()
    {
        ReportManager rManager = new ReportManager(ctx);
        DateTime      testDate;
        int           farmId;

        DateTime.TryParse(TextBox1.Text, out testDate);
        Int32.TryParse(DropDownList1.SelectedValue, out farmId);

        Report b     = rManager.GetByDateAndId(testDate, farmId);
        string nrb   = b.ReportNumber.ToString();
        string datab = b.TestDate.ToShortDateString();
        int    pos   = 0;

        LocalReport report = new LocalReport();

        byte[] file;
        string mimeType, encoding, fileExtension;

        string[]  streams;
        Warning[] warnings;

        string fabricaid   = DropDownList1.SelectedValue;
        string fabricaname = DropDownList1.Items[DropDownList1.SelectedIndex].ToString();
        // read fabrica
        SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["fccl2ConnectionString"].ConnectionString);
        SqlCommand    cmd = new SqlCommand();

        cmd.Connection = cnn;

        cmd.CommandText = "SELECT Fabrici.Strada,Fabrici.Numar,Fabrici.Oras,Judete.Denloc "
                          + "FROM Fabrici,Judete WHERE Fabrici.ID=" + fabricaid + " AND Fabrici.Judet=Judete.ID";
        cnn.Open();
        SqlDataReader reader = cmd.ExecuteReader();

        reader.Read();
        string fabricastrada = Convert.ToString(reader["Strada"]);
        string fabricanumar  = Convert.ToString(reader["Numar"]);
        string fabricaoras   = Convert.ToString(reader["Oras"]);
        string fabricajudet  = Convert.ToString(reader["Denloc"]);

        reader.Close();
        cnn.Close();
        string datatestare = TextBox1.Text;
        // date fabrica

        //deviceinfo

        string deviceInfo =
            "<DeviceInfo>" +
            "  <OutputFormat>PDF</OutputFormat>" +
            "  <PageWidth>29.7cm</PageWidth>" +
            "  <PageHeight>21cm</PageHeight>" +
            "  <MarginTop>0.0cm</MarginTop>" +
            "  <MarginLeft>0.5cm</MarginLeft>" +
            "  <MarginRight>0.5cm</MarginRight>" +
            "  <MarginBottom>0.5cm</MarginBottom>" +
            "</DeviceInfo>";

        string httppath = StaticDataHelper.SettingsManager.CaleRapoarteHttp;
        string filepath = StaticDataHelper.SettingsManager.CaleRapoarte;

        cmd.CommandTimeout = 300;
        cmd.CommandText    = "SELECT DISTINCT Ferme_CCL.Nume,Ferme_CCL.ID, MostreTancuri.FermaID,  Ferme_CCL.Cod, "
                             + "Ferme_CCL.Strada,Ferme_CCL.Numar, Ferme_CCL.Oras, Ferme_CCL.Judet,Ferme_CCL.PersonaDeContact,Ferme_CCL.TelPersoanaContact,Ferme_CCL.Ferme_CCL,Ferme_CCL.FermierID,Judete.Denloc "
                             + " FROM MostreTancuri, Ferme_CCL INNER JOIN JUDETE ON  Convert(int,Ferme_CCL.Judet,2)=Judete.ID WHERE"
                             + " CONVERT(datetime, MostreTancuri.DataTestareFinala, 103) = CONVERT(datetime, '" + datatestare + "', 103) "
                             + " AND MostreTancuri.CodFerma = Ferme_CCL.Cod " + " AND Ferme_CCL.FabricaID = " + fabricaid
                             + " AND MostreTancuri.Validat = 1 ORDER BY Ferme_CCL.Nume";

        cnn.Open();
        SqlDataReader drferme = cmd.ExecuteReader();
        //prepare report parameters
        string laborator   = ddlLaborator.Items[ddlLaborator.SelectedIndex].ToString();
        string responsabil = ddlResponsabil.Items[ddlResponsabil.SelectedIndex].ToString();
        string semnlab     = ddlLaborator.SelectedValue;
        string semnresp    = ddlResponsabil.SelectedValue;

        semnresp = semnresp.Substring(0, semnresp.LastIndexOf("."));
        semnlab  = semnlab.Substring(0, semnlab.LastIndexOf("."));
        semnresp = semnresp.ToLower();
        semnlab  = semnlab.ToLower();

        ReportParameter pDatatestare   = new ReportParameter("datatestare", datatestare);
        ReportParameter pDatab         = new ReportParameter("datab", datab);
        ReportParameter pNrb           = new ReportParameter("nrb", nrb);
        ReportParameter pFabricanume   = new ReportParameter("fabricanume", fabricaname);
        ReportParameter pFabricastrada = new ReportParameter("fabricastrada", fabricastrada);
        ReportParameter pFabricanumar  = new ReportParameter("fabricanumar", fabricanumar);
        ReportParameter pFabricaoras   = new ReportParameter("fabricaoras", fabricaoras);
        ReportParameter pFabricajudet  = new ReportParameter("fabricajudet", fabricajudet);
        ReportParameter pLaborator     = new ReportParameter("laborator", laborator);
        ReportParameter pResponsabil   = new ReportParameter("responsabil", responsabil);

        List <FileLinks> list = new List <FileLinks>();

        while (drferme.Read())
        {
            FileLinks filelink         = new FileLinks();
            string    fermacod         = Convert.ToString(drferme["Cod"]);
            string    fermanume        = Convert.ToString(drferme["Nume"]);
            string    fermastrada      = Convert.ToString(drferme["Strada"]);
            string    fermanumar       = Convert.ToString(drferme["Numar"]);
            string    fermaoras        = Convert.ToString(drferme["Oras"]);
            string    judet            = Convert.ToString(drferme["Denloc"]);
            string    codferma         = Convert.ToString(drferme["Cod"]);
            string    fermaadresa      = "Str. " + fermastrada + " nr. " + fermanumar + ", " + fermaoras;
            string    fermatelcontact  = Convert.ToString(drferme["TelPersoanaContact"]);
            string    fermaperscontact = Convert.ToString(drferme["PersonaDeContact"]);

            ReportDataSource rds = new ReportDataSource();
            rds.Name = "MostreFabrica";
            List <MostreFabrica> mostre = MostreFabrica.GetMostreFerma(fabricaid, fermacod, datatestare);
            rds.Value = mostre;
            // build dates interval
            string datatmin      = datatestare;
            string datatmax      = datatestare;
            string datatesttitlu = datatestare;

            string dataprimirii  = "";
            string datapmin      = dataprimirii;
            string datapmax      = dataprimirii;
            string dataprimtitlu = dataprimirii;

            string combi = mostre[0].Combi;

            foreach (MostreFabrica mf in mostre)
            {
                string datamin = mf.DataTestare;
                string datamax = mf.DataTestareFinala;
                dataprimirii = mf.DataPrimirii;
                if (datapmin == "")
                {
                    datapmin = dataprimirii;
                }
                if (datapmax == "")
                {
                    datapmax = dataprimirii;
                }

                if (datamin != datatmin)
                {
                    DateTime dt1 = new DateTime(Int32.Parse(datamin.Substring(6, 4)), Int32.Parse(datamin.Substring(3, 2)), Int32.Parse(datamin.Substring(0, 2)));
                    DateTime dt2 = new DateTime(Int32.Parse(datatmin.Substring(6, 4)), Int32.Parse(datatmin.Substring(3, 2)), Int32.Parse(datatmin.Substring(0, 2)));
                    if (DateTime.Compare(dt1, dt2) < 0)
                    {
                        datatmin = datamin;
                    }
                }
                if (datamax != datatmax)
                {
                    DateTime dt1 = new DateTime(Int32.Parse(datamax.Substring(6, 4)), Int32.Parse(datamax.Substring(3, 2)), Int32.Parse(datamax.Substring(0, 2)));
                    DateTime dt2 = new DateTime(Int32.Parse(datatmax.Substring(6, 4)), Int32.Parse(datatmax.Substring(3, 2)), Int32.Parse(datatmax.Substring(0, 2)));
                    if (DateTime.Compare(dt1, dt2) > 0)
                    {
                        datatmax = datamax;
                    }
                }
                // data primirii
                if (dataprimirii != datapmin)
                {
                    DateTime dt1 = new DateTime(Int32.Parse(dataprimirii.Substring(6, 4)), Int32.Parse(dataprimirii.Substring(3, 2)), Int32.Parse(dataprimirii.Substring(0, 2)));
                    DateTime dt2 = new DateTime(Int32.Parse(datapmin.Substring(6, 4)), Int32.Parse(datapmin.Substring(3, 2)), Int32.Parse(datapmin.Substring(0, 2)));
                    if (DateTime.Compare(dt1, dt2) < 0)
                    {
                        datapmin = dataprimirii;
                    }
                }
                if (dataprimirii != datapmax)
                {
                    DateTime dt1 = new DateTime(Int32.Parse(dataprimirii.Substring(6, 4)), Int32.Parse(dataprimirii.Substring(3, 2)), Int32.Parse(dataprimirii.Substring(0, 2)));
                    DateTime dt2 = new DateTime(Int32.Parse(datapmax.Substring(6, 4)), Int32.Parse(datapmax.Substring(3, 2)), Int32.Parse(datapmax.Substring(0, 2)));
                    if (DateTime.Compare(dt1, dt2) > 0)
                    {
                        datapmax = dataprimirii;
                    }
                }
            }
            if (datatmin != datatmax)
            {
                datatesttitlu = datatmin + " - " + datatmax;
            }
            if (datapmin != datapmax)
            {
                dataprimtitlu = datapmin + " si " + datapmax;
            }
            else
            {
                dataprimtitlu = datapmin;
            }

            // end dates interval
            report.DataSources.Clear();
            report.DataSources.Add(rds);

            pos++;
            report.ReportPath = "ReportFerme4.rdlc";

            report.Refresh();

            ReportParameter pDatatitlu        = new ReportParameter("datatestare", datatesttitlu);
            ReportParameter pDataprimirii     = new ReportParameter("dataprimirii", dataprimtitlu);
            ReportParameter pCombi            = new ReportParameter("combi", combi);
            ReportParameter pPos              = new ReportParameter("pos", pos.ToString());
            ReportParameter pCodferma         = new ReportParameter("codferma", codferma);
            ReportParameter pFermanume        = new ReportParameter("fermanume", fermanume);
            ReportParameter pFermaadresa      = new ReportParameter("fermaadresa", fermaadresa);
            ReportParameter pFermajudet       = new ReportParameter("fermajudet", judet);
            ReportParameter pFermaperscontact = new ReportParameter("fermaperscontact", fermaperscontact);
            ReportParameter pFermatelcontact  = new ReportParameter("fermatelcontact", fermatelcontact);
            ReportParameter versiuneRaport    = new ReportParameter("Versiune", new SettingManager(StaticDataHelper.FCCLDbContext).GetValueByName("ReportFerme4"));

            ReportParameter[] p = { pDatatitlu, pDataprimirii, pCombi,       pDatab,      pNrb,      pFabricanume,      pFabricastrada,   pFabricanumar, pFabricaoras, pFabricajudet, pLaborator, pResponsabil,
                                    pPos,       pFermanume,    pFermaadresa, pFermajudet, pCodferma, pFermaperscontact, pFermatelcontact, versiuneRaport };

            report.SetParameters(p);

            file = report.Render("PDF", deviceInfo, out mimeType, out encoding, out fileExtension, out streams, out warnings);
            // read from date fixe!!!

            fermanume = replace_special_car_null(fermanume);

            string raport_name  = "RaportFerma" + datatestare.Replace("/", "_") + "_" + fermacod + "-" + fermanume + ".pdf";
            string raport_excel = "RaportFerma" + datatestare.Replace("/", "_") + "_" + fermacod + "-" + fermanume + ".xls";

            string path_raport_http = "http://" + Request.ServerVariables.Get("HTTP_HOST") + "/" + httppath;
            string pdf_link         = path_raport_http + @"Ferme/" + raport_name;
            string pdf_file         = filepath + @"Ferme/" + raport_name;
            File.WriteAllBytes(pdf_file, file);

            filelink.Url = pdf_link;
            filelink.Des = raport_name;
            list.Add(filelink);
        }

        drferme.Close();
        cnn.Close();
        //raport cumulat
        LocalReport      report_cum = new LocalReport();
        ReportDataSource rdsc       = new ReportDataSource();

        rdsc.Name  = "MostreFabrica1";
        rdsc.Value = MostreFabrica.GetMostreFabrica(fabricaid, datatestare);

        report_cum.DataSources.Clear();
        report_cum.DataSources.Add(rdsc);

        report_cum.ReportPath = "ReportCumulat4.rdlc";
        report_cum.Refresh();

        ReportParameter pSemnlab        = new ReportParameter("semnlab", semnlab);
        ReportParameter pSemnresp       = new ReportParameter("semnresp", semnresp);
        ReportParameter pVersiuneRaport = new ReportParameter("Versiune", new SettingManager(StaticDataHelper.FCCLDbContext).GetValueByName("ReportCumulat4"));

        ReportParameter[] rp = { pDatatestare, pDatab, pNrb, pFabricanume, pFabricastrada, pFabricanumar, pFabricaoras, pFabricajudet, pLaborator, pResponsabil, pSemnlab, pSemnresp, pVersiuneRaport };

        report_cum.SetParameters(rp);

        byte[] file_cum    = report_cum.Render("PDF", deviceInfo, out mimeType, out encoding, out fileExtension, out streams, out warnings);
        string fabricanume = replace_special_car_null(fabricaname);

        string raport_name_cum = "RaportCumulat" + datatestare.Replace("/", "_") + "_" + fabricaid + "-" + fabricanume + ".pdf";

        string path_raport_http_cum = "http://" + Request.ServerVariables.Get("HTTP_HOST") + "/" + httppath;
        string pdf_link_cum         = path_raport_http_cum + @"Ferme/" + raport_name_cum;
        string pdf_file_cum         = filepath + @"Ferme/" + raport_name_cum;

        // writefile

        File.WriteAllBytes(pdf_file_cum, file_cum);
        linkall.Visible     = true;
        linkall.NavigateUrl = pdf_link_cum;
        linkall.Text        = raport_name_cum;
        //
        Repeater1.DataSource = list;
        Repeater1.DataBind();
        Repeater1.Visible = true;
    }