Wednesday, July 6, 2016

Document Upload in Azure Cloud with ASP.Net MVC

  • Configure Azure storage connection string

To configure your connection string, open the web.config or app.config file from Solution Explorer in Visual Studio.Add below line in <appSettings> tag of your config file. Replace "your account name" with the name of your storage account, and "your account key" with your account access key:
<add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=<your account name>;AccountKey=<your account key>" />
  • Parse the connection string from Config file
The Microsoft Azure Configuration Manager Library for .NET provides a class for parsing a connection string from a configuration file.
below is example that shows to retrieve a connection string from a configuration file:
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
Above line will parse CloudStorageAccount from your connection string.
  • Create the Blob service client
The CloudBlobClient class enables you to retrieve containers and blobs stored in your storage. Here's one way to create the service client:
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

  • Create Containers for  Blob service Client
Below example shows how to create a container for blob service client, you can create different containers for different users by replacing your names with "<container name>" in below code and also shows how to set permissions for that perticular container :
CloudBlobContainer container = blobClient.GetContainerReference(<container name>);
if (container.CreateIfNotExists())
 {
           container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
 }

For defining container name there are basic rules are there, which are as follows :
  1. Container names must start with a letter or number, and can contain only letters, numbers, and the dash (-) character.
  2. Every dash (-) character must be immediately preceded and followed by a letter or number; consecutive dashes are not permitted in container names.
  3. All letters in a container name must be lowercase.
  4. Container names must be from 3 through 63 characters long.
  • Create Blob into Containers
To upload a file to a block blob, get a container reference as shown above and use it to get a block blob reference. Once you have a blob reference, you can upload any stream of data to it by calling the UploadFromStream method. This operation will create the blob if it didn't previously exist, or overwrite it if it does exist.
The following example shows how to upload a blob into a container which is already created :
CloudBlockBlob blob = container.GetBlockBlobReference(fileName);
blob.UploadFromStream(upload.InputStream);

Now, you can get that files or data by using blob.Uri.AbsoluteUri, this will give you url for download or display data or files that you uploaded into
blob container. Or you can use below line of code for download stream of data which uploaded uisng  UploadFromStream function :

// Retrieve reference to a blob named .
CloudBlockBlob blockBlob = container.GetBlockBlobReference(<blob name>);
// Save blob contents to a file.
using (var fileStream = System.IO.File.OpenWrite(@"path\myfile"))
{
    blockBlob.DownloadToStream(fileStream);
}
In above code, first it will retreive refernce of blob which you want to download, and then it will transfer the blob contents to a stream object and then save that stream into file which given as "@"path\myfile".
Delete blob from Container :

To delete a blob, first get a blob reference and then call the Delete method of that blob as shown below :
// Retrieve reference to a blob
CloudBlockBlob blockBlob = container.GetBlockBlobReference(<blob name>);

// Delete the blob.
blockBlob.Delete();

Thursday, May 12, 2016

Export excel and Pdf with Kendo UI MVC c#

Export to Excel and Pdf

  • Export excel and pdf is now a days a basic needs of clients for saving reports or tables data.
  • Kendo UI has build features for exporting table data to excel and pdf with Excel() and Pdf() functions.
  • Functions are used as below.
 @(Html.Kendo().Grid(Model)
    .Name("timeGrid")
    .NoRecords()
    .Columns(columns =>
    {
        columns.Bound(p => p.Field1).Title("Field1");
        columns.Bound(p => p.Field2).Title("Field2");
        columns.Bound(p => p.Field3).Title("Field3");
    }).Groupable()
       .Sortable()
    .Excel(excel => excel
       .FileName("FileName.xlsx").AllPages(true)
       .Filterable(true)
       .ProxyURL(Url.Action("Excel_Export_Save", "Controller"))
    )
             .Pdf(pdf => pdf
                .AllPages()
                .FileName("FileName.pdf").ForceProxy(true)
                .ProxyURL(Url.Action("Pdf_Export_Save", "Controller"))
            )
    .ToolBar(tools => tools.Excel())
    .ToolBar(tools => tools.Pdf())
    .Filterable()
    .Pageable().DataSource(dataSource => dataSource
        .Ajax()
        .PageSize(10)
        .ServerOperation(false)
    )
                )
  • Place above code in your View page, in above code the use of Excel() and Pdf() function in Kendo MVC.
  • For Generating buttons for Excel and Pdf export Toolbar() function is used shown in code.
  • In above their sub-functions which are used like FileName(), ProxyURL(),etc. are used to customize Excel and Pdf.
  • FileName() : This function is used to give file name.
  • ProxyURL() : Sometimes client wants reports or file in different format or customize view in file at that time ProxyURL() function is used to create customize file. ProxyURL() generally takes two arguments like action name and controller name.
    Proxy URL
    ProxyURL Action in Controller
  • Filterable() : This function takes one argument i.e. true or false. If you passed true and then it will allows filtration in generated excel which you used in table.
  • AllPages() : AllPages() function indicates your generated Pdf or Excel file will contains pages of grid or not.It will takes argument as true or false.
Above how you can use Excel(),Pdf() and Toolbar() function for exporting grid data to Excel and Pdf file.

Click Here To Demo For Export to Excel with Kendo Grid 

Click Here To Demo For Export to PDF with Kendo Grid 

Hope this will help you. Keep coding... :)

Friday, April 29, 2016

File Upload uisng Jquery in C# ASP.Net MVC

There so many ways to upload files with jqueries in ASP.Net C#. One way is with creating XMLHttpRequest and another way is with FormData object.
In this post i'll show uploading files and saving form data in one ajax call using jquery.


Upload Files with Jquery in ASP.Net MVC C#

First code for View which represents normal html code of form

@model modelname



MVC Controller Code for Saving File
In controller create action method with two arguments one is for formdata and another one is for List of HttpPostedFileBase Class which represents multiple files that you select.
public JsonResult SaveFilesWithFormData(ModelName FormData, List Of HTTPPostedFileBase Files) //Model Name represents class provided in view
{           
    try
    {
        //logic for saving data into database

        //save multiple files
        foreach (var upload in File)
        {
            if (upload != null)
            {
                 string pathToSave = "folderpath";

                 //Check folder is exist or not if not then it will creates folder
                 if (!Directory.Exists(pathToSave))
                 {
                     Directory.CreateDirectory(pathToSave);
                 }

                 //get file name for selected file            
                 string filename = Path.GetFileName(upload.FileName);

                 //save file
                 upload.SaveAs(pathToSave + filename);
            }
        }
        msg = "Success";
    }
    catch (Exception ex)
    {
        Log.Error(ex.Message);
    }
    return Json(msg, JsonRequestBehavior.AllowGet);
}

Hope that above code will help you to save files easily with form data into server. Keep coding

Saturday, April 2, 2016

Display image from byte array in ASP.NET MVC

There are many ways to display image from byte array in MVC as well as normal ASP.Net projects.In this post I'll explain couple of them.

1) Using BASE64 string of the image through ViewBag 

The first way is by sending a Base64 string as dataURL through ViewBag. As shown in below action method under consideration generates such a Base64 string of the image (often called Data URL) and then pass it to the view via a ViewBag property in MVC.
public ActionResult Image()
{
    string path = Server.MapPath("~/images/computer.png");
    byte[] imageByteData = System.IO.File.ReadAllBytes(path);
    string imageBase64Data=Convert.ToBase64String(imageByteData);
    string imageDataURL= string.Format("data:image/png;base64,{0}", imageBase64Data);
    ViewBag.ImageData = imageDataURL;
    return View();
}
The above code is a action method of Controller. In this action method it uses physical path of image and read all bytes of that image using ReadAllBytes() method. Once it read all bytes of that image in form of byte array,it will converts that byte array into base64 string format.

This converted base64 string is used to generate dataURL as shown in code. Take care of not to forget to append data:image/png;base64 at beginning of base64 string as shown.This way the browser knows that the src attribute value itself contains the image data. and at last assign value of dataURL to ViewBag.and then just below line in View to use that ViewBag.
 
Output :


2) By Sending Image File as ActionResult

In this approach it will reads byte array from image physical path and creates one file, after this it will send that file as result of action method in Controller.
public ActionResult GetImageFile()
{
    string path = Server.MapPath("~/images/computer.png");
    byte[] imageByteData = System.IO.File.ReadAllBytes(path);
    return File(imageByteData, "image/png"); 
}
To use the GetImageFile() action method you have to write below line in View:
<img src='@Url.Action("GetImageFile", "Home")'/>
Hope this will help you.

Sunday, March 13, 2016

C# Currency Converter using Google API

Currency conversion in C# using Google API

  • There are so many ways to convert amount from one currency to another currency like using google finance converter, Yahoo finance and rate-exchange.
  • In this post i will show conversion using Google Finance Converter.
  • In below code, I create one WebRequest for Google Finance Converter which will return result of arguments which are attached with it.
  • Get the response of WebRequest in form of Stream and stored it in streamReader (which is the object of StreamReader Class).
  • By using, Regex fetched converted amount with desired currency code and stored this result into a string variable and again using Regex fetched only decimal part from generated string.
Hope this post will help you to get the exact result that you want.
public string CurrencyConvert(decimal amount, string fromCurrency, string toCurrency)
{
      decimal currency = 0;
      string convertedAmount = "0";
      try
      {
          string url = string.Format("https://www.google.com/finance/converter?a={2}&from={0}&to={1}", fromCurrency.ToUpper(), toCurrency.ToUpper(), amount);
          WebRequest request = WebRequest.Create(url);
          StreamReader streamReader = new StreamReader(request.GetResponse().GetResponseStream(), System.Text.Encoding.ASCII);
          string result = Regex.Matches(streamReader.ReadToEnd(), "([^<]+)")[0].Groups[1].Value;
          string rs = new Regex(@"^\D*?((-?(\d+(\.\d+)?))|(-?\.\d+)).*").Match(result).Groups[1].Value;
          if (decimal.TryParse((new Regex(@"^\D*?((-?(\d+(\.\d+)?))|(-?\.\d+)).*").Match(result).Groups[1].Value), out currency))
          {
              convertedAmount = currency.ToString("0.00");
          }
      }
      catch (Exception ex)
      {
          throw ex;
      }
      return convertedAmount;
}

Monday, February 29, 2016

Allow only numbers in textbox jquery

  • For allowing only numbers in textbox using jQuery, you can create key-press or key-down or key-up event for textbox by using textbox id or class.
  • In below example i used class name ("number") for applying validation to textbox. 
  • You just had copy above code and paste where you want to apply numeric validation.

For allowing numbers with decimal points 

Friday, February 19, 2016

Url rewrite for non-www to www in C#

  • WWW version is very useful to make your web site easily searchable by web crawler also WWW version helps to increase your chances make your web site rank higher in SEO purpose.
  • One common use of URL Rewrite is redirecting http://domain.com to http://www.domain.com.  Many people are doing this for search engine optimization (SEO) so that search engines only see the one site, rather than two sites.  The goal is to set a permanent 301 redirect. 
  • URL Rewrite works at the global level, or site level (or application level for that matter).  Where you apply it is really up to how you manage your server.  Either will work for a domain name redirect like this.
    You can choose to create the rules using IIS Manager, or using a text editor and updating web.config directly.
  • For specifying non-WWW version to WWW version for your web site in C#.net, write below code in web.config inside system.webServer tag,

Wednesday, February 17, 2016

Check valid JSON String

To check whether entered string is in valid json format or not. Use below link.
Check Valid JSON


If you entered valid json string it will show output as shown in below image :
Not Valid Json String


If you entered invalid json string it will show output as shown in above image
Valid JSON string

Sunday, February 7, 2016

MVC CRUD Operations Using jQuery JSON and LINQ To SQL Class

Step 1 : Database

Create an EmployeeData table in a SQL database as in the following


Step 2 : LINQ to SQL class

Create a LINQ to SQL class to read data from the table as in the following:

Add Linq to Sql Class

After using the Server Explorer and adding an EmployeeData table in the surface area as in the following:
Add Table
Now add a controller to the CRUD operations for EmployeeData.

So open the Solution Explorer and right-click on the controller folder and add a controller as in the following:

Select Controller

Add Controller Name

Step 3 : Controller 


Now create a select controller, an insert controller, an edit controller and a the Delete controller as in the following:

Step  4 : View

Now create a view and a partialview on a right-click corresponding to the controller as in the following:
Add view to controller


1. Index View (select data)
Add Index view

In this figure see the view name is auto create, it's not changed. After selecting a Template and Model class as shown in the following figure.

2. Create View (Insert data)
Create a view to create a partial view .
Add Create view

This section also created a script for the model data insert into the table.

Create View Code

3. Edit View (Update Employee)
Also create an Editview as a Partial view.
Add Edit View

Edit view code

In this view also create an update record script as in the following.
Finally all the operation views are created and can be seen in the project solution. 

Step: Models

Now create a Model for EmployeeInfo as in the following:

Add Models class

class

Models Class Code
Now run your MVC example in a browser.
Run Application

Now click the Add New Employee button and insert a record as in the following:
Add Record

Now delete the record without 130 with the delete button.
Record Delete


Selected Record open with edit dialog

Press the update button and close the dialog and check the record in the webgrid.
Record Update

Thursday, January 7, 2016

Add google translator to website

For adding google language tranlator to your web site click on below link

Add google translator to website

Step 1 :  
  • Enter your website url and select default language which you want to apply when your website loads first. 

Step 2 : 
  • Select languages which you want to use for your website to be translated.You select use all languages or specific languages,
  • Select display mode for language translator display like vertical, horizontal or dropdown only.
  • Based on your requirements select advanced options.
  • Click on Get Code button to get code for translator plugin.

Plugin Settings

Step : 3  
  • Copy code from which shown in textbox and paste that code where you want to display translator in your website.
Plugin Code