Example #1
5
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var content = WebUtility.GetRequestStr("s", "");
                if (!content.StartsWith("http"))
                    content = string.Format("http://{0}:{1}{2}", Request.Url.Host, Request.Url.Port, HttpUtility.UrlDecode(content));

                QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
                QrCode qrCode = new QrCode();
                if (qrEncoder.TryEncode(content, out qrCode))
                {
                    var fCodeSize = new FixedCodeSize(500, QuietZoneModules.Two);
                    fCodeSize.QuietZoneModules = QuietZoneModules.Four;
                    GraphicsRenderer renderer = new GraphicsRenderer(fCodeSize, Brushes.Black, Brushes.White);
                    MemoryStream ms = new MemoryStream();
                    renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms);

                    Response.Cache.SetNoStore();
                    Response.ClearContent();
                    Response.ContentType = "image/Png";
                    Response.BinaryWrite(ms.ToArray());
                }
            }
        }
Example #2
2
        private void button1_Click(object sender, EventArgs e)
        {
            /// generar un codigo QR para los elementos de la caja 

            // crear un encoder, codificador
            QrEncoder Codificador = new QrEncoder( ErrorCorrectionLevel.H );

            // crear un codigo QR
            QrCode Codigo = new QrCode();

            // generar generar  un codigo apartir de datos, y pasar el codigo por referencia
            Codificador.TryEncode(textBox1.Text, out Codigo);

            // generar un graficador 
            GraphicsRenderer Renderisado = new GraphicsRenderer(new FixedCodeSize(200, QuietZoneModules.Zero), Brushes.Black, Brushes.White);

            // generar un flujo de datos 
            MemoryStream ms = new MemoryStream();

            // escribir datos en el renderizado
            Renderisado.WriteToStream(Codigo.Matrix, ImageFormat.Png, ms);

            // generar controles para ponerlos en el form
            var ImagenQR = new Bitmap(ms);
            var ImgenSalida = new Bitmap(ImagenQR, new Size(panel1.Width, panel1.Height));

            // asignar la imagen al panel 
            panel1.BackgroundImage = ImgenSalida;
            


                 
        }
Example #3
0
        public byte[] Generator(string codeString, int size)
        {
            this.qrCodeSize   = size;
            this.qrCodeString = codeString;

            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);

            Gma.QrCodeNet.Encoding.QrCode qrCode = new Gma.QrCodeNet.Encoding.QrCode();
            qrEncoder.TryEncode(QrCodeString, out qrCode);
            var          renderer = new GraphicsRenderer(new FixedCodeSize(QrCodeSize, QuietZoneModules.Zero), Brushes.Black, Brushes.White);
            MemoryStream stream   = new MemoryStream();

            renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream);

            byte[] qrCodeBuffer = null;

            try
            {
                qrCodeBuffer = stream.ToBuffer();
            }
            catch (Exception exception)
            {
                SimpleConsole.WriteLine("Generator qr code fail. exception message:" + exception.Message);
            }
            return(qrCodeBuffer);
        }
Example #4
0
 /// <summary>
 /// Try to encode content
 /// </summary>
 /// <returns>False if input content is empty, null or too large.</returns>
 public bool TryEncode(string content, out QrCode qrCode)
 {
     try
     {
         qrCode = this.Encode(content);
         return true;
     }
     catch(InputOutOfBoundaryException)
     {
         qrCode = new QrCode();
         return false;
     }
 }
Example #5
0
 /// <summary>
 /// Try to encode content
 /// </summary>
 /// <returns>False if input content is empty, null or too large.</returns>
 public bool TryEncode(IEnumerable <byte> content, out QrCode qrCode)
 {
     try
     {
         qrCode = this.Encode(content);
         return(true);
     }
     catch (InputOutOfBoundaryException)
     {
         qrCode = new QrCode();
         return(false);
     }
 }
 /// <summary>
 /// Try to encode content
 /// </summary>
 /// <returns>False if input content is empty, null or too large.</returns>
 public bool TryEncode(string content, out QrCode qrCode)
 {
     try
     {
         qrCode = Encode(content);
         return(true);
     }
     catch (InputOutOfBoundaryException)
     {
         qrCode = new QrCode();
         return(false);
     }
 }
        public recieve_litecoin()
        {
            InitializeComponent();

            ILitecoinService litecoinService = new LitecoinService();
            string           a = litecoinService.GetNewAddress();

            address_textBox.Text = a;

            Gma.QrCodeNet.Encoding.QrEncoder Encoder = new Gma.QrCodeNet.Encoding.QrEncoder(Gma.QrCodeNet.Encoding.ErrorCorrectionLevel.H);
            Gma.QrCodeNet.Encoding.QrCode    Code    = Encoder.Encode(a);
            Bitmap TempBMP = new Bitmap(Code.Matrix.Width, Code.Matrix.Height);

            for (int X = 0; X <= (Code.Matrix.Width) - 1; X++)
            {
                for (int Y = 0; Y <= (Code.Matrix.Height) - 1; Y++)
                {
                    if (Code.Matrix.InternalArray[X, Y])
                    {
                        TempBMP.SetPixel(X, Y, System.Drawing.Color.Black);
                    }
                    else
                    {
                        TempBMP.SetPixel(X, Y, System.Drawing.Color.White);
                    }
                }
            }

            //TempBMP.Size abc = new System.Drawing.Size(120,120);

            //Console.Write(TempBMP);
            //ictureBox.Image.Size =new  Size(600, 700);
            //empBMP.Size = new Size(TempBMP.Height,TempBMP.Width);
            pictureBox.Size = new Size(100, 75);
            // pictureBox.Image = TempBMP;

            var imageTemp = new Bitmap(TempBMP);

            var image = new Bitmap(imageTemp, new System.Drawing.Size(new System.Drawing.Point(100, 75)));

            //image.Save("file.bmp", ImageFormat.Bmp);

            pictureBox.Image = image;



            //pictureBox.BorderStyle = BorderStyle.FixedSingle;
        }
        /// <summary>
        /// Qr Code generation
        /// </summary>
        /// <param name="barcodeText"></param>
        /// <returns></returns>
        public ActionResult BarcodeImage(String barcodeText)
        {
            // generating a barcode here. Code is taken from QrCode.Net library
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
            QrCode qrCode = new QrCode();
            qrEncoder.TryEncode(barcodeText, out qrCode);
            GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(4, QuietZoneModules.Four), Brushes.Black, Brushes.White);
            Stream memoryStream = new MemoryStream();
            renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, memoryStream);

            // very important to reset memory stream to a starting position, otherwise you would get 0 bytes returned
            memoryStream.Position = 0;
            var resultStream = new FileStreamResult(memoryStream, "image/png");
            resultStream.FileDownloadName = String.Format("{0}.png", barcodeText);
            return resultStream;
        }
Example #9
0
    private void ImageAdd()
    {
        string    qrurl     = CreateQRCodeUrl();
        QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);

        Gma.QrCodeNet.Encoding.QrCode qrCode = new Gma.QrCodeNet.Encoding.QrCode();
        qrEncoder.TryEncode(qrurl, out qrCode);
        using (MemoryStream ms = new MemoryStream())
        {
            var renderer = new GraphicsRenderer(new FixedModuleSize(4, QuietZoneModules.Two));
            renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms);
            Response.ContentType = "image/png";
            Response.OutputStream.Write(ms.GetBuffer(), 0, (int)ms.Length);
        }
        LogUtil.WriteLog("二维码生成");
    }
        public ActionResult BarcodeImage(String barcodeText)
        {
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
            QrCode qrCode = new QrCode();
            qrEncoder.TryEncode(barcodeText, out qrCode);
            GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(4, QuietZoneModules.Four), Brushes.Black, Brushes.White);

            Stream memoryStream = new MemoryStream();
            renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, memoryStream);

            memoryStream.Position = 0;

            var resultStream = new FileStreamResult(memoryStream, "image/png");
            resultStream.FileDownloadName = String.Format("{0}.png", barcodeText);

            return resultStream;
        }
        public ActionResult BarcodeImage(string secretKey, string userName)
        {
            string barcodeText = string.Format("otpauth://totp/Dentco%3A%20{0}?secret={1}", userName, secretKey);

            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
            QrCode qrCode = new QrCode();
            qrEncoder.TryEncode(barcodeText, out qrCode);
            GraphicsRenderer renderer = new GraphicsRenderer(new FixedCodeSize(200, QuietZoneModules.Zero), Brushes.Black, Brushes.White);

            Stream memoryStream = new MemoryStream();
            renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, memoryStream);

            memoryStream.Position = 0;

            var resultStream = new FileStreamResult(memoryStream, "image/png");
            resultStream.FileDownloadName = string.Format("{0}.png", barcodeText);

            return resultStream;
        }
Example #12
0
        /// <summary>
        /// 根据内容生成png格式的二维码,并保存到指定的物理路径中;
        /// </summary>
        /// <param name="content">二维码内容</param>
        /// <param name="moduleSize">控制图片的大小:1,2,3,4,6,7,8</param>
        /// <param name="physicalpath">图片存放的物理路径</param>
        /// <returns>返回生成的图片名</returns>
        public static string CreateQrCode(string content, int moduleSize, string physicalpath)
        {
            if (string.IsNullOrWhiteSpace(content))
            {
                return(null);
            }
            QrEncoder qrencoder = new QrEncoder(ErrorCorrectionLevel.L);

            Gma.QrCodeNet.Encoding.QrCode qrcode = new Gma.QrCodeNet.Encoding.QrCode();
            qrencoder.TryEncode(content, out qrcode);
            GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(moduleSize, QuietZoneModules.Zero), Brushes.Black, Brushes.White);

            using (MemoryStream ms = new MemoryStream())
            {
                render.WriteToStream(qrcode.Matrix, System.Drawing.Imaging.ImageFormat.Png, ms);
                Image  image    = Image.FromStream(ms);
                string filename = "JHD" + DateTime.Now.ToString("yyyyMMddhhmmssfff") + ".png";
                image.Save(physicalpath + filename);
                return(filename);
            }
        }
        Bitmap ComputeQRCode(int slice)
        {
            var qrEncoder = new QrEncoder(FErrorCorrectionLevel[slice]);
            var qrCode = new QrCode();
            if (qrEncoder.TryEncode(FText[slice], out qrCode))
            {
                var fc = FForeColor[slice];
                var bc = FBackColor[slice];
                fc = new RGBAColor(fc.B, fc.G, fc.R, fc.A);
                bc = new RGBAColor(bc.B, bc.G, bc.R, bc.A);
                using (var fore = new SolidBrush(fc.Color))
                using (var back = new SolidBrush(bc.Color))
                {
                    var renderer = new GraphicsRenderer(new FixedModuleSize(FPixelSize[slice], FQuietZoneModules[slice]), fore, back);
                    DrawingSize dSize = renderer.SizeCalculator.GetSize(qrCode.Matrix.Width);
                    var bmp = new Bitmap(dSize.CodeWidth, dSize.CodeWidth);
                    using (var g = Graphics.FromImage(bmp))
                        renderer.Draw(g, qrCode.Matrix);

                    return bmp;
                }
            }
            else
                return null;
        }
Example #14
0
        private void launch(BackgroundWorker worker, DoWorkEventArgs e)
        {
            //this.pbProgress.Value = 0;
            //SetProgress(0);
            //frmMain frmMainE = (frmMain)e.Argument;
            myParams = (Parameters)e.Argument;
            ProgressStatusClass myProgress = new ProgressStatusClass();

            // List of listed extensions when Only Music Files is Checked
            List<string> sExtOK = new List<string>();
            sExtOK.Add(".flac");
            sExtOK.Add(".mp3");
            sExtOK.Add(".ogg");
            sExtOK.Add(".wma");
            sExtOK.Add(".alac");

            foreach (Notebook notebook in notebooks)
            {
                if (notebook.Name == myParams.Notebook)
                {
                    musicNotebook = notebook;
                }
            }

            // Liste des M-0Top
            if (chkRegenLists.Checked)
            {
                //TextWriter tw_lst = new StreamWriter(myParams.Folder + "\\camuma-top.lst", false, Encoding.Default);
                TextWriter tw_lst = new StreamWriter(myParams.Folder + "\\camuma-top.lst", false, Encoding.GetEncoding(850));

                NoteFilter filter = new NoteFilter();
                filter.NotebookGuid = musicNotebook.Guid;
                //filter.Words = "intitle:\"" + dir.Name + "\"";
                //any: "Camuma ID: 153266"  intitle:"Muse - 1999 - Showbiz"
                //filter.Words = "\"CaMuMa ID: " + sId + "\"";
                // Recherche par CaMuMa ID ou Titre
                //filter.Words = "any: \"CaMuMa ID: " + sId + "\" intitle:\"" + dir.Name + "\"";
                filter.Words = "tag:M-0Top";
                NotesMetadataResultSpec spec = new NotesMetadataResultSpec();
                spec.IncludeTitle = true;
                int pageSize = 10;
                int offset = 0;
                NotesMetadataList notes = noteStore.findNotesMetadata(authToken, filter, 0, pageSize, spec);
                do {
                    notes = noteStore.findNotesMetadata(authToken, filter, offset, pageSize, spec);
                    foreach (NoteMetadata note in notes.Notes) {
                        Console.WriteLine("M-0Top : " + note.Title);
                        tw_lst.WriteLine(note.Title);
                    }
                    offset = offset + notes.Notes.Count;
                } while (notes.TotalNotes > offset);
                tw_lst.Close();
            } //Liste des M-0Top

            /*if (chkPdf.Checked)
            {
                PdfDocument pdf = new PdfDocument();
                pdf.PageLayout = PdfPageLayout.TwoColumnLeft;
                //pdf.PageMode = PdfPageMode.
                pdf.Info.Title = "CaMuMa List";
                //pdf.Info.Producer = "Calexo CaMuMa";
                pdf.Info.Creator = "Calexo CaMuMa";
            }*/

            // Listing all directories
            DirectoryInfo dir = new DirectoryInfo(myParams.Folder);
            DirectoryInfo dir2;
            //String sMsg="";
            Int32 i = 0;
            foreach (DirectoryInfo f in dir.GetDirectories())
            {
                this.sFolderList[i] = f.FullName;
                dir2 = new DirectoryInfo(this.sFolderList[i]);
                foreach (DirectoryInfo f2 in dir2.GetDirectories())
                {
                    i++;
                    this.sFolderList[i] = f2.FullName;
                }

                i++;
                myProgress.Info = i + " directories...";
                worker.ReportProgress(0, myProgress);
            }

            //TextWriter tw = new StreamWriter(myParams.Folder + "\\camuma.lst", false, System.Text.Encoding.Unicode);
            //TextWriter tw = new StreamWriter(myParams.Folder + "\\camuma.lst", false, Encoding.GetEncoding(65001));
            //TextWriter tw = new StreamWriter(myParams.Folder + "\\camuma.lst", false, Encoding.BigEndianUnicode);
            TextWriter tw = new StreamWriter(myParams.Folder + "\\camuma.lst", false, Encoding.Default);

            // Checking each directory
            // Checking if MP3 or Flac is here
            // Adding note
            bool isFlac, isMP3, isAlac, isWma;
            bool isFolderJPG;
            bool isSpotify;
            String sFileList;
            String sContent = "";
            String sFolderJPG = "";
            Int32 j = 0;
            String sId = "";
            List<string> lTagNames;
            String sArtist, sAlbum, sYear; //, sGenre;
            Boolean isParsed;
            Regex oRegex; MatchCollection oMatchCollection;

            String regArtist = @"^(?<ARTIST>([\w\'\(\)\&\, -])*([\w\'\(\)\&\,]))";
            String regAlbum = @"(?<ALBUM>([\w\'\(\)\-\&\,\. ])+)$";
            String regYear = @"(?<YEAR>([0-9]{4}))";
            String regDash = "[ ]+-[ ]+";

            foreach (String sDirName in sFolderList)
            {
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }

                if (sDirName != null)
                {
                    dir = new DirectoryInfo(sDirName);
                    isFlac = false;
                    isMP3 = false;
                    isWma = false;
                    isAlac = false;
                    isSpotify = false;
                    isFolderJPG = false;
                    sFolderJPG = "";
                    sFileList = "<div ><ul>";// "<div><b>" + WebUtility.HtmlEncode("Liste des fichiers :") + "</b></div>";
                    sContent = "";
                    sArtist = ""; sAlbum = ""; sYear = ""; //sGenre = "";
                    isParsed = false;

                    if (chkAddIdTags.Checked)
                    {
                        if (File.Exists(dir.FullName + "\\camuma.id"))
                        {
                            TextReader tr = new StreamReader(dir.FullName + "\\camuma.id");
                            sId = tr.ReadLine().Trim();
                        }
                        else
                        {
                            Random rRnd = new Random();
                            int iRnd = rRnd.Next(1001, 999999);
                            sId = iRnd.ToString().PadLeft(6,'0');
                            System.IO.File.WriteAllText(@dir.FullName + "\\camuma.id", sId);
                        }

                        // Ajout au camuma.lst
                        tw.WriteLine(sId + ":" + dir.FullName.Replace(myParams.Folder+"\\",""));
                        //tw.Flush();

                        if (!File.Exists(dir.FullName + "\\camuma.png"))
                        {
                            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
                            QrCode qrCode = new QrCode();
                            //QrCode qrCode = qrEncoder.Encode(sId, out qrCode);
                            qrEncoder.TryEncode("camuma://" + sId, out qrCode);
                            //GraphicsRenderer renderer = new GraphicsRenderer(5, Brushes.Black, Brushes.White);
                            GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Zero), Brushes.Black, Brushes.White);
                            //int pixelSize = renderer.Measure( qrCode.Matrix.Width).Width;
                            //WriteableBitmap wBitmap = new WriteableBitmap(pixelSize, pixelSize, 96, 96, PixelFormats.Gray8, null);
                            //renderer.CreateImageFile(qrCode.Matrix, @dir.FullName + "\\camuma.png", ImageFormat.Png);

                            using (FileStream stream = new FileStream(@dir.FullName + "\\camuma.png", FileMode.Create))
                            {
                                renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream);
                            }

                            SizeF size;
                            Font f = new Font(FontFamily.GenericSansSerif,20);
                            // creates 1Kx1K image buffer and uses it to find out how bit the image needs to be to fit the text
                            using (Image imageg = (Image)new Bitmap(1000, 1000))
                                size = Graphics.FromImage(imageg).MeasureString(sId, f);

                            using (Bitmap image = new Bitmap((int)size.Width, (int)size.Height)) //,, PixelFormat.Format32bppArgb))
                            {
                                Graphics g = Graphics.FromImage((Image)image);
                                //g.TranslateTransform(image.Width, image.Height);
                                //g.RotateTransform(180.0F); //note that we need the rotation as the default is down
                                //Color colBG = new Color();
                                //colBG.
                                g.Clear(ColorTranslator.FromHtml("#ABDA4C"));
                                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                                g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
                                // draw text
                                g.DrawString(sId, f, Brushes.Black, 0f, 0f);

                                //note that this image has to be a PNG, as GDI+'s gif handling renders any transparency as black.
                                //context.Response.AddHeader("ContentType", "image/png");
                                using (MemoryStream memStream = new MemoryStream())
                                {
                                    //note that context.Response.OutputStream doesn't support the Save, but does support WriteTo
                                    image.Save(memStream, ImageFormat.Png);
                                    //memStream.WriteTo(context.Response.OutputStream);
                                    System.IO.File.WriteAllBytes(@dir.FullName + "\\camumaid.png", memStream.ToArray());
                                }
                            }

                        }
                    }

                    foreach (FileInfo f in dir.GetFiles())
                    {
                        //if (f.Extension.Equals("flac", StringComparison.CurrentCultureIgnoreCase)
                        if (f.Extension.Equals(".flac", StringComparison.CurrentCultureIgnoreCase)) isFlac = true;
                        else if (f.Extension.Equals(".mp3", StringComparison.CurrentCultureIgnoreCase)) isMP3 = true;
                        else if (f.Extension.Equals(".wma", StringComparison.CurrentCultureIgnoreCase)) isWma = true;
                        else if (f.Extension.Equals(".alac", StringComparison.CurrentCultureIgnoreCase)) isAlac = true;
                        else if (f.Name.Equals("folder.jpg", StringComparison.CurrentCultureIgnoreCase))
                        {
                            isFolderJPG = true;
                            sFolderJPG = f.FullName;
                        }
                        if (!chkMusicFiles.Checked || sExtOK.Contains(f.Extension.ToLower()))
                        {
                            sFileList += "<li>" + WebUtility.HtmlEncode(f.Name) + "</li>";
                        }
                    }
                    sContent = "<h1>" + WebUtility.HtmlEncode(dir.Name) + "</h1>";
                    sContent += sFileList + "</ul></div>";

                    if (isMP3 || isFlac || isWma || isAlac)
                    {
                        j++;
                        myProgress.ProgressValue = j;
                        myProgress.Info = j + "/" + i +" \nAlbum...";
                        worker.ReportProgress(j, myProgress);
                        //Info("Creating Note... " + j + "/" + i);

                        lTagNames = new List<string>();
                        lTagNames.Add("M-Support:Cowon");
                        lTagNames.Add("M-Support:NAS2");
                        lTagNames.Add("M-Support:WD");
                        lTagNames.Add("M-Album");
                        if (isMP3) lTagNames.Add("M-MP3");
                        if (isFlac) lTagNames.Add("M-FLAC");
                        if (isAlac) lTagNames.Add("M-ALAC");
                        if (isWma) lTagNames.Add("M-WMA");
                        if (isFolderJPG) lTagNames.Add("M-Cover");
                        else lTagNames.Add("M-NoCover");

                        Console.WriteLine(dir.Name + "...");

                        // ARTIST - YEAR - ALBUM
                        oRegex = new Regex(regArtist + regDash + regYear + regDash + regAlbum);
                        oMatchCollection = oRegex.Matches(dir.Name);
                        foreach (Match oMatch in oMatchCollection)
                        {
                            Console.WriteLine(" * " + oMatch.Groups["ARTIST"] + ":" + oMatch.Groups["ALBUM"] + "(" + oMatch.Groups["YEAR"] + ")");
                            sArtist = oMatch.Groups["ARTIST"].ToString();
                            sYear = oMatch.Groups["YEAR"].ToString();
                            sAlbum = oMatch.Groups["ALBUM"].ToString();
                            isParsed = true;
                        }

                        // ARTIST - ALBUM - YEAR
                        if (!isParsed)
                        {
                            oRegex = new Regex(regArtist + regDash + regAlbum + regDash + regYear);
                            oMatchCollection = oRegex.Matches(dir.Name);
                            foreach (Match oMatch in oMatchCollection)
                            {
                                Console.WriteLine(" * " + oMatch.Groups["ARTIST"] + ":" + oMatch.Groups["ALBUM"] + "(" + oMatch.Groups["YEAR"] + ")");
                                sArtist = oMatch.Groups["ARTIST"].ToString();
                                sYear = oMatch.Groups["YEAR"].ToString();
                                sAlbum = oMatch.Groups["ALBUM"].ToString();
                                isParsed = true;
                            }
                        }

                        // ARTIST - ALBUM
                        if (!isParsed)
                        {
                            oRegex = new Regex(regArtist + regDash + regAlbum);
                            oMatchCollection = oRegex.Matches(dir.Name);
                            foreach (Match oMatch in oMatchCollection)
                            {
                                //lTagNames.Add (oMatch.Groups["ARTIST"].ToString());
                                Console.WriteLine(" * " + oMatch.Groups["ARTIST"] + ":" + oMatch.Groups["ALBUM"]);
                                sArtist = oMatch.Groups["ARTIST"].ToString();
                                sAlbum = oMatch.Groups["ALBUM"].ToString();
                                isParsed = true;
                            }
                        }

                        if (isParsed)
                        {
                            sArtist = sArtist.Trim();
                            sYear = sYear.Trim();
                            sAlbum = sAlbum.Trim();
                            if (!String.IsNullOrWhiteSpace(sArtist)) lTagNames.Add("M-Artist:" + sArtist);
                            if (!String.IsNullOrWhiteSpace(sYear)) lTagNames.Add("M-Year:" + sYear);
                            else lTagNames.Add("M-Year:None");
                            //if (!String.IsNullOrWhiteSpace(sAlbum)) lTagNames.Add("M-Album:" + sAlbum);

                            myProgress.Info = j + "/" + i + "\n"  + "Album : " + sArtist + ":" + sAlbum + "... ";
                            worker.ReportProgress(j, myProgress);
                        }
                        else lTagNames.Add("M-NotParsed");

                        // Spotify
                        if (chkSpotify.Checked)
                        {
                            try
                            {
                                SearchResults<Album> spoRes = Search.SearchAlbums(dir.Name);
                                if (spoRes.SearchResultsPage.Length > 0)
                                {
                                    Album album = spoRes.SearchResultsPage.First();
                                    Console.WriteLine(" * Spotify : " + album.Artist + " - " + album.Name + " (" + album.Url + ")");
                                    sContent += "<div><br/></div>";
                                    sContent += "<h2>Liens</h2>";
                                    sContent += "<div><strong>Spotify</strong> : ";
                                    sContent += "<a href=\"" + album.Url + "\">";
                                    sContent += WebUtility.HtmlEncode(album.Artist + " - " + album.Name + " : " + album.Url);
                                    sContent += "</a>";
                                    sContent += "</div>";

                                    lTagNames.Add("M-Spotify");
                                    isSpotify = true;
                                }
                            }
                            catch (WebException we)
                            {
                                Console.WriteLine(" * Spotify : " + we.Message);
                            }
                            catch (System.FormatException we)
                            {
                                Console.WriteLine(" * Spotify : " + we.Message);
                            }
                        } // chkSpotify true

                        /*foreach (Album album in spoRes.SearchResultsPage)
                        {
                            Console.WriteLine(" * Spotify : " + album.Artist + " - " + album.Name + " (" + album.Url + ")");
                        }*/

                        // Add CaMuMa Id
                        sContent += "<div><p><i>CaMuMa ID:</i> <a href=\"camuma://" + sId + "\">" + sId + "</a></p>";
                        byte[] image = ReadFully(File.OpenRead(@dir.FullName + "\\camuma.png"));
                        byte[] hashQR = new MD5CryptoServiceProvider().ComputeHash(image);
                        String hashHexQR = BitConverter.ToString(hashQR).Replace("-", "").ToLower();
                        //sContent += "<a href=\"camuma://" + sId + "\">";
                        sContent += "<en-media type=\"image/png\" hash=\"" + hashHexQR + "\"/>";
                        sContent += "</div>";
                        Data data = new Data();
                        data.Size = image.Length;
                        data.BodyHash = hashQR;
                        data.Body = image;
                        Resource imgQR = new Resource();
                        imgQR.Mime = "image/png";
                        imgQR.Data = data;
                        Console.WriteLine(@dir.FullName + "\\camuma.png -> " + hashHexQR);

                        // On ajoute si on n'est pas dans le Action AddSpotify
                        // ou si il y a effectivement du Spotify
                        if (chkEvernote.Checked)
                        {
                            if (!rbActSpotify.Checked || isSpotify)
                            {
                                // On recherche la note avec le même titre
                                NoteFilter filter = new NoteFilter();
                                filter.NotebookGuid = musicNotebook.Guid;
                                //filter.Words = "intitle:\"" + dir.Name + "\"";
                                //any: "Camuma ID: 153266"  intitle:"Muse - 1999 - Showbiz"
                                //filter.Words = "\"CaMuMa ID: " + sId + "\"";
                                // Recherche par CaMuMa ID ou Titre
                                //filter.Words = "any: \"CaMuMa ID: " + sId + "\" intitle:\"" + dir.Name + "\"";
                                filter.Words = "\"CaMuMa ID: " + sId;
                                NotesMetadataResultSpec spec = new NotesMetadataResultSpec();
                                spec.IncludeTitle = true;
                                int pageSize = 10;
                                NotesMetadataList notes = noteStore.findNotesMetadata(authToken, filter, 0, pageSize, spec);

                                // Non existing Note
                                if (notes.TotalNotes == 0)
                                {
                                    // If Adding ou Replacing
                                    if (rbAdd.Checked || rbReplace.Checked)
                                    {
                                        // Creating new note
                                        createNote(sFolderJPG, sContent, dir.Name, lTagNames, imgQR);
                                        Console.WriteLine(" * Creation");
                                    }
                                }
                                else if (notes.TotalNotes == 1)
                                {
                                    NoteMetadata noteToMod = notes.Notes.First();
                                    Console.WriteLine(" * Existing...");
                                    if (rbReplace.Checked)
                                    {
                                        Note note = noteStore.getNote(authToken, noteToMod.Guid, true, true, false, false);
                                        String hashHex = "";

                                        // Suppr tags négatifs (NotParsed, ...)
                                        note.TagGuids.Remove(getTagGuid("M-NotParsed"));
                                        note.TagGuids.Remove(getTagGuid("M-NoCover"));
                                        // Adding new tags
                                        note.TagNames = lTagNames;
                                        byte[] hash = null;
                                        if (sFolderJPG != "")
                                        {
                                            Console.WriteLine(" * folder.jpg exists");
                                            image = ReadFully(File.OpenRead(sFolderJPG));
                                            hash = new MD5CryptoServiceProvider().ComputeHash(image);
                                            hashHex = BitConverter.ToString(hash).Replace("-", "").ToLower();
                                        }

                                        if (note.Content != nodeContentEnrich(sContent, hashHex))
                                        {
                                            Console.WriteLine(" * Different contents");
                                            note.Content = nodeContentEnrich(sContent, hashHex);
                                            note.Resources = new List<Resource>();

                                            if (hash != null)
                                            {
                                                Console.WriteLine(" * Adding folder image");
                                                Data dataF = new Data();
                                                dataF.Size = image.Length;
                                                dataF.BodyHash = hash;
                                                dataF.Body = image;
                                                Resource resource = new Resource();
                                                resource.Mime = "image/jpg";
                                                resource.Data = dataF;
                                                note.Resources.Add(resource);
                                            }

                                            note.Resources.Add(imgQR);

                                            Console.WriteLine("Res : " + note.Resources.Count);

                                            note.UpdateSequenceNum = 0;
                                            note.Updated = 0;

                                            Note newNote = noteStore.updateNote(authToken, note);

                                            if (newNote != null)
                                            {
                                                Console.WriteLine(" * Modified");
                                                Console.WriteLine("Res : " + newNote.Resources.Count);
                                                //Console.WriteLine(newNote.Title);
                                                //Console.WriteLine(newNote.Updated);
                                                //Console.WriteLine(note.UpdateSequenceNum + " -> " + newNote.UpdateSequenceNum);
                                            }
                                            else
                                            {
                                                Console.WriteLine(" * Modification failed");
                                            }
                                        }

                                    }
                                } // TotalNotes=1
                                else // More than 1 matches
                                {
                                    createNote(sFolderJPG, sContent, dir.Name, lTagNames, imgQR);
                                    Console.WriteLine(" * ERROR - Multiple found");
                                }
                            } // ActSpotify
                        } // chkEvernote
                    }
                    else
                    {
                        i--;
                    }
                }

                //this.pbProgress.Maximum = i;
                //pbProgress.Value = j;

                myProgress.ProgressMax = i;
                myProgress.ProgressValue = j;
                worker.ReportProgress(j, myProgress);
            }
            //Info("OK");
            tw.Close();
        }
        public FileResult getQRCode(int id = 0)
        {
            Task task = db.Tasks.Find(id);
            if (task == null)
            {
                return null;
            }
            int t = (int)db.Tasks.Sum(s => s.bonusPoints);
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
            QrCode qrCode = new QrCode();
            qrEncoder.TryEncode("http://localhost:1558/Tasks/SubmitQR/?token=" + task.token, out qrCode);

            GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(2, QuietZoneModules.Two), Brushes.Black, Brushes.White);

            MemoryStream ms = new MemoryStream();

            renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms);

            var imageTemp = new Bitmap(ms);

            return File(ms.ToArray(), "image/png");
        }
Example #16
0
        public ActionResult Generate(String longurl)
        {
            var jsonResp = new UrlShortenResponse{
            Success = true
            };

            /*
             *   +--------------------------------------------------------------------------------+
             *   | Step 1: Check if the URL is valid. We will issue a web request and see the     |
             *   |         status code.                                                           |
             *   | Step 2: Check if this URL is already in the system. If exists, return          |
             *   |         We will check for the current user, since we will generate a unique    |
             *   |         URL for each user for a given original URL                             |
             *   | Step 3: Generate short URL. (May be check again if we generated a duplicate?)  |
             *   | Step 4: Generate a QR code for the URL                                         |
             *   | Step 5: Save generated short url and also save the QR image.                   |
             *   | Step 6: Send Json response back to the user.                                   |
             *   +--------------------------------------------------------------------------------+
            */

            #region Step 1 - Check for a valid URL

            bool bValidUrl = true;
            try
            {
                HttpWebRequest request = WebRequest.Create(longurl) as HttpWebRequest;
                request.Method = "GET";
                request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
                var response = request.GetResponse();
                bValidUrl = response.Headers.Count > 0;
            }
            catch
            {
                bValidUrl = false;
            }

            if (!bValidUrl)
            {
                return Json(new UrlShortenResponse
                {
                    Success = false,
                    Message = "Please check if the URL is correct and try again."
                }, "text/html");
            }

            String protoPrefix = "http://";
            String webUrl = longurl;
            if (longurl.Contains("://"))
            {
                int iIndex = longurl.IndexOf("://");
                protoPrefix = longurl.Substring(0, iIndex + 3);
                webUrl = longurl.Substring(iIndex + 3);
            }

            #endregion

            #region Step 2-5 - Generate URL and save

            UrlMap url = _UrlMapDataSource.FindSingleUrlByUserName(longurl, User.Identity.Name);
            if (url == null)
            {
                url = new UrlMap();
                url.OriginalUrl = longurl;
                url.DateCreated = DateTime.UtcNow;
                url.IsActive = true;

                //Step 3:
                //Now generate hash for the longUrl;
                uint hash = FNVHash.fnv_32a_str(webUrl + User.Identity.Name);

                //Convert hash to base36
                url.ShortUrlCode = Base36Converter.Encode(hash);

                url.ShortUrl = String.Format("{0}{1}", _URLShortenerHost, url.ShortUrlCode);

                //Step 4:
                QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
                QrCode qrCode = new QrCode();
                qrEncoder.TryEncode(url.ShortUrl, out qrCode);

                Renderer renderer = new Renderer(5, Brushes.Black, Brushes.White);

                String fileName = String.Format("{0}{1}.qr", AppDomain.CurrentDomain.BaseDirectory, url.ShortUrlCode);
                renderer.CreateImageFile(qrCode.Matrix, fileName, ImageFormat.Png);
                jsonResp.QRCodeUrl = String.Format("{0}Home/QRImage/{1}.qr", _URLShortenerHost, url.ShortUrlCode);

                //Save Url Map
                _UrlMapDataSource.AddUrlMap(url, User.Identity.Name);

                //Save method appends the .qr extension
                _UrlMapDataSource.SaveQRCode(fileName, url.ShortUrlCode);
            }
            #endregion

            // Step 6
            jsonResp.Url = url.ShortUrl;
            jsonResp.QRCodeUrl = String.Format("{0}Home/QRImage/{1}.qr", _URLShortenerHost, url.ShortUrlCode);

            return Json(jsonResp, "text/html");
        }
Example #17
0
        /// <summary>
        /// 计算矩阵
        /// </summary>
        /// <param name="code"></param>
        /// <param name="width">画布的尺寸</param>
        /// <param name="height">画布的尺寸</param>
        /// <param name="rectangle">画二维码的窗口</param>
        /// <returns></returns>
        private static byte[,] Calculate(QrCode code, int width, int height, Rectangle rectangle)
        {
            const int margin = 5;
            var map = new byte[width, height];

            int matrixW = code.Matrix.Width;
            int matrixH = code.Matrix.Height;

            int n = rectangle.Height > rectangle.Width ? (rectangle.Width - margin * 2) / matrixW : (rectangle.Height - margin * 2) / matrixH;

            int w = matrixW * n;
            int h = matrixH * n;

            int x = rectangle.X + (rectangle.Width - w) / 2 - n;
            int y = rectangle.Y + (rectangle.Height - h) / 2 - n;

            for (int xx = 0; xx < code.Matrix.Width; xx++)
            {
                for (int yy = 0; yy < code.Matrix.Height; yy++)
                {
                    if (code.Matrix.InternalArray[xx, yy])
                    {
                        int xxx = x + n + (n - 1) / 2 + xx * n;
                        int yyy = y + n + (n - 1) / 2 + yy * n;
                        //g.FillRectangle(black, new Rectangle(xxx, yyy, 2, 2));
                        FillRoundedRectangle(map, (byte)ColorType.Dark, new Rectangle(xxx, yyy, 2, 2));
                    }
                    else
                    {
                        int xxx = x + n + (n - 1) / 2 + xx * n;
                        int yyy = y + n + (n - 1) / 2 + yy * n;
                        //g.FillRectangle(white, new Rectangle(xxx, yyy, 2, 2));
                        FillRoundedRectangle(map, (byte)ColorType.Light, new Rectangle(xxx, yyy, 2, 2));
                    }
                }
            }

            DrawFinder(map, x, y, n);
            DrawFinder(map, x + (code.Matrix.Width - 7) * n, y, n);
            DrawFinder(map, x, y + (code.Matrix.Height - 7) * n, n);
            DrawAlignment(map, x + (code.Matrix.Width - 7 - 1) * n, y + (code.Matrix.Height - 7 - 1) * n, n);

            return map;
        }
Example #18
0
        public ActionResult IDCard(Guid Id)
        {
            string ProfilDirSetting = ConfigurationManager.AppSettings["ProfileImage"];
            if (string.IsNullOrWhiteSpace(ProfilDirSetting)) return null;
            Person p = reposetory.GetPersonComplete(Id);
            if (p == null) return null;
            string ProfilImageedPath = Server.MapPath(string.Format(ProfilDirSetting, p.PersonID));
            if (!System.IO.File.Exists(ProfilImageedPath)) return null;

            string idCardPath = Server.MapPath(ConfigurationManager.AppSettings["IDCARD"]);
            if (!System.IO.File.Exists(idCardPath)) return null;

            //ProfileImage parameters
            int ProfilImageX = string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["IDCARDProfilX"]) ? 200 : int.Parse(ConfigurationManager.AppSettings["IDCARDProfilX"]);
            int ProfilImageY = string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["IDCARDProfilY"]) ? 200 : int.Parse(ConfigurationManager.AppSettings["IDCARDProfilY"]);
            int ProfilImageH = string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["IDCARDProfilH"]) ? 550 : int.Parse(ConfigurationManager.AppSettings["IDCARDProfilH"]);
            int ProfilImageW = string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["IDCARDProfilW"]) ? 428 : int.Parse(ConfigurationManager.AppSettings["IDCARDProfilW"]);

            //Name Box parameters
            int NameX = string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["IDCARDNameX"]) ? 200 : int.Parse(ConfigurationManager.AppSettings["IDCARDNameX"]);
            int NameY = string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["IDCARDNameY"]) ? 200 : int.Parse(ConfigurationManager.AppSettings["IDCARDNameY"]);
            int NameH = string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["IDCARDNameH"]) ? 550 : int.Parse(ConfigurationManager.AppSettings["IDCARDNameH"]);
            int NameW = string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["IDCARDNameW"]) ? 428 : int.Parse(ConfigurationManager.AppSettings["IDCARDNameW"]);

            //QR Box parameters
            int QRX = string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["IDCARDQRX"]) ? 200 : int.Parse(ConfigurationManager.AppSettings["IDCARDQRX"]);
            int QRY = string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["IDCARDQRY"]) ? 200 : int.Parse(ConfigurationManager.AppSettings["IDCARDQRY"]);
            string QRCR = string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["IDCARDQRCR"]) ? "M" : ConfigurationManager.AppSettings["IDCARDQRCR"];

            Image idCard = Bitmap.FromFile(idCardPath);
            Image ProfilImage = Bitmap.FromFile(ProfilImageedPath);

            Graphics g = Graphics.FromImage(idCard);

            //Add profile image (Crop and Scale)
            RectangleF destinationRect = new RectangleF(
                    ProfilImageX,
                    ProfilImageY,
                    ProfilImageW,
                    ProfilImageH);

            RectangleF sourceRect;

            if (ProfilImage.Width / ProfilImage.Height <= ProfilImageW / ProfilImageH)
            {
                // Height

                sourceRect = new RectangleF(
                       (ProfilImage.Width - ProfilImage.Height * ProfilImage.Width / ProfilImage.Height) / 2,
                       0,
                       ProfilImage.Height * ProfilImage.Width / ProfilImage.Height,
                       ProfilImage.Height
                    );
            }
            else
            {
                // Width

                sourceRect = new RectangleF(
                       0,
                       (ProfilImage.Height - ProfilImage.Width * ProfilImage.Height / ProfilImage.Width) / 2,
                       ProfilImage.Width,
                       ProfilImage.Width * ProfilImage.Height / ProfilImage.Width
                    );
            }

            //RectangleF sourceRect = new RectangleF(

            g.DrawImage(
                  ProfilImage,
                  destinationRect,
                  sourceRect,
                  GraphicsUnit.Pixel
                  );

            //Name
            using (Font font1 = new Font("Verdana", 9, FontStyle.Bold, GraphicsUnit.Point))
            {
                RectangleF NameRect = new RectangleF(NameX, NameY, NameW, NameH);
                Pen blackPen = new Pen(Color.FromArgb(255, 0, 0, 0), 0);
                StringFormat sf = new StringFormat();
                sf.LineAlignment = StringAlignment.Center;
                sf.Alignment = StringAlignment.Center;

                g.DrawString(p.FullName, font1, Brushes.Black, NameRect, sf);

                //g.DrawRectangle(null, Rectangle.Round(NameRect));
            }


            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
            QrCode qrCode = new QrCode();
            qrEncoder.TryEncode(this.Url.Action("Verify", "ID", new { id = p.PersonID, area = "" }, this.Request.Url.Scheme), out qrCode);
            Renderer renderer = new Renderer(5, Brushes.Black, Brushes.Transparent);
            //Image QRCode = new Bitmap(200, 200);
            renderer.Draw(g, qrCode.Matrix, new Point(QRX, QRY));



            g.Dispose();
            MemoryStream m = new MemoryStream();
            idCard.Save(m, System.Drawing.Imaging.ImageFormat.Jpeg);
            m.Seek(0, SeekOrigin.Begin);

            FileStreamResult result = new FileStreamResult(m, "image/jpeg");
            result.FileDownloadName = "IDKORT.jpeg";
            return result;

        }