Showing posts with label a. Show all posts
Showing posts with label a. Show all posts

Wednesday, March 11, 2015

Building a Rails based app for Google Apps Marketplace

Editors note: This is a guest post by Benjamin Coe. Benjamin shares tips and best practices on using Ruby on Rails for integrating with Google Apps and launching on the Marketplace. — Arun Nagarajan

Yesware offers an app in the Google Apps Marketplace which allows our users to schedule reminders, from directly within the Gmail UI. Yesware’s app recently relaunched in the updated Google Apps Marketplace. In prep, we revamped our existing Google Apps Integration:
  • Replacing OpenID with OAuth 2.0 for Single-Sign-On.
  • Replacing 2-legged OAuth with OAuth 2.0 Service Accounts, for delegated account access.
  • Releasing a Gmail Contextual Gadget that worked within these new authentication paradigms.
We should like to share some of the decisions we made, and challenges we faced, upgrading our production Ruby on Rails application to support the improved Google Apps Marketplace.

OAuth 2.0 for SSO

In the revamped Google Apps Marketplace, OAuth 2.0 replaces OpenID for facilitating Single-Sign-On. The flow is as follows:

  1. OAuth 2.0 credentials are created in the Cloud Console, within the same project that has the Google Apps Marketplace SDK enabled.
  2. When accessing your application, a user is put through the standard OAuth 2.0 authentication flow using these credentials.
  3. If the user has the Google Apps Marketplace App installed they will be logged directly into your application, skipping the authorization step.
To implement the OAuth 2.0 authentication flow, you can use the OmniAuth Google OAuth2 Strategy gem. Assuming youre already using OmniAuth, you simply add a line to initializers/omniauth.rb that looks something like this:
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, ENV["GAM_OAUTH_KEY"], ENV["GAM_OAUTH_SECRET"]
end

Yesware already had a Google OAuth 2.0 authentication strategy, so we opted to subclass the Google OAuth 2.0 OmniAuth Strategy. This allowed us to continue supporting our existing OAuth 2.0 credentials, while adding support for Google Apps Marketplace SSO. Our subclassed strategy looked like this:
# Subclass the GoogleOauth2 Omniauth strategy for
# Google Apps Marketplace V2 SSO.
module OmniAuth
module Strategies
class GoogleAppsMarketplace < OmniAuth::Strategies::GoogleOauth2
option :name, google_apps_marketplace
end
end
end
Our final initializers/omniauth.rb file was this:
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, ENV["OAUTH_KEY"],
ENV["OAUTH_SECRET"],
{:scope => ENV["OAUTH_SCOPE"]}
provider :google_apps_marketplace, ENV["GAM_OAUTH_KEY"],
ENV["GAM_OAUTH_SECRET"],
{ :scope => ENV["GAM_OAUTH_SCOPE"],
:access_type => online }end

Note that :access_type is set to online. This is necessary to prevent the authorization prompt from being presented to a SSO user. Omniauth defaults to an :access_type of offline.
Thats all it takes. With this OmniAuth strategy in place, when a domain administrator installs your application SSO will be available across the domain.

OAuth 2.0 Service Accounts

To support Yeswares reminder functionality, we needed offline access to a users email account. In the past, this functionality was supported through 2-legged OAuth. In the new Google Apps Marketplace paradigm, OAuth 2.0 Service Accounts are the replacement.
  • In the Cloud Console, generate a private key for the OAuth 2.0 Service Account associated with your Google Apps Marketplace project. 
  • Download the .p12 private key generated. 
  • Place this key somewhere that will be accessible by your production servers, e.g., a certificates folder in your codebase. 
We used the Google API Ruby Client gem to generate an access token from our Service Accounts keys.
Using the deprecated 2-Legged OAuth based approach, our authorization logic looked like this:

Gmail.connect!(:xoauth, ben@example.com, {
token: authentication.token,
secret: authentication.secret,
consumer_key: google.key,
consumer_secret: google.secret,
read_only: true
})
Using the new Service Account Based Approach, it was as follows:
key = Google::APIClient::PKCS12.load_key(
google_apps.service.p12path, # this is a constant value Google uses
# to password protect the key.
notasecret
)service_account = Google::APIClient::JWTAsserter.new(
google_apps.service.email,
https://mail.google.com/,
key
)client = Google::APIClient.new(
:application_name => APPLICATION_NAME,
:version => APPLICATION_VERSION
).tap do |client|
client.authorization = service_account.authorize(ben@example.com)end
Google.connect!(:xoauth2, ben@example.com, {
:oauth2_token => client.authorization.access_token,
})
With OAuth 2.0 Service Accounts, the underlying libraries we used to interact with Gmail remained the same. There were simply a few extra steps necessary to obtain an access token.

Contextual Gadgets and SSO

Yesware provides a Gmail Contextual Gadget, for scheduling email reminders. To facilitate this, its necessary that the gadget interact with a users email account. To make this a reality, we needed to implement SSO through our contextual gadget. Google provides great reading material on this topic. However, the approach outlined concentrates on the deprecated OpenID-based SSO approach. We used a slightly modified approach.
Rather than OpenID, we used OAuth 2.0 for associating the opensocial_viewer_id with a user. To do this, we needed to modify our OmniAuth strategy to store the opensocial_viewer_id during authentication:
# Subclass the GoogleOauth2 Omniauth strategy for
# Google Apps Marketplace V2 SSO.
module OmniAuth
module Strategies
class GoogleAppsMarketplace < OmniAuth::Strategies::GoogleOauth2

option :name, google_apps_marketplace

def request_phase

# Store the opensocial_viewer_id in the session.
# this allows us to bind the Google Apps contextual
# gadget to a user account.
if request.params[opensocial_viewer_id]
session[:opensocial_viewer_id] = request.params[opensocial_viewer_id]
end

super
end

end
end
end
Once an opensocial_viewer_id was connected to a Yesware user, we could securely make API calls from our contextual gadget. To cut down on the ritual surrounding this, we wrote a Devise Google Apps OpenSocial Strategy for authenticating the OpenSocal signed requests.

Now Go Forth

Once we figured out all the moving parts, we were able to use mostly off the shelf mature libraries for building our Google Apps Marketplace Integration. I hope that this retrospective look at our development process helps other Rails developers hit the ground running even faster than we did.
Benjamin Coe profile

Benjamin Coe cofounded the email productivity company Attachments.me, which was acquired by Yesware, Inc., in  2013. Before starting his own company, Ben was an engineer at FreshBooks, the  world’s #1 accounting solution.
Ben’s in his element when writing scalable cloud-based infrastructure, and loves reflecting on the thought-process that goes into this. A rock-climber, amateur musician, and bagel aficionado, Ben can be found roaming the streets of San Francisco.
ben@yesware.com — https://github.com/bcoe— @benjamincoe

Monday, March 9, 2015

How we built a Social Network for Productivity on Top of Google Docs Calendar Contacts and Reader

Editor’s note: This is a guest post by Martin Böhringer, Co-Founder and CEO of Hojoki.
-- Steve Bazyl

Honestly, we love Google’s productivity tools. Back in 2010, when I was a computer science researcher at university, I was a heavy user of Google Docs, Google Calendar, Google Contacts and Google Reader. So it was the most natural thing to put these tools to the front for integrations into our startup, Hojoki.

Hojoki integrate productivity cloud apps into one newsfeed and enables sharing and discussions on top of the feed. We’ve integrated 17 apps now and counting, so it’s safe to say that we’re API addicts. Now its Time to share with you what we learned about the Google Apps APIs!

The goal: a newsfeed

Our initial reason for building Hojoki was because of the fragmentation we experience in all of our cloud apps. And all those emails. Still, there was this feeling of “I don’t know what’s going on” in our distributed teamwork. So we decided to build something like a Google+ where streams get automatically filled by activities in the apps you use.

This leads to a comprehensive stream of everything that’s going on in your team combined with comments and microblogging. You can organize your stream into workspaces, which are basically places for discussions and collaboration with your team.

Information needs

To build this, we first need some kind of information on recent events. As we wanted to be able to aggregate similar activities and to provide a search, as well as splitting up the stream in workspaces, we also had to be able to sort events as unique objects like files, calendar entries and contacts.

Further, it’s crucial to not only know what has changed, but who did it. So providing unique identities is important for building federated feeds.

Google APIs

Google’s APIs share some basic architecture and structure, described in their Google Data Protocol. Based on that, application-specific APIs provide access to the application’s data. What we use is the following:

  • Google Docs: Google Documents List API version 3.0
  • Google Calendar: Google Calendar API v2
    Note: there is a new API v3 for Google Calendar
  • Google Contacts: Google Contacts API v2

The basic call for Google Contacts for example looks like this:

https://www.google.com/m8/feeds/contacts/default/full

This responds with a complete list of your contacts. Once we have this list all we have to do is to ask for the delta to our existing knowledge. For such use cases, Google’s APIs support query parameters as well as sorting parameters. So we can set “orderby” to “lastmodified” as well as “updated-min” to the timestamp of our last call. This way we are able to keep the traffic low and get quick results by only asking for things we might have missed.

If you want to develop using those APIs you should definitely have a look at the SDKs for them. We used the Google Docs SDK for an early prototype and loved it. Today, Hojoki uses its own generic connection handler for all our integrated systems so we don’t leverage the SDKs anymore.

Real world problems

If you’re into API development, you’ve probably already realized that our information needs don’t fit into many of the APIs out there. Most of the APIs are object centric. They can tell you what objects are included in a certain folder, but they can’t tell you which object in this folder has been changed recently. They just aren’t built with newsfeeds in mind.

Google Apps APIs support most of our information needs. Complete support of OAuth and very responsive APIs definitely make our lives easier.

However, the APIs are not built with Hojoki-like newsfeeds in mind. For example, ETags may change even if nothing happened to an object because of asynchronous processing on Google’s side (see Google’s comment on this). For us this means that, once we detect an altered ETag, in some cases we still have to check based on our existing data if there really have been relevant activities. Furthermore, we often have trouble with missing actors in our activities. For example, up to now we know when somebody changed a calendar event, but there is no way to find out who this was.

Another issue is the classification of updates. Google’s APIs tell us that something changed with an object. But to build a nice newsfeed you also want to know what exactly has been changed. So you’re looking for a verb like created, updated, shared, commented, moved or deleted. While Hojoki calls itself an aggregator for activities, technically we’re primarily an activity detector.

Final solution

You can think of Hojoki as a multi-layer platform. First of all, we try to get a complete overview on your meta-data of the connected app. In Google Docs, this means files and collections, and we retrieve URI and name as well as some additional information (not the content itself). This information fills a graph-based data storage (we use RDF, read more about it here).

At the moment, we subscribe to events in the integrated apps. If detected, they create a changeset for the existing data graph. This changeset is an activity for our newsfeed and related to the object representation. This allows us to provide a very flexible aggregation and filtering on the client side. See the following screenshot. You can filter the stream for a certain collection (“Analytics”) or only for the file history or for the Hojoki workspace where this file is added (“Hojoki Marketing”).

What’s really important in terms of such heavy API processing is to use asynchronous calls. We use the great Open Source project async-http-client for this task.

A wishlist

When I wrote that “we subscribe to events” this is a very nice euphemism for “we’re polling every 30s to see if something changed”. This is not really optimal and we’d love to change it. If Google Apps APIs would support a feed of user events modelled in a common standard like ActivityStrea.ms, combined with reliable ETags and maybe even a push API (e.g. Webhooks) this would also make life easier for lots of developers syncing their local files with Google and help to reduce traffic on both sides.


Martin Böhringer

Martin is Co-Founder and CEO of Hojoki. Hojoki integrates Google Docs, Calendar, Contacts and Reader next to other apps like Dropbox and Evernote into one newsfeed, showing changes by co-workers in one central place. Martin holds a PhD in information systems and likes to perform on stage at Tech Events.

Wednesday, March 4, 2015

How to Place a Pattern Over Text in PowerPoint!

I have to say, when I realized how easy it was to put a pattern over text right in PowerPoint I was floored!  I had been doing it in Photoshop forever and its much more time consuming! 


More than half of the votes were for how to give text a pattern/texture! 


If youre looking for some textures to put over your text, scroll to the end of the document to grab three free textures!




 You can download this tutorial as a PDF by clicking this picture!
Note: This tutorial is hosted on Google Docs.  To save it from there, just open the file and click File > Download to save onto your computer!


Now, for your three free textures!





To save the files, just click the image to get to the higher quality picture, then right click (or Mac: Ctrl + Click) to save the image onto your computer! 



As for next weeks tutorial, Ill be adding a Smart Notebook option... how to "Erase to Reveal" an answer.

Saturday, February 28, 2015

DNA of a 21st Century Educator at Institut Pendidikan Guru Kampus Bahasa Melayu!


I am really looking forward to my DNA of a 21st Century Educator  talk on the 4th October (2012) at Institut Pendidikan Guru Kampus Bahasa Melayu (Kuala Lumpur). Mimma Sayuti Mat Khalid, thanks for inviting me to give this talk! Insya-Allah, I will be able to engage the teachers attending, and inspire those who are not already inspired to explore a new brave and open world of learning and teaching.

Actually, it is never too late to embrace it, and when we do...WOW!


21ST CENTURY EDUCATOR?

During your lifetime you have probably experienced inspirational educators, or witnessed inspiring lectures. But, what about you? Are you such an educator? If not, why not? In this talk, I explored some of the ingredients top educators in the 21st century have, and how we can learn from them, and reinvent ourselves to reach our true potential as an educator. 


SLIDES


DNA of a 21st Century Educator (v3) from IMU (International Medical University)

If you try, you can! Belum cuba, belum tahu! Trust me :)

Thursday, February 26, 2015

Easy Way to Make a Grab My Blog Button Code

Sarah over at Miss As Kindergarten asked me if I had a blog button code and I actually didnt!  I played around with HTML to make my own, but I was messing up somewhere along the line.  Then, I found this awesome website:


It does all of the HTML work for you... and you can even pick custom colors for your code box and text!  All you have to do is copy and paste the completed code to your blog!  Check mine out in the sidebar to see how it looks!

Thanks to Sarah for inspiring me to do this! Everyone, please stop by her blog to show her some love... she also has Technology Tutorials (with videos!) so I know youll love her!



Wednesday, February 25, 2015

More Spring Smartboard Games a Quick Giveaway!

In my classroom, I teach the core part of phonics in the morning, then review our new topic (and previous topics) at the end of the day after snack.  Its nice to have Smartboard games that the students can manage independently... and of course, it helps if theyre cute!

Ive been hard at work making phonics and phonemic awareness games for my students and I have SIX new games to share with you!


Spring Beginning Blends: "bl" and "br" Game for Smartboard or Promethean Board!

Spring Closed Syllables Game for Smartboard or Promethean Board!

Spring Ending Blends: Spelling CVCC Words for Smartboard or Promethean Board

Editing Spring Themed Sentences for Smartboard or Promethean Board

Spring Themed Ending Blends Game for Smartboard or Promethean Board

Spring Themed Middle Vowel Sounds Game for Smartboard or Promethean Board


I also added these games to my Spring Smartboard/Promethean bundle if you want to save 40% on all 12 Spring themed games I currently have up for sale.

Bundle of Spring Themed Smartboard and Promethean Board Games - 14 Games - Save 40%


Now of course, for a quick giveaway.  Im making my grandmas famous spinach ravioli again this Easter.  Yesterday, I made the stuffing and dough, and today Ill start making a million tiny ravioli (okay, not a million, but last year we made 723 ravioli... yikes!)

Anyway... how long did it take me to make the spinach stuffing?  I rounded the time to the nearest 15 minutes.  Whoever guesses correctly first will win all FOURTEEN games!

Wednesday, February 18, 2015

C program to enter a number and print it into words


C++ program to enter a number and print it into words

#include<iostream.h>
#include<conio.h>

void once(int a)
{
switch(a)
{
case 1: cout<<"One";
break;
case 2: cout<<"Two";
break;
case 3: cout<<"Three";
break;
case 4: cout<<"Four";
break;
case 5: cout<<"Five";
break;
case 6: cout<<"Six";
break;
case 7: cout<<"Seven";
break;
case 8: cout<<"Eight";
break;
case 9: cout<<"Nine";
break;
}
}

int tens(int a,int b)
{
int flag=0;
switch(a)
{
case 1:
flag=1;
switch(b)
{
case 0: cout<<"Ten";
break;
case 1: cout<<"Eleven";
break;
case 2: cout<<"Twelve";
break;
case 3: cout<<"Thirteen";
break;
case 4: cout<<"Fourteen";
break;
case 5: cout<<"Fifteen";
break;
case 6: cout<<"Sixteen";
break;
case 7: cout<<"Seventeen";
break;
case 8: cout<<"Eighteen";
break;
case 9: cout<<"Nineteen";
break;
}
break;
case 2: cout<<"Twenty";
break;
case 3: cout<<"Thirty";
break;
case 4: cout<<"Fourty";
break;
case 5: cout<<"Fifty";
break;
case 6: cout<<"Sixty";
break;
case 7: cout<<"Seventy";
break;
case 8: cout<<"Eighty";
break;
case 9: cout<<"Ninety";
break;
}
return(flag);
}

void hundred(int a)
{
switch(a)
{
case 1: cout<<"One Hundred";
break;
case 2: cout<<"Two Hundred";
break;
case 3: cout<<"Three Hundred";
break;
case 4: cout<<"Four Hundred";
break;
case 5: cout<<"Five Hundred";
break;
case 6: cout<<"Six Hundred";
break;
case 7: cout<<"Seven Hundred";
break;
case 8: cout<<"Eight Hundred";
break;
case 9: cout<<"Nine Hundred";
break;
}
}

void main()
{
clrscr();
int n,a[3],i=0,flag=0;
cout<<"Enter any number(max 3 digits):";
cin>>n;

while(n!=0)
{
a[i++]=n%10;
n=n/10;
}

for(i=i-1;i>=0;--i)
{
if(i==0&&flag==0)
once(a[0]);
if(i==1)
flag=tens(a[1],a[0]);
if(i==2)
hundred(a[2]);
cout<<" ";
}
getch();
}

Tuesday, February 17, 2015

C Program for Finding Transpose of a Sparse Matrix


Transpose of a matrix is obtained by interchanging rows and columns. In another way, we can say that element in the i, j position gets put in the j, i position. Transpose  of the matrix B1 is obtained as B2 by inserting (i,j)th element of B1 as (j,i)th element in B2.

Also Read: C program to read a matrix of size mxn and print its transpose

#include <stdio.h>

#define MAX 20

void printsparse(int[][3]);
void readsparse(int[][3]);
void transpose(int[][3],int[][3]);

void main()
{
    int b1[MAX][3],b2[MAX][3],m,n;
    printf("Enter the size of matrix (rows,columns):");
    scanf("%d%d",&m,&n);
    b1[0][0]=m;
    b1[0][1]=n;

    readsparse(b1);
    transpose(b1,b2);
    printsparse(b2);
}

void readsparse(int b[MAX][3])
{
    int i,t;
    printf("
Enter no. of non-zero elements:");
    scanf("%d",&t);
    b[0][2]=t;

    for(i=1;i<=t;i++)
    {
        printf("
Enter the next triple(row,column,value):");
        scanf("%d%d%d",&b[i][0],&b[i][1],&b[i][2]);
    }
}

void printsparse(int b[MAX][3])
{
    int i,n;
    n=b[0][2];  //no of 3-triples
    printf("
After Transpose:
");

    printf("
row column value
");

    for(i=0;i<=n;i++)
        printf("%d %d %d
",b[i][0],b[i][1],b[i][2]);
}

void transpose(int b1[][3],int b2[][3])
{

    int i,j,k,n;
    b2[0][0]=b1[0][1];
    b2[0][1]=b1[0][0];
    b2[0][2]=b1[0][2];

    k=1;
    n=b1[0][2];

    for(i=0;i<b1[0][1];i++)
        for(j=1;j<=n;j++)
        //if a column number of current triple==i then insert the current triple in b2
            if(i==b1[j][1])
    {

            b2[k][0]=i;
            b2[k][1]=b1[j][0];
            b2[k][2]=b1[j][2];
            k++;
    }
}

C Program for Finding Transpose of a Sparse Matrix

Sunday, February 15, 2015

How to Create a Web Browser in Visual Basic

In visual basic the simplest application ever could be created is a web browser. Visual basic already contain a web browser control within the toolbox, after adding it we could easily play around with the many web browser functions like navigate (to navigate to a particular website), refresh, etc. In this tutorial we will see how we can create a simple web browser in visual basic.

Also Read: How to Create a Keylogger in VB.Net?


How to Create a Web Browser in Visual Basic

How to Create a Web Browser in Visual Basic

1. First of all create a new windows form application in visual basic.

2. Now add 4 buttons and change their text as given below.

Button1 - << (To move backword)
Button2 - >> (To move forward)
Button3 - Refresh
Button4 - Go

3. Add a textbox and align them in the manner shown below.


How to Create a Web Browser in Visual Basic

4. Now double click the form to switch to code view and paste the code given below.

Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
WebBrowser1.GoBack()

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
WebBrowser1.GoForward()

End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
WebBrowser1.Refresh()
End Sub

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
WebBrowser1.Navigate(TextBox1.Text)
End Sub

Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown
If e.KeyData = Keys.Enter Then
Button4.PerformClick()
End If
End Sub

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged

End Sub
End Class

5. You have done!! Hit Debug and browse some of your favorite sites with your own fully functional web browser.

If you liked this tutorial then please take your few seconds to share it!

Thursday, February 12, 2015

Apple may be planning to announce a new mobile ad network


By Ian Paul

Apple is reportedly gearing up to introduce a new mobile advertising program on Thursday as part of the companys iPhone OS 4.0 event. Ever since January, when Apple purchased Quattro Wireless, a mobile advertising platform, there has been speculation about how Apple would integrate its services. On Thursday, we may get our answer, according to Media Memos Peter Kafka.

But its unclear whether Apples ad platform would be similar to Googles AdSense program and use simple text and visual ads, or be an entirely new strategy. So if the rumors are true, and Apples iAds (or whatever the ad network will be called) are on their way, what will the new ad platform look like? And what does this mean for users?

Here are five questions that are at the top of my mind.

What does this mean for privacy?

If you have an iPhone, then Apple has a lot of information about your buying habits. Even if youve never paid money for anything from the iTunes Store, and exclusively download free iPhone applications, Apple still knows what your preferences are. With me, for example, they know I like to play games like Air Hockey and Chess, I follow Major League Baseball, and have a hardcore addiction to political news.

Thats all juicy information for targeted advertising, and with Apple running its own advertising network, thats information they can use to maximise profits. Thats not necessarily a bad thing, but any time my buying habits are being used to for targeted advertising I want to know exactly how my information is being handled. Hopefully, Apple will come out with a clear privacy policy if the rumored ad network becomes reality.

Will the ad network be Apple only?

Will Apples mobile advertising network reach across device platforms, or will this network be for Apple devices only? Kafka is guessing the new platform will reach across other mobile platforms, but I have to wonder about that. It would certainly make sense to want an advertising network to reach as many people as possible, but Apple thrives on the exclusivity of its products. So why not extend that philosophy to its ad network? If Apple ads have a level of interactivity or some other unique feature, you can bet Cupertino will try to leverage its network as an exclusive means to reach iPhone, iPod Touch, and iPad users.

Will other ads be allowed?

The other question is whether or not Apple will allow competing advertising networks to continue on existing iPhone applications, or if developers will have to switch over to Apples network. Google already has a beta program called Google AdSense for Mobile Applications that is used by iPhone app development companies like Flipside 5. Smaller ad networks like The Deck also have popped up to fill the iPhone app advertising void.

Its unlikely that Apple would get away with limiting advertising platforms on the iPhone, since that would, as Kafka points out, be "a red flag for regulators." But we wont know for sure until Apple makes its rumoured announcement.

What about those patents?

Patently Apple has uncovered two interesting patents that may shed some light on how advertising will work on Apple devices. In October, the blog uncovered a patent that would force users to watch advertising by having them interact with the ads as a test to make sure they were paying attention to the commercial. The tests could include functions like pressing a button on the screen. Thats similar to what some iPhone ads already do by requiring you to press a "continue" button. If you dont respond appropriately to the ad, your device would be shut down or impaired until you complied with the ads interactive element. It should be pointed out that this scheme is for subsidised devices only, and would not include devices for which you paid full price.

A similar patent again uncovered by Patently Apple in early March shows a scheme that would require you to watch a commercial or several commercials as part of a television episode, film, or other video. As you watch the commercials, the next segment of the video would be unlocked. This plan would make it impossible to skip ads, since you couldnt watch the next video segment until youve seen the commercials.
Do these patents reflect what Apples rumored ad network will look like? Force feeding commercials while I watch a video isnt so uncommon, and is somewhat similar to Hulu, which also stops you from skipping ads when you watch a TV show online. But Im not too thrilled about the idea of being forced to interact with regularly scheduled ads on an iPad or iPhone. Id rather pay full price.

Will "iAds" change the mobile device business?

If, and this is a big if, Apples advertising platform is similar to the first patent uncovered by Patently Apple, this could mark a significant change in the mobile device business. The idea that you could get a dirt cheap iPhone, iPad, Mac Mini, or even MacBook in return for interacting with a few ads might be very attractive to some people. It would certainly be annoying to have to listen to an ad every time you wanted to make a phone call, but maybe thats an annoyance some people could live with.

Before Google launched the Nexus One, there were also rumors about the search giant releasing an ad-supported device. That didnt happen, and Im not sure that Apple would be willing to go this route. But if Apple did try selling ad-supported devices as part of its mobile strategy that would certainly put its handsets in the hands of more people. And if it works for Apple, it wouldnt take long for competitors to follow Cupertinos lead.

What do you think? Would you sign up for a free or almost free Apple device if it meant interacting with ads?

Thursday, February 5, 2015

Creating a Flex AIR Screenshot app Part 9

In this tutorial, we will make the screen settings save and load, as well as add an "Export" button and add some protection against errors.

Firstly we need to set the ids of all the screen setting items. Set the first checboxs id to set1checkbox, and all the rest ScreenSetting items ids to set2, set3, set4, set5, set6 and set7. Also add a button with label "Export" and set its click event listener to startExportScreenshot().

<s:NavigatorContent id="screenshotsettings">
<s:VGroup width="100%" horizontalAlign="center" paddingTop="20">
<s:Label styleName="descriptionText">Select screenshot screen sizes:</s:Label>
<s:SkinnableContainer backgroundColor="#999999" width="310" height="18" >
<s:CheckBox toolTip="Use this screen size" x="4" id="set1checkbox" />
<s:Label id="contSize" styleName="settingText" x="22" y="3" />
</s:SkinnableContainer>
<custom:ScreenSetting id="set2" />
<custom:ScreenSetting id="set3" />
<custom:ScreenSetting id="set4" />
<custom:ScreenSetting id="set5" />
<custom:ScreenSetting id="set6" />
<custom:ScreenSetting id="set7" />
<s:HGroup>
<s:Button label="Back" click="screenshotBack();" />
<s:Button label="Export" click="startExportScreenshot();" />
</s:HGroup>
</s:VGroup>
</s:NavigatorContent>

Now, go and declare these 3 variables:

private var preferences:SharedObject = SharedObject.getLocal("kirshotPreferences");
[Bindable]
private var pref_screensizes:Array;
private var screenSettings:Array;

The first one is a shared object which will be used for storing preferences data. The second variable is an array that holds screensizes taken from the shared object. The last variable will be used to reference set2-set7 items.

In the init() function, add code that checks if the application is launched for the first time, and if it is - set default values. Then apply the shared data to pref_screensizes:

private function init():void {
//preferences.data.firsttime = null;

// Set preferences if loaded for the first time
if (preferences.data.firsttime == null) {
preferences.data.firsttime = true;
preferences.data.screensizes = [
{ checked:true },
{ checked:true, w:1280, h:1024 },
{ checked:true, w:1280, h:800 },
{ checked:true, w:1024, h:768 },
{ checked:false, w:"", h:"" },
{ checked:false, w:"", h:"" },
{ checked:false, w:"", h:"" }];
preferences.flush();
}

// Set preferences loaded from local storage
pref_screensizes = preferences.data.screensizes;

addEventListener(FlexNativeWindowBoundsEvent.WINDOW_RESIZE, onResize);
}

Now, we will create functions that will load and save screen size preferences - loadScreenshotSettings() and saveScreenshotSettings(). Firstly, though, lets update the functions that will call these.

Call saveScreenshotSettings() from screenshotBack():

private function screenshotBack():void {
saveScreenshotSettings()
stack.selectedChild = loadpage;
removeElement(tempHTML);
}

Now update changeState() function, in the last conditional set screenSettings value to the array of references to our set objects, and then call loadScreenshotSettings():

private function changeState():void {
if (stack.selectedChild == loadpage) {
contentBox.setStyle("horizontalAlign", "center");
urlInput.text = urlString;
}
if (stack.selectedChild == crop) {
maximize();
canSelect = true;
contentBox.setStyle("horizontalAlign", "left");
cropHTML.htmlLoader.load(new URLRequest(urlString));
cropHTML.width = contentBox.width;
cropHTML.height = contentBox.height - 24;
cropStatus.text = "Loading";
cropStatus.setStyle("color", "#ffff00");
cropHTML.addEventListener(Event.COMPLETE, onCropLoad);
}
if (stack.selectedChild == screenshotsettings) {
screenSettings = [set2, set3, set4, set5, set6, set7];
contSize.text = "Full size (" + tempHTML.contentWidth + "x" + tempHTML.contentHeight + ")";
loadScreenshotSettings();
}
}

It was needed to store the references to the set objects to use them in a loop where we save and retreive variable values in loadScreenshotSettings() and saveScreenshotSettings():

private function loadScreenshotSettings():void {
set1checkbox.selected = pref_screensizes[0].checked;

for (var i:int = 0; i < screenSettings.length; i++) {
screenSettings[i].checked = pref_screensizes[i + 1].checked;
screenSettings[i].w = pref_screensizes[i + 1].w;
screenSettings[i].h = pref_screensizes[i + 1].h;
}
}

private function saveScreenshotSettings():void {
pref_screensizes[0].checked = set1checkbox.selected;

for (var i:int = 0; i < screenSettings.length; i++) {
pref_screensizes[i + 1].checked = screenSettings[i].checked;
pref_screensizes[i + 1].w = screenSettings[i].w;
pref_screensizes[i + 1].h = screenSettings[i].h;
}

preferences.flush();
}

It is also needed in the startExportScreenshot() function, which checks whether all the entered info is valid before proceeding to export.

We check if all the checked items have their size values not blank or not 0:

private function startExportScreenshot():void {
var canExport:Boolean = true;

for (var i:int = 0; i < screenSettings.length; i++) {
if (screenSettings[i].checked && ((screenSettings[i].w == "" || screenSettings[i].w == 0) || (screenSettings[i].h == "" || screenSettings[i].h == 0))) {
canExport = false;
}
}

if (canExport) {
Alert.show("Successful export");
}else {
Alert.show("One or more selected screen sizes are not entered or are invalid!", "Oops...");
}
}

And thats it for today. Full code:

<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:custom="*"
xmlns:mx="library://ns.adobe.com/flex/mx" showStatusBar="false"
width="550" height="500" creationComplete="init();">


<fx:Declarations>
<mx:ArrayCollection id="headerTitles">
<fx:Object step="Step one:" description="load a web page." />
<fx:Object step="Loading..." description="please wait." />
<fx:Object step="Step two:" description="set your export preferences." />
<fx:Object step="Step two:" description="select the area you wish to crop." />
<fx:Object step="Step three:" description="set your export preferences for the cropped image." />
<fx:Object step="Final step:" description="please wait while your images are being expored." />
</mx:ArrayCollection>
</fx:Declarations>

<fx:Style>
@namespace s "library://ns.adobe.com/flex/spark";
@namespace mx "library://ns.adobe.com/flex/mx";

.descriptionText{
fontSize: 24;
color: #fff;
}

.settingText{
fontSize: 16;
color: #fff;
}

#headStep{
fontSize: 30;
fontWeight: bold;
color: #ffffbb;
}

#headDesc{
fontSize: 30;
color: #ffffff;
}
</fx:Style>

<fx:Script>
<![CDATA[
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.filesystem.File;
import flash.geom.Rectangle;
import flash.net.URLRequest;
import mx.controls.HTML;
import mx.core.FlexHTMLLoader;
import mx.events.FlexNativeWindowBoundsEvent;
import mx.controls.Alert;
import mx.graphics.ImageSnapshot;
import spark.primitives.BitmapImage;

[Bindable]
private var urlString:String;
[Bindable]
private var canSelect:Boolean = true;
private var tempHTML:HTML = new HTML();

private var preferences:SharedObject = SharedObject.getLocal("kirshotPreferences");
[Bindable]
private var pref_screensizes:Array;
private var screenSettings:Array;

private function init():void {
//preferences.data.firsttime = null;

// Set preferences if loaded for the first time
if (preferences.data.firsttime == null) {
preferences.data.firsttime = true;
preferences.data.screensizes = [
{ checked:true },
{ checked:true, w:1280, h:1024 },
{ checked:true, w:1280, h:800 },
{ checked:true, w:1024, h:768 },
{ checked:false, w:"", h:"" },
{ checked:false, w:"", h:"" },
{ checked:false, w:"", h:"" }];
preferences.flush();
}

// Set preferences loaded from local storage
pref_screensizes = preferences.data.screensizes;

addEventListener(FlexNativeWindowBoundsEvent.WINDOW_RESIZE, onResize);
}

private function doBrowse():void{
var file:File = new File();
file.addEventListener(Event.SELECT, browseSelect);
file.browseForOpen("Load a webpage");

function browseSelect(evt:Event):void {
urlInput.text = file.nativePath;
}
}

private function goCrop():void {
stack.selectedChild = crop;
urlString = urlInput.text;
}

private function goScreenshot():void {
stack.selectedChild = screenshotloading;
urlString = urlInput.text;

addElement(tempHTML);
tempHTML.visible = false;
tempHTML.addEventListener(Event.COMPLETE, onTempLoad);
tempHTML.htmlLoader.load(new URLRequest(urlString));
}

private function onTempLoad(evt:Event):void {
stack.selectedChild = screenshotsettings;
}

private function cancelLoading():void {
tempHTML.removeEventListener(Event.COMPLETE, onTempLoad);
tempHTML.cancelLoad();
screenshotBack();
}

private function screenshotBack():void {
saveScreenshotSettings()
stack.selectedChild = loadpage;
removeElement(tempHTML);
}

private function changeState():void {
if (stack.selectedChild == loadpage) {
contentBox.setStyle("horizontalAlign", "center");
urlInput.text = urlString;
}
if (stack.selectedChild == crop) {
maximize();
canSelect = true;
contentBox.setStyle("horizontalAlign", "left");
cropHTML.htmlLoader.load(new URLRequest(urlString));
cropHTML.width = contentBox.width;
cropHTML.height = contentBox.height - 24;
cropStatus.text = "Loading";
cropStatus.setStyle("color", "#ffff00");
cropHTML.addEventListener(Event.COMPLETE, onCropLoad);
}
if (stack.selectedChild == screenshotsettings) {
screenSettings = [set2, set3, set4, set5, set6, set7];
contSize.text = "Full size (" + tempHTML.contentWidth + "x" + tempHTML.contentHeight + ")";
loadScreenshotSettings();
}
}

private function loadScreenshotSettings():void {
set1checkbox.selected = pref_screensizes[0].checked;

for (var i:int = 0; i < screenSettings.length; i++) {
screenSettings[i].checked = pref_screensizes[i + 1].checked;
screenSettings[i].w = pref_screensizes[i + 1].w;
screenSettings[i].h = pref_screensizes[i + 1].h;
}
}

private function saveScreenshotSettings():void {
pref_screensizes[0].checked = set1checkbox.selected;

for (var i:int = 0; i < screenSettings.length; i++) {
pref_screensizes[i + 1].checked = screenSettings[i].checked;
pref_screensizes[i + 1].w = screenSettings[i].w;
pref_screensizes[i + 1].h = screenSettings[i].h;
}

preferences.flush();
}

private function startExportScreenshot():void {
var canExport:Boolean = true;

for (var i:int = 0; i < screenSettings.length; i++) {
if (screenSettings[i].checked && ((screenSettings[i].w == "" || screenSettings[i].w == 0) || (screenSettings[i].h == "" || screenSettings[i].h == 0))) {
canExport = false;
}
}

if (canExport) {
Alert.show("Successful export");
}else {
Alert.show("One or more selected screen sizes are not entered or are invalid!", "Oops...");
}
}

private function onCropLoad(evt:Event):void {
cropStatus.text = "Loaded";
cropStatus.setStyle("color", "#ffffff");
}

private function onResize(evt:Event):void {
if (stack.selectedChild == crop) {
cropHTML.width = contentBox.width;
cropHTML.height = contentBox.height - 24;
}
}
]]>
</fx:Script>

<s:VGroup width="100%" height="100%" gap="0">
<mx:HBox backgroundColor="#333333" height="46" width="100%" paddingTop="10" paddingLeft="10">
<s:Label id="headStep" text="{headerTitles.getItemAt(stack.selectedIndex).step}" />
<s:Label id="headDesc" text="{headerTitles.getItemAt(stack.selectedIndex).description}" />
</mx:HBox>
<mx:Box backgroundColor="#666666" width="100%" height="100%" id="contentBox" horizontalAlign="center">
<mx:ViewStack id="stack" change="changeState();">
<s:NavigatorContent id="loadpage">
<s:VGroup width="100%" horizontalAlign="center" paddingTop="20">
<s:Label styleName="descriptionText">Enter the link to the page:</s:Label>
<s:HGroup>
<s:TextInput width="250" id="urlInput" text="http://" /><s:Button label="Browse local..." click="doBrowse();" />
</s:HGroup>
<s:HGroup>
<custom:ImageButton img="@Embed(../lib/b_screenshot.png)" over="@Embed(../lib/b_screenshot_over.png)" toolTip="Take screenshots" click="goScreenshot();" buttonMode="true" enabled="{urlInput.text!=}" />
<custom:ImageButton img="@Embed(../lib/b_cut.png)" over="@Embed(../lib/b_cut_over.png)" toolTip="Crop area" click="goCrop();" buttonMode="true" enabled="{urlInput.text!=}" />
</s:HGroup>
</s:VGroup>
</s:NavigatorContent>

<s:NavigatorContent id="screenshotloading">
<s:VGroup width="100%" horizontalAlign="center" paddingTop="20">
<s:Label styleName="descriptionText">The page is being loaded...</s:Label>
<s:Button label="Cancel" click="cancelLoading();" />
</s:VGroup>
</s:NavigatorContent>

<s:NavigatorContent id="screenshotsettings">
<s:VGroup width="100%" horizontalAlign="center" paddingTop="20">
<s:Label styleName="descriptionText">Select screenshot screen sizes:</s:Label>
<s:SkinnableContainer backgroundColor="#999999" width="310" height="18" >
<s:CheckBox toolTip="Use this screen size" x="4" id="set1checkbox" />
<s:Label id="contSize" styleName="settingText" x="22" y="3" />
</s:SkinnableContainer>
<custom:ScreenSetting id="set2" />
<custom:ScreenSetting id="set3" />
<custom:ScreenSetting id="set4" />
<custom:ScreenSetting id="set5" />
<custom:ScreenSetting id="set6" />
<custom:ScreenSetting id="set7" />
<s:HGroup>
<s:Button label="Back" click="screenshotBack();" />
<s:Button label="Export" click="startExportScreenshot();" />
</s:HGroup>
</s:VGroup>
</s:NavigatorContent>

<s:NavigatorContent id="crop">
<s:VGroup width="100%" height="100%" gap="0">
<mx:HBox backgroundColor="#999999" width="100%" height="24" verticalScrollPolicy="off" verticalAlign="middle" paddingLeft="2">
<s:Button label="Back" click="{cropHTML.htmlLoader.loadString(); stack.selectedChild = loadpage;}" />
<s:Button label="Export selection" enabled="false" />
<s:Label id="cropStatus" />
<s:Label text="{urlString}" />
</mx:HBox>
<mx:HTML id="cropHTML" horizontalScrollPolicy="on" verticalScrollPolicy="on" />
</s:VGroup>
</s:NavigatorContent>

<s:NavigatorContent id="cropsettings">

</s:NavigatorContent>

<s:NavigatorContent id="export">

</s:NavigatorContent>
</mx:ViewStack>
</mx:Box>
</s:VGroup>

</s:WindowedApplication>

Thanks for reading!

Tuesday, February 3, 2015

How to Create a Password Protected Folder

Create a Password Protected Folder without any Extra Software

There are a number of techniques for Folder Lock, which you can use to make a password protected folder, most of Folder Lock techniques demands the use of some third party applications. Using this clean method you can hide your folders with a quick batch script.

It’s necessary to note that this will not actually protect your data from someone who knows what you are doing.

Note: if you are a starter you should be careful with this script.

Create Your Password Protected Folder

Before, proceeding this method you need to create a folder that will main folder for your password protected folder, this is just common folder and can be located anywhere and named anything.

How to Create a Password Protected Folder

Enter into your newly created folder and create a new Text Document file. This can easily be done from the help of  following image.


How to Create a Password Protected Folder 2

Open the document, now paste the following code into the contents of the document:


cls 
@ECHO OFF
title Folder Private
if EXIST "HTG Locker" goto UNLOCK
if NOT EXIST Private goto MDLOCKER
:CONFIRM
echo Are you sure you want to lock the folder(Y/N)
set/p "cho=>"
if %cho%==Y goto LOCK
if %cho%==y goto LOCK
if %cho%==n goto END
if %cho%==N goto END
echo Invalid choice.
goto CONFIRM
:LOCK
ren Private "HTG Locker"
attrib +h +s "HTG Locker"
echo Folder locked
goto End
:UNLOCK
echo Enter password to unlock folder
set/p "pass=>"
if NOT %pass%== PASSWORD_GOES_HERE goto FAIL
attrib -h -s "HTG Locker"
ren "HTG Locker" Private
echo Folder Unlocked successfully
goto End
:FAIL
echo Invalid password
goto end
:MDLOCKER
md Private
echo Private created successfully
goto End
:End

Change the PASSWORD_GOES_HERE text to the password you want to set. Now go ahead and save the file as locker.bat.


How to Create a Password Protected Folder 3

Once the file is saved as a batch file you can delete the original text file.


How to Create a Password Protected Folder 4

Now run your batch file by double clicking on it–the first time you run it, it will create a folder called Private. It is the place where you can store all your important things. When you have complete adding all your data into the Private folder, run locker.bat again.

How to Create a Password Protected Folder 5

This time you will be asked if you sure that you want to lock the folder, press the “Y” key and hit enter to lock your folder.

How to Create a Password Protected Folder 6

You will see that your Private folder quickly disappears.

How to Create a Password Protected Folder 7
If you run the script yet again, you will prompted for a password.


How to Create a Password Protected Folder 8

If you enter the same password as you set in the script the Private folder will reappear if you enter the incorrect password the script will just Terminate.

How to See the Files Again

Most people don’t know how to show system files, but anyone who has some experience will easily be able to quickly figure it out in the Folder Options. To see the files again, all you have to do is un-check the boxes for “Show hidden files, folders, and drives” and un-check the box for “Hide protected operating system files”.


How to Create a Password Protected Folder 9
But any ordinary user who unchecks the box will most probably be scared off by the warning message that appears.



How to Create a Password Protected Folder 10

The 2nd way somebody could encapsulate the folder is to open the batch file and read your password. It’s certainly not a really secure method to hide your files, but it is fun.


Attribution note: We found this script on dozens of different web sites going back many years. We have no idea who first created the script, so we’ve omitted any sort of attribution link. If you do have proof that you first created the script, contact us and we’ll adjust the article accordingly.


If You Forget Your Password

Right-click on the locker.bat file and choose Edit, then you can see the password you set in the file.


How to Create a Password Protected Folder

You can download PDF copy of this article using below link.

 Download PDF Copy