Friday, December 24, 2010

Facebook OAuth - more information

Recently, I had to incorporate OAuth for Facebook.

I ran into a few issues.

First and foremost, I had a "Invalid redirect_uri: Given URL is not allowed by the Application configuration" error.

After some trolling on the net, I found that this can be corrected by Url-encoding the redirect_uri parameter.

Using C#, you can fix this by simply, using the Server.UrlEncode function.



Then, I hit a "Error validating verification code." error.

This is fixed by using a Http-GET rather than a Http-POST to retrieve the information.

To do this, simply do the following.
1. Instantiate a URI object and passing the https://graph.facebook.com/oauth/access_token with relevant parameters. See here for more info.
2. Create a HttpWebRequest object.
3. Setting the http web request "method" attribute to GET.
4. Create a HttpWebResponse object.
5. Create a stream reader object and this should return you the access_token values.



To log-in without a user, simply add "&type=client_cred" to 1.

Monday, December 6, 2010

MS Chart Visual Studio 2008 Add-On - Error executing child

I installed MS Chart Add-On for Visual Studio 2008, compiled the project and hit the "Play" button and received a yellow error screen as the below.





To fix this issue, what you have to do is to simply add an additional "verb" to the "httpHandlers" section within the "system.web" section of the ROOT web.config file.

See below for an example

<add verb="GET,HEAD,POST" path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false" />


I found this fix at handy Stack-Overflow. Click here

Wednesday, December 1, 2010

Google maps - Overcoming rotating label text for the x-axis

Recently, I had to integrate with Google Charts and ran into the problem of rotating the labels of the x-axis. There isn't a fix for this, however, I manage to do a work around by shortening the labels on the x-axis and creating a legend to explain what the labels meant.

Click here for a sample Google chart.



Thursday, November 18, 2010

Twitter OAuth - How To

Step 1:
Register your application. Don't know if you've to Callback URL field but I just assigned to a HTML page that contain very little information.

Step 2:
Get Twitterizer library from here

Step 3:
Use the following code to get the Twitter OAuth token. I used a session to store it but essentially, as long as you store it either using a Cookie, ViewState, Session, row on the DB, that's totally up to you.


OAuthTokenResponse oatResponse = OAuthUtility.GetRequestToken(CONSUMERKEY, CONSUMERSECRET, HttpContext.Current.Request.Url.AbsoluteUri);

if ((Request.QueryString["oauth_token"] == null) && (Session["tweetOAuthToken"] == null))
{
Uri uri = OAuthUtility.BuildAuthorizationUri(oatResponse.Token);
Response.Redirect(uri.AbsoluteUri);
}
else
{
oatResponse = OAuthUtility.GetAccessToken(CONSUMERKEY, CONSUMERSECRET, Request.QueryString["oauth_token"], Request.QueryString["oauth_verifier"]);

//Add to Session that will expire in 24 hours
OAuthTokens oAuthToken = new OAuthTokens();
oAuthToken.AccessToken = oatResponse.Token;
oAuthToken.AccessTokenSecret = oatResponse.TokenSecret;
oAuthToken.ConsumerKey = CONSUMERKEY;
oAuthToken.ConsumerSecret = CONSUMERSECRET;
Session.Add("tweetOAuthToken", oAuthToken);
Session.Timeout = 1440;

Response.Redirect("TwitterLanding.aspx");
}


NOTES:The consumer token and secret is obtained when you register your application and there is definately a requirement to tidy up this code but it works

Monday, October 25, 2010

Server-side button click - client side implementation

Recently, I had to override the server-side button OnClick function for a button but unfortunately and I hope you do NOT come across this scenario, but the source code file, the C# file went MISSING.

Yes, I could have use DotNet Reflector to recover the code but I was under a very quick deadline, so here is my approach.

Use jQuery!

What you have to do is to assign a unique CssClass name for the button, which can still be done with just the .aspx file.

And include jQuery as per normal the crucial part is when you declare the jQuery document.ready function, include the following within the document.ready function.

That way, you override the ASP.Net page life cycle, thus when you click the button, this code snippet runs first.

$("input.[insert_unique_css_class_here]").click(function() {
//Validate some other controls. You will have to implement the validateChkBox and validateDdl functions.
var postBackRequired = false;
var postBackIfCbChecked = validateChkBox();
var postBackIfDdl = validateDdl();

if (postBackIfCbChecked && postBackIfDdl) {
postBackRequired = true;
}

return postBackRequired;
});

Wednesday, October 6, 2010

Repeater Paging - Paged Data Source

Recently I was experimenting with paging and repeaters and managed to solve it with a PagedDataSource object.

There are certain rule that come with this, however.

After instantiating a PagedDataSource object, it is PIVOTAL to set the DataSource property directly after it, before using other properties of the PagedDataSource class.

The way I implemented it was as follows.

Have 1 repeater that will contain the list of data that would like to display.

Also, I've used a repeater approach to implement the paging numbers rather than having just the 1 page number and having 2 links that will go forward and backward.

I've also maintained the page number using a public property with ViewState holding the value of the current page.

Thursday, September 9, 2010

Javascript Pop-ups : Cross browser

http://www.quirksmode.org/js/popup.html

This site shows a good clarification between cross browser JS

Monday, August 30, 2010

SQL Server role and manual admin

I had to create a fresh instance of database for work and had to assign roles. However, I didn't want to use the "click, click, click" method but rather like to type on the query window.

NOTE: This is to be done after you've created a Database and I won't go into details as to how to create a Database or how to add a user to the database.

I retrieve info from MSDN TechNetabout the database roles and are as such.










































Database-level role nameDescription
db_ownerMembers of the db_owner fixed database role can perform all configuration and maintenance activities on the database, and can also drop the database.
db_securityadminMembers of the db_securityadmin fixed database role can modify role membership and manage permissions. Adding principals to this role could enable unintended privilege escalation.
db_accessadminMembers of the db_accessadmin fixed database role can add or remove access to the database for Windows logins, Windows groups, and SQL Server logins.
db_backupoperatorMembers of the db_backupoperator fixed database role can back up the database.
db_ddladminMembers of the db_ddladmin fixed database role can run any Data Definition Language (DDL) command in a database.
db_datawriterMembers of the db_datawriter fixed database role can add, delete, or change data in all user tables.
db_datareaderMembers of the db_datareader fixed database role can read all data from all user tables.
db_denydatawriterMembers of the db_denydatawriter fixed database role cannot add, modify, or delete any data in the user tables within a database.
db_denydatareaderMembers of the db_denydatareader fixed database role cannot read any data in the user tables within a database.

Wednesday, August 25, 2010

hMailServer

We experienced some issues with the IIS SMTP server recently at my work. The following is a description and may you say shameless promotion to a free email server for team at Redmond.

hMailServer is a free e-mail server for Microsoft Windows. It's used by Internet service providers, companies, governments, schools and enthusiasts in all parts of the world.

It supports the common e-mail protocols (IMAP, SMTP and POP3) and can easily be integrated with many existing web mail systems. It has flexible score-based spam protection and can attach to your virus scanner to scan all incoming and outgoing email.

http://www.hmailserver.com/index.php?page=functionality

Saturday, August 21, 2010

IE Tester

I know how web developers dislike the browser from Redmond, however, there is a simple tester that can be downloaded and basically allows you to test how your page renders in Internet Explorer.

Click here -> IE Tester

Saturday, August 7, 2010

Light musing - deep thoughts

“It is not the critic who counts; not the man who points out how the strong man stumbles, or where the doer of deeds could have done them better. The credit belongs to the man who is actually in the arena, whose face is marred by dust and sweat and blood, who strives valiantly; who errs and comes short again and again; because there is not effort without error and shortcomings; but who does actually strive to do the deed; who knows the great enthusiasm, the great devotion, who spends himself in a worthy cause, who at the best knows in the end the triumph of high achievement and who at the worst, if he fails, at least he fails while daring greatly. So that his place shall never be with those cold and timid souls who know neither victory nor defeat.”
-- Theodore Roosevelt, 26th President of the U.S of A

Friday, July 23, 2010

Javascript validate date - native

If somehow you are trying to validate dates that involves 2 drop downs and the values in the drop down are set, you can do the following.

function validateDate(dateToCheck, selectedDay)
{
var totalMonthCount = 12;
var i = 1;
var isValid = true;

var monthToCheck = parseInt(dateToCheck.getMonth());
var yearToCheck = parseInt(dateToCheck.getFullYear());

if(selectedDay > 28)
{
if(monthToCheck == 2)
{
if(yearToCheck%4 == 0)
{
if(selectedDay > 29)
{
isValid = false;
}
}
else
{
isValid = false;
}
}

if((monthToCheck == 4) || (monthToCheck == 6) || (monthToCheck == 9) || (monthToCheck == 11))
{
if(selectedDay > 30)
{
isValid = false;
}
}
}

return isValid;
}

Mobile web development issues

Show-Hide display
To show-hide a loading screen, you would have to ensure that javascript does an unload on the body tag.

In it, you would want to hide (css display = 'none') for the loading screen section. I've used DIVs for the loading screen section.

HTML links & runat="server"
You will have to ensure that the "href" attribute contains "javascript:;" in the event that you intend to add the runat="server" attribute to your HTML links.

Thursday, July 22, 2010

Software Development - Project Managers

This post is a rant. If you don't like a rant, I suggest skipping this.

I am intruiged at the fact that IT Project Managers will allow untested software to be released to the world.

I am beginning to feel that in the corporate world, software developers are the most unappreciated people and also I am having the inkling that project managers are not operating at effective levels.

According to wikipedia, project management is the discipline of planning, organizing, and managing resources to bring about the successful completion of specific project goals and objectives.

And if a software developer is a resource to the project, my argument is, does this mean that the resource is not being managed properly? Does this than equate to the fact that the project manager is not performing their role to a sufficient and acceptable level?

Yes, sufficient and acceptable is subjective, however, when a Software Development project is over cost, delivered past the deliverable date, who is to blame?
From experience, the blame falls squarely at the feet of the developer. The word around the water cooler is, "so and so is doing a bad job, he's not delivering the project". However, my question is, is the developer solely to be blamed for the ludicrious time-line and deliverable date set by the Project Manager?

My question than is, who set the time-line?

Who spoke to the client and made the promise to the client that at a certain date, the project is going to be delivered?

Do they understand the intricacies of software development?

Was testing done prior to release?

Does the project manager understand that the computer is nothing but a dumb terminal that has to be told in specific fine minute details to perform a certain task?

Tuesday, July 20, 2010

dotNet URL

Using the HTTP Request object from the current HTTP context, can return a few different URL path.

To retrieve just the URL without the query string variables, use
RequestObject.CurrentExecutionFilePath

To retrieve the entire URL with query string variables, use
RequestObject.RawURL

There are other important bits that we can use too.

Friday, July 16, 2010

ASP.Net custom validator with javascript

To validate controls using javascript, just so you can use it for XUI or jQuery or whatever Web 2.0 library you use, you can simply declare a ASP.Net Custom Validator as such and have the ClientValidationFunction to be your javascript validator function;

<asp:CustomValidator ID="someVal" runat="server" ClientValidationFunction="jsValidator"></asp:CustomValidator>

Then, in the section of where your javascript code resides, can be in a file or at the top of the same page, declare a function as such.

function jsValidator(args, sender)
{
    //Insert validation here.
    //To set the error message on the ASP.Net validator control, just use the
    //sender object as such;
    //sender.errormessage = "Some error message";
    //Also, remember to set the isValid boolean flag, "args.IsValid"
}

Javascript - retrieving the drop down selected value

I copied this from the Tek-Tips forum just so I have a repository of it.

<head>
<title>New Page 10</title>
<script Language="JavaScript">
function checkData()
{

var myTest = me.D1.selectedIndex.value;
alert(myTest);
}
</script>

</head>

<body>

<form method="POST" name="me">
<select size="1" name="D1" onChange="checkData()">
<option value="99">Default</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><input type="submit" value="Submit" name="B1"><input type="reset" value="Reset" name="B2"></p>
</form>

</body>

</html>

selectedIndex, when used correctly, returns the index (number) of the space in the options collection in which the selected option resides.

Here's what you want to use:

me.D1.options[me.D1.selectedIndex].value

I think that's it. Try the following if not:

me.D1.options[me.D1.options.selectedIndex].value

Thursday, July 15, 2010

ASP.Net hidden fields and XUI

After fiddling around with XUI, I realized that there is no function within to retrieve the hidden input values similar to jQuery.

Thus, the hacked way around it is to declare a HTML tag, eg: a span, paragraph or even div and make the CSS display style as hidden.

You will also have to assign it a class and then you will be able to obtain it using XUI and plain ol' javascript by using the XUI selector and then adding .elements[0].innerHTML to the end of it.

NOTE: Javascript is case sensitive and innerHTML doesn't work if you'd typed it innerHtml

Wednesday, July 14, 2010

XUI JS return false

When creating a HTML link and using XUI, you will HAVE to set the OnClick function of the HTML link tag to contain "return false;".

This is done as XUI events do not implement "return false" properly

Sunday, July 4, 2010

jQuery date picker

To have this working,

1. Include the jQuery UI javascript file into your page.

2. Create an input field and assign it a class. For the purposes of this example, I shall name the input field class, "testDatePicker"

2. Have a jQuery.Document.Ready function and within it, apply the following code.

$('.testDatePicker').datepicker({
dateFormat: 'dd/mm/yy',
showOn: 'both',
buttonImage: '/images/buttons/cal.png',
buttonImageOnly: true,
onSelect: function(){
//Insert any form of logic you will have.
//NOTE: it will have to be in the JavaScript syntax
}
});

Friday, July 2, 2010

jQuery alternating show and hide ...continued

After performing what I thought solve the issue, I came up with another blockage.

The technique from my previous posting worked brilliantly but it wasn't how I wanted it.

This post will further illustrate what I mean.

You see, what I set out to do was to allow the 'jQuery alternating show and hide' individually for each data row.

Let me explain.

I have a list of some data. For the purpose of this example. Lets use HTML unordered-list items.

<ul>
<li>blah1</li>
<li>blah2</li>
<li>blah3</li>
.
.
.
<li>blah-n</li>
</ul>

I had a HTML link (a-href tag) and a HTML paragraph (p tag) in each HTML li tag (see above). The a-href tag was suppose to perform the 'jQuery alternating show and hide' on the p tag.

Within the p tag, there lies the data.

Thus, to solved this, do the following.

1. Create a ASP.Net literal tag to replace the a-href tag.
If you are binding data to a repeater like what I am doing, you can simply access the ASP.Net literal tag in the OnItemDataBound event of the repeater.


2.Use the IF-ELSE statement from Step 5 of the previous post and convert that into a string.

NOTE: open & close swiggly brackets will have to be done twice for each instance.
This caught me out and I was having string issues when building my code.



3. After converting the IF-ELSE statement of Step 5 of the previous post to a string, append the converted string such that it make a distinction on each a-href tag.
The way I did this was to append "_" followed by the ID obtained from the data.

NOTE: Remember to include "return false;" after you've completed the IF-ELSE statement, if not the page will reload to the top of the page!

4. You will also have to append the p tag to used the same method as mentioned in Step 3.

Build your code and

TA-DAH, you're done!

jQuery alternating show and hide

Recently I was working on an iPhone WAP and required to alternate the jQuery show and hide.

This is a How-To to do such an event.

1. Create a HTML A-Href tag and specify the class value of it. For the purposes of this example, I shall call it 'hrefTest'.

Eg:
<a href="#" class="hrefTest">Some test link</a>


2. Create the hidden field. For the purpose of this example, I am going to create a HTML P tag and assign the class value of this P tag to 'test' and also specify in the style value of the P tag of display: none.

Eg:
<p class="test" style="display: none">Some test value</p>


3. Ensure that you have the jQuery library file (jQuery-1.4.2.min.js) or similar has been referenced at the top of the page.
This is something that I often forget to do

4. Declare another script tag and include the jQuery document.ready function.

5. Within the jQuery document.ready function, insert the following

$(".hrefTest").click(function(){
if($(".test").css("display") == "none")
{
$(".test").show();
}
else
{
$(".test").hide();
}
});


And walah, you have yourself a HTML link that will alternate between showing and hiding some text or whatever data.

Wednesday, June 30, 2010

Jokes #1

With many more light-hearted notes to come, I'd start this with #1

Tuesday, June 8, 2010

SQL Haversine formula

This will give you the straight-line a.k.a "as the crow flies" distance between 2 geospatial coordinates.

(6371.392896*2*ATN2(SQRT((sin((radians(GeoLatitude - @lat2Compare)) / 2) * sin((radians(GeoLatitude - @lat2Compare)) / 2)) + (cos(radians(GeoLatitude)) * cos(radians(@lat2Compare)) * sin(radians(GeoLongitude - @long2Compare)/2) * sin(radians(GeoLongitude - @long2Compare)/2)))
, SQRT(1-((sin((radians(GeoLatitude - @lat2Compare)) / 2) * sin((radians(GeoLatitude - @lat2Compare)) / 2)) + (cos(radians(GeoLatitude)) * cos(radians(@lat2Compare)) * sin(radians(GeoLongitude - @long2Compare)/2) * sin(radians(GeoLongitude - @long2Compare)/2)))
)))

Thursday, April 8, 2010

Facebook with DotNet

Recently, I was given the opportunity to work on connecting to Facebook.

The way I've done it is by using Facebook Developer Toolkit available on Codeplex.

Codeplex - Facebook Developer Toolkit

All that is required on Facebook is to create an application and specify the Connect Url on the Connect tab to a specific URL, obtain the API & Secret key and you are set to go.

Facebook developer

More to follow

ps: This has now change as Facebook released their new Graph API.
Further post to come

Sunday, February 7, 2010

jQuery - simulating a C# dropdownlist OnSelectedItemChanged event

To do a simulation of the C# code-behind event of the dropdownlist; OnSelectedItemChange. Simply do the following:-

1. Create a drop down list and ensure that the CssClass attribute contains some value. For the purpose of this example, I'll name it "ddlChange"

eg:
<asp:DropDownList ID="[Your DDL name here]" runat="server" CssClass="ddlChange"></asp:DropDownList>


2. Create a javascrpit tag and add the following code in it.
$(".ddlOrderType").change(function() {
//Insert any logic you require here.
});