Friday, April 20, 2012

Set SelectParameter for SqlDataSource SelectCommand with unknown ammount of variables

"



    SelectCommand="SELECT *
FROM Date AS t1 FULL OUTER JOIN (SELECT * FROM WorkHoursEntry WHERE (WorkerID LIKE @WorkerID)) AS t2 ON t1.PKDate = t2.WorkDay
LEFT OUTER JOIN Worker AS t3 ON t2.WorkerID = t3.WorkerID
LEFT OUTER JOIN (SELECT * FROM Project WHERE ProjectID IN(@Project)) AS t4 ON t2.ProjectID = t4.ProjectID"
FilterExpression="YearMonth IN({0})"
>
<FilterParameters>
<asp:ControlParameter ControlID="yearMonthFilterLabel" Name="YearMonth"
PropertyName="Text" Type="String" />
</FilterParameters>
<SelectParameters>
<asp:ControlParameter ControlID="WorkerIDLabel" Name="WorkerID"
PropertyName="Text" Type="String" />
<asp:ControlParameter ControlID="projectFilterLabel" Name="Project"
PropertyName="Text" Type="String" />
</SelectParameters>
</asp:SqlDataSource>


Greetings, I have problem with @Project ControlParameter, problem is I don't know how to pass several values and FilterParameters method won't work as I want. Is there any way to pass several variables ? (without using c#).



projectFilterLabel.Text = 'aaa, bbb, ccc';


Basically what I want to do is to select all values from Date table and join them with some values from Project table and output to DataList.



Any help appreciated, I just started learning asp.net



Thanks.





bind one report with datasat has multipe datatables

I have one Dataset (XSD) with one big data table (represent 2 tables)
I bind this dataset with ReportViewer like this:



        reportViewer1.ProcessingMode = ProcessingMode.Local;
reportViewer1.LocalReport.ReportPath =


"Master_re_Details.rdlc";



       reportViewer1.LocalReport.DataSources.Add(new 


ReportDataSource("DataSet1", this.B_ds.Tables[1]));
reportViewer1.RefreshReport();



        reportViewer1.LocalReport.DataSources.Add(new 


ReportDataSource("DataSet1", this.B_ds.Tables[0]));



        reportViewer1.RefreshReport();


but i get the value from only one datasource only Tables[1] or Tables



[0] but not both of them!
(I guess the first one used)
where is the mistake??





Can .NET website access C drive, add vba macros to ms office and enable Macros Security in Outlook?

This is the scenario:



There's an intranet website that stores a set of macros (Outlook addons). Now I want a user to visit, choose the one they're interested in (Language) and have it installed into their Outlook.



I first need to find the right folder of course, some users still have old images and their Outlook Profile lives in Windows/Microsoft. Some of them use 2003, some 2010 but majority is on 2007.



So the questions are as follows: Can I...




  • use .NET WEBSITE to navigate to user's C:/.. drive ?

  • install new macros ?

  • enable Outlook's Macros security ?





"self" can not detect its properties in Xcode indeed it even doesn't know which class itself is

Hi everyone I have a really strange problem. I create a new subclass of NSObject, but I just cannot use "self.someproperty" in the implementation. Normally when I type the word "self", Xcode will guess what I'm typing and give me the property name after dot. But in this case, it doesn't and give me an red error. I have check my code for a night and give up now. So, wish some one give me a advise please let me know this might be a small problem somewhere?



Here's my code:



#import <Foundation/Foundation.h>

@interface FlickrPhotoCache : NSObject

+(BOOL)isInCache:(NSDictionary *)photo;

@end



#import "FlickrPhotoCache.h"

@interface FlickrPhotoCache()

@property (nonatomic, strong) NSMutableArray *photos;

@end

@implementation FlickrPhotoCache
@synthesize photos = _photos;

+(BOOL)isInCache:(NSDictionary *)photo
{
self.photos // here I get error
}

@end


Thanks in advance! WHT





WPF Datagrid edit only single cell value

I have a WPF Datagrid with 2 columns say parametername and value.



My Requirement is only one value(cell content) for a Particular parametername should be editable and the entire Datagrid contents should be read only....



And I have a save button to save the values.



I had been researching from couple of days for an appropriate solution which observes to be a common requirement in many cases but I havent found...



Please any solution or ideas will be appreciated..



Here is XAML & cs : When the Datagrid loads I want only the PM2 cell value to be in edit mode and all other datagrid content should be greyed out or non-editable..






<Grid>
<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False"
Margin="20,57,18,19" Name="dataGrid1"
Height="250" SelectionUnit="Cell" >

<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding ParameterName}" Width="100" Header="Parameter Name" IsReadOnly="True"/>

<DataGridTextColumn Binding="{Binding Value}" Width="100" Header="Value" />

</DataGrid.Columns>

</DataGrid>
</Grid>





And my CS code



public partial class dgSF : Window
{

ObservableCollection<ParameterSet> pmset;

public dgSF()
{
InitializeComponent();
pmset = new ObservableCollection<ParameterSet>();

pmset.Add(new ParameterSet() { ParameterName = "PM1", Value = 10 });

pmset.Add(new ParameterSet() { ParameterName = "PM2", Value = 50 });

pmset.Add(new ParameterSet() { ParameterName = "PM3", Value = 70 });

pmset.Add(new ParameterSet() { ParameterName = "PM4", Value = 80 });

pmset.Add(new ParameterSet() { ParameterName = "PM5", Value = 100 });

dataGrid1.ItemsSource = pmset;
}
}

public class ParameterSet
{

public string ParameterName { get; set; }

public int Value { get; set; }

}


Thanks So much,



Anu





build multiple shared libraries

Hi I have a java program which has to invoke a native program, and this native program are given by two so files. So I create my so file in order to use this native program APIs to do something for my java program. I was trying to merge two so files with my created so file into single one, and run my java program. However, it seems that it failed this way. To be more concrete, here is my example.



I have a java program A which has to invoke some native code. Therefore I've written some native code and built it as a shared library (called: C.so).



Unfortunately, the native code I've written have to use other code which is in other so files. (A.so, B.so)



Thus, any ideas how to compile my so file with A.so and B.so in order to make my java program work?





TortoiseGit won't let me access my /trunk D:

I have no problem cloning/commiting from my ssh link, but if I ask tortoiseGit to do it on shhLink/trunk i'll get a 128 error.



"fatal: The remote end hung up unexpectedly"



Any idea why?
Thanks.





What is the use of Perform Selector in objective C/Iphone development

What is the use of perform selector in objective C? and can you please tell me the difference between perform selector and responds selector?





How should I access SQL Server from a WCF service solution?

I have some existing WCF code that accesses SQL Server 2005, but honestly I've come to mistrust that developer's methods, so I want to know how this should be done correctly and professionally. I need to be able to pass an SQL statement to a method that returns the resultant dataset. I'm not interested in entity frameworks or other abstraction layers. I need to run SQL, DML, and hopefully DDL too.



I also want to know how to re-use the same connection for the lifespan of the service rather than open and close a connection for each call.



Please point out your thoughts on better alternatives if you feel like it. I'm prepared to listen.





NSLocalizedString only retrieves the key, not the value in Localizable.strings (IOS)

I've made a strings file named "Localizable.strings" and added two languages to it, like so:



"CONNECTIONERROR" = "Check that you have a working internet connection.";
"CONNECTIONERRORTITLE" = "Network error";


I have also converted the files to Unicode UTF-8
However, when I create a UIAlertView like this:



 UIAlertView *myAlert = [[UIAlertView alloc]
initWithTitle:NSLocalizedString(@"CONNECTIONERRORITLE",nil)
message:NSLocalizedString(@"CONNECTIONERROR",nil)
delegate:self
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];


the alert view only shows the key text, not the value. It works if I, for example, set a UITextviews text to NSLocalizedString(@"CONNECTIONERROR",nil), but the alert view only displays the key. Anyone know what's wrong?





display all dates given start and end date

My following code fetches 2 dates



foreach records $get_times {
lassign $records start_date stop_date
puts [clock format [clock scan $start_date] \
-format {%d %b}]
puts [clock format [clock scan $stop_date] \
-format {%d %b}]
}


Is there a way I can display all the dates between the start_tdate and stop_date.
Something like:



puts "<tr><td>the $start_date</td>the next Date</td><td>....</td><td>the $stop_date</td>"




CakePHP SMTP Connection timed out

I know there is a load of questions about this topic, but still can't figure out what is going wrong.



Here's my code:



                $this->Email->to = 'any@mailadress.com';
$this->Email->subject = 'any subject';
$this->Email->replyTo = 'noreply@mailadress.com';
$this->Email->from = 'Somebody <noreply@mailadress.com>';
$this->Email->additionalParams = '-fnoreply@mailadress.com';
$this->Email->template = 'my_template';
$this->Email->sendAs = 'text';
$this->Email->smtpOptions = array(
'port'=>'465',
'timeout'=>'30',
'host' => 'ssl://smtp.googlemail.com', // also tried smtp.gmail.com
'username'=>'username',
'password'=>'pass',
);
$this->Email->send();


Now this leads to nothing but "Connection timed out: 110". I tried several other mailing services. Always get the connection error.



Help very much appreciated.





How can I call a class with variables from array php?

I would like something like this but dynamically from an array like this:



$array = array("first","second","third");


So class would be called like this:



$class = new class("first","second","third");




How to watch for a print screen system call?

A process is taking pictures of the screen. (screenshots, print screen)



How can I watch for a windows print screen api call so I know when a screenshot was taken?



I don't care from what process the screenshot was taken.



Do I have to necessary attach a debugger to the process taking screenshots?
Assume I can't attach a debugger.



I would like to do it in C#.
Something like....



while(true){
if(lastWinAPICall == PrintScreenCall){
// screenshot taken
}
Sleep(100);
}


Sorry, I don't know a lot about low-level stuff.



Thanks





change the defaults from outside of plugin

My plugin is :



$.fn.iPopup = function() {
var opts = new function() {
this.width = 957;
this.height = 590;
this.left = ($(document).width() / 2) - (this.width/2) - (17/2);
this.top = 160;
}
alert (opts.width);
}


I want change the width or height when I call plugin , like:



$('div#tP').iPopup({width:280});


what should I do in my plugin?





DatePicker bound to a DateTime. "String was not recognized as a valid DateTime"

(Disclaimer: This exception has been reported in numerous other threads, and yes, I have Googled around, trying to find a solution to my issue !!)



I have a WPF application, with a WPF Toolkit DatePicker control bound to a DateTime variable:



<UserControl x:Class="MikesApp.View.UserControls.FXRatesUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:toolkit="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit">

<toolkit:DatePicker x:Name="fxDate" VerticalAlignment="Center"
Text="{Binding Selected_FXRate_Date, Mode=TwoWay}"
Style="{DynamicResource DatePickerStyle1}" >
</toolkit:DatePicker>


Whenever I enter a date, such as 4/20/2012, the DatePicker control seems to think it's actually in UK date format (dd/MM/yyyy), and the WPFtoolkit source code throws an exception of "String was not recognised as a valid DateTime."



This abruptly stops any chance of WPF performing change notifications to other parts of the app, which need to know when this date changes.



Screenshot of VS2010 exception



I'm baffled.



My laptop is setup to display dates in the form MM/dd/yyyy, and I've specifically tried telling my app to use this US date format, first using this code:



Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");

Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = "MMM-dd-yyyy";
Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongDatePattern = "MMM-dd-yyyy hh:mm:ss";


Then, out of desperation, using this code:



CultureInfo ci = new CultureInfo("en-US");
ci.DateTimeFormat.SetAllDateTimePatterns(new string[] { "MM/dd/yyyy" }, 'd' );
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;


But regardless of what I try, the DatePicker throws an exception whenever I choose a date which can't be parsed using dd/MMM/yyyy.



If I look at the line of code (taken from DatePicker.cs in the WPF Toolkit SDK) which throws the exception:



newSelectedDate = DateTime.Parse(text, DateTimeHelper.GetDateFormat(DateTimeHelper.GetCulture(this)));


..I've found that "DateTimeHelper.GetCulture(this)" does correctly return "en-US", but that the GetDateFormat function is getting the WRONG date format. It's somehow returning dd/MMM/yyyy, rather than MMM/dd/yyyy.



GetDateFormat's return values



I'm really confused.



I've even tried cut'n'pasting the GetDateFormat function (taken from the following path in the WPFtoolkit source code) into my app, and tried to get it to reproduce the "wrong date format" problem... but when it's in my code, it runs fine, and parses MMM/dd/yyyy dates correctly every time.



WPFtoolkit\Calendar\Microsoft\Windows\Controls\DateTimeHelper.cs



Why would the WPFtoolkit code have a different Culture to my WPF application's code, which uses it ?



And how can I get the WPFtoolkit to use the correct Culture ?





exclude nodes from xpath query

Here's some code I am currently using. Where I need help are $bn_name_search and $bn_id_search



$xpath_base='/ItemSearchResponse/Items/Item[';
for ($i = 1; $i<=10; $i++)
{
$curr_item_base=$xpath_base.$i.']';
$bn_name_search=$curr_item_base.'/BrowseNodes//BrowseNode/Name/text()';
$bn_id_search=$curr_item_base.'/BrowseNodes//BrowseNode/BrowseNodeId/text()';
$bn_names=$parsed->xpath($bn_name_search);
$bn_ids=$parsed->xpath($bn_id_search);
}


This gives me all the browsnode names and all the broswnode ids. What I'd like to do now is find only the browsenode names "BrowseNode/Name/" that are not "All Products" and only browsnode ids "BrowseNode/BrowseNodeId/" share a "BrowseNode/" with a name that is not "All Departments" I don't have to test for the existance of BrowseNode/Name. It won't be blank if there is an ID. If I can put two negative expressions it would be even better. I would omit those whose names are "All Products" and those whose names are "Departments"



I did not post my XML because it is huge, but if you need to see it, let me know an I'll edit the question.





Follow path algorithm

Could you give me a link for beginner tutorial on fast follow path algorithm ?



Path should include curves.



Entities should follow this path within a given distance.



Entities in my world are represented as rectangles. Each time they update they get time delta argument.



Thanks





Problems installing an Open Source Soft: what am I doing wrong? :S

I had this trouble: I need to install a soft that could be found on source forge called tend ersystem ; I want to do a place where a bunch of NGO's could request prices to some companies, and the companies send their prices, and the lowest bid wins (during crisis, NGO's needs this kind of thing!) The trouble is... that i can't manage to install it! :@ (while in the past, I could) Also, I tried to do it with a wamp serer, but no luck either... could anywone helping me installing this (sending me a sql dump + modified config files dump of a working version) or recommending me which other open source soft could help me do this mechanism: someone request a service, and other one offers their price (dunno if an ebay clone might do it, but I do prefer this open source, since is just perfect!) Thanks in advance guys, you rock!





Removing jquery click event handler from child elements of a table row

I have a table with a checkbox on the first column. When I click anywhere on the row, a class 'row_selected' is set on the table row and the checkbox is checked. The code is as follows:



$('#my_table > tbody > tr > td').live('click', function() {
if ($(this).parent().hasClass('row_selected')) {
$(this).parent().removeClass('row_selected')
$('td.checkbox input', this.parentNode).prop("checked", false)
} else {
$(this).parent().addClass('row_selected')
$('td.checkbox input', this.parentNode).prop("checked", true)
}
})


The problem is some of the table cells have buttons which if clicked, I do not want the row to become selected. i.e.



<tr>
<td class="checkbox">
<input type="checkbox" checked="false"/>
</td>
<td>blah<td>
<td>
<a class="myButton">do stuff</a>
</td>
<td>blah<td>
</tr>


I want the jquery click event to work except when I click on myButton.



Anybody got any ideas?





Open all links within a div in a lightbox

I'm trying to figure out how to open all of the images within a div in a lightbox. The div is pulling images from a picasa album, so I can't edit each link individually.



What would also work for me is the ability to open all links of a certain filetype in a lightbox.



Thanks!





For a Rails View *.html.erb : where can I place the style sheet?

I have this file:



app/views/listings/list.html.erb


in my rails project.
Here are the contents of the file:



<h1>This file is:"list.html.erb"</h1>  












html { height: 100% }

body { height: 100%; margin: 0; padding: 0 }

#map_canvas { height: 100% }




src="http://maps.googleapis.com/maps/api/js?key=key&sensor=false">



<%=javascript_include_tag 'application'%>  
















Id like to apply a style sheet to it. Where should I place the stylesheet? I tried placing the code in this file:



app/assets/stylesheets/listings.css.scss


But the style wasn't applied to the html file. Also do I need to change anything in my html view file to include the style sheet?



This is the style sheet that resides at : "app/assets/stylesheets/listings.css.scss"



// Place all the styles related to the Listings controller here.  
// They will automatically be included in application.css.
// You can use Sass (SCSS) here: http://sass-lang.com/
.listings
{
table tr td
{
padding: 5px;
vertical-align: top;
}


dt
{
color: #232;
font-weight: bold;
font-size: larger;
}

dd
{
margin: 0;
}
}
#map_canvas
{
width: 80%;
height: 80%;
}


So wondering if anyone can give me a hand?



Thanks





How can I put white space at the bottom of my website, so the floating div never overlaps

I found a lot of questions on stack overflow about getting rid of white space, but I can't seem to figure out how to put it in.



I have a bottom navigation on my site that floats with the page, but if the window is small, the bottom part of the page gets covered up. I would like to insert some white space at the bottom, so when the window is smaller than the length of the page you can still read it.



I've tried adding:



margin-bottom: 50px;
padding-bottom: 50px;


to the div containing the top page content, but it doesn't work.



Is there something I am missing? Here's a demonstration: http://www.writingprompts.net/name-generator/





Ruby on Rails to Visual studio

I have a software written in Ruby on Rails. Is it possible to migrate/convert the data/codes into Visual basic or C#?





Python regular expressions matching within set

While testing on http://gskinner.com/RegExr/ (online regex tester), the regex [jpg|bmp] returns results when either jpg or bmp exist, however, when I run this regex in python, it only return j or b. How do I make the regex take the whole word "jpg" or "bmp" inside the set ? This may have been asked before however I was not sure how to structure question to find the answer. Thanks !!!



Here is the whole regex if it helps



"http://www\S*(?i)\\.(jpg|bmp|png|gif|img|jng|jpeg|jpe|gif|giff)"


Its just basically to look for pictures in a url





HAML - how to create links so that they go to the right controllers?

I have some links that I am trying to make work in HAML



  =link_to("My Disclosures", "") << ' |'
=link_to("Create Disclosure", "#") << ' |'
=link_to("My Programs", "#") << ' |'
=link_to("Log Out", "sign_out")


What I am not sure how to do is link to different controller actions that I have.



Here are my routes:



scope :module => :mobile, :as => :mobile do
constraints(:subdomain => /m/) do
devise_for :users, :path => "", :path_names =>
{ :sign_in => "login", :sign_out => "logout",
:sign_up => "signup" },
:controllers => {:sessions => "mobile/sessions"}

resources :home

resources :disclosures # Will have new, get, look up a disclosure
end
end


So I thought my log_out path would have worked, but it isn't working it seems.



Also, I have this very simple controller:



class Mobile::DisclosuresController < ApplicationController

def new
Rails.logger.debug "-"*100
Rails.logger.debug session.inspect
Rails.logger.debug "-"*100

respond_to do |format|

end
end

def create

end

def destroy

end
end


But I am not sure how to make the HAML links so that they lead to the various controller actions I need to go to on get and post. Any help with how to correctly link to the controllers would be much appreciated!



Thanks!





How to update password encrypted using MD5 and stored into sql server 2005 database

I have created a user account table. There are two fields in it Login which stores user id and Password which stores password in encrypted format. The password is encrypted at the time of registration using MD5 hashing. If the user wants to change his password, how will he change it into the database. I tried to update the password using simple update statement, but it didnt work.



My code is:



//Code

public int Changep(string strLogin, string strPassword, string newpass)
{
//Create a connection
string cs = "data source=DELL-PC;initial catalog=project;user id=sa;password=pass";
SqlConnection objConn = new SqlConnection(cs);


// Create a command object for the query
string strSQL = "UPDATE tblLogins SET Password= @Password WHERE Login=@Username AND Password = @Password2";

SqlCommand objCmd = new SqlCommand(strSQL, objConn);

//Create parameters
SqlParameter paramUsername;
paramUsername = new SqlParameter("@Username", SqlDbType.VarChar, 25);
paramUsername.Value = strLogin;
objCmd.Parameters.Add(paramUsername);

//Encrypt the password
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
byte[] hashedBytes;
UTF8Encoding encoder = new UTF8Encoding();
hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(strPassword));
SqlParameter paramPwd;
paramPwd = new SqlParameter("@Password", SqlDbType.Binary, 16);
paramPwd.Value = hashedBytes;
objCmd.Parameters.Add(paramPwd);

//Encrypt the old password
MD5CryptoServiceProvider md5Hasher2 = new MD5CryptoServiceProvider();
byte[] hashedBytes2;
UTF8Encoding encoder2 = new UTF8Encoding();
hashedBytes2 = md5Hasher2.ComputeHash(encoder2.GetBytes(strPassword));
SqlParameter paramPwd2;
paramPwd2 = new SqlParameter("@Password2", SqlDbType.Binary, 16);
paramPwd2.Value = hashedBytes;
objCmd.Parameters.Add(paramPwd2);
int iResults;
//Insert the record into the database
try
{
objConn.Open();
//We use execute scalar, since we only need one cell
iResults = Convert.ToInt32(objCmd.ExecuteScalar().ToString());
if(iResults==1)
return PassUpdated;
else
return Updatefailed;
}
catch
{
return Updatefailed;
}
finally
{
objConn.Close();
}
}
}




Calculate business hours between two dates

How can I calculate business hours between two dates?
For example we have two dates; 01/01/2010 15:00 and 04/01/2010 12:00
And we have working hours 09:00 to 17:00 in weekdays
How can I calculate working hours with sql?





how to load the Jquery response(HTML page with script tags) into the DOM

$.get('/web/guest/reports',function(data){
alert(data);
$('div #returnData').html(data);
});


Here i am making a request to the reports page through jquery get and in the callback function the jquery get response date ie the variable 'data' is html page with script tags in it. When i alert that i am able to see the whole html page response. After inserting the data into DOM ie div with id returnData ...The scripts are not available in the DOM..



Actually i have the requirement that i have to load the page and then run the script functions that are there in that page. But those script functions are getting added to the DOM..



please post the code snippet for solving the issue and requirement..





Oauth for Connect-auth for www.500px.com

I'm trying to extend connect-auth (https://github.com/ciaranj/connect-auth) to connect to http://www.500px.com oauth, but am having issues and can't find a way to debug other than console.log.




  1. I added a strategy five00px.js ( can't name a variable 500px ) as per below, which is a copy of twitter.js strategy with some string substitution.


  2. I keep getting Invalid OAuth Request



    Error retrieving the OAuth Request Token: {"statusCode":401,"data":"Invalid OAuth Request"}


  3. I can't really see the OAUTH request as it's in HTTP.




Any idea ?



    /*!
* Copyright(c) 2010 Ciaran Jessup <ciaranj@gmail.com>
* MIT Licensed
*/
var OAuth= require("oauth").OAuth,
url = require("url"),
http = require('http');

module.exports= function(options, server) {
options= options || {}
var that= {};
var my= {};

// Construct the internal OAuth client
my._oAuth= new OAuth("https://api.500px.com/v1/oauth/request_token",
"https://api.500px.com/v1/oauth/access_token",
options.consumerKey, options.consumerSecret,
"1.0A", options.callback || null, "HMAC-SHA1");
console.log('1');
// Give the strategy a name
that.name = "five00px";

// Build the authentication routes required
that.setupRoutes= function(app) {console.log('2setupRoutes');
app.use('/auth/five00px_callback', function(req, res){console.log('3five00px_callback');
req.authenticate([that.name], function(error, authenticated) {console.log('4authenticate');
res.writeHead(303, { 'Location': req.session.five00px_redirect_url });
res.end('');
});
});
}

// Declare the method that actually does the authentication
that.authenticate= function(request, response, callback) {console.log('5authenticate');
//todo: if multiple connect middlewares were doing this, it would be more efficient to do it in the stack??
var parsedUrl= url.parse(request.originalUrl, true);
this.trace('parsedUrl=' + request.originalUrl);

//todo: makw the call timeout ....
var self= this;
if( request.getAuthDetails()['500px_login_attempt_failed'] === true ) {
// Because we bounce through authentication calls across multiple requests
// we use this to keep track of the fact we *Really* have failed to authenticate
// so that we don't keep re-trying to authenticate forever.
delete request.getAuthDetails()['500px_login_attempt_failed'];
self.fail( callback );
}
else {
if( parsedUrl.query && parsedUrl.query.denied ) {
self.trace( 'User denied OAuth Access' );
request.getAuthDetails()['500px_login_attempt_failed'] = true;
this.fail(callback);
}
else if( parsedUrl.query && parsedUrl.query.oauth_token && request.session.auth["500px_oauth_token_secret"] ) {
self.trace( 'Phase 2/2 : Requesting an OAuth access token.' );
my._oAuth.getOAuthAccessToken(parsedUrl.query.oauth_token, request.session.auth["500px_oauth_token_secret"],
function( error, oauth_token, oauth_token_secret, additionalParameters ) {
if( error ) {
self.trace( 'Error retrieving the OAuth Access Token: ' + error );
request.getAuthDetails()['500px_login_attempt_failed'] = true;
this.fail(callback);
}
else {
self.trace( 'Successfully retrieved the OAuth Access Token' );
request.session.auth["500px_oauth_token_secret"]= oauth_token_secret;
request.session.auth["500px_oauth_token"]= oauth_token;
var user= { user_id: additionalParameters.user_id,
username: additionalParameters.screen_name }
self.executionResult.user= user;
self.success(user, callback)
}
});
}
else {


my._oAuth.getOAuthRequestToken(function(error, oauth_token, oauth_token_secret, oauth_authorize_url, additionalParameters ) {
if(error) {
self.trace( 'Error retrieving the OAuth Request Token: ' + JSON.stringify(error) );
callback(null); // Ignore the error upstream, treat as validation failure.
} else {
self.trace( 'Successfully retrieved the OAuth Request Token' );
request.session['500px_redirect_url']= request.originalUrl;
request.session.auth["500px_oauth_token_secret"]= oauth_token_secret;
request.session.auth["500px_oauth_token"]= oauth_token;
self.redirect(response, "https://api.500px.com/oauth/authenticate?oauth_token=" + oauth_token, callback);
}
});
}
}
}
return that;
};