Sunday, March 31, 2019

Azure Storage Account Part 1 & 2 Codeproject

Thursday, March 28, 2019

Delete Duplicate Rows in SQL Server using Common Table Expression

Introduction:

Sometimes, some duplicate data may be inserted in the SQL table. But it's harmful to you and your application too. So how do you remove the duplicate rows in your table?

Description

Take a look at the following table content. It has duplicate rows.

IdNameDepartment
1Arka.NET
2Ashok.NET
3AnubhavPHP
4Arka.NET
5SudeshnaGraphics

Row 1 and 4 are duplicates. So we have to remove one row and keep one in the table. Now the question is how to do this?

Using the Code

To solve this problem, take a look at the following code. This will solve this problem.

WITH tblTemp as
(
SELECT ROW_NUMBER() Over(PARTITION BY Name,Department ORDER BY Name)
   As RowNumber,* FROM <table_name>
)
DELETE FROM tblTemp where RowNumber >1

After running, this code shows the table data, it will ensure that all unique rows are present.

Friday, July 20, 2018

Deploy your site to Azure App service from Visual Studio

Building your website and publishing it i Azure app service is simpler than publishing the site into a remote machine. There are several methods through which you can publish your site into Azure.

Import publisher file:


This is one of the easiest way t publish your site in Azure app service. First off all create a new app service or if you have an existing one,  open the Overview section of that.
You will find several options on the top of the Overview sections like Browse, Stop, Swap etc. There will be another one named Get Publish Profile. By clicking on that link a new file will be downloaded with .PublishSettings extension.

If you open the file in any text editor, you will find that, it is nothing but a XML file having 2 tags. One for web deployment and another for FTP deployment with your app name. Within that your will also find all the credential for your deployment. Both for FTP and web deploy. But as usual all password will be decrypted so it is harmless.
<publishProfile profileName=" - Web Deploy" 
                 publishMethod="MSDeploy" 
                 publishUrl=".scm.azurewebsites.net:443" 
                 msdeploySite="" 
                 userName="" 
                 userPWD="" 
                 destinationAppUrl="" 
                 SQLServerDBConnectionString="" 
                 mySQLDBConnectionString="" 
                 hostingProviderForumLink="" 
                 controlPanelLink="http://windows.azure.com" 
                 webSystem="WebSites">


 <publishProfile profileName=" - FTP" 
                 publishMethod="FTP" 
                 publishUrl="/site/wwwroot" 
                 ftpPassiveMode="True" 
                 userName="" 
                 userPWD="" 
                 destinationAppUrl="" 
                 SQLServerDBConnectionString="" 
                 mySQLDBConnectionString="" 
                 hostingProviderForumLink="" 
                 controlPanelLink="http://windows.azure.com" 
                 webSystem="WebSites">
Now open your Visual Studio IDE and create a new application. In case you have already created it go to the solution. Right click on the solution -> Click the publish option to open the publish dialog.
Now in the publish dialog you will find an option named “Import”. Click on that option and a File dialog will be opened. Choose your file and click OK. After clicking OK it will automatically redirect to Connection tab in Publish web window.



Now you can choose either Web deploy or FTP from the drop down over there. For both all the fields will be pre populated with all the informations and credentials.

Click on the Validate connection and check our connections from Visual Studio.
Click Next to choose configuration parts. Choose either Debug or Release, whatever is suitable for your applications. You can also manage File publish options from here.
Again click on the Next to go to the Preview section. Click on the Start Preview button if you want to see the files are going to push into the server. Or click Publish (Keyboard: P) to publish the site into your app server.
After successful deployment site will be open automatically in your default browser.
FTP deployment:
There is another quick method to deploy your site into Azure app service through FTP. Go to the Overview section of your app service. In the first section right side you will find the details of FTP connections. Usernames, FTP hostname, FTPS hostname. Password for this deployment will your own account password.
Go to the Visual studio and right click on the solution. Click the publish option and create a new publisher profile. Choose FTP in the Connection tab from Publish method drop down list.
Server: FTP hostname/ FTPS hostnameSite Path: site/wwwroot (Check the passive mode)User name: FTP/deployment usernamePassword: Your account passwordDestination URL: Your site URL


Click on the Validate button to validate your enter details and connection. Click on the publish button to publish your site. After successful publish, site will be open in your default browser automatically. 

Thursday, July 20, 2017

Desktop notification in browser using JavaScript

In most of the sites have today their own desktop notification system to connect user in a large scale. So how to create a desktop notification for your site. Its very simple to generate a new notification using JavaScript, you have to write hardly 2-3 lines of code. Lets create one to generate desktop notification.

To create a new notification for user you have to follow three steps.
  1. Is the browser supports the notification feature. If not show an appropriate message.
  2. Ask user to allow the notification feature to show.
  3. Create a new notification and a click event to fire.
First lets start with whether the browser is supportable to show notification. For this we will use JavaScript Notification object to do all the operation.
 
if (!Notification) {
    alert('Desktop notifications not available in your browser. Try Chromium.');
    return;
}

 And when the user has opened the site prompt user with an box, saying user to allow the site to show notification. For this use follow code block.

document.addEventListener('DOMContentLoaded', function () {
    if (Notification.permission !== "granted")
        Notification.requestPermission();
});

 Now create a button in the body & by clicking on that button a notification will be shown.

<button onclick="notifyMe()">
    Notify me!
</button>

Now in the script section add the Notify() method and write the following piece of code.

function notifyMe() {
    if (!Notification) {
        alert('Desktop notifications not available in your browser. Try Chromium.');
        return;
    }
 
    if (Notification.permission !== "granted")
        Notification.requestPermission();
    else {
        var notification = new Notification('Notification title', {
            icon: 'https://pbs.twimg.com/profile_images/495133521262825472/wxlvCGWy.jpeg',
            body: "Here is your notification!",
        });
 
        notification.onclick = function () {
            window.open("http://asp-arka.blogspot.in/");
        };
    }
}

Here are the full code.

<html>
<button onclick="notifyMe()">
    Notify me!
</button>
<script>
    // request permission on page load
    document.addEventListener('DOMContentLoaded', function () {
        if (Notification.permission !== "granted")
            Notification.requestPermission();
    });
 
    function notifyMe() {
        if (!Notification) {
            alert('Desktop notifications not available in your browser.');
            return;
        }
 
        if (Notification.permission !== "granted")
            Notification.requestPermission();
        else {
            var notification = new Notification('Notification title', {
                icon: 'https://pbs.twimg.com/profile_images/495133521262825472/wxlvCGWy.jpeg',
                body: "Here is your notification!",
            });
 
            notification.onclick = function () {
                window.open("http://asp-arka.blogspot.in/");
            };
        }
    }
</script>
</html>

Host the file in any server like IIS or Apache to run it. Direct running the file in browser won't work out. Click on the Notify button to get the notification. Change the text and image according to your requirement. 

Tuesday, April 11, 2017

Installing TypeScript in Visual Studio

In this first tutorial of TypeScript we will get to know how to install TypeScript in Visual Studio and use it in the same. Starting from the scratch Microsoft provides different extension for TypeScript for different versions of Visual Studio. So I have Visual Studio installed in my PC. So, I will go with VS 13 but for later versions it is almost same to install the TypeScript.


1. To download TypeScritpt for Visual Studio follow the below links
 Download the application and install it.


2. After installing the patch open Visual Studio and create a new web project. Right click on the solution and you can see there is a option in the menu to add TypeScript file.









3. Add the TypeScript file with extension .ts. At the time of adding this file if your project doesn't contain the TypeScript compiler DLL then it will prompt you and will redirect you to Nuget Package Manager to install that.




4. Install the Microsoft.TypeScript.Compiler using Nuget Package Manager or you can download it using Package Manager console.




PM> install-Package Microsoft.TypeScript.Compiler


5. Your TypeScript is ready for coding, Write a few lines of code and save it. after saving you will see a JavaScript file of the same name will be generated in the same domain.




Click on the Show All Files button to show the files that are not included in the project. Within that we will find the JavaScript file of the same name of TypeScript file.











Wednesday, February 22, 2017

How to send encrypted mail in C#

It was a request of one of my client to send the mail as encrypted so that this kept secure while sending to customers. So after a search I found Jason Niver's code to be very handy to use. So I am sharing this will all so next time it becomes little bit easy to get.
 
using System;
using System.Text;
using System.Net.Mail;
using System.IO;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
 
namespace CommonUtilities
{
    //requires reference to System.Security
    class EmailUtil
    {
        public static void SendEncryptedEmail(string[] to, string from, string subject, string body, string[] attachments)
        {
            MailMessage message = new MailMessage();
            message.From = new MailAddress(from);
            message.Subject = subject;
 
            if (attachments != null && attachments.Length > 0)
            {
                StringBuilder buffer = new StringBuilder();
                buffer.Append("MIME-Version: 1.0\r\n");
                buffer.Append("Content-Type: multipart/mixed; boundary=unique-boundary-1\r\n");
                buffer.Append("\r\n");
                buffer.Append("This is a multi-part message in MIME format.\r\n");
                buffer.Append("--unique-boundary-1\r\n");
                buffer.Append("Content-Type: text/plain\r\n");  //could use text/html as well here if you want a html message
                buffer.Append("Content-Transfer-Encoding: 7Bit\r\n\r\n");
                buffer.Append(body);
                if (!body.EndsWith("\r\n"))
                    buffer.Append("\r\n");
                buffer.Append("\r\n\r\n");
 
                foreach (string filename in attachments)
                {
                    FileInfo fileInfo = new FileInfo(filename);
                    buffer.Append("--unique-boundary-1\r\n");
                    buffer.Append("Content-Type: application/octet-stream; file=" + fileInfo.Name + "\r\n");
                    buffer.Append("Content-Transfer-Encoding: base64\r\n");
                    buffer.Append("Content-Disposition: attachment; filename=" + fileInfo.Name + "\r\n");
                    buffer.Append("\r\n");
                    byte[] binaryData = File.ReadAllBytes(filename);
 
                    string base64Value = Convert.ToBase64String(binaryData, 0, binaryData.Length);
                    int position = 0;
                    while (position < base64Value.Length)
                    {
                        int chunkSize = 100;
                        if (base64Value.Length - (position + chunkSize) < 0)
                            chunkSize = base64Value.Length - position;
                        buffer.Append(base64Value.Substring(position, chunkSize));
                        buffer.Append("\r\n");
                        position += chunkSize;
                    }
                    buffer.Append("\r\n");
                }
 
                body = buffer.ToString();
            }
            else
            {
                body = "Content-Type: text/plain\r\nContent-Transfer-Encoding: 7Bit\r\n\r\n" + body;
            }
 
            byte[] messageData = Encoding.ASCII.GetBytes(body);
            ContentInfo content = new ContentInfo(messageData);
            EnvelopedCms envelopedCms = new EnvelopedCms(content);
            CmsRecipientCollection toCollection = new CmsRecipientCollection();
            foreach (string address in to)
            {
                message.To.Add(new MailAddress(address));
                X509Certificate2 certificate = null; //Need to load from store or from file the client's cert
                CmsRecipient recipient = new CmsRecipient(SubjectIdentifierType.SubjectKeyIdentifier, certificate);
                toCollection.Add(recipient);
            }
 
            envelopedCms.Encrypt(toCollection);
            byte[] encryptedBytes = envelopedCms.Encode();
 
            //add digital signature:
            SignedCms signedCms = new SignedCms(new ContentInfo(encryptedBytes));
            X509Certificate2 signerCertificate = null; //Need to load from store or from file the signer's cert
            CmsSigner signer = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, signerCertificate);
            signedCms.ComputeSignature(signer);
            encryptedBytes = signedCms.Encode();
            //end digital signature section
 
            MemoryStream stream = new MemoryStream(encryptedBytes);
            AlternateView view = new AlternateView(stream, "application/pkcs7-mime; smime-type=signed-data;name=smime.p7m");
            message.AlternateViews.Add(view);
 
            SmtpClient client = new SmtpClient("your.smtp.mailhost");
            //add authentication info if required by your smtp server etc...
            //client.Credentials = CredentialCache.DefaultCredentials;
            client.Send(message);
        }
    }
}


Now its time to install the certificate, for this go with the bellow codes.


using System.Security.Cryptography.X509Certificates;
 
private X509Certificate GetCertificate()
{
    X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
    store.Open(OpenFlags.ReadOnly);
    X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySerialNumber, “123456”, true);
    store.Close();
    return certs[0];
}


Sources:
1. Sending encrypted mail
2. Using certificates from the Windows certificate store

Popular Posts

Pageviews