Wednesday, January 24, 2018

How to mearge multiple PDF files with page number using PDFSharp using C# MVC

In this article how to mearge multiple PDF file using PDFSharp dll in c# MVC

first install this package from nuget "Install-Package PdfSharp -Version 1.32.3057"

string DirectoryPath = HttpContext.Server.MapPath("~/YourDirectoryName/");
 
// Get all PDF Files 
 
string[] pdfs = Directory.GetFiles(DirectoryPath);
 
// Pass all PDF files in function 
 
MergeMultiplePDFIntoSinglePDF(DirectoryPath + "YourMeargeFileName.pdf", pdfs);
 
// Add below function for generate single pdf file 
 
private void MergeMultiplePDFIntoSinglePDF(string outputFilePath, string[] pdfFiles)
{
 PdfDocument document = new PdfDocument();
 
 foreach (string pdfFile in pdfFiles)
 {
  PdfDocument inputPDFDocument = 
  PdfReader.Open(pdfFile, PdfDocumentOpenMode.Import); 
 
  document.Version = inputPDFDocument.Version;
 
  foreach (PdfPage page in inputPDFDocument.Pages)
  { 
     document.AddPage(page);
  }
 }
 
 XFont font = new XFont("Verdana", 9);
 XBrush brush = XBrushes.Black;
 
 string noPages = document.Pages.Count.ToString();
 
 for (int i = 0; i < document.Pages.Count; ++i)
 {
  PdfPage page = document.Pages[i];
 
  // Make a layout rectangle.
  XRect layoutRectangle = new 
  XRect(240/*X*/, page.Height - font.Height - 10/*Y*/ 
  , page.Width/*Width*/, font.Height/*Height*/);
 
  using (XGraphics gfx = XGraphics.FromPdfPage(page))
  {
     gfx.DrawString("Page " + (i + 1).ToString() + " of " + 
     noPages, font, brush, layoutRectangle, XStringFormats.Center);
  }
 }
 
 document.Options.CompressContentStreams = true;
 document.Options.NoCompression = false;
 document.Save(outputFilePath);
}

How to delete files from directory using c# MVC

In this article how to remove multiple files remove from 1 single directory using foreach loop in MVC using c#

string FilePath = HttpContext.Server.MapPath("~/YourMainDirectoryName/");
 
// First check if directory exists or not
 
if (!Directory.Exists(FilePath))
{
 string[] files = Directory.GetFiles(FilePath);
 
 if (files.Length > 0)
 {
  foreach (string filePaths in files)
                      System.IO.File.Delete(filePaths);
 }
}
 
at the end of loop if you want to delete main directory write below line 
 
Directory.Delete(FileSavePath);
 
again if you want to create same blank directory write below line 
 
Directory.CreateDirectory(FileSavePath);

Wednesday, January 17, 2018

How to create excel file from data table using NPOI in c# asp.net or MVC

Step 1 : Download or Install "NPOI" Nuget from package manager & "Newtonsoft" Nuget

Step 2 : Get Data in your datatable like

        DataTable dt1 = new DataTable();

            dt1.Columns.Add("ID");
            dt1.Columns.Add("Name");

            DataRow dr = dt.NewRow();
            dr["ID"] = "1";
            dr["Name"] = "Test";

            dt.Rows.Add(dr);

Step 3 : Create class

public class SummaryClass
{
   public string ID { get; set; }
   public string Name { get; set; }
}

Step 3 :

using NPOI.HSSF.UserModel;
using Newtonsoft.Json;


// Create Work Book
var workbook = new HSSFWorkbook();

// Add name of sheet
var sheet = workbook.CreateSheet("Daily Summary");

// convert your datatable to list

string JSON = JsonConvert.SerializeObject(dt);
var items = JsonConvert.DeserializeObject<List<SummaryClass>>(JSON);

// Create column & header string array
var columns = new[] { "ID", "Name" }; // Your DataTable Fields Name
var headers = new[] { "Sr. No.", "Client Name" }; // Header display name in excel

// Create row in excel sheet
var headerRow = sheet.CreateRow(0);

//create header
for (int i = 0; i < columns.Length; i++)
{
    var cell = headerRow.CreateCell(i);
    cell.SetCellValue(headers[i]);
}

//fill content
for (int i = 0; i < items.Count; i++)
{
    var rowIndex = i + 1;
    var row = sheet.CreateRow(rowIndex);

    for (int j = 0; j < columns.Length; j++)
    {
        var cell = row.CreateCell(j);
        var o = items[i];
        cell.SetCellValue(o.GetType().GetProperty(columns[j]).GetValue(o, null).ToString());
    }
}

// Store data in memory strem
var stream = new MemoryStream();
workbook.Write(stream);

//write to file
FileStream file = new FileStream("Your File Save Path", FileMode.CreateNew, FileAccess.Write);
stream.WriteTo(file);
file.Close();
stream.Close();

Download image or file from Azure Blob Storage using c#

Step 1 : Download NugetPackage "WindowsAzure.Storage"

Step 2 : Below code for download image or file

string storageConnectionString = "YourStorageConnectionString";


// get storage account from connection string
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);

// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference("YourBlobName created in azure storage");

// Retrieve reference to a previously created container.
var directort = container.GetDirectoryReference(Directory Name if create in blob storage);

// Retrieve reference to a blob named "myblob".
CloudBlockBlob blockBlob = directort.GetBlockBlobReference(Your file name);

if (blockBlob.Exists())
{
    // Create or overwrite the "myblob" blob with contents from a local file.
    using (var fileStream = System.IO.File.Create(File save path))
    {
        blockBlob.DownloadToStream(fileStream);
    }
}

Send mail using office365 email id

In this post how send mail using office 365 email credential and smtp below is c# code for send mail
 
string EmailSender = "YourEmailID";
string EmailPassword = "YourPassword";

var client = new SmtpClient("smtp.office365.com", 587);
client.EnableSsl = true;
client.Timeout = 300000;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(EmailSender, EmailPassword);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
var from = new MailAddress("FromEmailID", $"DisplayName", System.Text.Encoding.UTF8);
var message = new MailMessage { From = @from };

message.Subject = Subject;
message.To.Add(ToEmailID);
message.IsBodyHtml = true;
message.Body = myQueueItem.EmailBody
message.BodyEncoding = Encoding.UTF8;
message.SubjectEncoding = Encoding.UTF8;
client.Send(message);
message.Dispose();

Sunday, January 14, 2018

How to upload file in azure blob storage explorer

How to upload file in azure blob storage explorer

Step 1 : Download NugetPackage "WindowsAzure.Storage"

Step 2 : Below code for upload file

// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(Your Azure connection string);

// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference(Report Upload Blob Name);

// Retrieve reference to a previously created container.
var directort = container.GetDirectoryReference(Upload Directory Name);

// Retrieve reference to a blob named "myblob".
CloudBlockBlob blockBlob = directort.GetBlockBlobReference(Upload File Name);

// Create or overwrite the "myblob" blob with contents from a local file.
using (var fileStream = System.IO.File.OpenRead(Your local folder file path))
{
    blockBlob.UploadFromStream(fileStream);
}

How to create Insert or Update query from select statement

- Insert Query
SELECT 'INSERT INTO AspNetRoles VALUES ('''+CONVERT(NVARCHAR(50),Id)+''', '''+Name+''')' FROM AspNetRoles

- Update Query
SELECT 'UPDATE AspNetRoles SET Name = '+Name+' WHERE ID = '+Id+'' FROM AspNetRoles

How to generate random 10 digit number using sql

SELECT RIGHT('000000' + CAST(ABS(CHECKSUM(NEWID())) % 9999999999 AS varchar(10)), 10)

How to send Twillo SMS from Azure function

Step 1 : "Twilio": "5.9.0" Add this library in your function project.json file of azure function

Step 2 : #r "Twilio.Api" for import twillo library add this line in your run.csx file of azure function

Step 3 : using Twilio; add this for use twillo code

Step 4 :


string accountSid = "YourAccountSID";
string authToken = "YourAccountAuth";
 
Step 5 : Create class for return response 


public class OutResponse
{
public string ID {get;set;}
public string Status {get;set;}
public string MobileNo {get;set;}
public string DBID {get;set;}
}
 
Step 6 : Twillo SMS Send Code
 

OutResponse mytempList = new OutResponse();

 var client = new TwilioRestClient(accountSid, authToken);
      
 var message=client.SendMessage(
            
  FromNo "Get From Twillo Panel",
  myQueueItem.SendToMobileNo,
  myQueueItem.SMSText
 );

 mytempList.ID = message.Sid;
 mytempList.Status = message.Status;

 mytempList.MobileNo = message.To;

 mytempList.DBID = myQueueItem.EmailBody;

Monday, January 8, 2018

Saturday, January 6, 2018

How to create website thumbnail from URL in C# .net

Step 1 : Add reference in your web application System.Windows.Forms

Step 2 : Create class WebSiteThumbnail

Step 3 : Add Below code for generate thumbainl

private string url = null;
        private Bitmap bmp = null;
        public Bitmap Image
        {
            get
            {
                return bmp;
            }
        }

        private ManualResetEvent mre = new ManualResetEvent(false);
        private int timeout = 5;
        private int thumbWidth;
        private int thumbHeight;
        private int width;
        private int height;
        private string absolutePath;

        public static Bitmap GetSiteThumbnail(string url, int width, int height, int thumbWidth, int thumbHeight)
        {
            WebSiteThumbnail thumb = new WebSiteThumbnail(url, width, height, thumbWidth, thumbHeight);
            Bitmap b = thumb.GetScreenShot();
            if (b == null)
                b = (Bitmap)System.Drawing.Image.FromStream(Assembly.GetExecutingAssembly().GetManifestResourceStream("PAB.WebControls.Notavailable.jpg"));
            return b;
        }

        public static Bitmap GetSiteThumbnail(string url, int width, int height, int thumbWidth, int thumbHeight, string absolutePath)
        {
            WebSiteThumbnail thumb = new WebSiteThumbnail(url, width, height, thumbWidth, thumbHeight, absolutePath);
            Bitmap b = thumb.GetScreenShot();
            if (b == null)
                b = (Bitmap)System.Drawing.Image.FromStream(Assembly.GetExecutingAssembly().GetManifestResourceStream("PAB.WebControls.Notavailable.jpg"));
            return b;
        }

        public WebSiteThumbnail(string url, int width, int height, int thumbWidth, int thumbHeight)
        {
            this.url = url;
            this.width = width;
            this.height = height;
            this.thumbHeight = thumbHeight;
            this.thumbWidth = thumbWidth;
        }

        public WebSiteThumbnail(string url, int width, int height, int thumbWidth, int thumbHeight, string absolutePath)
        {
            this.url = url;
            this.width = width;
            this.height = height;
            this.thumbHeight = thumbHeight;
            this.thumbWidth = thumbWidth;
            this.absolutePath = absolutePath;
        }

        public Bitmap GetScreenShot()
        {
            string fileName = url.Replace("http://", "") + ".jpg";
            fileName = System.Web.HttpUtility.UrlEncode(fileName);
            if (absolutePath != null && File.Exists(absolutePath + fileName))
            {
                bmp = (Bitmap)System.Drawing.Image.FromFile(absolutePath + fileName);
            }
            else
            {
                Thread t = new Thread(new ThreadStart(_GetScreenShot));
                t.SetApartmentState(ApartmentState.STA);
                t.Start();
                mre.WaitOne();
                t.Abort();
            }
            return bmp;
        }

        private void _GetScreenShot()
        {
            WebBrowser webBrowser = new WebBrowser();
            webBrowser.ScrollBarsEnabled = false;
            DateTime time = DateTime.Now;
            webBrowser.Navigate(url);
            webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
            while (true)
            {
                Thread.Sleep(0);
                TimeSpan elapsedTime = DateTime.Now - time;
                if (elapsedTime.Seconds >= timeout)
                {
                    mre.Set();
                }
                Application.DoEvents();
            }
        }

        private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            WebBrowser webBrowser = (WebBrowser)sender;
            webBrowser.ClientSize = new Size(this.width, this.height);
            webBrowser.ScrollBarsEnabled = false;
            bmp = new Bitmap(webBrowser.Bounds.Width, webBrowser.Bounds.Height);
            webBrowser.BringToFront();
            webBrowser.DrawToBitmap(bmp, webBrowser.Bounds);
            Image img = bmp.GetThumbnailImage(thumbWidth, thumbHeight, null, IntPtr.Zero);
            string fileName = url.Replace("http://", "") + ".jpg";
            fileName = System.Web.HttpUtility.UrlEncode(fileName);
            if (absolutePath != null && !File.Exists(absolutePath + fileName))
            {
                img.Save(absolutePath + fileName);
            }
            bmp = (Bitmap)img;
            webBrowser.Dispose();
            if (mre != null)
                mre.Set();
        }

        public void Dispose()
        {
            if (bmp != null) this.bmp.Dispose();
        }

Step 4 : How to use class method in code

string Path = HttpContext.Server.MapPath("YourThumbnailSavePath");

Bitmap b = WebSiteThumbnail.GetSiteThumbnail("http://developer2001.blogspot.com/", 1024, 1024, 1024, 768, Path);

Write above line for generate website thumbnail

Labels : ASP.Net, How to create website thumbnail from URL in C# .net, Thumbnail, Website

Tuesday, January 2, 2018

How to convert xElement to XML Node in C#


XElement oXML = new GenerateXML().GetXML(obj);

                XmlDocument xmlDoc = new XmlDocument();

                using (XmlReader xmlReader = oXML.CreateReader())
                {
                    xmlDoc.Load(xmlReader);
                }

Monday, January 1, 2018

What is MVC and How it's work

MVC

M stand for Model
V stand for View
C stand for Controller

Model - View - Controller

Model : Model works is create a property class and access in view by adding reference of model

View : View is user interface part you can write html code in view

Controller : Controller part is handle user interaction and work with view & model and finally get data and display in view

SQL DROP TABLE Statement

Here is query for how to drop table in sql server

DROP TABLE tblTest

Replace your table name with tblTest