emclondon 38 Junior Poster in Training

I have searched online and I have found the best way to deal with this is by using XMLSerializers. So, I grabbed my XMLs and created respective XSDs and generated classes from the XSD and mapped the xml with generated XML.

The only problem now is I have to loop again and again for certain elements which is tiresome process.

emclondon 38 Junior Poster in Training

I have changed the fetching code to the following so that I can have greater flexibility over the content I get.

   private HttpWebResponse theresponse;

   public Boolean getmyxml(Uri sourceforxml)
    {
        WebRequest webrequest = WebRequest.Create(sourceforxml);
        HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
        if (webresponse.StatusDescription == "OK")
        {
            theresponse = webresponse;
            return true;
        }
        else
        {
            return false;
        }
    }

isn't there any other way to manipulate the data except for loadxml?

I'm thinking of using a serializer on the data now.

emclondon 38 Junior Poster in Training

no one?

emclondon 38 Junior Poster in Training

Alright please bear with me for few posts, I am trying to design a scoreboard application using HTML. The data for scoreboard (including headings and rows and columns) are stored on a server at a remote location. I am trying to develop an ASP.NET script to fetch that XML and convert it into JSON so that I could pick up via jQuery or something else at browser level.

here comes the tough part: I have little experience in C#.NET and have no experience in ASP.NET, I use my scrapings of PHP knowledge and try to find equivalent in ASP.NET.

The first thing I've thought of was to use cURL like alternative to fetch the xml from servers and that didn't go well as there is no cURL equivalent in .NET except to use cURL which I don't want to. I have looked online and found many REST clients examples and have used it in my application which is all good and dandy so far, but the result I'm expecting is not what it's displaying.

This is my code so far

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string scoreboardurl = @"http://www.w3schools.com/xml/cd_catalog.xml";
        Response.Write(HttpGet(scoreboardurl));
    }


    static string HttpGet(string url)
    {
        /** http://stackoverflow.com/a/1605921 **/

        HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
        req.Method = "GET";
        string result = string.Empty;
        using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
        {
            using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
            {
                result = reader.ReadToEnd();
            }       
        }
        return result;
    }
} …
emclondon 38 Junior Poster in Training

try this?

class A
{
    public void methodA()
    {
        Console.Write("This text is by methodA in Class A");
    }
}

class B
{
    public void methodB()
    {
        A Aobj = new A();
        Aobj.methodA();
    }
}
emclondon 38 Junior Poster in Training

Hi!

I forgot to mention, I don't want to use any plugins of any sort!.

I've made some changes to the code above and this is where I am stuck

<html>
    <head>
    <style type="text/css">
        #buttonsdiv{
        position: relative;
        left: 30%;
        top: 10%;
        }
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js ></script>
    <script type="text/javascript">
        $(document).ready({ 
            $("form").submit(function(form){
                    var result = null;
                    var data = null;
                    data = new FormData(); //create post data
                    data.append('file', document.getElementById("fileupload").value);
                    //make the call
                    jQuery.ajax({
                        url: "./upload.php",
                        type: "POST",
                        data: data,
                        contentType: 'multipart/form-data',
                        processData: false,
                        cache: false,
                        success: function(response){ alert(response); }
                    });
                });
        });

        function dismissUploader(){
            document.getElementById("file").value = "";
        }

        function processUpload(form){
            var result = null;
            var data = null;
            data = new FormData(); //create post data
            data.append('file', document.getElementById("fileupload").value);
            //make the call
            jQuery.ajax({
                url: "./upload.php",
                type: "POST",
                data: data,
                contentType: 'multipart/form-data',
                processData: false,
                cache: false,
                success: function(response){ alert(response); }
            });
        }
    </script>
</head>
<body>
    <form id="form" action="upload.php" method="POST" enctype="multipart/form-data" >  
        <label for="file" class="filelabel">Select an Image</label><BR />
        <input type="file" name="file" id="fileupload" class="fileupload" size="30"><BR />
        <div id="buttonsdiv">
            <input type="button" name="upload" class="uploadbutton" id="uploadbutton" value="Upload" onclick="javascript:processUpload(form);" />
            <input type="button" name="close" class="cancelbutton" id="cancelbutton" value="Cancel" onclick="javascript:dismissUploader();" />
        </div>
    </form>
 </body>
</html>

and my php is really simple

<?php 
    var_dump($_FILES['file']);
?>

This gives me an Undefined index error.

emclondon 38 Junior Poster in Training

I'm trying to upload an Image to PHP. The most common method I found out to do this was using FORM/POST; But that doesn't help me for what I am about to do.

What I actually am trying to do is upload an image to PHP, the PHP Script will perform its processing and returns a path to the processed image or the image itself. I need to handle sending and returned data. I have tried going through numerous image upload scripts and tutorials, which are good for nothin; except for telling me how image processing works.

The following is my code for HTML, Can anyone help me to write the image sending and retrieving in jQuery?

<html>
    <head>
        <style type="text/css">
            #buttonsdiv{
                position: relative;
                left: 30%;
                top: 10%;
            }
        </style>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js />
        <script type="text/javascript">
            $(document).ready({
            });

            function dismissUploader(){
                document.getElementById("file").value = "";
            }
        </script>
    </head>
    <body>
        <form action="upload.php" method="POST" enctype="multipart/form-data" >  
            <label for="file" class="filelabel">Select an Image</label><BR />
            <input type="file" name="image" id="file" class="fileupload" size="30"><BR />
            <div id="buttonsdiv">
            <input type="submit" name="upload" class="upload" id="upload" value="Upload" />
            <input type="button" name="close" class="cancel" value="Cancel" onclick="javascript:dismissUploader();" />
            </div>
        </form>
    </body>
</html>

and for the sake of argument, lets assume that the upload file is something like this

<?php
    if (isset($_POST["upload"]))
    {
        $result= "c:\usr\tmp\123.jpg";
        return $result;
    }else{
        die("error");
    }
?>

What happens now is When the user uploads the file, the file is then posted to a file called "upload.php" which returns the uploaded path of the file.

I wanted to …

emclondon 38 Junior Poster in Training

try clicking Help > About Eclipse > Installation Details

check whether if you have Android Developer Tools in the list.

emclondon 38 Junior Poster in Training

If you have skype running, close it, and start apache. That should solve your problem.

if that doesn't some other application is using port80; you will have to free it before you can use it for apache.

Alternatively, you could change the port niumber of apache to start php.

emclondon 38 Junior Poster in Training

here's something that I did earlier.

index.html

<!DOCTYPE HTML>
<HTML lang="en">
    <head>
        <title>First Demo</title>
        <META name="description" content="HTML5 JS Tutorial" />
        <META name="keywords" content="HTML5,CSS,JavaScript" />
        <META name="Author" lang="en" content="Prasanna K Yalala" />
        <style type="text/css">
                html,body {
                    border: 0;
                    height: 100%;
                    font-family: arial, helvetica, sans-serif;  
                }
                #popup{
                    display: none
                }

                #secret {
    font-size: 20px;
    font-style: italic;
    color: #f00;
}
                body{
                    font-family: Garamond;
                    background: -webkit-gradient(linear, left top, left bottom, from(#F0F0F0), to(#CCCCCC));
                    background-color: rgba(0, 0, 0, 0.6);
                    color: #999;
                    height: 100%;
                    margin: 0;
                }

                #my_div {
                    margin-top: 10%;
                    margin-left: 15%;
                    width: 425px;

                }

                #my_layout {
                    background: -webkit-gradient(linear, left top, left bottom, from(#FFFFFF), to(#DDDDDD));
                    width: 500px;
                    position:absolute;
                    top: 50%;
                    left: 50%;
                    width:28em;
                    height:10em;
                    margin-top: -5em; /*set to a negative number 1/2 of your height*/   
                    margin-left: -14em; /*set to a negative number 1/2 of your width*/
                    border: 1px solid #ccc;
                    -webkit-box-shadow: 2px 2px 2px #999;
                }

                #my_layout input{
                     border: 1px solid #ccc;
                }

                #my_layout button{
                    border: none;
                    color: #888;
                    padding: 5px;
                    font-size: 15px;
                    width: 125px;
                    height: 30px;
                    font-weight: bold;
                    font-family: Garamond;
                    border-radius: 5px;
                    -webkit-box-shadow: 1px 1px 1px #888;
                    background: -webkit-gradient(linear, left top, left bottom, from(#FFFFFF), to(#CCCCCC));
                }
                #my_layout button:hover{
                    color: #000;
                }

            </style>
        <script type="text/javascript">

            /**
            * Prasanna K Yalala
            * 
            * References
            * .tutorialspoint.com,  Stackoverflow.com,
            * html5rocks.com,  Tizag.com, w3schools.com, 
            *
            * Copyleft 2012, Nothing is Reserved.
            */

            /**
            * This function validates the data from the form and
            * sets a cookie for the next page.
            */
            function checkForm() {
                var u = document.getElementById('firstname').value
                if((u==null) || ( u==""))
                {
                    document.getElementById('secret').hidden = false;
                    setInterval(showme, 5000); …
emclondon 38 Junior Poster in Training

Hello everyone,

I'm trying to write a script which accepts URL by GET and then validates the URL before processing it.

for the sake of arguement lets say that the URL I'm expecting is in this format

http://mysite.com/myscript.php?url=http://blahblah.blahblah.bla/blahblah/blahblah/blahblah.bla

http://subdomain.domain.tld/section/category/file.ext

I need to validate the part which is a link to a XML; i.e, my URL might be like these

http://gradefive.belmontprimary.edu/grades/science/peter.xml
https://gradesix.belmontprimary.edu/grades/maths/geometry/lisa.xml
http://gradeeight.belmontprimary.edu/grades/maths/calculus/sandra.xml

I don't know wether if the XML files would be on a secure server (https) or unsecure one (non-https) at the moment, and also I don't know what the contents of the files may be. All I know for sure is that these are the XML files which I need to use for my project.

so far, I have snooped around and found this code

    function isValidURL($link)
    {
        $urlregex = '^(https?|s?ftp\:\/\/)|(mailto\:)';
        $urlregex .= "[a-z0-9+$_-]+(.[a-z0-9+$_-]+)+";
        $urlregex .= '(\?[a-z\+&\$_\.\-][a-z0-9\;\:@\/&%=\+\$_\.\-]*)?';


        if(preg_match('/'.$urlregex.'/i', $link))
        {
            return true;
        }
        else
        {
            return false;
        }
    }


        function getXMLData($url){
        if(!isValidURL($url))   {
            echo "Please enter valid URL including http://<br>";
        }
        else{

            try{
                $savedXML = file_get_contents($url);
                echo "thanks";
                return $savedXML;
            }catch(Exception $e){
                die($e.getMessage());
            }           
        }
    }

but this is not what I exactly need. can anyone please help me by solving this issue?

thanks in advance.

emclondon 38 Junior Poster in Training

either

<?php
    $feed_url = “http://www.engadget.com/rss.xml”;
    $data = file_get_contents($feed_url);
?>

get more info about that method here.
or

<?php

    function getData($feed_url) {

        $curl_handle = curl_init();

        curl_setopt ($curl_handle, CURLOPT_URL,$feed_url);
        curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl_handle);
        curl_close($curl_handle);

        return $result;
    }

    var_dump(getData("http://www.engadget.com/rss.xml"));
?>

Get more info about cURL here and here.

Further reading on which is best : http://stackoverflow.com/questions/555523/file-get-contents-vs-curl-what-has-better-performance

emclondon 38 Junior Poster in Training

write your function and call it in onsubmit. it will work just fine.

example:

<!-- standard html and head elements -->
<script type="text/javascript">
    // other functions (if any) here

    function foo(){
        if(a){
            return true;
        }
        else if(b){
            return false;
        }
        else{
            return false;
        }
    }

    // other functions (if any) here
</script>
<!-- standard head elements -->
<!-- standard body elements -->
<form name="myForm" action="#" method="POST" onsubmit="return function1(); function 2(); foo(); function 3();">
<!-- form elements -->
</form>
<!-- rest of body elements -->

I think this should solve your problems.

emclondon 38 Junior Poster in Training

here's your solution.

<!DOCTYPE HTML>
<HTML lang="en">
<head>
<title>First Demo</title>
<META name="description" content="HTML5 JS Tutorial" />
<META name="keywords" content="HTML5,CSS,JavaScript" />
<META name="Author" lang="en" content="Prasanna K Yalala" />
<style type="text/css">
            html,body {
                border: 0;
                height: 100%;
                font-family: arial, helvetica, sans-serif;  
            }
            body{
                background: -webkit-gradient(linear, left top, left bottom, from(#F0F0F0), to(#CCCCCC));
                background-color: rgba(0, 0, 0, 0.6);
                color: #000;
                height: 100%;
                margin: 0;
            }

            #my_div {
                margin-top: 15%;
                margin-left: 18%;
                width: 425px;
            }

            #my_layout {
                background: -webkit-gradient(linear, left top, left bottom, from(#FFFFFF), to(#DDDDDD));
                width: 500px;
                position:absolute;
                top: 50%;
                left: 50%;
                width:38em;
                height:20em;
                margin-top: -10em; /*set to a negative number 1/2 of your height*/  
                margin-left: -20em; /*set to a negative number 1/2 of your width*/
                border: 1px solid #ccc;
                -webkit-box-shadow: 2px 2px 2px #999;
            }

            #my_layout input{
                 border: 1px solid #ccc;
            }

            #my_layout button{
                border: none;
                color: #888;
                padding: 5px;
                width: 125px;
                height: 30px;
                font-weight: bold;
                border-radius: 5px;
                -webkit-box-shadow: 1px 1px 1px #888;
                background: -webkit-gradient(linear, left top, left bottom, from(#FFFFFF), to(#CCCCCC));
            }
            #my_layout button:hover{
                color: #A2ADD2;

            }

</style>
<script type="text/javascript">

/**
* Prasanna K Yalala
* 
* References
* .tutorialspoint.com,  Stackoverflow.com,
* html5rocks.com,  Tizag.com, w3schools.com, 
*
* Copyleft 2012, Nothing is Reserved.
*/

/**
* This function fetches the data from the form and displays
* onto the page. The result of the data being displayed depends
* on the check box being checked.
*/
function process(){
            var fName = document.getElementById("firstName").value;
            var sName = document.getElementById("lastName").value;
            var eAdd = document.getElementById("email").value;
            var food1 = document.DemoVersion.food[0].value;
            var food2 = document.DemoVersion.food[1].value;

            if(document.DemoVersion.food[0].checked == true){
                document.write("Hello "+fName+" "+sName+"!,<br/><br />"+"Your …
emclondon 38 Junior Poster in Training

calm down kid, I had to learn as fast as I can to answer your question.

its kinda complex but once you get a hold of it, its easy as a pie.

<!DOCTYPE HTML>
<HTML lang="en">
    <head>
        <title>
            Incident Report
        </title>
        <META name="description" content="HTML5 WebDatabase Tutorial" />
        <META name="keywords" content="HTML,CSS,JavaScript" />
        <META name="Author" lang="en" content="Prasanna K Yalala" />
        <style type="text/css">
            html,body {
                border: 0;
                height: 100%;
                font-family: arial, helvetica, sans-serif;  
            }
            body{
                background-color: rgba(0, 0, 0, 0.6);
                color: #000;
                height: 100%;
                margin: 0;
            }
            #insert_incident_div {
                display: none;
                margin-top: 8%;
                margin-left: 16%;
                width: 425px;
            }
            #menu{
                margin-top: 23%;
                margin-left: 30%;
            }

            #retrieve_incident_div {
                display: none;
                margin-top: 5%;
                margin-left: 15%;
                width: 425px;
            }

            #control {
                background: -webkit-gradient(linear, left top, left bottom, from(#FFFFFF), to(#DDDDDD));
                width: 500px;
                position:absolute;
                top: 50%;
                left: 50%;
                width:38em;
                height:20em;
                margin-top: -10em; /*set to a negative number 1/2 of your height*/  
                margin-left: -20em; /*set to a negative number 1/2 of your width*/
                border: 1px solid #ccc;
                -webkit-box-shadow: 2px 2px 2px #999;
            }
            #control button{
                border: none;
                color: #888;
                padding: 5px;
                width: 125px;
                height: 30px;
                border-radius: 5px;
                -webkit-box-shadow: 1px 1px 1px #888;
                background: -webkit-gradient(linear, left top, left bottom, from(#FFFFFF), to(#CCCCCC));
            }
            #control button:hover{
                color: red;
            }


            #result_div {
                color: red;
                padding-top: 20px;
                padding-left: 35px;
            }


            #message_box{
                height: 80px;
                margin: 0px auto -1px auto;
                width: 275px;
                border-radius: 5px;
                background: #fff;
                color: red;
                display:none;
            }
        </style>

        <script type="text/javascript">

            /**
            * Prasanna K Yalala
            * 
            * References
            * .tutorialspoint.com,  Stackoverflow.com,
            * html5rocks.com,  Tizag.com, w3schools.com, 
            *
            * Copyleft 2012, Nothing is Reserved.
            */

            /** …
emclondon 38 Junior Poster in Training

did you solve this issue?

emclondon 38 Junior Poster in Training

I'm not vijay :/ I just linked you to the blog.

emclondon 38 Junior Poster in Training

you must create a database prior to installing magento. magento DOESN'T create one for you.

emclondon 38 Junior Poster in Training

dude^ no offense but I work with magento.

and when I say you can run it on Windows, you should trust me.

cereal commented: no problem, bye ;) +8
emclondon 38 Junior Poster in Training

If you are referring to the e-commerce platform then look at system requirements:

- http://www.magentocommerce.com/system-requirements

it works only on linux. Bye.

You're mistaken. Magento Works on any platform as long as the platform runs a webserver with PHP/MySQL

follow the steps:

1. Create an empty database in your SQL server. (remember the name)
2. Copy Magento's files onto webserver's 'htdocs'/'www' directory
3. run the installer and give proper sql credentials with database name (from step 1)
4. installation would be easy as eating a pie.

emclondon 38 Junior Poster in Training

try this.

Maybe that would help?

/* database.inc.php */

<?php

	define("server","localhost");
	define("conn_username", "root");
	define("conn_password", "root");
	define("database_name", "database_1.1");
?>
/* index.php */

<?php
	require "database.inc.php";
	
	class mysql 
	{ 
	    function connect() { 
	    	@mysql_connect(server,conn_username,conn_password); 
	    	@mysql_select_db(database_name); 
		} 
	
	    function query($query) { 
	        $result = mysql_query($query); 
	        if (!$result) { 
	            echo 'Could not run query: ' . mysql_error(); 
	            exit; 
			} 
			else{
				return $result;
			}
	    } 
	    
	    function showresult($result) {
	    	$arr = array();
			 @mysql_data_seek($result);
			 while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
			 	array_push($arr, $row);
			 }
			 return $arr;
	    }
	    function end() { 
	        @mysql_close(); 
	    } 
	}
	
	$mysql = new mysql(); 
	$mysql->connect(); 
	print_r($mysql->showresult($mysql->query("SELECT * FROM Employee"))); 
	$mysql->end();
?>

read more here: http://www.vijayjoshi.org/2011/01/07/php-defining-configuration-values/

emclondon 38 Junior Poster in Training

not sure, maybe I think its sending twice because of the code you're using?

$body = "Dear ".$_GET["name_$x"]."
        \n\n $message \n\n
       YESHUA SCHOOL.";
      
       mail($to, $subject, $body, $headers);
       //break;
       
       if(mail($to, $subject, $body, $message))
       {
           echo 'Message sent successfully';
       }
 else {
           echo 'Message failed';
       }

try changing it to

$body = "Dear ".$_GET["name_$x"]."
        \n\n $message \n\n
       YESHUA SCHOOL.";

       if(mail($to, $subject, $body, $message))
       {
           echo 'Message sent successfully';
       }
 else {
           echo 'Message failed';
       }

maybe that would work. I'm not sure, but its worth giving a try.

karthik_ppts commented: Yes +7
emclondon 38 Junior Poster in Training

mate, It would be easy if you let us know what you are trying to do, and also if you could share the whole source, it would be easy to point out what's kicking your boots away.

emclondon 38 Junior Poster in Training

based on the code you posted, all you need to do is to include the file in your php page and perform a simple switch to get the result you are after. something like this:

yourpage.php

include('get_browser.php');
	$browser=getBrowser();
	switch ($browser['name'])
	{
		case 'Google Chrome':
			echo "you are using chrome";
			break;
		case 'Internet Explorer':
			echo "you are using ie";
			break;
		case 'Mozilla Firefox':
				echo "you are using firefox";
			break;		
		default:
			break;		
	}

now just a reminder that, if you are looking just to change the CSS based on the browser, this is not the way to do it.

emclondon 38 Junior Poster in Training

I can't see line 38 in sendmail.php but that's the first place I would look according to your error message.

You mis-read a part of the error wrong. The server displayed an error to check SMTP configuration details in php.ini, The server also suggested him to dynamically add SMTP settings to the script using ini_set() on the page.

--

@deyesborn, as StephNicolaou suggested, you should have a look into your SMTP settings. either change your php ini or add them on run by using ini_set();

emclondon 38 Junior Poster in Training

I rewrote the code for mysql, its almost same as oracle, maybe you could learn something from it?


SQL data

CREATE TABLE IF NOT EXISTS `him_details` (
  `NAME` varchar(25) DEFAULT NULL,
  `BRANCH` varchar(25) DEFAULT NULL,
  `SMOBILE` int(11) DEFAULT NULL,
  `ENO` int(11) DEFAULT NULL,
  `HOSTEL` varchar(25) DEFAULT NULL,
  `ROOM` varchar(25) DEFAULT NULL,
  `FMOBILE` int(11) DEFAULT NULL,
  `ADDRESS` varchar(25) DEFAULT NULL
)

INSERT INTO `him_details` (`NAME`, `BRANCH`, `SMOBILE`, `ENO`, `HOSTEL`, `ROOM`, `FMOBILE`, `ADDRESS`) VALUES
('first user', 'london', 123456789, 1, 'hostel', '22', 123456789, 'london, uk'),
('second user', 'oxford', 2147483647, 2, 'hotel', '14', 564789123, 'oxford, uk');

PHP

<?php
	$details = array(); 
	$username ='root';
	$password = '';
	$server =  'localhost';
	$database = 'orcl';
	$connection =  @mysql_connect($server,$username,$password);
	if($connection) {
		$db = @mysql_select_db($database);
		if($db){
			$query = @mysql_query("SELECT * FROM him_details");
			if($query){
				$details = @mysql_fetch_array($query);
			}
			else {
				die(mysql_errno()." ".mysql_error());
			}
			
		}
		else {
			die(mysql_errno()." ".mysql_error());
		}
	}
	else {
		die(mysql_errno()." ".mysql_error());
	}
?>

<html>
	<head>
		<title>
			Demo
		</title>
	</head>
	<body>
		<table>
			<tr>
				<td width="45%">
					Name
				</td>
				<td>
					<input type="text" value="<?php echo $details[0];?>" disabled="true"></input>
				</td>
			</tr>
			<tr>
				<td>
					Branch
				</td>
				<td>
					<input type="text" value="<?php echo $details[1];?>" disabled="true"></input>
				</td>
			</tr>
			<tr>
				<td>
					Smobile
				</td>
				<td>
					<input type="text" value="<?php echo $details[2];?>" disabled="true"></input>
				</td>
			</tr>
			<tr>
				<td>
					Eno
				</td>
				<td>
					<input type="text" value="<?php echo $details[3];?>" disabled="true"></input>
				</td>
			</tr>
			<tr>
				<td>
					Hostel
				</td>
				<td>
					<input type="text" value="<?php echo $details[4];?>" disabled="true"></input>
				</td>
			</tr>
			<tr>
				<td>
					Room
				</td>
				<td>
					<input type="text" value="<?php echo $details[5];?>" disabled="true"></input>
				</td>
			</tr>
			<tr>
				<td>
					Fmobile
				</td>
				<td>
					<input type="text" value="<?php echo $details[6];?>" disabled="true"></input>
				</td>
			</tr>
			<tr> …
emclondon 38 Junior Poster in Training

This is as far as I could get onto the code

process.php

<?php
	if(isset($_POST['submit'])) {
		include_once 'CurlREST.php';
		$category = urlencode($_POST['category']);
		$display = urlencode($_POST['display']);
		$sort = urlencode($_POST['sort']);
		$key = "12345678932156487"; // the key has been changed here
		
		$request = array();
		$request['$category']=$category;
		$request['$display']=$display;
		$request['$sort']=$sort;
		$request['$key']=$key;
		$myClient = new CurlREST();
		$response  = $myClient->getResponse($request); // this is the array I get

		if($response) {

			$doc = new DOMDocument();
			$doc->loadXML($response);
			
			$api = $doc->getElementsByTagName("api_item");

			foreach ($api as $item){
				
				$title = $item->getElementsByTagName("title");
				$deal_link = $item->getElementsByTagName("deal_link");
				$mobile_deal_link = $item->getElementsByTagName("mobile_deal_link");
				$deal_image = $item->getElementsByTagName("deal_image");
				$description = $item->getElementsByTagName("description");
				$submit_time = $item->getElementsByTagName("submit_time");
				$hot_time = $item->getElementsByTagName("hot_time");
				$poster_name = $item->getElementsByTagName("poster_name");
				$temperature = $item->getElementsByTagName("temperature");
				$price = $item->getElementsByTagName("price");
				$timestamp = $item->getElementsByTagName("timestamp");
				$expired = $item->getElementsByTagName("expired");
				$deal_image_highres = $item->getElementsByTagName("deal_image_highres");
				
				if(isset($deal_image_highres->item(0)->nodeValue))
				{
					$time = date("m-d-Y, g:i a",$timestamp->item(0)->nodeValue);
					echo "<table><tr><td><img src=\"".$deal_image->item(0)->nodeValue."\"/></td><td><a href=\"".$deal_link->item(0)->nodeValue."\">".iconv('UTF-8', 'ASCII//TRANSLIT',$title->item(0)->nodeValue)."</a></td><td>Posted by ".$poster_name->item(0)->nodeValue." (".$time.").</td></tr></table><br /><br />";
				}
				else
				{
					echo "Element Not found!<br />";
				}
			}
		}
		else {
			echo "Bad Selection";			
		}
	}
	else {
		header("HTTP/1.1 403 Forbidden");
	}
?>

CurlREST.php

<?php
	Class CurlREST {
		public function getResponse(array $params) {
			
			$category = $params['$category'];
			$display = $params['$display'];
			$sort = $params['$sort'];
			$key = $params['$key'];
			$option_error  ="bad options selected";
			$invalid_error = "Invalid Request; Please try again!";
			$url= 'http://api.hotukdeals.com/rest_api/v2?key='.$key.'&forum='.$category.'&results_per_page='.$display.'&order='.$sort;
			$curl_handler = curl_init();
			curl_setopt($curl_handler, CURLOPT_URL,$url);
			curl_setopt($curl_handler, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt ($curl_handler, CURLOPT_HEADER, 0);
			$response = curl_exec($curl_handler);
			$response_code = curl_getinfo($curl_handler, CURLINFO_HTTP_CODE);
			
			if($response_code == '200') {
				curl_close($curl_handler);
				return $response;
			}
			else {
				curl_close($curl_handler);
				return NULL;
			}
		}
	}
?>
emclondon 38 Junior Poster in Training

hmm.. sorry for being silent for too long. I think I've deviated from my track here.

indeed your solution is marvellous. lets forget 'getTags' for a moment and lets assume that my xml has like around more than 15000 elements, then wouldn't it be time consuming for the script to render the details on to the screen?

I have thought of a similar solution earlier, and the same thought occurred to me. That's the main reason which made me think of alternative solution to dump the data into a temporary 'db' and accessing it later at my own leisure.

also can the same result be achieved without json?

emclondon 38 Junior Poster in Training

I'm trying to auto-populate a tree/list based on the XML I recieve so that I can use it to display data on to a page.

You need may a recursive function here. I'm not sure what you need as you already have all the data in a nested array (the way it should be). . . . . . . . WHICH GIVES

title (single, level 1)
deal_link (single, level 1)
mobile_deal_link (single, level 1)
deal_image (single, level 1)
description (single, level 1)
submit_time (single, level 1)
hot_time (single, level 1)
poster_name (single, level 1)
temperature (single, level 1)
price (single, level 1)
timestamp (single, level 1)
expired (single, level 1)
forum  (single, level 1, container)
  name (single, level 2)
  url_name (single, level 2)
category (single, level 1, container)
  name (single, level 2)
  url_name (single, level 2)
merchant (single, level 1, container)
  name (single, level 2)
  url_name (single, level 2)
tags (single, level 1, container) 
  api_item (<strong>multiple</strong>, level 2, container)
    name (single, level 3)

Is this the extent of it? It doesn't look too bad

EXACTLY!

This is the reason I created my class this way:Hello guys,
.
.
.
.
.
.
.
.
.
this is what I designed

<?php

	class api_item{

		private $title;
		private $deal_link;
		private $mobile_deal_link;
		private $deal_image;
		private $description;
		private $submit_time;
		private $hot_time;
		private $poster_name;
		private $temperature;
		private $price;
		private $timestamp;
		private $expired;
		private $deal_image_highres;
		
		function get_title(){
			return $title;
		}
		function …
emclondon 38 Junior Poster in Training

I'm trying to auto-populate a tree/list based on the XML I recieve so that I can use it to display data on to a page.

All I want with that data is to display it on to my ui. sommething like this

emclondon 38 Junior Poster in Training

phew,

I finally figured out how to work this thing out. Its still mind numbing because of the lack of proper tutorials on the internet.

anyways, here is what I came up with.

MainClass.java

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainClass {

	public static void main(String[] args) {

		ExecutorService exec = Executors.newFixedThreadPool(3);

		exec.execute(new RunnerClass("Thread#1"));

		exec.execute(new RunnerClass("Thread#2"));

		exec.execute(new RunnerClass("Thread#3"));
		System.out.println("\nShutting Down Service");
		exec.shutdown();
	}
}

RunnerClass.java

public class RunnerClass implements Runnable {

	private String name;
	
	public RunnerClass(String args) {
		this.name = args;
	}
	
	public void run() {
		try{
			System.out.printf("The Thread '%s' is Running",name);
			Thread.sleep(5000);
			System.out.printf("The Thread '%s' is Awake",name);
		}
		catch (Exception e){
			e.printStackTrace();
		}	
	}
}

sorry for the late reply, btw.

work work work+getbulliedbyprojectmanager work work+drink drink+hangover drink+relax pattern is really tiresome :P

emclondon 38 Junior Poster in Training

so this is what I came up with.

$xmlstring = file_get_contents("file.xml");
	$apis = new SimpleXMLElement($xmlstring);
	$node = $apis->deals;
	$json = json_encode($node);
	$array = json_decode($json,TRUE);
	$MainClass= $array['api_item']; //aray of node 'api_item'
	$new_array = array(); //new blank array
	
	foreach($MainClass as $MainClassObj) { //traverse through the array
		if(is_array($MainClassObj)) { //if it has children which itself is an array
			foreach($MainClassObj as $MainClassChild) { //traverse through the child array
				if(is_array($MainClassChild)){ //if the child has array too
					foreach($MainClassObj as $MainClassChildObj) {//traverse through the grand child array
						print_r($MainClassChildObj); // dump the data
					}
				}
			}
		}

	}

This works in some sort of way, but I think I'm just looping the print_r for 'n' number of array items in the variable.
the more I think about it, the more it hurts my brain.

i'm stuck again :(

emclondon 38 Junior Poster in Training

Hello ardav,

thanks for your reply.

I don't think that the XML is well formed. Well, the code you've written is close to what I need.

The API also has an option to recieve data in JSON format. But I explicitly am not using it as I want to use XML so I could learn how things work.

now what I actually want to do is dump the data into dynamic array (becayse I dont't know the size of incoming data) automatically I get into a sensible array where I can get the data.

emclondon 38 Junior Poster in Training

Hello guys,

I am trying to learn working with Web services using PHP. I have found many methods to access and consume these services, but I've come to know Soap Client and cURL are the best way to do it. I decided to work on an API provided by a UK Money Saving Forum 'HUKD'

I used both (SOAP & cURL) and successfully retrieved data in XML format. which is pretty neat, so far. I get the following XML as a response. (don't be afraid its just a list of data)

file.xml

(I have attached the XML and not pasted here because of its really large text of 1000 something lines and its annoying to scroll down).

Now, this is a filtered response. My response can have many 'api_item' I found that a bit challenging to work with and handle.

So this is what I did.

<?php
include_once 'api_item.php';
$api_item[] = new api_item();
$file= 'file.xml';
$xml = simplexml_load_file($file);
$api_item[0]->put_title($xml->children()->children()->children()->__toString());
?>

and it gives me this
response.txt

the response is an array of all the xml data.

so I decided to create a class and I've planned to fetch the data and get the 'api_item' data from fetched data and dump it into the class array. (its just a theory. Is it something we can do?)

this is what I designed

<?php

class api_item{

    private $title;
    private $deal_link;
    private $mobile_deal_link;
    private $deal_image;
    private $description;
    private $submit_time;
    private $hot_time;
    private $poster_name;
    private $temperature;
    private $price; …
emclondon 38 Junior Poster in Training

they're in the same folder, but for some unknown reason the configuration on my system has gone haywire. i reinstalled the java and created this:

I have a class (say its 1st class) which invokes the superclass and creates a thread pool and I set the properties like poolsize, keepalive, etc and list in the same class.

im calling the method of queue.add(new 3rdclass()) from a 2nd class.
i have seen many methods like afterExecute, beforeExecute, etc, etc. I have no clue how teh right method of execution should be here.

what do i do next?

emclondon 38 Junior Poster in Training

thanks for the pointers james, They're a bit helpful.

With the help of my work colleague I coded a thread pool with 3 classes, pooler, runner and main where runner executes a line of code when called. pooler creates a threadpool with 4 threads and main has main function which calls the thread pool with runners instance.

This works fine but when I decided to monitor the usage using JConsole,it reports that the application uses 14 threads. Not sure why. I suspect that Eclipse is interfering here. So I decided to compile and run from command line and stuick with silly error now.

my project is structured as sj.threadpool, so my package name is threadpool and my files are in workspace/sj/src/threadpool when I compile the java files, the classes gets created, but when I run it I get an error

Exception in thread "main" java.lang.NoClassDefFoundError: MainClass (wrong name
: threadpool/MainClass)
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClassCond(Unknown Source)
        at java.lang.ClassLoader.defineClass(Unknown Source)
        at java.security.SecureClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.access$000(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: MainClass.  Program will exit.

anyoe know why the compiler cant find my MainClass?

emclondon 38 Junior Poster in Training

and modified it a bit to this:

MainClass.java

package sj;

public class MainClass
{
		MainClass(){}
		public static void main(String[] args)
		{
			RunnerClass runner = new RunnerClass("this is a test",5,500);
			Thread thread = new Thread(runner);
			thread.start();
		}
}

RunnerClass.java

package sj;

public class RunnerClass implements Runnable
{
	private String s;
	private int i;
	private long t;

	RunnerClass(String args0,int args1, long args2)
	{
		this.s = args0;
		this.i = args1;
		this.t = args2;
	}
	public void run()
	{

		for(int j=0;j<=i;j++)
		{

			System.out.println(s);
			try
			{	
				Thread.sleep(t);
			}
			catch(Exception e)
			{
				System.out.println(e.getMessage());
			}
		}
	}
}

simple as it is. Now is this the right way to do it? or am I doing it wrong?

also I have no clue about blocking queues and how to use them. so im basically stuck again!

emclondon 38 Junior Poster in Training

alright this is what I did, I would be posting in 2 different posts to avoid confusion.

simple program.

MainClass.java

package sj;

public class MainClass
{
		MainClass(){}
		public static void main(String[] args)
		{
			RunnerClass runner = new RunnerClass();
			runner.run("this is a test",5,500);
		}
}

RunnerClass.java

package sj;

public class RunnerClass implements Runnable
{
	private String s;
	private int i;
	private long t;
	
	public void run()
	{
		System.out.println("This is a demo");
	}
	
	public void run(String args0,int args1, long args2)
	{
		this.s = args0;
		this.i = args1;
		this.t = args2;
		for(int j=0;j<=i;j++)
		{
			System.out.println(s);
			try
			{	
			 Thread.sleep(t);
			 }
			catch(Exception e)
			{
				System.out.println(e.getMessage());
			}
		}
	}
}
emclondon 38 Junior Poster in Training

ah yes, I want to know how to implement a simple thread and pool.

emclondon 38 Junior Poster in Training

strange, why would you advise against extending a thread class, and why would you advise me to use implement a runnable interface.

bigger picture: I'm trying to write a thread pool which would be used to develop a pooling mechanism for a web service, which serve at least 10000 requests for 30 seconds.

smaller picture: I should create a small pool to show the demo on a scale model.

ThreadPoolExecutor is a class which contains methods to execute several pooled threads

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ThreadPoolExecutor.html

@James, the example I posted is one I got from google.

Basically, I don't want to copy paste everything. I want to know how a thread is implemented and thread pool in implemented, and how ThreadPoolExecutor can be used to achieve my goal.

emclondon 38 Junior Poster in Training

Hello Guys,

I'm trying to use a Thread Pool Executor in my application and I'm kinda stuck somewhere.

My aim is to create a pool of fixed number of threads (say 10) waiting in the pool to be called for action (say to print hello);

I'm still bad at java, but here is what I have come up with.

public class ThreadPoolExecution
{
	public static void  main(String[] args)
	{
		BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10);
		ThreadPoolExecutor ex = new ThreadPoolExecutor(4,10,20, TimeUnit.SECONDS,q);
		try
		{
				//ex.execute(null);
		}
		catch(RejectedExecutionException e)
		{
			System.out.println(e.getMessage());
		}	
	}

What I need is to know, how a plain thread is created, how to create a thread pool, and how to use ThreadPoolExecution.

I have searched the forum, but I haven't found any solution which I found useful. Can you please help me out?

emclondon 38 Junior Poster in Training

aaah! My bad. I thought the whole code was there. the following is a feeble attempt to use my class which has the method on a different panel.

import java.awt.*;
import javax.swing.*;

/**
*
* @(#)MyImageClass.java
*
* This class is used to render a JPEG image on panel
* which its being used.
*
* @author Prasanna Kumar Yalala
* @version 1.00, 2012/01/30
*/

/**
* This class contains methods used to resize and render an image on Panel.
*/

@SuppressWarnings("serial")
public class MyImageClass extends JLabel
{

	/**
	 * This creates a variable of ImageIcon class to hold the image.
	 */	 

	ImageIcon _temp;
	
	/**
	 * This creates a variable of ImageIcon class to hold the image.
	 */	 
	 	
	ImageIcon _newTemp;
	
	/**
	 * The method sets an image on to the panel 
	 *
	 */

	public void setImage(String path)
	{
		/**
		* an image would be resized and rendered on the panel
		* put the path of the image here.
		*/
		
		this.setIcon(resizeImage(new ImageIcon(path)));
	}

	/**
	 * The method resizes an image and returns it back to the sender.
	 *
	 * @param _myImage an image which needs to be resized
	 * @return _newIcon resized image of size 50x38 pixels
	 */
  	
	private ImageIcon resizeImage(ImageIcon _myImage)
	{
		Image _img = _myImage.getImage();
		Image _newimg = _img.getScaledInstance(50, 38,Image.SCALE_SMOOTH); 
		ImageIcon _newIcon = new ImageIcon(_newimg); 
		return _newIcon;
	}
}

and add the following code to the main panel

import java.awt.*;

/**
*
* @(#)MyClass.java
*
* This class is used to create and display a frame
* …
emclondon 38 Junior Poster in Training

err.. I don't quite understand what you said there james.

emclondon 38 Junior Poster in Training

I had a similar problem a year back and here is the solved reply.

the solution, basically create an imageicon and dump your image on to it.

JPanel mainpanel;
JLabel imagelabel; 
ImageIcon myImage;
String mypath;
JPanel lightpanel;

mypath = // put your path here.
myImage = new ImageIcon(mypath);
imagelabel = new JLabel(resizeImage(myImage));
lightpanel.add(imagelabel);	
mainpanel.add(lightpanel);

this should work 99.99%

emclondon 38 Junior Poster in Training

Sorry for being a total jackass and abandoning this thread.

big massive thanks and apologies to JamesCherrill, ~s.o.s~, and NormR1 for all your help and support during the grim period of my life.

Thanks to you guys, now I have a masters degree and a Jr. Developer position in a reputed firm UK. I cannot express how grateful I am to you guys for all your support. if you are around london/reading/maidenhead give me a shout, I'll definitely buy you guys a pint or a dozen.

AND FINALLY:

uniKEY.zip

Here is the final product free to use for whatever you may wish to use it for.

cheers mates!

~s.o.s~ commented: :) +17
emclondon 38 Junior Poster in Training

That would make half the commercial programs and operating systems violate the rules of plagurism The US courts have already ruled that concepts/ideas can not be copyright.

more than 70% of the universities here in UK have their plagiarism defined as the statement posted above.

While I can sympathize with your plight in regards to being concerned about being penalized for 'plagarism' unfairly, I am also certain that there would exist appeals procedures within the institution you are attending where you would be able to state your case and prove that the code content was, in fact, yours to begin with and that you simply received conceptual assistance from the DaniWeb Community.

I will try my best to convince my professor that I worked on the code with help from people on daniweb.

thanks for your help guys.

emclondon 38 Junior Poster in Training

1. Every student at the start of new school year, specifically at universities, is strongly encouraged to read university rules in regards of plagiarism which also includes sections how to use external resources and how to write reports. If you did you would know how much you can relay on internet forums

my bad, thats the one thing I didnt do.

3. Every year teachers are trying to put fear into students with some copyrights machine, but either it does not exists or it has very low margin because during my last 5 years study nobody was punished and I'm aware of many of the offenders

My friends have been victims of these "machines" inspite of them working hard and not cheating.

anyways, according to the regulations of my institute, Plagarism constitutes

"The presentation by the student as their own work of a body of material (written, visual or oral) which is wholly or partially the work of another, either in concept or expression, or which is a direct copy".

You cannot plagiarize your own code. Any sentient human being looking at that thread would see six pages of you working through issues with the original code you posted. Unless you copied the original post code from another source on the net, I don't see where you would have any problems defending that thread..

a human can understand that I've been working hard to get it done, but when a software (plagarism checker) tries verifying the …

emclondon 38 Junior Poster in Training

hello admin/mods,

I am facing a problem. I have PMed an admin and a mod about this earlier and the issue wasnt resolved as it bought a new issue.

I am a masters student from London and I posted a question here on the forums when I was stuck doing a coursework.

the link to my question is : http://www.daniweb.com/forums/thread298069.html

now the problem is that my professor told me that if the code is found on the internet, I would be subjected to plagarism and will fail my semester.

I tried explaining him that I've just got pointers and not the whole code, i was told that the check would be done by the software final verdict would be done by the software.

I have searched trough the daniweb site and I realised that the staff doesn't delete any of the threads. So, Im requesting you to remove the coding in my thread so that you and I can both be benfited from this moderation.

could you please help me out?
thanks.

emclondon 38 Junior Poster in Training

i used this code:

class myClass
{
        _myLapTimer = new Timer();
	_myLapTimer.schedule(new myLapTimer(),5000);
	
	class myLapTimer extends TimerTask
	{
		public void run()
		{
			resetState();
		}
	}
        public void reset()
        {
                cancelTimer();
	}

	public void cancelTimer()
	{
		_myLapTimer.cancel();	
	}
        
        public void check()
        {
             if(true)
             {
  		_myLapTimer.schedule(new myLapTimer(),5000);
             }
             else
             {
  		_myLapTimer.schedule(new myLapTimer(),5000);
             }
        }
}

kis this the right way to do it?

emclondon 38 Junior Poster in Training

how do I schedule the timer? I've tried once but I couldn't do it right :(

public java.util.Timer _myTimer;
_myTimer.schedule(new java.util.TimerTask (){public void run(){resetState();}},5000);

--


also, I was wondering if it was possible to an instance of a class?


for example:

class x
{

     public x v;
     public z w;

     public x()
     {
        // blah
        w.show();
     }

     public x getInstance()
     {
           return v; 
     }
}

class y
{
     public x a;
     public y()
     {
        a = new x();
     }
     public static void main(String[] args)
     {
         new y();
     }
}

class z
{
     public x b;
     public z()
     {
        b = new x();
     }
     public void show()
     {
          System.out.println(b.getInstance());
     }
}

can this be done?

in simple words: I have 3 classes, 1st class has object of 2nd class. I need to access variables of 2nd class in 3rd class.. how is it possible?