How to authenticate to FaceBook Graph Api – Part I

Facebook uses the OAuth 2.0 protocol for authentication and authorization. To begin use Facebook new Graph Api you have first to perform user authentication and authorization. As facebook mention in their documentation there are  two different OAuth 2.0 flows for user login: server-side (know as the authentication code flow in the specification) and client-side (known as the implicit flow). The server-side flow is used whenever you need to call the Graph API from your web server. The client-side flow is used when you need to make calls to the Graph API from a client, such as JavaScript running in a Web browser or from a native mobile or desktop app.
So, each OAuth flow (server-side or client-side) there are three different steps to pass

a- User authentication: ensures that the user is who they say they are
b- app authorization: ensures that the user knows exactly what data and capabilities they are providing to your app. Ex read permissions – write permissions – page permissions
c- app authentication: ensures that the user is giving their information to your app and not someone else

after completing this 3 steps your application is now granted user access token

Server-Side:
To authenticate user and application authorization you have to redirect user to facebook OAuth Dialog.
First of all you have to create facebook application just by go to https://developers.facebook.com/apps ,after login to facebook this page will appear to ensure that you want to allow Facebook Developer Application to access your data

If you notice that Facebook Developer Application asks for accessing you basic information. If you don’t allow the application, the application will forward you directly to nowhere because there is no redirect url. If you click on Allow then you will proceed to developer welcome page with some useful links that may help you in building applications

Let’s proceed to create your first Facebook Application just click on Create New App in the top right. You are just one step away from creating your first application by adding application name and continue, but before you continue there is two optional fields first is App Namespace that is an optional field for defining custom Open Graph actions and objects (e.g., namespace:action) and for the URL for Canvas apps used on Facebook (e.g., http://apps.facebook.com/namespace)

You have to enter security check pic 

And here is your First Facebook application 

Notice: you will use App Id and App Secret in your application to connect to Facebook.Also you have to define site url under web section you can  if you are working in localhost you can add site url as http://locahost:{port if exist}

Now you are ready to authenticate users by redirecting them to Facebook login page by any programming language to be continued ….

Lucene.Net – LINQ to Lucene using Entity Framework

What is Lucene ?

Lucene is an Information Retrieval System used for full-text searching and scoring results commonly referred to as a search engine (similar to google-type-searching).

Lucene.Net is a port of the Lucene search engine library, written in C# and targeted at .NET runtime users. The Lucene search library is based on an inverted index.

LINQ is Microsoft’s extensible Language Integrated Query platform that provides querying directly in a managed CLR. LINQ comes out of the box with LINQ to Objects, LINQ to DataSets, LINQ to XML, LINQ to SQL and LINQ to Entities. The goal of LINQ to Lucene is to provide developers with the ability to enjoy full-text searching using a fast-proven search-engine within the .Net managed CLR.

What is LINQ to Lucene?

CodePlex providing a custom LINQ solution for the Lucene Information Retrieval System, commonly referred to as a search-engine.

Since the format of Lucene, which stores its data in an Index as Documents with fields, the project will be capable of mapping custom business object types, a kind of Object-Index-Mapper (OIM) similar to the typical Object-Relational-Mapper (ORM) that LINQ to SQL provides. LINQ to Lucene uses attributes and reflection on classes to be indexed and their members, similar to the Table and Column decorators for SQL mapped objects. Types can easily support LINQ to SQL decorations for a larger number of members while co-supporting LINQ to Lucene decorations for the few members that support it. Classes stored in the lucene index are decorated with the [Document] attribute and its properties are decorated with the [Field] attribute. lets start practically.

Create Search Solution

Mainly there are two faces to a search solution , Indexing the data you wish to search on it, and actually searching the content.

First create a project and add the required references. We are going to use Lucene.Net.dll and Lucene.Linq.dll and finally the EntityFramework.dll.

Using Entity Framework capability “Reverse Engineer Code First” we are going to create our data context – we will use Northwind as a model , simply r-click on your project , choose Entity Framework , Reverse Engineer Code First , it will show a dialog to connect to your model database.

Entity Framework will do all the jobs for you to create all mapping and entity classes.

Now we got the NorthwindContext which represent the DbContext for the Northwind database. As we mentioned above we need to make IndexContext for the indexed data so we will create NorthwindIndexContext to manage our indexed data

Notice it must inherit from EfDatabaseIndexSet as we use Entity Framework DbContext. NorthwindIndexContext will hold all the entities that will be indexed and ready for search just like the NorthwindContext for the DbContext. Now we must specify the Entities that will be indexed, we will take the Customer entity as example.

As we mentioned above , to specify an entity for indexing you have to decorate the entity class by [Document] attribute , this attribute will tell Lucene that this entity is ready for indexing and searching. Other requirements is to Implement IIndexable Interface , INotifyPropertyChanging and INotifyPropertyChanged.

The next step is to specify fields that you would like to index.

The [Field] attribute is used for telling Lucene that field will be indexable and searchable, it has many parameters I will let you discover.

Back to the NorthwindIndexContext and add the property for the Customer entity

Now we are ready to write our program

In the previous code we specified the directory where Lucene will index the data in, instantiate the NorthwindIndexContext giving the path and the NorthwindContext , now we can index Customer entity by calling

The SimpleDemo method is an example for how to query from the indexed data , you will notice that it’s look similar to Linq and Entity querying.

There is a lot of features and solutions in Lucene you can discover it in the sample code.

Download sample

References
http://linqtolucene.codeplex.com/
http://lucene.apache.org/core/
http://incubator.apache.org/lucene.net/

Large file upload – asp.net

Uploading large files in ASP.Net or MVC is a little confusing for some of us.

I faced this confusing issue more than a year ago and solved it by the help of some articles online, but recently I faced the same issue I faced 1 year ago, and totally forgot how to fix it.

So I wanted to list here the URL which solved all my issues a year ago, and solved it recently as well:

Telerik Uploading Large Files , This article contain everything which helps to edit the web.config and IIS to make uploading large files a nice task.

To know more about these properties you will edit in the web.config, I recommend to take a look at this msdn page

 

Organize JavaScript and jQuery events – DOM-ready execution

In complex websites javascript and jquery events can conflict with each other, especially if you are using the same javascript files for different website pages.
There are many techniques to solve this issue, and I found a good solution by following these articles:
Automate firing of onload events
Markup-based unobtrusive comprehensive DOM-ready execution
Extending Paul Irish’s comprehensive DOM-ready execution

But while using this technique I faced an issue, I wanted to call more than one init function on the same page load, for example if I have my page as sections: header, login popup, inner form, footer. And each section needs to have its own init functions which load automatically when this section DOM-ready.

In Extending Paul Irish’s comprehensive DOM-ready execution article
He used the body element to run the selected action in the selected controller

And since body element is always one in any page, so we can’t call more than one controller action.

I extended this technique to use any html element in the page, something like that:

Like that i can use this element multiple times in the page for different controllers and actions.
But this required to edit JASON GARBER javascript UTIL function to fit this change.
Using the body element code was:

And using my way it required changing the code to be:

And as you see in my code I loop on all elements which use class ‘initializer’ and read/call from them one by one controllers – actions.

By applying this edit, you will be able to assign multiple different controllers in the same page based on the page sections.

 

Download Demo

How to schedule a database backup operation by using SQL Server Management Studio in SQL Server 2008

What is the meaning of backup?
a backup or the process of backing up is making copies of data which may be used to restore the original after a data loss event. So we need to create a periodically backup to ensure that users data is safe and can be recoverable if any loss happened.

How to create database backup?

  1. Start SQL Server Management Studio.
  2. In the Connect to Server dialog box, click the appropriate values in the Server type list, in the Server name list, and in the Authentication list.
  3. Click Connect.
  4. In Object Explorer, expand Databases.
  5. Right-click the database that you want to back up, click Tasks, and then click Back Up.
  6. In the Back Up Database – [Database Name] dialog box, type the name of the backup set in the Name box, and then click Add under Destination.
  7. In the Select Backup Destination dialog box, type a path and a file name in the Destinations on disk box, and then click OK.
  8. Click ok to save your backup to disk.

How To Schedule a database backup operation?

  1. Repeat steps from 1 to 7.
  2. In the Script list, click Script Action to Job.
  3. In the New Job dialog box, click Steps under Select a page, and then click Edit if you want to change the job parameters.
  4. Under Select a page, click Schedules, and then click New.
  5. In the New Job Schedule dialog box, type the job name in the Name box, specify the job schedule, and then click OK.
    Note If you want to configure alerts or notifications, you can click Alerts or Notifications under Select a page.
  6. Click OK two times. You will receive the following message:The backup of database ‘Database Name‘ completed successfully.

 

MongoDB Series – Admin UIs

In this post we are going to manage MongoDB visually. MongoDB has many admin UIs for many platforms, you can visit http://www.mongodb.org/display/DOCS/Admin+UIs to choose your suitable client UI.

We are going to setup one of these admin UI , as we are using windows platform I preferred to use MongoVUE.

Brief about MongoVUE

MongoVUE is an innovative MongoDB desktop application for Windows OS that gives you an elegant and highly usable GUI interface to work with MongoDB. Now there is one less worry in managing your web-scale data.

Before Installation

After installing MongoDB on your machine you noticed that each time you have to run the server mongod shell and it must be running along your work with the database. For a better solution you can run MongoDB as a service behind the seen. First open your cmd and locate your MongoDB directory (for Win 7 run as an administrator) and type :

lets explain each parameter :

–logpath Specify the log file path which will log every transaction on mongo server.
–logappend So that restarts of the service append to the existing log file.
–dbpath Specify the database saving path.

now you can find MongoDB service installed in your computer services

make sure it’s started and then try to connect by shell without running the mongod again.

Now we have to add a user to admin db so that we can connect from our server client and manage our databases.

every thing is now ready to install MongoVUE.

Install MongoVUE

Download MongoVUE installer from the official website and follow the wizard. Run MongoVUE from start menu.

When you run MongoVUE a window will show you the available connections so you can add/edit/delete connections to the server.

click on the green button to add a new connection, a window appears asking for basic settings.

Name Choose any name to save the connection with.
Server the localhost server IP for local connection is 127.0.0.1 otherwise put online address.
Port MongoDB default port is 27017
Username user can authenticate
Password: use’rs password
Database specify database or leave it blank so you can see all databases.

now you can test your connection and save it.

choose your connection and click connect , now you r running the server.

the left side bar shows the databases.

the admin database which holds the admin users, default system db local , and test db.

Now create new database let’s name it treenodesdb , right click on databases add database.

now you can add collections to treenodesdb , let’s create employees collection , right click on the database and add collection.

To add a document (record) on employees collection , right click on the collection and click insert document , will show dialogue to write the insert statement in BSON form

After adding some records  you can see all the records by clicking on View menu.

There are three types of view Tree View, Table View and Text View

This is the simplest actions you can do it on the Admin UI MongoVUE but there are advanced transactions will talk about it later.

References

http://www.mongodb.org/display/DOCS/Security+and+Authentication#SecurityandAuthentication-ViewingUsers

http://www.mongodb.org/display/DOCS/Admin+UIs#AdminUIs-MongoVision

http://www.mongovue.com/

Google Android Development – Part 3 – Android UI

This is the third post in a multi-part series on Android development.  Throughout the series, we’ll explore how to build applications for the Android platform.  This third post we are going to talk about android user interface.

Google Android Development

Introduction

The goal of this post is to get you familiar with the android user interface. So you will be able to understand android user interface components. I will continue working in Hello World project that I have created in my first post  here.

  1. Everything is a view.
  2. Layout files.

1-      Everything is a view

In an Android application, the user interface is built using View and ViewGroup objects. There are many types of views and view groups.

View objects are the basic units of user interface expression on the Android platform. The View class serves as the base for subclasses called “widgets” which offer fully implemented UI objects, like text fields and buttons.

The ViewGroup class serves as the base for subclasses called “layouts,” which offer different kinds of layout architecture, like linear, tabular and relative.

What is a View Object?

On the android platform, View is an overloaded word. The first meaning of View is the actual layout file. The second meaning of View is the individual widgets (Buttons, TextView, etc…) or any control in the screen. The third and the more common the Entire UI

A View object is a data structure whose properties store the layout parameters and content for a specific rectangular area of the screen. A View object handles its own measurement, layout, drawing, focus change, scrolling, and key/gesture interactions for the rectangular area of the screen in which it resides. A View is also a point of interaction for the user and the receiver of the interaction events.

On the Android platform, you define an Activity’s UI using a hierarchy of View and ViewGroup nodes, as shown in the diagram below. This hierarchy tree can be as simple or complex as you need it to be, and you can build it up using Android’s set of predefined widgets and layouts, or with custom Views that you create yourself.

How the Activity draws Views?

In the previous post here we talked about Android Activities. So if you are familiar with mvc framework you have to differentiate between Controller/Views  in MVC frame work and Activity/View in Android platform, In Android things a little different because the Activities is not actually the controller in MVC because it contains a lot of the logic of displaying.
How the activity draws the view? There are two ways you can design your interface either by View Object, you can programmatically create and construct the layout. Or, you can pass a XML Layout File to add controls

2-     Layout files

Layout files is XML representations of View objects that we talked about before.  XML offers a human-readable structure for the layout, much like HTML. Each element in XML is either a View or ViewGroup object. View objects are leaves in the tree, ViewGroup objects are branches in the tree as we mention in the previous graph.

The name of an XML element is respective to the Java class that it represents. So a <TextView> element creates a TextView in your UI, and a <LinearLayout> element creates a LinearLayout view group. When you load a layout resource, the Android system initializes these run-time objects.

For example, in our HelloWorld project

Lets open main.xml file that we have created before the first thing appears is the graphical layout we can see some controls TextView contains text Hello World, HelloWorldActivity! And a button Click Me!

If we switch to main.xml the xml file we can see

It is just xml file as we can see and it has a root element <LinearLayout> we are going to talk about it later in details when we are going to talk about layouts, for now you have to know that is a control let you put controls inside it. That LinearLayout gives you the ability to put controls vertically or horizontally and you can put another LinearLayout inside it or any other Layout type inside it. we have inside the Linear TextView and Button.

You can see each attribute in the view has a meaning and as you can see each attribute has android in the beginning that refer to the namespace of the attribute, you can define your own custom namespace that is more advanced topic we are going to talk about later. Inside the layout file the view needs to have two required parameters in every single view is a layout width and layout height we can use fill_parent , Wrap_content or match_parent.

  • Fill_parent means that the view wants to be as big as its parent, minus the parent’s padding, if any.
  • Wrap_content means that the view wants to be just large enough to fit its own internal content, taking its own padding into account.
  • Match_parent  means that the view wants to be as big as its parent, minus the parent’s padding

The difference between Fill_parent and Match_Parent ,Fill_parent is deprecated starting in API Level 8 and replaced by Match_Parent.

Also android:id that is what android uses to generate R.Java file it gives you a strong name if you are want to find that control later

What @+id/MyButton means?

  • @ means that is stored as a resource
  • + means we have to create this resource if it is not exist
  • Id means the name of the class in R.Java that this control will be created in
  • MyButton the control id

So if we go to R.Java we can see there is a new class generated automatically named id contains MyButton so that is the way how the activities are connected to layout

That all for that tutorial we can now understand what is a view and what is a layout and what is the difference between them

 

 

 

MongoDB Series – Manipulating the database

On the previous post I expressed my intention of Introduction to MongoDB windows installation. In this post I’m going to write some hints on how to manipulate with MongoDB.

Getting a Database connection

As we saw after install MongoDB and run the shell, the shell is convenient for interactive and administrative use. By default the shell connects to database “test” you will see then :

“connecting to” tells you which database in current use. To switch databases type :

Note that switching to a none exist database doesn’t mean creating the database – the database is created lazily the first time data is inserted, This means that if you use a database for the first time it won’t show up in the list provided by "show dbs” until data is inserted.

Dynamic Schema (“Schema Free”)

MongoDB has databases, collections, and indexes much like a traditional RDBMS. In some cases (databases and collections) these objects can be implicitly created, however once created they exist in a system catalog (db.systems.collections, db.system.indexes).

Collections – which is similar to tables in RDBMS – contain (BSON) documents – like rows or records in RDBMS . Within these documents are fields – columns in RDBMS. In MongoDB there is no predefinition of fields in other words there is no fixed structure in a collection. There is no schema for fields within documents – the fields and their value datatypes can vary. Thus there is no notion of an “alter table” operation which adds a “column”. This flexibility means that schema migration and augmentation are very easy in practice – rarely will you need to write scripts which perform “alter table” type operations. In addition to making schema migration flexible, this facility makes iterative software development atop the database easier.

Inserting data into a collection

Let’s create a test collection and insert some data into it. We will create two objects, user1 and user2, and then save them in the collection users.

Now let’s notice that :

  • We didn’t ask for creating the collection , the database creates it automatically on the first insertion.
  • The documents can have different fields.
  • Upon being inserted into the database, objects are assigned an object ID (if they do not already have one) in the field _id.

Accessing Data From a Query

We’ll use the simple find() query method, which returns everything in a collection, and talk about how to create specific queries later on.

In order to see all the elements in the collection when using the mongo shell, we need to explicitly use the cursor returned from the find() operation.

I will add some more documents so we can show it more clearly.

You can clear the shell by ctrl-l.

Lets repeat the same query, but this time use the cursor that find() returns, and iterate over it in a while loop :

The above example shows cursor-style iteration. The hasNext() function tells if there are any more documents to return, and the next() function returns the next document. We also used the built-in printjson() method to render the document in a pretty JSON-style format.

Notice that we are working in a JavaScript shell so we can use most functionality of JavaScript like forEach() directly without iterate in a while loop db.users.find().forEach(printjson);

Also we can treat with cursor as an array :

Specifying What The Query Returns

Now that we know how to work with the cursor objects that are returned from queries, lets now focus on how to make queries more specific.

In general, the way to do this is to create “query documents”, which are documents that indicate the pattern of keys and values that are to be matched.

These are easier to demonstrate than explain. In the following examples, we’ll give example SQL queries, and demonstrate how to represent the same query using MongoDB via the mongo shell. This way of specifying queries is fundamental to MongoDB, so you’ll find the same general facility in any driver or language.

SELECT * FROM users WHERE name=”Mohamed”

The query expression is an document itself. A query document of the form { a:A, b:B, … } means “where a==A and b==B and …”.

findOne() Query

For convenience, the mongo shell (and other drivers) lets you avoid the programming overhead of dealing with the cursor, and just lets you retrieve one document via the findOne() function. findOne() takes all the same parameters of the find() function, but instead of returning a cursor, it will return either the first document returned from the database, or null if no document is found that matches the specified query.

As an example, lets retrieve the one document with name=='Mohamed'. There are many ways to do it, including just calling next() on the cursor (after checking for null, of course), or treating the cursor as an array and accessing the 0th element.

However, the findOne() method is both convenient and efficient:

This is more efficient because the client requests a single object from the database, so less work is done by the database and the network. This is the equivalent of find({name:"Farrag"}).limit(1).

Another example of finding a single document by _id:

Limiting the Result Set via limit()

You may limit the size of a query’s result set by specifying a maximum number of results to be returned via the limit() method.

This is highly recommended for performance reasons, as it limits the work the database does, and limits the amount of data returned over the network. For example:

Now we covered the most commands for MongoDB, other commands you can find it at MonogDB documentation.

On the next post we will talk about using MongoDB with C#/.Net driver.

References

  • http://www.mongodb.org/display/DOCS/Tutorial