Thursday, 3 October 2013

How to send a Facebook App request/ invite? (MVC4)

How to send a Facebook App request/ invite? (MVC4)

At the moment I am creating a MVC4 web application and use the Facebook API.
I implemented this method to send a app request, but I get this error
"(GraphMethodException - #100) Unsupported post request.". How to solve
this problem?
public void SendAppRequest(string facebookUserId, string message)
{
FacebookClient fbClient = new FacebookClient();
fbClient.AccessToken = getAccessToken();
dynamic nparams = new ExpandoObject();
nparams.message = message;
nparams.title = "To receive notify messages of the Project Web
application, accept this request.";
var response = fbClient.Post(facebookUserId + "/apprequests",
nparams);
}

Wednesday, 2 October 2013

How do you overload MVC Controllers to avoid repeating common code?

How do you overload MVC Controllers to avoid repeating common code?

I'm working on a new MVC 5 project. It's a single multi tenanted site that
allows many organisations and branches to maintain a page. All pages start
with the following url format:
http://mysite.com/{organisation}/{branch}/...
For example:
http://mysite.com/contours/albany/...
http://mysite.com/contours/birkenhead/...
http://mysite.com/lifestyle/auckland/...
I've declared my RouteConfig with the {organisation} and {branch} before
the {controller} and {action}:
routes.MapRoute(
name: "Default",
url: "{organisation}/{branch}/{controller}/{action}/{id}",
defaults: new { controller = "TimeTable",
action = "Index",
id = UrlParameter.Optional });
This is working just fine. However EVERY single controller now has
identical code in the top of it that examines the organisation and branch.
public ActionResult Index(string organisation, string branch, string name,
int id)
{
// ensure the organisation and branch are valid
var branchInst = _branchRepository.GetBranchByUrlPath(organisation,
branch);
if (branchInst == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
// start the real code here...
}
I'm keen on the DRY principle (Don't Repeat Yourself) and I'm wondering if
it's possible to somehow isolate that common code and change my controller
signatures to something like this:
public ActionResult Index(Branch branch, string name, int id)
{
// start the real code here...
}

I am getting .asmx file not found exception

I am getting .asmx file not found exception

Apparently there is some iis configuration issue. I am getting the the error
System.ServiceModel.EndpointNotFoundException : There was no endpoint
listening at http.....asmx that could accept the message. This is often
caused by an incorrect address or SOAP action. See InnerException, if
present, for more details. ---- System.Net.WebException : The remote
server returned an error: (404) Not Found.
What should I do? I don't know anything about iis. I am just testing some
application

Insert table column value in the Php Session

Insert table column value in the Php Session

Hello, in my mysql database I have table called users which has primary
key column called userID which is Auto Increment column. I would like to
get inside the session array the value of this column for the logged in
user, here is how the array looks like right now:
array(4) { ["loggedIn"]=> bool(true) ["username"]=> string(9) "user"
["password"]=> string(3) "123" ["userID"]=> NULL }
This is the code of my login form:
session_start();
$usr = new Users;
$usr->storeFormValues( $_POST );
if( $usr->userLogin() ) {
header( 'Location: cursos.php' ) ;
$_SESSION["loggedIn"] = true;
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
$_SESSION['userID'] = $_POST['userID'];
and this is my login function:
public function userLogin() {
$success = false;
try{
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM users WHERE username = :username AND password =
:password LIMIT 1";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password .
$this->salt), PDO::PARAM_STR );
$stmt->execute();
$valid = $stmt->fetchColumn();
if( $valid ) {
$success = true;
}
$con = null;
return $success;
How this can be acheived ? If anyone can help I would appreciate it. Thank
you.

Facebook login php api save cookie?

Facebook login php api save cookie?

Im currently using this facebook login php api
https://github.com/facebook/facebook-php-sdk
It works fine however when the session ends it doesn't remember the cookie
and they have to login again everytime. I got it to save the cookie using
the JS method but I really dont prefer that. How can I have it remember
the user?

Tuesday, 1 October 2013

Why does this error, ERROR: relation "[name of function/Views/Trigger Functions]" does not exist, come up in pgAdmin III?

Why does this error, ERROR: relation "[name of function/Views/Trigger
Functions]" does not exist, come up in pgAdmin III?

I'm just new to pgAdmin so I don't really know what causes these error:
ERROR: relation "ongoingprojects" does not exist
LINE 1: SELECT * FROM ongoingProjects;
^
*** Error ***
ERROR: relation "ongoingprojects" does not exist
SQL state: 42P01
Character: 15
Even if the Function/View exist in the schema. Why does it give that
error? And what shall I do to fix it? Thanks!

Within an OSX package, how can I cleanup if an error occurs?

Within an OSX package, how can I cleanup if an error occurs?

I've built application that's distributed as a flat package on OSX. It
contains both preinstall and postinstall scripts, as well as a couple of
plugins that provide custom UI. And everything seems to work just
fine....except when it doesn't. :-)
If an error occurs for any reason during install (disk space, permission
issues, etc.), there doesn't seem to be a mechanism to allow my package to
react. In those cases, I'd really like to launch a script to clean up
temporary files and remove the partially installed app altogether.
Does anyone know of a way to accomplish this? Or am I asking too much from
a package based install?
Thanks in advance!

Putting \hat over first character of subscripted variable – tex.stackexchange.com

Putting \hat over first character of subscripted variable –
tex.stackexchange.com

I'm using a set of commands to define abstractions of mathematical
notations that often occur during my thesis such as:
\newcommand{\DNoise}{n_d} which would equal some distortion noise. This
allows …

Cool mathematics I can show to calculus students. – math.stackexchange.com

Cool mathematics I can show to calculus students. – math.stackexchange.com

I am a TA for theoretical linear algebra and calculus course this
semester. This is an advanced course for strong freshmen. Every discussion
section I am trying to show my students (give them as a …

Monday, 30 September 2013

How to limit negative voltage on uC input pin – electronics.stackexchange.com

How to limit negative voltage on uC input pin – electronics.stackexchange.com

I'm trying to design a pulse induction metal detector to increase my EE
skills a little bit. I started to sketch out the transmitting stage, which
is just a MOSFET that switches current through a …

What does this ${@:2} mean in shell scripting – unix.stackexchange.com

What does this ${@:2} mean in shell scripting – unix.stackexchange.com

I see this in a shell script. variable=${@:2} What is it doing?

DataTable Webmethod only works with thread.sleep

DataTable Webmethod only works with thread.sleep

I'm trying to serialize a DataTable return to use on a WebMethod its just
simple like that:
DataTable dtResult = Occurrences.Search(....);
The thing is, if I, immediatly type
return dtResult.Rows.Count.ToString();
It will return "0".
But if i add just after the first line:
System.Threading.Thread.Sleep(2000);
Everything works fine and the row count is 2.
Since when DataTable fetching is asynchronous?

collect acceleration data for 10 seconds using AsyncTask

collect acceleration data for 10 seconds using AsyncTask

I have searched for a clear answer for this but I have not found one. The
Android application will start the AsyncTask to collect accelerometer data
once a button is pressed. I want the AsyncTask to stop after 10 seconds.
Basically trying to save a 10 second chunk of acceleration data to be
process by another part of my application. Is there a way to control the
time the AsyncTask runs for?
Thank you.

Sunday, 29 September 2013

How to read '\0' from a text file?

How to read '\0' from a text file?

My text file contain '\0' characters. Thus, It is making problem. And i
need find out those files which contains '\0' character. Readlines() and
read() did not work as it marks them as terminating lines.

How to get file extension in Java?

How to get file extension in Java?

I want to get all files with a specific extension. The following code is
working fine.
String extension = "";
int i = fileName.lastIndexOf('.');
if (i > 0) {
extension = fileName.substring(i+1);
}
But, could there be any better way to do?

Javascript code for identicon

Javascript code for identicon

I have tried to find a good javascript idencicon generator but found none.
Can anyone give me a link/ code of a good javascript identicon generator?

Fetch a page with cookies using Python requests library

Fetch a page with cookies using Python requests library

I'm just studying the requests
library(http://docs.python-requests.org/en/latest/), and got a problem on
how to fetch a page with cookies using requests.
for example:
url2= 'https://passport.baidu.com'
parsedCookies={'PTOKEN': '412f...', 'BDUSS': 'hnN2...', ...} #Sorry that
the cookies value is replaced by ... for instance of privacy
req = requests.get(url2, cookies=parsedCookies)
text=req.text.encode('utf-8','ignore')
f=open('before.html','w')
f.write(text)
f.close()
req.close()
when I use the codes above to fetch the page, it redirects to the login
page, also I see the login page in 'before.html', it refers that actually
I haven't logged in successfully.
But if I use URLlib2 to fetch the page, it works properly as expected.
parsedCookies="PTOKEN=412f...;BDUSS=hnN2...;..." #Different format but
same content with the aboved cookies
req = urllib2.Request(url2)
req.add_header('Cookie', parsedCookies)
ret = urllib2.urlopen(req)
f=open('before_urllib2.html','w')
f.write(ret.read())
f.close()
ret.close()
When I use these codes, it saves the login page in before_urllib2.html.
--
Are there any mistakes in my code?

Saturday, 28 September 2013

Is there a way to frame a specific page element?

Is there a way to frame a specific page element?

So, I'm working on a web page, and I want to be able to let users give
feedback using google moderator. In order to help the user experience, I
want there to still be the logo and navigator bar across the top of the
page. The way I have it set up now is with frames. I have one frame on top
containing the logo and navigator bar, and the bottom frame being the
google moderator page. This is effective, but I would prefer it if there
wasn't that pesky grey navigation bar (the one with the links to search,
use youtube, etc.). I was poking around with the source-code and found
that if one where to go to
http://www.google.com/moderator/#16/e=1fe6a2/html/body/div[1]
you would have exclusively the navigation bar. Is there a way to link to
just the body? If not, is there a way to make a frame that excludes a
specific page element? If none of those would work, is there a way to crop
the top off? Any of the above options would be preferable over the current
layout. Any help is much appreciated. Thanks!

save value of variable in function till the next time function calls

save value of variable in function till the next time function calls

I need some function or solution to save the value of variable in function
until the next call of function without connecting to MySQL.
function test($price){
if(isset($lastPrice)){
if($lastPrice>$price){
return true;
}
$lastPrice = $price;
}else{
$lastPrice = $price;
returne false;
}
}
$prices= array ( '1' => '2000',
'2' => '2100',
'3' => '2100'
);
foreach($prices as $key = > $price){
if($this->test($price)){
echo 'got expensive';
}
}
In this code i need $lastPrice to be save till the next time that test()
get call in foreach,...

Multiplayer Flash Game with Java Server problems

Multiplayer Flash Game with Java Server problems

Alright, basically I've been trying to find out how to set up a
multiplayer flash game, recently I have concluded to code my own server
using Java. I have finally managed to do so after hours of trying and I
have bumped into a snag. Here is my server & client code.
**Server**
import java.net.*;
import java.io.*;
public class ServerFlash
{
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
Socket connection = new Socket();
InputStream in = null;
boolean listening = true;
try
{
serverSocket = new ServerSocket(14804);
System.err.println("The server is now bound to port.");
}
catch (IOException e)
{
System.err.println("Could not bind server to port.");
System.exit(-1);
}
while (listening)
{
connection = serverSocket.accept();
if(connection!=null)
{
System.err.println("Connection to client has been
established.");
in = connection.getInputStream();
listening = false;
}
}
while (!listening)
{
int data = in.read();
if(data!=-1)
{
System.err.println(data);
}
}
}
}
**Client**
var server = new Socket();
server.connect("[insertmyip]",14804);
server.addEventListener(Event.CONNECT, onConnect);
server.addEventListener(Event.CLOSE, onClose);
server.addEventListener(IOErrorEvent.IO_ERROR, onError);
server.addEventListener(ProgressEvent.SOCKET_DATA, onResponse);
server.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecError);
function onConnect(e:Event)
{
trace("Connection Established.");
}
function onClose(e:Event)
{
trace("Socket has been Close.");
}
function onError(e:Event)
{
trace("An Error has occured." + e);
}
function onResponse(e:Event)
{
trace("Responce has been recieved.");
}
function onSecError(e:Event)
{
trace("A SecError has occured.");
}
When I launch the server everything is okay. However when I launch the
client, it successfully connects to the server, but all of a sudden the
server receives data from the client (if you read the code the server
reads incoming data and displays it) and displays around 15 lines of code
and it does not accept any new data from the client. HOWEVER this only
happens when the client is launched from a website (or a folder) BUT it
works normally when I open the client as a test in Adobe Flash Pro.
If you require files and hand them over.