Wednesday 8 August 2018

How to execute SQL against all DBs on a Server

One option is sp_MSForEachDB. It's undocumented but useful nonetheless

DECLARE @command varchar(1000) 
SELECT @command = 
 'USE [?] SELECT c.name AS ColName, t.name AS TableName FROM sys.columns c JOIN 
sys.tables t ON c.object_id = t.object_id WHERE c.name LIKE ''%BILLG_BIN_ID%''' 
EXEC sp_MSforeachdb @command
NOTES:
  1. ? is replaced in the query as the database name, so structure the query to explicitly define which DB it is to query against

Monday 2 July 2018

LINQ query check if not null then only apply condition

Sometimes, we have requirement like need to pass one parameter but its nullable, and we have to pass this parameter in where clause also need to check only if value is not null then only check condition..then in this case what we can do ..???

well here is one of the solution :

public employee GetEmployee(int id, string appId)
{
      var result= (from e in objcontext.employee
                         where e.Id==id &&
                         (string.IsNullOrEmpty(appId) || e.AppId==appId)  
// Here it will check first if null then it will not go to second condition else it will check where clause for that column  
                          select e).ToList();

}

Friday 18 December 2015

Get specific JSON object by id from JSON array in AngularJS

I have a JSON file containing some data I d like to access on my AngularJS website. Now what I want is to get only one object from the array. So I d like for example Item with id 1.
The data looks like this:
{ "results": [
    {
        "id": 1,
        "name": "Test"
    },
    {
        "id": 2,
        "name": "Beispiel"
    },
    {
        "id": 3,
        "name": "Sample"
    }
] }
I d like to load the data with AngularJS $http functionality like this:
$http.get("data/SampleData.json");
which is working. But how can I now get a specific data object (by id) from the array I get from $http.get ?
Answer
$filter('filter')(foo.results, {id: 1})[0];
A use case example:
app.controller('FooCtrl', ['$filter', function($filter) {
    var foo = { "results": [
        {
            "id": 12,
            "name": "Test"
        },
        {
            "id": 2,
            "name": "Beispiel"
        },
        {
            "id": 3,
            "name": "Sample"
        }
    ] };

    // We filter the array by id, the result is an array
    // so we select the element 0

    single_object = $filter('filter')(foo.results, function (d) {return d.id === 2;})[0];

    // If you want to see the result, just check the log
    console.log(single_object);
}]);
http://stackoverflow.com/questions/19590063/get-specific-json-object-by-id-from-json-array-in-angularjs

Thursday 14 May 2015

AngularJS with save file using fileupload control

For save file in binary

[AllowAnonymous]
        public async System.Threading.Tasks.Task<HttpResponseMessage> PostMemberImage(int customerID, int memberID)
        {
            AjaxResult res = new AjaxResult();
            HttpRequestMessage request = this.Request;
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            if (!System.IO.Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(@"~/App_Data/uploads")))
            {
                System.IO.Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(@"~/App_Data/uploads"));
            }

            string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads");

            var provider = new MultipartFormDataStreamProvider(root);
            // System.Threading.Tasks.Task<byte[]> img ;
            byte[] img1 = new byte[1024];
            var task = await request.Content.ReadAsMultipartAsync(provider).
                ContinueWith<HttpResponseMessage>(o =>
                {


                    ///MY CODE///
                    FileStream fsOld = new FileStream(provider.FileData[0].LocalFileName, FileMode.Open, FileAccess.Read);

                    CreateThumbnail(fsOld.Name, 166, 166);

                    FileStream fs = new FileStream(provider.FileData[0].LocalFileName + "_thumb", FileMode.Open, FileAccess.Read);
                    BinaryReader br = new BinaryReader(fs);

                    byte[] image = br.ReadBytes((int)fs.Length);

                    br.Close();
                    var filepath = fs.Name;
                    var maxfilepath = fsOld.Name;
                    fs.Close();
                    fsOld.Close();

                    ////MY CODE END///////////

                    _memberService.SaveMemberImage(memberID, image, customerID);

                    try
                    {
                        if (System.IO.File.Exists(filepath))
                        {
                            System.IO.File.Delete(filepath);
                        }

                        if (System.IO.File.Exists(maxfilepath))
                        {
                            System.IO.File.Delete(maxfilepath);
                        }
                    }
                    catch
                    {
                    }


                    return new HttpResponseMessage()
                    {
                        Content = new StringContent("File uploaded.")
                    };
                }
            );

            return task;
        }

For html side

   <input type="file" id="myFile" ng-model="myfiles" accept="text/xml" />
                                <button type="button" ng-click="myFunction(myfiles)" class="btn btn-xs btn-purple mrg-t-5"><i class=" icon-cloud-upload"></i> Upload</button>

From JS
$scope.model = {
            name: "",
            type: ""
        };
$scope.myFunction = function (obj) {

            var x = document.getElementById("myFile");
            var txt = "";
            if ('files' in myFile) {
                if (x.files.length > 0 && x.files[0].type != "text/xml") {
                    toastr.error('Please import xml file only !'); return;
                }
                if (x.files.length == 0) {
                    toastr.error("Select one or more files."); return;
                } else {

                    for (var i = 0; i < x.files.length; i++) {
                        var file = x.files[i];
                        if ('name' in file) {
                            txt += file.name + "&nbsp;&nbsp;&nbsp;";
                        }
                        if ('size' in file) {
                            txt += bytesToSize(file.size);
                        }
                    }
                }
                function bytesToSize(bytes) {
                    var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
                    if (bytes == 0) return '0 Byte';
                    var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
                    return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
                };
                document.getElementById("demo").innerHTML = txt;
                //return false;
                if (x.files.length > 0 && x.files[0].type == "text/xml") {
                    $http({
                        method: 'POST',
                        url: httpServiceUrlForService + "api/GPROMemberImport/PostXMLFileupload?reportingyear=" + $scope.ReportYear,
                        headers: { 'Content-Type': undefined },//$scope.sourceID
                        transformRequest: function (data) {
                            //debugger

                            var formData = new FormData();
                            formData.append("model", angular.toJson(data.model));
                            formData.append("file", data.files);

                            if (data.files) {
                                $scope.message = 'Please wait, Document is uploading...';
                                $scope.showPrgress = true;
                            }

                            return formData;
                        },
                        data: { model: $scope.model, files: x.files[0] }
                    }).
                   success(function (data, status, headers, config) {
                       //alert("success!");
                       $scope.showPrgress = false;
                       $scope.message = '';
                       $scope.files = '';
                       angular.element("input[type='file']").val(null);
                       document.getElementById("demo").innerHTML = '';
                       toastr.success('Document uploaded successfully!'); return;
                   }).
                   error(function (data, status, headers, config) {
                       //alert("failed!");
                       $scope.showPrgress = false;
                       $scope.message = '';
                       toastr.error("Failed !"); return;
                   });
                }
            }
            else {
                if (x.value == "") {                   
                    toastr.error("Select one or more files!");
                } else {                  
                    txt += "The files property is not supported by your browser!";
                    txt += "<br>The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
                    toastr.error(txt);
                }
            }
            //  document.getElementById("demo").innerHTML = txt;

        }

Now while showing uploaded image in UI

<img class="list_photo" ng-src="data:image/png;base64,{{o.MemberImage}}" />