C# and Daniweb's API: Example, nasty, simple and quick code

riahc3 4 Tallied Votes 454 Views Share

RestSharp library needed

Mike Askew commented: Thanks for sharing, +rep +6
private void button1_Click(object sender, EventArgs e)
        {
            string newString = "";
            var client = new RestClient("http://www.daniweb.com/api"); /*I prepare the API*/

            /*I remove whitespaces except actual spaces*/
            for (int i = 0; i < textBox1.Text.Length; i++)
            {
                if ((char.IsWhiteSpace(textBox1.Text[i])) && (!textBox1.Text[i].Equals(' ')))
                {
                    textBox1.Text = textBox1.Text.Remove(i, 1); 
                }
                
            }


            /*I make sure that the user name isnt empty */
            if (textBox1.TextLength==0)
            {
                MessageBox.Show("Please insert a valid member");
            }
            else
            {
              
            /*I call the members method of the API and pass parameters by GET. POST did not work (Why?)*/
            var request = new RestRequest("members", Method.GET);
            request.AddParameter("username", textBox1.Text);

            /*Send it and wait for reply*/
            var response = client.Execute(request);
            
            /*Finding where it says the post number in the response...*/
            int next = 0;
            int first = response.Content.IndexOf("\"posts\":\"");
                if (first==-1) /*-1 means it could not find it therefore no member exists*/
                {
                    MessageBox.Show("Member not found!"); 
                }
                else
                {
                    /*I find the next quote that actually begins the post number*/
            do
            {
                next = response.Content.IndexOf("\"", first);
                /*Not neccesary but in case Dani changes the array to something else....*/
                if (next==-1)
                {
                    break;
                }
            } while ((next==0));

            
           
            /*VERY Ugly hack to get posts numbers. Tried with largest post numbers I could find (Dani's AFAIK)*/
            string str2 = response.Content.Substring(first, (next + 16) - first);
            newString = Regex.Replace(str2, "[^.0-9]", "");

            }
            
             if (textBox1.TextLength == 0)
             {
                 MessageBox.Show("Please insert a valid member");
             }
             else if (first!=-1)
             {
                 MessageBox.Show(newString, "The total amount of posts this user has is:");
             }
            }
             
        }
ddanbe 2,724 Professional Procrastinator Featured Poster

Did you marked your post on whitespace as solved yet?
You don't have to do this for my beautifull eyes you know...

Ketsuekiame 860 Master Poster Featured Poster

Rather than your for loop to check for whitespace, you can put all the code into a LINQ statement :)

textBox1.Text = String.Concat(textBox1.Text.Where(c => !char.IsWhiteSpace(c) || c.Equals(' ')));

The need for String.Concat arises because the where clause returns IEnumerable<char> which is unfortunate :(

There is probably also an improvement to resource usage with the above code as you won't be constantly creating string objects.

Ketsuekiame 860 Master Poster Featured Poster

After reviewing some performance figures, instead of using String.Concat above, use textBox1.Text = new String(textBox1.Text.Where(c => !char.IsWhiteSpace(c) || c.Equals(' ')).ToArray());

In fact, never use String.Concat. It seems it sucks...BAD.

riahc3 50   Team Colleague

Did you marked your post on whitespace as solved yet?
You don't have to do this for my beautifull eyes you know...

Your post wasnt exactly the answer or solved it....

Ill upvote you if you want but thats it.

riahc3 50   Team Colleague

Rather than your for loop to check for whitespace, you can put all the code into a LINQ statement :) textBox1.Text = String.Concat(textBox1.Text.Where(c => !char.IsWhiteSpace(c) || c.Equals(' '))); The need for String.Concat arises because the where clause returns IEnumerable<char> which is unfortunate :( There is probably also an improvement to resource usage with the above code as you won't be constantly creating string objects.

After reviewing some performance figures, instead of using String.Concat above, use textBox1.Text = new String(textBox1.Text.Where(c => !char.IsWhiteSpace(c) || c.Equals(' ')).ToArray()); In fact, never use String.Concat. It seems it sucks...BAD.

On a personal level, I have never cared or put intrest in resource hogging, memory hogging, or performance in any of my programs Ive written to date. I believe (your LINQ example) if it is not clear nor to me nor to most people that read the code, I should not use it. When writing code, I think that the most important thing is that the code is first clear to me than to others. Reason why I never use a foreach....

This code is as is and a proof of concept. No more than 10 minutes has been put into it. Its not ment to be used either seriously or in a production enviroment.

Ketsuekiame 860 Master Poster Featured Poster

LINQ is quite clear when used in small doses and in appropriate circumstances. I agree with you that code should be readable, however, that's no reason to avoid "advanced" coding methods.
I have seen some nightmare LINQ, truly, it should have been burned at some kind of sacrificial altar, but when used in small amounts, it's as easy to maintain and read as a normal loop statement.

I don't understand why you wouldn't use a foreach, it seems wasteful to exclude these features which are there for our benefit and is in fact, more clear than a for loop.

ddanbe 2,724 Professional Procrastinator Featured Poster

@riahc3: please don't upvote the small contribution I made. I just asked the post to be marked solved, and even that you don't have to do if you don't want to. But it would help other users of this site. Happy computing :o)

mvmalderen commented: You are modest. This is for all the other times you've helped as well. ;) +0
riahc3 50   Team Colleague

LINQ is quite clear when used in small doses and in appropriate circumstances. I agree with you that code should be readable, however, that's no reason to avoid "advanced" coding methods.
I have seen some nightmare LINQ, truly, it should have been burned at some kind of sacrificial altar, but when used in small amounts, it's as easy to maintain and read as a normal loop statement. I don't understand why you wouldn't use a foreach, it seems wasteful to exclude these features which are there for our benefit and is in fact, more clear than a for loop.

LINQ (AFAIK) is some kind of SQL-like sintaxis for programming in .NET Its nonstandard practice, although versions exists for other languages as well. My C# code is fairly portable in the sense that with little changes, (except for RestSharp) this should also work in other languages. As a matter of fact, Im looking to do a Java version as well.

The reason I dont use a foreach is like I stated:

Its unclear to a first timer.
I have yet to personally find a foreach that cannot be subbed by a for loop.

Ketsuekiame 860 Master Poster Featured Poster

Whether it can be substituted or not isn't the point. By that argument you'd never use Lists, only Arrays and you'd never use String, only character arrays and take it a step further, why use arrays when you can record each variable as a global. That way, there's no need to use classes and you can run your entire application in a single method...

Also, a for loop can be easily replaced by a while loop and in that case, why use loops at all when you can use recursive functions.

Saying it's non-standard is also a moot point as it is standard in .NET. Again, using your argument, you could say the only language you should program in is C or C++ as they're standard (or at least can be) on all platforms, but then again, you really should be writing machine code and only using instructions available to both AMD and INTEL processors, not to mention RISC processors such as those made by ARM.

Where exactly do you stop?

With regards to your Java port. It's exactly that, you're porting it to a different language. Even in C++ you will need to run #ifdef all over if you want the same code for Windows and Linux. You can't avoid it in anything but the most basic applications.

Finally, everyone starts as a first timer; how do you think a first timer would look at a for loop? for seems intuitive to us because we're used to it. But for a complete newbie the first line is simply a "Whaaa??? o.O" for(int i = 0; i < 10; i++) and we still don't know the intention of the loop. Sure we know it will loop ten times, but why? You have to analyse the content of the loop just to ascertain what the i is for and there's room for interpretation. On the other hand foreach(int number in myListOfNumbers) is incredibly clear on the first line. You immediately know that this loop will be performing some function on each number in this list/array.

There are times where foreach is inappropriate, but the same can be said about for loops.

tl;dr - Everyone starts as a newbie but you only learn by exploring and using the things you don't know about.

Ketsuekiame 860 Master Poster Featured Poster

Just a small correction as well, LINQ can be made to look like SQL syntax, but it's just a "Query" language.

var someVariable = from result in myList
                   where result.Value > 10
                   select result;

is LINQ and is, I think, horrible. Good for database designer people though as it a bit similar.

I prefer the following syntax

var someVariable = myList.Where(item => item.Value > 10).ToList();

Which performs exactly the same job.

ddanbe 2,724 Professional Procrastinator Featured Poster

I have no preference between for and foreach. I am a rather lazy programmer so I tend to foreach. That is also the reason I took some time to study some LINQ & lambda. Things get quicker done with little or no code. Intresting article about for versus foreach.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

tl;dr - Everyone starts as a newbie but you only learn by exploring and using the things you don't know about.

I want to preface this with the comment that there's no malice or judgement in this post, it's just an observation based on limited experience.

I'm reminded of the difference between "newbie" and "noob" in MMO circles. A newbie is a beginner, any ignorance is temporary as they learn how things work. A noob is willfully ignorant and refuses to learn regardless of how long they've been playing.

riahc3 strikes me as the type that reached a point of being able to write code that "works" and doesn't want to continue improving. What he knows is sufficient to do what he wants, and that's all that matters. Granted this is an observation over the course of maybe three threads, so it's hardly a statistically significant sample.

ddanbe commented: Very well spoken, like your signare. +14
riahc3 50   Team Colleague

riahc3 strikes me as the type that reached a point of being able to write code that "works" and doesn't want to continue improving

What works, works; Why reinvent the wheel?

Learning stuff is always great of course (when you dont know how) but I perfer to do something ASAP rather than look up information to do it a new/better way.

It really makes no difference to me; The programs I write (hobby or professional) arent performance intenstive or anything like that. Ive never cared in the slightest for performance at all, unless Im obviously asked for.

kplcjl 17 Junior Poster

The following doesn't make sense:

            do
            {
                next = response.Content.IndexOf("\"", first);
                /*Not neccesary but in case Dani changes the array to something else....*/
                if (next==-1)
                {
                    break;
               }
            } while ((next==0));

I'm not a fan of do whiles, but even if Dani changes things around this is only going to add another useless if statement every time next is zero that doesn't help or improve this:

do {next = response.Content.IndexOf("\"", first); }
while ((next==0));

PS What's with the extranious parentheses?
PPS If first IS 0 and next is set to 0, how is this NOT an infinite loop even if you added the break logic? if first is > 0, how does the while ever become true to even loop once?

kplcjl 17 Junior Poster

What riahc3 said makes sense. Worrying about string performance in a textbox event handler is pretty dumb.

However knowing WHEN to worry about performance also makes sense. For personal interest, I was working on a mathematical puzzle and I wanted to see just how much work was being done to solve it. I also wanted to see just how much not using StringBuilder impacted the performance so I intentionally put the string together by adding int fields and text describing what the int fields tell me.

I finally figured out the logic and got a program that completed in 27+ minutes. Putting in the StringBuilder logic cut it down to 14+ minutes. Changing the logic to NOT convert the stats into a string until a final answer was found (Or debug request to SEE the individual steps was made.) cut it down to 7 minutes. Playing around with the order in which numbers are solved cut it down to 4 minutes. Getting a new machine that was twice as fast cut it down to 2 minutes.

riahc3 50   Team Colleague

Dani hates me :P so here you go. Updated:

private void button1_Click(object sender, EventArgs e)
        {
            string newString = "";
            var client = new RestClient("http://www.daniweb.com/api"); /*I prepare the API*/

            /*I remove whitespaces except actual spaces*/
            for (int i = 0; i < textBox1.Text.Length; i++)
            {
                if ((char.IsWhiteSpace(textBox1.Text[i])) && (!textBox1.Text[i].Equals(' ')))
                {
                    textBox1.Text = textBox1.Text.Remove(i, 1); 
                }

            }


            /*I make sure that the user name isnt empty */
            if (textBox1.TextLength==0)
            {
                MessageBox.Show("Please insert a valid member");
            }
            else
            {

            /*I call the members method of the API and pass parameters by GET. POST did not work (Why?)*/
            var request = new RestRequest("members", Method.GET);
            request.AddParameter("username", textBox1.Text);

            /*Send it and wait for reply*/
            var response = client.Execute(request);

            /*Finding where it says the post number in the response...*/
            int next = 0;
            int first = response.Content.IndexOf("\"posts_count\":\"");
                if (first==-1) /*-1 means it could not find it therefore no member exists*/
                {
                    MessageBox.Show("Member not found!"); 
                }
                else
                {
                    /*I find the next quote that actually begins the post number*/
            do
            {
                next = response.Content.IndexOf("\"", first);
                /*Not neccesary but in case Dani changes the array to something else....*/
                if (next==-1)
                {
                    break;
                }
            } while ((next==0));



            /*VERY Ugly hack to get posts numbers. Tried with largest post numbers I could find (Dani's AFAIK)*/
            string str2 = response.Content.Substring(first, (next + 21) - first);
            newString = Regex.Replace(str2, "[^.0-9]", "");

            }

             if (textBox1.TextLength == 0)
             {
                 MessageBox.Show("Please insert a valid member");
             }
             else if (first!=-1)
             {
                 MessageBox.Show(newString, "The total amount of posts this user has is:");
             }
            }

        }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.