Showing posts with label Asp.Net Tutorial. Show all posts
Showing posts with label Asp.Net Tutorial. Show all posts

Thursday, 1 March 2018

How to call function after complete page load in javascript

Description : in this post how to call function after complete page load in aspx, html, cshtml page just add below code in script

Write below code and add your function in setInterval

<script>
        document.addEventListener("DOMContentLoaded", function () {
            setInterval(calculateTotalFees(), 0);
        }, false);
</script>

Wednesday, 28 February 2018

Upload image in folder with parameter using MVC with c#

Description : in this post how to upload image in folder. in this code use form data in jquery for upload image in folder front end html side use jquery code for upload image and c# code side create method that return result in json for successfully upload image

add file upload html control in your html

<input type="file" style="visibility: hidden;height:0"

 id="Logo" name="Logo" accept=".png,.jpg,.jpeg,.gif,.tif" />

ajax call for upload image with parameter

function Save()
{
 if (window.FormData !== undefined)
 {
  var fileUpload = $("#Logo").get(0);
  var files = fileUpload.files;

  // Create FormData object
  var fileData = new FormData();

  // Looping over all files and add it to FormData object
  for (var i = 0; i < files.length; i++)
  {
   fileData.append(files[i].name, files[i]);
  }

  // Adding one more key to FormData object
  fileData.append('Parameter1', $("#Parameter1").val());

  $.ajax({
   url: '/YourControllerName/YourMethodName',
   type: "POST",
   contentType: false, // Not to set any content header
   processData: false, // Not to process data
   data: fileData,
   success: function (result)
   {
    alert(result);
   },
   error: function (err)
   {
    alert(err.statusText);
   }
  });
 }
 else
 {
  alert('FormData is not supported.');
 }
}

below code for get image in .cs file side and proccess image like save image in folder and save record in database

public JsonResult Save()
{
    string Parameter1 = Request.Form["Parameter1"].ToString()

    if (Request.Files.Count > 0)
    {
        try
        {
            //  Get all files from Request object 
            HttpFileCollectionBase files = Request.Files;
            for (int i = 0; i < files.Count; i++)
            {
                HttpPostedFileBase file = files[i];
                string FileName;

                // Checking for Internet Explorer 
                if (Request.Browser.Browser.ToUpper() == "IE"

                || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
                {
                    string[] testfiles = file.FileName.Split(new char[] { '\\' });
                    FileName = testfiles[testfiles.Length - 1];
                }
                else
                {
                    FileName = file.FileName;
                }

                FileInfo fInfo = new FileInfo(FileName);

                FileName = Guid.NewGuid().ToString() + fInfo.Extension;
               
                // Get the complete folder path and store the file inside it. 
                FileName = Path.Combine(Server.MapPath("~/YourImageFolderSavePath/"), FileName);
                file.SaveAs(FileName);
            }
        }
        catch (Exception ex)
        {
            return Json("Error occurred. Error details: " + ex.Message);
        }
    }

    // WRITE YOUR SAVE RECORD CODE HERE
   
    return Json("Image upload successfully.", JsonRequestBehavior.AllowGet);
}

Saturday, 24 February 2018

How to send Twillo SMS from Azure function

Description : in this post how to send Text SMS from twillo using azure function C# script code

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;

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);
}

Friday, 23 February 2018

Send mail using office365 email id

Description : 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();

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);
    }
}

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();

Thursday, 22 February 2018

How to delete files from directory using c# MVC

Description : 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);

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

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

Step 1 : 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);
}

Wednesday, 21 February 2018

Introduction of ASP

ASP is a framework for develop web pages

Development tools for ASP

- Classic ASP

- ASP.NET Web Forms

- ASP.NET MVC

- ASP.NET Web Pages

- ASP.NET API

- ASP.NET Core

Description about ASP

- Classic ASP introduce in 1998 as first script langualge of Microsoft. classic asp file extension is .asp written in VB

Description about ASP.NET

- ASP.NET released in 2002 and file extension of ASP.NET is aspx written in C# and ASP.NET 4.7 is latest version of ASP.NET

Description about ASP.NET Web Pages

- ASP.NET Web Pages is and single page application similar to PHP and ASP.NET Web Pages mearged in ASP.NET Core

Description about ASP.NET MVC

- ASP.NET MVC s Model - View - Controller and this is also mearge in ASP.NET Core

Description about ASP.NET API

- ASP.NET API is Application Programming Interface and this is also mearge in ASP.NET Core

Description about ASP.NET Web Forms

- ASP.NET Web Forms is event driven application model and this is not a part of ASP.NET Core

Description about ASP.NET Core

- ASP.NET core release in 2016 and Core mearge ASP.NET, MVC, Web API and ASP.NET Web Pages