European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Create A Password Protected PDF In MVC

clock February 19, 2019 10:37 by author Peter
Sometimes, we need to create a PDF file that opens only when the users put in a password when prompted. Let us see how to create a password-protected PDF file in MVC.

First, let's open Visual Studio and create a new project. We need to select the ASP.NET Web application type.

Select Web API as the template and in the "Add folders and core references" section, we need to select MVC and Web API. Click on "Change Authentication" on the right side pane and select "No Authentication".

 

In the web.config file, let us define one key named Filepath and use it in our code. The PDF file must be present there.

It is good to change the key's value when it's placed in web.config.
<appSettings> 
     <add key="FilePath" value="Anil\PDF\LDEPRD9.pdf"/> 
 </appSettings> 


Add the below code to the Home Controller.
string FilePath = ConfigurationManager.AppSettings["FilePath"].ToString(); 
public ActionResult DownloadFile() 

    try 
    { 
        byte[] bytes = System.IO.File.ReadAllBytes(FilePath); 
        using (MemoryStream inputData = new MemoryStream(bytes)) 
        { 
        using (MemoryStream outputData = new MemoryStream()) 
        { 
        string PDFFilepassword = "123456"; 
        PdfReader reader = new PdfReader(inputData); 
        PdfReader.unethicalreading = true; 
PdfEncryptor.Encrypt(reader, outputData, true, PDFFilepassword, PDFFilepassword, PdfWriter.ALLOW_SCREENREADERS);
        bytes = outputData.ToArray(); 
        Response.AddHeader("content-length", bytes.Length.ToString()); 
        Response.BinaryWrite(bytes); 
        return File(bytes, "application/pdf"); 
       } 
      } 
    } 
    catch (Exception ex) 
    { 
        throw ex; 
    } 


string PDFFilepassword = "123456";   
PdfReader reader = new PdfReader(inputData);   
PdfReader.unethicalreading = true;   
PdfEncryptor.Encrypt(reader, outputData, true, PDFFilepassword, PDFFilepassword, PdfWriter.ALLOW_SCREENREADERS); 


In the PDFFilepassword variable, you can set anything as password - the file name, PAN card number, or you can validate the entered value against the values stored in the database.

In Route.config, we can define the default route with the Controller And ActionName.

Run the website and enter http://localhost:49744/Home/DownloadFile. 

Here, Home is the controller name and DownloadFile is the action name. 

It shows the following Password prompt.

 

After entering the right password and successful authentication, the PDF file will get opened.

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Server Sent Events In ASP.NET MVC

clock February 15, 2019 08:14 by author Peter

In some Web Applications, we need to show real time data to the end users, which means if any changes occur (new data available) in the Server, it needs to show an end user. For instance, you are doing chat in Facebook in one tab of your Browser. You opened another tab in the same Browser and send a message to the same user (with whom, you are doing chat in the previous chat). You will see that message will appear in both the tabs and it is called real-time push.

In order to accomplish the functionality, mentioned above, the client sends interval basis AJAX requests to the Server to check, if the data is available or not. ServerSentEvents(SSE) API helps ensure the Server will push the data to the client when the data is available in the Server.

What are Server Sent Events?
SSE is an acronym and stands for Server Sent Events. It is available in HTML5 EventSource JavaScript API. It allows a Web page to get the updates from a Server when any changes occurs in the Server. It is mostly supported by the latest Browsers except Internet Explorer(IE).

Using code
We are going to implement a requirement like there is a link button and click on it and it displays current time each second on an interval basis.
In order to achieve the same, we need to add the following action in HomeController. It sets response content type as text/event-stream. Next, it loops over the date and flushes the data to the Browser.
    public void Message() 
    { 
        Response.ContentType = "text/event-stream"; 
     
        DateTime startDate = DateTime.Now; 
        while (startDate.AddMinutes(1) > DateTime.Now) 
        { 
            Response.Write(string.Format("data: {0}\n\n", DateTime.Now.ToString())); 
            Response.Flush(); 
     
            System.Threading.Thread.Sleep(1000); 
        } 
         
        Response.Close(); 
    }


Once we are done with the Server side implementation, it's time to add the code in the client side to receive the data from the Server and displays it.

First, it adds a href link, which calls initialize() method to implement SSE. Second, it declares a div, where the data will display. Thirdly, it implements Server Sent Events(SSE) through JavaScript with the steps, mentioned below.
    In the first step, it checks whether SSE is available in the Browser or not. If it is null, then it alerts to the end user to use other Browser.
    In the second step, if SSE is available, then it creates EventSource object with passing the URL as a parameter. Subsequently, it injects the events, mentioned below.

        onopen- It calls when the connection is opened to the Server
        onmessage- It calls when the Browser gets any message from the Server
        onclose- It calls when the Server closes the connection.

    <a href="javascript:initialize();" >Click Me To See Magic</a> 
    <div id="targetDiv"></div> 
     
    <script> 
         
        function initialize() { 
            alert("called"); 
     
            if (window.EventSource == undefined) { 
                // If not supported 
                document.getElementById('targetDiv').innerHTML = "Your browser doesn't support Server Sent Events."; 
                return; 
            } else { 
                var source = new EventSource('../Home/Message'); 
     
                source.onopen = function (event) { 
                    document.getElementById('targetDiv').innerHTML += 'Connection Opened.<br>'; 
                }; 
     
                source.onerror = function (event) { 
                    if (event.eventPhase == EventSource.CLOSED) { 
                        document.getElementById('targetDiv').innerHTML += 'Connection Closed.<br>'; 
                    } 
                }; 
     
                source.onmessage = function (event) { 
                    document.getElementById('targetDiv').innerHTML += event.data + '<br>'; 
                }; 
            } 
        } 
    </script>


Output

Here, we discussed about SSE(Server Sent Events). It is very important API available in HTML5. It helps to push data from the Server to the client when any changes occurs in the Server side. If you want to use a bidirectional communication channel, you can use HTML5 Web Sockets API. The disadvantage of SSE is it is Browser dependent. If the Browser doesn't support SSE, then the user can't see the data, but it is easy to use it. You can also use SignalR for realtime pushing the data to the end user.

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.

 



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in