Pages

Monday, March 21, 2011

Google Search API & Bing Search API in C#

Hi all,
Making use of the Google search or Bing search in our business application is a very common and general task, with the help of these search API's we can make our application very effective and user friendly. The 2 top search engine that are Google and Bing has provided API that can be easily used in our application. What is required is a class that can handle the response from these search engine. here I am going to explain the general search result class that can be used to accommodate both the search engines. here is the sample code for the same.

public class result
{
public string url;
public string title;
public string content;
public Engine engine;

public enum Engine { bing,google };

public Result(string url, string title, string content, Engine engine)
{
this.url = url;
this.title = title;
this.content = content;
this.engine = engine;
}
}



this is a sample Wrapper for the result handling. Class having a constructor that can initialize all its member, having normal member variables like URL, Content, Engine and the Title. Both the search engines result contains all these field values so I have simply created a warper using the above fields..

Now Lets c the main API accommodation of the Google search API

public class result
{
public string url;
public string title;
public string content;
public FindingEngine engine;

public enum Engine { bing,google };

public Result(string url, string title, string content, Engine engine)
{
this.url = url;
this.title = title;
this.content = content;
this.engine = engine;
}public static List<Result> GoogleSearch(string expression,
Dictionary<string, object> stats_dict)
{
var template = "http://mannpandey.blogspot.com";

Uri search_url;
var results_list = new List<SearchResult>();

int[] offsets = { 0, 8, 16, 24, 32, 40, 48 };

foreach (var offset in offsets)
{
searchuri = new Uri(string.Format(template, expression, offset));

var page = new WebClient().DownloadString(searchuri);

JObject obj = (JObject) JsonConvert.DeserializeObject(page);

var results =
from result in obj["responseData"]["results"].Children()
select new SearchResult(
url: result.Value<string>("url").ToString(),
title: result.Value<string>("title").ToString(),
content: result.Value<string>("content").ToString(),
engine: SearchResult.FindingEngine.google
);

foreach (var result in results)
results_list.Add(result);
}

return results_list;
}
}


In this class we are simply passing the search expression and the dictionary object. Where the URL is passed and the response coming from the API is deserialize using the JSON deserialization.

What ever member variable we have used in the above class are coming from the APi result. like TITLE, CONTENT etc. The de serilizer can be found in the JSOn library that is Json.NET .

Here is the API accommodation for the Bing search

public static List<SearchResult> BingSearch(string expression, Dictionary<string, object> stats_dict)
{
var template = "http://mannpandey.blogspot.com";

var offset_template = "&Web.Offset={1}";
var listresult= new List<Result>();
Uri search_url;
int[] offsets = { 0, 50, 100, 150 };

foreach (var offset in offsets)
{
if (offset == 0)
searchurl = new Uri(string.Format(template, search_expression));
else
searchurl = new Uri(string.Format(template + offset_template, expression, offset));

var page = new WebClient().DownloadString(searchurl);

JObject obj = (JObject)JsonConvert.DeserializeObject(page);

var results_query =
from result in obj["SearchResponse"]["Web"]["Results"].Children()
select new SearchResult
(
url: result.Value<string>("Url").ToString(),
title: result.Value<string>("Title").ToString(),
content: result.Value<string>("Description").ToString(),
engine: SearchResult.FindingEngine.bing
);

foreach (var result in results_query)
listresults.Add(result);
}

return listresult;
}


Bing search API is also similar to the Google API except some difference in there Offset, here also I am making use of the JSON serializer because its very easy to use and can be found in our .net library..


Now you can easily create the object of these classes or put them under separate project that can be used as a DLL. The idea for the same article was taken from one of the popular publishing site "Oreilly", that publishes so many books in the C# and ASP. You can found the details here. URL

I Hope you like this article, if you have any Query please feel free to contact me.. Thanks.

Anil Kumar Pandey
MVP (Visual C# 2009-2010)

Friday, February 18, 2011

Tracking and Loging using Google Analytics

Hello Every one,
This is very important to check the popularity the site frequently, and for maintaining the same we can make use of the Tracking and Loging facility. What we do is simply get the Information that,

1 How many Members are coming to our site?
2. What is the geographical position of them?
3 What was the channel for them to visit our site?
4. And having the statistics in our hand for the performance measurement.

All this activity can be simply manage by using the Google Analytic. It is an enterprise class that let us know that what is the traffic in our site, How many new and old user are visiting our site, and many more, in a very easy way.


The Google Analytic handle all the headache of maintaining the traffic records and we can also view the report based in the Daily, Weekly and Monthly basic. What we have to do is , we just need to Registered into the site, to have an account where we can watch the activity, and a small piece of JavaScript code we need to put in our application that can track the page.


Now, Here the most important things is that if you just want to maintain the list of user that visited the site only, you can post the code in the Default or the Home page only, but if you wish to maintain the list of all the pages then place the code in all the pages.

If you are making use of the Master Pages, simply put them inside the master page so that they can appear on all the pages.

I will provide you the information that how can you set up the Google Analytic in your .NET application.


Step 1. Registration

You first have to Create an account with the Google Analytic for that make use of the URL.

SignUp

Provide the details there like Your UserId and password and other details and create an account.


Step 2. Confirmation Account

An email will be sent to you on the email address that you have provided while registration to activate the account. The email will contain a link and as you click that link your account will be activated.

Step 3. Sign-up to the account


SignUp to the account by using the User name and the password Provided by you at the time of registration.

Step 4. Provide the Website details

As you login to the site first time a page will be opened where you need to provide the information like your time zone and the website details.

Step 5 . Google Analytics Code

Once you fill that information you will come with a page where you will get a User id as UID.
This is your Unique Identification page that you must use inside the script of your page.

Step 6. Write the Script int the Code just below the End of Form Tag

You need to put the Script inside the page just before the end tag of the form tag, because this is the fixed location,. if there are any Master pages, put them just before the Form End tag.


<script type="text/javascript">

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXX-X']);
_gaq.push(['_trackPageview']);

(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

script>


In the Below line You have to Provide the ID generated or given by the Google at the time of registration.

_gaq.push(['UID']);


In Place of UID post your Unique Identification No.

Thanks all, You Tracking and login code is ready, you may wish to view the traffic by simply login to the Google Analytic site and viewing the reports.




I hope You have understood all the step as these are very easy to do and clear steps. If you want any more information you can log in to the official Google Analytic site.

Hope You have Like this Post, If there are any Queried please feel free to post a Comment.


Thanks

Anil Kumar Pandey

Tuesday, February 1, 2011

Sorting a DropDownList using Array list

Hello All,
We frequently make use of the Dropdownlost to display some list items, that may be country name, city name, Postcode , User Name and so many other things. At time we do not have the option to SORT all the list item. In this Code snippet, With the help of the ArrayList we can sort the items inside a DropDown.

The Array List is having a Inbuilt Sorting method which we can make use to sort any list. We simply Copy the Text and Value field of the Dropdown items inside 2 separate ArrayList and then We will add the Items from the Arry List to the DropDown.

Here is the Sample Code.


SortDropDown(ref ddlName); //Calling Method


private void SortDropDown(ref DropDownList objDDL)
{
// Decalre 2 ArryList to Hold the Text and Value of Items
ArrayList alText= new ArrayList();
ArrayList alValue = new ArrayList();


//Copy the Text field in the First Arry List
foreach (ListItem li in objDDL.Items)
{
alTextt.Add(li.Text);
}

alText.Sort(); //Sort the First Array List


//Copy the value field in the Second Array List based on First ArrayList value
foreach (object item in alText)
{
string val = objDDL.Items.FindByText(item.ToString()).Value;
alValue.Add(val);
}
objDDL.Items.Clear(); //Clear the Dropdown

//Finally Add the Sorted Value in DropDown
for(int intIndex = 0; intIndex < textList.Count; intIndex++)
{
ListItem itm = new ListItem(alText[intIndex].ToString(), alValue[intIndex].ToString());
objDDL.Items.Add(itm);
}
}



Hope you got this Clear idea about sorting the Arraylist. In cvase of Any issue Please send a Message.


Thanks
Anil Kumare Pandey

Monday, January 10, 2011

A Chance To become MVP....

Hello All,
here is your chance to become the Community leader and get recognized as the MVP. A chance to be a part of the community leader across the globe. MVP, Please go through the below details and Nominate your self..



Yes, you are good...perhaps the best! You deserve to be with the best -networking and sharing to build the technology the way you know its best!
As MVP nominees, you need to undergo a review and evaluation process. You will be evaluated by a panel that comprises members of the MVP team and Microsoft product groups basis your technical expertise and voluntary community contributions for the past 12 months. The panel would consider the quality, quantity and impact of your contributions in the community.
Participate in closed Betas/ Alphas of Microsoft Software and give feedback to shape up future technology
Network with Product Teams over exclusive MVP Only webcasts and mailing lists
Network with MVPs worldwide with exclusive MVP Private Forums

Nominate yourself by registering here to become Microsoft MVP. The closing date for nominations is 21st January, 2011.
For details on MVP program, joins us for an exclusive session on 13th January, 2011 at 1.00 PM
Topic: How to get the Microsoft MVP Award by Abhishek Kant
Time: 1:00 pm – 2:00 pm

At Microsoft, we believe technical communities enhance people’s lives and the industry’s success every day.

The Microsoft MVP Award recognizes exceptional technical community leaders who foster the free and objective exchange of knowledge by actively sharing their real world expertise with the community and Microsoft.




Thanks,
Anil Kumar Pandey
MVP (Visual C# 2009-2011)

Tuesday, January 4, 2011

New MVP announced for Januray 2011

A Very Happy New Year to you all. Here are the list of new MVP's announced for the january 2011.

DESTIN N JOY -- SharePoint Server -- PATHANAMTHITTA

Sohel Rana -- SharePoint Server -- Dhaka

Diptimaya Patra -- Client App Dev -- Cuttack

Abhishek Sur -- Client App Dev -- Kolkata

Dilip Kumar Pandey-- Excel -- New Delhi

Prabu Kumar Kesavan--Windows Embedded--

Shyam Sasindran -- Windows Expert-IT Pro-- Chennai

SIDDHARTH MEHTA-- SQL Server -- Mumbai

Vinoth Balasubramanian-- Dynamics CRM -- Chennai

Soumya Sengupta -- Windows Expert-Consumer--Kolkata

Gaurav Mantri -- Windows Azure -- Udaipur

Ravi Vermula -- ASP.NET -- Hyderabad

Alwyn Duraisingh -- ASP.NET -- Chennai


Congratulation to all the new MVP's. Keep rocking in the respective community...


Thanks,
Anil Kumar Pandey
MVP (Visual C# 2009-2011)

Thursday, December 16, 2010

Abbreviation for Twitter, FB and Texting

Hello Friends,
Now a days almost every one used Face Book, Twitter or SMS, the very common language used in all these are the abbreviated for of the Words. Most of the peoples know these few words and lot more is unknown. While surfing on net I come across a web site where so many abbreviation were specified, so I am presenting some of the Words here which you can read and come to know...

Abbreviation Meaning
<3>
404 I haven't a clue
A3 Anyplace, anywhere, anytime
ADN Any day now
AFAIK As far as I know
AFK Away from keyboard
ARE Acronym-rich environment
ASAP As soon as possible
A/S/L? Age/sex/location?
B4N Bye for now
BAK Back at the keyboard
BAS Big a** smile
BBIAB Be back in a bit
BBL Be back later
BBN Bye bye now
BBS Be back soon
BEG Big evil grin
BF Boy friend
BFD Big f***ing deal
BFN Bye for now
BG Big grin
BIBO Beer in, beer out
BIOYIOP Blow it out your I/O port
BL Belly laughing


BMGWL Busting my gut with laughter
BOTEC Back-of-the-envelope calculation
BRB Be right back
BTA But then again...
BTDT Been there, done that
BTW By the way
BWL Bursting with laughter
BWTHDIK But what the heck do I know...?
CICO Coffee in, coffee out
C&G Chuckle and grin
CNP Continued in next post
CRB Come right back
CRBT Crying real big tears
CU See you
CUL See you later
CUL8ER See you later
CYA See ya
CYA Cover your ass
CYO See you online
DBA Doing business as
DFLA Disenhanced four-letter acronym (that is, a TLA)
DL Dead link
DLTBBB Don't let the bed bugs bite
DIKU Do I know you?
DITYID Did I tell you I'm distressed?
DOM Dirty old man
DOS Dozing off soon
DQMOT Don't quote me on this
DTRT Do the right thing
DWB Don't write back
E2E exchange to exchange
E2E e-business to e-business
E2E employee to employee
E2E end to end
EG Evil grin
EMFBI Excuse me for butting in
EMSG E-mail message
EOM End of message
EOT End of thread (meaning: end of discussion)
ESAD Eat s**t and die
ETLA Extended three-letter acronym (that is, an FLA)
EWG evil wicked grin
F2F Face to face
FAQ Frequently-ask question(s)
FC Fingers crossed
FISH First in, still here
FLA Four-letter acronym
FMTYEWTK Far more than you ever wanted to know
FOMCL Falling off my chair laughing
FTBOMH From the bottom of my heart
FUBAR F***ed up beyond all repair or recognition
FUD Fear, Uncertainty, and Doubt
FWIW For what it's worth
FYI For your information
G Grin
GA Go ahead
GAL Get a life
GIGO Garbage in, garbage out
GD&R Grinning, ducking, and running
GF Girlfriend
GFN Gone for now
GGP Gotta go pee
GIWIST Gee, I wish I'd said that
GL Good luck
GMAB Give me a break
GMTA Great minds think alike
GOL Giggling out loud
GTRM Going to read mail
GTSY Glad to see you
H&K Hug and kiss
HAGN Have a good night
HAND Have a nice day
HHIS Hanging head in shame
HIG How's it going
HT Hi there
HTH Hope this helps
HUB Head up butt
IAC In any case
IAE In any event
IANAL I am not a lawyer (but)
IAW I agree with or In accordance with
IC I see
IGP I gotta pee
IHA I hate acronyms
IHU I hear you
IIRC If I recall/remember/recollect correctly
ILU or ILY I love you
IM Immediate message
IMCO In my considered opinion
IMHO In my humble opinion
IMing Chatting with someone online usually while doing other things such as playing trivia or other interactive game
IMNSHO In my not so humble opinion
IMO In my opinion
IMS I am sorry
IOW In other words
IPN I'm posting naked
IRL In real life (that is, when not chatting)
ITA I totally agree
ITIGBS I think I'm going to be sick
IWALU I will always love you
IYSWIM If you see what I mean
J4G Just for grins
JBOD Just a bunch of disks (like redundant array of independent disks, etc.)
JIC Just in case
JK or j/k Just kidding
JMO Just my opinion
JTLYK Just to let you know
k ok
KISS Keep it simple stupid
KIT Keep in touch
KOTC Kiss on the cheek
KOTL Kiss on the lips
KWIM? Know what I mean?
L8R Later
L8R G8R Later gator
LD Later, dude
LDR Long-distance relationship
LHO Laughing head off
LLTA Lots and lots of thunderous applause
LMAFO Laughing my f**king a** off
LMAO Laughing my a** off
LMSO Laughing my socks off
LOL Laughing out loud
LRF Little Rubber Feet (the little pads on the bottom of displays and other equipment)
LSHMBH Laughing so hard my belly hurts
LTM Laugh to myself
LTNS Long time no see
LTR Long-term relationship
LULAB Love you like a brother
LULAS Love you like a sister
LUWAMH Love you with all my heart
LY Love ya
LY4E Love ya forever
MorF Male or female
MOSS Member of the same sex
MOTOS Member of the opposite sex
MTF More to follow
MUSM Miss you so much
NADT Not a darn thing
NFG No f*****g good
NFW No feasible way or no f*****g way
NIFOC Naked in front of computer
NP or N/P No problem
NRN No response necessary
OIC Oh, I see
OLL Online love
OMG Oh my God
OTF Off the floor
OTOH On the other hand
OTTOMH Off the top of my head
PANS Pretty awesome new stuff (as opposed to "POTS")
PAW Parents are watching
PCMCIA People can't master computer industry acronyms
PDA Public display of affection
PEBCAK Problem exists between chair and keyboard
PIBKAC Problem is between keyboard and chair
PITA Pain in the ass
PM Private message
PMFJIB Pardon me for jumping in but...
POAHF Put on a happy face
::POOF:: Goodbye (leaving the room)
POTS Plain old telephone service
PU That stinks!
QT Cutie
RL Real life (that is, when not chatting)
ROR Raffing out roud (Engrish for "laughing out loud")
ROTFL Rolling on the floor laughing
ROTFLMAO Rolling on the floor laughing my a** off
ROTFLMAOWPIMP Rolling on the floor laughing my a** off while peeing in my pants
ROTFLMBO Rolling on the floor laughing my butt off
RPG Role-playing games
RSN Real soon now
RT Real time
RTFM Read the f***ing manual
RYO Roll your own (write your own program; derived from cigarettes rolled yourself with tobacco and paper)
S^ S'up - what's up
S4L Spam for life (what you may get when you become someone's customer or client)
SHCOON Shoot hot coffee out of nose
SEG S***-eating grin
SETE Smiling ear to ear
SF Surfer-friendly (low-graphics Web site)
SHID Slaps head in disgust
SNAFU Situation normal, all f***ed up
SO Significant other
SOL Smilling out loud or sh*t out of luck
SOMY Sick of me yet?
SOT Short on time
SOTMG Short on time must go
STFU Shut the f**k up
STFW Search the f*****g Web
STW Search the Web
SU Shut up
SUAKM Shut up and kiss me
SUP What's up
SWAG Stupid wild-a** guess
SWAK Sealed with a kiss
SWL Screaming with laughter
SYS See you soon
TA Thanks again
TAFN That's all for now
TANSTAAFL There ain't no such thing as a free lunch
TCOY Take care of yourself
TFH Thread from hell (a discussion that just won't die and is often irrelevant to the purpose of the forum or group)
TGIF Thank God it's Friday
THX Thanks
TIA Thanks in advance (used if you post a question and are expecting a helpful reply)
TILII Tell it like it is
TLA Three-letter acronym
TLK2UL8R Talk to you later
TB4U Too bad for you
TMI Too much information
TNT Till next time
TOPCA Til our paths cross again (early Celtic chat term)
TOY Thinking of you
TPTB The powers that be
TTFN Ta-Ta for now
TTT Thought that, too (when someone types in what you were about to type)
TTYL Talk to you later
TU Thank you
TY Thank you
TYVM Thank you very much
UAPITA You're a pain in the ass
UAF Until further notice
UW You're welcome
VBG Very big grin
VBSEG Very big s***-eating grin
WAG Wild a** guess
WAYD What are you doing
WB Welcome back
WBS Write back soon
WDALYIC Who died and left you in charge?
WEG Wicked evil grin
WFM Works for me
WIBNI Wouldn't it be nice if
WT? What/who the ?
WTF What the F***!
WTFO What the F***! Over!
WTG Way to go!
WTGP? Want to go private?
WU? What's up?
WYSITWIRL What you see is TOTALLY WORTHLESS IN REAL LIFE!
WUF? Where are you from?
WYSIWYG What you see is what you get
YBS You'll be sorry
YGBSM You gotta be s***tin' me!
YMMV Your mileage may vary.
YW You're welcome

The Source of the Information is here

Enjoy!!!!!

Thanks,
Anil Kumar Pandey
MVP (Visual C# 2009-2010)

Wednesday, December 15, 2010

Get No. of Users On-line in ASP.net Membership

Hello all,
In our web application many times we need to display, that how many numbers of users are on-line, This is become quite easy if we are making use of ASP.Net Membership in our application. The Membership is having a function which directly gives us the no. of users on-line in the web site. "Membership.GetNumberOfUsersOnline(); " this function gives us the list of users on-line.

Here is a implementation of this code in c#


System.Collections.Generic.List<string> lstUserOnline = new System.Collections.Generic.List<string>();

int intUsersOnline = Membership.GetNumberOfUsersOnline();

foreach(MembershipUser usr in Membership.GetAllUsers())
{
if(usr.IsOnline)
{
lstUserOnline.Items.Add(usr.UserName);
}
}

//Bind the List to the ListBox
ListBox1.DataSource = lstUserOnline;
ListBox1.DataBind();

But there are some cases which are hard to track, that Suppose if any users have Closed his browser window without Logging out from the application, in that the Users remains On-line so it will also come under the list. So to avoid this issue up to some extent we can make use of logout time setting in the web config file, where we can easily set the time-out for a user, if he is not active any more. The entry will be like this.

<membership defaultProvider="SqlProvider"
userIsOnlineTimeWindow="20">
<providers>
<add name="SqlProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="SqlServices"
enablePasswordRetrieval="true"
enablePasswordReset="false"
requiresQuestionAndAnswer="true"
passwordFormat="Encrypted"
applicationName="MyApplication" />
</providers>
</membership>


Hope You have like this small piece of code. Please feel free to post the comment or any issue regarding this code.


Thanks,
Anil Kumar Pandey
MVP (Visual C# 2009-2010)

Kontera