Exemplo n.º 1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                String url        = Page.Request.QueryString["url"];
                String fromMemory = Page.Request.QueryString["memory"];
                if (url != null)
                {
                    try
                    {
                        lblError.Text = "";
                        System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                        request.UseDefaultCredentials = true;

                        System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();

                        System.IO.Stream responseStream = response.GetResponseStream();

                        string fileName = Path.GetRandomFileName();

                        //new System.Drawing.Bitmap(responseStream).Save(@"C:\Digitas\" + fileName + ".tif", System.Drawing.Imaging.ImageFormat.Tiff);

                        //System.IO.Stream tbStream = File.OpenRead(@"C:\Digitas\" + fileName + ".tif");

                        decoder = new TiffBitmapDecoder(responseStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                        int pagecount = decoder.Frames.Count;


                        //lblError.Text = pagecount.ToString();
                        TiffBitmapEncoder encoderFile = new TiffBitmapEncoder();
                        images = new List <System.Drawing.Image>();

                        for (int i = 0; i < decoder.Frames.Count; i++)
                        {
                            MemoryStream      ms      = new MemoryStream();
                            TiffBitmapEncoder encoder = new TiffBitmapEncoder();
                            //ddlPaginas.Items.Add("Página " + (i + 1));
                            encoder.Frames.Add(decoder.Frames[i]);
                            encoder.Save(ms);
                            System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
                            images.Add(img);

                            MemoryStream ms3 = new MemoryStream();
                            images[i].Save(ms3, System.Drawing.Imaging.ImageFormat.Tiff);
                            System.Windows.Media.Imaging.BitmapFrame bmFrame = System.Windows.Media.Imaging.BitmapFrame.Create(ms3);
                            encoderFile.Frames.Add(bmFrame);
                        }
                        Session["images"] = images;
                        System.IO.FileStream fsTemp = new System.IO.FileStream(@"C:\Digitas\" + fileName + ".tif", FileMode.Create);
                        encoderFile.Save(fsTemp);
                        fsTemp.Close();

                        //Response.ContentType = "image/jpeg";
                        //new System.Drawing.Bitmap(responseStream).Save(@"C:\Digitas\Temp_Tiff.tif", System.Drawing.Imaging.ImageFormat.Tiff);


                        iTextSharp.text.Document      document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER, 5, 5, 5, 5);
                        iTextSharp.text.pdf.PdfWriter writer   = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(@"C:\Digitas\" + fileName + ".pdf", System.IO.FileMode.Create));

                        System.Drawing.Bitmap bm = new System.Drawing.Bitmap(@"C:\Digitas\" + fileName + ".tif");
                        int total = bm.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);

                        document.Open();

                        iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;

                        for (int k = 0; k < total; ++k)
                        {
                            bm.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k);
                            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bm, System.Drawing.Imaging.ImageFormat.Bmp);
                            // scale the image to fit in the page
                            img.ScaleAbsolute(600, 800);
                            img.SetAbsolutePosition(0, 0);
                            cb.AddImage(img);
                            document.NewPage();
                        }
                        document.Close();
                        Response.ContentType = "Application/pdf";
                        Response.TransmitFile(@"C:\Digitas\" + fileName + ".pdf");

                        /*
                         * System.Drawing.Image img = System.Drawing.Image.FromStream(responseStream);
                         *
                         * Tiff image = Tiff.ClientOpen("memory", "r", responseStream, new TiffStream());
                         *
                         * if (img == null)
                         * {
                         *  lblError.Text = "Null image s";
                         * }
                         * else
                         * {
                         *  img.Save(@"C:\Digitas\digit.tif");
                         * }
                         *
                         * if (image == null)
                         * {
                         *  lblError.Text = "Null image tiff";
                         * }
                         * else
                         * {
                         *  var num = image.NumberOfDirectories();
                         *  lblError.Text = num.ToString();
                         * }
                         */



                        /*
                         * MemoryStream ms2 = new MemoryStream();
                         * images[0].Save(ms2, System.Drawing.Imaging.ImageFormat.Jpeg);
                         * //BinaryReader br = new BinaryReader(ms2);
                         * //Byte[] bytes = br.ReadBytes((Int32)ms2.Length);
                         * byte[] bytes = ms2.ToArray();
                         * //string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
                         * string base64String = Convert.ToBase64String(bytes);
                         * //string base64String = Convert.ToBase64String((byte[])img);
                         * Image1.ImageUrl = "data:image/jpg;base64," + base64String;
                         */
                        /*
                         * Session["images"] = images;
                         *
                         *
                         * var document = new Document(PageSize.LETTER, 5, 5, 5, 5);
                         *
                         * // Create a new PdfWriter object, specifying the output stream
                         * var output = new MemoryStream();
                         * var writer = PdfWriter.GetInstance(document, output);
                         *
                         * document.Open();
                         *
                         * for (int i = 0; i < images.Count; i++)
                         * {
                         *  var image = iTextSharp.text.Image.GetInstance(images[i], iTextSharp.text.BaseColor.WHITE);
                         *  image.ScaleAbsolute(600, 800);
                         *  document.Add(image);
                         *  document.NewPage();
                         * }
                         *
                         * document.Close();
                         *
                         * Response.ContentType = "application/pdf";
                         * //Response.AddHeader("Content-Disposition", string.Format("attachment;filename=Receipt-{0}.pdf", txtOrderID.Text));
                         * Response.BinaryWrite(output.ToArray());
                         *
                         *
                         * // Open the Document for writing
                         *
                         * //img.Save(@"C:\Digitas\digit2.jpg");
                         *
                         * //Response.ContentType = "image/jpeg";
                         * //new System.Drawing.Bitmap(ms).Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                         *
                         * //HttpContext.Current.Response.Flush();
                         * //HttpContext.Current.Response.SuppressContent = true;
                         * //HttpContext.Current.ApplicationInstance.CompleteRequest();
                         *
                         * /*HttpContext.Current.Response.Flush();
                         * HttpContext.Current.Response.SuppressContent = true;
                         * HttpContext.Current.ApplicationInstance.CompleteRequest();
                         *
                         * /*FileWebRequest request = (FileWebRequest)WebRequest.Create(url);
                         *
                         * request.UseDefaultCredentials = true;
                         *
                         * System.Net.FileWebResponse response = (System.Net.FileWebResponse)request.GetResponse();*/

                        //System.IO.Stream responseStream = response.GetResponseStream();

                        /*System.IO.StreamReader reader = new StreamReader(responseStream);
                         *
                         * if (reader == null)
                         * {
                         *  lblError.Text = "Null";
                         * }
                         * else
                         * {
                         *  MemoryStream ms = new MemoryStream();
                         *  responseStream.CopyTo(ms);
                         *  /*responseStream.Close();
                         *  reader.Close();
                         *
                         *  Tiff image = Tiff.ClientOpen("memory", "r", ms, new TiffStream());
                         *
                         *  if (image == null)
                         *  {
                         *      lblError.Text = "Null image";
                         *  }
                         *  lblError.Text = ms.Length.ToString();
                         *  using (FileStream file = new FileStream(@"C:\Digitas\digit.tif", FileMode.Create, System.IO.FileAccess.Write))
                         *  {
                         *      byte[] bytes = new byte[ms.Length];
                         *      ms.Read(bytes, 0, (int)ms.Length);
                         *      file.Write(bytes, 0, bytes.Length);
                         *      //ms.Close();
                         *      //file.Close();
                         *  }
                         *
                         *  Tiff image = Tiff.Open(@"C:\Digitas\digit.tif", "r");
                         *  if (image == null)
                         *  {
                         *      lblError.Text = "Null image";
                         *  }
                         *  else
                         *  {
                         *      var num = image.NumberOfDirectories();
                         *      lblError.Text = num.ToString();
                         *  }
                         *
                         *
                         * }*/
                    }
                    catch (System.Exception ex)
                    {
                        lblError.Text = lblError.Text + " 0.- " + ex.Message;
                    }
                }
                else if (fromMemory == null)
                {
                    try
                    {
                        RPPMain.SharepointLibrary spLibrary = new RPPMain.SharepointLibrary("http://servidors04/sitios/digitalizacion", "Seccion Primera", "autostore", "Rpp1234");
                        //RPPMain.SharepointLibrary spLibrary = new RPPMain.SharepointLibrary("http://servidors04/sitios/digitalizacion", "Seccion Primera", "administrador", "Zmy45r1");

                        //int documentoID = int.Parse(Page.Request.QueryString["documentoID"]);

                        String reg_act_tomo     = Page.Request.QueryString["tomo"];
                        String reg_act_semestre = Page.Request.QueryString["semestre"];
                        String reg_act_año      = Page.Request.QueryString["anio"];
                        String reg_act_seccion  = Page.Request.QueryString["seccion"];
                        String reg_act_serie    = Page.Request.QueryString["serie"];
                        String reg_act_partida  = Page.Request.QueryString["partida"];
                        String reg_act_libro    = Page.Request.QueryString["libro"];

                        bool   firstParameter  = true;
                        bool   secondParameter = false;
                        bool   nextParameter   = false;
                        string query           = "";

                        if (reg_act_tomo.Length > 0)
                        {
                            if (firstParameter)
                            {
                                query           = query + "<And><Eq><FieldRef Name='Fec_Reg_Tomo' /><Value Type='Text'>{0}</Value></Eq>";
                                firstParameter  = false;
                                secondParameter = true;
                            }
                            else
                            {
                                if (secondParameter)
                                {
                                    query           = query + "<Eq><FieldRef Name='Fec_Reg_Tomo' /><Value Type='Text'>{0}</Value></Eq></And>";
                                    secondParameter = false;
                                    nextParameter   = true;
                                }
                                else
                                {
                                    query = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_Tomo' /><Value Type='Text'>{0}</Value></Eq></And>";
                                }
                            }
                        }

                        if (reg_act_semestre.Length > 0)
                        {
                            if (firstParameter)
                            {
                                query           = query + "<And><Eq><FieldRef Name='Fec_Reg_Semestre' /><Value Type='Text'>{1}</Value></Eq>";
                                firstParameter  = false;
                                secondParameter = true;
                            }
                            else
                            {
                                if (secondParameter)
                                {
                                    query           = query + "<Eq><FieldRef Name='Fec_Reg_Semestre' /><Value Type='Text'>{1}</Value></Eq></And>";
                                    secondParameter = false;
                                    nextParameter   = true;
                                }
                                else
                                {
                                    query = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_Semestre' /><Value Type='Text'>{1}</Value></Eq></And>";
                                }
                            }
                        }

                        if (reg_act_año.Length > 0)
                        {
                            if (firstParameter)
                            {
                                query           = query + "<And><Eq><FieldRef Name='Fec_Reg_A_x00f1_o_x0020_Semestre' /><Value Type='Text'>{2}</Value></Eq>";
                                firstParameter  = false;
                                secondParameter = true;
                            }
                            else
                            {
                                if (secondParameter)
                                {
                                    query           = query + "<Eq><FieldRef Name='Fec_Reg_A_x00f1_o_x0020_Semestre' /><Value Type='Text'>{2}</Value></Eq></And>";
                                    secondParameter = false;
                                    nextParameter   = true;
                                }
                                else
                                {
                                    query = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_A_x00f1_o_x0020_Semestre' /><Value Type='Text'>{2}</Value></Eq></And>";
                                }
                            }
                        }

                        if (reg_act_seccion.Length > 0)
                        {
                            if (firstParameter)
                            {
                                query           = query + "<And><Eq><FieldRef Name='Fec_Reg_Seccion' /><Value Type='Text'>{3}</Value></Eq>";
                                firstParameter  = false;
                                secondParameter = true;
                            }
                            else
                            {
                                if (secondParameter)
                                {
                                    query           = query + "<Eq><FieldRef Name='Fec_Reg_Seccion' /><Value Type='Text'>{3}</Value></Eq></And>";
                                    secondParameter = false;
                                    nextParameter   = true;
                                }
                                else
                                {
                                    query = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_Seccion' /><Value Type='Text'>{3}</Value></Eq></And>";
                                }
                            }
                        }

                        if (reg_act_serie.Length > 0)
                        {
                            if (firstParameter)
                            {
                                query           = query + "<And><Eq><FieldRef Name='Fec_Reg_Partida' /><Value Type='Text'>{4}</Value></Eq>";
                                firstParameter  = false;
                                secondParameter = true;
                            }
                            else
                            {
                                if (secondParameter)
                                {
                                    query           = query + "<Eq><FieldRef Name='Fec_Reg_Partida' /><Value Type='Text'>{4}</Value></Eq></And>";
                                    secondParameter = false;
                                    nextParameter   = true;
                                }
                                else
                                {
                                    query = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_Partida' /><Value Type='Text'>{4}</Value></Eq></And>";
                                }
                            }
                        }

                        if (reg_act_partida.Length > 0)
                        {
                            if (firstParameter)
                            {
                                query           = query + "<And><Eq><FieldRef Name='Partida' /><Value Type='Text'>{5}</Value></Eq>";
                                firstParameter  = false;
                                secondParameter = true;
                            }
                            else
                            {
                                if (secondParameter)
                                {
                                    query           = query + "<Eq><FieldRef Name='Partida' /><Value Type='Text'>{5}</Value></Eq></And>";
                                    secondParameter = false;
                                    nextParameter   = true;
                                }
                                else
                                {
                                    query = "<And>" + query + "<Eq><FieldRef Name='Partida' /><Value Type='Text'>{5}</Value></Eq></And>";
                                }
                            }
                        }

                        if (reg_act_libro.Length > 0)
                        {
                            if (firstParameter)
                            {
                                query           = query + "<And><Eq><FieldRef Name='Fec_Reg_Libro' /><Value Type='Text'>{6}</Value></Eq>";
                                firstParameter  = false;
                                secondParameter = true;
                            }
                            else
                            {
                                if (secondParameter)
                                {
                                    query           = query + "<Eq><FieldRef Name='Fec_Reg_Libro' /><Value Type='Text'>{6}</Value></Eq></And>";
                                    secondParameter = false;
                                    nextParameter   = true;
                                }
                                else
                                {
                                    query = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_Libro' /><Value Type='Text'>{6}</Value></Eq></And>";
                                }
                            }
                        }

                        query = "<View><Query><Where>" + query + "</Where></Query></View>";

                        query = string.Format(@"<View>
                                                <Query>
                                                    <Where>
                                                        <And>
                                                            <And>
                                                                <And>
                                                                    <And>
                                                                        <And>
                                                                            <And>
                                                                                <Eq><FieldRef Name='Fec_Reg_Tomo' /><Value Type='Text'>{0}</Value></Eq>
                                                                                <Eq><FieldRef Name='Fec_Reg_Semestre' /><Value Type='Text'>{1}</Value></Eq>
                                                                            </And>
                                                                            <Eq><FieldRef Name='Fec_Reg_A_x00f1_o_x0020_Semestre' /><Value Type='Text'>{2}</Value></Eq>
                                                                        </And>
                                                                        <Eq><FieldRef Name='Fec_Reg_Seccion' /><Value Type='Text'>{3}</Value></Eq>
                                                                    </And>
                                                                    <Eq><FieldRef Name='Fec_Reg_Partida' /><Value Type='Text'>{4}</Value></Eq>
                                                                </And>
                                                                <Eq><FieldRef Name='Partida' /><Value Type='Text'>{5}</Value></Eq>
                                                            </And>
                                                            <Eq><FieldRef Name='Fec_Reg_Libro' /><Value Type='Text'>{6}</Value></Eq>                                                            
                                                        </And>
                                                    </Where>
                                                </Query>
                                            </View>",
                                              reg_act_tomo,
                                              reg_act_semestre,
                                              reg_act_año,
                                              reg_act_seccion,
                                              reg_act_serie,
                                              reg_act_partida,
                                              reg_act_libro);


                        /*query = string.Format(@query,
                         *          reg_act_tomo,
                         *          reg_act_semestre,
                         *          reg_act_año,
                         *          reg_act_seccion,
                         *          reg_act_serie,
                         *          reg_act_partida,
                         *          reg_act_libro);*/

                        /*string query = string.Format(@"<View>
                         *                             <Query>
                         *                                 <Where>
                         *                                     <And>
                         *                                     <And>
                         *                                     <And>
                         *                                         <Eq><FieldRef Name='Fec_Reg_Libro' /><Value Type='Text'>{0}</Value></Eq>
                         *                                         <Eq><FieldRef Name='Partida' /><Value Type='Text'>{1}</Value></Eq>
                         *                                     </And>
                         *                                         <Eq><FieldRef Name='Fec_Reg_Seccion' /><Value Type='Text'>{2}</Value></Eq>
                         *                                     </And>
                         *                                         <Eq><FieldRef Name='Fec_Reg_Partida' /><Value Type='Text'>{3}</Value></Eq>
                         *                                     </And>
                         *                                 </Where>
                         *                             </Query>
                         *                         </View>",
                         *     2384,
                         *     1,
                         *     1,
                         *     "A");*/

                        System.Collections.ArrayList arlRows = spLibrary.GetLibraryItem(query);

                        if (arlRows.Count > 0)
                        {
                            lblError.Text = "";

                            Microsoft.SharePoint.Client.ListItem      itemRepositorio = (Microsoft.SharePoint.Client.ListItem)arlRows[0];
                            Dictionary <string, object>               dc   = (Dictionary <string, object>)itemRepositorio.FieldValues;
                            Microsoft.SharePoint.Client.FieldUrlValue fURl = (Microsoft.SharePoint.Client.FieldUrlValue)dc["Pagina"];

                            try
                            {
                                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(fURl.Url);
                                request.UseDefaultCredentials = true;

                                System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();

                                System.IO.Stream responseStream = response.GetResponseStream();

                                /*Response.ContentType = "image/jpeg";
                                 * new System.Drawing.Bitmap(responseStream).Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                                 *
                                 * HttpContext.Current.Response.Flush();
                                 * HttpContext.Current.Response.SuppressContent = true;
                                 * HttpContext.Current.ApplicationInstance.CompleteRequest();*/
                            }
                            catch (System.Exception ex)
                            {
                                lblError.Text = lblError.Text + " 1.- " + ex.Message;
                            }
                        }
                    }
                    catch (System.Exception ex)
                    {
                        lblError.Text = lblError.Text + " 2.- " + ex.Message;
                    }
                }
                else if (fromMemory != null)
                {
                    try
                    {
                        images = new List <System.Drawing.Image>();
                        images = (List <System.Drawing.Image>)Session["images"];

                        TiffBitmapEncoder encoder = new TiffBitmapEncoder();
                        MemoryStream      ms3     = new MemoryStream();

                        for (int i = 0; i < images.Count; i++)
                        {
                            //ddlPaginas.Items.Add("Página " + (i + 1));
                            ms3 = new MemoryStream();
                            images[i].Save(ms3, System.Drawing.Imaging.ImageFormat.Tiff);
                            System.Windows.Media.Imaging.BitmapFrame bmFrame = System.Windows.Media.Imaging.BitmapFrame.Create(ms3);
                            encoder.Frames.Add(bmFrame);
                        }

                        /*
                         * MemoryStream ms2 = new MemoryStream();
                         * images[0].Save(ms2, System.Drawing.Imaging.ImageFormat.Jpeg);
                         * byte[] bytes = ms2.ToArray();
                         * string base64String = Convert.ToBase64String(bytes);
                         * Image1.ImageUrl = "data:image/jpg;base64," + base64String;
                         *
                         * /*string fileName = Path.GetTempFileName();
                         *
                         * lblError.Text = fileName;
                         *
                         * Session["tempFileName"] = fileName;*/

                        string fileName = Path.GetRandomFileName();

                        Session["tempFileName"] = fileName + ".tif";

                        System.IO.FileStream fsTemp = new System.IO.FileStream(@"C:\Digitas\" + fileName + ".tif", FileMode.Create);
                        encoder.Save(fsTemp);
                        fsTemp.Close();



                        iTextSharp.text.Document      document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER, 5, 5, 5, 5);
                        iTextSharp.text.pdf.PdfWriter writer   = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(@"C:\Digitas\" + fileName + ".pdf", System.IO.FileMode.Create));

                        System.Drawing.Bitmap bm = new System.Drawing.Bitmap(@"C:\Digitas\" + fileName + ".tif");
                        int total = bm.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);

                        document.Open();
                        iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;
                        for (int k = 0; k < total; ++k)
                        {
                            bm.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k);
                            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bm, System.Drawing.Imaging.ImageFormat.Bmp);
                            // scale the image to fit in the page
                            img.ScaleAbsolute(600, 800);
                            img.SetAbsolutePosition(0, 0);
                            cb.AddImage(img);
                            document.NewPage();
                        }
                        document.Close();

                        Response.ContentType = "Application/pdf";
                        Response.TransmitFile(@"C:\Digitas\" + fileName + ".pdf");
                    }
                    catch (Exception exc)
                    {
                        lblError.Text = exc.Message;
                    }
                }
            }
            else
            {
                //decoder = (TiffBitmapDecoder)Session["decoder"];
                images = new List <System.Drawing.Image>();
                images = (List <System.Drawing.Image>)Session["images"];
            }
        }
Exemplo n.º 2
0
        private void btnInsertarDocumentos_Click(object sender, EventArgs e)
        {
            if (txtLibreriaSharePoint.Text == "Seleccionar...")
            {
                MessageBox.Show("Debe especificar el Repositorio de Sharepoint para la importación Documentos", "Repositorio de Sharepoint", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (txtDirectorioDocumentos.Text == "Seleccionar...")
            {
                MessageBox.Show("Debe seleccionar el directorio donde se encuentran los archivos .out para importar", "Directorio de Documentos", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (txtDirectorioDocumentos.Text == "Seleccionar...")
            {
                MessageBox.Show("Debe seleccionar el directorio donde se encuentran las imágenes .tif para importar", "Directorio de Documentos", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (!Directory.Exists(txtDirectorioDocumentos.Text))
            {
                MessageBox.Show("El directorio seleccionado para ubicación de documentos no existe, por favor verifiquelo", "Directorio Inválido", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (!Directory.Exists(txtDirectorioImagenes.Text))
            {
                MessageBox.Show("El directorio seleccionado para ubicación de imágenes no existe, por favor verifiquelo", "Directorio Inválido", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            RPPMain.SharepointLibrary spLibrary = null;
            try
            {
                spLibrary = new RPPMain.SharepointLibrary(txtLibreriaSharePoint.Text, "Seccion Primera", "autostore", "Rpp1234");
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Ocurrió un error al intentar conectarse a Sharepoint: " + ex.Message, "Conexión Fallida", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            string    documentoActual     = "";
            string    itemFile            = "";
            ArrayList lstArchivosImagenes = new ArrayList();

            try
            {
                lblTareaActual.Text = "Validando archivos de imágenes...";
                pgbAvance.Value     = 0;
                pgbAvance.Maximum   = lstDocumentos.Items.Count;
                lstArchivosNoEncontrados.Items.Clear();
                documentoActual = "Paso1";

                for (int i = 0; i < lstDocumentos.Items.Count; i++)
                {
                    #region Revisar
                    try
                    {
                        if (lstDocumentos.GetItemChecked(i) == false || chkReprocesar.Checked)
                        {
                            itemFile = lstDocumentos.Items[i].ToString();
                            string documentFullFileName = txtDirectorioDocumentos.Text + "\\" + itemFile;

                            documentoActual = "Paso2:" + documentFullFileName;

                            using (RPPMain.CsvFileReader reader = new RPPMain.CsvFileReader(documentFullFileName))
                            {
                                RPPMain.CsvRow row = new RPPMain.CsvRow();
                                while (reader.ReadRow(row))
                                {
                                    if (row[1] != "Página" && row[1] != "Página" && row[1].IndexOf("gina") > 0 && row[1].IndexOf("ginales") == 0)
                                    {
                                        string x = "";
                                    }

                                    if (row[1] == "Página" || row[1] == "Página")
                                    {
                                        documentoActual = "Paso3";
                                        string[] valores = row[2].Split('\\');
                                        if (valores.Length > 0)
                                        {
                                            string imagenFileName = valores[valores.Length - 1];
                                            documentoActual = "Paso4:" + valores.Length.ToString();
                                            string imageFullFileName = txtDirectorioImagenes.Text + "\\" + valores[valores.Length - 2] + "\\" + imagenFileName;
                                            documentoActual = "Paso5";

                                            bool existe = false;
                                            foreach (string[] imagen in lstArchivosImagenes)
                                            {
                                                if (imagen[0] == imagenFileName)
                                                {
                                                    int numeroInstancias = int.Parse(imagen[1]) + 1;
                                                    imagen[1] = numeroInstancias.ToString();
                                                    existe    = true;
                                                    break;
                                                }
                                            }

                                            if (!existe)
                                            {
                                                string[] imagenObject = new string[2];
                                                imagenObject[0] = imagenFileName;
                                                imagenObject[1] = "1";
                                                lstArchivosImagenes.Add(imagenObject);
                                            }

                                            if (!File.Exists(imageFullFileName))
                                            {
                                                lstArchivosNoEncontrados.Items.Add(itemFile + " Archivo de imágen no existe");
                                            }
                                            //throw new System.Exception(string.Format("El archivo de imágen [{0}] ligado al archivo out [{1}] no existe en la ruta de imágenes especificada.", imageFullFileName, documentFullFileName));
                                        }
                                        else
                                        {
                                            lstArchivosNoEncontrados.Items.Add(itemFile + "Archivo de imágen no definido");
                                        }
                                        //throw new System.Exception(string.Format("El archivo de imágen ligado al archivo out [{0}] no se especifico.", documentFullFileName));
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    catch
                    {
                        lstArchivosNoEncontrados.Items.Add(itemFile + " Con error en estructura");
                    }

                    #endregion

                    pgbAvance.Value++;
                }

                #region Imagenes no referenciadas

                lblNumeroImagenes.Text = lstArchivosImagenes.Count + " Imágenes";
                foreach (string[] imagen in lstArchivosImagenes)
                {
                    lstImagenes.Items.Add(imagen[0] + " - " + imagen[1]);
                }

                string[] tifFiles = Directory.GetFiles(folderImages.SelectedPath, "*.tif", SearchOption.AllDirectories);

                string archivoLogNoRef = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\imagenesNoReferenciadasA.txt";

                using (StreamWriter sw = new StreamWriter(archivoLogNoRef))
                {
                    foreach (string tifFile in tifFiles)
                    {
                        bool tifFound = false;
                        foreach (string[] imagen in lstArchivosImagenes)
                        {
                            string imagenFullPath = folderImages.SelectedPath + "\\" + imagen[0].Substring(0, 10) + "\\" + imagen[0];
                            if (tifFile == imagenFullPath)
                            {
                                tifFound = true;
                                break;
                            }
                        }

                        if (!tifFound)
                        {
                            lstImagenesNoReferenciadas.Items.Add(tifFile);
                            sw.WriteLine(tifFile);
                        }
                    }
                }

                lblTotalArchivosNoReferenciados.Text = lstImagenesNoReferenciadas.Items.Count.ToString();

                documentoActual = "Paso6";
                if (lstArchivosNoEncontrados.Items.Count > 0)
                {
                    string archivoNoRef = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\imagenesNoReferenciadas.txt";

                    if (File.Exists(archivoNoRef))
                    {
                        File.Delete(archivoNoRef);
                    }

                    int countFiles = 0;
                    using (StreamWriter sw = new StreamWriter(archivoNoRef))
                    {
                        foreach (string itemFileA in lstArchivosNoEncontrados.Items)
                        {
                            countFiles++;
                            sw.WriteLine(countFiles.ToString() + " - " + itemFileA);
                        }
                    }

                    DialogResult result = MessageBox.Show("No se encontraron los archivos de imágenes referenciadas en algunos de los documentos seleccionados, ¿ Procesar el resto de los documentos ?", "Archivos de Documento sin Imágen", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (result == DialogResult.No)
                    {
                        pgbAvance.Value     = 0;
                        lblTareaActual.Text = "En Espera...";
                        return;
                    }
                }

                #endregion

                #region Importar

                this.Cursor         = Cursors.WaitCursor;
                lblTareaActual.Text = "Importando documentos e imágenes al repositorio...";
                pgbAvance.Value     = 0;

                logArchivosProcesados.Clear();

                int numeroProcesadosReal = 0;
                for (int i = 0; i < lstDocumentos.Items.Count; i++)
                {
                    if (lstDocumentos.GetItemChecked(i) == false || chkReprocesar.Checked)
                    {
                        itemFile        = lstDocumentos.Items[i].ToString();
                        documentoActual = itemFile;
                        string documentFullFileName = txtDirectorioDocumentos.Text + "\\" + itemFile;
                        using (RPPMain.CsvFileReader reader = new RPPMain.CsvFileReader(documentFullFileName))
                        {
                            RPPMain.CsvRow row = new RPPMain.CsvRow();
                            while (reader.ReadRow(row))
                            {
                                if (row.Count > 0)
                                {
                                    if (row[1] == "Página" || row[1] == "Página")
                                    {
                                        string[] valores = row[2].Split('\\');
                                        if (valores.Length > 0)
                                        {
                                            string imageFullFileName = txtDirectorioImagenes.Text + "\\" + valores[valores.Length - 2] + "\\" + valores[valores.Length - 1];
                                            if (File.Exists(imageFullFileName))
                                            {
                                                string strDirectorioDocumentos = txtDirectorioDocumentos.Text;
                                                string strDirectorioImagenes   = txtDirectorioImagenes.Text + "\\" + valores[valores.Length - 2];

                                                try
                                                {
                                                    spLibrary.InsertLibraryItem(strDirectorioDocumentos, strDirectorioImagenes, valores[valores.Length - 1], itemFile, chkIgnorarCamposFaltantes.Checked);
                                                    lstDocumentos.SetItemChecked(i, true);
                                                    logArchivosProcesados.Add(itemFile + "," + imageFullFileName);
                                                    numeroProcesadosReal++;
                                                    this.lblTareaActual.Text = numeroProcesadosReal.ToString();
                                                    this.lblTareaActual.Refresh();
                                                }
                                                catch (Microsoft.SharePoint.Client.ServerException ex)
                                                {
                                                    lstArchivosNoEncontrados.Items.Add(itemFile + " - " + ex.Message);
                                                }
                                                catch (System.Exception ex)
                                                {
                                                    lstArchivosNoEncontrados.Items.Add(itemFile + " - " + ex.Message);
                                                }
                                            }
                                        }

                                        break;
                                    }
                                }
                            }
                        }
                    }

                    pgbAvance.Value++;
                }

                #endregion

                #region Escribir archivos

                string archivoLog = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\outUpload.txt";

                if (File.Exists(archivoLog))
                {
                    File.Delete(archivoLog);
                }

                int countFilesNR = 0;
                using (StreamWriter sw = new StreamWriter(archivoLog))
                {
                    foreach (string itemFileA in logArchivosProcesados)
                    {
                        countFilesNR++;
                        sw.WriteLine(countFilesNR.ToString() + " - " + itemFileA);
                    }
                }

                this.Cursor = Cursors.Default;
                MessageBox.Show("Proceso de importación finalizado correctamente", "Proceso Finalizado", MessageBoxButtons.OK, MessageBoxIcon.Information);
                pgbAvance.Value     = 0;
                lblTareaActual.Text = "En Espera...";

                #endregion
            }
            catch (System.Exception ex)
            {
                this.Cursor         = Cursors.Default;
                pgbAvance.Value     = 0;
                lblTareaActual.Text = "En Espera...";
                MessageBox.Show("Ocurrió un error al intentar importar el documento[" + documentoActual + "] : " + ex.Message + ex.StackTrace, "Importación Fallida", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 3
0
        private void btnValidar_Click(object sender, EventArgs e)
        {
            RPPMain.SharepointLibrary spLibrary = null;
            try
            {
                spLibrary = new RPPMain.SharepointLibrary(txtLibreriaSharePoint.Text, "Seccion Primera", "autostore", "Rpp1234");
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Ocurrió un error al intentar conectarse a Sharepoint: " + ex.Message, "Conexión Fallida", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            string itemFile           = "";
            string documentoActual    = "";
            string archivoIncidencias = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\archivosConIncidencias.txt";


            try
            {
                this.Cursor         = Cursors.WaitCursor;
                lblTareaActual.Text = "Validando archivos con incidencias...";
                pgbAvance.Value     = 0;

                using (RPPMain.CsvFileReader reader1 = new RPPMain.CsvFileReader(archivoIncidencias))
                {
                    RPPMain.CsvRow row1 = new RPPMain.CsvRow();
                    while (reader1.ReadRow(row1))
                    {
                        itemFile = "Libro_" + row1[0].Substring(0, 4) + "\\Libro_" + row1[0].Substring(0, 12) + ".out";

                        string documentFullFileName    = txtDirectorioDocumentos.Text + "\\" + itemFile;
                        string strDirectorioDocumentos = txtDirectorioDocumentos.Text;

                        try
                        {
                            spLibrary.ValidateLibraryItem(strDirectorioDocumentos, itemFile, false);
                        }
                        catch (Microsoft.SharePoint.Client.ServerException ex)
                        {
                            logArchivosProcesados.Add(itemFile + " - " + ex.Message);
                        }
                        catch (System.Exception ex)
                        {
                            logArchivosProcesados.Add(itemFile + " - " + ex.Message);
                        }

                        pgbAvance.Value++;
                    }
                }

                string archivoLog = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\observaciones.txt";

                if (File.Exists(archivoLog))
                {
                    File.Delete(archivoLog);
                }

                using (StreamWriter sw = new StreamWriter(archivoLog))
                {
                    foreach (string itemFileA in logArchivosProcesados)
                    {
                        sw.WriteLine(itemFileA);
                    }
                }

                this.Cursor = Cursors.Default;
                MessageBox.Show("Proceso de importación finalizado correctamente", "Proceso Finalizado", MessageBoxButtons.OK, MessageBoxIcon.Information);
                pgbAvance.Value     = 0;
                lblTareaActual.Text = "En Espera...";
            }
            catch (System.Exception ex)
            {
                this.Cursor         = Cursors.Default;
                pgbAvance.Value     = 0;
                lblTareaActual.Text = "En Espera...";
                MessageBox.Show("Ocurrió un error al intentar importar el documento[" + documentoActual + "] : " + ex.Message + ex.StackTrace, "Importación Fallida", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 4
0
        private void button1_Click(object sender, EventArgs e)
        {
            RPPMain.SharepointLibrary spLibrary = null;
            try
            {
                spLibrary = new RPPMain.SharepointLibrary(txtLibreriaSharePoint.Text, "Seccion Primera", "autostore", "Rpp1234");
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Ocurrió un error al intentar conectarse a Sharepoint: " + ex.Message, "Conexión Fallida", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            string query = string.Format(@"<View>
                                                <Query>
                                                    <Where>
                                                        <And>
                                                            <Eq><FieldRef Name='Tipo_x0020_de_x0020_documento' /><Value Type='Text'>{0}</Value></Eq>
                                                            <Eq><FieldRef Name='Numero_x0020_de_x0020_Documento' /><Value Type='Text'>{1}</Value></Eq>
                                                        </And>
                                                    </Where>
                                                </Query>
                                            </View>",
                                         "Escritura Pública",
                                         38773);

            query = @"<View>
                        <Query>
                            <Where> 
                                <And>
                                    <Eq><FieldRef Name='Partida' /><Value Type='Number'>15</Value></Eq>
                                    <Eq><FieldRef Name='Numero_x0020_de_x0020_Documento' /><Value Type='Text'>38885</Value></Eq>                                   
                                </And>
                                <And>
                                    <Eq><FieldRef Name='Fec_Reg_Libro' /><Value Type='Text'>1474</Value></Eq>
                                    <Eq><FieldRef Name='Fec_Reg_Seccion' /><Value Type='Text'>1</Value></Eq>
                                </And>
                            </Where>
                        </Query>
                    </View>";


            query = @"<View>
                        <Query>
                            <Where>
                                <And>
                                <And>
                                <And>
                                    <Eq><FieldRef Name='Fec_Reg_Seccion' /><Value Type='Text'>I</Value></Eq>
                                    <Eq><FieldRef Name='Fec_Reg_Partida' /><Value Type='Text'>A</Value></Eq>
                                </And>
                                    <Eq><FieldRef Name='Partida' /><Value Type='Text'>124</Value></Eq>
                                </And>
                                    <Eq><FieldRef Name='Fec_Reg_Libro' /><Value Type='Text'>1474</Value></Eq>
                                </And>
                            </Where>
                        </Query>
                      </View>";
            ArrayList valores = spLibrary.GetLibraryItem(query);

            if (valores.Count > 0)
            {
                Microsoft.SharePoint.Client.ListItem itemActual = (Microsoft.SharePoint.Client.ListItem)valores[0];

                Dictionary <string, object> dc = (Dictionary <string, object>)itemActual.FieldValues;
                Microsoft.SharePoint.Client.FieldUrlValue fURl = (Microsoft.SharePoint.Client.FieldUrlValue)dc["Pagina"];

                /*
                 * ArrayList arlResultado = spLibrary.GetLibraryItem(query);
                 *
                 * string strUrl = arlResultado[2].ToString().Split('|')[0];
                 * System.Uri uri = new Uri(strUrl);
                 *
                 * var request = System.Net.WebRequest.Create(uri);
                 *
                 */

                var request = System.Net.WebRequest.Create(fURl.Url);
                request.UseDefaultCredentials = true;
                var response = request.GetResponse();
                var stream   = response.GetResponseStream();

                pictureBox1.Image = Bitmap.FromStream(stream);
            }
        }