HTML5 indexedDb : locally stored data in client browser


  1. http://www.html5rocks.com/en/tutorials/indexeddb/todo/
  2. http://blog.teamtreehouse.com/create-your-own-to-do-app-with-html5-and-indexeddb
  3. http://code.tutsplus.com/tutorials/working-with-indexeddb–net-34673
  4. http://www.html5labs.com/IndexedDBTest/CodeSnippets/samples.html   (recommended)
  5. http://www.codeproject.com/Articles/671294/Using-HTML-IndexedDB-as-a-Client-Data-Store
  6. http://www.codeproject.com/Articles/325135/Getting-Started-with-IndexedDB

Happy Coding 🙂 

AngularJS – Beginners guide


AngularJS – Beginners guide

A bunch of links to blog posts, articles, videos, etc for learning AngularJS. This list is in its early stages. Feel free to submit a pull request if you have some links/resources to add. Also, I try to verify that the articles below have some real content (i.e. aren’t 2 paragraph blog posts with little information) to ensure I’m not listing “fluff” pieces. If you have an idea for a better way to organize these links, please let me know. As I find similar posts in the “General Topics” section, I will break them out into their own categories.

AngularJS

Books

Videos

Help

General Topics

Scopes

Dependency Injection

Directives

Services/Providers

Routing

Promises/Deferred

Forms

Code Organization

Testing

RESTful Stuff

UI Stuff

Hosted Backends

Text editor bundles

Beginners Tutorials and Step By Step Guide

Online angular JS tutorials start from the fundamental basics, explain key concepts in a simple and easy to understand manner, and then proceed to explain Angular JS in a step-by-step and systematic manner. Completing a tutorial can be a big step toward creating your own first app and quickly bridging the gap between HTML and JavaScript.

Websites For Learning Angular JS

Some great websites are dedicated exclusively for providing Angular JS tutorials that explain every concept clearly. These websites offer links to download Angular JS tutorials, comprehensive Angular JS learning and sequential and systematic explanations. E-learning resources, simplify learning and teach you everything about Angular JS, which is rapidly gaining popularity among developers.

Online Courses on Angular JS

An online course that explains the most complex concepts in a way that grasping information will become easy for any beginner. Efficient instruction delivery, continuous discussions, and high quality instructional videos make this course unique and powerful. Complete Angular JS tutorials, rapid Angular JS learning and Angular JS tutorial videos.

Best Cheatsheets and Guides for AngularJS

Angular JS style guides and cheatsheets are of great help in the beginning, and provide a useful list of references about the most essential and commonly used features. For SPAs or Single Page Applications, Angular JS provides one of the best available frameworks, and cheatsheets will help you in quickly becoming productive and save time.

Video Tutorials For Angular.js

Video tutorials on You Tube are a free resource for learning almost everything about Angular JS. Some of the top developers currently working on their own projects provide practical and simple instructions on learning Angular JS, core fundamental concepts, Angular 2.0, and other topics and concepts.

Blogs and News About Angular.js

Angular 2.0 means a better framework than Angular JS and has many great features, but at the same time developers used to the old Angular JS will have to spend a significant amount of time adapting to changes and getting used to the new framework. Online Angular 2.0 tutorials have all the necessary information for a smooth transition to the new framework, and utilizing online resources can make you proficient in a short span of time.

Useful Tutorials and Articles on AngularJS

The Angular JS framework provides tools that can make a huge difference to any developer’s productivity, and tutorials and presentations try to describe every important aspect with practical examples. All tutorials begin with simple basics and fundamentals and move on to the advanced practical application of concepts. Hard to learn, important concepts have been covered by various experts in separate presentations and articles. A lot of developers who are preparing to transition from Angular JS to Angular 2.0 will find these resources extremely useful.

Best Free PDF Tutorials and eBooks On Angular JS

Angular JS learning tutorials in PDF and e-book format provide a great resource for knowing all about angular JS. The systematic approach to understanding Angular JS starts from core basics and first mastering them effectively, then gradually integrating that knowledge with readily available practical examples. Knowing the differences between Angular JS and Angular 2.0, and preparing for a transition to the new framework.

Forums and Message Boards To Discuss Angular JS

Angular JS has evolved into the most popular framework for app developers and knowing all about is absolutely essential for new developers. Learning from online resources accelerates learning, but most tutorials often miss key issues that come up when actually get down to developing your first app. Forums provide simpler answers, great links, and can often be a great resource for learning absolutely new things.

Angularjs–Google Map


image

AngularGM

AngularGM is a set of directives for embedding Google Maps in your application using the Google Maps Javascript API.

Features

  • Bi-directional association of map bounds, center, and zoom with scope variables
  • Multiple Google Maps can be embedded in the same page
  • Works with ngView and reuses map instances so there is no memory leak
  • Bind custom objects to markers
  • Listen for and generate events on markers/objects
  • Create InfoWindows which compile Angular expressions (credit goes to ui-map for this feature)
  • Create polylines

See more information at – https://github.com/wpalahnuk/angular-gm

 

___________________________________________________________________________________________________

 

Another Best Google Map using Angular is 

http://angular-google-maps.org/

Happy Coding....

AngularJS Pageslide directive


An AngularJS directive which slides another panel over your browser to reveal an additional interaction pane.
It does all the css manipulation needed to position your content off canvas with html attibutes and it does not depend on jQuery.

I was looking for something like this since while using angular and I found really nice directive this time. Thought to share with everyone else… Happy Coding… Smile 

Download link

https://github.com/dpiccone/ng-pageslide

Demo link

http://dpiccone.github.io/ng-pageslide/examples/

Thanks to developer DpicCone.

image

GASP TimeLineMax/TimeLineLite : More Advance Flash styles complex animation library for Jquery and AngularJS


GSAP is a suite of tools for scripted, high-performance HTML5 animations that work in all major browsers. No other library delivers such advanced sequencing, API efficiency, and tight control. Stop wrestling with cumbersome CSS animations, stuttery jQuery.animate() calls, or a system that limits your creativity. Use animation to tell a story in a rich way rather than settling for a few fades and slides.

Download and Read More:  http://www.greensock.com/gsap-js/

Licence : Open Source 

Happy Coding…:)

 

Velocity JS – more advance way to handle jQuery animations….


http://julian.com/research/velocity/index.html

  • Overview

    Velocity is a jQuery plugin that re-implements $.animate() to produce significantly greater performance (making Velocity also faster than CSS animation libraries) while including new features to improve animation workflow.

  • Compatibility

    Velocity works everywhere — back to IE8 and Android 2.3. Under the hood, Velocity uses jQuery’s $.queue(), and thus interoperates seamlessly with jQuery’s $.animate(), $.fade(), and $.delay(). Since Velocity’s syntax is identical to $.animate()’s, none of your code needs to change.

  • Quickstart

    Download Velocity, add it to your page, and replace all instances of $.animate() with $.velocity(). You will immediately see a performance boost across all browsers and devices — especially on smartphones.

Learning AngularJS – best resources to learn angularjs for beginners.


AngularJS –HTML is great for declaring static documents, but it falters when we try to use it for declaring dynamic views in web-applications. AngularJS lets you extend HTML vocabulary for your application. The resulting environment is extraordinarily expressive, readable, and quick to develop.

  1. https://github.com/jmcunningham/AngularJS-Learning
  2. http://techslides.com/angular-js-demos-examples-and-resources/
  3. https://leanpub.com/recipes-with-angular-js/read
  4. https://www.youtube.com/watch?v=i9MHigUZKEM
  5. https://www.youtube.com/watch?v=QETUuZ27N0w
  6. https://www.youtube.com/watch?v=TRrL5j3MIvo&index=11&list=PLmtADjkIi7R9_HFpGdosdOrDsAkHQVSq3
  7. https://egghead.io/technologies/angularjs
  8. http://ng-learn.org/
  9. http://henriquat.re/intro/angular/angularjsForDotNetDevelopers.html  – (2 min learning of angularjs for .net developers…)

And Last but not least ofcource – AngularJS.org  & http://ng-learn.org/

Some jquery plugins for AngularJS

  1. https://github.com/jirikavi/AngularJS-Toaster    (toastr notification plugin)
  2. https://github.com/codef0rmer/angular-dragdrop
  3. https://github.com/revolunet/angular-carousel
  4. https://github.com/nlaplante/angular-google-maps
  5. https://github.com/simpulton/angularjs-wizard
  6. https://github.com/angular-ui/bootstrap
  7. http://vitalets.github.io/angular-xeditable/  (Inline editing using angular)                    e.g.http://plnkr.co/edit/2UFfaG?p=preview           http://jsfiddle.net/christianacca/gpgD4/          http://jsfiddle.net/Thw8n/4/     http://icelab.com.au/articles/click-to-edit-with-angularjs/                http://scotch.io/tag/angular-js
  8. https://github.com/pikock/bootstrap-magic  ( Bootstrap themer for angular)
  9. https://github.com/nervgh/angular-file-upload  (file uploader)
  10. https://github.com/arunisrael/angularjs-geolocation
  11. https://github.com/2fdevs/videogular
  12. https://github.com/Wintellect/Angular-MVC-Cookbook
  13. http://juampy72.github.io/angularjs_form/
  14. https://github.com/webux/ux-angularjs-datagrid
  15. https://github.com/Augus/ngAnimate (best animations with angular)
  16. https://github.com/gsklee/ngStorage     – localStorage and sessionStorage done right for AngularJS.
  17. https://github.com/angular-ui/ui-date
  18. https://github.com/eu81273/angular.treeview
    1. http://jimliu.github.io/angular-ui-tree/
  19. https://github.com/fabiobiondi/angular-fullscreen
  20. https://github.com/darylrowland/angucomplete
  21. http://blog.brentmckendrick.com/angularjs-visual-studio-2012-intellisense/
  22. http://mozilla.github.io/pdf.js/
  23. https://github.com/allaud/quick-ng-repeat
  24. https://github.com/frapontillo/angular-filters (Useful AngularJS filters)
  25. http://chieffancypants.github.io/angular-hotkeys/  (AngularJS Keyboard Shortcut)
  26. https://github.com/wpalahnuk/angular-gm (Angular Google Map )
  27. https://github.com/revolunet/angular-carousel  (Angular Carousel)
  28. https://github.com/wpalahnuk/ngAutocomplete  (Angular Auto Complete)
  29. https://github.com/zensh/ui-autocomplete  (another AutoComplete with Angular)
  30. http://ngmodules.org/modules/AngularJS-Toaster   (Toaster Notification using Angular)
  31. http://pgwjs.com/pgwmodal/   (Another modal dialog service)
  32. BootStrap Window Using JQUERY – https://github.com/Flyer53/jsPanel-bootstrap
  33. http://plnkr.co/edit/l13dwaGeUqBy79sEW4Zi?p=preview   ( Custom Filter Directive plunkr & ng-if example)

 

 

AngularJS – Beginners guide

A bunch of links to blog posts, articles, videos, etc for learning AngularJS. This list is in its early stages. Feel free to submit a pull request if you have some links/resources to add. Also, I try to verify that the articles below have some real content (i.e. aren’t 2 paragraph blog posts with little information) to ensure I’m not listing “fluff” pieces. If you have an idea for a better way to organize these links, please let me know. As I find similar posts in the “General Topics” section, I will break them out into their own categories.

AngularJS

Books

Videos

Help

General Topics

Scopes

Dependency Injection

Directives

Services/Providers

Routing

Promises/Deferred

Forms

Code Organization

Testing

RESTful Stuff

UI Stuff

Hosted Backends

Text editor bundles

Originally published by Jeff Cunningham on github

AngularJS: ng-repeat get last 3 element from JSON


You could do

message in item.comments | limitTo:-3

Also for your comments, you should haven’t them as a object dictionary, rather just use an array like so:

"comments":[{"id":"comment1","name":"user1","description":"This is comment 1"},{"id":"comment2","name":"Jane D.","description":"This is comment 2"},{"id":"comment3","name":"Jone D.","description":"This is comment 3"},{"id":"comment4","name":"Test","description":"This is comment 4"},{"id":"comment5","name":"user","description":"This is comment 5"}]

If they aren’t already in order you may need to add a date field of sort and sort them after you pull them in.

Dropshadow and border color issue – Mahapps Metro WPF


the screenhots/examples at the quickstart are not quite updated.

you can have a border

<controls:MetroWindowx:Class="MahApps.Metro.Simple.Demo.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:controls="http://metro.mahapps.com/winfx/xaml/controls"Title="MainWindow"
Height="200"Width="600"BorderBrush="{DynamicResource AccentColorBrush}"BorderThickness="1"WindowStartupLocation="CenterScreen"></controls:MetroWindow>

enter image description here

or a glow border

<controls:MetroWindowx:Class="MahApps.Metro.Simple.Demo.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:controls="http://metro.mahapps.com/winfx/xaml/controls"Title="MainWindow"
Height="200"Width="600"GlowBrush="{DynamicResource AccentColorBrush}"WindowStartupLocation="CenterScreen"></controls:MetroWindow>

enter image description here

or a drop shadow

<controls:MetroWindowx:Class="MahApps.Metro.Simple.Demo.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:controls="http://metro.mahapps.com/winfx/xaml/controls"xmlns:behaviours="http://metro.mahapps.com/winfx/xaml/shared"
Title="MainWindow"Height="200"Width="600"ResizeMode="CanResizeWithGrip"WindowTransitionsEnabled="False"
WindowStartupLocation="CenterScreen"><i:Interaction.Behaviors><behaviours:BorderlessWindowBehaviorAllowsTransparency="False"
EnableDWMDropShadow="True"/><behaviours:WindowsSettingBehaviour/><behaviours:GlowWindowBehavior/></i:Interaction.Behaviors>
</controls:MetroWindow>

Update

EnableDWMDropShadow has been moved to MetroWindow in version 0.13 alpha (latest version)

<controls:MetroWindowx:Class="MahApps.Metro.Simple.Demo.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:controls="http://metro.mahapps.com/winfx/xaml/controls"xmlns:behaviours="http://metro.mahapps.com/winfx/xaml/shared"
Title="MainWindow"Height="200"Width="600"EnableDWMDropShadow="True"ResizeMode="CanResizeWithGrip"WindowTransitionsEnabled="False"
WindowStartupLocation="CenterScreen"></controls:MetroWindow>

enter image description here

For more info –

http://rehansaeed.co.uk/wpf-metro-part2-mahapps-metro/

hope that helps

Little information about ASP.net Different Session States…


ASP.NET has different Session State modes:

  • InProc, this is in-memory. Session State lives as long as the IIS Application Pool isn’t recycled or the entire IIS is restarted.

  • SqlServer. This is Session State is stored in a SQL Server storage. This is great because sessions survives after an IIS Application Pool or entire IIS restart, but it’s a bottleneck as it means that every access to the session requires a deserialization and/or serialization of the Session State objects and, after all, database connections and so on.

  • StateServer. Similar to SqlServer, but using a Session State Server provided by Microsoft. This mode isn’t used at all, but it’s an option… (I’ve no experience with it).

  • Custom. You can implement some interfaces/abstract classes and define your own Session State storage.

Sql Server Triggers: Get list of Updated columns in Trigger


— ————————————————————————————————————–
— Get the table id of the trigger

DECLARE @idTable INT

SELECT @idTable = T.id
FROM sysobjects P JOIN sysobjects T ON P.parent_obj = T.id
WHERE P.id = @@procid

— Get COLUMNS_UPDATED if update

DECLARE @Columns_Updated VARCHAR(50)

SELECT @Columns_Updated = ISNULL(@Columns_Updated + ‘, ‘, ”) + name
FROM syscolumns
WHERE id = @idTable
AND CONVERT(VARBINARY,REVERSE(COLUMNS_UPDATED())) & POWER(CONVERT(BIGINT, 2), colorder – 1) > 0
— ————————————————————————————————————–

PRINT ‘ ‘ + @Columns_Updated

Sql Dependency and SignalR: SqlDependency.Start() must be called prior ….


I got this error: “When using SqlDependency without providing an options value, SqlDependency.Start() must be called prior to execution of a command added to the SqlDependency instance” couple of hours ago and I decided to share.

This error occurs if you didn’t started your SqlDependency or it got closed for some reason.  I usually start it this way in the Global.asax
     

 protected void Application_Start(Object sender, EventArgs e)
 {
   var sConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
   SqlDependency.Start(sConn);
 
   // Cache systemwide data in the application object.
   ApplicationAdapter.InitApplicationCache();
 }

 

Moment.JS “A javascript date library for parsing, validating, manipulating, and formatting dates.”


“A javascript date library for parsing, validating, manipulating, and formatting dates.”

Moment was designed to work both in the browser and in Node.JS.

Currently the following browsers are used for the ci system: ie8, ie9 on Windows 7, stable Chrome on Windows XP, Safari 10.8 on Mac and stable Firefox on Linux.

All code will work in both environments. All unit tests are run in both environments.

_ It supports all possible Date manipulation , formats and zone detection & most importantly ASP.NET JSON date format like “/date(1396293230)/” i.e. EPOCH Time / Unix timestamp

Read more  ….http://momentjs.com/docs/

Happy Coding.. 🙂

Really nice article on Microsoft Sync Framework – thanks to Jaliya’s Blog.


Database Synchronization with Microsoft Sync Framework

 
Microsoft Sync Framework is a comprehensive synchronization platform enabling collaboration and offline for applications, services and devices. This is actually shipped with Visual Studio 2008 for the first time and now the current stable version is Microsoft Sync Framework 2.1. There are number of providers in Sync Framework which supports many common data sources.The following are the providers included,
  • Database synchronization providers: Synchronization for ADO.NET-enabled data sources.
  • File synchronization provider: Synchronization for files and folders.
  • Web synchronization components: Synchronization for FeedSync feeds such as RSS and ATOM feeds.
I am not going to write much intro about Microsoft Sync Framework as you can find many articles on internet. Let’s see how database synchronization works with Microsoft Sync Framework by a simple example.

I have two Microsoft SQL Server 2008R2 Databases which are “SyncDBServer” and “SyncDBClient”. Unfortunately I am having them on the same server and actually what I want to demonstrate is data synchronization between two remote database servers. Since I don’t have such environment I am using the same server, because it will not do any harm to the logic I am using here.

In “SyncDBServer”, I have three tables which are CUSTOMER, PRODUCT and ORDER. I have filled up these tables with sample data and “SyncDBClient” database has no tables. What I am going to do today is synchronize only the CUSTOMER and PRODUCT tables of “SyncDBServer” with “SyncDBClient”. In this case Microsoft Sync Framework will create CUSTOMER and PRODUCT tables in “SyncDBClient” for me.
image
“SyncDBServer” and “SyncDBClient”
First I need to prepare or provision these two databases for the synchronization. For that I will have to write some codes. Let’s create a console application for provisioning “SyncDBServer” and I am naming it as “ProvisionServer”. I am adding following references (I am using Microsoft Sync Framework 2.1 Software Development Kit (SDK)).
  • Microsoft.Synchronization.Data : Version 3.1.0.0
  • Microsoft.Synchronization.Data.SqlServer: Version 3.1.0.0
using System.Data.SqlClient;
using Microsoft.Synchronization.Data;
using Microsoft.Synchronization.Data.SqlServer;

namespace ProvisionServer
{
    class Program
    {
        static void Main(string[] args)
        {
            // connect to server database
            SqlConnection serverConn = new SqlConnection("Data Source=.; Initial Catalog=SyncDBServer; Integrated Security=True");

            // define a new scope named MySyncScope
            DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription("MySyncScope");

            // get the description of the CUSTOMER & PRODUCT table from SERVER database
            DbSyncTableDescription cusTableDesc = SqlSyncDescriptionBuilder.GetDescriptionForTable("CUSTOMER", serverConn);
            DbSyncTableDescription prodTableDesc = SqlSyncDescriptionBuilder.GetDescriptionForTable("PRODUCT", serverConn);

            // add the table description to the sync scope definition
            scopeDesc.Tables.Add(cusTableDesc);
            scopeDesc.Tables.Add(prodTableDesc);

            // create a server scope provisioning object based on the MySyncScope
            SqlSyncScopeProvisioning serverProvision = new SqlSyncScopeProvisioning(serverConn, scopeDesc);

            // skipping the creation of table since table already exists on server
            serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip);

            // start the provisioning process
            serverProvision.Apply();

            Console.WriteLine("Server Successfully Provisioned.");
            Console.ReadLine();
        }
    }
}
Here I am accessing “SyncDBServer” database and specified my synchronization scope. Now when I run this project, I can see the message “Server Successfully Provisioned.” and most importantly I can see some new tables created in  “SyncDBServer” database.
image
“Server Successfully Provisioned.”
image
“SyncDBServer”
Now I am creating a console application for provisioning “SyncDBClient” and I am naming it as “ProvisionClient”. Again I am adding the same references.

using System;
using System.Data.SqlClient;
using Microsoft.Synchronization.Data;
using Microsoft.Synchronization.Data.SqlServer;

namespace ProvisionClient
{
    class Program
    {
        static void Main(string[] args)
        {
            // create a connection to the client database
            SqlConnection clientConn = new SqlConnection(@"Data Source=.; Initial Catalog=SyncDBClient; Integrated Security=True");

            // create a connection to the server database
            SqlConnection serverConn = new SqlConnection("Data Source=.; Initial Catalog=SyncDBServer; Integrated Security=True");

            // get the description of SyncScope from the server database
            DbSyncScopeDescription scopeDesc = SqlSyncDescriptionBuilder.GetDescriptionForScope("MySyncScope", serverConn);

            // create server provisioning object based on the SyncScope
            SqlSyncScopeProvisioning clientProvision = new SqlSyncScopeProvisioning(clientConn, scopeDesc);

            // starts the provisioning process
            clientProvision.Apply();

            Console.WriteLine("Client Successfully Provisioned.");
            Console.ReadLine();
        }
    }
}
Here I am accessing both “SyncDBServer” and “SyncDBClient”. I am getting the synchronization scope from “SyncDBServer” and applying it on the “SyncDBClient”. Now when I run this project, I can see the message “Client Successfully Provisioned.” and here also I can see some new tables created in “SyncDBClient” database including CUSTOMER and PRODUCT tables. But there will be no data in these two tables.
image
“Client Successfully Provisioned.”
image
“SyncDBClient”

Now finally what’s left to do is the synchronization. For that I am creating a console application and I am naming it as “ExecuteSync”. I am adding following references.

  • Microsoft.Synchronization: Version 2.1.0.0
  • Microsoft.Synchronization.Data : Version 3.1.0.0
  • Microsoft.Synchronization.Data.SqlServer: Version 3.1.0.0
using System;
using System.Data.SqlClient;
using Microsoft.Synchronization;
using Microsoft.Synchronization.Data;
using Microsoft.Synchronization.Data.SqlServer;

namespace ExecuteSync
{
    class Program
    {
        static void Main(string[] args)
        {
            SqlConnection clientConn = new SqlConnection(@"Data Source=.; Initial Catalog=SyncDBClient; Integrated Security=True");

            SqlConnection serverConn = new SqlConnection("Data Source=.; Initial Catalog=SyncDBServer; Integrated Security=True");

            // create the sync orhcestrator
            SyncOrchestrator syncOrchestrator = new SyncOrchestrator();

            // set local provider of orchestrator to a sync provider associated with the 
            // MySyncScope in the client database
            syncOrchestrator.LocalProvider = new SqlSyncProvider("MySyncScope", clientConn);

            // set the remote provider of orchestrator to a server sync provider associated with
            // the MySyncScope in the server database
            syncOrchestrator.RemoteProvider = new SqlSyncProvider("MySyncScope", serverConn);

            // set the direction of sync session to Upload and Download
            syncOrchestrator.Direction = SyncDirectionOrder.UploadAndDownload;

            // subscribe for errors that occur when applying changes to the client
            ((SqlSyncProvider)syncOrchestrator.LocalProvider).ApplyChangeFailed += new EventHandler<DbApplyChangeFailedEventArgs>(Program_ApplyChangeFailed);

            // execute the synchronization process
            SyncOperationStatistics syncStats = syncOrchestrator.Synchronize();

            // print statistics
            Console.WriteLine("Start Time: " + syncStats.SyncStartTime);
            Console.WriteLine("Total Changes Uploaded: " + syncStats.UploadChangesTotal);
            Console.WriteLine("Total Changes Downloaded: " + syncStats.DownloadChangesTotal);
            Console.WriteLine("Complete Time: " + syncStats.SyncEndTime);
            Console.WriteLine(String.Empty);
            Console.ReadLine();
        }

        static void Program_ApplyChangeFailed(object sender, DbApplyChangeFailedEventArgs e)
        {
            // display conflict type
            Console.WriteLine(e.Conflict.Type);

            // display error message 
            Console.WriteLine(e.Error);
        }
    }
}

Here I am mentioning the synchronization direction(Upload or Download or UploadAndDownload or DownloadAndUpload) and doing the synchronization according to my specified scope. When I run this, I am getting the following output.
image
Synchronization Completed.
image
“SyncDBClient” after Synchronization

MVC 5 & ASP.NET Best Practices – Some nice articles and tutorials.


  1. http://www.dotnet-tricks.com/Tutorial/mvc/N50P050314-Understanding-HTML-Helpers-in-ASP.NET-MVC.html
  2. http://www.dotnet-tricks.com/Tutorial/mvc/19D9140313-Exception-or-Error-Handling-and-Logging-in-MVC4.html
  3. http://www.dotnet-tricks.com/Tutorial/mvc/4XDc110313-return-View()-vs-return-RedirectToAction()-vs-return-Redirect()-vs-return-RedirectToRoute().html
  4. http://www.dotnet-tricks.com/Tutorial/mvc/E2S9150113-Enhancing-WebGrid-with-Insert-Update-and-Delete-Operations.html
  5. http://www.dotnet-tricks.com/Tutorial/mvc/18NI110113-Enhancing-WebGrid-with-ajax-in-MVC4.html
  6. http://www.dotnet-tricks.com/Tutorial/mvc/ODJa210113-Donut-Caching-and-Donut-Hole-Caching-with-Asp.Net-MVC-4.html
  7. http://www.dotnet-tricks.com/Tutorial/designpatterns/2FMM060314-Understanding-MVC,-MVP-and-MVVM-Design-Patterns.html
  8. http://www.dotnet-tricks.com/Tutorial/dependencyinjection/bSVa100413-Understanding-Inversion-of-Control,-Dependency-Injection-and-Service-Locator.html
  9. http://www.asp.net/signalr

Hope you like it…Happy Coding… 🙂 

Backup & Restore the Sql Server DB with Data.


SQL SERVER – FIX : Error 3154: The backup set holds a backup of a database other than the existing database

Our Jr. DBA ran to me with this error just a few days ago while restoring the database.

Error 3154: The backup set holds a backup of a database other than the existing database.

Solution is very simple and not as difficult as he was thinking. He was trying to restore the database on another existing active database.

Fix/WorkAround/Solution:

1) Use WITH REPLACE while using the RESTORE command. View Example

2) Delete the older database which is conflicting and restore again using RESTORE command.

I understand my solution is little different than BOL but I use it to fix my database issue successfully.

3) Sample Example :
RESTORE DATABASE AdventureWorks
FROM DISK = 'C:\BackupAdventureworks.bak'
WITH REPLACE

SQLAuthority Article : SQL SERVER – Fix: Error: 15138 – The database principal owns a schema in the database, and cannot be dropped


SQL SERVER – Fix: Error: 15138 – The database principal owns a schema in the database, and cannot be dropped

Thanks to SQL Authority & Author Pinal Dave for such a nice article. –

Workaround / Resolution / Fix:

Let us assume that user was trying to delete user which is named as ‘pinaladmin’ and it exists in the database ‘AdventureWorks’.

Now run following script with the context of the database where user belongs.

USE AdventureWorks;
SELECT s.name
FROM sys.schemas s
WHERE s.principal_id = USER_ID('pinaladmin');

In my query I get following two schema as a result.

Now let us run following query where I will take my schema and and alter authorization on schema. In our case we have two schema so we will execute it two times.

ALTER AUTHORIZATION ON SCHEMA::db_denydatareader TO dbo;
ALTER AUTHORIZATION ON SCHEMA::db_denydatawriter TO dbo;

Now if you drop the database owner it will not throw any error.

Here is generic script for resolving the error:

SELECT s.name
FROM sys.schemas s
WHERE s.principal_id = USER_ID('YourUserID');

Now replace the result name in following script:

ALTER AUTHORIZATION ON SCHEMA::YourSchemaName TO dbo;

Android: TabHost is stealing focus from a EditText


I am recently working on Android app development and had an issue with TabHost and EditText inside that TabHost. 

somehow, when I was trying to insert a value in that EditText, focus was set automatically on tab and was not able to type anything. 

Tried hard to google and came to know that its a bug and Good team is working on it as of today. But there is a workaround for this problem as below – 

 

txtDescription = (EditText) V.findViewById(R.id.txtAttactmentDescription);
txtDescription.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
txtDescription.requestFocusFromTouch();
return false;
}
});

Android : Can’t open SDK or AVD – AndroidStudio


Recently , I got a chance to work on Android projects but while I was setting up Android Studio, I got error saying ” Cannot open SDK manager” / AVD  (don’t remember exact error line)

Solution – 1
Give full control to SDK folder for logged in windows user. 

Solution – 2

Manually create 2 directories under the SDK directory

platforms

add-ons

The SDK and AVD manager should now be launchable.

Solution – 3

adding the JAVA_HOME environment variable pointing to the jdk folder (in my case c:\Program Files\Java\jdk1.7.0_04) and adding %JAVA_HOME%\bin to PATH variable

Happy Coding 🙂

ASP.NET WebAPI – Return image from Api to View


if you want to return an Image (i.e. Byte[]) from Api Controller to Browser (view), use following method. 

public HttpResponseMessage Get(string imageName, int width, int height)
    {
        Image img = GetImage(imageName, width, height);
        MemoryStream ms = new MemoryStream();
        img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new ByteArrayContent(ms.ToArray());
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
        return result;
    }

SQL SERVER – Fix: Error: 15138 – The database principal owns a schema in the database, and cannot be dropped


 

Thanks to Pinal Dave (SQL Authority) 
 

SQL SERVER – Fix: Error: 15138 – The database principal owns a schema in the database, and cannot be dropped

Last day I had excellent fun asking puzzle on SQL Server Login SQL SERVER – Merry Christmas and Happy Holidays – Database Properties – Number of Users. One of the user sent me email asking urgent question about how to resolve following error. Reader was trying to remove the login from database but every single time he was getting error and was not able to remove the user.

The database principal owns a schema in the database, and cannot be dropped. (Microsoft SQL Server, Error: 15138)

As per him it was very urgent and he was not able to solve the same. I totally understand his situation and here is the quick workaround to the issue. The reason for error is quite clear from the error message as there were schema associated with the user and that needs to be transferred to another user.

Workaround / Resolution / Fix:

Let us assume that user was trying to delete user which is named as ‘pinaladmin’ and it exists in the database ‘AdventureWorks’.

Now run following script with the context of the database where user belongs.

USE AdventureWorks;
SELECT s.name
FROM sys.schemas s
WHERE s.principal_id = USER_ID('pinaladmin');

In my query I get following two schema as a result.

Now let us run following query where I will take my schema and and alter authorization on schema. In our case we have two schema so we will execute it two times.

ALTER AUTHORIZATION ON SCHEMA::db_denydatareader TO dbo;
ALTER AUTHORIZATION ON SCHEMA::db_denydatawriter TO dbo;

Now if you drop the database owner it will not throw any error.

LINQ PredicateBuilder (A or B) And ( X or Y) expression error


Simple way to work with two predicate builder with And/Or statements are as – 

 

// This predicate is the 1st predicate builder
var predicate = PredicateBuilder.True<Widget>();

// and I am adding more predicates to it (all no problem here)
predicate = predicate.And(c => c.ColumnA == 1);
predicate = predicate.And(c => c.ColumnB > 32);
predicate = predicate.And(c => c.ColumnC == 73);

// Now I want to add another AND predicate with is actually comprises 
// of sub OR predicates
if(keywords.Length > 0)
{
    // NOTICE HERE: Here I am starting off a brand new 2nd predicate builder....
    // (not ANDing it to the existing one (yet))
    var subpredicate = PredicateBuilder.False<Widget>();

    foreach(string s in keywords)
    {
        string t = s;
        subpredicate = subpredicate.Or(c => c.Name.Contains(t));
    }

    // This is the "gotcha" bit... adding the ANDing the independent
    // sub-predicate to the 1st one....

    // If done like this, you will FAIL!
//  predicate = predicate.And(subpredicate); // FAIL at runtime!

    // To correct it, you must do this...
    predicate = predicate.And(subpredicate.Expand());  // OK at runtime!
}

> Download Linux – LQ ISO


I found this site to get all possible linux bistros –

This site is designed to meet all of your Linux distribution download needs, including searching for fast mirrors, receiving email updates when new versions of your favorite distributions are released and reading reviews. If you do not see the distribution you are looking for below, you can view the complete alphabetical list. Please let us know if you have any suggestions.

If you find the site useful, you can help spread the word by telling 10 friends the URL (http://www.lqiso.org/). Thanks.

via > Download Linux – LQ ISO.

Linux distributions that can run on an MK802 Mini PC


Here are some of the Linux distributions that are currently available for the MK802.

Miniand Lubuntu 12.04 – This is a version of Ubuntu 12.04 with the light-weight LXDE desktop interface. It also includes the DroidMote server, which means you can install DroidMote Client on your Android phone or tablet to use it as a remote control for Ubuntu.

Miniand Ubuntu 12.04 and Xubuntu 12.04 – You can also find builds using the default Ubuntu 12.04 Unity desktop environment and the light-weight Xfce environment. Neither of these builds includes DroidMote yet, but you can download and install the server app manually.

Toby Corkindale’s Linaro 12.06 armhf build – This version of Ubuntu uses technology that should speed up performance on the Allwinner A10 chip. The installation instructions are a little more complicated, though.

Rikomagic Lubuntu 12.04 – This build includes a number of tweaks including a fix for WiFi performance, a working Chromium web browser, and the ability to access the MK802′s internal storage.

Puppy Linux – Puppy is a light-weight operating system designed to run well on older computers with slow processors and small amounts of storage and memory. I found that a version for the Mele A1000 set-top-box works pretty well on the MK802.

Fedora 17 – Fedora is probably one of the most popular Linux distributions that’s not based on Ubuntu or Debian. Now it’s also available for the MK802.

Bodhi Linux – Bodhi is a light-weight OS based on Ubuntu with support for desktops, notebooks, tablets, and more. It uses the Enlightenment E17 desktop environment.

You can load any of these operating systems on a microSD card following our instructions for preparing an Ubuntu 10.04 installation. Just use the disk image for your operating system instead of Ubuntu 10.04.

 

RowFilter with IN operator over a column of type Guid


RowFilter with IN operator over a column of type Guid

Case

Apply a RowFilter on a DataView which filters a column of type System.Guid and can contain a variable number of values.

Example:

DataView dv = new DataView();

dv.RowFilter = \”TypeId in (\’\’, \’\’, …)\”;

where TypeId column is of a System.Guid type. As the number of values is variable it makes perfect sense to use the in operator.

The problem

When you are looking at this expression you may think this should be working as expected, i.e. the result should only contain the data where TypeId is in the specified values. In fact, if you run it you will get the following exception:

Cannot perform \’=\’ operation on System.Guid and System.String.

The Solution

To convert the String to Guid you should use the Convert(expression, type) method like this:

dv.RowFilter = \”TypeId in (Convert(\’\’, \’System.Guid\’), Convert(\’\’, \’System.Guid\’),

 

ASP.NET / MVC / Jquery : Metro Styles Web applications


For creating web application with Metro Style, we have good options compare to creating WPF or pure winforms applications with those complex styles. 

Few packages which I have used in my projects are as below – 

Bootstrap Metro – http://aozora.github.io/bootmetro/ 

Metro UI – http://metroui.org.ua/

Metro BootStrap – http://talkslab.com/metro-bootstrap/components.html  ( I never used this but hear that its nice too)

Bootswatch – http://bootswatch.com/cosmo/

Metro UI Template – http://metro-webdesign.info/

 

Hope this helps someone to choose proper , if you find anything really nice which you think someone can use it, please let me know and i will be happy to put it here… 

Happy Coding..:)

 

C# Write Console App with Colored lines (Command prompt with color lines)


I have this legacy old application which is running its output to console. I wanted to do something really cool rather than just showing everything in white forecolor with black backcolor.

I wrote small function in my console program.cs as –

public static void ColoredConsoleWrite(ConsoleColor color, string text, bool newLine)
{
           ConsoleColor originalColor = Console.ForegroundColor;
            Console.ForegroundColor = color;
            if (newLine)
                       Console.WriteLine(text);
             else
                      Console.Write(text);
               Console.ForegroundColor = originalColor;
}

Then when I wanted to print line in whatever color , i called that function like –

 ColoredConsoleWrite(ConsoleColor.Red ,  ”     Process is being started … “, true);

That’s it…Worked like a charm.. Hope this helps someone…

Happy Coding… 🙂

.net – Create Excel (.XLS and .XLSX) file from C# – Stack Overflow


You can use a library called ExcelLibrary. It\’s a free, open source library posted on Google Code: ExcelLibrary This looks to be a port of the PHP ExcelWriter that you mentioned above. It will not write to the new .xlsx format yet, but they are working on adding that functionality in. ExcelLibrary

  • It\’s very simple, small and easy to use. Plus it has a DataSetHelper that lets you use DataSets and DataTables to easily work with Excel data.

 

  • ExcelLibrary seems to still only work for the older Excel format (.xls files), but may be adding support in the future for newer 2007/2010 formats.

EPPlus

  • You can also use EPPlus, which works only for Excel 2007/2010 format files (.xlsx files).
  • There are a few known bugs with each library as noted in the comments. In all, EPPlus seems to be the best choice as time goes on. It seems to be more actively updated and documented as well.

 

  • Also, EPPlus has support for Pivot Tables and ExcelLibrary may have some support (Pivot table issue in ExcelLibrary)

You can use a library called ExcelLibrary. It\’s a free, open source library posted on Google Code:

ExcelLibrary

This looks to be a port of the PHP ExcelWriter that you mentioned above. It will not write to the new .xlsx format yet, but they are working on adding that functionality in.

ExcelLibrary

  • It\’s very simple, small and easy to use. Plus it has a DataSetHelper that lets you use DataSets and DataTables to easily work with Excel data.

 

  • ExcelLibrary seems to still only work for the older Excel format (.xls files), but may be adding support in the future for newer 2007/2010 formats.

EPPlus

  • You can also use EPPlus, which works only for Excel 2007/2010 format files (.xlsx files).
  • There are a few known bugs with each library as noted in the comments. In all, EPPlus seems to be the best choice as time goes on. It seems to be more actively updated and documented as well.

 

  • Also, EPPlus has support for Pivot Tables and ExcelLibrary may have some support (Pivot table issue in ExcelLibrary)

 

Here are a couple links for quick reference:

ExcelLibrary – GNU Lesser GPL

EPPlus – GNU Library General Public License (LGPL)

 

Here some example code for ExcelLibrary:

Here is an example taking data from a database and creating a workbook from it. Note that the ExcelLibrary code is the single line at the bottom:

//Create the data set and table

DataSet ds = new DataSet(\”New_DataSet\”);

DataTable dt = new DataTable(\”New_DataTable\”);

//Set the locale for each

ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;

dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;

//Open a DB connection (in this example with OleDB)

OleDbConnection con = new OleDbConnection(dbConnectionString);

con.Open();

//Create a query and fill the data table with the data from the DB

string sql = \”SELECT Whatever FROM MyDBTable;\”;

OleDbCommand cmd = new OleDbCommand(sql, con);

OleDbDataAdapter adptr = new OleDbDataAdapter();

adptr.SelectCommand = cmd;

adptr.Fill(dt);

con.Close();

//Add the table to the data set

ds.Tables.Add(dt);

//Here\’s the easy part. Create the Excel worksheet from the data set

ExcelLibrary.DataSetHelper.CreateWorkbook(\”MyExcelFile.xls\”, ds);

Creating the Excel file is as easy as that. You can also manually create Excel files, but the above functionality is what really impressed me.

 

Download links –

 

https://code.google.com/p/excellibrary/downloads/detail?name=ExcelLibrary_20110730.zip&can=2&q=

 

https://code.google.com/p/excellibrary/

 

Happy Coding … J

 

WebService: Get all States from Country – JQuery


http://www.westclicks.com/web-services/

This is really nice webservice where it will return json,  array or html option list of countries and if you select country , it will return same for all states too.

HOW TO USE THE WEB SERVICE

The service is comprised of URL calls.
There are a only a few variables to use in the name-value-pair request in the URL:

format
f=format
where format is either:

  • json a json object
  • jsarray a javascript array
  • option an html option list
country
(optional) if you are after the states in the country
c=country
where country is the international double character designation for the country
ie. AU for Australia

thus you end up with a query string something like:
f=json&c=US
Which you pass to the webservice as:
http://www.westclicks.com/webservices/?f=json&c=US

Clicking on the following link will return a page with an option string of all the countries:http://www.westclicks.com/webservices/?f=option
Clicking on the following link will return a page with a json string of the states in Australia:http://www.westclicks.com/webservices/?f=json&c=AU

———————————————

After implementation if you are getting following error – “XMLHttpRequest cannot load . No ‘Access-Control-Allow-Origin’ header is present on the requested resource.”   its, because of cross domain CORS request. You might use Jsonp with .ajax of jquery but looks like this web service is returning option string or json string , so using jsonp is not an option to use. 

Solution: so what i did is, I called controller’s method from jquery and from controller , i called this web service url and get option string –

My code  :

<div data-field-span=”2″>
<label>Country</label>
<select name=”Country” id=”Country” style=”width: 200px;” class=”textBoxDecor” required=”required”>
</select>
</div>
<div data-field-span=”2″>
<label>State</label>
<select class=”textBoxDecor” required=”required” id=”state” name=”state” style=”width: 150px;”></select>
</div>

Script :

<script>

$.getJSON(“doctors/GetCountries“, function (data) {
                         var decoded = $(‘<div/>’).html(data).text();
                         $(“#Country”).append(“<option value=”></option>”);
                         $(“#Country”).append(decoded);
});

$(“#Country”).change(function () {
            var dStates = “”;
            var code = $(“#Country”).val();
            $.getJSON(“/doctors/GetStates?code=” + code, function (data) {
                                dStates = $(‘<div/>’).html(data).text();
                               $(“#state”).html(”);
                               $(“#state”).append(dStates);
            });
});

 </script>

Controller Code C#

public JsonResult GetCountries()
{
               var res = new WebClient().DownloadString(“http://www.westclicks.com/webservices/?f=option&#8221;);
               return Json(res, JsonRequestBehavior.AllowGet);
}
public JsonResult GetStates(string code)
{
                var res = new WebClient().DownloadString(“http://www.westclicks.com/webservices/?f=option&c=”+code);
                return Json(res, JsonRequestBehavior.AllowGet);
}

Hope this helps …    Happy Coding…:)

Solution: Hotmail account disconnected in outlook


  • Select Tools | Account Settings… from the menu in Outlook.
  • Go to the E-mail tab.
  • Click New….
  • Make sure Microsoft Exchange, POP3, IMAP, or HTTP is selected.
  • Click Next >.
  • Type your name as you want it to appear in outgoing email under Your Name:.
  • Enter your Windows Live Hotmail address under E-mail Address:.
  • Make sure Manually configure server settings or additional server types is checked.
  • Click Next >.
  • Make sure Internet E-mail is selected.
  • Click Next >.
  • Make sure POP3 is selected under Account Type:.
  • Enter “pop3.live.com” (not including the quotation marks) under Incoming mail server:.
  • Type “smtp.live.com” under Outgoing mail server (SMTP):.
  • Enter your complete Windows Live Hotmail address (“*** Email address is removed for privacy ***”, for example) under User Name:.
  • Type your Windows Live Hotmail password under Password:.
  • Click More Settings….
  • Go to the Outgoing Server tab.
  • Make sure My outgoing server (SMTP) requires authentication is checked.
  • Verify Use same settings as my incoming mail server is selected.
  • Go to the Advanced tab.
  • Make sure This server requires an encrypted connection (SSL) is checked under Incoming server (POP3):.
  • Make sure SSL is selected for Use the following type of encrypted connection: under Outgoing server (SMTP):
  • Check that “995” appears under Incoming server (POP3:) and “25” under Outgoing server (SMTP):.
  • Click OK.
  • Now click Next >.
  • Click Finish.
  • Click Close.

FIltering jQuery sortable unordered list using selector


I have used the helper code by Kilian Valkhof:

jQuery.expr[':'].contains = function(a,i,m){
    return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase())>=0;
};

This code practically allowed me to use selector :contains in my expressions.

With the helper, I can find any elements that contains the given text. When I have found matching elements, I will look the DOM tree upwards to find the closest li tag. The matched li tag is what I want to hide (or show).

filter = "textToSearch";
$matches = $("ul").find(':contains(' + filter + ')').closest('li');
$('li', list).not($matches).hide();
$matches.show();

 

How to know if the scrollbars has appeared in browser (jQuery)?


if (document.documentElement.scrollHeight === document.documentElement.clientHeight) {
    //There is no vertical scrollbar
}

Entire Function code : 

function ScrollToTop() {
if (document.documentElement.scrollHeight == document.documentElement.clientHeight) {
$(‘#bottom’).hide(); //There is no vertical scrollbar
}
else {
$(‘#bottom’).show();
}
$(‘html, body’).animate({ scrollTop: 0 }, ‘slow’);
}

You can also use

var hasScrollbar = $('body').outerHeight() > $(window).height();