Author:- Tushar Sonu Lambole
1. Before start this steps will require UnityPlayer classes.Jar
in Mac will find at location "/Applications/Unity/Unity.app/Contents/PlaybackEngines/
AndroidPlayer/bin"
2. Right-click on the project in Eclipse, go to Properties > Java Build Path > Libraries
3. Create new classActivity paste the following code
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;
import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;
public class RootActivity extends UnityPlayerActivity {
static UnityPlayerActivity instance;
public static UnityPlayerActivity getInstance() {
return instance;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
instance = this;
super.onCreate(savedInstanceState);
}
public void showMessage(final String message) {
this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(RootActivity.this, message, Toast.LENGTH_LONG)
.show();
}
});
}
public void SocialMessageAdvanced(String message, String subject,
String url, String img) {
//showMessage(img);
Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND);
if (url != null && url.length() > 0) {
if (message == null) {
message = url;
} else {
message = message + " " + url;
}
}
try {
doSendIntent(message, subject, img);
} catch (IOException e) {
e.printStackTrace();
}
UnityPlayer.currentActivity.startActivity(sendIntent);
}
private void doSendIntent(String text, String subject, String image)
throws IOException {
final Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND);
if (text != null && text.length() > 0) {
sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, text);
}
if (subject != null && subject.length() > 0) {
sendIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
}
if (image != null && image.length() > 0) {
sendIntent.setType("image/*");
sendIntent.putExtra(Intent.EXTRA_STREAM,
Uri.fromFile(new File(image)));
UnityPlayer.currentActivity.startActivity(sendIntent);
} else {
sendIntent.setType("text/plain");
UnityPlayer.currentActivity.startActivity(sendIntent);
}
}
public void SocialMessage(String message) {
Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);
UnityPlayer.currentActivity.startActivity(sendIntent);
}
}
4. Right click on project and export as JAR file.
5. Open Unity3D application and paste the JAR from step 4 at location Assets/Plugins/Andoid
6. Open AndroidManifest.xml of unity3D file and make the changes as follows.
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.qualcomm.QCARUnityPlayer"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<uses-feature android:name="android.hardware.camera" />
<supports-screens
android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:anyDensity="true" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:icon="@drawable/app_icon"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:debuggable="false">
<activity android:name="com.qualcomm.QCARUnityPlayer.QCARPlayerProxyActivity"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|
orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
</activity>
<activity android:name="com.qualcomm.QCARUnityPlayer.QCARPlayerActivity"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|
orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
</activity>
<activity android:name="com.qualcomm.QCARUnityPlayer.QCARPlayerNativeActivity"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|
orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
<meta-data android:name="android.app.lib_name" android:value="unity" />
<meta-data android:name="unityplayer.ForwardNativeEventsToDalvik" android:value="false" />
</activity>
<activity android:name="com.unity3d.player.VideoPlayer"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|
orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
</activity>
<activity
android:name="com.tushar.androidunityplugin. RootActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
7. Create new c# script in Unity3D as "AndroidMapInterface"
using UnityEngine;
using System.Collections;
public class AndroidMapInterface : MonoBehaviour {
// Use this for initialization
void Start () {
//Initialize AndroidBridge
AndroidBridge.Initialize();
//Register Action
AndroidBridge.OnXploarShowEvent += onXploarShowEvent;
}
public void CallSocialShare(string text)
{
AndroidBridge.CallSocialShare(text);
}
public void CallSocialShareAdvanced(string text, string subject, string url, string img)
{
AndroidBridge.CallSocialShareAdvanced(text, subject,url,img);
}
void onXploarShowEvent(string eventStr){
Debug.Log("AndroidXploarInterface - onXploarShowEvent:"+eventStr);
}
void OnDestroy() {
AndroidBridge.OnXploarShowEvent -= onXploarShowEvent;
}
}
8. Create new C# script paste code
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
using System;
public class AndroidBridge : MonoBehaviour {
public static event Action<string> OnXploarShowEvent;
#if UNITY_IPHONE
public struct ConfigStruct
{
public string tittle;
public string message;
}
[DllImport ("__Internal")] private static extern void showAlertMessage(ref ConfigStruct conf);
#endif
// Init the class instance
static AndroidBridge instance;
public static void Initialize()
{
Debug.Log("Application Init");
if (instance == null)
{
GameObject newGameObject = new GameObject("XploarBridge");
newGameObject.AddComponent<AndroidBridge>();
instance = newGameObject.GetComponent<AndroidBridge>();
}
}
//Callback from Java or Objective-C which notifies an event
//param : "EVENT_OPENED", "EVENT_CLOSED"
//Method name starts small "o" and Event name is capital "O"
void onXploarShowEvent(string eventStr){
//Debug.Log("EasyCodeScanner - onScannerEvent eventStr=:"+eventStr);
if (OnXploarShowEvent != null)
{
OnXploarShowEvent(eventStr);
}
}
public static void CallSocialShare(string defaultTxt)
{
if (instance==null)
{
Debug.Log("instance is null");
Debug.LogError("AndroiddBridge - launchSilverpointMap error : ScriptObject must be initialized before.");
return;
}
#if UNITY_ANDROID
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
//Invoke the "SocialMessage" method in our Android Plugin Activity
jo.Call("SocialMessage", defaultTxt);
#endif
#if UNITY_IPHONE
//IPHONE - Display the UIViewController
ConfigStruct conf = new ConfigStruct();
conf.tittle = "Alert Message Tittle";
conf.message = "First Attempt to call IOS plugin";
showAlertMessage(ref conf);
#endif
}
public static void CallSocialShareAdvanced(string defaultTxt, string subject, string url, string img)
{
if (instance==null)
{
Debug.Log("instance is null");
Debug.LogError("AndroiddBridge - error : ScriptObject must be initialized before.");
return;
}
#if UNITY_ANDROID
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
//Invoke the "SocialMessage" method in our Android Plugin Activity
jo.Call("SocialMessageAdvanced", defaultTxt, subject, url, img);
#endif
}
}
9. Attach "AndroidMapInterface" script to the any gameobject
10. Call the methods as follows
AndroidMapInterface androidInterface = objectHavingScript.GetComponent<AndroidMapInterface>();
androidInterface.CallSocialShareAdvanced("Text",
"Subject","https://play.google.com/store/apps/details?id=com.tushar.ARBattleTank",
Application.persistentDataPath+"/Pic.jpg");
IOS Native plugin for Unity3D
Author:- Tushar Sonu Lambole
1. In xcode project create new File as File-->New-->File..
Select Cocoa Touch in left panel, in right panel Select "Objective-C class"
2. Click Next Name file as "XploarIOSPlugin" You can Use any file name just remember to rename "XploarIOSPlugin" to your file name in below code.
3. Open "XploarIOSPlugin.h" file and paste the below code
#import "UnityAppController.h"
@interface XploarIOSPlugin : UIViewController
{
UINavigationController *navController;
}
struct ConfigStruct {
char* tittle;
char* message;
};
struct SocialSharingStruct {
char* text;
char* url;
char* image;
char* subject;
};
#ifdef __cplusplus
extern "C" {
#endif
void showAlertMessage(struct ConfigStruct *confStruct);
void showSocialSharing(struct SocialSharingStruct *confStruct);
#ifdef __cplusplus
}
#endif
@end
4. Open "XploarIOSPlugin.mm" file and paste the below code
#import "XploarIOSPlugin.h"
@implementation XploarIOSPlugin{
}
//Grab the Unity3D ViewController (UnityGetGLViewController())
#ifdef UNITY_4_0
//Unity4
#import "iPhone_View.h"
#else
//Unity3.5
extern UIViewController* UnityGetGLViewController();
#endif
+(id) withTittle:(char*)tittle withMessage:(char*)message{
return [[XploarIOSPlugin alloc] withTittle:tittle withMessage:message];
}
-(id) withTittle:(char*)tittle withMessage:(char*)message{
self = [super init];
if( !self ) return self;
@implementation XploarIOSPlugin{
}
//Grab the Unity3D ViewController (UnityGetGLViewController())
#ifdef UNITY_4_0
//Unity4
#import "iPhone_View.h"
#else
//Unity3.5
extern UIViewController* UnityGetGLViewController();
#endif
+(id) withTittle:(char*)tittle withMessage:(char*)message{
return [[XploarIOSPlugin alloc] withTittle:tittle withMessage:message];
}
-(id) withTittle:(char*)tittle withMessage:(char*)message{
self = [super init];
if( !self ) return self;
ShowAlertMessage([[NSString alloc] initWithUTF8String:tittle], [[NSString alloc] initWithUTF8String:message]);
return self;
}
void ShowAlertMessage (NSString *tittle, NSString *message){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:tittle
message:message
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
[alert show];
}
+(id) withText:(char*)text withURL:(char*)url withImage:(char*)image withSubject:(char*)subject{
return [[XploarIOSPlugin alloc] withText:text withURL:url withImage:image withSubject:subject];
}
-(id) withText:(char*)text withURL:(char*)url withImage:(char*)image withSubject:(char*)subject{
self = [super init];
if( !self ) return self;
NSString *mText = [[NSString alloc] initWithUTF8String:text];
NSString *mUrl = [[NSString alloc] initWithUTF8String:url];
NSString *mImage = [[NSString alloc] initWithUTF8String:image];
NSString *mSubject = [[NSString alloc] initWithUTF8String:subject];
NSMutableArray *items = [NSMutableArray new];
if(mText != NULL && mText.length > 0){
[items addObject:mText];
}
if(mUrl != NULL && mUrl.length > 0){
NSURL *formattedURL = [NSURL URLWithString:mUrl];
[items addObject:formattedURL];
}
if(mImage != NULL && mImage.length > 0){
// For image from Web Url
if([mImage hasPrefix:@"http"])
{
NSURL *urlImage = [NSURL URLWithString:mImage];
// NSLog(@"Enter urlImage");
NSData *dataImage = [NSData dataWithContentsOfURL:urlImage];
// NSLog(@"Enter data %d",dataImage.length);
UIImage *imageFromUrl = [UIImage imageWithData:dataImage];
// NSLog(@"Enter data %f",imageFromUrl.size.height);
[items addObject:imageFromUrl];
}else{
// For image in local storage
NSFileManager *fileMgr = [NSFileManager defaultManager];
// Point to Document directory
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *imagePath = [[documentsDirectory stringByAppendingString:@"/"] stringByAppendingString:mImage];
// NSLog(@"Image Path %@",imagePath);
if([fileMgr fileExistsAtPath:imagePath]){
NSData *dataImage = [NSData dataWithContentsOfFile:imagePath];
// NSLog(@"Enter data %d",dataImage.length);
UIImage *imageFromUrl = [UIImage imageWithData:dataImage];
// NSLog(@"Enter data %f",imageFromUrl.size.height);
[items addObject:imageFromUrl];
}else{
ShowAlertMessage(@"Error", @"Cannot find image");
}
}
}
UIActivityViewController *activity = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:Nil];
[activity setValue:mSubject forKey:@"subject"];
UIViewController *rootViewController = UnityGetGLViewController();
[rootViewController presentViewController:activity animated:YES completion:Nil];
return self;
}
# pragma mark - C API
XploarIOSPlugin* instance;
void showAlertMessage(struct ConfigStruct *confStruct) {
instance = [XploarIOSPlugin withTittle:confStruct->tittle withMessage:confStruct->message];
}
}
void showSocialSharing(struct SocialSharingStruct *confStruct) {
instance = [XploarIOSPlugin withText:confStruct->text withURL:confStruct->url withImage:confStruct->image withSubject:confStruct->subject];
}
@end
Here your IOS code part ends. Copy the both the files "XploarIOSPlugin.h" and "XploarIOSPlugin.m" and paste at the location /Assets/Plugins/iOS of your Unity3D project.
---- In Unity3d ----------
1. Create new c# script name it as "IOSBridge" and paste the below cod
#if UNITY_IPHONE
public struct ConfigStruct
{
public string tittle;
public string message;
}
[DllImport ("__Internal")] private static extern void showAlertMessage(ref ConfigStruct conf);
public struct SocialSharingStruct
{
public string text;
public string url;
public string image;
public string subject;
}
[DllImport ("__Internal")] private static extern void showSocialSharing(ref SocialSharingStruct conf);
#endif
public static void CallSocialShare(string title, string message)
{
#if UNITY_IPHONE
//IPHONE - Display the UIViewController
ConfigStruct conf = new ConfigStruct();
conf.tittle = title;
conf.message = message;
showAlertMessage(ref conf);
#endif
}
public static void CallSocialShareAdvanced(string defaultTxt, string subject, string url, string img)
{
#if UNITY_IPHONE
//IPHONE - Display the UIViewController
SocialSharingStruct conf = new SocialSharingStruct();
conf.text = defaultTxt;
conf.url = url;
conf.image = img;
conf.subject = subject;
showSocialSharing(ref conf);
#endif
}
2. Call above method CallSocialShare("This is Alert Tittle"," This is Message Text");
CallSocialShareAdvanced("AR Battle Tank"," AR Battle Tank Application link","https://play.google.com/store/apps/details?id=com.tushar.ARBattleTank","01.jpg");
"01.jpg" can be replace with any web url of image like
"http://blog.gettyimages.com/wp-content/uploads/2013/01/Siberian-Tiger-Running-Through-Snow-Tom-Brakefield-Getty-Images-200353826-001.jpg"
Python Basics
Author:- Tushar Sonu Lambole
-------------------------------------------------------------------------------
1. Activate the virtualEnvi
Step A. Open terminal and go to the path of VirtualEnvi
$ cd /Users/tusharlambole/Documents/Development/Projects/DjangoProjects/PycharmProjects/VirtualEnviAR/bin
Step B. Activate the Virtual Envi
$ source activate
Step C. Go to the package folder which have to install
$ cd /Users/tusharlambole/Documents/Development/TusharHelpDesk/AR\ Python\ CMS\ Related/python-vuforia-master
Step D. install package in Virtual Envi
(VirtualEnviAR)Tushars-Mac-mini:python-vuforia-master tusharlambole$ sudo /Users/tusharlambole/Documents/Development/Projects/DjangoProjects/PycharmProjects/VirtualEnviAR/bin/python setup.py install
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
1. Activate the virtualEnvi
Step A. Open terminal and go to the path of VirtualEnvi
$ cd /Users/tusharlambole/Documents/Development/Projects/DjangoProjects/PycharmProjects/VirtualEnviAR/bin
Step B. Activate the Virtual Envi
$ source activate
Step C. Go to the package folder which have to install
$ cd /Users/tusharlambole/Documents/Development/TusharHelpDesk/AR\ Python\ CMS\ Related/python-vuforia-master
Step D. install package in Virtual Envi
(VirtualEnviAR)Tushars-Mac-mini:python-vuforia-master tusharlambole$ sudo /Users/tusharlambole/Documents/Development/Projects/DjangoProjects/PycharmProjects/VirtualEnviAR/bin/python setup.py install
-------------------------------------------------------------------------------
Django Model creation Basics
Author:- Tushar Sonu Lambole
This post includes the basics of Model creation in Django
1. AutoIncrement and primary field
class ProjectMaster(models.Model):
p_id = models.AutoField(primary_key=True)
2. Display text for model fields
class ProjectMaster(models.Model):
p_name = models.CharField(verbose_name='Project Name', max_length=150)
3. Ordering the data in admin view
class ProjectMaster(models.Model):
class Meta:
ordering = ('-p_date',)
4. Display model in admin site
class ProjectMasterAdmin(admin.ModelAdmin):
list_display = ('p_id','p_name','p_description','p_date')
admin.site.register(ProjectMaster, ProjectMasterAdmin)
5. Foreign Key
class ClientMaster(models.Model):
c_id = models.AutoField(primary_key=True)
p_fk = models.ForeignKey(ProjectMaster,verbose_name='Project')
6. ImageUploader with validation for ".png" extension and Dynamic ImagePath
class ClientMaster(models.Model):
c_name = models.CharField(max_length=150,verbose_name='Name')
def image_path(instance, filename):
return os.path.join('ImagesFiles', str(instance.c_name), str(instance.c_name)+'.png')
def validate_file_extension(value):
if not value.name.endswith('.png'):
raise ValidationError(u'Error: Only .Png files')
7. View uploaded images
A) in settings.py
MEDIA_ROOT = '/Users/tusharlambole/Documents/Development/Projects/DjangoProjects/PycharmProjects/TusharWebApp/'
MEDIA_URL = 'http://127.0.0.1:8000/'
B) in Url.py
urlpatterns = patterns('',
url(r'^(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)
This post includes the basics of Model creation in Django
1. AutoIncrement and primary field
class ProjectMaster(models.Model):
p_id = models.AutoField(primary_key=True)
2. Display text for model fields
class ProjectMaster(models.Model):
p_name = models.CharField(verbose_name='Project Name', max_length=150)
class ProjectMaster(models.Model):
class Meta:
ordering = ('-p_date',)
4. Display model in admin site
class ProjectMasterAdmin(admin.ModelAdmin):
list_display = ('p_id','p_name','p_description','p_date')
admin.site.register(ProjectMaster, ProjectMasterAdmin)
5. Foreign Key
class ClientMaster(models.Model):
c_id = models.AutoField(primary_key=True)
p_fk = models.ForeignKey(ProjectMaster,verbose_name='Project')
class ClientMaster(models.Model):
c_name = models.CharField(max_length=150,verbose_name='Name')
return os.path.join('ImagesFiles', str(instance.c_name), str(instance.c_name)+'.png')
def validate_file_extension(value):
if not value.name.endswith('.png'):
raise ValidationError(u'Error: Only .Png files')
c_logo = models.ImageField(upload_to=image_path, validators=[validate_file_extension],verbose_name='Logo Image')
A) in settings.py
MEDIA_ROOT = '/Users/tusharlambole/Documents/Development/Projects/DjangoProjects/PycharmProjects/TusharWebApp/'
MEDIA_URL = 'http://127.0.0.1:8000/'
B) in Url.py
urlpatterns = patterns('',
url(r'^(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)
Django - Rest - API
Author- Tushar Sonu Lambole
Installed packages
1) Django
2) PIL (for image related)
3) Django Rest framework (for Rest APIs)
4) pip
5) South (for database alterations)
1. To view the table in sqlite database python
AR App
models.py
__author__ = 'tusharlambole'
from django.db import models
from django.contrib import admin
import os
class ProjectMaster(models.Model):
p_id = models.AutoField(primary_key=True)
p_name = models.CharField(max_length=150)
p_description = models.TextField()
p_date = models.DateTimeField()
def __unicode__(self):
return (self.p_name)
class Meta:
ordering = ('-p_date',)
class ProjectMasterAdmin(admin.ModelAdmin):
list_display = ('p_id','p_name','p_description','p_date')
admin.site.register(ProjectMaster, ProjectMasterAdmin)
class ClientMaster(models.Model):
c_id = models.AutoField(primary_key=True)
p_fk = models.ForeignKey(ProjectMaster)
c_name = models.CharField(max_length=150)
def image_path(instance, filename):
return os.path.join('ImagesFiles', str(instance.c_name), str(instance.c_name)+'.png')
c_access_key = models.CharField(max_length=150)
c_secret_key = models.CharField(max_length=150)
c_is_active = models.BooleanField(default=False)
c_logo = models.ImageField(upload_to=image_path)
def __unicode__(self):
return (self.c_name)
class Meta:
ordering = ('c_id',)
class ClientMasterAdmin(admin.ModelAdmin):
list_display = ('c_id','c_name','c_is_active','c_logo')
admin.site.register(ClientMaster,ClientMasterAdmin)
----------------------------------------------------------------------------------------------------
urls.py
from django.conf.urls import patterns, include, url
from FirstSite.views import archieve
urlpatterns = patterns('',url(r'^$',archieve),)
----------------------------------------------------------------------------------------------------
views.py
from django.shortcuts import render
from django.template import loader, Context
from django.http import HttpResponse
from FirstSite.models import BlogPost
def archieve(request):
posts = BlogPost.objects.all()
t = loader.get_template("archive.html")
c = Context({ 'posts': posts })
return HttpResponse(t.render(c))
Installed packages
1) Django
2) PIL (for image related)
3) Django Rest framework (for Rest APIs)
4) pip
5) South (for database alterations)
1. To view the table in sqlite database python
python manage.py shelldb
SELECT * FROM sqlite_master WHERE type='table';
DROP TABLE appname_modelname
.exit
2. Drops and re-creates the tables used by the models of this app.python manage.py reset app_name
----------------------------------------------------------------------------------------------------AR App
models.py
__author__ = 'tusharlambole'
from django.db import models
from django.contrib import admin
import os
class ProjectMaster(models.Model):
p_id = models.AutoField(primary_key=True)
p_name = models.CharField(max_length=150)
p_description = models.TextField()
p_date = models.DateTimeField()
def __unicode__(self):
return (self.p_name)
class Meta:
ordering = ('-p_date',)
class ProjectMasterAdmin(admin.ModelAdmin):
list_display = ('p_id','p_name','p_description','p_date')
admin.site.register(ProjectMaster, ProjectMasterAdmin)
class ClientMaster(models.Model):
c_id = models.AutoField(primary_key=True)
p_fk = models.ForeignKey(ProjectMaster)
c_name = models.CharField(max_length=150)
def image_path(instance, filename):
return os.path.join('ImagesFiles', str(instance.c_name), str(instance.c_name)+'.png')
c_access_key = models.CharField(max_length=150)
c_secret_key = models.CharField(max_length=150)
c_is_active = models.BooleanField(default=False)
c_logo = models.ImageField(upload_to=image_path)
def __unicode__(self):
return (self.c_name)
class Meta:
ordering = ('c_id',)
class ClientMasterAdmin(admin.ModelAdmin):
list_display = ('c_id','c_name','c_is_active','c_logo')
admin.site.register(ClientMaster,ClientMasterAdmin)
----------------------------------------------------------------------------------------------------
serializers.py
from models import ProjectMaster,ClientMaster
from rest_framework import serializers
class ProjectMasterSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = ProjectMaster
fields = ('p_name','p_description','p_date')
class ClientMasterSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = ClientMaster
fields = ('c_id','c_name','c_is_active','p_fk','c_access_key','c_secret_key','c_logo')
----------------------------------------------------------------------------------------------------
views.py
__author__ = 'tusharlambole'
from models import ProjectMaster,ClientMaster
from serializers import ProjectMasterSerializer,ClientMasterSerializer
from rest_framework import viewsets
class ProjectMasterViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = ProjectMaster.objects.all()
serializer_class = ProjectMasterSerializer
class ClientMasterViewSet(viewsets.ModelViewSet):
queryset = ClientMaster.objects.all()
serializer_class = ClientMasterSerializer
----------------------------------------------------------------------------------------------------
settings.py
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'FirstSite',
'rest_framework',
'AR',
'south',
)
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',),
'PAGINATE_BY': 10
}
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'
----------------------------------------------------------------------------------------------------
urls.py
from django.conf.urls import patterns, include, url
from FirstSite.views import archieve,GroupViewSet,UserViewSet
from rest_framework import routers
from AR.views import ProjectMasterViewSet,ClientMasterViewSet
from django.contrib import admin
admin.autodiscover()
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
router.register(r'groups', GroupViewSet)
router.register(r'projectmaster', ProjectMasterViewSet)
router.register(r'clientmaster', ClientMasterViewSet)
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'TusharWebApp.views.home', name='home'),
url(r'^blog/', include('FirstSite.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
)
----------------------------------------------------------------------------------------------------
FirstSite App
templates/base.html
<html>
<style type="text/css">
body { color: #efd; background: #453; padding: 0 5em; margin: 0 } h1 { padding: 2em 1em; background: #675 }
h2 { color: #bf8; border-top: 1px dotted #fff; margin-top: 2em } p { margin: 1em 0 }
</style>
<body>
<h1>Tushar Sonu Lambole</h1>
{% block content %}
{% endblock %}
</body>
</html>
----------------------------------------------------------------------------------------------------
templates/archieve.html
{% extends "base.html" %}
{% block content %}
{% for post in posts %}
<h2>{{ post.title }}
</h2> <p>{{ post.timestamp|date:"l, F jS" }}</p>
<p>{{ post.body }}</p>
{% endfor %}
{% endblock %}
----------------------------------------------------------------------------------------------------
models.py
from django.db import models
from django.contrib import admin
# Create your models here.
class BlogPost(models.Model):
title = models.CharField(max_length=150)
body = models.TextField()
timestamp = models.DateTimeField()
class Meta:
ordering = ('-timestamp',)
class BlogPostAdmin(admin.ModelAdmin):
list_display = ('title','timestamp')
admin.site.register(BlogPost, BlogPostAdmin)
urls.py
from django.conf.urls import patterns, include, url
from FirstSite.views import archieve
urlpatterns = patterns('',url(r'^$',archieve),)
----------------------------------------------------------------------------------------------------
views.py
from django.shortcuts import render
from django.template import loader, Context
from django.http import HttpResponse
from FirstSite.models import BlogPost
def archieve(request):
posts = BlogPost.objects.all()
t = loader.get_template("archive.html")
c = Context({ 'posts': posts })
return HttpResponse(t.render(c))
Photoshop Basics
Author:- Tushar Sonu Lambole
I am new to Photoshop. My first exercise in Photoshop. will update when will learn new things.
Q1. How to create transparent background image with height and width of 512 pixels using Photoshop?
1. Make Image transparent
=> A. Click and Hold on eraser tool
B. Select "Magic eraser" option
C. Click on the image area to make it transparent.
2. Move Image
=> A. ctrl + T
3. Resize image
=> A. Select File option
B. Select "Save for Web..."
C. Select "PNG-24" from dropdown
D. Check "Transparency" checkBox
E. In Image Size panel W="512", H="512"
F. click "Save"
I am new to Photoshop. My first exercise in Photoshop. will update when will learn new things.
Q1. How to create transparent background image with height and width of 512 pixels using Photoshop?
1. Make Image transparent
=> A. Click and Hold on eraser tool
B. Select "Magic eraser" option
C. Click on the image area to make it transparent.
2. Move Image
=> A. ctrl + T
3. Resize image
=> A. Select File option
B. Select "Save for Web..."
C. Select "PNG-24" from dropdown
D. Check "Transparency" checkBox
E. In Image Size panel W="512", H="512"
F. click "Save"
Unity3D - Mobile device Touch click and redirection to links
Author:- Tushar Sonu Lambole
1) This blog includes the sample code for Unity3d project to handle touch event on the mobile devices.
2) Call SetSocialLinks method
public class SocialLinks : MonoBehaviour {
private Vector2 mTouchStartPos;
private bool mTouchMoved = false;
private float mTimeElapsed = 0.0f;
private bool mTapped = false;
private float mTimeElapsedSinceTap = 0.0f;
public GameObject FacebookObj;
public GameObject TwitterObj;
public GameObject YoutubeObj;
public GameObject GooglePlusObj;
public GameObject LinkedINObj;
public GameObject CustomObj;
bool ShowFacebook; string FacebookLink;
bool ShowTwitter; string TwitterLink;
bool ShowGooglePlus; string GooglePlusLink;
bool ShowYoutube; string YoutubeLink;
bool ShowLinkedIn; string LinkedInLink;
bool ShowCustom; string CustomLink;
string CustomIconLink;
public void SetSocialLinks(bool showFacebook, string facebookLink, bool showTwitter, string twitterLink, bool showGooglePlus, string googlePlusLink, bool showYoutube, string youtubeLink, bool showLinkedIn, string linkedInLink, bool showCustom, string customLink, string custonIconLink)
{
ShowFacebook = showFacebook;
FacebookLink = facebookLink;
ShowTwitter = showTwitter;
TwitterLink = twitterLink;
ShowGooglePlus = showGooglePlus;
GooglePlusLink = googlePlusLink;
ShowYoutube = showYoutube;
YoutubeLink = youtubeLink;
ShowLinkedIn = showLinkedIn;
LinkedInLink = linkedInLink;
ShowCustom = showCustom;
CustomLink = customLink;
CustomIconLink = custonIconLink;
Debug.Log("FB:- "+facebookLink+" ,TW:- "+twitterLink+" ,GL:- "+googlePlusLink+" \n In:- "+linkedInLink+" ,YT:-"+youtubeLink+" ,cust:- "+customLink);
}
// Use this for initialization void Start ()
{
}
// Update is called once per frame
void Update () {
FacebookObj.SetActiveRecursively(ShowFacebook);
TwitterObj.SetActiveRecursively(ShowTwitter);
GooglePlusObj.SetActiveRecursively(ShowGooglePlus);
LinkedINObj.SetActiveRecursively(ShowLinkedIn);
YoutubeObj.SetActiveRecursively(ShowYoutube);
CustomObj.SetActiveRecursively(ShowCustom);
// Determine the number of taps
// Note: Input.tapCount doesn't work on Androidif (Input.touchCount > 0) {
Touch touch = Input.touches[0];
if (touch.phase == TouchPhase.Began)
{
mTouchStartPos = touch.position;
mTouchMoved = false;
mTimeElapsed = 0.0f;
}
else {
mTimeElapsed += Time.deltaTime;
}
if (touch.phase == TouchPhase.Moved) {
if (Vector2.Distance(mTouchStartPos, touch.position) > 40) {
// Touch moved too far
mTouchMoved = true;
}
} else if (touch.phase == TouchPhase.Ended){
if (!mTouchMoved && mTimeElapsed < 1.0){
if (mTapped) {
// Second tap
mTapped = false;
} else {
// Wait to see if this is a double tap
mTapped = true;
mTimeElapsedSinceTap = 0.0f;
}
}
}
}
if (mTapped){
if (mTimeElapsedSinceTap >= 0.5f) {
// Not a double tap
// getClickedLink(mTouchStartPos);
buttonclicked();
mTapped = false;
}else{
mTimeElapsedSinceTap += Time.deltaTime;
}
}
}
private void buttonclicked() {
RaycastHit hitInfo;
Ray r = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(r, out hitInfo)){
if(hitInfo.collider == FacebookObj.collider)
{
Application.OpenURL(FacebookLink);
}else if(hitInfo.collider == YoutubeObj.collider)
{
Application.OpenURL(YoutubeLink);
}else if(hitInfo.collider == TwitterObj.collider)
{
Application.OpenURL(TwitterLink);
}else if(hitInfo.collider == GooglePlusObj.collider)
{
Application.OpenURL(GooglePlusLink);
}else if(hitInfo.collider == LinkedINObj.collider)
{
Application.OpenURL(LinkedInLink);
}
else if(hitInfo.collider == CustomObj.collider)
{
Application.OpenURL(CustomLink);
}
}
}
GooglePlusObj.SetActiveRecursively(ShowGooglePlus);
LinkedINObj.SetActiveRecursively(ShowLinkedIn);
YoutubeObj.SetActiveRecursively(ShowYoutube);
CustomObj.SetActiveRecursively(ShowCustom);
// Determine the number of taps
// Note: Input.tapCount doesn't work on Androidif (Input.touchCount > 0) {
Touch touch = Input.touches[0];
if (touch.phase == TouchPhase.Began)
{
mTouchStartPos = touch.position;
mTouchMoved = false;
mTimeElapsed = 0.0f;
}
else {
mTimeElapsed += Time.deltaTime;
}
if (touch.phase == TouchPhase.Moved) {
if (Vector2.Distance(mTouchStartPos, touch.position) > 40) {
// Touch moved too far
mTouchMoved = true;
}
} else if (touch.phase == TouchPhase.Ended){
if (!mTouchMoved && mTimeElapsed < 1.0){
if (mTapped) {
// Second tap
mTapped = false;
} else {
// Wait to see if this is a double tap
mTapped = true;
mTimeElapsedSinceTap = 0.0f;
}
}
}
}
if (mTapped){
if (mTimeElapsedSinceTap >= 0.5f) {
// Not a double tap
// getClickedLink(mTouchStartPos);
buttonclicked();
mTapped = false;
}else{
mTimeElapsedSinceTap += Time.deltaTime;
}
}
}
private void buttonclicked() {
RaycastHit hitInfo;
Ray r = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(r, out hitInfo)){
if(hitInfo.collider == FacebookObj.collider)
{
Application.OpenURL(FacebookLink);
}else if(hitInfo.collider == YoutubeObj.collider)
{
Application.OpenURL(YoutubeLink);
}else if(hitInfo.collider == TwitterObj.collider)
{
Application.OpenURL(TwitterLink);
}else if(hitInfo.collider == GooglePlusObj.collider)
{
Application.OpenURL(GooglePlusLink);
}else if(hitInfo.collider == LinkedINObj.collider)
{
Application.OpenURL(LinkedInLink);
}
else if(hitInfo.collider == CustomObj.collider)
{
Application.OpenURL(CustomLink);
}
}
}