Thursday, September 24, 2015

Laravel Global Variable for All Controller and Views

Hello,

Recently in one of my project we have an admin panel crated with Laravel. There was a requirement to setup global object that can be accessed in all controllers, views, models etc.  Basically it was logged in user object with additional information so we can access details of user in anywhere. Here in this blog I am going to explain how to do this.

First open app -> config -> filters.php file and add following code to it.

App::before(function($request)
{
    // Singleton (global) object
    App::singleton('app', function(){
        $app = new stdClass;
        if (Auth::check()) {
            // Put your User object in $app->user
            $app->user = Auth::User();
            $app->user_access = UserAccess::getAccess($app->user);
        }
        return $app;
    });
    $app = App::make('app');
    View::share('app', $app);
});


As you can see here we are setting filter to setup singleton object and checking if user is logged in or not. If he is logged in we are create global object with name app and setting user information there. Now you can access this in controller with following code. 

$app = App::make('app');
$user = $app->user;
$userAccess = $app->user_access;

And in view you can access in following way.

<div>Welcome {{$app->user->name}}</div>

Or you can use in if condition.

@if($app->user->access_level == "Admin")
@endif

Same way you can access it in model functions.

$app = App::make('app');
$user = $app->user;
$userAccess = $app->user_access;

Hope this helps you.

Wednesday, September 23, 2015

Upload File From Local Machine to Remote Server with SSH

Hello,

Recently while working on SSL on my Amazon EC 2 server I had to upload few certificates files from my local machine to EC 2 server. I had to spent some time to figure out this so thought of publishing blog on it so this may help others

First lets see how to upload file to remote server with permission on directory. We will use scp command for it. Following is the syntax.

$ scp /path/to/local/file sshuser@host:/path/to/remote/server

Once you run command it will prompt you for password. When you enter password it will upload file.

Now lets see what if you don't have password and have public or private key. Following is the command.

$ scp -i "yourkey" /path/to/local/file sshuser@host:/path/to/remote/server

If you have specified correct key it will upload your file.

Now here comes the real problem with EC 2. I was trying to upload crt file to system directory which was not allowed. So what you have to do is upload that file default ssh directory with following command

$ scp -i "yourkey" /path/to/local/file sshuser@host:filename

And then go to that directory. Usually in amazon EC 2. It's /home/ubntu directory. Then you can copy files from here using cp command with sudo.

I hope this helps you and dave your time.




Friday, September 18, 2015

Android Download and Save Image to Internal Memory

Hello,

Recently in one of my project. We have a requirement to download image from remote URL and save it to internal memory so every time image won't be downloaded but it will be displayed from internal memory.

First let's create a utility class and add static function to load and save image. Following is the UTIL class I used.

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class Utils {
    public static void saveFile(Context context, Bitmap b, String picName){ 
    FileOutputStream fos; 
    try
        fos = context.openFileOutput(picName, Context.MODE_PRIVATE); 
        b.compress(Bitmap.CompressFormat.PNG, 100, fos); 
        fos.close(); 
    }  
    catch (FileNotFoundException e) { 
        Log.d("file", "file not found"); 
        e.printStackTrace(); 
    }  
    catch (IOException e) { 
        Log.d("file", "io exception"); 
        e.printStackTrace(); 
    } 

}
    
    public static Bitmap loadBitmap(Context context, String picName){ 
    Bitmap b = null
    FileInputStream fis; 
    try
        fis = context.openFileInput(picName); 
        b = BitmapFactory.decodeStream(fis); 
        fis.close(); 

    }  
    catch (FileNotFoundException e) { 
        Log.d("file", "file not found"); 
        e.printStackTrace(); 
    }  
    catch (IOException e) { 
        Log.d("file", "io exception"); 
        e.printStackTrace(); 
    }  
    return b; 
}

}

As you can see above it has two functions one is to save image and one is to load saved image. Now first we will check if if image is already saved or not.

ImageView imgView = new Image(getActivity());
Bitmap b = Utils.loadBitmap(getActivity(),"myImage.png");
if(b == null){
       new DownloadImageTask(imgView,"myImage.png").execute("http://remoteimagepath");
}else{
      imgView.setImageBitmap(b);
}

Now we have to add DownloadImageTask class as follow.

private class DownloadImageTask extends AsyncTask {
ImageView imageView = null;
        String name = "";
public DownloadImageTask(ImageView img, String name) {
this.imageView = img;
                this.name = name;
}

protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}

protected void onPostExecute(Bitmap result) {
Utils.saveFile(getActivity(),result, this.name);
this.imageView.setImageBitmap(result);
}
}

As you can see above in this class we are passing reference of imageView and when image is downloaded we setup bitmap to imageview and save image to local memory with name which we passed in parameter. 

Hope this helps you.

Monday, September 14, 2015

Amazon EC2 File Upload Permission

Hello,

Recently in one of my project we hosted our PHP website on Amazon EC 2 which was running Apache on ubuntu. In our project we have file upload functionality which was not working. First I tired to set permission to 777 for the upload directory but still it was not working, so I went into details and found out this was the user permission issue. In this blog I am going to explain how to solve this.

Your website is running in Apache on Ubuntu. So there is a apache user, which is actually handling file operations. By default apache user does not have write permission and it does not own your website folder. So there are three basic steps to resolve this issue.

1) Find out your apache user.

Fist we have to find out name of apache user. Run following command in terminal.


ps -ef | grep apache

Check the left most column of the output. See the image below. That is name of your apache user.

In my case it was www-data user. 

2) Change directory owner to Apache user.

Change owner of your upload directory.

sudo chown www-data /var/www/html/uploads

3) Setup permission on your directory.

sudo chmod 755 /var/www/html/uploads

That's it. Now you can upload file from your web application. Hope this helps you and save your time.





Saturday, September 12, 2015

How to Create a Horizontal Carousel View in Android (Using ViewPager)

Hello,

Recently in one of my project we have to create  Horizontal Carousel View for banner images. User can swipe left or right to view other banners and there will be bottom page indicators. See the below image of final output.


In this blog I am going to explain how to create horizontal carousel view. We are going to use Android ViewPager for this. First add following to layout XML.

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/viewpager"
    android:layout_width="fill_parent"
    android:layout_height="120dp" />
     
     <LinearLayout
     android:layout_width="fill_parent"
     android:id="@+id/pagination"
     android:layout_height="15dp"
     android:background="#443915"
     android:orientation="horizontal" 
     android:gravity="center">
    </LinearLayout>

In android view page we will have different fragments for each page so we will need layout XML for fragment. Add new XML file myfragment_layout.xml in your layout and add following code to it.

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

        android:id="@+id/imageView" />

Now let's create fragments for each images.

List fList = new ArrayList();
List bannerList = getAllBanners(); 
LinearLayout pagination = (LinearLayout)rootView.findViewById(R.id.pagination);

getAllBanners () is the function I used my code, you can replace it with your logic.
pagination is the linear layout we added in XML above.

Now first create a linear layout to hold all the indicators.

LinearLayout layout = new LinearLayout(getActivity());
layout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
layout.setOrientation(LinearLayout.HORIZONTAL);

for(int i=0;i
          fList.add(new MyFragment().newInstance(bannerList.get(i).getPicName()));
          ImageView imageView = new ImageView(getActivity());
          if(i == 0){
              imageView.setImageResource(R.drawable.activeindicators);
          }else{
              imageView.setImageResource(R.drawable.inactiveindicators);
          }
          imageView.setId(i);
          LayoutParams params =new LayoutParams(LayoutParams.WRAP_CONTENT,     LayoutParams.WRAP_CONTENT);
          imageView.setLayoutParams(params);
          layout.addView(imageView);
}

pagination.addView(layout);

As you can in above code we are adding indicators in pagination and adding fragments to fragment list. By default we are setting first indicator as active.

Now to create Fragment we have to add MyFragment class.

public class MyFragment extends Fragment {
    public static final String EXTRA_MESSAGE = "PICTURE";
    public final MyFragment newInstance(String picName){
      MyFragment f = new MyFragment();
      Bundle bdl = new Bundle(1);
      bdl.putString(EXTRA_MESSAGE, picName);
      f.setArguments(bdl);
      return f;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
      String picName = getArguments().getString(EXTRA_MESSAGE);
      View v = inflater.inflate(R.layout.myfragment_layout, container, false);
      ImageView messageTextView = (ImageView)v.findViewById(R.id.imageView);
      int id = getResources().getIdentifier("yourpackagename:drawable/" + picName, null, null);
      v.setImageResource(id);
      return v;
    }
}

Now lets's create Adapter for ViewPager. 

MyPageAdapter  pageAdapter = new MyPageAdapter(getActivity().getSupportFragmentManager(), fList);
ViewPager pager =(ViewPager)rootView.findViewById(R.id.viewpager);
pager.setAdapter(pageAdapter);

For that we have to create MyPageAdapter

class MyPageAdapter extends FragmentPagerAdapter {
      private List fragments;
      public MyPageAdapter(FragmentManager fm, List fragments) {
        super(fm);
        this.fragments = fragments;
      }
      @Override 
      public Fragment getItem(int position) {
        return this.fragments.get(position);
      }
      @Override
      public int getCount() {
        return this.fragments.size();
      }
 }

This will create number of fragments as per your number. Now we have to add logic to change page indicators when user swipe left or right.

pager.setOnPageChangeListener(new OnPageChangeListener() {
  @Override
   public void onPageSelected(int position) {
   // TODO Auto-generated method stub
        for(int i=0 ;i<totalBannerCount;i++){
        ImageView img = (ImageView)rootView.findViewById(i);
        if(i== position){
            img.setImageResource(R.drawable.activeindicators);
        }else{
            img.setImageResource(R.drawable.inactiveindicators);
        }
    }
}
  @Override
   public void onPageScrolled(int arg0, float arg1, int arg2) {
      // TODO Auto-generated method stub
   }
   @Override
    public void onPageScrollStateChanged(int arg0) {
    // TODO Auto-generated method stub
    }
});

That's it and you have Horizontal Carousel View in Android. Hope this helps you.

Wednesday, September 9, 2015

Android How to Work With AutoCompleteTextView

Hello,

Recently in one of my project I have to create auto complete text view in android. In this blog I am going to explain how to work with it.

First you have to add AutoCompleteTextView in your layout XML file.

<AutoCompleteTextView  
        android:id="@+id/autoCompleteLocationTextView"  
        android:layout_width="fill_parent"  
        android:layout_height="60dp"  
        android:ems="10"  

        android:hint="Type to Search">

Then in your activity get reference of it.

AutoCompleteTextView  locationText = (AutoCompleteTextView)findViewById(R.id.autoCompleteLocationTextView);

Then set threshold for it.

locationText.setThreshold(1); 

Here we set threshold to 1 that means after typing first character it will show you matched suggestions. You can change it as per your requirement.

Then we have to set an adapter. Adapter is nothing but it's a collections of your suggestions.


String[] locationListArray = {
    "Ahmedabad",
    "Ahmednagar",
    "Agartala",
    "Mumbai",
    "Noida",
    "Kolkata"
}

ArrayAdapter adapter1 = new ArrayAdapter  
            (this,android.R.layout.select_dialog_item,locationListArray);

locationText.setAdapter(adapter1);

As you can see above we have loaded our collections in array and created adapter from it and assigned adapter to locationList. That's it now it will show you suggestions as soon as you start typing it.

If you want to get value of it on change. You can do following.

locationText.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView arg0, View arg1, int position,
                    long arg3) {
            String item = (String)arg0.getItemAtPosition(position);
});

Hope this helps you.

Introducing Tagsum - GPS Location Tagging

Hello,

This blog is about my company's product. After we introduced following two products.

Adsum
Tracksum

Here is our next product Tagsum - GPS Location Tagging. This app is helpful in tagging the required location with exact latitude and longitude.

This app is helpful in tagging the required location with exact latitude and longitude of the desired location. Very useful app for field survey in remote locations. You don't need special GPS devices to locate locations now. If you have smart phone just install this app and use it. It uses standard GPS services so you get very accurate locations. Locations added with this app can be downloaded in excel files later from admin panel.

Also in admin panel you can create routes with tagged location and can plot path on Google map with standard markings.

Also you can preload your locations in app and tag it with latitude and longitude from the application. So you can update your locations or add new locations.  This application can be used in various domains and fields like.

Field Survey
Geological Survey
Map building.
City Paths Creation etc..

Major benefit of our app is that you will get admin panel where you can maintain your app users, you can add/update/delete users, can see tagged locations, can create add new locations for tagging, can create paths. When you create path it will also calculate total kms for the path. This gives you much more flexibility. Your data will be confidential and only you can see that in admin panel.

So if you need this app please install app from Google Play Store. App is available from following link.

https://play.google.com/store/apps/details?id=com.tagsum.app&hl=en

And get back to us for admin panel access.