Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, 21 June 2023

Develop And Deploy Azure WebJobs In Azure App Service

 Step 1: - Create Console application => Click “Next” => Project Name “TestWebJob” => Click “Next“ => Click “Create”


























The console application created successfully

Step 2: - Go to application containing folder => expand “bin” folder => expand “Release” folder => select “net6.0” folder and compress to zip








Step 3: - Login to Microsoft Azure Portal

Step 4: - Search “App Service” in search bar => Select Web APP (WebJobUAT) in the list












Step 5:- Select “WebJobs” from the left pane => Click “Add”












Step 6:- Fill Details => Click “Create Webjob”













Step 7:- Click “Refresh”












Step 8:- Click “Run” => Click “Run”













Step 9:- Click “Logs”












Step 10:- Click “TestWebJob” name












Step 11:- Click “Timing”












Step 12:- Job Run Successfully












Step 13:- Delete the “TestWebJob”



Merge Multiple PDFs into a single PDF using iTextSharp in C#

Do not forget to install iTextSharp.dll using Manage NuGet Packages

using
iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
 
namespace ConsoleApplication1
{
    public class MergePDF
    {
        public void ProcessMergePDF()
        {
            string[] files = Directory.GetFiles(@"E:\Form\");
            string outputPath = @"E:\Output\Merge.pdf";
            using (Document doc = new Document())
            {
                using (PdfCopy writer = new PdfCopy(doc, new FileStream(outputPath, FileMode.Create)))
                {
                    if (writer == null)
                        return;
                    doc.Open();
                    foreach (string file in files)
                    {
                        using (PdfReader reader = new PdfReader(file))
                        {
                            reader.ConsolidateNamedDestinations();
                            for (int i = 1; i <= reader.NumberOfPages; i++)
                            {
                                PdfImportedPage page = writer.GetImportedPage(reader, i);
                                writer.AddPage(page);
                            }
                        }
                    }
                }
            }
        }
    }

} 

Sunday, 18 June 2023

Remove items from one list in another in C#

List<string> list1 = new List<string>() { "A", "B", "C", "D" };
List<string> list2 = new List<string>() { "B", "D" }; 
List<string> list3 = list1.Except(list2).ToList();

Here, in the list3 object, we will get the value A & C.

Convert Byte array to Base64 string in c#

 string byteString = Convert.ToBase64String(bytes);

How to Generate an SSRS Report as a Password-Protected PDF Using ASP.Net C#

Case scenario, apply password on pdf generated with SSRS report.

DLL Required.


Microsoft.ReportViewer.WebForms.dll
Microsoft.ReportViewer.Common.dll
itextsharp.dll


using iTextSharp.text.pdf;
using Microsoft.Reporting.WebForms;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
 
namespace ConsoleApplication1
{
    public class SSRSReport
    {
        public void Report()
        {
            string path = "Report Path";
            string ssrsURL = "Report Server URL";
            string ssrsUser = "Report Server User";
            string ssrsPass = "Report Server Password";
 
            ReportViewer reportViewer = new ReportViewer();
            reportViewer.ProcessingMode = ProcessingMode.Remote;
            reportViewer.ServerReport.ReportServerCredentials
                = new ReportCredentials(new NetworkCredential(ssrsUser.Trim(), ssrsPass.Trim(), ""));
            reportViewer.ServerReport.ReportServerUrl = new Uri(ssrsURL);
            reportViewer.ServerReport.ReportPath = path;
            reportViewer.ServerReport.SetParameters(new List<ReportParameter>() {
                new ReportParameter("Param1", "Value1"),
                new ReportParameter("Param2", "Value2")
            });
            reportViewer.ServerReport.Refresh();
 
            byte[] bytes = reportViewer.ServerReport.Render("pdf");

            using (MemoryStream inputData = new MemoryStream(bytes))
            {
                using (MemoryStream outputData = new MemoryStream())
                {
                    string pdfPassword = "test@123";
                    PdfReader reader = new PdfReader(inputData);
                    PdfEncryptor.Encrypt(reader, outputData, true, pdfPassword, pdfPassword, PdfWriter.ALLOW_SCREENREADERS);
                    byte[] passwordFileBytes = outputData.ToArray();
 
                    if (!Directory.Exists(@"D:\Report\"))
                        Directory.CreateDirectory(@"D:\Report\");
 
                    File.WriteAllBytes(@"D:\Report\WithoutPassword.pdf", bytes);
                    File.WriteAllBytes(@"D:\Report\WithPassword.pdf", passwordFileBytes);
 
                    //Line of code used in the web application
                    //Response.ContentType = "application/pdf";
                    //Response.AddHeader("content-disposition", "attachment;filename=Sample.pdf");
                    //Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    //Response.BinaryWrite(passwordFileBytes);
                    //Response.End();
                }
            }
        }
    }
}

Monday, 10 April 2023

Convert DataTable To JsonString in C#

using System.Data;
using System.Text;
 
DataTable dataTable = new DataTable();
DataRow? dataRow = null;
dataTable.Columns.Add("EmpCode", typeof(string));
dataTable.Columns.Add("EmpName", typeof(string));
 
dataRow = dataTable.NewRow();
dataRow["EmpCode"] = "E0001";
dataRow["EmpName"] = "Ram";
dataTable.Rows.Add(dataRow);
 
dataRow = dataTable.NewRow();
dataRow["EmpCode"] = "E0002";
dataRow["EmpName"] = "Shyam";
dataTable.Rows.Add(dataRow);
 
Console.WriteLine(Utility.ConvertDataTableToJsonString(dataTable));
Console.ReadLine();
 
public class Utility
{
    public static string ConvertDataTableToJsonString(DataTable dataTable)
    {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.Append("[");
 
        int totalColumnCount = dataTable.Columns.Count;
        int totalRowCount = dataTable.Rows.Count;
        int rowCount = 0;
 
        foreach (DataRow row in dataTable.Rows)
        {
            rowCount++;
            stringBuilder.Append("{");
 
            int columnCount = 0;
 
            foreach (DataColumn dataColumn in dataTable.Columns)
            {
                columnCount++;
 
                stringBuilder.Append("\"" + dataColumn.ColumnName.ToString() + "\":" + "\"" + row[dataColumn.ColumnName].ToString() + "\"");
 
                if (columnCount != totalColumnCount)
                {
                    stringBuilder.Append(",");
                }
            }
            stringBuilder.Append("}");
 
            if (rowCount != totalRowCount)
            {
                stringBuilder.Append(",");
            }
        }
        stringBuilder.Append("]");
 
        return stringBuilder.ToString();
    }
}

Output



 

Sunday, 27 June 2021

split data table by rows c#

In this demo, large data table records split into multiple tables based on a given number of records.
For Example, 1000 records split into two tables if we pass a split table with 500 records in each table. Based on the number of records last table record may vary.

Datatable does not contain a definition for AsEnumerable: - Using NuGet Package Manager install the System.Data.DataTableExtensions 

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

class Program
{
    public static IEnumerable<IEnumerable<T>> Split<T>(IEnumerable<T> enumerable, int chunkSize)
    {
        int itemsReturned = 0;
        List<T> list = enumerable.ToList();
        int count = list.Count;
        while (itemsReturned < count)
        {
            int currentChunkSize = Math.Min(chunkSize, count - itemsReturned);
            yield return list.GetRange(itemsReturned, currentChunkSize);
            itemsReturned += currentChunkSize;
        }
    }
 
    static void Main(string[] args)
    {
        DataTable dt = new DataTable("Table1");
        dt.Columns.Add("Col1");
        dt.Columns.Add("Col2");
 
        DataRow dr = null;
 
        for (int i = 0; i < 3400; i++)
        {
            dr = dt.NewRow();
            dr["Col1"] = i + 1;
            dr["Col2"] = i + 1;
            dt.Rows.Add(dr);
        }
 
        var tables = Split(dt.AsEnumerable(), 500).Select(rows => rows.CopyToDataTable());
 
        foreach (DataTable item in tables)
        {
            //code goes here
        }
        Console.ReadLine();
    }
}
 
With Extension Method
 
public static class Helper
{
    public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> enumerable, int chunkSize)
    {
        int itemsReturned = 0;
        List<T> list = enumerable.ToList();
        int count = list.Count;
        while (itemsReturned < count)
        {
            int currentChunkSize = Math.Min(chunkSize, count - itemsReturned);
            yield return list.GetRange(itemsReturned, currentChunkSize);
            itemsReturned += currentChunkSize;
        }
    }
}
 
class Program
{
    static void Main(string[] args)
    {
        DataTable dt = new DataTable("Table1");
        dt.Columns.Add("Col1");
        dt.Columns.Add("Col2");
 
        DataRow dr = null;
 
        for (int i = 0; i < 3400; i++)
        {
            dr = dt.NewRow();
            dr["Col1"] = i + 1;
            dr["Col2"] = i + 1;
            dt.Rows.Add(dr);
        }
 
        var tables = dt.AsEnumerable().Split(500).Select(rows => rows.CopyToDataTable());
 
        foreach (DataTable item in tables)
        {
            //code goes here
        }
        Console.ReadLine();
    } 
}

Monday, 20 April 2020

Get IP address in c#

public string GetLocalIPAddress()
{
    var host = Dns.GetHostEntry(Dns.GetHostName());
    foreach (var ip in host.AddressList)
    {
        if (ip.AddressFamily == AddressFamily.InterNetwork)
        {
            return ip.ToString();
        }
    }
    return "";
}