Data Storage Schemes in Android-Shared preferences (Setting Font Size)

To Setting Dynamic Fonts Size in Android Activity Use “Shared Preferences”

1. Create a project SharedPreference and add the bellow code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <SeekBar
        android:id="@+id/SeekBar01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/TextView01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <EditText
        android:id="@+id/EditText01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btnSave"
        android:text="Save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

package com.jetbrain.nazim.sharedpreferences;
//[changeable as your project package]

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;

public class SharedPreferencesActivity extends Activity {

    private SharedPreferences prefs;
    private String prefName = "MyPref";
    private EditText editText;
    private SeekBar seekBar;
    private Button btn;

    private static final String FONT_SIZE_KEY = "fontsize";
    private static final String TEXT_VALUE_KEY = "textvalue";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shared_preferences);

        editText = (EditText) findViewById(R.id.EditText01);
        seekBar = (SeekBar) findViewById(R.id.SeekBar01);
        btn = (Button) findViewById(R.id.btnSave);

        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                //---get the SharedPreferences object---
                //prefs = getSharedPreferences(prefName, MODE_PRIVATE);
                prefs = getPreferences(MODE_PRIVATE);

                SharedPreferences.Editor editor = prefs.edit();

                //---save the values in the EditText view to preferences---
                editor.putFloat(FONT_SIZE_KEY, editText.getTextSize());
                editor.putString(TEXT_VALUE_KEY, editText.getText().toString());

                //---saves the values---
                editor.commit();

                //---display file saved message---
                Toast.makeText(getBaseContext(),
                        "Font size saved successfully!"+editText.getTextSize(),
                        Toast.LENGTH_SHORT).show();
            }
        });

        //---load the SharedPreferences object---
        //SharedPreferences prefs = getSharedPreferences(prefName, MODE_PRIVATE);
        prefs = getPreferences(MODE_PRIVATE);

        //---set the TextView font size to the previously saved values---
        float fontSize = prefs.getFloat(FONT_SIZE_KEY, 12);

        //---init the SeekBar and EditText---
        seekBar.setProgress((int) fontSize);
        editText.setText(prefs.getString(TEXT_VALUE_KEY, ""));
        editText.setTextSize(seekBar.getProgress());

        seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                                          boolean fromUser) {
                //---change the font size of the EditText---
                editText.setTextSize(progress);
            }
        });
    }
}

now run your project


Advertisements

Download/Stream file from URL – Asp.net and C#

 //Create a stream for the file
    Stream stream = null;

    //This controls how many bytes to read at a time and send to the client
    int bytesToRead = 10000;

    // Buffer to read bytes in chunk size specified above
    byte[] buffer = new Byte[bytesToRead];

    // The number of bytes read
    try
    {
      //Create a WebRequest to get the file
      HttpWebRequest fileReq = (HttpWebRequest) HttpWebRequest.Create(url);

      //Create a response for this request
      HttpWebResponse fileResp = (HttpWebResponse) fileReq.GetResponse();

      if (fileReq.ContentLength > 0)
        fileResp.ContentLength = fileReq.ContentLength;

        //Get the Stream returned from the response
        stream = fileResp.GetResponseStream();

        // prepare the response to the client. resp is the client Response
        var resp = HttpContext.Current.Response;

        //Indicate the type of data being sent
        resp.ContentType = "application/octet-stream";

        //Name the file 
        resp.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());

        int length;
        do
        {
            // Verify that the client is connected.
            if (resp.IsClientConnected)
            {
                // Read data into the buffer.
                length = stream.Read(buffer, 0, bytesToRead);

                // and write it out to the response's output stream
                resp.OutputStream.Write(buffer, 0, length);

                // Flush the data
                resp.Flush();

                //Clear the buffer
                buffer = new Byte[bytesToRead];
            }
            else
            {
                // cancel the download if client has disconnected
                length = -1;
            }
        } while (length > 0); //Repeat until no data is read
    }
    finally
    {
        if (stream != null)
        {
            //Close the input stream
            stream.Close();
        }
    }

Android spinner (drop down list) example

Original Post: http://www.mkyong.com/android/android-spinner-drop-down-list-example/

In Android, you can use “android.widget.Spinner” class to render a dropdown box selection list.

Note
Spinner is a widget similar to a drop-down list for selecting items.

In this tutorial, we show you how to do the following tasks :

  1. Render a Spinner in XML, and load the selection items via XML file also.
  2. Render another Spinner in XML, and load the selection items via code dynamically.
  3. Attach a listener on Spinner, fire when user select a value in Spinner.
  4. Render and attach a listener on a normal button, fire when user click on it, and it will display selected value of Spinner.

P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.

1. List of Items in Spinner

Open “res/values/strings.xml” file, define the list of items that will display in Spinner (dropdown list).

File : res/values/strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
 
    <string name="app_name">MyAndroidApp</string>
    <string name="country_prompt">Choose a country</string>
 
    <string-array name="country_arrays">
        <item>Malaysia</item>
        <item>United States</item>
        <item>Indonesia</item>
        <item>France</item>
        <item>Italy</item>
        <item>Singapore</item>
        <item>New Zealand</item>
        <item>India</item>
    </string-array>
 
</resources>

2. Spinner (DropDown List)

Open “res/layout/main.xml” file, add two spinner components and a button.

  1. In “spinner1″, the “android:entries” represents the selection items in spinner.
  2. In “spinner2″, the selection items will be defined in code later.

File : res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:entries="@array/country_arrays"
        android:prompt="@string/country_prompt" />
 
    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
 
    <Button
        android:id="@+id/btnSubmit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Submit" />
 
</LinearLayout>

3. Code Code

Read the code and also code’s comment, it should be self-explanatory.

File : MyAndroidAppActivity.java

package com.mkyong.android;
 
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
 
public class MyAndroidAppActivity extends Activity {
 
  private Spinner spinner1, spinner2;
  private Button btnSubmit;
 
  @Override
  public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.main);
 
	addItemsOnSpinner2();
	addListenerOnButton();
	addListenerOnSpinnerItemSelection();
  }
 
  // add items into spinner dynamically
  public void addItemsOnSpinner2() {
 
	spinner2 = (Spinner) findViewById(R.id.spinner2);
	List<String> list = new ArrayList<String>();
	list.add("list 1");
	list.add("list 2");
	list.add("list 3");
	ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
		android.R.layout.simple_spinner_item, list);
	dataAdapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
	spinner2.setAdapter(dataAdapter);
  }
 
  public void addListenerOnSpinnerItemSelection() {
	spinner1 = (Spinner) findViewById(R.id.spinner1);
	spinner1.setOnItemSelectedListener(new 
CustomOnItemSelectedListener());
  }
 
  // get the selected dropdown list value
  public void addListenerOnButton() {
 
	spinner1 = (Spinner) findViewById(R.id.spinner1);
	spinner2 = (Spinner) findViewById(R.id.spinner2);
	btnSubmit = (Button) findViewById(R.id.btnSubmit);
 
	btnSubmit.setOnClickListener(new OnClickListener() {
 
	  @Override
	  public void onClick(View v) {
 
	    Toast.makeText(MyAndroidAppActivity.this,
		"OnClickListener : " + 
                "\nSpinner 1 : "+ String.valueOf(
spinner1.getSelectedItem()) + 
                "\nSpinner 2 : "+ String.valueOf(
spinner2.getSelectedItem()),
			Toast.LENGTH_SHORT).show();
	  }
 
	});
  }
}

File : CustomOnItemSelectedListener.java

package com.mkyong.android;
 
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
 
public class CustomOnItemSelectedListener implements 
OnItemSelectedListener {
 
  public void onItemSelected(AdapterView<?> parent, View view, 
int pos,long id) {
	Toast.makeText(parent.getContext(), 
		"OnItemSelectedListener : " + 
parent.getItemAtPosition(pos).toString(),
		Toast.LENGTH_SHORT).show();
  }
 
  @Override
  public void onNothingSelected(AdapterView<?> arg0) {
	// TODO Auto-generated method stub
  }
 
}

4. Demo

Run the application.

1. Result, two spinners are displayed :

android spinner demo1
android spinner demo2

2. Select “France” from spinner1, item selection listener is fired :

android spinner demo3

3. Select “list2″ from spinner2, and click on the submit button :

android spinner demo4

Download Source Code

How to get a custom error message from Web Api to jQuery.ajax?

This code uses the Microsoft Web Api Http stack and jQuery.

How do I get a custom error message, created by an HttpError parameter to CreateErrorResponse(), displayed by jQuery’s deferred.fail()?

An example of creating an error response for test purposes in an ApiController:

public HttpResponseMessage Post(Region region)
{
    var error = new HttpError("Failure to lunch.");
    return this.Request.CreateErrorResponse(
               HttpStatusCode.InternalServerError, 
               error);
}

Here’s a cut-down client that’s trying to find the error message to display, “Failure to lunch.”.

$.ajax({
    type: 'POST',
    url: 'api/region',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify(region)
})
.fail(function (jqXhr, textStatus, errorThrown) {
    alert(textStatus + ": " + errorThrown + ": " + jqXhr.responseText);
});

What will be displayed is:

“error: Internal Server Error: {full stack here}”

What I want instead is:

“Failure to lunch.”

Answer:

You could parse the responseText string and then use the Message property:

.fail(function (jqXhr, textStatus, errorThrown) {
    if (jqXhr.getResponseHeader('Content-Type').indexOf('application/json') > -1) {
        // only parse the response if you know it is JSON
        var error = $.parseJSON(jqXhr.responseText);
        alert(error.Message);
    } else {
        alert('Fatal error');
    }
});
This is where I’m getting confused. jqXhr.responseText.Message has the error message from the InternalServerError (“An error has occurred.”), not the custom message I put into HttpError. –  Boggin Aug 15 ’13 at 13:15
I made a mistake in my answer. You should use alert(error.Message) instead of alert(error).Message. The Message property will contain the text Failure to lunch.. I have just tested it and it worked fine. Could you show the value of jqXhr.responseText? –  Darin Dimitrov Aug 15 ’13 at 13:18
I was confused, it turns out, because my test case here was throwing another InternalServerError exception which was being returned before my CreateErrorResponse code was being hit. The Web API will comfortably cope with this in the absence of any try..catch code. You’re quite right, the Message property is what I needed. –  Boggin Aug 15 ’13 at 13:33
 

How to get HTTP response code for a URL in Java?

Original Post: http://stackoverflow.com/questions/6467848/how-to-get-http-response-code-for-a-url-in-java

URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();

int code = connection.getResponseCode();

This is by no means a robust example; you’ll need to handle IOExceptions and whatnot. But it should get you started.

http://docs.oracle.com/javase/6/docs/api/java/net/HttpURLConnection.html#getResponseCode%28%29

getRequestMethod

public String getRequestMethod()
Get the request method.
Returns:
the HTTP request method
See Also:
setRequestMethod(java.lang.String)

getResponseCode

public int getResponseCode()
                    throws IOException
Gets the status code from an HTTP response message. For example, in the case of the following status lines:

 HTTP/1.0 200 OK
 HTTP/1.0 401 Unauthorized

It will return 200 and 401 respectively. Returns -1 if no code can be discerned from the response (i.e., the response is not valid HTTP).

Returns:
the HTTP Status-Code, or -1
Throws:
IOException – if an error occurred connecting to the server.

getResponseMessage

public String getResponseMessage()
                          throws IOException
Gets the HTTP response message, if any, returned along with the response code from a server. From responses like:

 HTTP/1.0 200 OK
 HTTP/1.0 404 Not Found

Extracts the Strings “OK” and “Not Found” respectively. Returns null if none could be discerned from the responses (the result was not valid HTTP).

Returns:
the HTTP response message, or null
Throws:
IOException – if an error occurred connecting to the server.
URL url = new URL("http://www.google.com/humans.txt");
HttpURLConnection http = (HttpURLConnection)url.openConnection();
int statusCode = http.getResponseCode();
class ResponseCodeCheck 
{

    public static void main (String args[]) throws Exception
    {

        URL url = new URL("http://google.com");
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();

        int code = connection.getResponseCode();
        System.out.println("Response code of the object is "+code);
        if (code==200)
        {
            System.out.println("OK");
        }
    }
}
import java.io.IOException;
import java.net.URL;
import java.net.HttpURLConnection;

public class API{
    public static void main(String args[]) throws IOException
    {
        URL url = new URL("http://www.google.com");
        HttpURLConnection http = (HttpURLConnection)url.openConnection();
        int statusCode = http.getResponseCode();
        System.out.println(statusCode);
    }
}
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");

. . . . . . .

System.out.println("Value" + connection.getResponseCode());
             System.out.println(connection.getResponseMessage());
             System.out.println("content"+connection.getContent());

This is what worked for me:

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class UrlHelpers {

    public static int getHTTPResponseStatusCode(String u) throws IOException {

        URL url = new URL(u);
        HttpURLConnection http = (HttpURLConnection)url.openConnection();
        return http.getResponseCode();
    }
}

Hope this helps someone 🙂

Redirect and POST in ASP.NET

Original Post: http://www.codeproject.com/Articles/37539/Redirect-and-POST-in-ASP-NET

Introduction

Recently, I faced a situation where I have an application on which I needed to communicate with a third party payment application, where in some point, I will have to send information to that third party application using POST and not GET.

Background

Well, at first, that sounded easy, but that wasn’t the case at all. I worked on this heavily, Googled intensively, tried hard with no good solution to satisfy my desire. Let’s first see what our options are for submitting data (POST or GET) to a destination URL:

  1. Response.Redirect: This method is widely used and common, but it will only use the GET method in ASP.NET, and there is no way to do a POST using it.
  2. Server.Transfer: This method does a POST not GET, but … unfortunately, it will only work when the source and destination are in the same application; therefore, if you are sending a request to a third party application, this will not work … too bad :S
  3. Using HttpWebRequest: This is another method where you are creating the whole request from scratch, you specify the content, its type, write the data in a concatenated form of “&”, then convert to bytes and submit the request by calling the GetResponse() method … does it do a POST? Yes it does !!! Does it make a redirection to the destination UrRL? No, it doesn’t !!! Even so, you will render the response on the browser for the user and the user will see the destination page perfectly, but any action on this rendered page will end with tears since you are still referring to the same origin of the request … which is your application … so any postbacks on that page will end up displaying 404 .. Page Not Found. (Why? Remember that default postback behaviour is always to the page itself … that’s why Wink | ;) .)
  4. Using a WebClient: This method is my favourite of the listed ones … because it’s easy … create a WebClient object, give it the destination URL, call the UploadValues method which takes a name-value collection (in which all of your POST data is available), render the response, and everything is POSTed perfectly to the destination URL; but like the previous option, you are still in the same place, which is your application … so any postbacks on that page will end up displaying 404 … Page not Found.
  5. HTML Submit button with POST form: Well, this is the standard way of sending POST data to any URL, whether it is in your application or in a third party application, but this will restrict you to have a Submit button, e.g., <input type="submit"/>, and that one will not, of course, do any server side event for you!!! And in one way or another, you are forced to press that button at some point … no other way … too bad :S

Note: if you have other methods .. keep it … Wink | ;) I’ve had enough with what I have seen!

Now, let’s imagine that I have a Response.Redirect method to which I give a collection of data and I tell it to do a POST method instead of a GET method … wouldn’t that be wonderful? I think that will be great … really a simple wish! Smile | :)

Now, that’s the whole point, to have a method to which I give a collection of data to be submitted to the destination URL and then all data is POSTed with redirection.

Using the code

I am attaching a file with this article, which has a class called HttpHelper. This class has only two methods: a private method PreparePOSTForm and a public method RedirectAndPOST. Of course, you will be only using the public one; the private one is just for encapsulating a functionality needed for the public one … never mind … you only call the public one and voila … you are done!

Shown below is the use of this method:

NameValueCollection data = new NameValueCollection();
data.Add("v1", "val1");
data.Add("v2", "val2");
HttpHelper.RedirectAndPOST(this.Page, "http://DestUrl/Default.aspx", data);

v1 and v2 will be POSTed to the destination URL with redirection; redirection means that you will be redirected to the destination URL and any postbacks there will occur successfully since you are completely transferred there.

But, how does the RedirectAndPOST method work to do the desired trick?!

/// <summary>
/// POST data and Redirect to the specified url using the specified page.
/// </summary>
/// <param name="page">The page which will be the referrer page.</param>
/// <param name="destinationUrl">The destination Url to which
/// the post and redirection is occuring.</param>
/// <param name="data">The data should be posted.</param>
/// <Author>Samer Abu Rabie</Author>

public static void RedirectAndPOST(Page page, string destinationUrl, 
                                   NameValueCollection data)
{
//Prepare the Posting form
string strForm = PreparePOSTForm(destinationUrl, data);
//Add a literal control the specified page holding 
//the Post Form, this is to submit the Posting form with the request.
page.Controls.Add(new LiteralControl(strForm));
}

As you can see … we prepare the POST form which is an HTML form that holds the hidden fields of your POSTed data and a script tag which holds the submit operation of the form .. which will be executed immediately upon the postback.

Below is the code for the PreparePOSTForm method:

/// <summary>
/// This method prepares an Html form which holds all data
/// in hidden field in the addetion to form submitting script.
/// </summary>
/// <param name="url">The destination Url to which the post and redirection
/// will occur, the Url can be in the same App or ouside the App.</param>
/// <param name="data">A collection of data that
/// will be posted to the destination Url.</param>
/// <returns>Returns a string representation of the Posting form.</returns>
/// <Author>Samer Abu Rabie</Author>

private static String PreparePOSTForm(string url, NameValueCollection data)
{
    //Set a name for the form
    string formID = "PostForm";
    //Build the form using the specified data to be posted.
    StringBuilder strForm = new StringBuilder();
    strForm.Append("<form id=\"" + formID + "\" name=\"" + 
                   formID + "\" action=\"" + url + 
                   "\" method=\"POST\">");

    foreach (string key in data)
    {
        strForm.Append("<input type=\"hidden\" name=\"" + key + 
                       "\" value=\"" + data[key] + "\">");
    }

    strForm.Append("</form>");
    //Build the JavaScript which will do the Posting operation.
    StringBuilder strScript = new StringBuilder();
    strScript.Append("<script language="'javascript'">");
    strScript.Append("var v" + formID + " = document." + 
                     formID + ";");
    strScript.Append("v" + formID + ".submit();");
    strScript.Append("</script>");
    //Return the form and the script concatenated.
    //(The order is important, Form then JavaScript)
    return strForm.ToString() + strScript.ToString();
}

Really simple code … for each key value you want to POST, we create a hidden field, we create the form, we then add the script necessary to make the auto submit by calling vPostForm.submit() from the JavaScript code.

Points of Interest

Why put the generated form and script in a literal control and add that control to the requesting page?! Well … the idea basically is to have a form which makes an auto submit of the values by itself without triggering it … we created that form and its script …now we need to make it run … we do that by adding that piece of code to a Literal control on which we will display its contents with no tags! Yes … no tags … that’s the trick … so the form and script will be displayed in the request. Now, since we are posting back to the same page … the contents (our form and script) will run successfully. When it runs, the submit process happens and the auto-postback with our data occurs to the destination URL as we have specified Smile | :)

If I am asked what the drawbacks of this solution are, I would say maybe one drawback … which is that if the client is disabling JavaScript on the browser … then this wouldn’t work. I haven’t tried that … but I expect so … for me, this is a big step and an important solution that helps me a lot to solve a lot of problems Smile | :)

I hope I was clear enough in my explanation … since it requires a deep understanding of the ASP.NET page life cycle and understanding of the postback concepts of a page.

.NET: Check URL’s response status code?

What’s the easiest way in .NET to check what status code a web server replies with to a GET request?

public HttpStatusCode GetHeaders(string url)
    {
        HttpStatusCode result = default(HttpStatusCode);

        var request = HttpWebRequest.Create(url);
        request.Method = "HEAD";
        using (var response = request.GetResponse() as HttpWebResponse)
        {
            if (response != null)
            {
                result = response.StatusCode;
                response.Close();
            }
        }

        return result;
    }

Use the HTTP method HEAD, which is the same as GET except doesn’t return the body:

var request = (HttpWebRequest)WebRequest.Create("http://www.example.com");
request.Method = "HEAD";
var response = (HttpWebResponse)request.GetResponse();

// status code...
response.StatusCode;

If you use HttpWebRequest, it’s pretty easy:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://url");
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
HttpStatusCode status = response.StatusCode;

You can surround that with a blanket catch clause, or look at the docs for WebRequest.Create and .GetResponse to see what exceptions will get thrown.

I’ve ended up with this method which combines Ivan Ferić’s answer and with proper exceptional cases support:

public async Task<bool> IsAccessibleAsync (string url)
{
    if (url == null)
        throw new ArgumentNullException ("url");

    if (url.IndexOf (':') < 0)
        url = "http://" + url.TrimStart ('/');

    if (!Uri.IsWellFormedUriString (url, UriKind.Absolute))
        return false;

    var request = (HttpWebRequest) WebRequest.Create (url);
    request.Method = "HEAD";

    try
    {
        using (var response = await request.GetResponseAsync () as HttpWebResponse)
        {
            if (response != null && response.StatusCode == HttpStatusCode.OK)
                return true;

            return false;
        }
    }
    catch (WebException)
    {
        return false;
    }
}