c#.net

Generate x509 certificate in pem, cer and pfx and export public key

Generate x509 cerntifcate

c:\Demo>openssl req -x509 -days 365 -newkey rsa:2048 -keyout my-key.pem -out -my-cert.pem

Generating a RSA private key
………………………+++++
…………..+++++
writing new private key to ‘my-key.pem’
Enter PEM pass phrase:
Verifying – Enter PEM pass phrase:
—–
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter ‘.’, the field will be left blank.
—–
Country Name (2 letter code) [AU]:IN
State or Province Name (full name) [Some-State]:Gujarat
Locality Name (eg, city) []:Gandhinagar
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Your Company Name
Organizational Unit Name (eg, section) []:Development
Common Name (e.g. server FQDN or YOUR name) []:www.yourcompany.com
Email Address []:your@emailaddress.com

Generate .PFX file

c:\Demo>openssl pkcs12 -export -in -my-cert.pem -inkey my-key.pem -out my-xero.pfx
Enter pass phrase for my-key.pem:
Enter Export Password:
Verifying - Enter Export Password:

Generate .cer certificate

c:\Demo>openssl pkcs12 -export -in -my-cert.pem -inkey my-key.pem -out my-xero.cer
Enter pass phrase for my-key.pem:
Enter Export Password:
Verifying - Enter Export Password:

Export public key


c:\Demo>openssl pkcs12 -in my-xero.pfx -clcerts -nokeys -out myxeropublic.cer
Enter Import Password:

Reference: https://www.youtube.com/watch?v=3EBXAtyB6ys

Send an image (stored as base64 string) inline in email


Byte[] bitmapData = Convert.FromBase64String(FixBase64ForImage("Base64 string"));
System.IO.MemoryStream streamBitmap = new System.IO.MemoryStream(bitmapData);
var imageToInline = new LinkedResource(streamBitmap, MediaTypeNames.Image.Jpeg);
imageToInline.ContentId = "Pic1";
AlternateView avHtml = AlternateView.CreateAlternateViewFromString(mailMessage.Body, null, MediaTypeNames.Text.Html);
avHtml.LinkedResources.Add(imageToInline);
mailMessage.AlternateViews.Add(avHtml);

public static string FixBase64ForImage(string Image)
{
System.Text.StringBuilder sbText = new System.Text.StringBuilder(Image, Image.Length);
sbText.Replace("\r\n", string.Empty); sbText.Replace(" ", string.Empty);
return sbText.ToString();
}

Generate and Download PDF file on Ajax Post method, C#

Requirements: On ajax post, save data to database, generate invoice and download as PDF file. There are many open source packages available to generate PDF file. So I’m not going describe that using which paid/free package is used to generate PDF file. I am going to describe the trick how can download the generated PDF file without saving on hard drive.

HomeController.CS


public class HomeController : Controller
    {
        public ActionResult Index()
        {         
            return View();
        }

        public ActionResult Download()
        {
            //using (var ms = new MemoryStream())
            //{
                //using (var document = new Document(PageSize.A4, 50, 50, 15, 15))
                //{
                //    PdfWriter.GetInstance(document, ms);
                //    document.Open();
                //    document.Add(new Paragraph("HelloWorld"));
                //    document.Close();
                //}
                //Response.Clear();
                ////Response.ContentType = "application/pdf";
                //Response.ContentType = "application/octet-stream";
                //Response.AddHeader("content-disposition", "attachment;filename= Test.pdf");
                //Response.Buffer = true;
                //Response.Clear();
                //var bytes = ms.ToArray();
                //Response.OutputStream.Write(bytes, 0, bytes.Length);
                //Response.OutputStream.Flush();
           // }

            return View();
        }

        [HttpPost]
        public ActionResult Save()
        {

// write code here to save the data in database. 
            var fName = string.Format("MYPDF-{0}.pdf", DateTime.Now.ToString("s"));
            using (var ms = new MemoryStream())
            {
                using (var document = new Document(PageSize.A4, 50, 50, 15, 15))
                {
                    PdfWriter.GetInstance(document, ms);
                    document.Open();
                    document.Add(new Paragraph("HelloWorld"));
                    document.Close();
                }

                var bytes = ms.ToArray();              
                Session[fName] = bytes;
            }

            return Json(new { success = true, fName }, JsonRequestBehavior.AllowGet);
            //return View();
        }
         public ActionResult DownloadInvoice(string fName)
         {
             var ms =  Session[fName] as byte[] ;
             if(ms == null)
                 return new EmptyResult();
             Session[fName] = null;
             return File(ms, "application/octet-stream", fName);
         }
    }

Index.cshtml

 <input type="button" id="btnSave" value="Save & Download PDF" />
 
 $(document).ready(function () {
 $("#btnSave").click(function () {
 $.ajax({
 type: 'POST',
 url: "/home/save",
 dataType: "json",
 success: function (resultData)
 {
 if (resultData.success) {
 window.location = "/home/DownloadInvoice" + "?fName=" + resultData.fName;
 }
 }
 });
 })
 })
 

On ajax post method, data will save into the database. Here Save is a post method. Check the HomeController.CS file. Generate file and save an array of byte in Session. In JSON result, send the name of file. Ajax post method retrieve the data and using window.location send request to server to download the file. Now, check DownloadInvoice method in HomeController.cs.

Thank you for reading this post.

UK Postcode Validation

Regular expression for JavaScript

var regPostcode = /^([a-zA-Z]){1}([0-9][0-9]|[0-9]|[a-zA-Z][0-9][a-zA-Z]|[a-zA-Z][0-9][0-9]|[a-zA-Z][0-9]){1}([ ])([0-9][a-zA-z][a-zA-z]){1}$/;

var result = regPostcode.test(SearchTerm);

if (!result) {
alert(“Please enter valid postcode”);
return false;
}

Regular expression for C#

string regPostcode = “([a-zA-Z]){1}([0-9][0-9]|[0-9]|[a-zA-Z][0-9][a-zA-Z]|[a-zA-Z][0-9][0-9]|[a-zA-Z][0-9]){1}([ ])([0-9][a-zA-z][a-zA-z]){1}”;

System.Text.RegularExpressions.Regex regx = new System.Text.RegularExpressions.Regex(regPostcode);

if(!regx.IsMatch(address0.PostalCode))
{
results.Add(new ValidationResult(String.Format(“Please enter valid postcode for {0}.”, addressRank)));
}

You can check the regular expression at http://www.regexplanet.com/

Postal code format and sample postcodes are as below.

Format Example
A9 9AA S1 1AA
A99 9AA M60 1NW
AA9 9AA CR2 6XH
AA99 9AA DN55 1PT
A9A 9AA W1A 1HQ
AA9A 9AA EC1M 1BB

Remove illegal characters from file name or file path in c#

File cannot be saved if file name has illegal characters. So how to remove the illegal characters by a single line code as below. I use LINQ Querty for that.


string fileName = "prakash C/O swami.xml";
fileName = System.IO.Path.GetInvalidFileNameChars().Aggregate(fileName, (current, c) => current.Replace(c.ToString(), string.Empty));

Now the fileName is “rakash CO swami.xml”. The code removes slash ‘/’ because it is a illegal characters. As same any illegal characters will remove using this above code.

Download / Upload Files on FTP Server

Require following ftp details where you want to upload the files:

FTP URL: “ftp://ftp.yoursite.com/”
FTP Username: username
FTP Password: password
FTP Port: 21

Upload File


public string UploadFile(string FtpUrl, string fileName, string userName, string password, string UploadDirectory = "")
        {
            string PureFileName = new FileInfo(fileName).Name;
            String uploadUrl = String.Format("{0}{1}/{2}", FtpUrl, UploadDirectory, PureFileName);
            FtpWebRequest req = (FtpWebRequest)FtpWebRequest.Create(uploadUrl);
            req.Proxy = null;
            req.Method = WebRequestMethods.Ftp.UploadFile;
            req.Credentials = new NetworkCredential(userName, password);
            req.UseBinary = true;
            req.UsePassive = true;
            byte[] data = File.ReadAllBytes(fileName);
            req.ContentLength = data.Length;
            Stream stream = req.GetRequestStream();
            stream.Write(data, 0, data.Length);
            stream.Close();
            FtpWebResponse res = (FtpWebResponse)req.GetResponse();
            return res.StatusDescription;
        }

Download File


 public static string DownloadFile(string FtpUrl,string FileNameToDownload,
                        string userName, string password,string tempDirPath)
    {
        string ResponseDescription = "";
        string PureFileName = new FileInfo(FileNameToDownload).Name;
        string DownloadedFilePath  =  tempDirPath+"/"+PureFileName;
        string downloadUrl = String.Format("{0}/{1}", FtpUrl, FileNameToDownload);
        FtpWebRequest req = (FtpWebRequest)FtpWebRequest.Create(downloadUrl);
        req.Method = WebRequestMethods.Ftp.DownloadFile;
        req.Credentials = new NetworkCredential(userName, password);
        req.UseBinary = true;
        req.Proxy = null;
        try
        {
            FtpWebResponse response = (FtpWebResponse)req.GetResponse();
            Stream stream = response.GetResponseStream();
            byte[] buffer = new byte[2048];
            FileStream fs = new FileStream(DownloadedFilePath, FileMode.Create);
            int ReadCount = stream.Read(buffer, 0, buffer.Length);
            while (ReadCount > 0)
            {
                fs.Write(buffer, 0, ReadCount);
                ReadCount = stream.Read(buffer, 0, buffer.Length);
            }
            ResponseDescription = response.StatusDescription;
            fs.Close();
            stream.Close();
        }
        catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }
        return ResponseDescription;
    }

UnitOfWork Generic Repository

The repository and unit of work patterns are intended to create an abstraction layer between the data access layer and the business logic layer of an application. Implementing these patterns can help insulate your application from changes in the data store and can facilitate automated unit testing or test-driven development (TDD).

UnitOfwork


  public class UnitOfWork : IUnitOfWork
    {
        public DataBaseEntities _context;

        #region Constructor
        public UnitOfWork()
        {
            _context = new DataBaseEntities ();
        }
        #endregion

        #region Implement Inteface Methods

        public void Commit()
        {
            _context.SaveChanges();
        }

        public void CommitAndRefreshChanges()
        {
            bool saveFailed = false;

            do
            {
                try
                {
                    _context.SaveChanges();
                    saveFailed = false;
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    saveFailed = true;

                    ex.Entries.ToList()
                              .ForEach(entry =>
                              {
                                  entry.OriginalValues.SetValues(entry.GetDatabaseValues());
                              });

                }
            } while (saveFailed);
        }

        public void RollbackChanges()
        {
            // set all entities in change tracker 
            // as 'unchanged state'
            _context.ChangeTracker.Entries()
                              .ToList()
                              .ForEach(entry => entry.State = System.Data.Entity.EntityState.Unchanged);
        }

        public IEnumerable ExecuteQuery(string sqlQuery, params object[] parameters)
        {
            return _context.Database.SqlQuery(sqlQuery, parameters);
        }

        public int ExecuteCommand(string sqlCommand, params object[] parameters)
        {
            return _context.Database.ExecuteSqlCommand(sqlCommand, parameters);
        }

        private bool _disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this._disposed)
            {
                if (disposing)
                {
                    _context.Dispose();
                }
            }
            this._disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion

  public List ExecuteQueryForDropdown(string sqlQuery)
        {
            var result = db.Database.SqlQuery(sqlQuery).ToList();
            return result;
        }

 public IQueryable Filter(Expression<Func> filter, string orderByColumnName, bool ascending, out int total, int index = 0, int size = 50)
        {
            int skipCount = index * size;
            var resetSet = filter != null ? table.Where(filter).AsQueryable() : table.AsQueryable();
           
            total = resetSet.Count();


            if (!string.IsNullOrEmpty(orderByColumnName))
            {
                resetSet = resetSet.OrderBy(orderByColumnName, ascending);
                resetSet = skipCount == 0 ? resetSet.Take(size) : resetSet.Skip(skipCount).Take(size);
            }
            return resetSet.AsQueryable();
        }

        #region Repositories

        #endregion
    }

Interface of UnitOfWork


 public interface IUnitOfWork : IDisposable
    {
        /// 
        /// Commit all changes made in a container.
        /// 
        void Commit();

        /// 
        ///  If the entity have fixed properties and any optimistic concurrency problem exists,
        ///  then 'client changes' are refreshed - Client wins
        /// 
        void CommitAndRefreshChanges();

        /// 
        /// Rollback tracked changes. See references of UnitOfWork pattern
        /// 
        void RollbackChanges();

        /// 
        /// Execute specific query with underliying persistence store
        /// 
        /// Entity type to map query results
        /// 
        /// SELECT idCustomer,Name FROM dbo.[Customers] WHERE idCustomer > {0}
        /// 
        /// 
        /// 
        /// 
        IEnumerable ExecuteQuery(string sqlQuery, params object[] parameters);

        /// 
        /// Execute arbitrary command into underliying persistence store
        /// 
        /// 
        /// Command to execute
        /// 
        /// SELECT idCustomer,Name FROM dbo.[Customers] WHERE idCustomer > {0}
        /// 
        ///
        /// A vector of parameters values
        /// The number of affected records
        int ExecuteCommand(string sqlCommand, params object[] parameters);

 List ExecuteQueryForDropdown(string sqlQuery);

        IQueryable Filter(Expression<Func> filter, string orderByColumnName, bool ascending, out int total, int index = 0, int size = 20);
    }

Generic Repository


 public class RepositoryBase where T : class
    {
        internal TSPEntities _dataContext;
        internal DbSet _dbset;

        public RepositoryBase(TSPEntities context)
        {
            this._dataContext = context;
            this._dbset = context.Set();
        }

        /// 
        /// Paging Query with filter
        /// 
        /// 
        /// 
        /// 
        /// 
        public virtual List Get(Expression<Func> filter = null, Func<IQueryable, IOrderedQueryable> orderBy = null, string includeProperties = "")
        {
            IQueryable query = _dbset;

            if (filter != null)
            {
                query = query.Where(filter);
            }

            foreach (var includeProperty in includeProperties.Split
                (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                query = query.Include(includeProperty);
            }

            if (orderBy != null)
            {
                return orderBy(query).ToList();
            }
            else
            {
                return query.ToList();
            }
        }

        /// 
        /// Get selected records with paging
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public virtual IEnumerable GetPaged(int pageIndex, int pageCount, System.Linq.Expressions.Expression<Func> orderByExpression, bool ascending)
        {
            var set = _dbset;

            if (ascending)
            {
                return set.OrderBy(orderByExpression)
                          .Skip(pageCount * pageIndex)
                          .Take(pageCount);
            }
            else
            {
                return set.OrderByDescending(orderByExpression)
                          .Skip(pageCount * pageIndex)
                          .Take(pageCount);
            }
        }

        public virtual void Add(T entity)
        {
            _dbset.Add(entity);
        }

        public virtual void Delete(T entity)
        {
            _dbset.Remove(entity);
        }

        public virtual void Delete(Expression<Func> where)
        {
            IEnumerable objects = _dbset.Where(where).AsEnumerable();
            foreach (T obj in objects)
                _dbset.Remove(obj);
        }

        public virtual T GetById(long id)
        {
            return _dbset.Find(id);
        }

        public virtual T GetById(string id)
        {
            return _dbset.Find(id);
        }

        public virtual IEnumerable GetAll()
        {
            return _dbset.ToList();
        }

        public virtual IQueryable GetAllQueryable()
        {
            return _dbset.AsQueryable();
        }

        public virtual IEnumerable GetMany(Expression<Func> where)
        {
            return _dbset.Where(where).ToList();
        }

        public virtual IQueryable GetManyQueryable(Expression<Func> where)
        {
            return _dbset.AsQueryable().Where(where);
        }

        public T Get(Expression<Func> where)
        {
            return _dbset.Where(where).FirstOrDefault();
        }

 public IQueryable Filter(Expression<Func> filter, string orderByColumnName, bool ascending, out int total, int index = 0, int size = 50)
        {
            int skipCount = index * size;
            var resetSet = filter != null ? table.Where(filter).AsQueryable() : table.AsQueryable();
           
            total = resetSet.Count();


            if (!string.IsNullOrEmpty(orderByColumnName))
            {
                resetSet = resetSet.OrderBy(orderByColumnName, ascending);
                resetSet = skipCount == 0 ? resetSet.Take(size) : resetSet.Skip(skipCount).Take(size);
            }
            return resetSet.AsQueryable();
        }
    }

Export DataTable to Excel/CSV C#


protected void btnExport_Click(object sender, EventArgs e)
    {
        DataTable dtTable = new DataTable();
        DataRow dtRow;

        dtTable.Columns.Add("SNo", typeof(int));
        dtTable.Columns.Add("Address", typeof(string));

        for (int i = 0; i <= 9; i++)
        {
            dtRow = dtTable.NewRow();
            dtRow[0] = i;
            dtRow[1] = "Address " + i.ToString();
            dtTable.Rows.Add(dtRow);
        }

        Response.ContentType = "Application/x-msexcel";
        Response.AddHeader("content-disposition", "attachment;filename=test.csv");
        Response.Write(ExportToCSVFile(dtTable));
        Response.End();
    }

    private string ExportToCSVFile(DataTable dtTable)
    {
        StringBuilder sbldr = new StringBuilder();
        if (dtTable.Columns.Count != 0)
        {
            foreach (DataColumn col in dtTable.Columns)
            {
                sbldr.Append(col.ColumnName + ',');
            }
            sbldr.Append("\r\n");
            foreach (DataRow row in dtTable.Rows)
            {
                foreach (DataColumn column in dtTable.Columns)
                {
                    sbldr.Append(row[column].ToString() + ',');
                }
                sbldr.Append("\r\n");
            }
        }
        return sbldr.ToString();
    }
}

Setup Project in Visual Studio

Create a new project

  • Right click on Soultion Explorer of a Project.
  • Select New Project.
  • Select Project Type ‘Setup and Deployment’ under ‘Other Project Types’.
  • Enter project name in text box in front of Name:
  • Press OK

How do I change the Product Name, Author, Manufaturer, etc?
Select created a project from the Solution Explorer and Press F4. Properties list will appear where you change the Properties of Product like Author, Description of Product, Manufacturer, Product version, Product Name, Product Code etc.

How do I add readme/license form into Setup Wizard?
Select setup project from the solution Explorer and Right click on it. Select ‘View’ option from the context menu than after select ‘User Interface’. User Interface screen will in front of you. Now, right click on ‘Start’ and Select ‘Add Dialog’. A popup will shows up with some forms, from them select Read me form and press OK. Now, click on right Readme form and select ‘Properties Window’ and set Readme File path by selecting .rtf file from Application Folder. Keep in mind for doing this setup you have to create a .rtf document and add into the Application Folder under the File System of the Setup Project.

How do I add shortcuts of Product at User’s Desktop, User’s Program Menu, User’s Startup Folder?
Select setup project from the solution Explorer and Right click on it. Select ‘File System’ option from context menu.
Right Click on Application Folder and select Add->Project Out from the context menu. A popup window will appear, select main Project (source project) and select Primary Output. And press OK. Again right click on Application Folder and select ‘create shortcut. After that rename the Shortcut name and right click on it and select Properties window. Change the Icon property. Keep in mind you have to select the executable file from Application Folder. So the executable file ICON automatically set as Shortcuts Icon.