Monday, November 9, 2015

SQL Server 2012 : Working with FileTables

Hi Guys,

I had a requirement to store files in the database. But had an issue with storage as the files were growing, so my project leader asked me to come up with a solution. Then I found about FileStream and FileTables. So thought of sharing my experience.

1) Enable FileStream in your instance
Go to Configuration Manager, select the instance -> Properties -> FileStream Tab



2) Enable FileStream on your Server
Go to SQL Server Management Studio, select server -> Properties -> Advanced ->FileStream -> FileStream Access Level -> Full Access Enabled 




3) Create Database with FileStream

CREATE DATABASE Archive 
ON
PRIMARY ( NAME = Arch1,
    FILENAME = 'd:\FileStorage\archdat1.mdf'),
FILEGROUP FileStreamGroup1 CONTAINS FILESTREAM( NAME = Arch3,
    FILENAME = 'd:\FileStorage\filestream1')
LOG ON  ( NAME = Archlog1,
    FILENAME = 'd:\FileStorage\archlog1.ldf')
GO


4) Specify FileStream Directory Name
Go to SQL Server Management Studio, select database -> Properties -> Options ->FileStream -> FileStream Directory Name  -> Provide Any Name



5) Create FileTable 

USE Archive

IF OBJECT_ID('dbo.TestFileTable', 'U') IS NOT NULL
  DROP TABLE dbo.TestFileTable
GO

CREATE TABLE dbo.TestFileTable AS FILETABLE
  WITH
  (
    FILETABLE_DIRECTORY = 'ArchiveFileTable', --This name must be the name given in 3rd Step
    FILETABLE_COLLATE_FILENAME =  database_default
  )
GO

6) Add Files to your FileTable

There are three ways you can do this.

  • Drag and drop files from the source folders to the new FileTable folder in Windows Explorer.
  • Use command line options such as MOVE, COPY, XCOPY, or ROBOCOPY from the command prompt or in a batch file or script.
  • Write a custom application in C# or Visual Basic.NET that uses methods from the System.IO namespace to move or copy the files.




7) Insert Files to your FileTable using TSQL

INSERT INTO [dbo].[TestFileTable]([name],[file_stream])SELECT'NewFile.txt', * FROM OPENROWSET(BULK N'd:\NewFile.txt'SINGLE_BLOB)AS FileData
GO


Tuesday, August 11, 2015

iCreativator Lite App using Angular, Ionic, glfx.js

Hi Guys,

This time I made very lightweight Image Editor App, which allows users to select an existing image and add some effects on it. In the future I will enable it to be saved to the device. Hope you like it.








High Contrast Effect

High Brightness Effect


High Hue Effect
Sepia Effect

High Saturation Effect



Denoise Effect



Lens Blur Effect

Ink Effect

Thursday, August 6, 2015

MyFinance App using Iconic, Apache Cordova, Microsoft Azure Mobile Services

Hi Guys,

I am having some fun with Aprache Cordova in Vs 2015. just wanted to show you guys a glimpse of what I am doing right now. 







Sunday, July 26, 2015

Hybrid Apps in VS 2015 using AngularJS, Angular Material, Web Api

Hi Guys,

Finally VS 2015 is out there. And It supports multi platform mobile application development in two ways,

1) Hybrid Apps (Javascript,Typescript, Apache Cordova)
2) Native Apps (C#,Xamarin)

Since I am a fan of javascript frameworks (AngularJs). I thought of doing my tasks project using Hybrid Apps. Hope you like it. Since I have reused the same AngularJS Application I created before I am not going to publish the code again. For my previous posts regarding my tasks Click Here.










Tuesday, June 16, 2015

Progress Notification for Long Running Methods using WCF Duplex Binding, SignalR

Hi Guys,

This time I made a WCF Duplex Service which notifies the progress to the client using SingalR. Hope you like it.













Windows Client









1) ServiceClient.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ServiceClient.aspx.cs" Inherits="Htm5Notifications.ServiceClient" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="../Scripts/jquery-1.6.4.js"></script>    
    <script src="../Scripts/jquery.signalR-2.2.0.js"></script>
    <script src="http://localhost:51255/signalr/hubs/" type="text/javascript"></script>
    <script src="Message.js"></script>
    <link href="../Styles/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="hidden" id="hfHubName" value="<%= string.Format("#{0}",hfHubId.ClientID) %>" />
        <asp:HiddenField ID="hfHubId" runat="server" />
    <div class="progress">
  <div id="progressBar" class="progress-bar progress-bar-success progress-bar-striped" role="progressbar"
  aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width:10%" >
   
  </div>
</div>
        <br />
        <asp:Button runat="server" CssClass="btn-primary" ID="btnStart" OnClick="btnStart_Click" Text="Start Long Process" />
    </div>
    </form>
</body>

</html>

2) DuplexService.svc.cs

public class DuplexService : IDuplexService
    {
        public void DoWork()
        {
            for (int i = 0; i < 100; i++)
            {
                System.Threading.Thread.Sleep(1000);
                Callback.Progress(i + 1);
            }
        }

        IDuplexServiceCallback Callback
        {
            get
            {
                return OperationContext.Current.GetCallbackChannel<IDuplexServiceCallback>();
            }
        }

    }

[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples", SessionMode = SessionMode.Required,
                 CallbackContract = typeof(IDuplexServiceCallback))]
    public interface IDuplexService
    {
        [OperationContract(IsOneWay = true)]
        void DoWork();
    }

   public interface IDuplexServiceCallback
   {
       [OperationContract(IsOneWay = true)]
       void Progress(int percentage);
       

   }

3) MessageHub.cs

[HubName("messageHub")]
    public class MessageHub : Hub
    {

     
        [HubMethodName("setPercentage")]
        public static void SetPercentage(string cId,string percentage)
        {

            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MessageHub>();
            context.Clients.All.setPercentage(cId,percentage);

        }   


    }

4) Message.js
/// <reference path="../Scripts/jquery-1.6.4.js" />
/// <reference path="../Scripts/jquery.signalR-2.2.0.js" />


$(function () {

    //Instance of the Hub
    
    function setPercent(cid, percent)
    {
        alert($($('#hfHubName').val()).val());
        alert(cid);
        if ($($('#hfHubName').val()).val() == cid) {
            $('#progressBar').text(percent + "% Completed!");
            $('#progressBar').attr("aria-valuenow", percent);
            $('#progressBar').css("width", percent + "%");
        }
    }

    var messageHub = $.connection.messageHub;
    messageHub.client.showMessage = function (cpu, mem, proc, thread, cmem, memUse) {
        show(cpu, mem,proc, thread,cmem,memUse);
    }

    messageHub.client.setPercentage = function (cid, percentage)
    {
        setPercent(cid, percentage);
    }

    $.connection.hub.url = "http://localhost:51255/signalr";
    $.connection.hub.start().done(function () {
        if ($($('#hfHubName').val()).val() == '')
        $($('#hfHubName').val()).val($.connection.hub.id);
        
    }).fail(function (error) {
        console.error(error);
    });;


    

});






Wednesday, May 27, 2015

Multiple File Uploading using Javascript and Web API

Hi Guys,

I had a requirement to make way to upload multiple files using basic htmls. So I used javascript to achieve this. Hope you like it.





1) MultiFileUpload.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MulitpleFileUpload.aspx.cs" Inherits="MulitpleFileUpload" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
     <script>
         function addRow() {
             var table = document.getElementById('myTable');
             var row = table.insertRow(0);
             var cell1 = row.insertCell(0);
             var cell2 = row.insertCell(1);
             var cell3 = row.insertCell(2);
             cell1.setAttribute("class", "formLabelTd");
             cell2.innerHTML = "<input type='File' />";
             cell2.setAttribute("class", "formControlTd");
             cell1.innerHTML = "<input type='text'  />";
         }





         function saveFiles() {

             var data = new FormData();




             var x = document.getElementById("myTable").getElementsByTagName("INPUT");
             var y = [];
             var imageFile;


             if (Validate()) {

                 var id = 1;
                 for (var cnt = 0; cnt < x.length; cnt++) {
                     if (x[cnt].type == "file") {
                         imageFile = x[cnt];
                         data.append("UploadedImage" + id, imageFile.files[0]);
                         id++;
                     }
                     else if (x[cnt].type == "text") {
                         data.append("UploadedText" + id, x[cnt].value);

                     }

                 }
                 


            var xhr = getXMLHttpRequest();
            xhr.open("POST", "/api/FileUpload/UploadFile", true);

            xhr.send(data);
            return true;
        }
        else
            return false;


    }

    function getXMLHttpRequest() {
        if (window.XMLHttpRequest) {
            return new window.XMLHttpRequest;
        }
        else {
            try {
                return new ActiveXObject("MSXML2.XMLHTTP.3.0");
            }
            catch (ex) {
                return null;
            }
        }
    }

    var message = 'File Extension Must be (PDF, DOC, DOCx, JPG, JIF, TIFF)';

    var _validFileExtensions = [".jpg", ".tiff", ".pdf", ".doc", ".docx"];
    function Validate() {
        var arrInputs = document.getElementById("myTable").getElementsByTagName("input");
        for (var i = 0; i < arrInputs.length; i++) {
            var oInput = arrInputs[i];
            if (oInput.type == "file") {
                var sFileName = oInput.value;
                if (sFileName.length > 0) {
                    var blnValid = false;
                    for (var j = 0; j < _validFileExtensions.length; j++) {
                        var sCurExtension = _validFileExtensions[j];
                        if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
                            blnValid = true;
                            break;
                        }
                    }

                    if (!blnValid) {
                        document.getElementById("spMore").innerText = message;
                        return false;
                    }
                }
            }
        }
        document.getElementById("spMore").innerText = "";
        return true;
    }



</script>
<body>
    <form id="form1" runat="server">
    <div>
     <form name="formUpload" id="formUpload" enctype="multipart/form-data">
                                <span style="color:red" id="spMore"></span>
                                 <table width="50%" id="myTable">
                                        <td width="20%" class="formLabelTd">
                            <input type="text" />
                                            
                        </td>
                        <td Width="75%" class="formControlTd">
                            <input type="file"  />
                            
                            
                        </td>
                                     <td width="5%">
                                         <img style="float:right" src="Images/Add.png" onclick="addRow()" />
                                     </td>
                                    </table >
                                 
    </form>
        <input type="button" value="Upload Files" onclick="saveFiles()" />
    </div>
    </form>
</body>

</html>

2) FileUploadController.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

public class FileUploadController : ApiController
{
    [HttpPost]
    public void UploadFile()
    {
        try
        {
            if (HttpContext.Current.Request.Files.AllKeys.Any())
            {
                string uploadText;
                int fileSize_AttachedFile;
                byte[] fileContent_AttachedFile;
                File objFile;
                BinaryReader oBinaryReader_AttachedFile;
               
                // Get the uploaded image from the Files collection
                for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++)
                {
                    var httpPostedFile = HttpContext.Current.Request.Files["UploadedImage" + (i + 1)];

                    if (httpPostedFile != null)
                    {
                        uploadText = HttpContext.Current.Request.Form["UploadedText" + (i + 1)];
                        //Save the File
                        using (LocationDataDataContext context = new LocationDataDataContext())
                        {
                            oBinaryReader_AttachedFile = new BinaryReader(httpPostedFile.InputStream);
                            fileSize_AttachedFile = Convert.ToInt32(httpPostedFile.ContentLength);
                            fileContent_AttachedFile = oBinaryReader_AttachedFile.ReadBytes(fileSize_AttachedFile);

                            objFile = new File() { FileBytes = fileContent_AttachedFile,
                                FileName = Path.GetFileName(httpPostedFile.FileName),
                                                        Remarks = uploadText
                            };

                            context.Files.InsertOnSubmit(objFile);
                            context.SubmitChanges();


                        }
                    }


                }


            }
        }
        catch
        {

        }
    }

}